rch-common 2.1.20

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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! `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, cargo_xwin_compilation_kind, classify_command, classify_command_detailed,
    normalize_command, split_shell_commands, split_wrapper_word, unquote_literal_option_word,
};

/// 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 native tool or requested `--target`
    /// triple implies one (e.g. `xcodebuild` → `darwin`). `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);
    }
    // The xwin matcher validates the entire normalized suffix before admitting
    // quoted option words. Scan that same suffix so an env/wrapper payload cannot
    // introduce a target and a quoted --target= option cannot lose its requirement.
    let xwin = cargo_xwin_compilation_kind(command).is_some();
    let normalized = xwin.then(|| normalize_command(command));
    let token_command = normalized.as_deref().unwrap_or(command);
    // Scan tokens for `--target <triple>` / `--target=<triple>` and `+toolchain`.
    let tokens: Vec<&str> = token_command
        .split_whitespace()
        .map(|token| {
            if xwin {
                unquote_literal_option_word(token)
            } else {
                token
            }
        })
        .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 = cargo_xwin_compilation_kind(command).is_some();
    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_command_and_targets(command, &triples)
}

/// Native Apple tools need a Darwin host even in explicit job mode, where the
/// compilation classifier deliberately does not recognize them. Only inspect
/// the invoked command word, never an argument mentioning a tool. Opaque shell
/// scripts are not inferred: callers must invoke the Apple tool directly.
fn os_from_command_and_targets(command: &str, triples: &[String]) -> Option<String> {
    let native_hosts = split_shell_commands(command)
        .into_iter()
        .filter_map(|part| {
            let normalized = normalize_command(part);
            let (word, _) = split_wrapper_word(&normalized)?;
            match word.rsplit('/').next()? {
                "xcodebuild" | "xcrun" => Some("darwin"),
                _ => None,
            }
        });
    unique_host_os(
        triples
            .iter()
            .filter_map(|triple| target_host_os(triple))
            .chain(native_hosts),
    )
}

/// 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 compilations 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> {
    unique_host_os(triples.iter().filter_map(|triple| target_host_os(triple)))
}

fn target_host_os(triple: &str) -> Option<&'static str> {
    let lower = triple.to_ascii_lowercase();
    if lower.contains("-windows-msvc") {
        Some("windows")
    } else if lower.contains("-apple-") {
        Some("darwin")
    } else {
        None
    }
}

