calmrun 0.1.0

A machine-wide queue for heavy commands, so parallel coding agents and terminals don't freeze the computer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! Command analysis: where the program is in a command line, what to call the job, which
//! hints and keys apply, and which commands are refused.
//!
//! Detection looks only at the command position (after env assignments and launchers such as
//! `npx` or `pnpm exec`), so `git commit -m "fix vitest"` is not mistaken for a vitest run.
//! What counts as heavy lives in [`crate::kinds`].

use crate::config::KindConfig;
use crate::kinds::{self, first_non_flag, Hint, KeyRule, Workers};
use crate::shell::{is_shell_string, split_segments, tokenize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Result of analysing one command.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Detected {
    /// Heavy kind, or `None` for a command calmrun does not know.
    pub kind: Option<String>,
    /// Tool + subcommand only, never arguments.
    pub label: String,
    /// Normalised tool name (basename without extension).
    pub tool: String,
}

impl Detected {
    /// The kind, or `other` for an unknown command.
    pub fn kind_name(&self) -> &str {
        self.kind.as_deref().unwrap_or("other")
    }
}

/// Basename, lowercased, without .cmd/.bat/.exe/.ps1/.js-style extensions and without a
/// package version (`tsc@5`, `@scope/pkg@1` -> `tsc`, `pkg`).
pub fn tool_name(word: &str) -> String {
    const EXTENSIONS: &[&str] = &[".cmd", ".bat", ".exe", ".ps1", ".js", ".mjs", ".cjs"];
    let base = word
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(word)
        .to_ascii_lowercase();
    // A package spec such as `tsc@5` or `@scope/pkg@1` (the scope is already cut off above).
    let base = match base.rfind('@') {
        Some(at) if at > 0 => base[..at].to_string(),
        _ => base,
    };
    EXTENSIONS
        .iter()
        .find_map(|ext| base.strip_suffix(ext).filter(|s| !s.is_empty()))
        .map(str::to_string)
        .unwrap_or(base)
}

fn is_assignment(w: &str) -> bool {
    w.split_once('=').is_some_and(|(name, _)| {
        !name.is_empty()
            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
            && !name.starts_with(|c: char| c.is_ascii_digit())
    })
}

/// Words that run the next word as the command (`time npx vitest`).
const PREFIX_WRAPPERS: &[&str] = &[
    "env",
    "time",
    "command",
    "nohup",
    "cross-env",
    "call",
    "&",
    "exec",
];
/// Package bins that `pnpm <bin>` / `yarn <bin>` run directly.
const JS_BINS: &[&str] = &[
    "vitest",
    "jest",
    "tsc",
    "vue-tsc",
    "tsgo",
    "eslint",
    "oxlint",
    "biome",
    "playwright",
    "cypress",
    "puppeteer",
    "vite",
    "next",
    "ng",
    "webpack",
    "rollup",
    "esbuild",
];
/// Launchers whose flags take a value (`npx -p pkg`).
const PACKAGE_FLAGS: &[&str] = &["-p", "--package"];

/// A command split at its command position.
#[derive(Debug, Clone, PartialEq)]
pub struct Parsed {
    pub launcher: Vec<String>,
    pub tool: String,
    pub rest: Vec<String>,
    /// Index of the first word after env assignments and wrappers such as `time` or `nohup`
    /// (where `calmrun --` can be inserted).
    pub start: usize,
}

fn skip_flags(words: &[String], mut i: usize, value_flags: &[&str]) -> usize {
    while i < words.len() && words[i].starts_with('-') {
        if value_flags.contains(&words[i].as_str()) {
            i += 1;
        }
        i += 1;
    }
    i
}

/// Index of the first word after env assignments and wrappers.
fn command_start(words: &[String]) -> Option<usize> {
    let mut i = 0;
    loop {
        let w = words.get(i)?;
        if is_assignment(w) {
            i += 1;
            continue;
        }
        let t = tool_name(w);
        if PREFIX_WRAPPERS.contains(&t.as_str()) {
            i += 1;
            while i < words.len() && (words[i].starts_with('-') || is_assignment(&words[i])) {
                i += 1;
            }
        } else if t == "nice" {
            i = skip_flags(words, i + 1, &["-n"]);
        } else {
            return Some(i);
        }
    }
}

fn looks_like_script(w: &str) -> bool {
    [".js", ".mjs", ".cjs", ".ts"].iter().any(|e| w.ends_with(e)) && (w.contains('/') || w.contains('\\'))
}

/// Where the tool is after a launcher at `i`: (launcher words, tool index). `None` means the
/// word at `i` is itself the tool.
fn launcher_at(words: &[String], i: usize) -> Option<(Vec<String>, usize)> {
    let first = tool_name(&words[i]);
    let next = words.get(i + 1).map(|s| s.to_ascii_lowercase());
    match (first.as_str(), next.as_deref()) {
        ("npx" | "pnpx" | "bunx", _) => Some((vec![first.clone()], skip_flags(words, i + 1, PACKAGE_FLAGS))),
        ("pnpm" | "yarn" | "npm", Some(sub @ ("exec" | "dlx" | "x"))) | ("bun", Some(sub @ "x")) => {
            let j = skip_flags(words, i + 2, PACKAGE_FLAGS);
            let j = if words.get(j).map(String::as_str) == Some("--") {
                j + 1
            } else {
                j
            };
            Some((vec![first.clone(), sub.to_string()], j))
        }
        ("pnpm" | "yarn", Some(n)) if JS_BINS.contains(&n) => Some((vec![first.clone()], i + 1)),
        ("python" | "python3" | "py", _) => {
            let m = words[i + 1..]
                .iter()
                .take_while(|w| w.starts_with('-'))
                .position(|w| w == "-m")?;
            Some((vec![first.clone(), "-m".to_string()], i + 1 + m + 1))
        }
        ("node" | "bun" | "deno", Some(n)) if looks_like_script(n) => Some((vec![first.clone()], i + 1)),
        _ => None,
    }
}

/// Find the program in a list of words.
pub fn parse(words: &[String]) -> Option<Parsed> {
    let start = command_start(words)?;
    let first = tool_name(&words[start]);
    let next = words.get(start + 1).map(|s| s.to_ascii_lowercase());
    if matches!(first.as_str(), "uv" | "poetry" | "pipenv" | "pdm" | "hatch")
        && next.as_deref() == Some("run")
    {
        let inner = parse(&words[start + 2..])?;
        let mut launcher = vec![first, "run".to_string()];
        launcher.extend(inner.launcher);
        return Some(Parsed {
            launcher,
            tool: inner.tool,
            rest: inner.rest,
            start,
        });
    }
    match launcher_at(words, start) {
        Some((launcher, idx)) if idx < words.len() => Some(Parsed {
            launcher,
            tool: tool_name(&words[idx]),
            rest: words[idx + 1..].to_vec(),
            start,
        }),
        // A bare launcher such as `npx --version`, or a plain tool.
        _ => Some(Parsed {
            launcher: Vec::new(),
            tool: first,
            rest: words[start + 1..].to_vec(),
            start,
        }),
    }
}

/// Tools whose first plain word is a subcommand worth showing in labels.
const SUB_TOOLS: &[&str] = &[
    "cargo",
    "go",
    "docker",
    "docker-compose",
    "npm",
    "pnpm",
    "yarn",
    "bun",
    "flutter",
    "dotnet",
    "gradle",
    "gradlew",
    "mvn",
    "mvnw",
    "vite",
    "next",
    "ng",
    "git",
    "deno",
    "make",
    "playwright",
];
const VITEST_SUBS: &[&str] = &["run", "watch", "bench", "dev", "related", "list"];
/// Longest word shown in a label; longer ones are likely arguments, not subcommands.
const LABEL_WORD_MAX: usize = 24;

fn safe_word(w: &str) -> bool {
    let mut chars = w.chars();
    matches!(chars.next(), Some(c) if c.is_ascii_lowercase())
        && w.len() <= LABEL_WORD_MAX
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | ':' | '_'))
}

