rch 2.1.25

Remote Compilation Helper - PreToolUse hook CLI
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
//! Named Cargo binary/example retrieval without unrelated pooled build outputs.
//!
//! This is an optimization of the existing retrieval policy, not a proof of
//! output completeness. Only literal `cargo build --bin/--example` selections
//! narrow retrieval. The shared parser also identifies explicit named test and
//! benchmark executables under `--no-run` for the completed-output contract;
//! their transfer policy still comes from the ordinary build-only path.
//! Unknown flags, shell expansion, other target kinds, response files and
//! custom target specifications retain the broad policy.

use rch_common::CompilationKind;
use std::collections::BTreeSet;
use std::path::Path;

/// One bounded parse shared by the transfer optimization and the required
/// output capture. The latter must never guess selectors from the globs.
pub(in crate::hook) struct NamedCargoSelection {
    pub(in crate::hook) bins: BTreeSet<String>,
    pub(in crate::hook) examples: BTreeSet<String>,
    pub(in crate::hook) tests: BTreeSet<String>,
    pub(in crate::hook) benches: BTreeSet<String>,
    pub(in crate::hook) message_formats: Vec<String>,
    targets: BTreeSet<String>,
    profile: String,
}

pub(in crate::hook) fn selection(
    kind: Option<CompilationKind>,
    command: &str,
) -> Option<NamedCargoSelection> {
    let kind = kind?;
    let args = build_arguments(kind, command)?;
    let mut bins = BTreeSet::new();
    let mut examples = BTreeSet::new();
    let mut tests = BTreeSet::new();
    let mut benches = BTreeSet::new();
    let mut no_run = false;
    let mut targets = BTreeSet::new();
    let mut message_formats = Vec::new();
    let mut profile = None;
    let mut iter = args.iter().map(String::as_str);
    while let Some(arg) = iter.next() {
        let (flag, inline) = arg
            .split_once('=')
            .map_or((arg, None), |(k, v)| (k, Some(v)));
        match flag {
            "--bin" | "--example" if kind == CompilationKind::CargoBuild => {
                let name = inline.or_else(|| iter.next())?;
                if !component(name) {
                    return None;
                }
                if flag == "--bin" {
                    bins.insert(name);
                } else {
                    examples.insert(name);
                }
            }
            "--test" if kind == CompilationKind::CargoTest => {
                let name = inline.or_else(|| iter.next())?;
                if !component(name) {
                    return None;
                }
                tests.insert(name);
            }
            "--bench" if kind == CompilationKind::CargoBench => {
                let name = inline.or_else(|| iter.next())?;
                if !component(name) {
                    return None;
                }
                benches.insert(name);
            }
            "--no-run" if kind != CompilationKind::CargoBuild && inline.is_none() => {
                no_run = true;
            }
            "--target" => {
                let target = inline.or_else(|| iter.next())?;
                // Cargo substitutes host-tuple at runtime; it is not a directory.
                if !component(target) || target == "host-tuple" {
                    return None;
                }
                targets.insert(target);
            }
            "--profile" => {
                let value = inline.or_else(|| iter.next())?;
                let dir = match value {
                    "dev" | "test" => "debug",
                    "release" | "bench" => "release",
                    value if component(value) => value,
                    _ => return None,
                };
                set_profile(&mut profile, dir)?;
            }
            "--release" | "-r" if inline.is_none() => {
                set_profile(&mut profile, "release")?;
            }
            "--message-format" => {
                let value = inline.or_else(|| iter.next())?;
                if value.is_empty() || value.starts_with('-') {
                    return None;
                }
                message_formats.push(value);
            }
            "--package" | "-p" | "--exclude" | "--jobs" | "-j" | "--features" | "-F"
            | "--color" | "--manifest-path" | "--target-dir" => {
                // Consume opaque option values exactly once, never as selectors.
                let value = inline.or_else(|| iter.next())?;
                if value.is_empty() || value.starts_with('-') {
                    return None;
                }
            }
            "--workspace"
            | "--all"
            | "--all-features"
            | "--no-default-features"
            | "--locked"
            | "--frozen"
            | "--offline"
            | "--keep-going"
            | "--verbose"
            | "--quiet"
            | "-v"
            | "-vv"
            | "-q"
                if inline.is_none() => {}
            _ if inline.is_none()
                && ["-p", "-j", "-F"]
                    .iter()
                    .any(|prefix| arg.starts_with(*prefix) && arg.len() > prefix.len()) => {}
            // Includes --bins/--examples/--lib/--all-targets and test selectors,
            // --timings, --config, -Z, output-dir overrides and `--` passthrough.
            _ => return None,
        }
    }
    if bins.is_empty() && examples.is_empty() && tests.is_empty() && benches.is_empty() {
        return None;
    }
    // Executing tests/benches produces a result stream, not caller-owned
    // executables. Only Cargo's own --no-run can enable output capture; a
    // similarly named test-program argument after `--` never reaches here.
    if kind != CompilationKind::CargoBuild && !no_run {
        return None;
    }
    Some(NamedCargoSelection {
        bins: bins.into_iter().map(str::to_string).collect(),
        examples: examples.into_iter().map(str::to_string).collect(),
        tests: tests.into_iter().map(str::to_string).collect(),
        benches: benches.into_iter().map(str::to_string).collect(),
        message_formats: message_formats.into_iter().map(str::to_string).collect(),
        targets: targets.into_iter().map(str::to_string).collect(),
        profile: profile.unwrap_or("debug").to_owned(),
    })
}