fn unique_host_os(hosts: impl IntoIterator<Item = &'static str>) -> Option<String> {
    let mut required: Option<String> = None;
    for os in hosts {
        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_command_and_targets(command, &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 {
    /// Add explicit compiler capabilities without bypassing classification or
    /// replacing the command's existing Rust/target/toolchain requirements.
    #[must_use]
    pub fn with_required_tools(mut self, required_tools: Vec<String>) -> Self {
        self.required.needs_tools.extend(required_tools);
        self.required.needs_tools.sort();
        self.required.needs_tools.dedup();
        self
    }

    /// 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 compiler_tool_requirements_preserve_rust_target_and_classification() {
        let original = preflight(
            "cargo build --target x86_64-pc-windows-msvc --release",
            true,
        );
        let observed = original.clone().with_required_tools(vec![
            "cargo-xwin".into(),
            "llvm-ar".into(),
            "cargo-xwin".into(),
        ]);
        assert_eq!(observed.is_compilation, original.is_compilation);
        assert_eq!(observed.family, original.family);
        assert_eq!(observed.base_recommendation, original.base_recommendation);
        assert_eq!(
            observed.required.needs_targets,
            original.required.needs_targets
        );
        assert_eq!(
            observed.required.needs_toolchains,
            original.required.needs_toolchains
        );
        assert!(observed.required.needs_cargo);
        assert!(!observed.job_mode);
        assert!(observed.proof_policy);
        assert_eq!(observed.required.needs_tools, vec!["cargo-xwin", "llvm-ar"]);
    }

    #[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_requirements_without_a_native_windows_gate() {
        for (subcommand, family) in [
            ("build", "cargo_build"),
            ("check", "cargo_check"),
            ("clippy", "cargo_clippy"),
        ] {
            for (prefix, toolchain) in [
                ("cargo xwin", None),
                ("cargo +nightly-2026-08-31 xwin", Some("nightly-2026-08-31")),
                ("cargo-xwin", None),
                ("cargo-xwin xwin", None),
            ] {
                for (target_argument, target) in [
                    ("--target x86_64-pc-windows-msvc", "x86_64-pc-windows-msvc"),
                    (
                        "--target=aarch64-pc-windows-msvc",
                        "aarch64-pc-windows-msvc",
                    ),
                ] {
                    let passthrough = if subcommand == "clippy" {
                        " -- -D warnings"
                    } else {
                        ""
                    };
                    let command = format!(
                        "{prefix} {subcommand} --locked --all-targets {target_argument}{passthrough}"
                    );
                    let result = preflight(&command, true);
                    let expected_toolchains: Vec<String> = toolchain
                        .into_iter()
                        .map(|value| value.to_string())
                        .collect();
                    assert!(result.is_compilation, "{command}");
                    assert!(result.required.needs_cargo, "{command}");
                    assert_eq!(result.family.as_deref(), Some(family), "{command}");
                    assert_eq!(
                        result.required.needs_targets,
                        vec![target.to_string()],
                        "{command}"
                    );
                    assert_eq!(
                        result.required.needs_toolchains, expected_toolchains,
                        "{command}"
                    );
                    assert_eq!(result.required.needs_os, None, "{command}");
                    assert_eq!(required_os_for_command(&command), None, "{command}");
                    let requirement = result.required.to_requirement(1);
                    assert!(requirement.needs_cargo, "{command}");
                    assert_eq!(requirement.min_protocol, 1, "{command}");
                    assert_eq!(
                        requirement.needs_targets, result.required.needs_targets,
                        "{command}"
                    );
                    assert_eq!(
                        requirement.needs_toolchains, result.required.needs_toolchains,
                        "{command}"
                    );
                    assert_eq!(requirement.needs_os, None, "{command}");
                }
            }
        }
    }

    #[test]
    fn cargo_xwin_does_not_relax_other_commands_or_apple_targets() {
        for command in [
            "cargo check --target x86_64-pc-windows-msvc",
            "cargo clippy --target x86_64-pc-windows-msvc -- -D warnings",
            "cargo xwin build --target x86_64-pc-windows-msvc && cargo build --target x86_64-pc-windows-msvc",
            "cargo xwin check --target x86_64-pc-windows-msvc && cargo check --target x86_64-pc-windows-msvc",
            "cargo xwin clippy --target x86_64-pc-windows-msvc && cargo clippy --target x86_64-pc-windows-msvc",
            "cargo --config xwin build --target x86_64-pc-windows-msvc",
            "cargo --config xwin check --target x86_64-pc-windows-msvc",
            "cargo --config xwin clippy --target x86_64-pc-windows-msvc",
            "cargo build --manifest-path cargo-xwin --target x86_64-pc-windows-msvc",
            "cargo check --manifest-path 'cargo xwin check' --target x86_64-pc-windows-msvc",
            "cargo clippy --config 'alias.cross=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 check --target aarch64-apple-darwin",
            "cargo xwin clippy --target aarch64-apple-darwin",
            "cargo-xwin check --target aarch64-apple-darwin",
            "cargo-xwin xwin clippy --target aarch64-apple-darwin",
            "cargo xwin build --target x86_64-pc-windows-msvc && cargo build --target aarch64-apple-darwin",
            "cargo xwin check --target x86_64-pc-windows-msvc && cargo check --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 native_apple_jobs_require_darwin_without_rust_target_flags() {
        for command in [
            "xcodebuild -version",
            "/usr/bin/xcodebuild -project ios/App.xcodeproj -scheme App build",
            "'xcodebuild' -scheme App test",
            "'/Applications/Xcode Beta.app/Contents/Developer/usr/bin/xcodebuild' -version",
            "env DEVELOPER_DIR='/Applications/Xcode Beta.app' xcodebuild -jobs 1 test",
            "timeout 1200 xcodebuild -destination 'platform=macOS,variant=Mac Catalyst' test",
            "xcrun --sdk iphoneos xcodebuild -scheme App build",
            "/usr/bin/xcrun --find swift",
            "cd ios && xcodebuild -scheme App build",
        ] {
            assert_eq!(
                required_os_for_command(command).as_deref(),
                Some("darwin"),
                "{command}"
            );
            let job = preflight(command, true).as_job(Vec::new());
            assert_eq!(
                job.required.needs_os.as_deref(),
                Some("darwin"),
                "{command}"
            );
            assert!(
                job.required.needs_targets.is_empty(),
                "not a Rust target: {command}"
            );
            assert!(!job.required.needs_cargo, "not a Cargo job: {command}");
        }
    }

    #[test]
    fn native_apple_job_inference_does_not_claim_mentions_or_opaque_scripts() {
        for command in [
            "echo xcodebuild -version",
            "printf '%s' 'xcrun --sdk macosx'",
            "br comments add bd-example 'xcodebuild -scheme App build'",
            "env NOTE=xcodebuild bun test",
            "env -u xcodebuild bun test",
            "xcodebuild-wrapper -scheme App build",
            "./check.sh --target aarch64-apple-darwin",
            "bash -c 'echo xcodebuild'",
            "bash -c 'xcodebuild -version'",
            "'xcodebuild -version'",
            "\"${TOOL}/xcodebuild\" -version",
            "'unterminated/xcodebuild -version",
        ] {
            assert_eq!(required_os_for_command(command), None, "{command}");
            assert_eq!(
                preflight(command, true)
                    .as_job(Vec::new())
                    .required
                    .needs_os,
                None,
                "{command}"
            );
        }
        assert_eq!(
            required_os_for_command(
                "xcodebuild build && cargo build --target x86_64-pc-windows-msvc"
            ),
            None,
            "mixed native host requirements must not inherit just the Rust half"
        );
    }

    #[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);
    }
}