flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
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
//! Launcher build failure boundaries, injected through Cargo's documented subprocess outputs.
#![cfg(unix)]
mod common;
use flow_start::Spawn as _;
use flow_toolkit::Json;
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use tempfile::TempDir;

struct Fixture {
    files: TempDir,
    source: PathBuf,
    executable: PathBuf,
    bin: PathBuf,
}
fn quoted(text: &str) -> String {
    format!("'{}'", text.replace('\'', "'\"'\"'"))
}
fn script(path: &Path, source: &str) {
    flow_testing::write_executable(path, source, 0o755).expect("the fixture script is written");
}
fn object(fields: Vec<(&str, Json)>) -> Json {
    Json::Object(
        fields
            .into_iter()
            .map(|(key, value)| (key.into(), value))
            .collect(),
    )
}
fn text(path: &Path) -> Json {
    Json::String(path.to_str().expect("fixture paths are UTF-8").into())
}
/// The fixture launcher's one contract module, its root module, as the
/// host prints the contract it writes, [`common::echo_contract`].
const CONTRACT: &str = "// Generated by flow build from rust module fixture. Do not edit.\n\npub flow echo(value: Text) -> Result<Text, Text>\n";

fn descriptor_command(case: &str, source: &Path) -> String {
    if case == "descriptor-exit" {
        "printf '%s\\n' 'fixture descriptor failed' >&2; exit 8".into()
    } else if case == "source-race" {
        format!(
            "printf '%s\\n' '#[tool] pub fn echo() {{}} // changed during build' > {}; printf '{}' > \"$5\"",
            quoted(source.to_str().expect("fixture paths are UTF-8")),
            common::printf_format(&common::echo_contract())
        )
    } else {
        format!(
            "if [ \"$1\" = serve ]; then printf 'serving %s\\n' \"$3\"; exit 0; fi; printf '{}' > \"$5\"",
            common::printf_format(&common::echo_contract())
        )
    }
}
fn cargo_script(case: &str, metadata: &str, artifact: &str, dependencies: &str) -> String {
    let metadata_command = if case == "metadata-exit" {
        "printf '%s\\n' 'fixture metadata failed' >&2; exit 7".into()
    } else {
        format!("printf '%s\\n' {}", quoted(metadata))
    };
    let metadata_command = if case == "cargo-disappears-after-metadata" {
        format!("{metadata_command}\n/bin/rm -- \"$0\"")
    } else {
        metadata_command
    };
    let build_command = if case == "build-exit" {
        "printf '%s\\n' 'fixture build failed' >&2; exit 9".into()
    } else {
        format!("{dependencies}\nprintf '%s\\n' {}", quoted(artifact))
    };
    format!(
        "#!/bin/sh\nif [ \"$1\" = metadata ]; then\n{metadata_command}\nelse\n{build_command}\nfi\n"
    )
}

fn metadata_package(id: &str, manifest: Option<&Path>) -> Json {
    let (name, version) = id
        .rsplit_once('#')
        .expect("the id has the form name#package@version")
        .1
        .rsplit_once('@')
        .expect("the id has the form name#package@version");
    let mut fields = vec![
        ("id", Json::String(id.into())),
        ("name", Json::String(name.into())),
        ("version", Json::String(version.into())),
        ("source", Json::Null),
    ];
    if let Some(manifest) = manifest {
        fields.push(("manifest_path", text(manifest)));
    }
    object(fields)
}

fn metadata_node(id: &str, dependencies: &[&str]) -> Json {
    let dependencies = dependencies
        .iter()
        .map(|id| {
            object(vec![
                ("pkg", Json::String((*id).into())),
                (
                    "dep_kinds",
                    Json::Array(vec![object(vec![
                        ("kind", Json::Null),
                        ("target", Json::Null),
                    ])]),
                ),
            ])
        })
        .collect();
    object(vec![
        ("id", Json::String(id.into())),
        ("deps", Json::Array(dependencies)),
    ])
}