/// Return project-root patterns; the caller rebases them for custom target dirs.
pub(super) fn patterns(
    kind: Option<CompilationKind>,
    command: Option<&str>,
) -> Option<Vec<String>> {
    if kind != Some(CompilationKind::CargoBuild) {
        return None;
    }
    let NamedCargoSelection {
        bins,
        examples,
        targets,
        profile,
        ..
    } = selection(kind, command?)?;
    let roots: Vec<String> = if targets.is_empty() {
        // Configuration/environment can choose a target even without --target.
        vec![format!("target/{profile}"), format!("target/*/{profile}")]
    } else {
        targets
            .into_iter()
            .map(|target| format!("target/{target}/{profile}"))
            .collect()
    };
    let mut selected = BTreeSet::new();
    for root in roots {
        for name in &bins {
            add_named_output(&mut selected, &root, name);
        }
        let example_root = format!("{root}/examples");
        for name in &examples {
            // Examples may be bin, rlib, staticlib, cdylib or dylib targets.
            // Keep both executable spelling and normalized crate/library names
            // rather than assuming that every example has a main function.
            let crate_name = name.replace('-', "_");
            for stem in [
                (*name).to_owned(),
                crate_name.clone(),
                format!("lib{crate_name}"),
            ] {
                add_named_output(&mut selected, &example_root, &stem);
            }
        }
        // A linked binary may still need dynamic dependencies. Preserve these
        // and split-debug data, but not dependency rlibs/rmeta/object caches or
        // other hashed executables from the shared target pool.
        let mut runtime_dirs = vec![root.clone(), format!("{root}/deps")];
        if !examples.is_empty() {
            runtime_dirs.push(example_root);
        }
        for directory in runtime_dirs {
            for suffix in ["so", "so.*", "dylib", "dll", "pdb", "dwo", "dwp"] {
                selected.insert(format!("{directory}/*.{suffix}"));
            }
            selected.insert(format!("{directory}/*.dSYM/**"));
        }
    }
    Some(selected.into_iter().collect())
}

/// Platform extensions and sidecar bundles, but not unrelated name prefixes.
fn add_named_output(selected: &mut BTreeSet<String>, directory: &str, name: &str) {
    selected.insert(format!("{directory}/{name}"));
    selected.insert(format!("{directory}/{name}.*"));
    selected.insert(format!("{directory}/{name}.*/**"));
}

fn set_profile<'a>(profile: &mut Option<&'a str>, value: &'a str) -> Option<()> {
    if profile.is_some_and(|previous| previous != value) {
        return None;
    }
    *profile = Some(value);
    Some(())
}

