cargo-tops 0.4.0

init / check / gate for the Rust-TOPS protocol. Orchestrates existing Cargo tools; does not replace them.
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
//! The `laws` layer (protocol 1.1.0, ยง3.1).
//!
//! `gate` ensures the Bend release `laws/bend.lock` pins, writes the cases
//! [`crate::facts`] chose as one Bend program, and runs `bend` on it. The
//! program's only obligation is that each verdict is not `Refuse`; the
//! verdicts themselves come from `LAWS.bend`, and the pass or fail is
//! `bend`'s exit status on that proof. When the proof fails, one more run
//! of `main` alone prints every verdict. That run does not decide pass or fail.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]

#[cfg(test)]
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result};
use serde_json::json;

use crate::facts::{self, Choice, Ctx};
use crate::profiles;

pub(crate) const PACK: &str = "LAWS.bend";
pub(crate) const LOCK: &str = "laws/bend.lock";
pub(crate) const FETCH: &str = "scripts/fetch-bend.sh";
pub(crate) const OUT_DIR: &str = "target/rust-tops";

/// Directory that receives `cases.bend` and `cases.json`.
///
/// A nonempty `CARGO_TARGET_DIR` wins. Otherwise, when `Cargo.toml` exists
/// and `cargo metadata` returns JSON, that `target_directory` wins. Otherwise
/// the report is `<project>/target/rust-tops`. `cargo metadata` runs at most
/// once per project inside one gate. [`begin_gate`] clears that cache, so the
/// next gate resolves the same project again.
pub(crate) fn report_dir(project: &Path) -> PathBuf {
    artifact_dir(project)
}

/// Drop the metadata cache. `gate` calls this once before any [`report_dir`].
pub(crate) fn begin_gate() {
    META_CACHE.with(|slot| slot.borrow_mut().clear());
}

/// Directory for `lcov.info` and `crap.json`.
///
/// This is the same path as [`report_dir`], so a nonempty `CARGO_TARGET_DIR`
/// moves the laws report and both artifacts together.
pub(crate) fn artifact_dir(project: &Path) -> PathBuf {
    let from_env = std::env::var("CARGO_TARGET_DIR").ok();
    let meta = if nonempty(from_env.as_deref()).is_some() {
        None
    } else {
        metadata_target_once(project)
    };
    resolve_report_dir(project, from_env.as_deref(), meta.as_deref())
}

thread_local! {
    static META_CACHE: RefCell<HashMap<PathBuf, Option<String>>> = RefCell::new(HashMap::new());
    #[cfg(test)]
    static META_SPAWNS: Cell<u32> = const { Cell::new(0) };
}

fn metadata_target_once(project: &Path) -> Option<String> {
    let key = project
        .canonicalize()
        .unwrap_or_else(|_| project.to_path_buf());
    let cached = META_CACHE.with(|slot| slot.borrow().get(&key).cloned());
    if let Some(target) = cached {
        return target;
    }
    let target = metadata_target(project);
    META_CACHE.with(|slot| {
        slot.borrow_mut().insert(key, target.clone());
    });
    target
}

/// Same rule as [`report_dir`], with the two lookups passed in. A relative
/// `CARGO_TARGET_DIR` is under `project`, because the gate runs Cargo there
/// and Cargo reads it relative to its working directory.
pub(crate) fn resolve_report_dir(
    project: &Path,
    cargo_target_dir: Option<&str>,
    metadata_target: Option<&str>,
) -> PathBuf {
    if let Some(dir) = nonempty(cargo_target_dir) {
        return project.join(dir).join("rust-tops");
    }
    if let Some(dir) = nonempty(metadata_target) {
        return PathBuf::from(dir).join("rust-tops");
    }
    project.join(OUT_DIR)
}

/// Path printed in gate output. Stays `target/rust-tops` when the report
/// sits under the project.
pub(crate) fn report_display(project: &Path) -> String {
    display_under(project, &report_dir(project))
}

fn nonempty(value: Option<&str>) -> Option<&str> {
    value.map(str::trim).filter(|text| !text.is_empty())
}

fn display_under(project: &Path, out: &Path) -> String {
    out.strip_prefix(project)
        .ok()
        .map(|rel| rel.display().to_string())
        .filter(|text| !text.is_empty())
        .unwrap_or_else(|| out.display().to_string())
}