fn resolved_sdk_metadata(root: &Path, sdk: &Path, source: Json, identity: Option<&str>) -> String {
    let selected = format!("path+file://{}#fault-fixture@0.0.0", root.display());
    let source_identity =
        identity.map_or_else(|| format!("path+file://{}", sdk.display()), str::to_owned);
    let dependency = format!(
        "{source_identity}#flow-toolkit@{}",
        env!("CARGO_PKG_VERSION")
    );
    let mut toolkit = metadata_package(&dependency, Some(&sdk.join("Cargo.toml")));
    let Json::Object(members) = &mut toolkit else {
        unreachable!("the fixture package is an object")
    };
    members
        .iter_mut()
        .find(|(key, _)| key == "source")
        .expect("the fixture package has a source")
        .1 = source;
    object(vec![
        (
            "packages",
            Json::Array(vec![
                metadata_package(&selected, Some(&root.join("Cargo.toml"))),
                toolkit,
            ]),
        ),
        (
            "resolve",
            object(vec![(
                "nodes",
                Json::Array(vec![
                    metadata_node(&selected, &[&dependency]),
                    metadata_node(&dependency, &[]),
                ]),
            )]),
        ),
        ("workspace_root", text(root)),
    ])
    .canonical()
}

fn metadata(case: &str, root: &Path, manifest: &Path) -> String {
    let malformed_sdk_source = match case {
        "metadata-sdk-source" => Some("directory+file:///unsupported"),
        "metadata-sdk-git-commit" => Some("git+https://example.invalid/toolkit"),
        "metadata-sdk-git-reference" => {
            Some("git+https://example.invalid/toolkit?unsupported=topic#0123456789abcdef")
        }
        _ => None,
    };
    if let Some(source) = malformed_sdk_source {
        return resolved_sdk_metadata(
            root,
            &common::own("").canonicalize().expect("the path exists"),
            Json::String(source.into()),
            None,
        );
    }
    match case {
        "metadata-malformed" => return "not JSON".into(),
        "metadata-no-packages" => return "{}".into(),
        _ => {}
    }
    let selected = format!("path+file://{}#fault-fixture@0.0.0", root.display());
    let sdk = common::own("")
        .canonicalize()
        .expect("the toolkit source exists");
    let toolkit = format!(
        "path+file://{}#flow-toolkit@{}",
        sdk.display(),
        env!("CARGO_PKG_VERSION")
    );
    let dependency = "path+file:///fixture-dependency#dependency@0.0.0";
    let malformed_dependency = matches!(case, "metadata-no-manifest" | "metadata-newline");
    let mut packages = vec![
        metadata_package(&selected, Some(manifest)),
        metadata_package(&toolkit, Some(&sdk.join("Cargo.toml"))),
    ];
    let mut dependencies = vec![toolkit.as_str()];
    if malformed_dependency {
        dependencies.push(dependency);
    }
    let mut nodes = vec![
        metadata_node(&selected, &dependencies),
        metadata_node(&toolkit, &[]),
    ];
    if malformed_dependency {
        let manifest = if case == "metadata-newline" {
            let directory = root.join("target/line\nbreak");
            fs::create_dir(&directory).expect("the fixture directory is created");
            let manifest = directory.join("Cargo.toml");
            fs::write(
                &manifest,
                "[package]\nname=\"dependency\"\nversion=\"0.0.0\"\n",
            )
            .expect("the fixture file is written");
            Some(manifest)
        } else {
            None
        };
        packages.push(metadata_package(dependency, manifest.as_deref()));
        nodes.push(metadata_node(dependency, &[]));
    }
    let workspace = if case == "metadata-invalid-workspace" {
        fs::create_dir(root.join("target/workspace")).expect("the fixture directory is created");
        fs::write(root.join("target/workspace/Cargo.toml"), "not toml!!!")
            .expect("the fixture file is written");
        root.join("target/workspace")
    } else {
        root.to_owned()
    };
    object(vec![
        ("packages", Json::Array(packages)),
        ("resolve", object(vec![("nodes", Json::Array(nodes))])),
        ("workspace_root", text(&workspace)),
    ])
    .canonical()
}

