rch-common 2.1.4

Shared types and utilities for Remote Compilation Helper
Documentation
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! `rch admit` preflight core (bd-session-history-remediation-ocv9i.6.1).
//!
//! `rch admit -- <command>` is a fast, read-only preflight an agent runs before
//! expensive work: it classifies the command, determines its family and the
//! capabilities a worker must have to run it, and — given the daemon's
//! candidate/rejection data — returns a decisive Offload / Local / Queue / Defer
//! answer. This module is the **pure** heart of that: classification and
//! capability derivation ([`preflight`]) plus the decision rule that folds in
//! aggregated candidate rejections ([`refine_recommendation`]).
//!
//! It reuses the existing classifier ([`crate::patterns`]), the capability
//! requirement contract ([`crate::capability_probe::CapabilityRequirement`]),
//! and the admission-rejection vocabulary ([`crate::admission_rejection`]) rather
//! than inventing a parallel path. The clap `rch admit` subcommand and the
//! optional daemon candidate query are the CLI/daemon surface over this contract.

use serde::{Deserialize, Serialize};

use crate::admission_rejection::{AdmissionRejectionSummary, RejectionClass};
use crate::capability_probe::CapabilityRequirement;
use crate::patterns::{
    CompilationKind, classify_command, classify_command_detailed, is_cargo_xwin_build,
    split_shell_commands,
};

/// The decisive recommendation `rch admit` returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AdmitRecommendation {
    /// Offload to a remote worker.
    Offload,
    /// Run locally (not a compilation, or nothing to gain from offload).
    Local,
    /// Offload-eligible but the fleet is transiently busy/unhealthy — queue.
    Queue,
    /// No worker can run this command (structural capability gap) — defer until
    /// the fleet gains the capability rather than waiting on a slot.
    Defer,
}

impl AdmitRecommendation {
    /// Stable lowercase token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            AdmitRecommendation::Offload => "offload",
            AdmitRecommendation::Local => "local",
            AdmitRecommendation::Queue => "queue",
            AdmitRecommendation::Defer => "defer",
        }
    }
}

/// The capabilities a command needs from a worker, as a serializable summary.
/// Mirrors (and converts to) [`CapabilityRequirement`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequiredCapabilities {
    pub needs_cargo: bool,
    pub needs_bun: bool,
    /// Whether the command requires nix (binary + populated `/nix/store`).
    pub needs_nix: bool,
    /// Whether the command requires the Go toolchain.
    pub needs_go: bool,
    /// Whether the command requires Node.js (e.g. `tsc` / `npx tsc`).
    pub needs_node: bool,
    /// Whether the command requires `zig` + `cargo-zigbuild` (a zig cross-build).
    /// This is on TOP of `needs_cargo` and the requested `needs_targets`.
    pub needs_zig: bool,
    /// rustup targets the command explicitly requests (`--target <triple>`).
    pub needs_targets: Vec<String>,
    /// Explicit toolchain overrides (`cargo +nightly-…`).
    pub needs_toolchains: Vec<String>,
    /// Host OS the worker must run, when a requested `--target` triple implies
    /// one (e.g. `*-pc-windows-msvc` → `windows`). `None` for the ordinary
    /// native build, which stays schedulable on any worker.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub needs_os: Option<String>,
    /// Operator-declared named tools the caller required (`--require-tool`).
    ///
    /// Job mode only, and never derived from the command: RCH cannot know that
    /// `./run_shards.sh` shells out to clang, so the requirement is something
    /// the caller states, not something a classifier guesses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub needs_tools: Vec<String>,
}

impl RequiredCapabilities {
    /// Convert to the admission-gate [`CapabilityRequirement`] for a given wire
    /// protocol.
    #[must_use]
    pub fn to_requirement(&self, min_protocol: u32) -> CapabilityRequirement {
        CapabilityRequirement {
            needs_targets: self.needs_targets.clone(),
            min_protocol,
            needs_cargo: self.needs_cargo,
            needs_bun: self.needs_bun,
            needs_nix: self.needs_nix,
            needs_go: self.needs_go,
            needs_node: self.needs_node,
            needs_zig: self.needs_zig,
            needs_toolchains: self.needs_toolchains.clone(),
            needs_os: self.needs_os.clone(),
            needs_tools: self.needs_tools.clone(),
            ..CapabilityRequirement::default()
        }
    }
}