fn metadata_target(project: &Path) -> Option<String> {
    let manifest = project.join("Cargo.toml");
    if !manifest.is_file() {
        return None;
    }
    #[cfg(test)]
    META_SPAWNS.with(|count| count.set(count.get() + 1));
    let output = Command::new("cargo")
        .args([
            "metadata",
            "--format-version",
            "1",
            "--no-deps",
            "--manifest-path",
        ])
        .arg(&manifest)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8(output.stdout).ok()?;
    let value: serde_json::Value = serde_json::from_str(&text).ok()?;
    value.get("target_directory")?.as_str().map(str::to_string)
}

/// The `bend` binary that reports the pinned version.
pub(crate) struct Judge {
    bend: PathBuf,
    version: String,
}

fn lock_version(raw: &str) -> Option<String> {
    let table: toml::Table = raw.parse().ok()?;
    table
        .get("bend")?
        .get("version")?
        .as_str()
        .map(str::to_string)
}

fn reports_version(bend: &Path, want: &str) -> bool {
    let Ok(out) = Command::new(bend)
        .arg("version")
        .env("BEND_NO_TELEMETRY", "1")
        .output()
    else {
        return false;
    };
    let stdout = String::from_utf8_lossy(&out.stdout);
    let got = stdout
        .lines()
        .next()
        .and_then(|line| line.split_whitespace().nth(1));
    out.status.success() && got == Some(want)
}

fn home_bend() -> Option<PathBuf> {
    let home = std::env::var_os("HOME")?;
    Some(PathBuf::from(home).join(".bend/bin/bend")).filter(|path| path.is_file())
}

fn path_bend_opt_in(want: &str) -> Option<PathBuf> {
    if std::env::var("CARGO_TOPS_BEND_PATH").ok().as_deref() != Some("1") {
        return None;
    }
    let out = Command::new("sh")
        .args(["-c", "command -v bend"])
        .output()
        .ok()?;
    let found = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if found.is_empty() {
        return None;
    }
    let path = PathBuf::from(found);
    if !reports_version(&path, want) {
        return None;
    }
    println!("laws: bend PATH fallback {}", path.display());
    Some(path)
}

/// Find the pinned Bend in `$HOME/.bend`. A `sh -c` search of `PATH` runs
/// only when `CARGO_TOPS_BEND_PATH=1` and that pin is missing or the wrong
/// version. The fallback log names the binary. Else run the vendored
/// `scripts/fetch-bend.sh` (sha256-checked, no `curl | sh`). Every miss is
/// a failed gate, never a skip (H-37).
pub(crate) fn ensure_bend(dir: &Path) -> Result<Judge, String> {
    let raw = fs::read_to_string(dir.join(LOCK))
        .map_err(|_| format!("laws: {LOCK} is missing; run `cargo tops init` to write it"))?;
    let want = lock_version(&raw).ok_or_else(|| format!("laws: {LOCK} has no [bend] version"))?;
    let found = home_bend()
        .filter(|bend| reports_version(bend, &want))
        .or_else(|| path_bend_opt_in(&want));
    if let Some(bend) = found {
        return Ok(Judge {
            bend,
            version: want,
        });
    }
    let script = dir.join(FETCH);
    if !script.is_file() {
        return Err(format!(
            "laws: Bend {want} ({LOCK}) is not installed and {FETCH} is missing; run `cargo tops init`"
        ));
    }
    println!("\n==> [laws] sh {FETCH} (Bend {want} from {LOCK} is not installed)");
    let status = Command::new("sh")
        .arg(&script)
        .current_dir(dir)
        .env("BEND_NO_TELEMETRY", "1")
        .status()
        .map_err(|err| format!("laws: spawn {FETCH}: {err}"))?;
    if !status.success() {
        return Err(format!(
            "laws: {FETCH} failed ({status}); Bend {want} is not installed"
        ));
    }
    home_bend()
        .filter(|bend| reports_version(bend, &want))
        .map(|bend| Judge {
            bend,
            version: want.clone(),
        })
        .ok_or_else(|| {
            format!("laws: {FETCH} finished, but $HOME/.bend/bin/bend does not report {want}")
        })
}