/// Label: launcher + tool + subcommand (two words for `npm run x` / `docker compose up`).
fn label_of(p: &Parsed) -> String {
    let mut parts = p.launcher.clone();
    parts.push(p.tool.clone());
    let sub = first_non_flag(&p.rest).unwrap_or("");
    let allowed = (SUB_TOOLS.contains(&p.tool.as_str()) && safe_word(sub))
        || (p.tool == "vitest" && VITEST_SUBS.contains(&sub));
    if allowed {
        parts.push(sub.to_string());
        let second = p
            .rest
            .iter()
            .skip_while(|w| w.as_str() != sub)
            .nth(1)
            .map(String::as_str);
        let two_word = matches!(
            (p.tool.as_str(), sub),
            ("npm" | "pnpm" | "yarn" | "bun", "run" | "run-script") | ("docker", "compose" | "buildx")
        );
        if let Some(s) = second.filter(|s| two_word && safe_word(s)) {
            parts.push(s.to_string());
        }
    }
    parts.join(" ")
}

/// Analyse a list of argv words (one segment).
pub fn detect_words(words: &[String], kinds: &BTreeMap<String, KindConfig>) -> Detected {
    match parse(words) {
        Some(p) => Detected {
            kind: kinds::classify(&p.tool, &p.rest, kinds),
            label: label_of(&p),
            tool: p.tool,
        },
        None => Detected::default(),
    }
}