/// The result of a read-only admit preflight.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmitPreflight {
    /// The command as given.
    pub command: String,
    /// Sub-commands when the input is a compound shell form (`a && b`); a single
    /// command yields one element.
    pub compound: Vec<String>,
    /// Whether the (whole) command is a compilation worth offloading.
    pub is_compilation: bool,
    /// The compilation family, when classified (e.g. `cargo_build`, `bun_test`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub family: Option<String>,
    /// Capabilities a worker must have to run it.
    pub required: RequiredCapabilities,
    /// Whether proof/strict-remote policy is in force (caller-supplied).
    pub proof_policy: bool,
    /// Whether this was preflighted as a job-mode admission (`--job`), where
    /// the compilation classifier is bypassed rather than consulted.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub job_mode: bool,
    /// The decision before daemon candidate data is folded in.
    pub base_recommendation: AdmitRecommendation,
    /// Operator-facing explanation.
    pub detail: String,
}

/// Snake_case family token for a compilation kind.
fn family_token(kind: CompilationKind) -> &'static str {
    match kind {
        CompilationKind::CargoBuild => "cargo_build",
        CompilationKind::CargoTest => "cargo_test",
        CompilationKind::CargoCheck => "cargo_check",
        CompilationKind::CargoClippy => "cargo_clippy",
        CompilationKind::CargoDoc => "cargo_doc",
        CompilationKind::CargoNextest => "cargo_nextest",
        CompilationKind::CargoBench => "cargo_bench",
        CompilationKind::CargoZigbuild => "cargo_zigbuild",
        CompilationKind::Rustc => "rustc",
        CompilationKind::Gcc => "gcc",
        CompilationKind::Gpp => "gpp",
        CompilationKind::Clang => "clang",
        CompilationKind::Clangpp => "clangpp",
        CompilationKind::Make => "make",
        CompilationKind::CmakeBuild => "cmake",
        CompilationKind::Ninja => "ninja",
        CompilationKind::Meson => "meson",
        CompilationKind::BunTest => "bun_test",
        CompilationKind::BunTypecheck => "bun_typecheck",
        CompilationKind::NixBuild => "nix_build",
        CompilationKind::GoBuild => "go_build",
        CompilationKind::GoTest => "go_test",
        CompilationKind::GoVet => "go_vet",
        CompilationKind::Tsc => "tsc",
        CompilationKind::Job => "job",
    }
}

/// Whether a kind is part of the Rust/cargo family (needs cargo).
fn is_rust_kind(kind: CompilationKind) -> bool {
    matches!(
        kind,
        CompilationKind::CargoBuild
            | CompilationKind::CargoTest
            | CompilationKind::CargoCheck
            | CompilationKind::CargoClippy
            | CompilationKind::CargoDoc
            | CompilationKind::CargoNextest
            | CompilationKind::CargoBench
            // A zig cross-build runs through cargo, so it needs the cargo toolchain
            // too (plus zig — see `needs_zig` in derive_capabilities).
            | CompilationKind::CargoZigbuild
            | CompilationKind::Rustc
    )
}

