SLOPSHOPPER

sprc-slurm-mods

Claude Code mod for the sprc Slurm cluster: follows the jobs you submit and tells the agent once when they end (results, failures, right-sizing), job tools, a…

guardcommandtoaststatusprompttool
A shopper browsing a rack in a slop shop
README

sprc-slurm-mods — Claude Code only

A Claude Code mod that makes agents faster on the sprc cluster. It follows the jobs an agent submits and tells that agent once, briefly, when they have ended. It is not an Agent Skill and does nothing in codex, opencode or oh-my-pi. Those harnesses (and Claude Code) get the generic slurm skill, which works on its own; this mod is an optional extra on top of it.

You getWhat it is
Auto-followEvery sbatch the agent runs is followed, including loops, job arrays and JID=$(sbatch --parsable …). Jobs submitted by one agent in one turn form a group.
One message per groupWhen every job in a group has ended, the agent gets one short message: state counts, the failures with exit codes and log paths, and right-sizing advice it hasn't already seen. If the conversation is idle, this starts a turn (setting wake). If it is busy, the message rides on its next tool result. Subagents and teammates get their own jobs' results.
Toasts▶ when a followed job starts, ✓/✗ when followed jobs end, combined into one toast per poll.
Status linesprc ▸ 4/8 GPU free · following 21 (3R 18PD) · queue 71
Job tools for the modelsprc_status, sprc_job (log tail, efficiency, array summary), sprc_wait (blocks up to 9 min on several jobs), sprc_follow (for jobs submitted elsewhere)
GuardrailsBlocks only commands that would fail silently or load the login node, and that Slurm doesn't refuse itself: sbatch whose working directory is node-local /tmp (the script's own #SBATCH --chdir counts), and GPU launchers (torchrun, vllm serve, …) on sprlab005. Notes on ssh to a node you have no job on, and on sacct --json, are shown once per session and never block.
Live contextA one-line cluster summary on prompts that mention Slurm, GPUs or the cluster. It is sent again only when the summary changes.

"Free" GPUs are the ones a default GPU job could actually get: an idle GPU plus the 32 CPUs and 375G of memory that come with it by default. Idle GPUs on a node full of CPU jobs show as stranded.

Agents can still poll Slurm their own way, for example with a background while squeue …; do sleep 60; done. The mod never blocks that.

When it is active

Only when the session runs on the sprc cluster (Slurm reports ClusterName = sprc), normally on sprlab005. Anywhere else, including another site's Slurm cluster and Claude Code on the web, it registers nothing and stays silent. If a hook fails, the command it was watching runs as if the mod weren't installed.

Install

Needs a recent Claude Code with mod (function hook) support. Add the marketplace as in the main README, then:

/plugin install sprc-slurm-mods@sprc-plugins
/reload-plugins

Install sprc-slurm too: the mod tracks jobs, and the skill tells Claude how to submit them well.

Settings

/config → sprc-slurm-mods:

SettingDefault
pollSeconds30How often to read sinfo + squeue (minimum 10). With nothing followed, it polls at a quarter of that rate.
wakeonWhen a conversation's followed jobs have all ended and it is idle, start a turn with the results. Off: the results wait for your next prompt; the toast still shows.
guardsenforceenforce blocks; warn lets the command run and tells Claude; off disables the checks. Jobs are followed either way.
liveContextonThe one-line summary on cluster-related prompts.

/sprc prints the cluster summary and what this session follows. /sprc follow <ids> and /sprc unfollow <ids> change that list.

Privacy

The tools show other users' jobs only as counts: no names, users or job names.

Developing it

Load the working copy on sprlab005 with claude --plugin-dir plugins/sprc-slurm-mods (disable the installed plugin first); edits hot-reload. Before committing, run claude plugin validate . and claude plugin test . in this directory.