/// Analyse the full command. A shell string is split into segments; the costliest heavy
/// segment decides the kind.
pub fn detect(argv: &[String], kinds: &BTreeMap<String, KindConfig>) -> Detected {
    if !is_shell_string(argv) {
        return detect_words(argv, kinds);
    }
    let s = &argv[0];
    let mut first: Option<Detected> = None;
    let mut best: Option<(u32, Detected)> = None;
    for r in split_segments(s) {
        let d = detect_words(&tokenize(&s[r]), kinds);
        if d.label.is_empty() {
            continue;
        }
        if let Some(k) = &d.kind {
            let c = kinds::cost(k, kinds);
            if best.as_ref().is_none_or(|(bc, _)| c > *bc) {
                best = Some((c, d.clone()));
            }
        }
        first.get_or_insert(d);
    }
    best.map(|(_, d)| d).or(first).unwrap_or_default()
}

/// The changes the tool's hint asks for: new argv (if any) and extra environment.
#[derive(Debug, Default, PartialEq)]
pub struct HintChanges {
    pub argv: Option<Vec<String>>,
    pub env: Vec<(String, String)>,
}

/// Apply the [`Hint`] of the detected tool. `workers` turns a [`Workers`] into a number;
/// `env_set` says whether an environment variable is already set.
pub fn apply_hints(
    argv: &[String],
    tool: &str,
    cwd: &Path,
    workers: &dyn Fn(Workers) -> u32,
    env_set: &dyn Fn(&str) -> bool,
) -> HintChanges {
    let mut out = HintChanges::default();
    match kinds::hint_for(tool) {
        Some(Hint::Arg {
            flag,
            opt_out,
            launchers,
            min_args,
            workers: w,
        }) => {
            out.argv = arg_hint(argv, tool, launchers, opt_out, min_args).map(|(mut a, at)| {
                a.insert(at, format!("{flag}{}", workers(w)));
                a
            });
        }
        Some(Hint::Env {
            var,
            workers: w,
            user_limit,
        }) if !env_set(var) => {
            let ours = workers(w);
            let n = user_limit
                .and_then(|f| f(cwd))
                .map_or(ours, |theirs| theirs.min(ours));
            out.env.push((var.to_string(), n.to_string()))
        }
        _ => {}
    }
    out
}

/// Where to insert an argument hint, if the tool was started directly through one of the
/// launchers and has not opted out. Returns the argv copy and the insert position.
fn arg_hint(
    argv: &[String],
    tool: &str,
    launchers: &[&[&str]],
    opt_out: &[&str],
    min_args: usize,
) -> Option<(Vec<String>, usize)> {
    if is_shell_string(argv) || argv.is_empty() {
        return None;
    }
    let word = |i: usize| {
        if i == 0 {
            tool_name(&argv[0])
        } else {
            argv[i].to_ascii_lowercase()
        }
    };
    let at = launchers
        .iter()
        .find(|l| {
            argv.len() > l.len()
                && l.iter().enumerate().all(|(i, w)| word(i) == *w)
                && tool_name(&argv[l.len()]) == tool
        })?
        .len();
    let rest = &argv[at + 1..];
    let opted_out = rest.iter().any(|w| {
        let w = w.to_ascii_lowercase();
        opt_out.iter().any(|o| w.starts_with(o))
    });
    if opted_out || rest.len() < min_args || kinds::only_info_flags(rest) {
        return None;
    }
    let insert = at + 1 + rest.iter().position(|w| w == "--").unwrap_or(rest.len());
    Some((argv.to_vec(), insert))
}