/// Derive required capabilities from a command string + its classified kind.
fn derive_capabilities(command: &str, kind: Option<CompilationKind>) -> RequiredCapabilities {
    let mut req = RequiredCapabilities::default();
    if let Some(kind) = kind {
        req.needs_cargo = is_rust_kind(kind);
        req.needs_bun = matches!(
            kind,
            CompilationKind::BunTest | CompilationKind::BunTypecheck
        );
        req.needs_nix = matches!(kind, CompilationKind::NixBuild);
        req.needs_go = matches!(
            kind,
            CompilationKind::GoBuild | CompilationKind::GoTest | CompilationKind::GoVet
        );
        req.needs_node = matches!(kind, CompilationKind::Tsc);
        // A zig cross-build additionally needs zig + cargo-zigbuild on the worker.
        // The requested `--target` std is captured by the needs_targets scan below,
        // exactly as for a plain `cargo build --target ...`.
        req.needs_zig = matches!(kind, CompilationKind::CargoZigbuild);
    }
    // Scan tokens for `--target <triple>` / `--target=<triple>` and `+toolchain`.
    let tokens: Vec<&str> = command.split_whitespace().collect();
    let mut i = 0;
    while i < tokens.len() {
        let tok = tokens[i];
        if let Some(triple) = tok.strip_prefix("--target=") {
            if !triple.is_empty() {
                req.needs_targets.push(triple.to_string());
            }
        } else if tok == "--target" {
            if let Some(triple) = tokens.get(i + 1) {
                req.needs_targets.push((*triple).to_string());
                i += 1;
            }
        } else if let Some(toolchain) = tok.strip_prefix('+') {
            // A cargo toolchain override token, e.g. `cargo +nightly-2025-11-01 build`.
            if !toolchain.is_empty() {
                req.needs_toolchains.push(toolchain.to_string());
            }
        }
        i += 1;
    }
    req.needs_targets.sort();
    req.needs_targets.dedup();
    req.needs_toolchains.sort();
    req.needs_toolchains.dedup();
    req.needs_os = os_from_target_triples(&host_bound_targets(command, &req.needs_targets));
    req
}

/// Explicit cross-build tools supply their linker on the build host. Darwin
/// zigbuild still needs the Apple SDK, Zig, and the requested Rust target, but
/// the SDK can reside on Linux. Keep native constraints for ordinary Cargo and
/// for targets the selected cross-build tool does not support here.
fn host_bound_targets(command: &str, targets: &[String]) -> Vec<String> {
    let cross_msvc = is_cargo_xwin_build(command);
    let cross_darwin = classify_command(command).kind == Some(CompilationKind::CargoZigbuild);
    targets
        .iter()
        .filter(|target| {
            let target = target.to_ascii_lowercase();
            !(cross_msvc && target.contains("-windows-msvc")
                || cross_darwin && target.ends_with("-apple-darwin"))
        })
        .cloned()
        .collect()
}

/// The host OS a command demands of a worker, if any.
///
/// Exposed for the daemon's selection path, which gates on the command string it
/// already carries rather than on a new wire field — keeping this usable across
/// a fleet whose `rch` and `rchd` binaries are at mixed versions.
#[must_use]
pub fn required_os_for_command(command: &str) -> Option<String> {
    let mut triples: Vec<String> = Vec::new();
    for part in split_shell_commands(command) {
        let detail = classify_command_detailed(part);
        if detail.classification.is_compilation {
            let required = derive_capabilities(part, detail.classification.kind);
            triples.extend(host_bound_targets(part, &required.needs_targets));
        }
    }
    os_from_target_triples(&triples)
}

/// The host OS a set of `--target` triples demands, when they agree on one.
///
/// Only a triple naming an OS the worker must *be* counts. `x86_64-pc-windows-msvc`
/// ordinarily links against the native MSVC toolchain, so it yields `windows`;
/// explicit cargo-xwin builds remove their MSVC targets before this step.
/// Every `*-apple-*` target (darwin, ios, tvos, watchos, visionos)
/// needs the macOS SDK, so it yields `darwin`. `x86_64-pc-windows-gnu` and
/// `wasm32-unknown-unknown` cross-compile happily from Linux and yield nothing.
///
/// Mixed or absent requirements yield `None`, leaving the command schedulable
/// anywhere — the historical behaviour. A compound command spanning two host
/// OSes cannot succeed on any single worker regardless, and returning `None`
/// keeps that no worse than it is today rather than inventing a new refusal.
fn os_from_target_triples(triples: &[String]) -> Option<String> {
    let mut required: Option<String> = None;
    for triple in triples {
        let lower = triple.to_ascii_lowercase();
        let os = if lower.contains("-windows-msvc") {
            "windows"
        } else if lower.contains("-apple-") {
            "darwin"
        } else {
            continue;
        };
        match &required {
            Some(existing) if existing != os => return None,
            Some(_) => {}
            None => required = Some(os.to_string()),
        }
    }
    required
}