/// No path separators, glob operators, traversal, suffixes or filter syntax.
fn component(value: &str) -> bool {
    !value.is_empty()
        && !value.starts_with('-')
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}

/// Reuse the managed Cargo parser's literal-shell validation and decoding.
/// `rch exec` reconstructs argv with shell_words::join, so even an ordinary
/// manifest/target path containing spaces or quotes reaches this policy quoted.
/// Splitting that string on whitespace either lost the argument boundary or
/// disabled the required-output contract entirely. Only decoded literal words
/// may select outputs; this remains narrower than the managed execution grammar.
fn build_arguments(kind: CompilationKind, command: &str) -> Option<Vec<String>> {
    if command.len() > 65_536
        || command.chars().any(|ch| ch.is_control() && ch != '\t')
        // Comments could swallow appended instrumentation; brace syntax is
        // shell-dependent. Neither spelling belongs to this bounded subset,
        // including quoted occurrences. Do not silently reinterpret either.
        || command.contains(['#', '{', '}'])
    {
        return None;
    }
    let (tokens, _) =
        crate::hook::cargo_target_dir::managed_clean_overlay_cargo_tokens(command).ok()?;
    if tokens.len() > 4096 || tokens.iter().any(|word| word.chars().any(char::is_control)) {
        return None;
    }
    // Keep the original wrapper allowlist below: using the shared lexer does
    // not admit chdir, arbitrary wrappers, or a different Cargo subcommand.
    let words: Vec<_> = tokens.iter().map(String::as_str).collect();
    let mut index = 0;
    let mut standalone_xwin = false;
    loop {
        while words.get(index).is_some_and(|word| {
            word.split_once('=')
                .is_some_and(|(key, _)| rch_common::ssh_utils::is_valid_env_key(key))
        }) {
            index += 1;
        }
        let executable = Path::new(words.get(index)?).file_name()?.to_str()?;
        match executable.strip_suffix(".exe").unwrap_or(executable) {
            "cargo" => break,
            "cargo-xwin" if kind == CompilationKind::CargoBuild => {
                standalone_xwin = true;
                break;
            }
            "env" => {
                index += 1;
                while let Some(word) = words.get(index) {
                    match *word {
                        "--" => {
                            index += 1;
                            break;
                        }
                        "-i" | "--ignore-environment" => index += 1,
                        "-u" | "--unset" => {
                            let key = words.get(index + 1)?;
                            if !rch_common::ssh_utils::is_valid_env_key(key) {
                                return None;
                            }
                            index += 2;
                        }
                        _ if word.starts_with("--unset=") => {
                            if !rch_common::ssh_utils::is_valid_env_key(&word[8..]) {
                                return None;
                            }
                            index += 1;
                        }
                        _ if word.starts_with('-') => return None,
                        _ => break,
                    }
                }
            }
            "rustup" => {
                if words.get(index + 1) != Some(&"run") {
                    return None;
                }
                let channel = words.get(index + 2)?;
                if channel.is_empty() || channel.starts_with('-') {
                    return None;
                }
                index += 3;
            }
            _ => return None,
        }
    }
    index += 1;
    if !standalone_xwin && words.get(index).is_some_and(|word| word.starts_with('+')) {
        index += 1;
    }
    // Keep the plugin invocation intact for execution; only parse the Cargo
    // build options after its explicit verb for named-output custody.
    let plugin = words.get(index) == Some(&"xwin");
    if kind == CompilationKind::CargoBuild && plugin {
        index += 1;
    }
    let subcommand = words.get(index).copied()?;
    if (standalone_xwin || plugin) && subcommand != "build" {
        return None;
    }
    if !matches!(
        (kind, subcommand),
        (CompilationKind::CargoBuild, "build" | "b")
            | (CompilationKind::CargoTest, "test" | "t")
            | (CompilationKind::CargoBench, "bench")
    ) {
        return None;
    }
    Some(tokens.into_iter().skip(index + 1).collect())
}