fn compose_up_attached(words: &[String]) -> bool {
    let Some(p) = parse(words) else {
        return false;
    };
    let after = match p.tool.as_str() {
        "docker-compose" => &p.rest[..],
        "docker" => match kinds::after_docker_compose(&p.rest) {
            Some(a) => a,
            None => return false,
        },
        _ => return false,
    };
    if kinds::compose_sub(after).as_deref() != Some("up") {
        return false;
    }
    let detached = after.iter().any(|w| {
        w == "--detach"
            || w.starts_with("--detach=") && !w.ends_with("=false")
            || w == "--wait"
            || (w.starts_with('-') && !w.starts_with("--") && w[1..].contains('d'))
    });
    !detached
}

/// What to do with a command before it is queued.
#[derive(Debug, Clone, PartialEq)]
pub enum Disposition {
    /// Wait in the queue as usual.
    Queue,
    /// Run at once without the queue (help/version output, dev servers).
    Light(&'static str),
    /// Refuse: it would hold its points forever. `fixed` is the one-shot form, if known.
    Refuse {
        reason: String,
        fixed: Option<Vec<String>>,
    },
}

/// Decide whether a command is queued, run at once, or refused. `stdin_tty` matters for
/// tools that watch by default in a terminal (vitest).
pub fn disposition(argv: &[String], stdin_tty: bool) -> Disposition {
    if is_shell_string(argv) {
        let s = &argv[0];
        return split_segments(s)
            .into_iter()
            .find_map(|r| match words_disposition(&tokenize(&s[r]), stdin_tty) {
                Disposition::Refuse { reason, .. } => Some(Disposition::Refuse { reason, fixed: None }),
                _ => None,
            })
            .unwrap_or(Disposition::Queue);
    }
    words_disposition(argv, stdin_tty)
}

fn words_disposition(words: &[String], stdin_tty: bool) -> Disposition {
    if compose_up_attached(words) {
        return Disposition::Refuse {
            reason: "`docker compose up` without -d would hold queue points forever; run it detached \
                     (`docker compose up -d`) or outside calmrun"
                .to_string(),
            fixed: detached_compose(words),
        };
    }
    let Some(p) = parse(words) else {
        return Disposition::Queue;
    };
    if kinds::asks_for_info(&p.rest) {
        return Disposition::Light("only prints help or a version");
    }
    if let Some(rule) = kinds::endless_rule(&p.tool, &p.rest, stdin_tty) {
        return Disposition::Refuse {
            reason: format!(
                "`{}` is {} and never ends, so it would hold queue points forever; run the one-shot \
                 form, or run it outside calmrun",
                label_of(&p),
                rule.what
            ),
            fixed: apply_fix(words, &p, rule.fix),
        };
    }
    match kinds::light_rule(&p.tool, &p.rest) {
        Some(r) => Disposition::Light(r.kind),
        None => Disposition::Queue,
    }
}

/// The one-shot form of an endless command (argv words only).
fn apply_fix(words: &[String], p: &Parsed, fix: kinds::Fix) -> Option<Vec<String>> {
    let tool_at = (p.start..words.len()).find(|&i| tool_name(&words[i]) == p.tool)?;
    let mut out = words.to_vec();
    match fix {
        kinds::Fix::None => return None,
        kinds::Fix::RemoveFlags(flags) => {
            let tail = out.split_off(tool_at + 1);
            out.extend(tail.into_iter().filter(|w| {
                let lw = w.to_ascii_lowercase();
                !flags.iter().any(|f| lw == *f || lw.starts_with(&format!("{f}=")))
            }));
        }
        kinds::Fix::SetSub(sub) => {
            let at = (tool_at + 1..out.len()).find(|&i| !out[i].starts_with('-'))?;
            out[at] = sub.to_string();
        }
        kinds::Fix::InsertSub(sub) => out.insert(tool_at + 1, sub.to_string()),
    }
    Some(out)
}

/// The same compose command with `-d` added after `up` (argv words only).
pub fn detached_compose(argv: &[String]) -> Option<Vec<String>> {
    if is_shell_string(argv) || !compose_up_attached(argv) {
        return None;
    }
    let start = argv
        .iter()
        .position(|w| matches!(tool_name(w).as_str(), "docker" | "docker-compose"))?;
    let up = start + argv[start..].iter().position(|w| w == "up")?;
    let mut out = argv.to_vec();
    out.insert(up + 1, "-d".to_string());
    Some(out)
}

/// FNV-1a 64-bit, stable across builds and platforms.
pub fn fnv1a(s: &str) -> String {
    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const PRIME: u64 = 0x0100_0000_01b3;
    let h = s.bytes().fold(OFFSET, |h, b| (h ^ b as u64).wrapping_mul(PRIME));
    format!("{h:016x}")
}

fn key_for(prefix: &str, p: &Path) -> String {
    format!("{prefix}:{}", fnv1a(&crate::sys::path_key(p)))
}

fn nearest(cwd: &Path, test: impl Fn(&Path) -> bool) -> Option<PathBuf> {
    cwd.ancestors().find(|d| test(d)).map(Path::to_path_buf)
}

/// Exclusive keys of a job of `kind` run by `tool` in `cwd`: two jobs sharing a key never
/// run together.
pub fn exclusive_keys(kind: &str, tool: &str, cwd: &Path) -> Vec<String> {
    match kinds::key_rule(kind, tool) {
        KeyRule::None => Vec::new(),
        KeyRule::NodeModules => nearest(cwd, |d| d.join("node_modules").is_dir())
            .map(|d| vec![key_for("nm", &d.join("node_modules"))])
            .unwrap_or_default(),
        KeyRule::CargoTarget => {
            if let Some(t) = std::env::var_os("CARGO_TARGET_DIR").filter(|v| !v.is_empty()) {
                return vec![key_for("cargo", Path::new(&t))];
            }
            nearest(cwd, |d| {
                d.join("Cargo.toml").is_file() && d.join("target").is_dir()
            })
            .or_else(|| nearest(cwd, |d| d.join("Cargo.toml").is_file()))
            .map(|d| vec![key_for("cargo", &d.join("target"))])
            .unwrap_or_default()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn w(s: &str) -> Vec<String> {
        tokenize(s)
    }
    fn kind(s: &str) -> Option<String> {
        detect_words(&w(s), &BTreeMap::new()).kind
    }
    fn label(s: &str) -> String {
        detect_words(&w(s), &BTreeMap::new()).label
    }
    fn argv(s: &str) -> Vec<String> {
        s.split(' ').map(String::from).collect()
    }
    fn hinted(s: &str, n: u32) -> Option<Vec<String>> {
        let a = argv(s);
        let tool = detect_words(&a, &BTreeMap::new()).tool;
        apply_hints(&a, &tool, Path::new("."), &|_| n, &|_| false).argv
    }

    #[test]
    fn tool_names() {
        assert_eq!(tool_name("C:\\Program Files\\nodejs\\npx.cmd"), "npx");
        assert_eq!(tool_name("./node_modules/.bin/vitest"), "vitest");
        assert_eq!(tool_name("ESLINT.EXE"), "eslint");
        assert_eq!(tool_name("run.ps1"), "run");
        assert_eq!(tool_name("tsc@5"), "tsc");
        assert_eq!(tool_name("@vitest/browser@3.1"), "browser");
        assert_eq!(tool_name("eslint@9.0.0"), "eslint");
    }

    #[test]
    fn kinds_detected() {
        for (cmd, k) in [
            ("vitest run", "vitest"),
            ("npx vitest", "vitest"),
            ("npx -y jest --ci", "jest"),
            ("pnpm exec vue-tsc --noEmit", "tsc"),
            ("pnpm tsgo", "tsc"),
            ("npx playwright test", "capture"),
            ("docker compose -f a.yml up -d", "docker"),
            ("docker-compose build", "docker"),
            ("docker build .", "docker"),
            ("npx biome check .", "eslint"),
            ("python -m pytest -q", "pytest"),
            ("uv run pytest", "pytest"),
            ("npx vite build", "build"),
            ("./gradlew assembleDebug", "build"),
            ("cargo build --release", "build"),
            ("flutter build apk", "build"),
            ("dotnet build", "build"),
            ("cargo test", "test"),
            ("go test ./...", "test"),
            ("npm test", "test"),
            ("npm run build", "build"),
            ("pnpm lint", "eslint"),
            ("FOO=1 CI=true npx vitest", "vitest"),
            ("node ./node_modules/vitest/vitest.mjs run", "vitest"),
            ("npx tsc@5 --noEmit", "tsc"),
            ("npx vitest@3 run", "vitest"),
            ("npx -p typescript@5 tsc", "tsc"),
            ("pnpm dlx eslint@9 .", "eslint"),
            ("bunx eslint@9 .", "eslint"),
        ] {
            assert_eq!(kind(cmd).as_deref(), Some(k), "{cmd}");
        }
    }

    #[test]
    fn light_commands_not_detected() {
        for c in [
            "git commit -m \"fix vitest\"",
            "grep jest .",
            "npm install eslint",
            "npm ci",
            "ls -la",
            "cat vitest.config.ts",
            "docker ps",
            "docker compose logs",
            "cargo install calmrun",
            "npx vitest --version",
            "vite",
            "npm run dev",
            "echo tsc",
        ] {
            assert_eq!(kind(c), None, "{c}");
        }
    }

    #[test]
    fn labels_have_no_arguments() {
        assert_eq!(label("npx vitest run src/secret.test.ts"), "npx vitest run");
        assert_eq!(label("vitest --token=abc"), "vitest");
        assert_eq!(label("cargo build --release"), "cargo build");
        assert_eq!(label("npm run build -- --token abc"), "npm run build");
        assert_eq!(label("docker compose up -d"), "docker compose up");
        assert_eq!(label("jest mySecretFilter"), "jest");
        assert_eq!(label("curl https://x?token=1"), "curl");
        assert_eq!(label("pnpm exec tsc -p ."), "pnpm exec tsc");
        assert_eq!(label("npx --version"), "npx");
    }

    #[test]
    fn custom_patterns() {
        let mut kinds = BTreeMap::new();
        kinds.insert(
            "heavy".to_string(),
            KindConfig {
                cost: Some(3),
                patterns: vec!["make".into(), "bazel build".into()],
            },
        );
        assert_eq!(
            detect_words(&w("make -j8"), &kinds).kind.as_deref(),
            Some("heavy")
        );
        assert_eq!(
            detect_words(&w("bazel build //..."), &kinds).kind.as_deref(),
            Some("heavy")
        );
        assert_eq!(detect_words(&w("bazel query x"), &kinds).kind, None);
        assert_eq!(kinds::cost("heavy", &kinds), 3);
    }

    #[test]
    fn shell_string_takes_costliest_segment() {
        let d = detect(
            &["npm ci && npx eslint . && npx vitest run".to_string()],
            &BTreeMap::new(),
        );
        assert_eq!(d.kind.as_deref(), Some("vitest"));
        assert_eq!(d.label, "npx vitest run");
    }

    #[test]
    fn vitest_hint() {
        assert_eq!(hinted("vitest run", 2), Some(argv("vitest run --maxWorkers=2")));
        assert_eq!(hinted("npx vitest", 1), Some(argv("npx vitest --maxWorkers=1")));
        assert_eq!(
            hinted("pnpm exec vitest run", 3),
            Some(argv("pnpm exec vitest run --maxWorkers=3"))
        );
        assert_eq!(
            hinted("yarn exec vitest -- a", 1),
            Some(argv("yarn exec vitest --maxWorkers=1 -- a"))
        );
        assert_eq!(hinted("vitest --maxWorkers=4", 1), None);
        assert_eq!(hinted("vitest --pool=forks", 1), None);
        assert_eq!(hinted("vitest --no-file-parallelism", 1), None);
        assert_eq!(hinted("npm run test", 1), None);
        assert_eq!(hinted("npx jest", 1), None);
        assert_eq!(hinted("FOO=1 vitest", 1), None);
        let shell = vec!["npx vitest run".to_string()];
        assert_eq!(
            apply_hints(&shell, "vitest", Path::new("."), &|_| 1, &|_| false).argv,
            None
        );
    }

    #[test]
    fn gradle_and_cargo_hints() {
        assert_eq!(
            hinted("./gradlew build", 4),
            Some(argv("./gradlew build --max-workers=4"))
        );
        assert_eq!(hinted("gradle test --max-workers=2", 4), None);
        assert_eq!(hinted("gradlew build -Dorg.gradle.workers.max=2", 4), None);
        assert_eq!(hinted("gradlew --version", 4), None);
        assert_eq!(hinted("gradlew", 4), None);
        assert_eq!(hinted("mvn package", 4), None);
        let c = apply_hints(
            &argv("cargo build"),
            "cargo",
            Path::new("/nonexistent-cwd"),
            &|_| 5,
            &|_| false,
        );
        // At most ours; lower if this machine's ~/.cargo config sets build.jobs.
        assert_eq!(c.env.len(), 1);
        assert_eq!(c.env[0].0, "CARGO_BUILD_JOBS");
        assert!((1..=5).contains(&c.env[0].1.parse::<u32>().unwrap()));
        assert!(
            apply_hints(&argv("cargo build"), "cargo", Path::new("."), &|_| 5, &|_| true)
                .env
                .is_empty()
        );
    }

    fn refused(a: &[String]) -> bool {
        matches!(disposition(a, false), Disposition::Refuse { .. })
    }

    #[test]
    fn compose_up_refused() {
        assert!(refused(&argv("docker compose up")));
        assert!(refused(&argv("docker-compose -f x.yml up --build")));
        assert!(refused(&["cd a && docker compose up".to_string()]));
        assert!(!refused(&argv("docker compose up -d")));
        assert!(!refused(&argv("docker compose up --detach")));
        assert!(!refused(&argv("docker-compose up -dV")));
        assert!(!refused(&argv("docker compose up --wait")));
        assert!(!refused(&argv("docker compose build")));
        assert_eq!(
            detached_compose(&argv("docker compose -f a.yml up --build")),
            Some(argv("docker compose -f a.yml up -d --build"))
        );
        assert_eq!(detached_compose(&argv("docker compose up -d")), None);
    }

    #[test]
    fn watch_modes_are_refused_with_the_one_shot_form() {
        let fixed = |s: &str, tty: bool| match disposition(&argv(s), tty) {
            Disposition::Refuse { fixed, .. } => fixed.map(|f| f.join(" ")),
            other => panic!("{s}: {other:?}"),
        };
        assert_eq!(fixed("npx tsc --watch", false).as_deref(), Some("npx tsc"));
        assert_eq!(fixed("npx tsc -w -p .", false).as_deref(), Some("npx tsc -p ."));
        assert_eq!(fixed("npx jest --watchAll", false).as_deref(), Some("npx jest"));
        assert_eq!(
            fixed("npx vitest watch", false).as_deref(),
            Some("npx vitest run")
        );
        assert_eq!(fixed("vitest", true).as_deref(), Some("vitest run"));
        assert_eq!(
            fixed("npx vitest --coverage", true).as_deref(),
            Some("npx vitest run --coverage")
        );
        assert_eq!(fixed("docker run -it ubuntu", false), None);
        // Not endless: one-shot forms, and vitest without a terminal (it runs once then).
        for ok in [
            "npx tsc -p .",
            "npx vitest run",
            "vitest",
            "docker build -t x .",
            "docker run --rm x",
        ] {
            assert_eq!(disposition(&argv(ok), false), Disposition::Queue, "{ok}");
        }
    }

    #[test]
    fn dev_servers_and_help_run_without_the_queue() {
        for c in [
            "npx vite",
            "npm run dev",
            "pnpm dev",
            "next dev",
            "ng serve",
            "cargo build --help",
            "npx tsc --version",
        ] {
            assert!(
                matches!(disposition(&argv(c), false), Disposition::Light(_)),
                "{c}"
            );
        }
        assert_eq!(disposition(&argv("npx vite build"), false), Disposition::Queue);
    }

    #[test]
    fn keys_for_node_modules_and_cargo() {
        let tmp = tempfile::tempdir().unwrap();
        let proj = tmp.path().join("proj");
        std::fs::create_dir_all(proj.join("node_modules")).unwrap();
        std::fs::create_dir_all(proj.join("src/deep")).unwrap();
        let k1 = exclusive_keys("vitest", "vitest", &proj.join("src/deep"));
        assert_eq!(k1.len(), 1);
        assert_eq!(k1, exclusive_keys("vitest", "vitest", &proj));
        assert!(exclusive_keys("eslint", "eslint", &proj).is_empty());
        std::fs::write(proj.join("Cargo.toml"), "").unwrap();
        std::fs::create_dir_all(proj.join("target")).unwrap();
        let ck = exclusive_keys("build", "cargo", &proj.join("src"));
        assert_eq!(ck.len(), 1);
        assert!(ck[0].starts_with("cargo:"));
    }
}