impl Fixture {
    fn new(case: &str) -> Self {
        let files = TempDir::with_prefix("rust-native-faults").expect("a temporary directory");
        let root = files.path();
        fs::create_dir(root.join("src")).expect("the fixture directory is created");
        fs::create_dir_all(root.join("target/bin")).expect("the fixture directory is created");
        fs::write(
            root.join("Cargo.toml"),
            format!("[package]\nname=\"fault-fixture\"\nversion=\"0.0.0\"\n[profile.dev]\ndebug=1\n[dependencies]\nflow-toolkit={{path={}}}\n", toml::Value::String(common::own("").canonicalize().expect("the toolkit source exists").to_str().expect("the toolkit path is UTF-8").into())),
        )
        .expect("the fixture file is written");
        fs::write(root.join("Cargo.lock"), "version = 4\n").expect("the fixture file is written");
        fs::write(
            root.join("flow.toml"),
            "[process]\ncommand = \"flow-toolkit-rust serve\"\nextract = \"flow-toolkit-rust extract\"\n",
        )
        .expect("the fixture file is written");
        let source = root.join("src/lib.rs");
        fs::write(
            &source,
            "#[tool] pub fn echo(value:String)->Result<String,String>{Ok(value)}",
        )
        .expect("the fixture file is written");
        let executable = root.join("target/launcher");
        let bin = root.join("target/bin");
        let manifest = root.join("Cargo.toml");
        let metadata = metadata(case, root, &manifest);
        let artifact = object(vec![
            ("reason", Json::String("compiler-artifact".into())),
            (
                "target",
                object(vec![(
                    "name",
                    Json::String("flow-function-launcher".into()),
                )]),
            ),
            ("executable", text(&executable)),
        ])
        .canonical();
        // Cargo's dependency information beside the launcher: every Rust
        // source under `src`, which is what a build of the fixture compiles.
        let dependencies = format!(
            "{{ printf '%s:' {launcher}; /usr/bin/find {src} -name '*.rs' | while read -r f; do printf ' %s' \"$f\"; done; echo; }} > {information}",
            launcher = quoted(executable.to_str().expect("fixture paths are UTF-8")),
            src = quoted(root.join("src").to_str().expect("fixture paths are UTF-8")),
            information = quoted(
                executable
                    .with_extension("d")
                    .to_str()
                    .expect("fixture paths are UTF-8")
            ),
        );
        script(
            &bin.join("cargo"),
            &cargo_script(case, &metadata, &artifact, &dependencies),
        );
        let descriptor = descriptor_command(case, &source);
        script(&executable, &format!("#!/bin/sh\n{descriptor}\n"));
        if case == "descriptor-unexecutable" {
            fs::set_permissions(&executable, fs::Permissions::from_mode(0o644))
                .expect("the fixture permissions change");
        }
        Self {
            files,
            source,
            executable,
            bin,
        }
    }
    fn cache(&self) -> PathBuf {
        common::launcher_cache(self.files.path())
    }
    /// Where `extract` writes the contract.
    fn out(&self) -> PathBuf {
        self.files.path().join("target/contract-out")
    }
    /// `extract` with the toolkit binary `toolkit`, writing the contract
    /// to `out`.
    fn extract_with(&self, toolkit: &Path, out: &Path) -> Command {
        let mut command = common::toolkit(toolkit.to_str().expect("fixture paths are UTF-8"));
        command
            .args(["extract", "--library"])
            .arg(self.files.path())
            .arg("--out")
            .arg(out)
            .arg("--depfile")
            .arg(self.files.path().join("target/deps"))
            .env("PATH", &self.bin);
        command
    }
    fn extract(&self) -> Command {
        self.extract_with(common::rust_toolkit().as_ref(), &self.out())
    }
    /// Asserts `extract` wrote the fixture launcher's one contract module.
    fn assert_extracted(&self) {
        assert_eq!(
            common::modules(&self.out()),
            BTreeMap::from([(flow_types::Segments::root(), CONTRACT.to_owned())]),
            "extract writes the launcher's one root module"
        );
    }
    fn prepare(&self) -> Output {
        self.extract().locked_output().expect("the command runs")
    }
    fn prepare_resolved_sdk(&self, sdk: &Path, source: Json, identity: Option<&str>) -> Output {
        let resolved = resolved_sdk_metadata(self.files.path(), sdk, source, identity);
        let cargo = self.bin.join("cargo");
        let original = fs::read_to_string(&cargo).expect("the fixture file is readable");
        let previous = metadata(
            "success",
            self.files.path(),
            &self.files.path().join("Cargo.toml"),
        );
        script(
            &cargo,
            &original.replace(&quoted(&previous), &quoted(&resolved)),
        );
        self.extract().locked_output().expect("the command runs")
    }
    fn assert_sdk_identity(&self, sdk: &Path, dependency: &str, output: &Output) -> PathBuf {
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let cache = self.cache();
        let manifest = fs::read_to_string(cache.join("Cargo.toml")).expect("the launcher manifest");
        assert!(
            manifest.contains("[profile.dev]"),
            "the launcher keeps the package's profiles: {manifest}"
        );
        assert_eq!(
            fs::read_to_string(cache.join("Cargo.lock")).expect("the launcher lockfile"),
            "version = 4\n",
            "the launcher's lockfile is the one Cargo wrote"
        );
        assert!(
            self.source.is_file() && self.executable.is_file(),
            "preparation leaves the source and builds the launcher"
        );
        assert_eq!(
            fs::read_to_string(cache.join("sdk")).expect("the recorded toolkit"),
            sdk.to_str().expect("a UTF-8 path"),
            "the cache records the toolkit it was built with"
        );
        assert_eq!(
            fs::read_to_string(cache.join("sdk-dependency")).expect("the recorded dependency"),
            dependency,
            "the cache records the toolkit dependency"
        );
        assert!(
            manifest.contains(&format!("flow-toolkit = {dependency}")),
            "the launcher depends on that toolkit: {manifest}"
        );
        let isolated = self.files.path().join("target/isolated-toolkit");
        // Keep the executable's writer out of this parallel test process:
        // another thread's child can inherit it until exec, causing ETXTBSY.
        let copied = Command::new("/bin/cp")
            .arg(common::rust_toolkit())
            .arg(&isolated)
            .locked_output()
            .expect("the command runs");
        assert!(
            copied.status.success(),
            "{}",
            String::from_utf8_lossy(&copied.stderr)
        );
        let reused_out = self.files.path().join("target/reused-contract");
        let reused = self
            .extract_with(&isolated, &reused_out)
            .locked_output()
            .expect("the command runs");
        assert!(
            reused.status.success(),
            "{}",
            String::from_utf8_lossy(&reused.stderr)
        );
        assert_eq!(
            common::modules(&reused_out),
            common::modules(&self.out()),
            "a copied toolkit binary reuses the preparation"
        );
        isolated
    }
}
#[test]
fn malformed_cargo_metadata_build_failures_and_descriptor_failures_never_publish_a_fresh_cache() {
    for (case, message) in [
        ("metadata-exit", "fixture metadata failed"),
        ("metadata-malformed", "JSON"),
        ("metadata-no-packages", "no packages"),
        ("metadata-no-manifest", "Cargo metadata needs manifest_path"),
        ("metadata-newline", "not one line of UTF-8"),
        ("metadata-invalid-workspace", "TOML parse error"),
        ("metadata-sdk-source", "Cargo toolkit source is unsupported"),
        (
            "metadata-sdk-git-commit",
            "Cargo Git source has no commit identity",
        ),
        (
            "metadata-sdk-git-reference",
            "Cargo Git reference kind is unsupported",
        ),
        ("build-exit", "compilation failed"),
        ("descriptor-exit", "fixture descriptor failed"),
        ("descriptor-unexecutable", "native Cargo build target"),
        ("source-race", "changed during the build"),
    ] {
        let fixture = Fixture::new(case);
        let output = fixture.prepare();
        assert_eq!(
            output.status.code(),
            Some(2),
            "{case}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains(message), "{case}: {stderr}");
        assert!(!fixture.cache().join("fingerprint").exists(), "{case}");
    }
}
#[test]
fn a_declared_toolkit_dependency_does_not_depend_on_the_cargo_target_location() {
    let fixture = Fixture::new("success");
    let target = TempDir::with_prefix("external-cargo-target").unwrap();
    let executable = target.path().join("flow-toolkit-rust");
    let copied = Command::new("/bin/cp")
        .arg(common::rust_toolkit())
        .arg(&executable)
        .locked_output()
        .unwrap();
    assert!(copied.status.success());
    let output = fixture
        .extract_with(&executable, &fixture.out())
        .env("CARGO_TARGET_DIR", target.path())
        .locked_output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    fixture.assert_extracted();
    assert_eq!(
        fs::read_to_string(fixture.cache().join("sdk")).unwrap(),
        common::own("").canonicalize().unwrap().to_str().unwrap()
    );
}

#[test]
fn workspace_profiles_and_lock_are_preserved_and_sdk_failures_are_actionable_without_recompiling() {
    let sdk = common::own("").canonicalize().unwrap();
    let version = env!("CARGO_PKG_VERSION");
    let mut path_fixture = None;
    for (source, identity, dependency) in [
        (Json::Null, None, format!("{{ path = {:?} }}", sdk.to_str().unwrap())),
        (
            Json::String("registry+https://example.invalid/index".into()),
            Some("registry+https://example.invalid/index"),
            format!("{{ version = \"={version}\", registry-index = \"https://example.invalid/index\" }}"),
        ),
        // Cargo's source keeps the raw ref; its package ID escapes the query value.
        (
            Json::String("git+https://example.invalid/flow-toolkit?branch=release/%25proof#0123456789abcdef0123456789abcdef01234567".into()),
            Some("git+https://example.invalid/flow-toolkit?branch=release%2F%2525proof"),
            "{ git = \"https://example.invalid/flow-toolkit\", branch = \"release/%25proof\" }".into(),
        ),
    ] {
        let is_path = source == Json::Null;
        let fixture = Fixture::new("success");
        let output = fixture.prepare_resolved_sdk(&sdk, source, identity);
        let isolated = fixture.assert_sdk_identity(&sdk, &dependency, &output);
        if is_path {
            path_fixture = Some((fixture, isolated));
        }
    }
    let (fixture, isolated) = path_fixture.unwrap();
    let cache = fixture.cache();
    fs::remove_file(cache.join("sdk")).unwrap();
    fs::remove_file(cache.join("sdk-dependency")).unwrap();
    let absent = fixture
        .extract_with(&isolated, &fixture.out())
        .locked_output()
        .unwrap();
    assert_eq!(absent.status.code(), Some(2));
    assert!(
        String::from_utf8_lossy(&absent.stderr).contains("depends on no flow-toolkit crate"),
        "{}",
        String::from_utf8_lossy(&absent.stderr)
    );
}

#[test]
fn corrupt_cache_artifact_kinds_refuse_without_publishing_and_recover_after_repair() {
    for name in [
        "prepare.lock",
        "inputs",
        "executable",
        "fingerprint",
        "Cargo.toml",
    ] {
        let fixture = Fixture::new("success");
        let cache = fixture.cache();
        fs::create_dir_all(cache.join(name)).unwrap();
        let refused = fixture.prepare();
        assert_eq!(
            refused.status.code(),
            Some(2),
            "{name}: {}",
            String::from_utf8_lossy(&refused.stderr)
        );
        assert!(
            refused.stdout.is_empty() && !fixture.out().exists(),
            "{name}: refused preparation published a contract"
        );
        assert!(
            String::from_utf8_lossy(&refused.stderr)
                .to_lowercase()
                .contains("directory"),
            "{name}: {}",
            String::from_utf8_lossy(&refused.stderr)
        );
        assert!(
            !cache.join("fingerprint").is_file(),
            "{name}: failed preparation acquired a success stamp"
        );
        fs::remove_dir(cache.join(name)).unwrap();
        let repaired = fixture.prepare();
        assert!(
            repaired.status.success(),
            "{name}: {}",
            String::from_utf8_lossy(&repaired.stderr)
        );
        fixture.assert_extracted();
        assert!(cache.join("fingerprint").is_file());
        let metadata_only = fixture.extract().locked_output().unwrap();
        assert!(
            metadata_only.status.success(),
            "{name}: repaired preparation was not reusable"
        );
    }
}

#[test]
fn a_launcher_cargo_reports_but_never_wrote_fails_naming_both_paths_and_recovers_once_built() {
    let fixture = Fixture::new("success");
    let launcher = fs::read(&fixture.executable).unwrap();
    fs::remove_file(&fixture.executable).unwrap();
    let refused = fixture.prepare();
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert_eq!(refused.status.code(), Some(2), "{stderr}");
    assert!(
        stderr.contains(&format!(
            "{} -> {}: ",
            fixture.executable.display(),
            fixture.cache().join("launcher").display()
        )),
        "the refusal names Cargo's artifact and the cache's launcher: {stderr}"
    );
    assert!(
        refused.stdout.is_empty() && !fixture.out().exists(),
        "a launcher that was never copied publishes no contract"
    );
    assert!(
        !fixture.cache().join("fingerprint").exists(),
        "a launcher that was never copied acquires no success stamp"
    );
    flow_testing::write_executable(&fixture.executable, launcher, 0o755).unwrap();
    let repaired = fixture.prepare();
    assert!(
        repaired.status.success(),
        "{}",
        String::from_utf8_lossy(&repaired.stderr)
    );
    fixture.assert_extracted();
}

#[test]
fn a_prepared_contract_that_cannot_be_written_fails_with_the_cause() {
    let fixture = Fixture::new("success");
    assert!(fixture.prepare().status.success());
    // The contract's directory is a file: the contract cannot be written there.
    fs::write(fixture.files.path().join("target/file"), "").unwrap();
    let out = fixture.files.path().join("target/file/contract");
    let output = fixture
        .extract_with(common::rust_toolkit().as_ref(), &out)
        .locked_output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains(&out.display().to_string()), "{stderr}");
}