/// One law of the adopter's pack, with the case chosen for it or the reason
/// there is none.
struct Row {
    law: String,
    case: Option<(&'static str, &'static str)>,
    read: Vec<String>,
    reason: Option<String>,
    reason_code: Option<&'static str>,
}

fn pack_laws(pack: &str) -> Vec<String> {
    pack.lines()
        .filter_map(|line| {
            line.strip_prefix("law ")
                .and_then(|rest| rest.strip_suffix(':'))
        })
        .map(|law| law.trim().to_string())
        .collect()
}

fn choose_rows(pack: &str, ctx: &Ctx) -> Vec<Row> {
    pack_laws(pack)
        .into_iter()
        .map(|law| {
            let Some(fact) = facts::find(&law) else {
                let reason = facts::not_evaluated(&law).to_string();
                return Row {
                    law,
                    case: None,
                    read: Vec::new(),
                    reason: Some(reason),
                    reason_code: Some(facts::NO_FACT_READER),
                };
            };
            match (fact.choose)(ctx) {
                Choice::Fact { met, read } => Row {
                    law,
                    case: Some((fact.fun, fact.ctor(met))),
                    read,
                    reason: None,
                    reason_code: None,
                },
                Choice::NotEvaluated { reason, code } => Row {
                    law,
                    case: None,
                    read: Vec::new(),
                    reason: Some(reason),
                    reason_code: Some(code),
                },
            }
        })
        .collect()
}

const PROGRAM_HEAD: &str = "\
# Written by `cargo tops gate` (laws layer, rust-tops 1.1.0 ยง3.1). Do not edit.
# Each law below applies a LAWS.bend verdict to the case cargo-tops chose.
# The obligation is only that the verdict is not Refuse; bend checks it.
import Base
import ./LAWS.bend as Laws

def not_refuse(v: Laws.Verdict) -> Bool:
  match v:
    case Laws.Refuse{}:
      False{}
    case Laws.Ack{}:
      True{}
    case Laws.Allow{}:
      True{}
";

/// The case file: one obligation per checked law, and a `main` that returns
/// every verdict so `bend` prints them when the proof passes.
fn program(rows: &[Row]) -> String {
    let mut out = PROGRAM_HEAD.to_string();
    let mut calls = Vec::new();
    for row in rows {
        let Some((fun, ctor)) = row.case else {
            continue;
        };
        let call = verdict_call(fun, ctor);
        let read = row.read.join(", ").replace(['\n', '\r'], " ");
        #[expect(clippy::let_underscore_must_use, reason = "already in this crate when the strict table was turned on")]
        let _ = write!(
            out,
            "\n# {law}: {ctor}, read {read}\nlaw case_{law}:\n  {{not_refuse({call}) == True{{}} : Bool}}\n\ndef case_{law}():\n  {{==}}\n",
            law = row.law,
        );
        calls.push(call);
    }
    write_main(&mut out, &calls);
    out
}

/// `main` and nothing else. Bend prints every verdict instead of stopping
/// at the first `law` that refuses. This file is not a proof.
fn main_program(rows: &[Row]) -> String {
    let mut out = "\
# Written by `cargo tops gate` after the proof run failed.
# `main` prints every verdict. This run does not decide pass or fail.
import Base
import ./LAWS.bend as Laws
"
    .to_string();
    let calls = rows
        .iter()
        .filter_map(|row| row.case.map(|(fun, ctor)| verdict_call(fun, ctor)))
        .collect::<Vec<_>>();
    write_main(&mut out, &calls);
    out
}

fn verdict_call(fun: &str, ctor: &str) -> String {
    format!("Laws.{fun}(Laws.{ctor}{{}})")
}

fn write_main(out: &mut String, calls: &[String]) {
    match calls.len() {
        0 => {}
        1 => {
            #[expect(
                clippy::indexing_slicing,
                reason = "already in this crate when the strict table was turned on"
            )]
            #[expect(
                clippy::let_underscore_must_use,
                reason = "already in this crate when the strict table was turned on"
            )]
            let _ = write!(out, "\ndef main() -> Laws.Verdict:\n  {}\n", calls[0]);
        }
        n => {
            let types = vec!["Laws.Verdict"; n].join(" & ");
            #[expect(
                clippy::let_underscore_must_use,
                reason = "already in this crate when the strict table was turned on"
            )]
            let _ = write!(out, "\ndef main() -> {types}:\n  ({})\n", calls.join(", "));
        }
    }
}