#[cfg(test)]
mod quoted_tests;

#[cfg(test)]
mod tests {
    use super::super::{get_custom_target_artifact_patterns, get_project_artifact_patterns};
    use super::*;

    fn select(command: &str) -> Option<Vec<String>> {
        patterns(Some(CompilationKind::CargoBuild), Some(command))
    }

    #[test]
    fn explicit_bins_select_only_the_requested_profile_and_names() {
        let selected = select("cargo build --release --bin rch --bin=rchd --bin rch").unwrap();
        for expected in [
            "target/release/rch",
            "target/release/rchd",
            "target/*/release/rch",
            "target/release/rch.*",
            "target/release/rch.*/**",
            "target/release/deps/*.so",
            "target/release/deps/*.dwo",
        ] {
            assert!(
                selected.iter().any(|pattern| pattern == expected),
                "{expected}"
            );
        }
        assert!(!selected.iter().any(|pattern| pattern.contains("debug")));
        assert!(
            !selected
                .iter()
                .any(|pattern| pattern.ends_with("release/**"))
        );
        assert!(!selected.iter().any(|pattern| pattern.ends_with("deps/**")));
        assert_eq!(
            selected
                .iter()
                .filter(|p| *p == "target/release/rch")
                .count(),
            1
        );
    }

    #[test]
    fn wrappers_profiles_targets_and_opaque_arguments_are_resolved() {
        for command in [
            "CARGO_TARGET_DIR=/tmp/out cargo +nightly build --bin app --profile small --target x86_64-unknown-linux-gnu",
            "env -u RUSTFLAGS -- rustup run nightly /usr/bin/cargo b --bin=app --profile=small --target=x86_64-unknown-linux-gnu",
        ] {
            let selected = select(command).unwrap();
            assert!(selected.contains(&"target/x86_64-unknown-linux-gnu/small/app".into()));
            assert!(
                selected
                    .iter()
                    .all(|p| p.starts_with("target/x86_64-unknown-linux-gnu/small/"))
            );
        }
        assert!(select("cargo build --package --bin app").is_none());
        assert!(select("cargo build --features=--bin=decoy").is_none());
        assert!(
            select("cargo build --bin app --profile dev")
                .unwrap()
                .contains(&"target/debug/app".into())
        );
        assert!(
            select("cargo build --bin app --target a --target b")
                .unwrap()
                .contains(&"target/b/debug/app".into())
        );
    }

    #[test]
    fn xwin_builds_keep_named_output_target_and_profile_custody() {
        for command in [
            "cargo xwin build --locked --release --target x86_64-pc-windows-msvc --bin app",
            "cargo +nightly xwin build --release --target=x86_64-pc-windows-msvc --bin=app",
            "cargo-xwin build --release --target x86_64-pc-windows-msvc --bin app",
            "env CARGO_HOME=/opt/cargo cargo-xwin xwin build --release --target x86_64-pc-windows-msvc --bin app",
        ] {
            let selected = select(command).unwrap();
            assert!(selected.contains(&"target/x86_64-pc-windows-msvc/release/app".to_owned()));
            assert!(
                selected
                    .iter()
                    .all(|path| path.starts_with("target/x86_64-pc-windows-msvc/release/"))
            );
            assert!(!selected.iter().any(|path| path.ends_with("release/**")));
        }
        for command in [
            "cargo xwin check --bin app",
            "cargo-xwin install --bin app",
            "cargo xwin b --bin app",
            "cargo xwin build --bin app --help",
            "cargo xwin build --bin app; cargo build --bin other",
        ] {
            assert!(
                select(command).is_none(),
                "accepted unsupported plugin command {command}"
            );
        }
    }