#[test]
fn a_missing_cargo_is_a_missing_toolchain_and_a_directory_without_a_cargo_package_is_no_library() {
    let fixture = Fixture::new("success");
    let cargo = fixture.bin.join("cargo");
    let saved = fs::read(&cargo).unwrap();
    fs::remove_file(&cargo).unwrap();
    let refused = fixture.prepare();
    assert_eq!(
        refused.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&refused.stderr)
    );
    assert!(String::from_utf8_lossy(&refused.stderr).contains("cargo was not found on PATH"));
    assert_eq!(refused.stdout, <[u8; 0]>::default());
    assert!(!fixture.cache().join("fingerprint").exists());
    flow_testing::write_executable(&cargo, saved, 0o755).unwrap();
    assert!(fixture.prepare().status.success());
    let invalid = fixture
        .extract_with(common::rust_toolkit().as_ref(), &fixture.out())
        .args(["--library"])
        .locked_output()
        .unwrap();
    assert_eq!(invalid.status.code(), Some(2), "--library is given twice");
    let invalid = common::toolkit(common::rust_toolkit())
        .args(["extract", "--library"])
        .arg(fixture.files.path().join("src"))
        .arg("--out")
        .arg(fixture.out())
        .arg("--depfile")
        .arg(fixture.files.path().join("target/deps"))
        .locked_output()
        .unwrap();
    assert_eq!(invalid.status.code(), Some(2));
    assert!(
        String::from_utf8_lossy(&invalid.stderr)
            .contains("a Rust library's root is the root of its Cargo package"),
        "{}",
        String::from_utf8_lossy(&invalid.stderr)
    );
    assert_eq!(invalid.stdout, <[u8; 0]>::default());
}