/// Verdict names in the order `bend` printed `main`'s value.
fn printed_verdicts(output: &str) -> Vec<&str> {
    output
        .split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ','))
        .filter_map(|token| token.rsplit('.').next())
        .filter_map(|name| name.strip_suffix("{}"))
        .filter(|name| matches!(*name, "Allow" | "Ack" | "Refuse"))
        .collect()
}

/// The law `bend` stopped on, from its `Location: case_<law>` line.
fn failed_law(output: &str) -> Option<&str> {
    output
        .lines()
        .find_map(|line| line.trim().strip_prefix("Location: case_"))
}

struct Judged<'r> {
    rows: &'r [Row],
    verdicts: Vec<String>,
    passed: bool,
    failed_law: Option<String>,
}

impl Judged<'_> {
    /// `bend`'s verdict for row `index`, or what we can honestly say instead.
    fn status(&self, row: &Row, checked_index: usize) -> String {
        if row.case.is_none() {
            return "not-evaluated".into();
        }
        if let Some(verdict) = self.verdicts.get(checked_index) {
            return verdict.clone();
        }
        if self.passed {
            return "unread".into();
        }
        if self.failed_law.as_deref() == Some(row.law.as_str()) {
            "Refuse".into()
        } else {
            "unreported".into()
        }
    }

    /// Every checked law whose printed verdict is `Refuse`.
    fn refusals(&self) -> Vec<&str> {
        let mut index = 0;
        let mut names = Vec::new();
        for row in self.rows {
            if row.case.is_none() {
                continue;
            }
            if self.status(row, index) == "Refuse" {
                names.push(row.law.as_str());
            }
            index += 1;
        }
        names
    }

    fn print(&self) {
        let mut checked = 0;
        for row in self.rows {
            let status = self.status(row, checked);
            match (row.case, &row.reason) {
                (Some((_, ctor)), _) => {
                    checked += 1;
                    println!(
                        "  {status:<13} {:<40} {ctor:<22} {}",
                        row.law,
                        row.read.join(", ")
                    );
                }
                (None, reason) => {
                    println!(
                        "  {status:<13} {:<40} {}",
                        row.law,
                        reason.as_deref().unwrap_or("")
                    );
                }
            }
        }
        let skipped = self.rows.len() - checked;
        println!(
            "laws: {checked} checked by bend, {skipped} not-evaluated (not checked, not passed)"
        );
        if !self.passed && self.verdicts.len() != checked {
            println!("laws: bend stops at the first refusal; `unreported` laws were not judged");
        }
    }

    fn json(&self, judge: &Judge, exit: Option<i32>, program: &str) -> serde_json::Value {
        let mut checked = 0;
        let laws: Vec<serde_json::Value> = self
            .rows
            .iter()
            .map(|row| {
                let status = self.status(row, checked);
                let entry = match row.case {
                    Some((fun, ctor)) => json!({
                        "law": row.law, "status": "checked", "verdict_fn": fun, "case": ctor,
                        "read": row.read, "verdict": status, "reason_code": null,
                    }),
                    None => json!({
                        "law": row.law, "status": "not-evaluated", "case": null,
                        "read": [], "verdict": null, "reason": row.reason,
                        "reason_code": row.reason_code,
                    }),
                };
                checked += usize::from(row.case.is_some());
                entry
            })
            .collect();
        json!({
            "protocol_layer": "laws",
            "bend": judge.version,
            "program": program,
            "bend_exit": exit,
            "passed": self.passed,
            "laws": laws,
        })
    }
}

/// Write `contents` to a new file. A symlink is refused and not followed.
/// An existing regular file is removed, then `create_new` creates the
/// replacement, so a link that appears in between fails the create instead
/// of being written through.
fn write_refusing_symlink(path: &Path, contents: &str) -> Result<()> {
    match fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_symlink() => {
            anyhow::bail!(
                "refusing to write {}: it is a symlink, and the laws layer does not follow one",
                path.display()
            );
        }
        Ok(_) => fs::remove_file(path).with_context(|| format!("remove {}", path.display()))?,
        Err(_) => {}
    }
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .with_context(|| format!("create {}", path.display()))?;
    std::io::Write::write_all(&mut file, contents.as_bytes())
        .with_context(|| format!("write {}", path.display()))
}