    #[test]
    fn ambiguous_or_additional_outputs_retain_the_broad_policy() {
        for command in [
            "cargo build",
            "cargo build --bins",
            "cargo build --bin app --lib",
            "cargo build --bin app --examples",
            "cargo build --bin app --all-targets",
            "cargo build --bin app --timings",
            "cargo build --bin app --config foo.toml",
            "cargo build --bin app -Z unstable-options",
            "cargo build --bin app --out-dir out",
            "cargo test --no-run --bin app",
            "cargo rustc --bin app -- --emit asm",
            "cargo build --bin app --target custom.json",
            "cargo build --bin app --target host-tuple",
            "cargo build --bin app --profile ../source",
            "cargo build --bin ../app",
            "cargo build --bin app --release --profile dev",
            "cargo build --bin app --profile",
            "cargo build --bin app --unknown",
            "cargo build --bin app --",
            "cargo build --bin 'app*'",
            "cargo build --bin $APP",
            "cargo build --bin app; echo x",
            "env -C other cargo build --bin app",
            "sh -c cargo build --bin app",
        ] {
            assert!(
                select(command).is_none(),
                "narrowed ambiguous command: {command}"
            );
        }
        assert!(
            patterns(
                Some(CompilationKind::CargoDoc),
                Some("cargo build --bin app")
            )
            .is_none()
        );
    }

    #[test]
    fn both_live_retrieval_bases_use_the_selection() {
        let kind = Some(CompilationKind::CargoBuild);
        let command = Some("cargo build --bin app --profile lean");
        let project = get_project_artifact_patterns(kind, command, false);
        assert_eq!(project, patterns(kind, command).unwrap());
        assert!(get_project_artifact_patterns(kind, command, true).is_empty());
        let custom = get_custom_target_artifact_patterns(kind, command);
        for pattern in &project {
            assert!(custom.contains(&pattern.strip_prefix("target/").unwrap().to_owned()));
        }
        assert!(!custom.iter().any(|p| p == "lean/**" || p == "debug/**"));
    }