/// Run the read-only preflight for a command. `proof_policy` reflects the
/// caller's strict/proof-remote setting (from env/flags). Pure.
#[must_use]
pub fn preflight(command: &str, proof_policy: bool) -> AdmitPreflight {
    let compound: Vec<String> = split_shell_commands(command)
        .into_iter()
        .map(Into::into)
        .collect();
    let compound = if compound.is_empty() {
        vec![command.to_string()]
    } else {
        compound
    };

    // The whole command is a compilation if any sub-command classifies as one;
    // capabilities are the union across compilation sub-commands.
    let mut is_compilation = false;
    let mut family: Option<String> = None;
    let mut required = RequiredCapabilities::default();
    let mut host_targets = Vec::new();
    for part in &compound {
        let detail = classify_command_detailed(part);
        let c = &detail.classification;
        if c.is_compilation {
            is_compilation = true;
            if let Some(kind) = c.kind
                && family.is_none()
            {
                family = Some(family_token(kind).to_string());
            }
            let part_req = derive_capabilities(part, c.kind);
            host_targets.extend(host_bound_targets(part, &part_req.needs_targets));
            required.needs_cargo |= part_req.needs_cargo;
            required.needs_zig |= part_req.needs_zig;
            required.needs_bun |= part_req.needs_bun;
            required.needs_nix |= part_req.needs_nix;
            required.needs_go |= part_req.needs_go;
            required.needs_node |= part_req.needs_node;
            required.needs_targets.extend(part_req.needs_targets);
            required.needs_toolchains.extend(part_req.needs_toolchains);
        }
    }
    required.needs_targets.sort();
    required.needs_targets.dedup();
    required.needs_toolchains.sort();
    required.needs_toolchains.dedup();
    // Recomputed over the merged target set: a compound command whose parts
    // disagree on the required OS must not inherit one part's answer.
    required.needs_os = os_from_target_triples(&host_targets);

    let base_recommendation = if is_compilation {
        AdmitRecommendation::Offload
    } else {
        AdmitRecommendation::Local
    };

    let detail = if !is_compilation {
        "not a compilation command; run locally".to_string()
    } else if compound.len() > 1 {
        format!(
            "compound command with {} parts; offload-eligible (family={})",
            compound.len(),
            family.as_deref().unwrap_or("unknown")
        )
    } else {
        format!(
            "offload-eligible (family={})",
            family.as_deref().unwrap_or("unknown")
        )
    };

    AdmitPreflight {
        command: command.to_string(),
        compound,
        is_compilation,
        family,
        required,
        proof_policy,
        job_mode: false,
        base_recommendation,
        detail,
    }
}

impl AdmitPreflight {
    /// Re-frame a preflight as a JOB-mode admission (`rch exec --job`).
    ///
    /// Job mode bypasses the compilation classifier rather than consulting it,
    /// so a job is offload-eligible whatever the classifier thought: `./fuzz.sh`
    /// is not a compilation and must still preflight as `offload`, otherwise
    /// this command would answer `local` for every workload job mode exists to
    /// serve.
    ///
    /// The classification facts are KEPT rather than cleared. A caller that
    /// passes `cargo test` to `--job` should still be able to see that it would
    /// have classified as a compilation — that is usually a mistake worth
    /// noticing, and erasing the evidence would hide it.
    ///
    /// Required tools are caller-stated, never derived: RCH cannot know that a
    /// shell script shells out to clang.
    #[must_use]
    pub fn as_job(mut self, required_tools: Vec<String>) -> Self {
        self.job_mode = true;
        self.required.needs_tools = required_tools;
        self.required.needs_tools.sort();
        self.required.needs_tools.dedup();
        self.base_recommendation = AdmitRecommendation::Offload;
        let tools = if self.required.needs_tools.is_empty() {
            String::new()
        } else {
            format!(
                "; requires verified tool(s) {}",
                self.required.needs_tools.join(", ")
            )
        };
        self.detail = format!(
            "job-mode admission: classifier bypassed, offload-eligible (classified as {}{})",
            if self.is_compilation {
                self.family.as_deref().unwrap_or("a compilation")
            } else {
                "non-compilation"
            },
            tools
        );
        self
    }
}