/// Second `bend` run. `main.bend` has no `law` obligation, so Bend prints
/// every verdict. The caller does not use this exit status.
fn verdicts_from_main(judge: &Judge, out: &Path, rows: &[Row]) -> Result<Vec<String>> {
    let path = out.join("main.bend");
    write_refusing_symlink(&path, &main_program(rows))?;
    let output = Command::new(&judge.bend)
        .arg("main.bend")
        .current_dir(out)
        .env("BEND_NO_TELEMETRY", "1")
        .output()
        .with_context(|| format!("spawn {}", judge.bend.display()))?;
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(printed_verdicts(&text)
        .into_iter()
        .map(str::to_string)
        .collect())
}

/// Write the case file, run `bend`, print and record the result. Returns
/// the gate failures, empty when `bend` accepted every checked law.
/// A failing proof is followed by [`verdicts_from_main`]; that run only
/// fills the verdict column.
#[expect(clippy::too_many_lines, reason = "over the kit line threshold")]
pub(crate) fn run(judge: &Judge, ctx: &Ctx) -> Result<Vec<String>> {
    let Ok(pack) = fs::read_to_string(ctx.dir.join(PACK)) else {
        return Ok(vec![format!(
            "laws: {PACK} is missing; run `cargo tops init`"
        )]);
    };
    let rows = choose_rows(&pack, ctx);
    let out = report_dir(ctx.dir);
    let shown = display_under(ctx.dir, &out);
    fs::create_dir_all(&out).with_context(|| format!("create {}", out.display()))?;
    fs::write(out.join(PACK), &pack).with_context(|| format!("write {shown}/{PACK}"))?;
    fs::write(out.join("cases.bend"), program(&rows))
        .with_context(|| format!("write {shown}/cases.bend"))?;

    println!(
        "\n==> [laws] bend {shown}/cases.bend (Bend {})",
        judge.version
    );
    if pack != profiles::LAWS_BEND {
        println!(
            "note: {PACK} differs from the pack cargo-tops {} ships; bend judges this repo's copy",
            env!("CARGO_PKG_VERSION")
        );
    }
    let output = Command::new(&judge.bend)
        .arg("cases.bend")
        .current_dir(&out)
        .env("BEND_NO_TELEMETRY", "1")
        .output()
        .with_context(|| format!("spawn {}", judge.bend.display()))?;
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let checked = rows.iter().filter(|row| row.case.is_some()).count();
    let proof_verdicts: Vec<String> = printed_verdicts(&text)
        .into_iter()
        .map(str::to_string)
        .collect();
    // A failed proof stops at the first refusal, so this output does not
    // name the later laws. Run `main` alone and print those verdicts. The
    // proof run's status is still what passes or fails the gate.
    let verdicts = if !output.status.success() && checked > 0 {
        let printed = verdicts_from_main(judge, &out, &rows)?;
        if printed.len() == checked {
            printed
        } else {
            proof_verdicts
        }
    } else {
        proof_verdicts
    };
    let readable = verdicts.len() == checked && !verdicts.iter().any(|verdict| verdict == "Refuse");
    let judged = Judged {
        rows: &rows,
        passed: output.status.success() && readable,
        verdicts,
        failed_law: failed_law(&text).map(str::to_string),
    };
    judged.print();

    let mut failures = Vec::new();
    if !output.status.success() {
        for line in text.lines() {
            println!("    | {line}");
        }
        failures.push(match judged.refusals().as_slice() {
            [] => match &judged.failed_law {
                Some(law) => format!("laws: bend refused {law} ({shown}/cases.bend)"),
                None => format!("laws: bend exited {} on {shown}/cases.bend", output.status),
            },
            names => format!(
                "laws: bend refused {} ({shown}/cases.bend)",
                names.join(", ")
            ),
        });
    } else if !readable {
        failures.push(format!(
            "laws: bend printed {} verdict(s) for {checked} checked law(s)",
            judged.verdicts.len()
        ));
    }
    #[expect(
        clippy::string_add,
        reason = "already in this crate when the strict table was turned on"
    )]
    let report = serde_json::to_string_pretty(&judged.json(
        judge,
        output.status.code(),
        &format!("{shown}/cases.bend"),
    ))? + "\n";
    fs::write(out.join("cases.json"), report)
        .with_context(|| format!("write {shown}/cases.json"))?;
    Ok(failures)
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::*;

    fn row(law: &str, case: Option<(&'static str, &'static str)>) -> Row {
        Row {
            law: law.into(),
            case,
            read: vec!["rust-tops.yaml".into()],
            reason: None,
            reason_code: None,
        }
    }

    #[test]
    fn program_has_one_obligation_per_checked_law_and_prints_every_verdict() {
        let rows = [
            row("fmt_is_tier0", Some(("fmt_verdict", "FmtTier0"))),
            row("evidence_not_self_served", None),
            row("lock_honesty", Some(("lock_verdict", "LockDrift"))),
        ];
        let text = program(&rows);
        assert!(text.contains("import ./LAWS.bend as Laws"));
        assert!(text.contains("law case_fmt_is_tier0:\n  {not_refuse(Laws.fmt_verdict(Laws.FmtTier0{})) == True{} : Bool}"));
        assert!(text.contains("law case_lock_honesty:"));
        assert!(
            !text.contains("evidence_not_self_served"),
            "a not-evaluated law must not be encoded"
        );
        assert!(text.contains(
            "def main() -> Laws.Verdict & Laws.Verdict:\n  (Laws.fmt_verdict(Laws.FmtTier0{}), Laws.lock_verdict(Laws.LockDrift{}))"
        ));
    }

    #[test]
    fn program_without_checked_laws_has_no_main() {
        let text = program(&[row("evidence_not_self_served", None)]);
        assert!(!text.contains("def main"));
        assert!(!text.contains("law case_"));
    }

    #[test]
    fn single_checked_law_returns_one_verdict() {
        let text = program(&[row("fmt_is_tier0", Some(("fmt_verdict", "FmtTier0")))]);
        assert!(text.contains("def main() -> Laws.Verdict:\n  Laws.fmt_verdict(Laws.FmtTier0{})\n"));
    }

    #[test]
    fn main_program_prints_every_verdict_and_states_no_law() {
        let rows = [
            row("fmt_is_tier0", Some(("fmt_verdict", "FmtTier0"))),
            row("evidence_not_self_served", None),
            row("lock_honesty", Some(("lock_verdict", "LockDrift"))),
        ];
        let text = main_program(&rows);
        assert!(text.contains("import ./LAWS.bend as Laws"));
        assert!(!text.contains("law case_"), "{text}");
        assert!(text.contains(
            "def main() -> Laws.Verdict & Laws.Verdict:\n  (Laws.fmt_verdict(Laws.FmtTier0{}), Laws.lock_verdict(Laws.LockDrift{}))"
        ));
    }

    #[test]
    fn a_failed_proof_reports_every_printed_verdict() {
        let rows = [
            row("fmt_is_tier0", Some(("fmt_verdict", "FmtTier0"))),
            row("lock_honesty", Some(("lock_verdict", "LockDrift"))),
        ];
        let judged = Judged {
            rows: &rows,
            verdicts: vec!["Refuse".into(), "Allow".into()],
            passed: false,
            failed_law: Some("fmt_is_tier0".into()),
        };
        assert!(!judged.passed);
        assert_eq!(judged.status(&rows[0], 0), "Refuse");
        assert_eq!(judged.status(&rows[1], 1), "Allow");
    }

    #[test]
    fn reads_the_verdicts_bend_prints() {
        assert_eq!(
            printed_verdicts("(LAWS.Allow{}, LAWS.Ack{}, LAWS.Allow{})\n"),
            ["Allow", "Ack", "Allow"]
        );
        assert_eq!(printed_verdicts("LAWS.Allow{}\n"), ["Allow"]);
        assert!(printed_verdicts("ALL PROOFS CHECK\n").is_empty());
    }

    #[test]
    fn reads_the_law_bend_stopped_on() {
        let out = "SOME PROOFS FAIL\nError:\n- expected : False{}\n- observed : True{}\nLocation: case_lock_honesty\n";
        assert_eq!(failed_law(out), Some("lock_honesty"));
        assert_eq!(failed_law("SOME PROOFS FAIL\nLocation: main\n"), None);
    }

    #[test]
    fn lock_version_reads_the_bend_section() {
        assert_eq!(lock_version(profiles::BEND_LOCK).as_deref(), Some("2.0.36"));
        assert_eq!(lock_version("[bend]\nnote = \"x\"\n"), None);
    }

    #[test]
    fn report_dir_prefers_a_nonempty_cargo_target_dir() {
        let project = Path::new("/proj");
        let got = resolve_report_dir(project, Some("/env-target"), Some("/meta-target"));
        assert_eq!(got, PathBuf::from("/env-target/rust-tops"));
        // Cargo runs in the project, so a relative target dir is under it.
        let got = resolve_report_dir(project, Some("out/"), Some("/meta-target"));
        assert_eq!(got, PathBuf::from("/proj/out/rust-tops"));
    }

    #[test]
    fn report_dir_uses_metadata_when_the_env_is_empty() {
        let project = Path::new("/proj");
        assert_eq!(
            resolve_report_dir(project, Some("  "), Some("/meta-target")),
            PathBuf::from("/meta-target/rust-tops")
        );
        assert_eq!(
            resolve_report_dir(project, None, Some("/meta-target")),
            PathBuf::from("/meta-target/rust-tops")
        );
    }

    #[test]
    fn metadata_target_reads_target_directory() {
        let dir = std::env::temp_dir().join(format!("cargo-tops-meta-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("src")).unwrap();
        fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"meta-fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(dir.join("src/lib.rs"), "// fixture\n").unwrap();
        let got = metadata_target(&dir).expect("cargo metadata");
        assert!(Path::new(&got).is_absolute(), "{got}");
        assert!(got.contains("target"), "{got}");
        let report = resolve_report_dir(&dir, None, Some(&got));
        assert_eq!(report, PathBuf::from(got).join("rust-tops"));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn report_dir_reuses_one_cargo_metadata_and_shares_the_artifact_dir() {
        let _lock = lock_target_env();
        let dir = std::env::temp_dir().join(format!("cargo-tops-meta-once-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("src")).unwrap();
        fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"meta-once\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(dir.join("src/lib.rs"), "// fixture\n").unwrap();
        let _env = EnvGuard::remove("CARGO_TARGET_DIR");
        begin_gate();
        let before = META_SPAWNS.with(|count| count.get());
        let first = report_dir(&dir);
        let second = report_dir(&dir);
        let after = META_SPAWNS.with(|count| count.get());
        assert_eq!(first, second);
        assert_eq!(artifact_dir(&dir), first);
        assert_eq!(after - before, 1, "cargo metadata ran more than once");
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[expect(clippy::too_many_lines, reason = "over the kit line threshold")]
    fn a_second_project_on_the_same_thread_spawns_its_own_metadata() {
        let _lock = lock_target_env();
        let root =
            std::env::temp_dir().join(format!("cargo-tops-two-projects-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&root);
        let alpha = root.join("alpha");
        let beta = root.join("beta");
        for (dir, name) in [(&alpha, "alpha"), (&beta, "beta")] {
            fs::create_dir_all(dir.join("src")).unwrap();
            fs::write(
                dir.join("Cargo.toml"),
                format!("[package]\nname = \"{name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n"),
            )
            .unwrap();
            fs::write(dir.join("src/lib.rs"), "// fixture\n").unwrap();
        }
        let _env = EnvGuard::remove("CARGO_TARGET_DIR");
        begin_gate();
        let before = META_SPAWNS.with(|count| count.get());
        let first = report_dir(&alpha);
        let after_first = META_SPAWNS.with(|count| count.get());
        let second = report_dir(&beta);
        let after_second = META_SPAWNS.with(|count| count.get());
        assert_eq!(
            after_first - before,
            1,
            "the first project did not spawn metadata"
        );
        assert_eq!(
            after_second - after_first,
            1,
            "the second project reused the first project's metadata"
        );
        assert_ne!(first, second);
        assert!(first.ends_with("alpha/target/rust-tops"), "{first:?}");
        assert!(second.ends_with("beta/target/rust-tops"), "{second:?}");
        let again = report_dir(&alpha);
        let after_again = META_SPAWNS.with(|count| count.get());
        assert_eq!(again, first);
        assert_eq!(
            after_again, after_second,
            "the first project spawned again inside the same gate"
        );
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_second_gate_on_the_same_project_resolves_metadata_again() {
        let _lock = lock_target_env();
        let dir =
            std::env::temp_dir().join(format!("cargo-tops-second-gate-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("src")).unwrap();
        fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"second-gate\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(dir.join("src/lib.rs"), "// fixture\n").unwrap();
        let _env = EnvGuard::remove("CARGO_TARGET_DIR");
        begin_gate();
        let before = META_SPAWNS.with(|count| count.get());
        let first = report_dir(&dir);
        let second = report_dir(&dir);
        let after_gate = META_SPAWNS.with(|count| count.get());
        assert_eq!(first, second);
        assert_eq!(after_gate - before, 1, "one gate spawned metadata twice");
        begin_gate();
        let third = report_dir(&dir);
        let after_next = META_SPAWNS.with(|count| count.get());
        assert_eq!(third, first);
        assert_eq!(
            after_next - after_gate,
            1,
            "the next gate reused the previous metadata"
        );
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_nonempty_cargo_target_dir_skips_metadata_and_moves_artifacts() {
        let _lock = lock_target_env();
        let project =
            std::env::temp_dir().join(format!("cargo-tops-env-target-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&project);
        fs::create_dir_all(project.join("src")).unwrap();
        fs::write(
            project.join("Cargo.toml"),
            "[package]\nname = \"env-target\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(project.join("src/lib.rs"), "// fixture\n").unwrap();
        let outside =
            std::env::temp_dir().join(format!("cargo-tops-outside-target-{}", std::process::id()));
        let _env = EnvGuard::set("CARGO_TARGET_DIR", &outside.to_string_lossy());
        let before = META_SPAWNS.with(|count| count.get());
        let got = report_dir(&project);
        let again = artifact_dir(&project);
        let after = META_SPAWNS.with(|count| count.get());
        assert_eq!(got, outside.join("rust-tops"));
        assert_eq!(again, got);
        assert_eq!(
            after, before,
            "a set CARGO_TARGET_DIR still spawned cargo metadata"
        );
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&project);
    }

    #[test]
    fn report_dir_falls_back_to_the_project_target() {
        let project = Path::new("/proj");
        assert_eq!(
            resolve_report_dir(project, None, None),
            PathBuf::from("/proj/target/rust-tops")
        );
        assert_eq!(
            resolve_report_dir(project, Some(""), Some("")),
            PathBuf::from("/proj/target/rust-tops")
        );
    }

    fn lock_target_env() -> std::sync::MutexGuard<'static, ()> {
        TARGET_ENV.lock().unwrap_or_else(|err| err.into_inner())
    }

    static TARGET_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());

    struct EnvGuard {
        key: &'static str,
        prev: Option<String>,
    }

    impl EnvGuard {
        fn remove(key: &'static str) -> Self {
            let prev = std::env::var(key).ok();
            std::env::remove_var(key);
            Self { key, prev }
        }

        fn set(key: &'static str, value: &str) -> Self {
            let prev = std::env::var(key).ok();
            std::env::set_var(key, value);
            Self { key, prev }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            match &self.prev {
                Some(value) => std::env::set_var(self.key, value),
                None => std::env::remove_var(self.key),
            }
        }
    }

    #[test]
    fn pack_lists_all_53_laws() {
        let laws = pack_laws(profiles::LAWS_BEND);
        assert_eq!(laws.len(), 53);
        #[expect(
            clippy::indexing_slicing,
            reason = "already in this crate when the strict table was turned on"
        )]
        let tops_idx_1029_20 = laws[0].clone();
        assert_eq!(tops_idx_1029_20, "evidence_not_self_served");
    }

    #[cfg(unix)]
    #[test]
    fn main_bend_write_refuses_a_symlink_and_does_not_follow_it() {
        use std::os::unix::fs::symlink;
        let dir = std::env::temp_dir().join(format!("cargo-tops-main-bend-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let real = dir.join("real.bend");
        let link = dir.join("main.bend");
        fs::write(&real, "kept").unwrap();
        symlink(&real, &link).unwrap();
        let err = write_refusing_symlink(&link, "replaced").unwrap_err();
        assert!(err.to_string().contains("symlink"), "{err}");
        assert_eq!(fs::read_to_string(&real).unwrap(), "kept");
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
    }
}