    #[test]
    fn named_examples_preserve_executable_and_library_forms_in_mixed_requests() {
        for command in [
            "cargo build --example demo-lib --profile lean",
            "cargo build --bin app --example=demo-lib --profile=lean",
        ] {
            let selected = select(command).unwrap();
            for expected in [
                "target/lean/examples/demo-lib",
                "target/lean/examples/demo_lib.*",
                "target/lean/examples/libdemo_lib.*",
                "target/*/lean/examples/libdemo_lib.*",
                "target/lean/examples/demo-lib.*/**",
                "target/lean/deps/*.so",
            ] {
                assert!(
                    selected.iter().any(|pattern| pattern == expected),
                    "{expected}"
                );
            }
            assert!(!selected.iter().any(|p| p.ends_with("examples/**")));
            let kind = Some(CompilationKind::CargoBuild);
            assert!(get_project_artifact_patterns(kind, Some(command), true).is_empty());
            let custom = get_custom_target_artifact_patterns(kind, Some(command));
            assert!(custom.contains(&"lean/examples/libdemo_lib.*".to_owned()));
        }
        let mixed = select("cargo build --bin app --example demo").unwrap();
        assert!(mixed.contains(&"target/debug/app".to_owned()));
        assert!(mixed.contains(&"target/debug/examples/demo".to_owned()));
        for command in [
            "cargo build --example demo --examples",
            "cargo build --example demo --lib",
            "cargo build --example demo --test integration",
            "cargo build --example ../demo",
            "cargo build --example demo --bin app --all-targets",
        ] {
            assert!(select(command).is_none(), "{command}");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn real_rsync_keeps_outputs_sidecars_and_runtime_libraries_not_pool_residue() {
        use std::process::Stdio;
        use std::time::Duration;
        use tokio::process::Command;

        for (forwarded, example) in [(false, false), (true, false), (false, true), (true, true)] {
            let root = tempfile::tempdir().unwrap();
            let source = root.path().join("worker");
            let destination = root.path().join("local");
            let prefix = if forwarded { "lean" } else { "target/lean" };
            let mut keep = vec![
                "app",
                "app.exe",
                "app.pdb",
                "app.dSYM/Contents/Resources/DWARF/app",
                "deps/libneeded.so",
                "deps/libneeded.so.1",
                "deps/libneeded.dylib",
                "deps/needed.dll",
                "deps/split.dwo",
            ];
            if example {
                keep.extend([
                    "examples/demo-lib",
                    "examples/demo_lib.exe",
                    "examples/libdemo_lib.a",
                    "examples/demo_lib.lib",
                    "examples/libdemo_lib.rlib",
                    "examples/libdemo_lib.so",
                    "examples/demo-lib.dSYM/Contents/Info.plist",
                ]);
            }
            let omit = [
                "other",
                "app-helper",
                "deps/app-deadbeef",
                "deps/libhuge.rlib",
                "incremental/state",
                ".fingerprint/state",
                "build/state",
                "examples/other",
            ];
            for relative in keep.iter().chain(omit.iter()) {
                let path = source.join(prefix).join(relative);
                std::fs::create_dir_all(path.parent().unwrap()).unwrap();
                std::fs::write(path, format!("fresh {relative}\n")).unwrap();
            }
            std::fs::create_dir_all(destination.join(prefix)).unwrap();
            std::fs::write(destination.join(prefix).join("app"), b"stale executable\n").unwrap();
            std::fs::write(destination.join("source.rs"), b"local source sentinel\n").unwrap();
            std::fs::write(source.join("source.rs"), b"foreign source\n").unwrap();
            let kind = Some(CompilationKind::CargoBuild);
            let command = Some(if example {
                "cargo build --bin app --example demo-lib --profile lean"
            } else {
                "cargo build --bin app --profile lean"
            });
            let selected = if forwarded {
                get_custom_target_artifact_patterns(kind, command)
            } else {
                get_project_artifact_patterns(kind, command, false)
            };
            for _ in 0..2 {
                let mut copy = Command::new("rsync");
                copy.args(["-a", "--checksum", "--safe-links", "--prune-empty-dirs"]);
                for rule in &selected {
                    if let Some(exclude) = rule.strip_prefix("- ") {
                        copy.arg(format!("--exclude={exclude}"));
                    }
                }
                copy.arg("--include=*/");
                for rule in &selected {
                    if !rule.starts_with("- ") {
                        copy.arg(format!("--include=/{rule}"));
                    }
                }
                copy.arg("--exclude=*")
                    .arg(format!("{}/", source.display()))
                    .arg(format!("{}/", destination.display()))
                    .stdin(Stdio::null())
                    .kill_on_drop(true);
                let copied = tokio::time::timeout(Duration::from_secs(10), copy.output())
                    .await
                    .expect("owned rsync fixture timed out")
                    .expect("rsync is required");
                assert!(copied.status.success(), "{copied:?}");
                for relative in &keep {
                    assert_eq!(
                        std::fs::read(destination.join(prefix).join(relative)).unwrap(),
                        std::fs::read(source.join(prefix).join(relative)).unwrap(),
                        "{relative}"
                    );
                }
                for relative in omit {
                    assert!(
                        !destination.join(prefix).join(relative).exists(),
                        "copied {relative}"
                    );
                }
                assert_eq!(
                    std::fs::read(destination.join("source.rs")).unwrap(),
                    b"local source sentinel\n"
                );
            }
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn real_cargo_selected_bins_and_library_examples_round_trip() {
        use crate::hook::cargo_output_contract::CargoOutputCapture;
        use crate::hook::transfer_orchestration::recovery::assert_cargo_fixture_publication;
        use std::process::Stdio;
        use std::time::Duration;
        use tokio::process::Command;

        for forwarded in [false, true] {
            let root = tempfile::tempdir().unwrap();
            let source = root.path().join("source λ with ' quote");
            let local = root.path().join("local λ with ' quote");
            std::fs::create_dir_all(source.join("src")).unwrap();
            std::fs::create_dir_all(source.join("examples")).unwrap();
            std::fs::create_dir_all(&local).unwrap();
            std::fs::write(source.join("Cargo.toml"), concat!(
                "[package]\nname = \"rch_selected_fixture\"\nversion = \"0.0.0\"\nedition = \"2024\"\n",
                "[workspace]\n",
                "[[bin]]\nname = \"app\"\npath = \"src/main.rs\"\n",
                "[[bin]]\nname = \"helper\"\npath = \"src/helper.rs\"\n",
                "[[example]]\nname = \"demo\"\npath = \"examples/demo.rs\"\n",
                "[[example]]\nname = \"demo-lib\"\npath = \"examples/library.rs\"\ncrate-type = [\"staticlib\"]\n",
                "[profile.lean]\ninherits = \"dev\"\ndebug = 0\n",
            )).unwrap();
            std::fs::write(
                source.join("src/main.rs"),
                "fn main() { println!(\"selected app\"); }\n",
            )
            .unwrap();
            std::fs::write(
                source.join("src/helper.rs"),
                "fn main() { println!(\"selected helper\"); }\n",
            )
            .unwrap();
            std::fs::write(
                source.join("examples/demo.rs"),
                "fn main() { println!(\"selected example\"); }\n",
            )
            .unwrap();
            std::fs::write(
                source.join("examples/library.rs"),
                "pub fn answer() -> u32 { 42 }\n",
            )
            .unwrap();
            let remote_target = if forwarded {
                root.path().join("worker target λ with ' quote")
            } else {
                source.join("target")
            };
            let manifest = source.join("Cargo.toml");
            let manifest_arg = shell_words::join([manifest.to_str().unwrap()]);
            let command_storage = format!(
                "cargo build --bin app --bin helper --example demo --example demo-lib --profile lean --offline --jobs=1 --manifest-path {manifest_arg}"
            );
            let command_text = command_storage.as_str();
            let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
            let mut compile = Command::new(&cargo);
            compile
                .current_dir(&source)
                .args(
                    shell_words::split(command_text)
                        .unwrap()
                        .into_iter()
                        .skip(1),
                )
                .arg("--message-format=json")
                .env("CARGO_HOME", root.path().join("cargo-home"))
                .env("CARGO_TARGET_DIR", &remote_target)
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTFLAGS")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("CARGO_BUILD_TARGET")
                .env_remove("CARGO_BUILD_TARGET_DIR")
                .env_remove("CARGO_BUILD_BUILD_DIR")
                .env_remove("CARGO_MAKEFLAGS")
                .env_remove("MAKEFLAGS")
                .stdin(Stdio::null())
                .kill_on_drop(true);
            let built = tokio::time::timeout(Duration::from_secs(90), compile.output())
                .await
                .expect("owned Cargo fixture timed out")
                .expect("Cargo is required");
            assert!(
                built.status.success(),
                "{}",
                String::from_utf8_lossy(&built.stderr)
            );
            let stdout = String::from_utf8(built.stdout).unwrap();
            let artifacts: Vec<serde_json::Value> = stdout
                .lines()
                .filter_map(|line| serde_json::from_str(line).ok())
                .filter(|message: &serde_json::Value| message["reason"] == "compiler-artifact")
                .collect();
            assert_eq!(
                artifacts.len(),
                4,
                "fixture must compile two bins and two examples"
            );
            let files: Vec<std::path::PathBuf> = artifacts
                .iter()
                .flat_map(|message| message["filenames"].as_array().unwrap())
                .map(|filename| filename.as_str().unwrap().into())
                .collect();
            assert!(
                files
                    .iter()
                    .any(|p| p.file_name().unwrap() == "libdemo_lib.a")
            );
            let remote_basis = if forwarded { &remote_target } else { &source };
            // The mixed binary/library-example invocation above keeps the
            // existing selection policy. Exercise the required executable
            // contract with a second, warm, named-binary invocation in the
            // same real Cargo tree (no second compilation fixture).
            assert!(
                CargoOutputCapture::for_command(Some(CompilationKind::CargoBuild), command_text)
                    .is_none()
            );
            let binary_storage = format!(
                "cargo build --bin app --bin helper --profile lean --offline --jobs=1 --manifest-path {manifest_arg}"
            );
            let binary_command = binary_storage.as_str();
            let capture =
                CargoOutputCapture::for_command(Some(CompilationKind::CargoBuild), binary_command)
                    .unwrap();
            let instrumented = capture.execution_command(binary_command);
            let mut binaries = Command::new(&cargo);
            binaries
                .current_dir(&source)
                .args(
                    shell_words::split(&instrumented)
                        .unwrap()
                        .into_iter()
                        .skip(1),
                )
                .stdin(Stdio::null())
                .kill_on_drop(true);
            for (key, value) in compile.as_std().get_envs() {
                if let Some(value) = value {
                    binaries.env(key, value);
                } else {
                    binaries.env_remove(key);
                }
            }
            let binary_output = tokio::time::timeout(Duration::from_secs(90), binaries.output())
                .await
                .expect("owned named-binary Cargo fixture timed out")
                .expect("Cargo is required");
            assert!(
                binary_output.status.success(),
                "{}",
                String::from_utf8_lossy(&binary_output.stderr)
            );
            let contract = capture
                .parse_receipt(&binary_output.stdout, remote_basis)
                .unwrap();
            assert_eq!(contract.required_files.len(), 2);
            assert_cargo_fixture_publication(
                CompilationKind::CargoBuild,
                binary_command,
                &binary_output.stdout,
                remote_basis,
                forwarded,
            )
            .await;
            for path in &files {
                let destination = local.join(path.strip_prefix(remote_basis).unwrap());
                std::fs::create_dir_all(destination.parent().unwrap()).unwrap();
                std::fs::write(destination, b"stale artifact\n").unwrap();
            }
            std::fs::write(
                remote_target.join("lean/not_requested"),
                b"pooled residue\n",
            )
            .unwrap();
            let kind = Some(CompilationKind::CargoBuild);
            let selected = if forwarded {
                get_custom_target_artifact_patterns(kind, Some(command_text))
            } else {
                get_project_artifact_patterns(kind, Some(command_text), false)
            };
            assert!(!selected.iter().any(|p| p.ends_with("lean/**")));
            let mut copy = Command::new("rsync");
            copy.args(["-a", "--checksum", "--safe-links", "--prune-empty-dirs"]);
            for rule in &selected {
                if let Some(exclude) = rule.strip_prefix("- ") {
                    copy.arg(format!("--exclude={exclude}"));
                }
            }
            copy.arg("--include=*/");
            for rule in &selected {
                if !rule.starts_with("- ") {
                    copy.arg(format!("--include=/{rule}"));
                }
            }
            copy.arg("--exclude=*")
                .arg(format!("{}/", remote_basis.display()))
                .arg(format!("{}/", local.display()))
                .stdin(Stdio::null())
                .kill_on_drop(true);
            let copied = tokio::time::timeout(Duration::from_secs(15), copy.output())
                .await
                .expect("owned rsync fixture timed out")
                .expect("rsync is required");
            assert!(copied.status.success(), "{copied:?}");
            for path in files {
                let destination = local.join(path.strip_prefix(remote_basis).unwrap());
                assert_eq!(
                    std::fs::read(&destination).unwrap(),
                    std::fs::read(&path).unwrap(),
                    "{}",
                    path.display()
                );
            }
            let residue = remote_target.join("lean/not_requested");
            assert!(
                !local
                    .join(residue.strip_prefix(remote_basis).unwrap())
                    .exists()
            );
            for artifact in artifacts {
                if let Some(executable) = artifact["executable"].as_str() {
                    let executable =
                        local.join(Path::new(executable).strip_prefix(remote_basis).unwrap());
                    let mut run = Command::new(executable);
                    run.stdin(Stdio::null()).kill_on_drop(true);
                    let ran = tokio::time::timeout(Duration::from_secs(10), run.output())
                        .await
                        .expect("returned executable timed out")
                        .unwrap();
                    assert!(ran.status.success(), "{ran:?}");
                    assert!(String::from_utf8_lossy(&ran.stdout).contains("selected"));
                }
            }
        }
    }
}