Skip to main content

greengate_runtime/
slot_cmd.rs

1//! `amont slot run` and `amont slots` (ADR-0014): the host slots for any
2//! command, and who holds them.
3//!
4//! `amont slot run [--weight N] [--max-wait S | --now] -- <cmd…>` waits for a
5//! slot, runs the command with `GREENHARNESS_HOST_SLOT=held`, passes its exit
6//! status through and frees the slot when the command exits. The wrapper
7//! alone holds the slot: its descriptors are close-on-exec, so a daemon the
8//! command leaves behind never keeps it. A wait ends, with exit 75 and nothing
9//! run, when the line makes no progress for 300 s or `--max-wait` runs out
10//! (default 90 s, under Claude Code's 120 s Bash timeout) (ADR-0022). `--now`
11//! skips the queue up front: the command runs at once, unqueued, journalled
12//! `now`.
13
14/// The holder name a `slot run` queues under, as `greengate slots` shows it.
15const SLOT_RUN_HOLDER: &str = concat!(crate::bin!(), " slot run");
16
17use crate::names::BIN;
18use std::ffi::OsString;
19use std::process::Command;
20use std::time::{Duration, Instant};
21
22/// Exit status for "the host stayed busy; nothing ran" (EX_TEMPFAIL).
23pub const BUSY_EXIT: i32 = 75;
24
25/// Exit status for "the slot queue failed after it was joined; nothing ran"
26/// (EX_IOERR): unlike a busy host, retrying the same command fails the same
27/// way.
28pub const QUEUE_FAILED_EXIT: i32 = 74;
29
30/// The default `--max-wait`: under Claude Code's 120 s Bash timeout, so a
31/// wrapped command is never killed while it is still queued.
32pub const DEFAULT_MAX_WAIT: Duration = Duration::from_secs(90);
33
34/// `amont slot <args>`.
35pub fn slot_command(args: &[OsString]) -> i32 {
36    let (own, cmd) = split_at_dashes(args);
37    match own.first().and_then(|a| a.to_str()) {
38        Some("run") => run(&own[1..], cmd),
39        Some("promote") => promote(&own[1..], cmd),
40        _ => {
41            eprintln!(
42                "{BIN}: usage: {BIN} slot run [--weight N] [--max-wait S | --now] -- <command…>"
43            );
44            eprintln!("       {BIN} slot promote <id> --reason <text> [--to N]");
45            2
46        }
47    }
48}
49
50/// `slot promote <id> --reason <text> [--to N]` (host-slot-admission t06;
51/// ADR-0022): move one of this session's waiting jobs ahead. Every message
52/// goes to stderr; the exit status carries the result: 0 moved, 1 refused or
53/// slots off, 2 usage, 74 an I/O failure, 75 the admission lock stayed held
54/// (nothing moved).
55fn promote(own: &[OsString], operands: &[OsString]) -> i32 {
56    let (id, reason, to) = match parse_promote(own, operands) {
57        Ok(parsed) => parsed,
58        Err(why) => {
59            eprintln!("{BIN}: slot promote: {why}");
60            eprintln!("  usage: {BIN} slot promote <id> --reason <text> [--to N]");
61            return 2;
62        }
63    };
64    let settings = crate::config::Settings::default();
65    let (sizing, _) = crate::host_slots::sizing_and_machine(&settings);
66    if sizing.is_none() || !greenharness_slots::SUPPORTED {
67        eprintln!("{BIN}: host slots are off here, so no job waits to be moved");
68        return 1;
69    }
70    // Read at the binary's edge: the crate reads no environment for it.
71    let session = greenharness_slots::session_id();
72    let request = greenharness_slots::Promote {
73        id: &id,
74        session: &session,
75        reason: &reason,
76        to,
77        tool: BIN,
78    };
79    let dir = greenharness_slots::dir();
80    let answer = greenharness_slots::promote_in_waiting(&dir, &request, || {
81        eprintln!("{BIN}: waiting for the admission lock…");
82    });
83    match answer {
84        Ok(Ok(moved)) => {
85            let jobs = if moved.passed == 1 { "job" } else { "jobs" };
86            eprintln!(
87                "moved {} from {} to {}, past {} {jobs}; {} of {} moves left in 24 h",
88                moved.id,
89                moved.from,
90                moved.to,
91                moved.passed,
92                moved.budget.saturating_sub(moved.used),
93                moved.budget
94            );
95            0
96        }
97        Ok(Err(refused)) => {
98            eprintln!(
99                "{BIN}: slot promote refused ({}): {}",
100                refused.limit(),
101                refused.describe()
102            );
103            for hint in refusal_hints(&refused, &id) {
104                eprintln!("  {hint}");
105            }
106            1
107        }
108        Err(greenharness_slots::PromoteError::LockBusy { waited }) => {
109            eprintln!(
110                "{BIN}: slot promote: the admission lock stayed held for {}s; nothing moved",
111                waited.as_secs()
112            );
113            let to_flag = if to > 0 {
114                format!(" --to {to}")
115            } else {
116                String::new()
117            };
118            eprintln!("  retry: {BIN} slot promote {id}{to_flag} --reason <text>");
119            BUSY_EXIT
120        }
121        Err(error) => {
122            eprintln!("{BIN}: slot promote: {error}");
123            QUEUE_FAILED_EXIT
124        }
125    }
126}
127
128/// What to do next after a refusal, beside its one line.
129fn refusal_hints(refused: &greenharness_slots::Refused, id: &str) -> Vec<String> {
130    use greenharness_slots::Refused;
131    match refused {
132        Refused::NoSession => vec![
133            "the session comes from CLAUDE_CODE_SESSION_ID, RELAIS_SESSION_ID or CLAUDE_SESSION_ID"
134                .to_string(),
135        ],
136        Refused::NoReason => vec![format!("{BIN} slot promote {id} --reason <text>")],
137        Refused::NotQueued { .. } | Refused::Ambiguous { .. } => {
138            vec![format!("see: {BIN} slots")]
139        }
140        Refused::AgeFloor {
141            furthest: Some(n), ..
142        } => vec![format!(
143            "try: {BIN} slot promote {id} --to {n} --reason <text>"
144        )],
145        _ => Vec::new(),
146    }
147}
148
149/// `<id> --reason <text> [--to N]`: flags as `--flag value` or
150/// `--flag=value`, in any order; `operands` are the words after `--`, taken
151/// as the job's id only (a flag there is not a flag).
152fn parse_promote(
153    own: &[OsString],
154    operands: &[OsString],
155) -> Result<(String, String, usize), String> {
156    let mut id = None;
157    let mut reason = None;
158    let mut to = 0;
159    let mut words = own.iter();
160    while let Some(word) = words.next() {
161        let word = word.to_str().ok_or("an argument is not valid UTF-8")?;
162        let (name, inline) = match word.split_once('=') {
163            Some((n, v)) if n.starts_with("--") => (n, Some(v.to_string())),
164            _ => (word, None),
165        };
166        let mut value = |flag: &str| -> Result<String, String> {
167            match inline.clone() {
168                Some(v) => Ok(v),
169                None => words
170                    .next()
171                    .and_then(|v| v.to_str())
172                    .map(str::to_string)
173                    .ok_or(format!("{flag} needs a value")),
174            }
175        };
176        match name {
177            "--reason" => reason = Some(value("--reason")?),
178            "--to" => {
179                to = value("--to")?
180                    .parse()
181                    .map_err(|_| "--to is a whole number from 0".to_string())?
182            }
183            flag if flag.starts_with('-') => return Err(format!("unknown argument {flag:?}")),
184            job if id.is_none() => id = Some(job.to_string()),
185            extra => return Err(format!("one job at a time, not also {extra:?}")),
186        }
187    }
188    for word in operands {
189        let job = word.to_str().ok_or("an argument is not valid UTF-8")?;
190        if id.is_some() {
191            return Err(format!("one job at a time, not also {job:?}"));
192        }
193        id = Some(job.to_string());
194    }
195    let id = id.ok_or("name the job to move: its id from `slots`")?;
196    let reason = reason
197        .filter(|r| !r.trim().is_empty())
198        .ok_or("--reason <text> is required: it is journalled with the move")?;
199    Ok((id, reason, to))
200}
201
202/// The arguments before `--`, and the command after it.
203pub fn split_at_dashes(args: &[OsString]) -> (&[OsString], &[OsString]) {
204    match args.iter().position(|a| a == "--") {
205        Some(i) => (&args[..i], &args[i + 1..]),
206        None => (args, &[]),
207    }
208}
209
210/// The flags `slot run` takes with a value. `--on-timeout` is read only to
211/// refuse `run` and warn on `exit` (ADR-0022).
212const VALUED: &[&str] = &["--weight", "--max-wait", "--on-timeout"];
213
214/// The flags `slot run` takes alone; given, their value is `"true"`.
215const SWITCHES: &[&str] = &["--now"];
216
217/// Read `own` (the words before `--`) into flag values, as `--flag value`
218/// or `--flag=value`, and switches alone. Anything else is a usage error.
219fn parse(own: &[OsString]) -> Result<Vec<(&'static str, String)>, String> {
220    let mut out = Vec::new();
221    let mut words = own.iter();
222    while let Some(word) = words.next() {
223        let word = word.to_str().ok_or("an argument is not valid UTF-8")?;
224        let (name, inline) = match word.split_once('=') {
225            Some((n, v)) => (n, Some(v.to_string())),
226            None => (word, None),
227        };
228        if let Some(switch) = SWITCHES.iter().find(|f| **f == name) {
229            if inline.is_some() {
230                return Err(format!("{switch} takes no value"));
231            }
232            out.push((*switch, "true".to_string()));
233            continue;
234        }
235        let Some(flag) = VALUED.iter().find(|f| **f == name) else {
236            return Err(format!("unknown argument {word:?}"));
237        };
238        let value = match inline {
239            Some(v) => v,
240            None => words
241                .next()
242                .and_then(|v| v.to_str())
243                .ok_or(format!("{flag} needs a value"))?
244                .to_string(),
245        };
246        out.push((*flag, value));
247    }
248    Ok(out)
249}
250
251fn value<'a>(flags: &'a [(&'static str, String)], flag: &str) -> Option<&'a str> {
252    flags
253        .iter()
254        .find(|(f, _)| *f == flag)
255        .map(|(_, v)| v.as_str())
256}
257
258/// How the command runs: inside a held slot, or with none.
259#[derive(Clone, Copy)]
260enum Launch {
261    /// A slot is held for it (here or by an ancestor): `GREENHARNESS_HOST_SLOT=held`.
262    Held,
263    /// No slot: off, unsupported, unavailable, or `--now`.
264    Unqueued,
265}
266
267fn run(own: &[OsString], cmd: &[OsString]) -> i32 {
268    let own = match parse(own) {
269        Ok(flags) => flags,
270        Err(why) => {
271            eprintln!("{BIN}: slot run: {why}");
272            return 2;
273        }
274    };
275    let own = own.as_slice();
276    let Some((program, rest)) = cmd.split_first() else {
277        eprintln!("{BIN}: `{BIN} slot run` needs a command after `--`");
278        return 2;
279    };
280    let weight = match value(own, "--weight").map(str::parse::<u32>) {
281        None => 1,
282        Some(Ok(n)) if n >= 1 => n,
283        Some(_) => {
284            eprintln!("{BIN}: --weight is a whole number from 1");
285            return 2;
286        }
287    };
288    let max_wait = match value(own, "--max-wait").map(str::parse::<u64>) {
289        None => DEFAULT_MAX_WAIT,
290        Some(Ok(s)) => Duration::from_secs(s),
291        Some(Err(_)) => {
292            eprintln!("{BIN}: --max-wait is a whole number of seconds");
293            return 2;
294        }
295    };
296    match value(own, "--on-timeout") {
297        None => {}
298        Some("exit") => {
299            eprintln!("{BIN}: --on-timeout exit is deprecated and will be removed; drop it")
300        }
301        Some("run") => {
302            eprintln!("{BIN}: --on-timeout was removed (ADR-0022): a wait that ends runs nothing");
303            eprintln!("  skip the queue up front: {BIN} slot run --now -- <cmd>");
304            return 2;
305        }
306        Some(other) => {
307            eprintln!(
308                "{BIN}: --on-timeout was removed (ADR-0022), and {other:?} was never a value"
309            );
310            return 2;
311        }
312    }
313    let now = value(own, "--now").is_some();
314    if now && value(own, "--max-wait").is_some() {
315        eprintln!("{BIN}: --now skips the queue, so --max-wait has nothing to bound");
316        return 2;
317    }
318    let label: String = std::iter::once(program)
319        .chain(rest.iter().take(2))
320        .map(|a| a.to_string_lossy().into_owned())
321        .collect::<Vec<_>>()
322        .join(" ");
323
324    // Already inside a slot (a wrapped command running this one): no second
325    // queue for the slot the parent holds.
326    let nested = std::env::var_os(greenharness_slots::HELD_ENV).is_some_and(|v| !v.is_empty());
327    let settings = crate::config::Settings::default();
328    let (sizing, machine) = crate::host_slots::sizing_and_machine(&settings);
329    let (Some(sizing), false, true) = (sizing, nested, greenharness_slots::SUPPORTED) else {
330        return spawn(
331            program,
332            rest,
333            if nested {
334                Launch::Held
335            } else {
336                Launch::Unqueued
337            },
338            None,
339        );
340    };
341    // The width this command may run at, held or not: a `--now` run happens
342    // when the host is busy, so it is bounded too.
343    let slot_cap = sizing.cap_for(machine.cores);
344    let jobs = greenharness_slots::parallelism(weight, machine.cores, slot_cap);
345
346    let dir = greenharness_slots::dir();
347    // Every line of this run names the cap and cores it was sized for.
348    let record = |waited: u128, outcome: &str, end: Option<greenharness_slots::WaitEnd>| {
349        greenharness_slots::record_wait_named(
350            &dir,
351            SLOT_RUN_HOLDER,
352            greenharness_slots::WaitContext {
353                cap: Some(slot_cap),
354                cores: Some(machine.cores),
355                end,
356                ..greenharness_slots::WaitContext::default()
357            },
358            weight,
359            Some(jobs),
360            waited,
361            outcome,
362        );
363    };
364    if now {
365        record(0, "now", None);
366        return spawn(program, rest, Launch::Unqueued, Some(jobs));
367    }
368    // Read at the binary's edge: the crate reads no environment for it.
369    let setting = std::env::var(greenharness_slots::STALL_ENV).ok();
370    let (window, warning) = greenharness_slots::Stall::window_from(setting.as_deref());
371    if let Some(warning) = warning {
372        eprintln!("{BIN}: warning: {warning}");
373    }
374    let started = Instant::now();
375    let waiter = match greenharness_slots::Waiter::new_in_on(
376        &dir,
377        sizing,
378        weight,
379        greenharness_slots::Holder::here(SLOT_RUN_HOLDER, &label),
380        machine,
381    ) {
382        Ok(w) => w,
383        Err(e) => {
384            eprintln!("{BIN}: host slots unavailable ({e}); running unqueued");
385            return spawn(program, rest, Launch::Unqueued, Some(jobs));
386        }
387    };
388    // The caller's deadline is hard (the Bash tool's 120 s); the crate does
389    // not apply a stall window as long as it.
390    let bounds = greenharness_slots::WaitBounds {
391        window: Some(window),
392        ceiling: max_wait,
393    };
394    let mut last_said: Option<Instant> = None;
395    let id = waiter.id().to_string();
396    let ended = greenharness_slots::wait_in_line(waiter, bounds, |queue| {
397        let due = last_said.map_or(true, |t| t.elapsed() >= Duration::from_secs(30));
398        if due && (!queue.holders.is_empty() || queue.unknown > 0) {
399            eprintln!("{BIN}: {}", crate::host_slots::behind(queue));
400            // The pointers once, not on every 30 s repeat.
401            if last_said.is_none() {
402                eprintln!("  see: {BIN} slots");
403                eprintln!("  id {id}; move ahead: {BIN} slot promote {id} --reason <text>");
404            }
405            last_said = Some(Instant::now());
406        }
407    });
408    let waited = started.elapsed().as_millis();
409    let lease = match ended {
410        Ok(lease) => lease,
411        Err(end) => {
412            record(waited, "timeout", Some(end.end()));
413            eprintln!("{BIN}: {}", end_message(&end, max_wait));
414            return match end {
415                // A broken queue is not a busy host: retrying the same
416                // command would fail the same way.
417                greenharness_slots::LineEnd::PollFailed { .. } => {
418                    eprintln!("  `{label}` did not run (exit {QUEUE_FAILED_EXIT})");
419                    QUEUE_FAILED_EXIT
420                }
421                greenharness_slots::LineEnd::Stalled { .. }
422                | greenharness_slots::LineEnd::Ceiling { .. } => {
423                    eprintln!("  `{label}` did not run (exit {BUSY_EXIT}); retry later, or pass --now to skip the queue");
424                    BUSY_EXIT
425                }
426            };
427        }
428    };
429    record(waited, "admitted", None);
430    let code = spawn(program, rest, Launch::Held, Some(jobs));
431    drop(lease);
432    code
433}
434
435/// Why a `slot run` wait ended, in one line under 80 columns.
436fn end_message(end: &greenharness_slots::LineEnd, max_wait: Duration) -> String {
437    match end {
438        greenharness_slots::LineEnd::Stalled { window, .. } => {
439            format!(
440                "no progress in the host slot line for {}s",
441                window.as_secs()
442            )
443        }
444        greenharness_slots::LineEnd::Ceiling { .. } => {
445            format!("no host slot within --max-wait {}s", max_wait.as_secs())
446        }
447        greenharness_slots::LineEnd::PollFailed { error } => {
448            format!("the host slot queue failed while queued: {error}")
449        }
450    }
451}
452
453/// Run the command, inheriting stdio, and pass its exit status through: the
454/// code, or 128 + the signal that ended it. `jobs` bounds its width
455/// (`greenharness_slots::bound_width`); `None` (slots off, unsupported, or nested
456/// under a holder whose own bounds it inherits) sets nothing.
457fn spawn(program: &OsString, rest: &[OsString], launch: Launch, jobs: Option<u32>) -> i32 {
458    let mut cmd = Command::new(program);
459    cmd.args(rest);
460    if let Some(jobs) = jobs {
461        greenharness_slots::bound_width(&mut cmd, jobs);
462    }
463    match launch {
464        Launch::Held => {
465            cmd.env(greenharness_slots::HELD_ENV, "held");
466        }
467        Launch::Unqueued => {}
468    }
469    match cmd.status() {
470        Ok(status) => exit_code(status),
471        Err(e) => {
472            eprintln!("{BIN}: cannot run {}: {e}", program.to_string_lossy());
473            127
474        }
475    }
476}
477
478fn exit_code(status: std::process::ExitStatus) -> i32 {
479    if let Some(code) = status.code() {
480        return code;
481    }
482    #[cfg(unix)]
483    {
484        use std::os::unix::process::ExitStatusExt;
485        if let Some(sig) = status.signal() {
486            return 128 + sig;
487        }
488    }
489    1
490}
491
492/// `amont slots [--json]`.
493/// `6 cores, 12 threads`: the threads only where they differ from the cores
494/// (SMT), and a short tag when the count did not come from plain detection,
495/// so the `slots` header stays inside 80 columns. `doctor` names the key.
496pub fn cores_phrase(cores: u32, threads: u32, source: greenharness_slots::host::Source) -> String {
497    use greenharness_slots::host::Source;
498    let mut phrase = format!("{cores} cores");
499    if threads != cores {
500        phrase.push_str(&format!(", {threads} threads"));
501    }
502    let tag = match source {
503        Source::Env => Some("env"),
504        Source::Global | Source::System => Some("git"),
505        Source::LogicalFallback => Some("logical"),
506        Source::LimitedByAffinity => Some("affinity"),
507        Source::Detected => None,
508        // `Source` is non_exhaustive: a new variant needs a tag here.
509        _ => None,
510    };
511    if let Some(tag) = tag {
512        phrase.push_str(&format!(" ({tag})"));
513    }
514    phrase
515}
516
517/// Where a host key's value came from, in words a person can act on: the
518/// variable or the `git config` scope and key, else the detection outcome.
519fn source_label(source: greenharness_slots::host::Source, key: &str, env: &str) -> String {
520    use greenharness_slots::host::Source;
521    match source {
522        Source::Env => env.to_string(),
523        Source::Global => format!("git config --global {key}"),
524        Source::System => format!("git config --system {key}"),
525        other => other.name().to_string(),
526    }
527}
528
529/// The host sizing lines `doctor` prints, one per key so each fits in 80
530/// columns: the core count and the slot count, each with the source that set
531/// it. Any warning about either key is printed separately, once, by
532/// `host_slots::host_sizing`.
533pub fn doctor_line() -> String {
534    use greenharness_slots::host::{CORES_ENV, CORES_KEY, SLOTS_ENV, SLOTS_KEY};
535    let settings = crate::config::Settings::default();
536    let host = crate::host_slots::host_sizing(&settings);
537    let slots = match host.slots.value {
538        None => "off".to_string(),
539        Some(greenharness_slots::Sizing::Auto) => "auto".to_string(),
540        Some(greenharness_slots::Sizing::Fixed(n)) => n.to_string(),
541    };
542    format!(
543        "host cores: {}, {} threads ({})\nhost slots: {slots} ({})",
544        host.cores.value,
545        greenharness_slots::logical_cores(),
546        source_label(host.cores.source, CORES_KEY, CORES_ENV),
547        source_label(host.slots.source, SLOTS_KEY, SLOTS_ENV),
548    )
549}
550
551pub fn slots_command(args: &[OsString]) -> i32 {
552    if let Some(bad) = args.iter().find(|a| *a != "--json") {
553        eprintln!("{BIN}: slots: unknown argument {:?}", bad.to_string_lossy());
554        return 2;
555    }
556    let json = !args.is_empty();
557    let settings = crate::config::Settings::default();
558    let host = crate::host_slots::host_sizing(&settings);
559    let machine = greenharness_slots::Machine {
560        cores: host.cores.value.max(1),
561    };
562    // Additive fields: the core count the slots are sized from, and its source.
563    let cores_json = format!(
564        "\"cores\":{},\"cores_source\":\"{}\"",
565        machine.cores,
566        host.cores.source.token()
567    );
568    let Some(sizing) = host.slots.value else {
569        if json {
570            println!(
571                "{{\"cap\":0,{cores_json},\"held\":0,\"holders\":[],\"unknown\":0,\"waiting\":0,\"queue\":[]}}"
572            );
573        } else {
574            let by = match host.slots.source {
575                greenharness_slots::host::Source::Env => {
576                    format!("{}=0", greenharness_slots::host::SLOTS_ENV)
577                }
578                _ => format!("{} 0", greenharness_slots::host::SLOTS_KEY),
579            };
580            println!("host slots are off ({by})");
581        }
582        return 0;
583    };
584    let status = match greenharness_slots::status_in_on(&greenharness_slots::dir(), sizing, machine)
585    {
586        Ok(s) => s,
587        Err(e) => {
588            eprintln!("{BIN}: cannot read the host slots: {e}");
589            return 1;
590        }
591    };
592    let held = status.holders.len() + status.unknown;
593    // The queue is an observation beside the count: a listing that cannot be
594    // read shows no lines rather than failing the command.
595    let queue = match greenharness_slots::queue_in(&greenharness_slots::dir()) {
596        Ok(queue) => queue,
597        Err(e) => {
598            eprintln!("{BIN}: slots: cannot list the queue: {e}");
599            Vec::new()
600        }
601    };
602    let now = greenharness_slots::now_ms();
603    let mode = match sizing {
604        greenharness_slots::Sizing::Auto => format!(
605            "auto: load {}, {}",
606            greenharness_slots::load1().map_or("?".to_string(), |l| format!("{l:.1}")),
607            cores_phrase(
608                machine.cores,
609                greenharness_slots::logical_cores(),
610                host.cores.source
611            )
612        ),
613        greenharness_slots::Sizing::Fixed(n) => format!("greengate.hostSlots {n}"),
614    };
615    if json {
616        let holders: Vec<String> = status
617            .holders
618            .iter()
619            .map(greenharness_slots::Holder::to_json)
620            .collect();
621        let queue: Vec<String> = queue.iter().map(|job| queue_json(job, now)).collect();
622        println!(
623            "{{\"cap\":{},{cores_json},\"held\":{held},\"holders\":[{}],\"unknown\":{},\"waiting\":{},\"queue\":[{}]}}",
624            status.cap,
625            holders.join(","),
626            status.unknown,
627            status.waiting,
628            queue.join(",")
629        );
630        return 0;
631    }
632    println!("host slots: {held} of {} held ({mode})", status.cap);
633    for h in &status.holders {
634        let jobs = h.jobs.map_or("-".to_string(), |j| j.to_string());
635        println!(
636            "  {}  pid {}  jobs {jobs}  session {}",
637            h.describe(now),
638            h.pid,
639            h.short_session()
640        );
641    }
642    if status.unknown > 0 {
643        println!("  {} unknown (old client)", status.unknown);
644    }
645    println!("waiting: {}", status.waiting);
646    for job in &queue {
647        println!("{}", queue_line(job, now));
648    }
649    0
650}
651
652/// The widest a `slots` line may be.
653const COLUMNS: usize = 80;
654
655fn queue_line(job: &greenharness_slots::QueuedJob, now_ms: u128) -> String {
656    match job.state {
657        greenharness_slots::JobState::Waiting { position } => line_of(
658            Some(position),
659            &job.id,
660            job.holder.as_ref(),
661            Some(now_ms.saturating_sub(job.joined_ms)),
662        ),
663        greenharness_slots::JobState::Gone => line_of(None, &job.id, job.holder.as_ref(), None),
664    }
665}
666
667/// One queued job from its parts; `waited_ms` is `None` for a gone job. The
668/// position is `-` for a gone job; a live job's is the `--to` a promotion uses.
669fn line_of(
670    position: Option<usize>,
671    id: &str,
672    holder: Option<&greenharness_slots::Holder>,
673    waited_ms: Option<u128>,
674) -> String {
675    let position = position.map_or("-".to_string(), |p| p.to_string());
676    let (session, what) = match (holder, waited_ms) {
677        (_, None) => ("-", "gone".to_string()),
678        (None, Some(_)) => ("-", "old client".to_string()),
679        (Some(h), Some(_)) => {
680            let repo = std::path::Path::new(&h.repo)
681                .file_name()
682                .map(|n| n.to_string_lossy().into_owned())
683                .unwrap_or_else(|| h.repo.clone());
684            (
685                h.short_session(),
686                format!("{}: {} ({repo})", h.tool, h.command),
687            )
688        }
689    };
690    let wait = waited_ms.map_or("-".to_string(), greenharness_slots::wait_text);
691    let head = format!("  {position:>2}  {id}  {wait}  {session}  ");
692    let room = COLUMNS.saturating_sub(head.chars().count());
693    let what = if what.chars().count() > room {
694        let cut: String = what.chars().take(room.saturating_sub(1)).collect();
695        format!("{cut}…")
696    } else {
697        what
698    };
699    format!("{head}{what}")
700}
701
702/// One queued job for `slots --json`: `position`, `waited_ms` and `gone` follow
703/// its state; `session` to `repo` are `null` for an older client's ticket.
704fn queue_json(job: &greenharness_slots::QueuedJob, now_ms: u128) -> String {
705    use crate::json::escape;
706    let text = |s: Option<&str>| s.map_or("null".to_string(), |s| format!("\"{}\"", escape(s)));
707    let h = job.holder.as_ref();
708    let (position, waited, gone) = match job.state {
709        greenharness_slots::JobState::Waiting { position } => (
710            position.to_string(),
711            now_ms.saturating_sub(job.joined_ms).to_string(),
712            false,
713        ),
714        greenharness_slots::JobState::Gone => ("null".to_string(), "null".to_string(), true),
715    };
716    format!(
717        "{{\"id\":\"{}\",\"position\":{position},\"waited_ms\":{waited},\"session\":{},\"tool\":{},\"command\":{},\"repo\":{},\"gone\":{gone}}}",
718        escape(&job.id),
719        text(h.map(|h| h.session.as_str()).filter(|s| !s.is_empty())),
720        text(h.map(|h| h.tool.as_str())),
721        text(h.map(|h| h.command.as_str())),
722        text(h.map(|h| h.repo.as_str())),
723    )
724}
725
726#[cfg(test)]
727mod tests {
728    use super::*;
729
730    fn os(v: &[&str]) -> Vec<OsString> {
731        v.iter().map(OsString::from).collect()
732    }
733
734    #[test]
735    fn the_cores_phrase_names_threads_and_overrides_only_when_they_matter() {
736        use greenharness_slots::host::Source;
737        assert_eq!(cores_phrase(6, 12, Source::Detected), "6 cores, 12 threads");
738        assert_eq!(cores_phrase(10, 10, Source::Detected), "10 cores");
739        assert_eq!(
740            cores_phrase(4, 12, Source::Env),
741            "4 cores, 12 threads (env)"
742        );
743        assert_eq!(
744            cores_phrase(4, 12, Source::Global),
745            "4 cores, 12 threads (git)"
746        );
747        assert_eq!(
748            cores_phrase(8, 8, Source::LogicalFallback),
749            "8 cores (logical)"
750        );
751        // A large host with every slot held, a heavy load and the longest tag
752        // still fits in 80 columns.
753        let header = format!(
754            "host slots: 64 of 64 held (auto: load 99.9, {})",
755            cores_phrase(128, 256, Source::LimitedByAffinity)
756        );
757        assert!(header.len() <= 80, "{} columns: {header}", header.len());
758    }
759
760    /// A queue line stays within 80 columns with a 7-digit pid and a
761    /// 200-character command, and keeps its leading fields whole.
762    #[test]
763    fn a_queue_line_fits_80_columns() {
764        let holder = greenharness_slots::Holder {
765            pid: 4_194_303,
766            tool: "greengate slot run".to_string(),
767            repo: "/Users/x/Developer/Perso/a-rather-long-worktree-name".to_string(),
768            command: "c".repeat(200),
769            session: "0b1c2d3e-aaaa-bbbb".to_string(),
770            started_ms: 0,
771            jobs: Some(2),
772        };
773        let line = line_of(Some(12), "4194303-17", Some(&holder), Some(3_900_000));
774        assert!(line.chars().count() <= COLUMNS, "{line}");
775        assert!(
776            line.starts_with("  12  4194303-17  1h05m  0b1c2d3e  greengate slot run: c"),
777            "{line}"
778        );
779        assert!(line.ends_with('…'), "{line}");
780        assert_eq!(line_of(None, "1-0", None, None), "   -  1-0  -  -  gone");
781        assert_eq!(
782            line_of(Some(0), "1-0", None, Some(0)),
783            "   0  1-0  <1m  -  old client"
784        );
785    }
786
787    #[test]
788    fn promote_takes_one_job_a_reason_and_an_optional_place() {
789        let (id, reason, to) = parse_promote(
790            &os(&["123-4", "--reason", "the person waits", "--to=2"]),
791            &[],
792        )
793        .unwrap();
794        assert_eq!(
795            (id.as_str(), reason.as_str(), to),
796            ("123-4", "the person waits", 2)
797        );
798        assert_eq!(
799            parse_promote(&os(&["--reason=r", "9-0"]), &[]).unwrap().2,
800            0
801        );
802        assert!(parse_promote(&os(&["9-0"]), &[])
803            .unwrap_err()
804            .contains("--reason"));
805        assert!(parse_promote(&os(&["9-0", "--reason", " "]), &[])
806            .unwrap_err()
807            .contains("--reason"));
808        assert!(parse_promote(&os(&["--reason", "r"]), &[])
809            .unwrap_err()
810            .contains("name the job"));
811        assert!(parse_promote(&os(&["9-0", "8-0", "--reason", "r"]), &[])
812            .unwrap_err()
813            .contains("one job"));
814        assert!(
815            parse_promote(&os(&["9-0", "--reason", "r", "--to", "x"]), &[])
816                .unwrap_err()
817                .contains("--to")
818        );
819        assert!(parse_promote(&os(&["9-0", "--why", "r"]), &[])
820            .unwrap_err()
821            .contains("unknown"));
822    }
823
824    #[test]
825    fn flags_take_a_separate_or_an_inline_value_and_nothing_else() {
826        let flags = parse(&os(&["--weight", "2", "--on-timeout=run"])).unwrap();
827        assert_eq!(value(&flags, "--weight"), Some("2"));
828        assert_eq!(value(&flags, "--on-timeout"), Some("run"));
829        assert!(parse(&os(&["--wieght", "2"]))
830            .unwrap_err()
831            .contains("unknown"));
832        assert!(parse(&os(&["extra"])).unwrap_err().contains("unknown"));
833        assert!(parse(&os(&["--max-wait"]))
834            .unwrap_err()
835            .contains("needs a value"));
836    }
837
838    #[test]
839    fn the_command_is_everything_after_the_first_dashes() {
840        let args = os(&[
841            "run",
842            "--weight",
843            "2",
844            "--",
845            "cargo",
846            "test",
847            "--",
848            "--nocapture",
849        ]);
850        let (own, cmd) = split_at_dashes(&args);
851        assert_eq!(own, &os(&["run", "--weight", "2"])[..]);
852        assert_eq!(cmd, &os(&["cargo", "test", "--", "--nocapture"])[..]);
853    }
854}