/// Fold aggregated candidate-rejection data into a final recommendation.
///
/// A non-offload base stays as-is. For an offload-eligible command: if every
/// candidate was rejected, distinguish a *structural* gap (command-admissibility
/// rejections dominate — no worker can run it, so `Defer`) from a *transient*
/// one (worker-health rejections dominate — busy/unhealthy, so `Queue`). If some
/// candidate remained admissible, `Offload`.
#[must_use]
pub fn refine_recommendation(
    base: AdmitRecommendation,
    summary: &AdmissionRejectionSummary,
) -> AdmitRecommendation {
    if base != AdmitRecommendation::Offload {
        return base;
    }
    if !summary.all_rejected() {
        return AdmitRecommendation::Offload;
    }
    let command_specific = summary.class_count(RejectionClass::CommandAdmissibility)
        + summary.class_count(RejectionClass::ProjectPolicy);
    let health = summary.class_count(RejectionClass::WorkerHealth);
    if command_specific >= health {
        AdmitRecommendation::Defer
    } else {
        AdmitRecommendation::Queue
    }
}

/// Convenience: whether `command` would offload at all (cheap classification).
#[must_use]
pub fn is_offloadable(command: &str) -> bool {
    classify_command(command).is_compilation
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::admission_rejection::{
        AdmissionRejectionCategory, CandidateRejection, aggregate_rejections,
    };

    #[test]
    fn job_mode_preflight_is_offload_eligible_whatever_the_classifier_said() {
        // THE point of the job-mode preflight: `exec --job` bypasses the
        // classifier, so a preflight that consulted it would answer `local`
        // for every workload job mode exists to serve.
        let script = preflight("./run_shards.sh --shard 3", false);
        assert!(!script.is_compilation);
        assert_eq!(script.base_recommendation, AdmitRecommendation::Local);

        let job = script.clone().as_job(Vec::new());
        assert!(job.job_mode);
        assert_eq!(job.base_recommendation, AdmitRecommendation::Offload);
        assert!(job.detail.contains("classifier bypassed"), "{}", job.detail);
        // The classification facts are KEPT, not cleared — they are still the
        // truth about the command, and erasing them would hide a mistake.
        assert!(!job.is_compilation);
        assert_eq!(job.command, script.command);
        assert_eq!(job.compound, script.compound);

        // A compilation passed to --job keeps its family visible, precisely so
        // a caller can notice they probably did not mean `--job`.
        let compile = preflight("cargo test --workspace", false).as_job(Vec::new());
        assert!(compile.is_compilation);
        assert_eq!(compile.family.as_deref(), Some("cargo_test"));
        assert_eq!(compile.base_recommendation, AdmitRecommendation::Offload);
        assert!(compile.detail.contains("cargo_test"), "{}", compile.detail);
    }

    #[test]
    fn job_mode_required_tools_are_caller_stated_normalized_and_gate_ready() {
        // Never derived: nothing can know that a shell script shells out to
        // clang, so the requirement only ever comes from the caller.
        assert!(
            preflight("./fuzz.sh", false)
                .as_job(Vec::new())
                .required
                .needs_tools
                .is_empty()
        );

        let job = preflight("./fuzz.sh", false).as_job(vec![
            "clang".to_string(),
            "ld.lld".to_string(),
            "clang".to_string(),
        ]);
        assert_eq!(
            job.required.needs_tools,
            vec!["clang".to_string(), "ld.lld".to_string()],
            "sorted and deduped so the same request preflights identically"
        );
        assert!(job.detail.contains("clang, ld.lld"), "{}", job.detail);

        // And it converts into the SAME requirement the selection gate uses,
        // so the preflight cannot drift from the admission it predicts.
        let requirement = job.required.to_requirement(1);
        assert_eq!(
            requirement.needs_tools,
            vec!["clang".to_string(), "ld.lld".to_string()]
        );
    }

    #[test]
    fn msvc_target_requires_a_windows_host() {
        // Ordinary Cargo builds use the native Microsoft toolchain. Only an
        // explicit cross-build entry point can supply that SDK on another OS.
        assert_eq!(
            required_os_for_command("cargo build --target x86_64-pc-windows-msvc"),
            Some("windows".to_string())
        );
        assert_eq!(
            required_os_for_command("cargo build --target=aarch64-pc-windows-msvc --release"),
            Some("windows".to_string())
        );
    }

    #[test]
    fn cargo_xwin_keeps_rust_target_requirements_without_a_native_windows_gate() {
        for command in [
            "cargo xwin build --target x86_64-pc-windows-msvc",
            "cargo +nightly-2026-08-31 xwin build --target=aarch64-pc-windows-msvc",
            "cargo-xwin xwin build --target x86_64-pc-windows-msvc",
        ] {
            let result = preflight(command, true);
            assert!(result.is_compilation, "{command}");
            assert!(result.required.needs_cargo, "{command}");
            assert_eq!(result.family.as_deref(), Some("cargo_build"));
            assert_eq!(result.required.needs_targets.len(), 1);
            assert!(result.required.needs_targets[0].contains("-windows-msvc"));
            assert_eq!(result.required.needs_os, None);
            assert_eq!(required_os_for_command(command), None);
        }
    }

    #[test]
    fn cargo_xwin_does_not_relax_other_commands_or_apple_targets() {
        for command in [
            "cargo xwin build --target x86_64-pc-windows-msvc && cargo build --target x86_64-pc-windows-msvc",
            "cargo --config xwin build --target x86_64-pc-windows-msvc",
            "cargo build --manifest-path cargo-xwin --target x86_64-pc-windows-msvc",
        ] {
            assert_eq!(
                required_os_for_command(command).as_deref(),
                Some("windows"),
                "{command}"
            );
            assert_eq!(
                preflight(command, true).required.needs_os.as_deref(),
                Some("windows"),
                "{command}"
            );
        }
        for command in [
            "cargo xwin build --target aarch64-apple-darwin",
            "cargo xwin build --target x86_64-pc-windows-msvc && cargo build --target aarch64-apple-darwin",
        ] {
            assert_eq!(
                required_os_for_command(command).as_deref(),
                Some("darwin"),
                "{command}"
            );
            assert_eq!(
                preflight(command, true).required.needs_os.as_deref(),
                Some("darwin"),
                "{command}"
            );
        }
    }

    #[test]
    fn darwin_zigbuild_keeps_linker_and_target_requirements_without_native_host_gate() {
        for command in [
            "cargo zigbuild --target aarch64-apple-darwin",
            "cargo +nightly zigbuild --target=x86_64-apple-darwin",
            "cargo-zigbuild zigbuild --target aarch64-apple-darwin",
            "env SDKROOT=/opt/MacOSX.sdk cargo zigbuild --target aarch64-apple-darwin",
        ] {
            let result = preflight(command, true);
            assert!(result.is_compilation, "{command}");
            assert!(result.required.needs_cargo, "{command}");
            assert!(result.required.needs_zig, "{command}");
            assert_eq!(result.family.as_deref(), Some("cargo_zigbuild"));
            assert_eq!(result.required.needs_targets.len(), 1);
            assert!(result.required.needs_targets[0].ends_with("-apple-darwin"));
            assert_eq!(result.required.needs_os, None);
            assert_eq!(required_os_for_command(command), None);
        }
    }

    #[test]
    fn darwin_zigbuild_does_not_relax_native_commands_or_other_apple_targets() {
        for command in [
            "cargo build --target aarch64-apple-darwin",
            "cargo build --manifest-path cargo-zigbuild --target aarch64-apple-darwin",
            "cargo --config zigbuild build --target aarch64-apple-darwin",
            "cargo zigbuild --target aarch64-apple-ios",
            "cargo zigbuild --target aarch64-apple-darwin && cargo build --target aarch64-apple-darwin",
        ] {
            assert_eq!(
                required_os_for_command(command).as_deref(),
                Some("darwin"),
                "{command}"
            );
            assert_eq!(
                preflight(command, true).required.needs_os.as_deref(),
                Some("darwin"),
                "{command}"
            );
        }
        let command = "cargo zigbuild --target x86_64-pc-windows-msvc";
        assert_eq!(required_os_for_command(command).as_deref(), Some("windows"));
        assert_eq!(
            preflight(command, true).required.needs_os.as_deref(),
            Some("windows")
        );
    }

    #[test]
    fn cross_compilable_targets_stay_unconstrained() {
        // mingw and wasm cross-compile from Linux, so constraining them would
        // strand work that the existing fleet handles today.
        assert_eq!(
            required_os_for_command("cargo build --target x86_64-pc-windows-gnu"),
            None
        );
        assert_eq!(
            required_os_for_command("cargo build --target wasm32-unknown-unknown"),
            None
        );
        assert_eq!(required_os_for_command("cargo check --workspace"), None);
        assert_eq!(required_os_for_command("cargo test"), None);
    }

    #[test]
    fn apple_target_requires_a_darwin_host() {
        // Every Apple target needs the macOS SDK, not just apple-darwin.
        for triple in [
            "aarch64-apple-darwin",
            "x86_64-apple-darwin",
            "aarch64-apple-ios",
            "aarch64-apple-tvos",
            "arm64_32-apple-watchos",
        ] {
            assert_eq!(
                required_os_for_command(&format!("cargo build --target {triple}")),
                Some("darwin".to_string()),
                "triple={triple}"
            );
        }
    }

    #[test]
    fn conflicting_targets_constrain_nothing() {
        // A compound command spanning two host OSes has no single answer; it must
        // stay schedulable rather than inherit one half's requirement.
        assert_eq!(
            required_os_for_command(
                "cargo build --target x86_64-pc-windows-msvc && cargo build --target aarch64-apple-darwin"
            ),
            None
        );
    }

    #[test]
    fn preflight_surfaces_the_required_os() {
        let p = preflight("cargo build --target x86_64-pc-windows-msvc", false);
        assert_eq!(p.required.needs_os.as_deref(), Some("windows"));
        assert_eq!(
            p.required.to_requirement(0).needs_os.as_deref(),
            Some("windows")
        );

        let plain = preflight("cargo build --release", false);
        assert_eq!(plain.required.needs_os, None);
        assert_eq!(plain.required.to_requirement(0).needs_os, None);
    }

    #[test]
    fn common_cargo_build_offloads_needing_cargo() {
        let p = preflight("cargo build --release", false);
        assert!(p.is_compilation);
        assert_eq!(p.family.as_deref(), Some("cargo_build"));
        assert!(p.required.needs_cargo);
        assert!(!p.required.needs_bun);
        assert_eq!(p.base_recommendation, AdmitRecommendation::Offload);
    }

    #[test]
    fn wasm_target_is_captured_as_required_capability() {
        let p = preflight("cargo build --target wasm32-unknown-unknown", false);
        assert!(p.required.needs_cargo);
        assert_eq!(p.required.needs_targets, vec!["wasm32-unknown-unknown"]);
        // `--target=triple` form too.
        let p2 = preflight("cargo test --target=aarch64-apple-darwin", false);
        assert_eq!(p2.required.needs_targets, vec!["aarch64-apple-darwin"]);
    }

    #[test]
    fn explicit_toolchain_override_is_captured() {
        let p = preflight("cargo +nightly-2025-11-01 build", false);
        assert_eq!(p.required.needs_toolchains, vec!["nightly-2025-11-01"]);
    }

    #[test]
    fn bun_command_needs_bun() {
        let p = preflight("bun test", false);
        if p.is_compilation {
            assert!(p.required.needs_bun);
            assert!(!p.required.needs_cargo);
            assert_eq!(p.base_recommendation, AdmitRecommendation::Offload);
        } else {
            // If the classifier doesn't treat this bun form as compilation, the
            // preflight must still be decisive (local), never ambiguous.
            assert_eq!(p.base_recommendation, AdmitRecommendation::Local);
        }
    }

    #[test]
    fn non_compilation_runs_local() {
        let p = preflight("ls -la", false);
        assert!(!p.is_compilation);
        assert_eq!(p.base_recommendation, AdmitRecommendation::Local);
        assert!(!p.required.needs_cargo && !p.required.needs_bun);
        assert!(p.detail.contains("locally"));
    }

    #[test]
    fn quoted_exec_form_is_classified_decisively() {
        // A quoted exec wrapper around a build still resolves to a definite
        // recommendation (never ambiguous).
        let p = preflight("sh -c 'cargo build'", false);
        assert!(matches!(
            p.base_recommendation,
            AdmitRecommendation::Offload | AdmitRecommendation::Local
        ));
    }

    #[test]
    fn compound_shell_form_is_split_and_unioned() {
        let p = preflight("cargo build && bun test", false);
        assert!(
            p.compound.len() >= 2,
            "compound must be split: {:?}",
            p.compound
        );
        // It is compilation if either part is, and capabilities union.
        if p.is_compilation {
            assert!(p.required.needs_cargo || p.required.needs_bun);
        }
    }

    #[test]
    fn refine_offload_when_some_candidate_admissible() {
        // 1 of 3 rejected => others admissible => Offload.
        let summary = aggregate_rejections(
            3,
            &[CandidateRejection {
                worker_id: "a".into(),
                category: AdmissionRejectionCategory::InsufficientSlots,
            }],
        );
        assert_eq!(
            refine_recommendation(AdmitRecommendation::Offload, &summary),
            AdmitRecommendation::Offload
        );
    }

    #[test]
    fn refine_queue_when_all_rejected_for_health() {
        // All rejected, dominated by worker-health (busy/unhealthy) => Queue.
        let summary = aggregate_rejections(
            2,
            &[
                CandidateRejection {
                    worker_id: "a".into(),
                    category: AdmissionRejectionCategory::InsufficientSlots,
                },
                CandidateRejection {
                    worker_id: "b".into(),
                    category: AdmissionRejectionCategory::CircuitOpen,
                },
            ],
        );
        assert_eq!(
            refine_recommendation(AdmitRecommendation::Offload, &summary),
            AdmitRecommendation::Queue
        );
    }

    #[test]
    fn refine_defer_when_all_rejected_for_capability() {
        // All rejected for command-specific capability => no worker can ever run
        // it => Defer (waiting on a slot is pointless).
        let summary = aggregate_rejections(
            2,
            &[
                CandidateRejection {
                    worker_id: "a".into(),
                    category: AdmissionRejectionCategory::MissingRustTarget,
                },
                CandidateRejection {
                    worker_id: "b".into(),
                    category: AdmissionRejectionCategory::OsArchMismatch,
                },
            ],
        );
        assert_eq!(
            refine_recommendation(AdmitRecommendation::Offload, &summary),
            AdmitRecommendation::Defer
        );
    }

    #[test]
    fn refine_keeps_local_recommendation() {
        let summary = aggregate_rejections(0, &[]);
        assert_eq!(
            refine_recommendation(AdmitRecommendation::Local, &summary),
            AdmitRecommendation::Local
        );
    }

    #[test]
    fn required_capabilities_convert_to_requirement() {
        let p = preflight("cargo build --target wasm32-unknown-unknown", false);
        let req = p.required.to_requirement(3);
        assert!(req.needs_cargo);
        assert_eq!(req.min_protocol, 3);
        assert_eq!(
            req.needs_targets,
            vec!["wasm32-unknown-unknown".to_string()]
        );
    }

    #[test]
    fn preflight_serializes_with_stable_tokens() {
        let p = preflight("cargo build", false);
        let value = serde_json::to_value(&p).unwrap();
        assert_eq!(value["base_recommendation"], "offload");
        assert_eq!(value["is_compilation"], true);
        let back: AdmitPreflight = serde_json::from_value(value).unwrap();
        assert_eq!(back, p);
    }
}