#[test]
fn a_missing_exported_rust_module_is_located_and_recoverable_before_any_build() {
    let fixture = Fixture::new("success");
    fs::write(
        &fixture.source,
        "pub mod actions;\n#[tool] pub fn root() {}\n",
    )
    .unwrap();
    let refused = fixture.prepare();
    assert_eq!(refused.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(stderr.contains("actions/mod.rs"), "{stderr}");
    assert!(stderr.contains("No such file"), "{stderr}");
    assert!(!fixture.cache().join("fingerprint").exists());
    fs::write(
        fixture.source.parent().unwrap().join("actions.rs"),
        "#[flow_toolkit::tool] pub fn echo(value:String)->Result<String,String>{Ok(value)}\n",
    )
    .unwrap();
    let repaired = fixture.prepare();
    assert!(
        repaired.status.success(),
        "{}",
        String::from_utf8_lossy(&repaired.stderr)
    );
}

#[test]
fn serve_with_a_missing_contract_starts_nothing_and_leaves_the_launcher_current() {
    let fixture = Fixture::new("success");
    assert!(fixture.prepare().status.success());
    let contract = fixture.files.path().join("missing-contract");
    let output = common::toolkit(common::rust_toolkit())
        .args(["serve", "--contract"])
        .arg(contract)
        .current_dir(fixture.files.path())
        .env("PATH", &fixture.bin)
        .locked_output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("No such file"), "{stderr}");
    assert!(
        output.stdout.is_empty(),
        "the launcher must not start without its contract"
    );
    let cached = fixture.extract().locked_output().unwrap();
    assert!(cached.status.success(), "the launcher remains current");
}