Source 4 files
hooks/register.tsx 829 lines
1import type { EngineInterface, PluginState, Register } from 'claude-code'
2
3import type { Followed, JobReport, Notice, Snapshot } from '../types'
4import { checkBash, runsSbatch, sbatchScripts, submittedJobs } from './guards'
5import type { Finding } from './guards'
6import {
7  TERMINAL_STATES,
8  endMessage,
9  expandNodes,
10  fetchReport,
11  fetchReports,
12  fetchScontrol,
13  fetchSnapshot,
14  gpuTotals,
15  hasJob,
16  idRanges,
17  isBad,
18  nodeUsable,
19  parentId,
20  reportLine,
21  tailFile,
22} from './slurm'
23import type { FailedLog, Run } from './slurm'
24
25type $ = EngineInterface
26
27const REF_snapshot = { plugin: 'sprc-slurm-mods', key: 'snapshot' } as const
28const REF_followed = { plugin: 'sprc-slurm-mods', key: 'followed' } as const
29const REF_finished = { plugin: 'sprc-slurm-mods', key: 'finished' } as const
30const REF_outbox = { plugin: 'sprc-slurm-mods', key: 'outbox' } as const
31const REF_isEnabled = { plugin: 'sprc-slurm-mods', key: 'isEnabled' } as const
32
33// Slurm's own words and cluster phrases only: "job", "node" or "queue" alone
34// mostly mean CI, Node.js or a web queue.
35const SLURMY =
36  /\b(slurm|sbatch|salloc|srun|squeue|sacct|sinfo|scancel|scontrol|gpus?|h100s?|sprc\w*|sprlab005|my jobs?|the queue|the cluster|compute nodes?|scavenger|expedite)\b/i
37
38const JOB_ID = /^\d+(_\d+)?$/
39
40// Reads within one dispatch see the state as it stood when the dispatch
41// began, so a value written mid-hook reads stale. This module is the only
42// writer of its values, so it keeps them here too: `get` answers from the
43// cache, `put` writes both. A reload empties the cache; the next `get` loads
44// from the host.
45type S = PluginState['sprc-slurm-mods']
46const mem: { [K in keyof S]?: S[K] } = {}
47async function load<K extends keyof S>($: $, k: K): Promise<S[K]> {
48  switch (k) {
49    case 'snapshot':
50      return ((await $.state.get(REF_snapshot)).value ?? null) as S[K]
51    case 'followed':
52      return ((await $.state.get(REF_followed)).value ?? []) as S[K]
53    case 'finished':
54      return ((await $.state.get(REF_finished)).value ?? []) as S[K]
55    case 'outbox':
56      return ((await $.state.get(REF_outbox)).value ?? []) as S[K]
57    case 'isEnabled':
58      return ((await $.state.get(REF_isEnabled)).value ?? false) as S[K]
59  }
60  throw new Error(`unknown state key ${String(k)}`)
61}
62
63async function get<K extends keyof S>($: $, k: K): Promise<S[K]> {
64  if (!(k in mem)) mem[k] = await load($, k)
65  return mem[k] as S[K]
66}
67
68async function put<K extends keyof S>($: $, k: K, fn: (v: S[K]) => S[K]): Promise<void> {
69  const v = fn(await get($, k))
70  mem[k] = v
71  switch (k) {
72    case 'snapshot':
73      await $.state.set(REF_snapshot, v as S['snapshot'])
74      break
75    case 'followed':
76      await $.state.set(REF_followed, v as S['followed'])
77      break
78    case 'finished':
79      await $.state.set(REF_finished, v as S['finished'])
80      break
81    case 'outbox':
82      await $.state.set(REF_outbox, v as S['outbox'])
83      break
84    case 'isEnabled':
85      await $.state.set(REF_isEnabled, v as S['isEnabled'])
86      break
87  }
88}
89
90// Module-local; a reload starts these over.
91const cfg = { pollMs: 30_000, guards: 'enforce', liveContext: true, wake: true }
92let user = ''
93let isLoginNode = false
94let isPolling = false
95let lastPollAt = 0
96// What the prompt hook last attached, so an unchanged cluster is not re-sent.
97let lastContext = { text: '', at: 0 }
98// The main conversation's running turn, if any. Jobs one loop follows during
99// one turn form a group and are reported together.
100let mainTurn: { id: string } | null = null
101let idleTurn = 0
102// Said once per session (per loop): repeating them costs tokens and says nothing new.
103const toldFollowing = new Set<string>()
104const toldRules = new Set<string>()
105const seenAdvice = new Set<string>()
106// Jobs an sprc_wait call is blocked on: that call reports their end, so the
107// background poll must not report it a second time.
108const awaited = new Set<string>()
109
110function runner($: $): Run {
111  return (argv, init) => $.process.run(argv, { timeoutMs: init?.timeoutMs ?? 20_000 })
112}
113
114function groupKey(owner: string | undefined): string {
115  return `${owner ?? 'main'}|${mainTurn?.id ?? `idle${idleTurn}`}`
116}
117
118function loopKey(owner: string | undefined): string {
119  return owner ?? 'main'
120}
121
122// ---- following -----------------------------------------------------------
123
124async function follow($: $, ids: readonly string[], owner: string | undefined, origin: Followed['origin']): Promise<string[]> {
125  const since = await $.clock.now()
126  const have = new Set((await get($, 'followed')).map(f => f.id))
127  const fresh = [...new Set(ids.map(parentId))].filter(id => !have.has(id))
128  if (!fresh.length) return []
129  const group = groupKey(owner)
130  await put($, 'followed', list => [...list, ...fresh.map(id => ({ id, owner, group, origin, since }))])
131  return fresh
132}
133
134/** Tells the right loop: the main conversation through its tool results or a woken turn, an agent by message. */
135async function queueNotice($: $, owner: string | undefined, text: string): Promise<void> {
136  const at = await $.clock.now()
137  await put($, 'outbox', list => [...list, { owner, text, at }])
138}
139
140/** Notices for one loop, taken out of the outbox. */
141async function takeNotices($: $, owner: string | undefined): Promise<string[]> {
142  const box = await get($, 'outbox')
143  const mine = box.filter(n => n.owner === owner)
144  if (!mine.length) return []
145  await put($, 'outbox', list => list.filter(n => n.owner !== owner))
146  return mine.map(n => n.text)
147}
148
149/**
150 * Delivers what is waiting in the outbox that its loop has not picked up
151 * from a tool result: an idle main conversation is woken with one short
152 * prompt (setting `wake`), an agent is sent a message, and an agent that is
153 * gone hands its notice to the main conversation.
154 */
155async function deliver($: $): Promise<void> {
156  const box = await get($, 'outbox')
157  if (!box.length) return
158  const now = await $.clock.now()
159  const keep: Notice[] = []
160  const toMain: string[] = []
161  for (const n of box) {
162    if (n.owner === undefined) toMain.push(n.text)
163    // Give a running agent one poll to pick it up from a tool result.
164    else if (now - n.at < cfg.pollMs - 1000) keep.push(n)
165    else {
166      const sent = await $.session.send({ to: { agentId: n.owner }, text: n.text }).catch(() => ({ isDelivered: false }))
167      if (!sent.isDelivered) toMain.push(n.text)
168    }
169  }
170  if (toMain.length && !mainTurn && cfg.wake) {
171    await put($, 'outbox', () => keep)
172    void $.prompt.submit({ text: toMain.join('\n') }).catch(err => $.ui.log(`sprc: wake failed: ${String(err)}`, { to: 'debug' }))
173    return
174  }
175  // The main conversation is busy (its next tool result carries them) or
176  // waking is off (the person's next prompt carries them).
177  await put($, 'outbox', () => [...keep, ...toMain.map(text => ({ text, at: now }))])
178}
179
180/** Failed tasks' log paths, while scontrol still remembers them (a few minutes after the end). */
181async function failedLogs(run: Run, reports: readonly JobReport[]): Promise<FailedLog[]> {
182  const logs: FailedLog[] = []
183  for (const t of reports.flatMap(r => r.failed).slice(0, 3)) {
184    const f = await fetchScontrol(run, t.id).catch(() => null)
185    const path = f?.['StdErr'] && f['StdErr'] !== f['StdOut'] ? f['StdErr'] : f?.['StdOut']
186    if (path) logs.push({ id: t.id, path })
187  }
188  return logs
189}
190
191/**
192 * Updates followed jobs from a fresh snapshot: start toasts, jobs gone from
193 * the queue, their reports once sacct has them, and one notice per group
194 * once every job of the group has ended.
195 */
196async function track($: $, snap: Snapshot): Promise<void> {
197  const run = runner($)
198  const now = snap.at
199  let follows = await get($, 'followed')
200  if (!follows.length) return
201
202  const started: string[] = []
203  follows = follows.map(f => {
204    const rows = snap.mine.filter(j => parentId(j.id) === f.id)
205    if (!f.started && rows.some(j => j.state === 'R')) {
206      started.push(f.id)
207      return { ...f, started: true }
208    }
209    if (!f.gone && f.since < now && !hasJob(snap.mine, f.id)) return { ...f, gone: now }
210    return f
211  })
212  if (started.length) {
213    const f = follows.find(x => x.id === started[0])!
214    const nodes = [...new Set(snap.mine.filter(j => started.includes(parentId(j.id)) && j.state === 'R').map(j => j.nodes))]
215    $.ui.toast(
216      started.length === 1
217        ? `▶ job ${f.id} started on ${nodes.join(', ')}`
218        : `▶ ${started.length} jobs started (${idRanges(started)})`,
219    )
220  }
221
222  // Reports for jobs that left the queue; sacct can lag the queue by a few
223  // seconds, so a job it has not finished recording waits for the next poll
224  // (up to five minutes, then it is reported as best known).
225  const pending = follows.filter(f => f.gone && !f.report)
226  if (pending.length) {
227    const reports = await fetchReports(run, pending.map(f => f.id), now)
228    follows = follows.map(f => {
229      const report = reports.get(f.id)
230      if (report) return { ...f, report }
231      if (f.gone && !f.report && now - f.gone > 5 * 60_000) return { ...f, report: unknownReport(f.id, now) }
232      return f
233    })
234  }
235
236  // Groups whose every job has a report are done.
237  const done = new Map<string, Followed[]>()
238  for (const f of follows) done.set(f.group, [...(done.get(f.group) ?? []), f])
239  const ended: Followed[] = []
240  for (const [, members] of done) if (members.every(f => f.report)) ended.push(...members)
241  await put($, 'followed', () => follows.filter(f => !ended.includes(f)))
242  if (!ended.length) return
243
244  const reports = ended.map(f => f.report!)
245  await put($, 'finished', list => [...reports, ...list.filter(r => !reports.some(x => x.id === r.id))].slice(0, 20))
246
247  const told = ended.filter(f => !awaited.has(f.id))
248  const byLoop = new Map<string, Followed[]>()
249  for (const f of told) byLoop.set(loopKey(f.owner), [...(byLoop.get(loopKey(f.owner)) ?? []), f])
250  for (const [, members] of byLoop) {
251    const rs = members.map(f => f.report!)
252    await queueNotice($, members[0]!.owner, endMessage(rs, await failedLogs(run, rs), seenAdvice))
253  }
254
255  const bad = reports.filter(r => r.failed.length || isBad(r.state)).length
256  const left = follows.length - ended.length
257  $.ui.toast(
258    reports.length === 1
259      ? `${bad ? '✗' : '✓'} job ${reports[0]!.id} ${reports[0]!.state} (${reports[0]!.elapsed})`
260      : `${bad ? '✗' : '✓'} ${reports.length} jobs ended: ${reports.length - bad} ok${bad ? `, ${bad} failed` : ''}${left ? ` · ${left} still followed` : ''}`,
261    { timeoutMs: 8000 },
262  )
263}
264
265function unknownReport(id: string, now: number): JobReport {
266  return {
267    id,
268    name: '',
269    state: 'ENDED',
270    counts: { ENDED: 1 },
271    tasks: 1,
272    isArray: false,
273    failed: [],
274    exitCode: '?',
275    elapsed: '?',
276    elapsedS: NaN,
277    limit: '?',
278    cpus: 0,
279    gpus: 0,
280    reqMem: '?',
281    maxRss: '?',
282    advice: [],
283    endedAt: now,
284  }
285}
286
287// ---- polling ---------------------------------------------------------------
288
289/**
290 * `isTimer`: a background tick. With nothing followed those run at a quarter
291 * of the configured rate; anything that needs fresh data (a tool, /sprc, a
292 * cluster-ish prompt) polls on its own.
293 */
294async function poll($: $, isTimer = false): Promise<void> {
295  if (isPolling || !user) return
296  const now = await $.clock.now()
297  if (isTimer && now - lastPollAt < 4 * cfg.pollMs - 1000) {
298    const isIdle = (await get($, 'followed')).length === 0 && (await get($, 'outbox')).length === 0
299    if (isIdle) return
300  }
301  isPolling = true
302  lastPollAt = now
303  try {
304    const snap = await fetchSnapshot(runner($), user, now)
305    await put($, 'snapshot', () => snap)
306    if (!snap.error) {
307      await track($, snap)
308    }
309    await deliver($)
310    await setStatus($, snap)
311  } catch (err) {
312    $.ui.log(`sprc poll failed: ${String(err)}`, { to: 'debug' })
313  } finally {
314    isPolling = false
315  }
316}
317
318async function setStatus($: $, snap: Snapshot): Promise<void> {
319  if (snap.error) {
320    $.ui.status('sprc ▸ Slurm unreachable')
321    return
322  }
323  const g = gpuTotals(snap.nodes)
324  const follows = await get($, 'followed')
325  let mine = ''
326  if (follows.length) {
327    const rows = snap.mine.filter(j => follows.some(f => f.id === parentId(j.id)))
328    const r = rows.filter(j => j.state === 'R').length
329    const pd = rows.filter(j => j.state === 'PD').length
330    mine = ` · following ${follows.length}${r || pd ? ` (${r}R ${pd}PD)` : ''}`
331  } else if (snap.mine.length) {
332    mine = ` · you ${snap.mine.filter(j => j.state === 'R').length}R ${snap.mine.filter(j => j.state === 'PD').length}PD`
333  }
334  $.ui.status(`sprc ▸ ${g.usable}/${g.total} GPU free${g.idle > g.usable ? ` (+${g.idle - g.usable} stranded)` : ''}${mine} · queue ${snap.others.pending}`)
335}
336
337function summary(snap: Snapshot | null): string {
338  if (!snap) return '[sprc] no data yet'
339  if (snap.error) return `[sprc] Slurm unreachable (${snap.error})`
340  const g = gpuTotals(snap.nodes)
341  const free = snap.nodes.filter(n => nodeUsable(n) > 0).map(n => `${n.name} ${nodeUsable(n)}`)
342  const r = snap.mine.filter(j => j.state === 'R').length
343  const pd = snap.mine.filter(j => j.state === 'PD').length
344  return `[sprc live] ${g.usable}/${g.total} GPUs free for a default GPU job${free.length ? ` (${free.join(', ')})` : ''}${g.idle > g.usable ? `; ${g.idle - g.usable} more idle but short of the 32 CPU + 375G a GPU gets by default` : ''}. You: ${r} running, ${pd} pending. Others: ${snap.others.running} running, ${snap.others.pending} pending.`
345}
346
347// ---- model tools -------------------------------------------------------------
348
349/** "123, 124 125_3" -> ["123", "124", "125_3"]; null if any is not a job id. */
350function jobIds(raw: unknown): string[] | null {
351  const ids = String(raw ?? '')
352    .split(/[\s,]+/)
353    .filter(Boolean)
354  return ids.length && ids.every(id => JOB_ID.test(id)) ? ids : null
355}
356
357async function registerTools($: $): Promise<void> {
358  await $.tool.register({
359    name: 'sprc_status',
360    description:
361      'Live state of the sprc Slurm cluster: free GPUs per node, your queued/running jobs with pending reasons explained, queue depth, what this session follows, and recently finished followed jobs.',
362    inputSchema: { type: 'object', properties: {} },
363  })
364  await $.tool.register({
365    name: 'sprc_job',
366    description:
367      'One Slurm job (running, pending or finished; an array id summarises its tasks): state and pending reason explained, times, resources, log paths, the tail of its log, and for finished jobs CPU/memory/time use with right-sizing advice.',
368    inputSchema: {
369      type: 'object',
370      properties: {
371        job_id: { type: 'string', description: 'A job id, e.g. "80240", or an array task, "80240_3".' },
372        log_lines: { type: 'number', description: 'Trailing log lines to include (default 30, max 200).' },
373        stderr: { type: 'boolean', description: 'Tail StdErr instead of StdOut (when they differ).' },
374      },
375      required: ['job_id'],
376    },
377  })
378  await $.tool.register({
379    name: 'sprc_wait',
380    description:
381      'Block until Slurm jobs end (or start), up to 9 minutes per call, then return their results. Takes several ids and array ids. Only for short waits you cannot work through: jobs you submit are already followed, and you get one message when they have all ended.',
382    inputSchema: {
383      type: 'object',
384      properties: {
385        job_id: { type: 'string', description: 'One or more job ids, comma- or space-separated.' },
386        until: { type: 'string', enum: ['end', 'any', 'start'], description: '"end" (default): all have ended; "any": the first ends; "start": the first starts.' },
387        timeout_minutes: { type: 'number', description: '1-9, default 9.' },
388      },
389      required: ['job_id'],
390    },
391  })
392  await $.tool.register({
393    name: 'sprc_follow',
394    description:
395      'Follow jobs you did not submit with sbatch in this session (sbatch submissions are followed automatically): when they have all ended you get one message with results, failures and log paths. stop=true unfollows.',
396    inputSchema: {
397      type: 'object',
398      properties: {
399        job_id: { type: 'string', description: 'One or more job ids, comma- or space-separated.' },
400        stop: { type: 'boolean' },
401      },
402      required: ['job_id'],
403    },
404  })
405}
406
407/**
408 * Why job `id` cannot be followed, or null if it can: it must be yours and
409 * still queued or running. An ended one is returned as its result, so the
410 * caller learns it now instead of waiting on an end that never comes.
411 */
412async function followRefusal($: $, id: string): Promise<string | null> {
413  const run = runner($)
414  const q = await run(['squeue', '-h', '-j', id, '-o', '%u'])
415  const owners = new Set(q.exitCode === 0 ? q.stdout.split('\n').map(l => l.trim()).filter(Boolean) : [])
416  if (owners.size) return owners.has(user) ? null : `${id}: not yours; only your own jobs can be followed.`
417  const report = (await fetchReports(run, [id], await $.clock.now())).get(parentId(id))
418  if (!report) return `${id}: not queued or running, and sacct has no finished record of it.`
419  if (report.user && report.user !== user) return `${id}: not yours; only your own jobs can be followed.`
420  return `${id} already ended: ${reportLine(report)}`
421}
422
423async function statusTool($: $): Promise<string> {
424  await poll($)
425  const snap = await get($, 'snapshot')
426  const fin = await get($, 'finished')
427  const follows = await get($, 'followed')
428  const lines = [summary(snap)]
429  // Bounded: a campaign of hundreds of jobs must not become hundreds of lines.
430  const mine = snap?.mine ?? []
431  const running = mine.filter(j => j.state !== 'PD')
432  const pending = mine.filter(j => j.state === 'PD')
433  for (const j of running.slice(0, 10)) {
434    lines.push(`  ${j.id} ${j.state} "${j.name}" ${j.elapsed}/${j.limit} on ${j.nodes} · ${j.gpus} GPU ${j.cpus} CPU ${j.mem}`)
435  }
436  if (running.length > 10) lines.push(`  … ${running.length - 10} more running`)
437  for (const j of pending.slice(0, 6)) {
438    lines.push(`  ${j.id} PD "${j.name}" ${explainReason(j.reason)}${j.start !== 'N/A' ? ` · est. start ${j.start}` : ''} · ${j.gpus} GPU ${j.cpus} CPU ${j.mem} · qos ${j.qos}`)
439  }
440  if (pending.length > 6) {
441    const why = new Map<string, number>()
442    for (const j of pending.slice(6)) why.set(j.reason, (why.get(j.reason) ?? 0) + 1)
443    lines.push(`  … ${pending.length - 6} more pending (${[...why].map(([k, n]) => `${explainReason(k)} ×${n}`).join(', ')})`)
444  }
445  if (follows.length) lines.push(`Following: ${idRanges(follows.map(f => f.id))}`)
446  if (fin.length) {
447    lines.push('Recently ended (followed):')
448    for (const r of fin.slice(0, 5)) lines.push(`  ${reportLine(r)}`)
449  }
450  return lines.join('\n')
451}
452
453async function jobTool($: $, args: { job_id?: unknown; log_lines?: unknown; stderr?: unknown }): Promise<string> {
454  const id = String(args.job_id ?? '').trim()
455  if (!JOB_ID.test(id)) return `"${id}" is not a job id.`
456  const run = runner($)
457  const now = await $.clock.now()
458  const fields = await fetchScontrol(run, id)
459  const state = fields?.['JobState']
460  const isPlainLive = !!state && !TERMINAL_STATES.has(state) && !fields?.['ArrayJobId']
461  const report = isPlainLive ? null : await fetchReport(run, id, now)
462  if (!fields && !report) return `Job ${id}: unknown to scontrol and sacct.`
463  const out: string[] = []
464  if (fields) {
465    const f = fields
466    out.push(`Job ${f['JobId']}${f['ArrayTaskId'] ? ` (array ${f['ArrayJobId']} task ${f['ArrayTaskId']})` : ''} "${f['JobName']}" ${f['JobState']}${f['Reason'] && f['Reason'] !== 'None' ? ` (${explainReason(f['Reason'])})` : ''}`)
467    out.push(`  partition ${f['Partition']} · qos ${f['QOS']} · nodes ${f['NodeList'] || '-'} · TRES ${f['AllocTRES'] || f['ReqTRES'] || '?'}`)
468    out.push(`  time ${f['RunTime']} of ${f['TimeLimit']} · submitted ${f['SubmitTime']} · start ${f['StartTime']}${f['EndTime'] !== 'Unknown' ? ` · end ${f['EndTime']}` : ''}${f['Restarts'] && f['Restarts'] !== '0' ? ` · requeued ${f['Restarts']}×` : ''}`)
469    out.push(`  workdir ${f['WorkDir']} · command ${f['Command']}`)
470    if (f['ExitCode'] && f['ExitCode'] !== '0:0') out.push(`  exit ${f['ExitCode']}`)
471  }
472  if (report && Object.keys(report.counts).every(s => TERMINAL_STATES.has(s))) {
473    out.push(`Ended: ${reportLine(report)}`)
474    if (report.failed.length) out.push(`  failed: ${report.failed.map(t => `${t.id} ${t.state} exit ${t.exitCode}`).join('; ')}`)
475    out.push(`  right-sizing: ${report.advice.length ? report.advice.join('; ') : 'request looked about right'}`)
476  } else if (report?.isArray) {
477    out.push(`Array tasks so far: ${Object.entries(report.counts).map(([s, n]) => `${n} ${s}`).join(', ')}`)
478  }
479  const path = args.stderr ? fields?.['StdErr'] : fields?.['StdOut']
480  if (path) {
481    const n = Math.max(1, Math.min(200, Number(args.log_lines ?? 30) || 30))
482    const log = await tailFile(run, path, n)
483    out.push(`--- last ${log.length} lines of ${path} ---`, ...log)
484  } else if (!fields) {
485    out.push('(scontrol has forgotten this job, so its log path is unknown; the job script\'s --output says where)')
486  }
487  return out.join('\n')
488}
489
490// The loop runs on the host (squeue every 15 s), so the hook's own time
491// budget is not spent while it waits. `$.process.run` allows ten minutes at
492// most, so a wait is capped at nine.
493const WAIT_SCRIPT = `
494ids="$1"; until="$2"; deadline=$(( $(date +%s) + $3 ))
495st() { squeue -h -j "$ids" -o '%F %T' 2>/dev/null | sort -u; }
496first=$(st | cut -d' ' -f1 | sort -u | wc -l)
497while :; do
498  s=$(st)
499  if [ -z "$s" ]; then echo "ENDED"; exit 0; fi
500  case "$until" in
501    start) echo "$s" | grep -q ' RUNNING$' && { echo "STARTED"; echo "$s"; exit 0; } ;;
502    any) [ "$(echo "$s" | cut -d' ' -f1 | sort -u | wc -l)" -lt "$first" ] && { echo "SOME"; echo "$s"; exit 0; } ;;
503  esac
504  [ $(date +%s) -ge $deadline ] && { echo "TIMEOUT"; echo "$s"; exit 0; }
505  sleep 15
506done`
507
508async function waitTool($: $, args: { job_id?: unknown; until?: unknown; timeout_minutes?: unknown }, owner: string | undefined): Promise<string> {
509  const ids = jobIds(args.job_id)
510  if (!ids) return `"${String(args.job_id ?? '')}" is not a job id (or a comma-separated list of them).`
511  const until = args.until === 'start' || args.until === 'any' ? args.until : 'end'
512  const minutes = Math.max(1, Math.min(9, Number(args.timeout_minutes ?? 9) || 9))
513  const parents = [...new Set(ids.map(parentId))]
514  for (const id of parents) awaited.add(id)
515  let outcome: string[]
516  try {
517    const r = await $.process.run(['bash', '-c', WAIT_SCRIPT, 'sprc_wait', ids.join(','), until, String(minutes * 60)], {
518      timeoutMs: minutes * 60_000 + 30_000,
519    })
520    outcome = r.stdout.trim().split('\n')
521  } finally {
522    for (const id of parents) awaited.delete(id)
523  }
524  const now = await $.clock.now()
525  const queued = new Set(outcome.slice(1).map(l => l.split(' ')[0]!))
526  const ended = parents.filter(id => !queued.has(id))
527  const reports = [...(await fetchReports(runner($), ended, now)).values()]
528  // Reported here, so the follow does not report them again.
529  const reported = new Set(reports.map(r => r.id))
530  await put($, 'followed', list => list.filter(f => !reported.has(f.id)))
531  if (reports.length) await put($, 'finished', list => [...reports, ...list.filter(r => !reported.has(r.id))].slice(0, 20))
532  const lines: string[] = []
533  if (reports.length) lines.push(endMessage(reports, await failedLogs(runner($), reports), seenAdvice))
534  if (outcome[0] === 'STARTED') {
535    lines.push(`Started: ${outcome.slice(1).filter(l => l.endsWith(' RUNNING')).map(l => l.split(' ')[0]).join(', ')}`)
536    return lines.join('\n')
537  }
538  if (outcome[0] === 'TIMEOUT') {
539    const states = new Map<string, number>()
540    for (const l of outcome.slice(1)) states.set(l.split(' ')[1]!, (states.get(l.split(' ')[1]!) ?? 0) + 1)
541    await follow($, parents.filter(id => !reported.has(id)), owner, 'tool')
542    lines.push(
543      `Still queued after ${minutes} min: ${[...states].map(([s, n]) => `${n} ${s}`).join(', ')}. They are followed: you will get one message when they have all ended, so rather than waiting again, end your turn or carry on with other work.`,
544    )
545  }
546  if (!lines.length) lines.push(`${idRanges(ended)}: no longer queued; sacct has no finished record yet. Try sprc_job shortly.`)
547  return lines.join('\n')
548}
549
550async function followTool($: $, args: { job_id?: unknown; stop?: unknown }, owner: string | undefined): Promise<string> {
551  const ids = jobIds(args.job_id)
552  if (!ids) return `"${String(args.job_id ?? '')}" is not a job id (or a comma-separated list of them).`
553  const parents = [...new Set(ids.map(parentId))]
554  if (args.stop === true) {
555    await put($, 'followed', list => list.filter(f => !parents.includes(f.id)))
556    return `Stopped following ${idRanges(parents)}.`
557  }
558  const already = new Set((await get($, 'followed')).map(f => f.id))
559  const out: string[] = []
560  const ok: string[] = []
561  for (const id of parents) {
562    if (already.has(id)) continue
563    const refusal = await followRefusal($, id)
564    if (refusal) out.push(refusal)
565    else ok.push(id)
566  }
567  await follow($, ok, owner, 'tool')
568  const now = [...already].filter(id => parents.includes(id)).concat(ok)
569  if (now.length) out.unshift(`Following ${idRanges(now)}: one message when they have all ended. End your turn or keep working; no need to poll.`)
570  return out.join('\n')
571}
572
573// ---- explaining pending reasons -------------------------------------------
574
575const REASONS: Record<string, string> = {
576  Priority: 'behind higher-priority jobs',
577  Resources: 'next in line, waiting for resources',
578  Dependency: 'waiting on a dependency',
579  DependencyNeverSatisfied: 'dependency failed; will never start (scancel it)',
580  JobArrayTaskLimit: 'array throttle (%N) reached',
581  QOSMaxGRESPerUser: 'at your QoS GPU limit',
582  QOSMaxJobsPerUserLimit: 'at your QoS job-count limit',
583  QOSGrpGRES: 'QoS group GPU limit reached',
584  AssocGrpGRESMinutes: 'GPU-minutes budget exhausted',
585  AssocGrpGRES: 'account GPU limit reached',
586  ReqNodeNotAvail: 'requested node unavailable (drained or reserved)',
587  BeginTime: 'held until its --begin time',
588  JobHeldUser: 'held by you (scontrol release)',
589  JobHeldAdmin: 'held by an admin',
590  PartitionTimeLimit: '--time exceeds the partition limit; will never start',
591  QOSMaxWallDurationPerJobLimit: '--time exceeds the QoS limit; will never start',
592}
593
594export function explainReason(reason: string): string {
595  const key = reason.replace(/^\(|\)$/g, '')
596  return REASONS[key] ?? key
597}
598
599// ---- the Bash hook's pieces --------------------------------------------------
600
601/** The highest job id anyone has queued, so the ids sbatch hands out next are known to be above it. */
602async function queueTop(run: Run): Promise<number> {
603  const r = await run(['squeue', '-h', '-a', '-r', '-o', '%F'], { timeoutMs: 10_000 }).catch(() => null)
604  if (!r || r.exitCode !== 0) return Infinity
605  return r.stdout.split('\n').reduce((m, l) => Math.max(m, Number(l.trim()) || 0), 0)
606}
607
608/** Your jobs above `floor`: what a command submitted when its output did not say. */
609async function mineAbove(run: Run, floor: number): Promise<string[]> {
610  if (!Number.isFinite(floor)) return []
611  const r = await run(['squeue', '--me', '-h', '-r', '-o', '%F'], { timeoutMs: 10_000 }).catch(() => null)
612  if (!r || r.exitCode !== 0) return []
613  return [...new Set(r.stdout.split('\n').map(l => l.trim()).filter(l => Number(l) > floor))]
614}
615
616async function guardFindings($: $, command: string): Promise<Finding[]> {
617  let allocated: Set<string> | null = null
618  if (/\bssh\b/.test(command) && /\bsprc\d+/.test(command)) {
619    const r = await $.process.run(['squeue', '--me', '-h', '-t', 'R', '-o', '%N']).catch(() => null)
620    if (r && r.exitCode === 0) allocated = new Set(r.stdout.split('\n').flatMap(l => expandNodes(l.trim())))
621  }
622  const cwd = await $.session.cwd()
623  // A script's own #SBATCH --chdir settles where it runs, so read the scripts named.
624  const scripts = new Map<string, string>()
625  for (const { script, path } of sbatchScripts(command, cwd)) {
626    if (!path || scripts.has(script)) continue
627    const text = await $.fs.read(path).catch(() => null)
628    if (text !== null) scripts.set(script, text.slice(0, 20_000))
629  }
630  return checkBash(command, { cwd, allocatedNodes: allocated, isLoginNode, scripts })
631}
632
633function why(err: { kind: string; message?: string }): string {
634  return err.message ? `${err.kind}: ${err.message}` : err.kind
635}
636
637// ---- hooks -------------------------------------------------------------------
638
639export const register: Register = (on, options) => {
640  cfg.pollMs = Math.max(10, Number(options['pollSeconds'] ?? 30)) * 1000
641  cfg.guards = String(options['guards'] ?? 'enforce')
642  cfg.liveContext = options['liveContext'] !== false
643  cfg.wake = options['wake'] !== false
644
645  on('session.start', async ($, e, next) => {
646    const started = await next(e)
647    // Only on the sprc cluster: another site's Slurm, or no Slurm, gets nothing.
648    const probe = await $.process.run(['scontrol', 'show', 'config'], { timeoutMs: 5000 }).catch(() => null)
649    if (!probe || probe.exitCode !== 0 || !/^ClusterName\s*=\s*sprc\s*$/m.test(probe.stdout)) {
650      await put($, 'isEnabled', () => false)
651      return started
652    }
653    user = (await $.env.get('USER')) ?? ''
654    const host = await $.process.run(['hostname', '-s']).catch(() => null)
655    isLoginNode = (host?.stdout.trim() ?? '') === 'sprlab005'
656    await put($, 'isEnabled', () => true)
657
658    await $.command.register({
659      name: 'sprc',
660      description: 'sprc cluster summary and followed jobs: /sprc, /sprc follow <ids>, /sprc unfollow <ids>',
661      argumentHint: '[follow <ids> | unfollow <ids>]',
662      immediate: true,
663    })
664    await registerTools($)
665    await poll($)
666    $.clock.every(cfg.pollMs, () => void poll($, true))
667    return started
668  })
669
670  // ---- the main conversation's turns: when to wake it, and job groups
671
672  on('turn.start', async ($, e, next) => {
673    mainTurn = { id: e.turnId }
674    return next(e)
675  })
676
677  on('turn.complete', async ($, e, next) => {
678    const r = await next(e)
679    if (mainTurn?.id === e.turnId) {
680      mainTurn = null
681      idleTurn++
682      // Whatever came in during the turn and found no tool result to ride on.
683      if ((await get($, 'isEnabled')) && (await get($, 'outbox')).some(n => n.owner === undefined)) void deliver($)
684    }
685    return r
686  })
687
688  // ---- slash command
689
690  on('command.run', { command: 'sprc' }, async ($, e) => {
691    if (!(await get($, 'isEnabled'))) return { text: 'sprc: not on the sprc cluster.' }
692    const [sub, ...rest] = e.args.trim().split(/\s+/)
693    if (sub === 'follow' || sub === 'unfollow') {
694      const ids = jobIds(rest.join(' '))
695      if (!ids) return { text: `sprc: usage: /sprc ${sub} <job ids>` }
696      if (sub === 'unfollow') {
697        await put($, 'followed', list => list.filter(f => !ids.map(parentId).includes(f.id)))
698        return { text: `sprc: stopped following ${idRanges(ids.map(parentId))}.` }
699      }
700      const out: string[] = []
701      const ok: string[] = []
702      for (const id of ids) {
703        const refusal = await followRefusal($, id)
704        if (refusal) out.push(refusal)
705        else ok.push(id)
706      }
707      await follow($, ok, undefined, 'person')
708      if (ok.length) out.unshift(`following ${idRanges(ok.map(parentId))}`)
709      return { text: `sprc: ${out.join('\n')}` }
710    }
711    await poll($)
712    const follows = await get($, 'followed')
713    return { text: `${summary(await get($, 'snapshot'))}${follows.length ? `\nFollowing: ${idRanges(follows.map(f => f.id))}` : ''}` }
714  })
715
716  // ---- model tools. A failure becomes the tool's result, never a missing answer.
717
718  on('tool.call', { tool: 'mcp__sprc-slurm-mods__sprc_status' }, async $ => ({ result: await statusTool($) })).catch(($, e, next) => ({
719    result: `sprc_status failed: ${why(next.error)}`,
720  }))
721
722  on('tool.call', { tool: 'mcp__sprc-slurm-mods__sprc_job' }, async ($, e) => ({ result: await jobTool($, e as unknown as Record<string, unknown>) })).catch(($, e, next) => ({
723    result: `sprc_job failed: ${why(next.error)}`,
724  }))
725
726  on('tool.call', { tool: 'mcp__sprc-slurm-mods__sprc_wait' }, async ($, e) => ({ result: await waitTool($, e as unknown as Record<string, unknown>, e.agentId) })).catch(($, e, next) => ({
727    result: `sprc_wait failed (${why(next.error)}). Your jobs stay followed; you will get a message when they end.`,
728  }))
729
730  on('tool.call', { tool: 'mcp__sprc-slurm-mods__sprc_follow' }, async ($, e) => ({ result: await followTool($, e as unknown as Record<string, unknown>, e.agentId) })).catch(($, e, next) => ({
731    result: `sprc_follow failed: ${why(next.error)}`,
732  }))
733
734  // ---- guardrails and sbatch tracking on Bash
735
736  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
737    if (!(await get($, 'isEnabled'))) return next(e)
738    const command = e.command
739    const isSubmit = runsSbatch(command) || /`\s*sbatch\b/.test(command)
740    const isGuarded = cfg.guards !== 'off' && /\b(sbatch|ssh|sacct|torchrun|deepspeed|accelerate|vllm|sglang|python[\d.]*)\b/.test(command)
741    if (!isSubmit && !isGuarded) return next(e)
742
743    // Everything the mod does here is advisory: if it fails, the command runs as if the mod were not there.
744    let findings: Finding[] = []
745    let top = Infinity
746    try {
747      if (isGuarded) findings = await guardFindings($, command)
748      if (isSubmit && !e.run_in_background) top = await queueTop(runner($))
749    } catch (err) {
750      $.ui.log(`sprc guard skipped: ${String(err)}`, { to: 'debug' })
751    }
752    const blocking = findings.filter(f => f.level === 'reject')
753    if (blocking.length && cfg.guards === 'enforce') {
754      $.ui.toast(`sprc blocked: ${blocking.map(f => f.rule).join(', ')}`)
755      return { deny: `[sprc guard] ${blocking.map(f => f.message).join('\n')}\n(The user can relax this with /config → sprc-slurm-mods guards.)` }
756    }
757
758    const ran = await next(e)
759    if (ran.deny !== undefined) return ran
760    try {
761      const notes = findings
762        .filter(f => f.level !== 'reject' || cfg.guards === 'warn')
763        .filter(f => f.level === 'reject' || !toldRules.has(f.rule))
764        .map(f => (toldRules.add(f.rule), `[sprc guard] ${f.message}`))
765      if (isSubmit && !e.run_in_background) {
766        let ids = submittedJobs(ran.text ?? '', /--parsable\b/.test(command))
767        // `JID=$(sbatch --parsable …)` prints nothing: the queue says what is new.
768        if (!ids.length) ids = await mineAbove(runner($), top)
769        const fresh = await follow($, ids, e.agentId, 'sbatch')
770        if (fresh.length) {
771          const loop = loopKey(e.agentId)
772          notes.push(
773            toldFollowing.has(loop)
774              ? `[sprc] Following ${idRanges(fresh)}.`
775              : `[sprc] Following ${idRanges(fresh)}${fresh.length > 1 ? ' as a group' : ''}: when ${fresh.length > 1 ? 'they have all' : 'it has'} ended you get one message with results, failures, log paths and right-sizing. No need to poll squeue: end your turn or keep working (sprc_wait blocks if you must).`,
776          )
777          toldFollowing.add(loop)
778          $.ui.toast(`following ${fresh.length === 1 ? `job ${fresh[0]}` : `${fresh.length} jobs`}`)
779          void poll($)
780        }
781      }
782      if (!notes.length) return ran
783      return { ...ran, context: [...(ran.context ?? []), ...notes] }
784    } catch (err) {
785      $.ui.log(`sprc: after-Bash tracking failed: ${String(err)}`, { to: 'debug' })
786      return ran
787    }
788  }).catch(($, e, next) => next(e)) // advisory: a failure runs the command as if the mod were not there
789
790  // ---- notices ride on the next tool result of the loop they are for
791
792  on('tool.call', async ($, e, next) => {
793    const ran = await next(e)
794    if (!mem.outbox?.length || ran.deny !== undefined || ran.isError) return ran
795    try {
796      const texts = await takeNotices($, e.agentId)
797      if (!texts.length) return ran
798      return { ...ran, context: [...(ran.context ?? []), ...texts] }
799    } catch {
800      return ran
801    }
802  }).catch(($, e, next) => next(e))
803
804  // ---- live context and waiting notices on the person's prompts
805
806  on('prompt.submit', async ($, e, next) => {
807    if (e.origin.kind === 'plugin' || !(await get($, 'isEnabled').catch(() => false))) return next(e)
808    const context = [...(e.context ?? [])]
809    try {
810      context.push(...(await takeNotices($, undefined)))
811      if (cfg.liveContext && SLURMY.test(e.text)) {
812        const now = await $.clock.now()
813        if (now - lastPollAt > 60_000) await poll($)
814        const snap = await get($, 'snapshot')
815        // An unchanged cluster is already in the conversation: re-send it only
816        // after 15 minutes, so a long Slurm-heavy session pays for it once.
817        const text = summary(snap)
818        if (snap && (text !== lastContext.text || now - lastContext.at >= 15 * 60_000)) {
819          lastContext = { text, at: now }
820          context.push(text)
821        }
822      }
823    } catch (err) {
824      $.ui.log(`sprc prompt context skipped: ${String(err)}`, { to: 'debug' })
825    }
826    return context.length === (e.context ?? []).length ? next(e) : next({ ...e, context })
827  }).catch(($, e, next) => next(e))
828}
829
hooks/guards.ts 241 lines
1// Checks on Bash commands before they run. Pure: the hook passes in what it
2// knows about the session and the cluster.
3//
4// `reject` findings are commands that would silently break or hurt other
5// users, and that Slurm itself does not refuse: blocking them never costs a
6// working command. Anything Slurm refuses on its own (interactive scavenger,
7// say) is left to Slurm, whose message stays in step with the policy.
8// `note` findings never block; they ride along as context for the model.
9
10export type Finding = { level: 'reject' | 'note'; rule: string; message: string }
11
12export type GuardContext = {
13  /** The session's working directory, where a bare command runs; '' = unknown. */
14  cwd: string
15  /** Nodes where this user holds a running allocation right now; null = unknown. */
16  allocatedNodes: ReadonlySet<string> | null
17  /** True when the session runs on the login node (sprlab005). */
18  isLoginNode: boolean
19  /**
20   * The text of batch scripts the hook could read, by the path as written in
21   * the command; a script's own `#SBATCH --chdir` settles where it runs.
22   */
23  scripts?: ReadonlyMap<string, string>
24}
25
26/** Splits a command line into simple commands on ;, &&, ||, |, newlines. Quote-aware. */
27export function segments(command: string): string[][] {
28  const out: string[][] = []
29  let words: string[] = []
30  let word = ''
31  let hasWord = false
32  let quote: '"' | "'" | null = null
33  const endWord = () => {
34    if (hasWord) words.push(word)
35    word = ''
36    hasWord = false
37  }
38  const endSeg = () => {
39    endWord()
40    if (words.length) out.push(words)
41    words = []
42  }
43  for (let i = 0; i < command.length; i++) {
44    const c = command[i]!
45    if (quote) {
46      if (c === quote) quote = null
47      else if (c === '\\' && quote === '"' && i + 1 < command.length) word += command[++i]
48      else word += c
49      continue
50    }
51    if (c === '"' || c === "'") {
52      quote = c
53      hasWord = true
54    } else if (c === '\\' && i + 1 < command.length) {
55      word += command[++i]
56      hasWord = true
57    } else if (c === ' ' || c === '\t') endWord()
58    else if (c === '\n' || c === ';' || c === '&' || c === '|' || c === '(' || c === ')') endSeg()
59    else if (c === '#' && !hasWord) {
60      while (i < command.length && command[i] !== '\n') i++
61      endSeg()
62    } else {
63      word += c
64      hasWord = true
65    }
66  }
67  endSeg()
68  return out
69}
70
71/** Drops leading VAR=value assignments, wrappers like `env`, `time`, `nohup`, and shell keywords (`do`, `then`). */
72function head(words: readonly string[]): string[] {
73  let i = 0
74  while (i < words.length) {
75    const w = words[i]!
76    if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) i++
77    else if (/^(env|time|nohup|exec|command|do|then|else|elif|if|while|until|!|\{)$/.test(w)) i++
78    else break
79  }
80  return words.slice(i)
81}
82
83function base(word: string | undefined): string {
84  return (word ?? '').split('/').pop() ?? ''
85}
86
87/** Value of a long/short option in either `--opt=v`, `--opt v`, `-o v` or `-ov` form. */
88function option(words: readonly string[], long: string, short?: string): string | undefined {
89  for (let i = 0; i < words.length; i++) {
90    const w = words[i]!
91    if (w === `--${long}`) return words[i + 1]
92    if (w.startsWith(`--${long}=`)) return w.slice(long.length + 3)
93    if (short && w === `-${short}`) return words[i + 1]
94    if (short && w.startsWith(`-${short}`) && w.length > 2 && !w.startsWith('--')) return w.slice(2)
95  }
96  return undefined
97}
98
99// sbatch options that take no value; any other short option takes the next word.
100const SBATCH_FLAGS = /^(--parsable|--wait|-W|--hold|-H|--requeue|--no-requeue|--test-only|--exclusive|--quiet|-Q|--verbose|-v+|--overcommit|-O|--contiguous|--spread-job|--use-min-nodes|--ignore-pbs|--get-user-env|--export-file|--no-kill|-k|--oversubscribe|-s)$/
101
102/** The batch script an sbatch command line names, or undefined (none, or --wrap). */
103export function sbatchScript(words: readonly string[]): string | undefined {
104  for (let i = 1; i < words.length; i++) {
105    const w = words[i]!
106    if (w === '--wrap' || w.startsWith('--wrap=')) return undefined
107    if (w.startsWith('--')) {
108      if (!w.includes('=') && !SBATCH_FLAGS.test(w)) i++
109      continue
110    }
111    if (w.startsWith('-') && w.length > 1) {
112      if (w.length === 2 && !SBATCH_FLAGS.test(w)) i++
113      continue
114    }
115    return w
116  }
117  return undefined
118}
119
120/** An `#SBATCH` directive's value from a script's header. */
121function directive(text: string | undefined, long: string, short: string): string | undefined {
122  if (!text) return undefined
123  for (const line of text.split('\n')) {
124    if (line.startsWith('#!') || !line.trim()) continue
125    if (!line.startsWith('#')) break // directives end at the first command
126    const m = /^#SBATCH\s+(.*)$/.exec(line)
127    if (m) {
128      const v = option(m[1]!.trim().split(/\s+/), long, short)
129      if (v !== undefined) return v
130    }
131  }
132  return undefined
133}
134
135const HEAVY = /^(torchrun|deepspeed|accelerate|vllm|sglang|python[\d.]*)$/
136const SCRATCH_DIRS = /^\/(tmp|var\/tmp|dev\/shm)(\/|$)/
137
138export function checkBash(command: string, ctx: GuardContext): Finding[] {
139  const findings: Finding[] = []
140  let cwd = ctx.cwd
141  const segs = segments(command)
142
143  for (let s = 0; s < segs.length; s++) {
144    const words = head(segs[s]!)
145    const cmd = base(words[0])
146    if (!cmd) continue
147
148    // A relative, ~ or $VAR target is not resolved here: the directory becomes unknown.
149    if (cmd === 'cd' || cmd === 'pushd') cwd = words[1]?.startsWith('/') ? words[1] : ''
150
151    if (cmd === 'sbatch') {
152      const script = sbatchScript(words)
153      const chdir = option(words, 'chdir', 'D') ?? (script !== undefined ? directive(ctx.scripts?.get(script), 'chdir', 'D') : undefined)
154      const workdir = chdir ? (chdir.startsWith('/') ? chdir : '') : cwd
155      if (workdir && SCRATCH_DIRS.test(workdir)) {
156        findings.push({
157          level: 'reject',
158          rule: 'sbatch-from-tmp',
159          message: `sbatch would run with working directory ${workdir}, which is node-local: the compute node cannot see the login node's copy, so the job starts in an empty directory and fails or writes output nowhere you can read. Stage the script and data under /home, /projects or /data and submit from there.`,
160        })
161      }
162    }
163
164    // A note, not a block: admins are exempt from pam_slurm_adopt, and the
165    // node's own refusal already explains itself to everyone else.
166    if (cmd === 'ssh' && ctx.allocatedNodes) {
167      const target = words.slice(1).find(w => !w.startsWith('-') && /^(\S+@)?sprc\d+/.test(w))
168      const node = target?.replace(/^\S+@/, '').replace(/\..*$/, '')
169      if (node && !ctx.allocatedNodes.has(node)) {
170        const held = [...ctx.allocatedNodes]
171        findings.push({
172          level: 'note',
173          rule: 'ssh-without-allocation',
174          message: `If ssh ${node} was refused: compute nodes admit only users with a running job there, and you have none on ${node}${held.length ? ` (you do on ${held.join(', ')})` : ''}. Get an allocation first (salloc), or ssh to a node your job is on.`,
175        })
176      }
177    }
178
179    if (ctx.isLoginNode && HEAVY.test(cmd)) {
180      const isLaunch =
181        cmd === 'torchrun' ||
182        cmd === 'deepspeed' ||
183        (cmd === 'accelerate' && words[1] === 'launch') ||
184        ((cmd === 'vllm' || cmd === 'sglang') && words[1] === 'serve') ||
185        (cmd.startsWith('python') && words.includes('-m') && /^(torch\.distributed\.(run|launch)|vllm\.entrypoints|sglang\.launch_server)/.test(words[words.indexOf('-m') + 1] ?? ''))
186      const wrapped = segs.slice(0, s).some(p => /^(srun|salloc|sbatch)$/.test(base(head(p)[0])))
187      if (isLaunch && !wrapped) {
188        findings.push({
189          level: 'reject',
190          rule: 'gpu-work-on-login-node',
191          message: `\`${words.slice(0, 3).join(' ')}\` would run on the login node sprlab005, which has no GPUs and is shared by everyone. Run it through sbatch, or inside an salloc/srun allocation.`,
192        })
193      }
194    }
195
196    if (cmd === 'sacct' && words.includes('--json')) {
197      findings.push({
198        level: 'note',
199        rule: 'sacct-json-mem',
200        message: 'Note: on this cluster sacct --json omits memory used (MaxRSS). For efficiency numbers use text sacct (-P -o ...MaxRSS...) or the sprc_job tool.',
201      })
202    }
203  }
204
205  return findings
206}
207
208/**
209 * The batch scripts a command line submits, each with the path to read it
210 * at (following `cd` to absolute directories; '' where it cannot tell).
211 */
212export function sbatchScripts(command: string, cwd: string): { script: string; path: string }[] {
213  const out: { script: string; path: string }[] = []
214  for (const seg of segments(command)) {
215    const words = head(seg)
216    const cmd = base(words[0])
217    if (cmd === 'cd' || cmd === 'pushd') cwd = words[1]?.startsWith('/') ? words[1] : ''
218    if (cmd !== 'sbatch') continue
219    const script = sbatchScript(words)
220    if (script === undefined) continue
221    out.push({ script, path: script.startsWith('/') ? script : cwd && !/^[~$]/.test(script) ? `${cwd}/${script}` : '' })
222  }
223  return out
224}
225
226/** Whether a command line runs sbatch (also inside `$( )`, a loop or a pipeline). */
227export function runsSbatch(command: string): boolean {
228  return segments(command).some(words => base(head(words)[0]) === 'sbatch') || /`\s*sbatch\b/.test(command)
229}
230
231/**
232 * Job ids a Bash result announced: "Submitted batch job 123", or a bare
233 * "123" / "123;cluster" line from sbatch --parsable.
234 */
235export function submittedJobs(output: string, isParsable = false): string[] {
236  const ids = new Set<string>()
237  if (isParsable) for (const m of output.matchAll(/^(\d+)(?:;\S+)?$/gm)) ids.add(m[1]!)
238  for (const m of output.matchAll(/Submitted batch job (\d+)/g)) ids.add(m[1]!)
239  return [...ids]
240}
241
hooks/slurm.ts 561 lines
1// Slurm queries and parsers. Everything here takes a `run` function so the
2// parsers are testable without a cluster; the hooks module passes
3// `$.process.run`.
4
5import type { JobReport, JobRow, NodeRow, Snapshot } from '../types'
6
7export type RunResult = { exitCode: number; stdout: string; stderr: string }
8export type Run = (argv: readonly string[], init?: { timeoutMs?: number }) => Promise<RunResult>
9
10const SINFO_FIELDS = 'NodeList:|,StateLong:|,Gres:|,GresUsed:|,CPUsState:|,AllocMem:|,Memory:|'
11// Name goes last so a `|` in a job name cannot shift the other columns.
12const SQUEUE_FIELDS =
13  'JobID:|,UserName:|,StateCompact:|,TimeUsed:|,TimeLimit:|,tres-alloc:|,Reason:|,QOS:|,Partition:|,NodeList:|,StartTime:|,Name:|'
14
15export const SACCT_FIELDS =
16  'JobID,JobName,State,ExitCode,Elapsed,Timelimit,NCPUS,TotalCPU,ReqMem,MaxRSS,AllocTRES,End,NodeList,User'
17
18// ---- parsing helpers ---------------------------------------------------
19
20/** "gpu:h100_nvl:2" or "gpu:h100_nvl:1(IDX:0)" -> 2 / 1 */
21export function gresCount(gres: string): number {
22  let total = 0
23  for (const part of gres.split(',')) {
24    const m = /gpu(?::[\w.-]+)?:(\d+)/.exec(part)
25    if (m) total += Number(m[1])
26  }
27  return total
28}
29
30/** "cpu=8,mem=12G,node=1,gres/gpu=1" -> { cpu: "8", mem: "12G", ... } */
31export function parseTres(tres: string): Record<string, string> {
32  const out: Record<string, string> = {}
33  for (const kv of tres.split(',')) {
34    const i = kv.indexOf('=')
35    if (i > 0) out[kv.slice(0, i)] = kv.slice(i + 1)
36  }
37  return out
38}
39
40/** "[D-]HH:MM:SS", "MM:SS", "MM:SS.mmm", "UNLIMITED" -> seconds (NaN if unknown) */
41export function durationSeconds(s: string): number {
42  if (!s || s === 'UNLIMITED' || s === 'Partition_Limit' || s === 'INVALID') return NaN
43  let days = 0
44  let rest = s
45  const dash = s.indexOf('-')
46  if (dash >= 0) {
47    days = Number(s.slice(0, dash))
48    rest = s.slice(dash + 1)
49  }
50  const parts = rest.split(':').map(Number)
51  if (parts.some(Number.isNaN)) return NaN
52  let secs = 0
53  for (const p of parts) secs = secs * 60 + p
54  if (parts.length === 2 && dash < 0) {
55    // MM:SS
56  } else if (parts.length === 1) {
57    secs = parts[0]! * 60 // bare minutes, as sbatch --time takes them
58  }
59  return days * 86400 + secs
60}
61
62export function formatDuration(secs: number): string {
63  if (!Number.isFinite(secs)) return '?'
64  secs = Math.max(0, Math.round(secs))
65  const d = Math.floor(secs / 86400)
66  const h = Math.floor((secs % 86400) / 3600)
67  const m = Math.floor((secs % 3600) / 60)
68  if (d > 0) return `${d}d${h}h`
69  if (h > 0) return `${h}h${String(m).padStart(2, '0')}m`
70  if (m > 0) return `${m}m`
71  return `${secs}s`
72}
73
74/** "12G", "500M", "123456K", "12Gn" -> MiB (NaN if unknown) */
75export function memMb(s: string): number {
76  const m = /^([\d.]+)([KMGT]?)/i.exec(s.trim())
77  if (!m) return NaN
78  const n = Number(m[1])
79  switch ((m[2] ?? '').toUpperCase()) {
80    case 'K':
81      return n / 1024
82    case 'G':
83      return n * 1024
84    case 'T':
85      return n * 1024 * 1024
86    case 'M':
87      return n
88    default:
89      return n / (1024 * 1024) // bytes
90  }
91}
92
93export function formatMem(mb: number): string {
94  if (!Number.isFinite(mb)) return '?'
95  if (mb >= 1024) return `${(mb / 1024).toFixed(mb >= 10240 ? 0 : 1)}G`
96  return mb > 0 && mb < 1 ? '<1M' : `${Math.round(mb)}M`
97}
98
99/** "sprc[00-01,03],sprc05" -> ["sprc00","sprc01","sprc03","sprc05"] */
100export function expandNodes(list: string): string[] {
101  const out: string[] = []
102  const re = /([^,[\]]+)(?:\[([^\]]+)\])?/g
103  let m: RegExpExecArray | null
104  while ((m = re.exec(list)) !== null) {
105    const prefix = m[1]!
106    if (!m[2]) {
107      if (prefix && prefix !== '(null)') out.push(prefix)
108      continue
109    }
110    for (const range of m[2].split(',')) {
111      const [a, b] = range.split('-')
112      if (b === undefined) {
113        out.push(prefix + a)
114        continue
115      }
116      const width = a!.length
117      for (let i = Number(a); i <= Number(b); i++) out.push(prefix + String(i).padStart(width, '0'))
118    }
119  }
120  return out
121}
122
123// ---- cluster snapshot --------------------------------------------------
124
125export function parseSinfo(stdout: string): NodeRow[] {
126  const seen = new Map<string, NodeRow>()
127  for (const line of stdout.split('\n')) {
128    const f = line.split('|')
129    if (f.length < 7 || !f[0]) continue
130    const name = f[0].trim()
131    if (seen.has(name)) continue // one row per partition the node is in
132    const [alloc, , , total] = (f[4] ?? '').split('/').map(Number)
133    seen.set(name, {
134      name,
135      state: (f[1] ?? '').trim(),
136      gpus: gresCount(f[2] ?? ''),
137      gpusUsed: gresCount((f[3] ?? '').replace(/\(IDX:[^)]*\)/g, '')),
138      cpusAlloc: alloc ?? 0,
139      cpusTotal: total ?? 0,
140      memAllocMb: Number(f[5]) || 0,
141      memTotalMb: Number(f[6]) || 0,
142    })
143  }
144  return [...seen.values()].sort((a, b) => a.name.localeCompare(b.name))
145}
146
147export function parseSqueue(stdout: string): JobRow[] {
148  const rows: JobRow[] = []
149  for (const line of stdout.split('\n')) {
150    if (!line.trim()) continue
151    const f = line.split('|')
152    if (f.length < 12) continue
153    const tres = parseTres(f[5] ?? '')
154    rows.push({
155      id: f[0]!.trim(),
156      user: f[1]!.trim(),
157      state: f[2]!.trim(),
158      elapsed: f[3]!.trim(),
159      limit: f[4]!.trim(),
160      gpus: Number(tres['gres/gpu'] ?? 0) || 0,
161      cpus: Number(tres['cpu'] ?? 0) || 0,
162      mem: tres['mem'] ?? '?',
163      reason: f[6]!.trim(),
164      qos: f[7]!.trim(),
165      partition: f[8]!.trim(),
166      nodes: f[9]!.trim(),
167      start: f[10]!.trim(),
168      name: f.slice(11).join('|').replace(/\|$/, '').trim(),
169    })
170  }
171  return rows
172}
173
174export async function fetchSnapshot(run: Run, user: string, now: number): Promise<Snapshot> {
175  const [si, sq] = await Promise.all([
176    run(['sinfo', '-h', '-N', '-O', SINFO_FIELDS]),
177    run(['squeue', '-h', '-a', '-O', SQUEUE_FIELDS]),
178  ])
179  if (si.exitCode !== 0 || sq.exitCode !== 0) {
180    return {
181      at: now,
182      error: (si.stderr || sq.stderr || 'sinfo/squeue failed').trim().split('\n')[0],
183      nodes: [],
184      mine: [],
185      others: { running: 0, pending: 0, gpusRunning: 0, gpusPending: 0 },
186    }
187  }
188  const jobs = parseSqueue(sq.stdout)
189  const mine = jobs.filter(j => j.user === user)
190  const others = { running: 0, pending: 0, gpusRunning: 0, gpusPending: 0 }
191  for (const j of jobs) {
192    if (j.user === user) continue
193    if (j.state === 'R' || j.state === 'CG') {
194      others.running++
195      others.gpusRunning += j.gpus
196    } else if (j.state === 'PD') {
197      others.pending++
198      others.gpusPending += j.gpus
199    }
200  }
201  return { at: now, nodes: parseSinfo(si.stdout), mine, others }
202}
203
204// What a GPU job gets per GPU when it asks for nothing else: slurm.conf's
205// DefCpuPerGPU=32, times DefMemPerCPU=12000.
206export const GPU_SHARE = { cpus: 32, memMb: 32 * 12000 }
207
208/** Idle GPUs on one node that a default 1-GPU job could actually start on. */
209export function nodeUsable(n: NodeRow): number {
210  if (/drain|down|fail|maint|reserved|inval/i.test(n.state)) return 0
211  const byCpu = Math.floor((n.cpusTotal - n.cpusAlloc) / GPU_SHARE.cpus)
212  const byMem = Math.floor((n.memTotalMb - n.memAllocMb) / GPU_SHARE.memMb)
213  return Math.max(0, Math.min(n.gpus - n.gpusUsed, byCpu, byMem))
214}
215
216/**
217 * `idle`: GPUs no job holds. `usable`: idle GPUs a default GPU job could
218 * actually get, which excludes nodes that are down/drained or lack the CPUs
219 * or memory that go with a GPU (a node full of CPU jobs strands its GPUs).
220 */
221export function gpuTotals(nodes: readonly NodeRow[]): { total: number; used: number; idle: number; usable: number } {
222  let total = 0
223  let used = 0
224  let usable = 0
225  for (const n of nodes) {
226    total += n.gpus
227    used += n.gpusUsed
228    usable += nodeUsable(n)
229  }
230  return { total, used, idle: total - used, usable }
231}
232
233/** Whether job `id` (or, for an array or het job, any of its parts) is in `rows`. */
234export function hasJob(rows: readonly { id: string }[], id: string): boolean {
235  return rows.some(j => j.id === id || j.id.startsWith(`${id}_`) || j.id.startsWith(`${id}+`))
236}
237
238// ---- one job -----------------------------------------------------------
239
240/** `scontrol show job -o ID` -> key/value fields (first record). */
241export function parseScontrol(stdout: string): Record<string, string> {
242  const line = stdout.split('\n').find(l => l.includes('JobId=')) ?? ''
243  const out: Record<string, string> = {}
244  // Values may contain spaces only in a few fields (Command, Comment); keys
245  // are CamelCase words followed by '='.
246  const re = /(?:^|\s)([A-Za-z][\w:/]*)=(.*?)(?=\s[A-Za-z][\w:/]*=|$)/g
247  let m: RegExpExecArray | null
248  while ((m = re.exec(line)) !== null) out[m[1]!] = m[2]!
249  return out
250}
251
252export async function fetchScontrol(run: Run, id: string): Promise<Record<string, string> | null> {
253  const r = await run(['scontrol', 'show', 'job', '-o', id])
254  if (r.exitCode !== 0) return null
255  const f = parseScontrol(r.stdout)
256  return f['JobId'] ? f : null
257}
258
259type SacctRow = Record<string, string>
260const SACCT_COLUMNS = SACCT_FIELDS.split(',') as readonly string[]
261
262export function parseSacct(stdout: string): SacctRow[] {
263  return stdout
264    .split('\n')
265    .filter(l => l.trim())
266    .map(l => {
267      const f = l.split('|')
268      const row: Record<string, string> = {}
269      SACCT_COLUMNS.forEach((c, i) => (row[c] = f[i] ?? ''))
270      return row
271    })
272}
273
274/** "95605_3" / "95605_[3-200]" / "123+0" / "123.batch" -> "95605" / "95605" / "123" / "123" */
275export function parentId(id: string): string {
276  return /^\d+/.exec(id)?.[0] ?? id
277}
278
279/** "95605_[3-5,9]%4" -> 4 tasks; anything else -> 1 */
280function taskCount(id: string): number {
281  const m = /_\[([^\]]+)\]/.exec(id)
282  if (!m) return 1
283  let n = 0
284  for (const r of m[1]!.replace(/%\d+$/, '').split(',')) {
285    const [a, b] = r.split('-').map(Number)
286    n += b === undefined ? 1 : Math.max(1, b - a! + 1)
287  }
288  return n
289}
290
291type Task = {
292  id: string
293  name: string
294  user: string
295  state: string
296  exitCode: string
297  count: number
298  elapsed: number
299  limit: number
300  cpus: number
301  totalCpu: number
302  reqMemMb: number
303  maxRssMb: number
304  gpus: number
305}
306
307function tasksOf(rows: readonly SacctRow[]): Task[] {
308  const byTask = new Map<string, Task>()
309  for (const r of rows) {
310    const jobId = r['JobID'] ?? ''
311    const taskId = jobId.split('.')[0]!
312    let t = byTask.get(taskId)
313    if (!jobId.includes('.')) {
314      const tres = parseTres(r['AllocTRES'] ?? '')
315      t = {
316        id: taskId,
317        name: r['JobName'] ?? '',
318        user: r['User'] ?? '',
319        state: (r['State'] ?? '').split(' ')[0]!,
320        exitCode: r['ExitCode'] ?? '',
321        count: taskCount(taskId),
322        elapsed: durationSeconds(r['Elapsed'] ?? ''),
323        limit: durationSeconds(r['Timelimit'] ?? ''),
324        cpus: Number(r['NCPUS']) || 0,
325        totalCpu: durationSeconds(r['TotalCPU'] ?? ''),
326        reqMemMb: memMb(r['ReqMem'] ?? ''),
327        maxRssMb: t?.maxRssMb ?? NaN,
328        gpus: Number(tres['gres/gpu'] ?? 0) || 0,
329      }
330      byTask.set(taskId, t)
331    }
332    const v = memMb(r['MaxRSS'] ?? '')
333    // 0 means the 30 s sampler never ran (a short job), not 0 bytes.
334    if (Number.isFinite(v) && v > 0) {
335      if (!t) {
336        t = { id: taskId, maxRssMb: v } as Task
337        byTask.set(taskId, t)
338      } else if (!(t.maxRssMb >= v)) t.maxRssMb = v
339    }
340  }
341  return [...byTask.values()].filter(t => t.state !== undefined)
342}
343
344/** Right-sizing for the next submission, from what the job (or every task of it) used. */
345function advise(a: {
346  states: ReadonlySet<string>
347  elapsed: number
348  limit: number
349  cpus: number
350  cpuEff?: number
351  reqMemMb: number
352  maxRssMb: number
353  memEff?: number
354  timeEff?: number
355}): string[] {
356  const advice: string[] = []
357  // A job that ran under two minutes says little about what it needs.
358  const isMeasured = a.elapsed >= 120
359  if (a.states.has('OUT_OF_MEMORY') || (a.memEff !== undefined && a.memEff > 0.92)) {
360    const want = Math.ceil(((Number.isFinite(a.maxRssMb) ? a.maxRssMb : a.reqMemMb) * 1.5) / 1024)
361    advice.push(`memory was the limit: request --mem=${want}G`)
362  } else if (isMeasured && a.memEff !== undefined && a.memEff < 0.5 && a.reqMemMb >= 8192) {
363    advice.push(`peak mem ${formatMem(a.maxRssMb)} of ${formatMem(a.reqMemMb)}: --mem=${Math.max(4, Math.ceil((a.maxRssMb * 1.3) / 1024))}G is enough`)
364  }
365  if (a.states.has('TIMEOUT')) {
366    advice.push('hit its walltime: raise --time, or checkpoint and --requeue')
367  } else if (isMeasured && a.states.size === 1 && a.states.has('COMPLETED') && a.timeEff !== undefined && a.timeEff < 0.35 && a.limit >= 3600) {
368    advice.push(`ran ${formatDuration(a.elapsed)} of a ${formatDuration(a.limit)} limit: --time=${Math.ceil((a.elapsed * 1.5) / 900) * 15} backfills sooner`)
369  }
370  if (a.cpuEff !== undefined && a.cpuEff < 0.25 && a.cpus >= 8 && a.elapsed > 300) {
371    advice.push(`CPU use ${Math.round(a.cpuEff * 100)}% of ${a.cpus} cores: --cpus-per-task=${Math.max(2, Math.ceil(a.cpus * a.cpuEff * 1.5))} would do`)
372  }
373  return advice
374}
375
376/** The larger of two measurements, either of which may be NaN (unknown). */
377function most(a: number, b: number): number {
378  return Number.isNaN(a) ? b : Number.isNaN(b) ? a : Math.max(a, b)
379}
380
381/**
382 * One report for job `id` from its sacct rows: a plain job, or an array
383 * job summarised over all its tasks (state counts, the failures, and the
384 * peak use of any task, so the advice fits every task).
385 */
386export function buildReport(id: string, rows: readonly SacctRow[], endedAt: number): JobReport | null {
387  // A task id ("123_4") reports that task alone; a job id, all of its tasks.
388  const tasks = tasksOf(rows.filter(r => (id.includes('_') ? (r['JobID'] ?? '').split('.')[0] === id : parentId(r['JobID'] ?? '') === id)))
389  if (!tasks.length) return null
390  const counts: Record<string, number> = {}
391  let n = 0
392  let elapsed = NaN
393  let limit = NaN
394  let maxRssMb = NaN
395  let reqMemMb = NaN
396  let cpuUsed = 0
397  let cpuHeld = 0
398  for (const t of tasks) {
399    counts[t.state] = (counts[t.state] ?? 0) + t.count
400    n += t.count
401    elapsed = most(elapsed, t.elapsed)
402    limit = most(limit, t.limit)
403    maxRssMb = most(maxRssMb, t.maxRssMb)
404    reqMemMb = most(reqMemMb, t.reqMemMb)
405    if (t.elapsed > 0 && t.cpus > 0 && Number.isFinite(t.totalCpu)) {
406      cpuUsed += t.totalCpu
407      cpuHeld += t.elapsed * t.cpus
408    }
409  }
410  const first = tasks[0]!
411  const states = new Set(Object.keys(counts))
412  const failed = tasks.filter(t => isBad(t.state)).map(t => ({ id: t.id, state: t.state, exitCode: t.exitCode }))
413  const cpuEff = cpuHeld > 0 ? cpuUsed / cpuHeld : undefined
414  const memEff = reqMemMb > 0 && Number.isFinite(maxRssMb) ? maxRssMb / reqMemMb : undefined
415  const timeEff = limit > 0 && Number.isFinite(elapsed) ? elapsed / limit : undefined
416  return {
417    id,
418    name: first.name,
419    user: first.user || undefined,
420    state: states.size === 1 ? first.state : 'MIXED',
421    counts,
422    tasks: n,
423    isArray: tasks.some(t => t.id.includes('_')),
424    failed: failed.slice(0, 10),
425    exitCode: first.exitCode,
426    elapsed: formatDuration(elapsed),
427    elapsedS: elapsed,
428    limit: formatDuration(limit),
429    cpus: first.cpus,
430    gpus: first.gpus,
431    reqMem: formatMem(reqMemMb),
432    maxRss: Number.isFinite(maxRssMb) ? formatMem(maxRssMb) : '?',
433    cpuEff,
434    memEff,
435    timeEff,
436    advice: advise({ states, elapsed, limit, cpus: first.cpus, cpuEff, reqMemMb, maxRssMb, memEff, timeEff }),
437    endedAt,
438  }
439}
440
441/** Reports for several jobs from one sacct call; a job sacct has not finished recording is left out. */
442export async function fetchReports(run: Run, ids: readonly string[], now: number): Promise<Map<string, JobReport>> {
443  const out = new Map<string, JobReport>()
444  if (!ids.length) return out
445  // Text sacct, not --json: --json omits mem-used on this cluster.
446  const r = await run(['sacct', '-j', ids.join(','), '-n', '-P', '-o', SACCT_FIELDS])
447  if (r.exitCode !== 0) return out
448  const rows = parseSacct(r.stdout)
449  for (const id of ids) {
450    const report = buildReport(parentId(id), rows, now)
451    if (report && Object.keys(report.counts).every(s => TERMINAL_STATES.has(s))) out.set(report.id, report)
452  }
453  return out
454}
455
456export async function fetchReport(run: Run, id: string, now: number): Promise<JobReport | null> {
457  const r = await run(['sacct', '-j', id, '-n', '-P', '-o', SACCT_FIELDS])
458  if (r.exitCode !== 0) return null
459  return buildReport(id, parseSacct(r.stdout), now)
460}
461
462export async function tailFile(run: Run, path: string, lines: number): Promise<string[]> {
463  if (!path || path === '(null)') return []
464  const r = await run(['tail', '-n', String(lines), path])
465  if (r.exitCode !== 0) return [`(cannot read ${path}: ${r.stderr.trim().split('\n')[0] ?? 'error'})`]
466  return r.stdout.replace(/\r/g, '').split('\n').filter((l, i, a) => i < a.length - 1 || l !== '')
467}
468
469export const TERMINAL_STATES = new Set([
470  'COMPLETED',
471  'FAILED',
472  'CANCELLED',
473  'TIMEOUT',
474  'OUT_OF_MEMORY',
475  'NODE_FAIL',
476  'PREEMPTED',
477  'BOOT_FAIL',
478  'DEADLINE',
479])
480
481export function isBad(state: string): boolean {
482  return state !== 'COMPLETED' && TERMINAL_STATES.has(state)
483}
484
485export function pct(x: number | undefined): string {
486  return x === undefined ? '–' : `${Math.round(x * 100)}%`
487}
488
489/** "85353,85354,85355,85360" -> "85353–85355, 85360" */
490export function idRanges(ids: readonly string[]): string {
491  const nums = [...new Set(ids)].map(Number).sort((a, b) => a - b)
492  const out: string[] = []
493  for (let i = 0; i < nums.length; ) {
494    let j = i
495    while (j + 1 < nums.length && nums[j + 1] === nums[j]! + 1) j++
496    out.push(j > i ? `${nums[i]}–${nums[j]}` : String(nums[i]))
497    i = j + 1
498  }
499  return out.join(', ')
500}
501
502function countsText(counts: Record<string, number>): string {
503  return Object.entries(counts)
504    .sort((a, b) => b[1] - a[1])
505    .map(([s, n]) => `${n} ${s}`)
506    .join(', ')
507}
508
509function useText(r: JobReport): string {
510  // Under two minutes the samples say nothing worth the tokens.
511  if (!(r.elapsedS >= 120)) return ''
512  return [
513    r.memEff !== undefined ? `peak mem ${r.maxRss}/${r.reqMem}` : '',
514    r.cpuEff !== undefined && r.cpus ? `CPU ${pct(r.cpuEff)} of ${r.cpus}` : '',
515    r.timeEff !== undefined ? `${pct(r.timeEff)} of ${r.limit} limit` : '',
516  ]
517    .filter(Boolean)
518    .join(' · ')
519}
520
521/** One line for one job: `job 85353 "train" COMPLETED in 12m · peak mem 3G/16G · ...` */
522export function reportLine(r: JobReport): string {
523  const what = r.isArray ? `array ${r.id} "${r.name}" (${r.tasks} tasks: ${countsText(r.counts)})` : `job ${r.id} "${r.name}" ${r.state}`
524  const exit = !r.isArray && isBad(r.state) ? ` exit ${r.exitCode}` : ''
525  const use = useText(r)
526  return `${what}${exit} ${r.isArray ? 'longest' : 'in'} ${r.elapsed}${use ? ` · ${use}` : ''}`
527}
528
529export type FailedLog = { id: string; path: string }
530
531/**
532 * The message for a set of jobs that have all ended: one line per job up to
533 * a few, then counts; failures with their log; advice not already given.
534 */
535export function endMessage(reports: readonly JobReport[], logs: readonly FailedLog[], seenAdvice: Set<string>): string {
536  const lines: string[] = []
537  const bad = reports.filter(r => r.failed.length > 0)
538  if (reports.length <= 3) {
539    lines.push(`[sprc] Ended: ${reports.map(reportLine).join('\n  ')}`)
540  } else {
541    const counts: Record<string, number> = {}
542    for (const r of reports) for (const [s, n] of Object.entries(r.counts)) counts[s] = (counts[s] ?? 0) + n
543    const longest = Math.max(...reports.map(r => r.elapsedS).filter(Number.isFinite))
544    lines.push(`[sprc] ${reports.length} jobs ended (${idRanges(reports.map(r => r.id))}): ${countsText(counts)}; longest ${formatDuration(longest)}.`)
545    for (const r of bad.slice(0, 5)) lines.push(`  ${reportLine(r)}`)
546    if (bad.length > 5) lines.push(`  … ${bad.length - 5} more with failures: ${idRanges(bad.slice(5).map(r => r.id))}`)
547  }
548  const failedTasks = bad.flatMap(r => r.failed)
549  if (failedTasks.length) {
550    const shown = failedTasks.slice(0, 5).map(t => {
551      const log = logs.find(l => l.id === t.id || l.id === parentId(t.id))
552      return `${t.id} ${t.state} exit ${t.exitCode}${log ? ` log ${log.path}` : ''}`
553    })
554    lines.push(`  Failed: ${shown.join('; ')}${failedTasks.length > 5 ? `; +${failedTasks.length - 5} more` : ''}`)
555  }
556  const advice = [...new Set(reports.flatMap(r => r.advice))].filter(a => !seenAdvice.has(a))
557  for (const a of advice) seenAdvice.add(a)
558  if (advice.length) lines.push(`  Right-sizing: ${advice.slice(0, 3).join('; ')}`)
559  return lines.join('\n')
560}
561
types/index.d.ts 107 lines
1export type NodeRow = {
2  name: string
3  state: string
4  gpus: number
5  gpusUsed: number
6  cpusAlloc: number
7  cpusTotal: number
8  memAllocMb: number
9  memTotalMb: number
10}
11
12export type JobRow = {
13  /** As squeue prints it: "123", "123_4" (array task), "123_[5-200]" (pending tasks). */
14  id: string
15  user: string
16  name: string
17  /** Compact state: R, PD, CG, ... */
18  state: string
19  elapsed: string
20  limit: string
21  gpus: number
22  cpus: number
23  mem: string
24  reason: string
25  qos: string
26  partition: string
27  nodes: string
28  /** Expected (pending) or actual (running) start, ISO, or N/A. */
29  start: string
30}
31
32export type Snapshot = {
33  at: number
34  error?: string
35  nodes: NodeRow[]
36  mine: JobRow[]
37  others: { running: number; pending: number; gpusRunning: number; gpusPending: number }
38}
39
40/** One ended job, or one ended array job summarised over its tasks. */
41export type JobReport = {
42  /** The job id; for an array, the array's own id. */
43  id: string
44  name: string
45  user?: string
46  /** The state every task ended in, or MIXED. */
47  state: string
48  /** Tasks per end state; a plain job counts as one task. */
49  counts: Record<string, number>
50  tasks: number
51  isArray: boolean
52  /** Tasks that did not complete (at most 10). */
53  failed: { id: string; state: string; exitCode: string }[]
54  exitCode: string
55  /** Longest task, formatted, and in seconds (NaN when unknown). */
56  elapsed: string
57  elapsedS: number
58  limit: string
59  cpus: number
60  gpus: number
61  reqMem: string
62  maxRss: string
63  /** Fractions 0..1, absent where Slurm had nothing to measure. */
64  cpuEff?: number
65  memEff?: number
66  timeEff?: number
67  advice: string[]
68  endedAt: number
69}
70
71export type Followed = {
72  /** The job id (an array's own id for a whole array). */
73  id: string
74  /** The loop that submitted or followed it: a subagent's or teammate's id; absent for the main conversation. */
75  owner?: string
76  /** Jobs followed by one loop during one main-conversation turn share a group and are reported together. */
77  group: string
78  origin: 'sbatch' | 'tool' | 'person'
79  /** When following began; a snapshot taken before then cannot say it ended. */
80  since: number
81  /** Seen running; a start toast was shown. */
82  started?: boolean
83  /** Left the queue; the report once sacct has it. */
84  gone?: number
85  report?: JobReport
86}
87
88/** A finished-jobs message waiting for its loop to be told. */
89export type Notice = {
90  owner?: string
91  text: string
92  /** When it was queued; a loop that has not picked it up by the next poll is messaged. */
93  at: number
94}
95
96declare module 'claude-code' {
97  interface PluginState {
98    'sprc-slurm-mods': {
99      snapshot: Snapshot | null
100      followed: Followed[]
101      finished: JobReport[]
102      outbox: Notice[]
103      isEnabled: boolean
104    }
105  }
106}
107