#[test]
fn one_launcher_registers_every_module_and_a_stale_one_is_built_again_before_it_serves() {
    let fixture = Fixture::new("success");
    fs::write(&fixture.source, "pub mod left; pub mod right;\n").unwrap();
    let left = fixture.source.parent().unwrap().join("left.rs");
    let right = fixture.source.parent().unwrap().join("right.rs");
    fs::write(&left, "// café 🌊\n#[tool] pub fn answer() {}\n").unwrap();
    fs::write(&right, "#[tool] pub fn other() {}\n").unwrap();
    let output = fixture.prepare();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let launcher = fs::read_to_string(fixture.cache().join("src/main.rs")).unwrap();
    for registered in [
        r#"flow_toolkit::__bridge::at("left", "src/left.rs", 2, tool_impl::left::__flow_tool_answer())"#,
        r#"flow_toolkit::__bridge::at("right", "src/right.rs", 1, tool_impl::right::__flow_tool_other())"#,
    ] {
        assert!(launcher.contains(registered), "{launcher}");
    }
    assert!(
        launcher.contains(r#"flow_toolkit::__bridge::run("fault_fixture","#),
        "{launcher}"
    );
    fs::write(&left, "#[tool] pub fn changed() {}\n").unwrap();
    let serve = |contract: &Path| {
        common::toolkit(common::rust_toolkit())
            .args(["serve", "--contract"])
            .arg(contract)
            .current_dir(fixture.files.path())
            .env("PATH", &fixture.bin)
            .locked_output()
            .unwrap()
    };
    let invalid = fixture.files.path().join("target/other-version");
    fs::write(&invalid, "{}").unwrap();
    let refused = serve(&invalid);
    assert_eq!(refused.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(
        stderr.contains(&format!(
            "data version 123.125, not {}",
            flow_abi::DATA_VERSION
        )),
        "a contract file of another data version is refused naming both: {stderr}"
    );
    assert_eq!(refused.stdout, <[u8; 0]>::default());
    let main = fixture.cache().join("src/main.rs");
    assert!(
        fs::read_to_string(&main)
            .unwrap()
            .contains("__flow_tool_answer"),
        "a refused contract builds nothing"
    );
    let contract = fixture.files.path().join("target/contract");
    let mut listing = Vec::new();
    flow_abi::primitives::write_uint(&mut listing, flow_abi::DATA_VERSION.major);
    flow_abi::primitives::write_uint(&mut listing, flow_abi::DATA_VERSION.minor);
    flow_abi::primitives::write_uint(&mut listing, 0);
    fs::write(&contract, listing).unwrap();
    let served = serve(&contract);
    assert!(
        served.status.success(),
        "{}",
        String::from_utf8_lossy(&served.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&served.stdout),
        format!("serving {}\n", contract.canonicalize().unwrap().display()),
        "the launcher is started with --contract FILE"
    );
    assert!(
        fs::read_to_string(&main)
            .unwrap()
            .contains("__flow_tool_changed"),
        "the stale launcher is built again before it serves"
    );
}

#[test]
fn missing_native_inputs_and_incomplete_toolchains_refuse_without_accepted_outputs() {
    let fixture = Fixture::new("success");
    let missing = fixture.files.path().join("missing-library");
    let output = common::toolkit(common::rust_toolkit())
        .args(["extract", "--library"])
        .arg(&missing)
        .arg("--out")
        .arg(fixture.out())
        .arg("--depfile")
        .arg(fixture.files.path().join("target/deps"))
        .locked_output()
        .unwrap();
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("missing-library"));
    assert_eq!(output.stdout, <[u8; 0]>::default());
    let repaired = fixture.prepare();
    assert!(
        repaired.status.success(),
        "{}",
        String::from_utf8_lossy(&repaired.stderr)
    );
    assert!(fixture.cache().join("fingerprint").is_file());
}

#[test]
fn cargo_disappearing_after_metadata_refuses_then_recovers_with_the_same_source() {
    let fixture = Fixture::new("cargo-disappears-after-metadata");
    let cargo = fixture.bin.join("cargo");
    let program = fs::read(&cargo).unwrap();
    let output = fixture.prepare();
    assert_eq!(
        output.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(String::from_utf8_lossy(&output.stderr).contains("cargo was not found"));
    assert!(output.stdout.is_empty() && !fixture.cache().join("fingerprint").exists());
    let repaired = String::from_utf8(program)
        .unwrap()
        .replace("/bin/rm -- \"$0\"", "");
    script(&cargo, &repaired);
    let output = fixture.prepare();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(fixture.cache().join("fingerprint").is_file());
}

#[test]
fn a_blocked_resolved_sdk_sidecar_cannot_publish_preparation_and_repair_preserves_identity() {
    let sdk = common::own("").canonicalize().unwrap();
    let dependency = format!("{{ path = {:?} }}", sdk.to_str().unwrap());
    for name in ["sdk", "sdk-dependency"] {
        let fixture = Fixture::new("success");
        let cache = fixture.cache();
        fs::create_dir_all(cache.join(name)).unwrap();
        let refused = fixture.prepare_resolved_sdk(&sdk, Json::Null, None);
        assert_eq!(refused.status.code(), Some(2));
        assert!(
            String::from_utf8_lossy(&refused.stderr)
                .to_lowercase()
                .contains("directory")
        );
        assert_eq!(refused.stdout, <[u8; 0]>::default());
        assert!(!cache.join("fingerprint").exists());
        fs::remove_dir(cache.join(name)).unwrap();
        let repaired = fixture.prepare_resolved_sdk(&sdk, Json::Null, None);
        fixture.assert_sdk_identity(&sdk, &dependency, &repaired);
    }
}