arvin 0.2.0

A staged cutoff for agent runs, where a run keeps its tools, budget, and sandbox only while it keeps proving progress. Three triggers move the stage, an operator pull, a budget ceiling, and missed proofs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! The setup pins, translated from the Python setup suite the repo
//! was seeded with, brought up to the current fleet standard. Each
//! test names the same fact its Python original named, with the
//! strengthenings the fleet folded in after arvin's Round 1 suite
//! was written, three of them landing with this port: the job level
//! if false pin, the wrong arc label pin, and the CI credential
//! hygiene pin. Two facts changed with the Rust conversion and the
//! change is stated where it lands. The CI gate commands are the
//! Rust gate commands of amended obligation S2, and the contract
//! substance pin asserts the amended S2 phrases.

use std::path::{Path, PathBuf};
use std::process::Command;

use sha2::{Digest, Sha256};

const MARKER: &str = "<!-- repo annex below this line -->";
const GATE_COMMAND: &str = "cargo test";
const SCAN_COMMAND: &str = "cargo run --bin codepoint_scan";
const FMT_COMMAND: &str = "cargo fmt --check";
const CLIPPY_COMMAND: &str = "cargo clippy --all-targets -- -D warnings";

fn root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

fn read(name: &str) -> String {
    std::fs::read_to_string(root().join(name)).unwrap()
}

fn temp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("arvin-setup-test-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn seed_files_exist() {
    for name in ["README.md", "LICENSE", ".gitignore"] {
        assert!(root().join(name).is_file(), "{name}");
    }
}

#[test]
fn license_starts_with_mit_heading() {
    assert!(read("LICENSE").starts_with("MIT License\n"));
}

#[test]
fn agents_has_marker_and_arvin_annex_below_it() {
    let text = read("AGENTS.md");
    assert!(text.contains(MARKER));
    let annex = text.split(MARKER).nth(1).unwrap();
    assert!(annex.contains("arvin"));
    assert!(annex.contains("CONTRACT.md"));
    assert!(annex.contains("staged kill switch"));
}

#[test]
fn agents_annex_names_the_five_stages_in_order() {
    let text = read("AGENTS.md");
    let annex = text.split(MARKER).nth(1).unwrap();
    assert!(
        annex.contains("the stage names warn and throttle and cut tools and cut budget and kill")
    );
}

#[test]
fn agents_canonical_part_carries_program_headings() {
    let text = read("AGENTS.md");
    let canonical = text.split(MARKER).next().unwrap();
    assert!(canonical.starts_with("# AGENTS.md\n"));
    assert!(canonical.contains("## The round discipline"));
    assert!(canonical.contains("## Contract first"));
    assert!(canonical.contains("39 repo storefront perfection program"));
}

#[test]
fn contract_names_five_setup_obligations() {
    let text = read("CONTRACT.md");
    for name in ["S1", "S2", "S3", "S4", "S5"] {
        assert!(
            text.contains(&format!("Obligation {name} covers")),
            "{name}"
        );
    }
    assert!(!text.contains("Obligation S6"));
}

fn status_section(text: &str) -> &str {
    let start = text.find("\n## Status\n").unwrap() + "\n## Status\n".len();
    let rest = &text[start..];
    match rest.find("\n## ") {
        Some(end) => &rest[..end],
        None => rest,
    }
}

#[test]
fn readme_status_states_one_hundred_of_one_hundred() {
    let text = read("README.md");
    assert!(text.contains("## Status"));
    let status = status_section(&text);
    // The full sentence, never the bare count, because the
    // bare count is a substring of every two digit count that
    // ends in the same digit and a pin on it would pass over
    // a wrong statement of the closed rounds.
    assert!(status.contains("Closed perfection rounds are 100 of 100."));
    assert!(status.contains("aa48f0fe5d57b8bc0e01db2c687ed128e1e0f2d4"));
}

/// Whether an `if:` value disables its step or job. The value
/// is read through its quote marks and through the expression
/// wrapper GitHub Actions accepts, because a step disabled as
/// ${{ false }} is skipped exactly as one disabled as false.
fn if_value_is_false(value: &str) -> bool {
    let value = value
        .trim()
        .trim_matches(|c| c == '\'' || c == '"')
        .trim_start_matches("${{")
        .trim_end_matches("}}")
        .trim()
        .trim_matches(|c| c == '\'' || c == '"')
        .to_lowercase();
    value == "false"
}

fn flush_step(step_lines: &mut Vec<String>, commands: &mut Vec<String>) {
    if step_lines.is_empty() {
        return;
    }
    let mut disabled = false;
    let mut runs = Vec::new();
    for stripped in step_lines.iter() {
        if let Some(value) = stripped.strip_prefix("if:") {
            if if_value_is_false(value) {
                disabled = true;
            }
        }
        if let Some(command) = stripped.strip_prefix("run:") {
            runs.push(command.trim().to_string());
        }
    }
    if !disabled {
        commands.extend(runs);
    }
    step_lines.clear();
}

fn run_commands(ci_text: &str) -> Vec<String> {
    let mut commands = Vec::new();
    let mut step_lines: Vec<String> = Vec::new();
    let mut in_steps = false;
    let mut in_test_job = false;
    let mut job_disabled = false;
    for line in ci_text.lines() {
        let stripped = line.trim();
        if stripped.starts_with('#') {
            continue;
        }
        if stripped == "test:" {
            in_test_job = true;
            continue;
        }
        if in_test_job && !in_steps && stripped.starts_with("if:") {
            let value = stripped
                .split_once(':')
                .map(|(_, rest)| rest)
                .unwrap_or_default();
            if if_value_is_false(value) {
                job_disabled = true;
            }
            continue;
        }
        if stripped == "steps:" {
            in_steps = true;
            continue;
        }
        if in_steps && stripped.starts_with("- ") {
            flush_step(&mut step_lines, &mut commands);
            step_lines.push(stripped[2..].trim().to_string());
            continue;
        }
        if in_steps {
            step_lines.push(stripped.to_string());
        }
    }
    flush_step(&mut step_lines, &mut commands);
    if job_disabled {
        return Vec::new();
    }
    commands
}

#[test]
fn ci_runs_the_local_gate_commands() {
    let commands = run_commands(&read(".github/workflows/ci.yml"));
    assert!(commands.iter().any(|c| c == GATE_COMMAND));
    assert!(commands.iter().any(|c| c == SCAN_COMMAND));
    assert!(commands.iter().any(|c| c == FMT_COMMAND));
    assert!(commands.iter().any(|c| c == CLIPPY_COMMAND));
}

/// The pytest file arguments the workflow's binding job
/// names, read from the binding job's own section of the
/// workflow text, so a judgement about the binding job never
/// borrows a line from another job. A job section runs from
/// its two space key to the next two space key.
fn binding_pytest_files(ci_text: &str) -> Vec<String> {
    let mut files = Vec::new();
    let mut in_binding = false;
    for line in ci_text.lines() {
        let stripped = line.trim();
        let job_key = line.starts_with("  ")
            && !line.starts_with("   ")
            && stripped.ends_with(':')
            && !stripped.contains(' ');
        if job_key {
            in_binding = stripped == "binding:";
            continue;
        }
        if in_binding && stripped.starts_with("python -m pytest") {
            files.extend(
                stripped
                    .split_whitespace()
                    .skip(3)
                    .map(|name| name.to_string()),
            );
        }
    }
    files
}

#[test]
fn ci_binding_job_runs_both_binding_suites() {
    // DM-A23: DM-A8's repair made the binding job run both
    // Python suites, and no pin guarded the repair, so the
    // replay file could drop out of the binding job with
    // every pin green. This pin reads the binding job's own
    // section and names both files.
    let files = binding_pytest_files(&read(".github/workflows/ci.yml"));
    assert!(
        files.iter().any(|f| f == "tests/test_binding_smoke.py"),
        "{files:?}"
    );
    assert!(
        files.iter().any(|f| f == "tests/test_binding_replay.py"),
        "{files:?}"
    );
    // The plausible wrong forms of the regression must fail
    // the helper: the binding job naming the smoke file
    // alone, the replay file alone, and a text whose binding
    // job names the smoke file alone while another job's
    // pytest line names both, which the helper must not
    // borrow across the job boundary.
    let binding_head = "jobs:\n  binding:\n    steps:\n      - name: Build the binding\n        run: |\n          python -m pytest ";
    let both = binding_pytest_files(&format!(
        "{binding_head}tests/test_binding_smoke.py tests/test_binding_replay.py\n"
    ));
    assert_eq!(both.len(), 2, "{both:?}");
    let smoke_only = binding_pytest_files(&format!("{binding_head}tests/test_binding_smoke.py\n"));
    assert!(
        !smoke_only
            .iter()
            .any(|f| f == "tests/test_binding_replay.py"),
        "{smoke_only:?}"
    );
    let replay_only =
        binding_pytest_files(&format!("{binding_head}tests/test_binding_replay.py\n"));
    assert!(
        !replay_only
            .iter()
            .any(|f| f == "tests/test_binding_smoke.py"),
        "{replay_only:?}"
    );
    let borrowed = binding_pytest_files(
        "jobs:\n  test:\n    steps:\n      - run: python -m pytest tests/test_binding_smoke.py tests/test_binding_replay.py\n  binding:\n    steps:\n      - name: Build the binding\n        run: |\n          python -m pytest tests/test_binding_smoke.py\n",
    );
    assert!(
        !borrowed.iter().any(|f| f == "tests/test_binding_replay.py"),
        "{borrowed:?}"
    );
}

#[test]
fn ci_carries_the_fleet_credential_hygiene() {
    let text = read(".github/workflows/ci.yml");
    // The workflow asks for no more than it uses. Its token
    // is limited to reading the repository, the checkout
    // leaves no credential behind for later steps, and the
    // toolchain action is pinned to a full commit SHA rather
    // than a moving branch name.
    assert!(text.contains("permissions:"));
    assert!(text.contains("contents: read"));
    assert!(text
        .lines()
        .any(|line| line.trim() == "persist-credentials: false"));
    assert!(!text.contains("rust-toolchain@master"));
    assert!(toolchain_pins_all_full(&text));
}

/// Whether every toolchain step in a workflow text stands
/// pinned to a full commit SHA, and at least one stands in
/// the text at all. The workflow carries the toolchain step
/// once per job, so the judgement runs over every line that
/// names the action, not the first alone.
fn toolchain_pins_all_full(text: &str) -> bool {
    let mut seen = false;
    for line in text.lines() {
        if let Some((_, pin)) = line.split_once("dtolnay/rust-toolchain@") {
            seen = true;
            let pin = pin.trim();
            if pin.len() != 40
                || !pin
                    .bytes()
                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
            {
                return false;
            }
        }
    }
    seen
}

#[test]
fn ci_toolchain_pin_judges_every_toolchain_line() {
    let ci_text = read(".github/workflows/ci.yml");
    assert!(toolchain_pins_all_full(&ci_text));
    // A second toolchain step repinned to a branch name or a
    // short digest passes the first line judgement this pin
    // replaces, so the every line judgement must refuse both
    // texts, and a text carrying no toolchain step at all.
    let pinned = "      - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8\n";
    let branch = "      - uses: dtolnay/rust-toolchain@master\n";
    let short = "      - uses: dtolnay/rust-toolchain@683b588\n";
    assert!(toolchain_pins_all_full(&format!("{pinned}{pinned}")));
    assert!(!toolchain_pins_all_full(&format!("{pinned}{branch}")));
    assert!(!toolchain_pins_all_full(&format!("{pinned}{short}")));
    assert!(!toolchain_pins_all_full("name: CI\n"));
}

#[test]
fn ci_gate_parser_skips_a_step_disabled_with_if_false() {
    let ci_text = read(".github/workflows/ci.yml");
    let gate_step = "      - name: Run the local gate\n        run: cargo test";
    assert!(ci_text.contains(gate_step));
    for flag in ["false", "\"false\"", "${{ false }}", "${{false}}"] {
        let disabled = ci_text.replace(
            gate_step,
            &format!(
                "      - name: Run the local gate\n        if: {flag}\n        run: cargo test"
            ),
        );
        let commands = run_commands(&disabled);
        assert!(!commands.iter().any(|c| c == GATE_COMMAND));
        assert!(commands.iter().any(|c| c == SCAN_COMMAND));
    }
}

#[test]
fn ci_gate_parser_rejects_a_job_disabled_with_if_false() {
    let ci_text = read(".github/workflows/ci.yml");
    let job_head = "  test:\n    runs-on: ubuntu-latest";
    assert!(ci_text.contains(job_head));
    for flag in ["false", "\"false\"", "${{ false }}", "${{false}}"] {
        let disabled = ci_text.replace(
            job_head,
            &format!("  test:\n    if: {flag}\n    runs-on: ubuntu-latest"),
        );
        let commands = run_commands(&disabled);
        assert!(!commands.iter().any(|c| c == GATE_COMMAND));
        assert!(!commands.iter().any(|c| c == SCAN_COMMAND));
        assert!(!commands.iter().any(|c| c == FMT_COMMAND));
        assert!(!commands.iter().any(|c| c == CLIPPY_COMMAND));
    }
    let commands = run_commands(&ci_text);
    assert!(commands.iter().any(|c| c == GATE_COMMAND));
    assert!(commands.iter().any(|c| c == SCAN_COMMAND));
    assert!(commands.iter().any(|c| c == FMT_COMMAND));
    assert!(commands.iter().any(|c| c == CLIPPY_COMMAND));
}

struct ScanOutput {
    status: i32,
    stdout: String,
    stderr: String,
}

fn scan_tree(root: &Path) -> ScanOutput {
    let output = Command::new(env!("CARGO_BIN_EXE_codepoint_scan"))
        .arg(root)
        .output()
        .unwrap();
    ScanOutput {
        status: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    }
}

#[test]
fn codepoint_scan_reports_zero_for_the_repo() {
    let result = scan_tree(&root());
    assert_eq!(result.status, 0, "{}", result.stdout);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

const CANONICAL_ABOVE_MARKER_SHA256: &str =
    "bb3e2fc1790b13729da3495c3f0902b968577f4e45ceb27e48e90b489f36e1a7";

#[test]
fn agents_canonical_part_matches_pinned_digest() {
    let agents = std::fs::read(root().join("AGENTS.md")).unwrap();
    let marker: &[u8] = b"<!-- repo annex below this line -->";
    let position = agents
        .windows(marker.len())
        .position(|window| window == marker)
        .unwrap();
    let mut hasher = Sha256::new();
    hasher.update(&agents[..position]);
    let digest: String = hasher
        .finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    assert_eq!(digest, CANONICAL_ABOVE_MARKER_SHA256);
}

#[test]
fn readme_has_exactly_one_status_section() {
    let text = read("README.md");
    assert_eq!(text.matches("\n## Status\n").count(), 1);
}

#[test]
fn readme_carries_no_wrong_arc_label() {
    assert!(!read("README.md").contains("Fleet Operations"));
}

#[test]
fn codepoint_scan_counts_an_em_dash() {
    let dir = temp_dir("em-dash");
    std::fs::write(dir.join("note.md"), "a\u{2014}b").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
    assert!(result.stdout.contains("note.md"));
}

#[test]
fn codepoint_scan_counts_an_en_dash() {
    let dir = temp_dir("en-dash");
    std::fs::write(dir.join("note.md"), "a\u{2013}b").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("en dash U+2013 count 1"));
    assert!(result.stdout.contains("em dash U+2014 count 0"));
}

#[test]
fn codepoint_scan_scans_a_root_under_an_excluded_ancestor() {
    let dir = temp_dir("excluded-ancestor").join("venv").join("tree");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("note.md"), "a\u{2014}b").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

#[test]
fn codepoint_scan_skips_excluded_dirs_below_the_root() {
    let dir = temp_dir("excluded-dirs");
    let cache = dir.join("build");
    std::fs::create_dir_all(&cache).unwrap();
    std::fs::write(cache.join("note.md"), "a\u{2014}b").unwrap();
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 0);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

#[test]
fn contract_obligations_carry_their_substance() {
    let text = read("CONTRACT.md");
    for phrase in [
        "present from the first commit",
        "every later change lands through a pull request",
        "no paid service",
        "cargo test plus the codepoint scan run through cargo",
        "0 of 100 until a full cycle",
        "no file carries a real trace or a real transcript or a real name",
        "SHA-256 digest of the part above the marked line",
    ] {
        assert!(text.contains(phrase), "{phrase}");
    }
}

#[test]
fn codepoint_scan_fails_loudly_on_undecodable_input() {
    let dir = temp_dir("undecodable");
    std::fs::write(dir.join("note.md"), b"\xff\xfe not utf-8").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 2);
    assert!(result.stderr.contains("note.md"));
}

#[test]
fn codepoint_scan_counts_a_dash_in_a_file_with_no_suffix() {
    let dir = temp_dir("no-suffix");
    std::fs::write(dir.join("LICENSE"), "a\u{2014}b").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

#[test]
fn codepoint_scan_counts_a_dash_in_an_uppercase_suffix_file() {
    let dir = temp_dir("upper-suffix");
    std::fs::write(dir.join("UPPER.MD"), "a\u{2014}b").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

#[test]
fn codepoint_scan_skips_a_file_with_an_uppercase_binary_suffix() {
    let dir = temp_dir("upper-binary");
    std::fs::write(dir.join("FAKE.PNG"), "a\u{2014}b").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 0);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

#[test]
fn codepoint_scan_refuses_a_root_that_does_not_stand() {
    // The port names this refusal a deliberate difference
    // from the setup scanner, which exited 0 with zero
    // counts over a root that does not stand, a false green
    // over a tree that was never scanned. The root here
    // stands beneath a directory the test creates, and the
    // root itself is never created.
    let root = temp_dir("missing-root").join("no-such-tree");
    let result = scan_tree(&root);
    assert_eq!(result.status, 2);
    assert!(result.stderr.contains("scan error"), "{}", result.stderr);
    assert!(result.stderr.contains("no-such-tree"), "{}", result.stderr);
    assert!(result.stdout.is_empty(), "{}", result.stdout);
}

#[test]
fn codepoint_scan_refuses_an_extra_argument() {
    // DM-A25: the scanner read its root from the first
    // argument and never examined the rest, so a call naming
    // two clean roots scanned one and reported success for
    // the whole call. The call now refuses before any
    // scanning, at exit 2, with empty stdout.
    let first = temp_dir("extra-arg-first");
    let second = temp_dir("extra-arg-second");
    std::fs::write(first.join("clean.md"), "clean").unwrap();
    std::fs::write(second.join("clean.md"), "clean").unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_codepoint_scan"))
        .arg(&first)
        .arg(&second)
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    assert_eq!(
        String::from_utf8_lossy(&output.stderr),
        "scan error, unexpected extra argument after the scan root\n"
    );
    assert!(output.stdout.is_empty());
}

/// Return a writable stream whose writes fail immediately, preferring
/// /dev/full when the host provides it and falling back to an
/// anonymous pipe whose reader has already been closed.
fn dead_stream() -> std::process::Stdio {
    use std::io::Write;
    if let Ok(mut file) = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/full")
    {
        if file.write_all(b"probe").is_err() {
            return std::process::Stdio::from(file);
        }
    }
    // Portability adaptation retries pipe creation when a concurrent child
    // spawn on macOS inherits reader before FIOCLEX closes the race window.
    for _ in 0..64 {
        let (reader, mut writer) = std::io::pipe().expect("the anonymous pipe opens");
        drop(reader);
        if writer.write_all(b"probe").is_err() {
            return std::process::Stdio::from(writer);
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    panic!("writes to a closed pipe must fail")
}

#[test]
fn codepoint_scan_reports_a_failed_output_write() {
    // DM-A24: the scanner printed its report through the
    // panicking macros, so a failed write panicked. The
    // report now goes out through a checked writer, and a
    // failed write answers the scan error line at exit 2.
    // The device is opened for writing, because a read only
    // descriptor's writes are silently accepted by the
    // standard output layer and the drive would prove
    // nothing. Portability adaptation uses dead_stream so
    // hosts without /dev/full prove the same failing write
    // through a closed pipe.
    let dir = temp_dir("full-output");
    std::fs::write(dir.join("note.md"), "a\u{2014}b").unwrap();
    let dead = dead_stream();
    let output = Command::new(env!("CARGO_BIN_EXE_codepoint_scan"))
        .arg(&dir)
        .stdout(dead)
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    assert_eq!(
        String::from_utf8_lossy(&output.stderr),
        "scan error, the scan output could not be written\n"
    );
}

#[test]
fn codepoint_scan_extra_argument_on_dead_stderr_exits_two() {
    let dir = temp_dir("extra-arg-dead-stderr");
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    let status = Command::new(env!("CARGO_BIN_EXE_codepoint_scan"))
        .arg(&dir)
        .arg("second-root")
        .stdout(std::process::Stdio::null())
        .stderr(dead_stream())
        .status()
        .unwrap();
    assert_eq!(status.code(), Some(2));
}

#[test]
fn portability_workflow_carries_the_fleet_credential_hygiene() {
    let port_text = read(".github/workflows/portability.yml");
    assert!(port_text.contains("permissions:\n  contents: read"));
    assert!(!port_text.contains("write-all"));
    assert!(!port_text.contains("contents: write"));
    let checkouts = port_text.matches("actions/checkout@").count();
    assert_eq!(checkouts, 4);
    assert_eq!(
        port_text.matches("persist-credentials: false").count(),
        checkouts
    );
    assert!(!port_text.contains("rust-toolchain@master"));
    assert!(toolchain_pins_all_full(&port_text));
}

#[test]
fn codepoint_scan_skips_every_excluded_dir_below_the_root() {
    let dir = temp_dir("excluded-dirs-all");
    for name in [
        ".git",
        "__pycache__",
        ".pytest_cache",
        ".venv",
        "venv",
        "node_modules",
        "build",
        "dist",
        "target",
    ] {
        let excluded = dir.join(name);
        std::fs::create_dir_all(&excluded).unwrap();
        std::fs::write(excluded.join("note.md"), "a\u{2014}b").unwrap();
    }
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 0);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
    let control = temp_dir("excluded-dirs-all-control");
    let inside = control.join("real-dir");
    std::fs::create_dir_all(&inside).unwrap();
    std::fs::write(inside.join("note.md"), "a\u{2014}b").unwrap();
    let result = scan_tree(&control);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
}

#[test]
fn codepoint_scan_skips_every_binary_suffix() {
    let dir = temp_dir("binary-suffixes-all");
    for suffix in [
        "png", "jpg", "jpeg", "gif", "ico", "webp", "pdf", "zip", "gz", "tar", "whl", "so", "dylib",
    ] {
        std::fs::write(dir.join(format!("sample.{suffix}")), "a\u{2014}b").unwrap();
    }
    let result = scan_tree(&dir);
    assert_eq!(result.status, 0);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
    let control = temp_dir("binary-suffixes-all-control");
    std::fs::write(control.join("note.md"), "a\u{2014}b").unwrap();
    let result = scan_tree(&control);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
}

// Portability adaptation gates mkfifo and Unix symlink pins to Unix.
#[cfg(unix)]
#[test]
fn codepoint_scan_completes_over_a_fifo_in_the_tree() {
    let dir = temp_dir("fifo");
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    let pipe_path = dir.join("planted-pipe");
    let status = Command::new("mkfifo").arg(&pipe_path).status().unwrap();
    assert!(status.success());
    let (tx, rx) = std::sync::mpsc::channel();
    let dir_clone = dir.clone();
    std::thread::spawn(move || {
        let _ = tx.send(scan_tree(&dir_clone));
    });
    let result = rx
        .recv_timeout(std::time::Duration::from_secs(10))
        .expect("the scan did not finish inside its bound");
    assert_eq!(result.status, 0, "{}", result.stderr);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

// Portability adaptation gates mkfifo and Unix symlink pins to Unix.
#[cfg(unix)]
#[test]
fn codepoint_scan_completes_over_a_dangling_symlink() {
    let dir = temp_dir("dangling-symlink");
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    std::os::unix::fs::symlink(dir.join("no-such-target"), dir.join("dangling.md")).unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 0, "{}", result.stderr);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

// Portability adaptation gates mkfifo and Unix symlink pins to Unix.
#[cfg(unix)]
#[test]
fn codepoint_scan_completes_over_a_symlink_to_a_fifo() {
    let dir = temp_dir("symlink-fifo");
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    let pipe_path = dir.join("planted-pipe");
    let status = Command::new("mkfifo").arg(&pipe_path).status().unwrap();
    assert!(status.success());
    std::os::unix::fs::symlink(&pipe_path, dir.join("linked-pipe")).unwrap();
    let (tx, rx) = std::sync::mpsc::channel();
    let dir_clone = dir.clone();
    std::thread::spawn(move || {
        let _ = tx.send(scan_tree(&dir_clone));
    });
    let result = rx
        .recv_timeout(std::time::Duration::from_secs(10))
        .expect("the scan did not finish inside its bound");
    assert_eq!(result.status, 0, "{}", result.stderr);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
}

// Portability adaptation gates mkfifo and Unix symlink pins to Unix.
#[cfg(unix)]
#[test]
fn codepoint_scan_counts_a_dash_behind_a_symlink_to_a_regular_file() {
    let dir = temp_dir("symlink-file");
    let target = dir.join("real.md");
    std::fs::write(&target, "a\u{2014}b").unwrap();
    std::os::unix::fs::symlink(&target, dir.join("linked.md")).unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 2"));
}

// Portability adaptation gates mkfifo and Unix symlink pins to Unix.
#[cfg(unix)]
#[test]
fn codepoint_scan_does_not_follow_a_symlink_to_a_directory() {
    let outside = temp_dir("symlink-dir-outside");
    std::fs::write(outside.join("note.md"), "a\u{2014}b").unwrap();
    let dir = temp_dir("symlink-dir");
    std::fs::write(dir.join("clean.md"), "clean").unwrap();
    std::os::unix::fs::symlink(&outside, dir.join("linked-dir")).unwrap();
    let result = scan_tree(&dir);
    assert_eq!(result.status, 0, "{}", result.stderr);
    assert!(result.stdout.contains("em dash U+2014 count 0"));
    assert!(result.stdout.contains("en dash U+2013 count 0"));
    let control = temp_dir("symlink-dir-control");
    let inside = control.join("real-dir");
    std::fs::create_dir_all(&inside).unwrap();
    std::fs::write(inside.join("note.md"), "a\u{2014}b").unwrap();
    let result = scan_tree(&control);
    assert_eq!(result.status, 1);
    assert!(result.stdout.contains("em dash U+2014 count 1"));
}

fn job_sections(workflow_text: &str) -> Vec<(String, String)> {
    let mut jobs: Vec<(String, String)> = Vec::new();
    let mut in_jobs = false;
    let mut current_name: Option<String> = None;
    let mut current_body = String::new();
    for line in workflow_text.lines() {
        if line == "jobs:" {
            in_jobs = true;
            continue;
        }
        if !in_jobs {
            continue;
        }
        let is_job_header = line.starts_with("  ")
            && !line.starts_with("   ")
            && line.trim_end().ends_with(':')
            && !line.trim().contains(' ');
        if is_job_header {
            if let Some(prev) = current_name.take() {
                jobs.push((prev, std::mem::take(&mut current_body)));
            }
            current_name = Some(line.trim().trim_end_matches(':').to_string());
        } else if current_name.is_some() {
            current_body.push_str(line);
            current_body.push('\n');
        }
    }
    if let Some(prev) = current_name {
        jobs.push((prev, current_body));
    }
    jobs
}

fn checkout_steps_all_disable_credentials(workflow_text: &str) -> usize {
    let mut count = 0usize;
    for (_, body) in job_sections(workflow_text) {
        let mut in_checkout = false;
        let mut saw_false = false;
        for line in body.lines() {
            let trimmed = line.trim_start();
            if trimmed.starts_with("- ") {
                if in_checkout {
                    assert!(
                        saw_false,
                        "checkout step missing persist-credentials: false in:\n{body}"
                    );
                }
                in_checkout = trimmed.contains("actions/checkout@");
                saw_false = false;
                if in_checkout {
                    count += 1;
                }
            } else if in_checkout && trimmed == "persist-credentials: false" {
                saw_false = true;
            }
        }
        if in_checkout {
            assert!(
                saw_false,
                "checkout step missing persist-credentials: false in:\n{body}"
            );
        }
    }
    count
}

#[test]
fn dm26_release_packaging_metadata_and_version_parity() {
    assert_eq!(env!("CARGO_PKG_VERSION"), "0.2.0");
    let cargo_toml = read("Cargo.toml");
    for required in [
        "version = \"0.2.0\"",
        "rust-version = \"1.91\"",
        "default-run = \"arvin\"",
        "readme = \"README.md\"",
        "repository = \"https://github.com/david-engelmann/arvin\"",
        "homepage = \"https://github.com/david-engelmann/arvin\"",
        "documentation = \"https://docs.rs/arvin\"",
        "keywords = [",
        "categories = [",
        "\".github/**\"",
        "\"bindings/**\"",
        "\"python/**\"",
        "\"pyproject.toml\"",
        "\"tests/fixtures/**\"",
    ] {
        assert!(cargo_toml.contains(required), "missing {required}");
    }
    let bind_cargo = read("bindings/Cargo.toml");
    assert!(bind_cargo.contains("version = \"0.2.0\""));
    assert!(bind_cargo.contains("publish = false"));
    assert!(!root().join("bindings/pyproject.toml").exists());
    let pyproject = read("pyproject.toml");
    assert!(pyproject.contains("version = \"0.2.0\""));
    assert!(pyproject.contains("readme = \"README.md\""));
    assert!(pyproject.contains("manifest-path = \"bindings/Cargo.toml\""));
    assert!(pyproject.contains("python-source = \"python\""));
    assert!(pyproject.contains("[project.urls]"));
    let init_py = read("python/arvin/__init__.py");
    assert!(init_py.contains("__version__ = \"0.2.0\""));
    assert!(init_py.contains("\"__version__\""));
    assert!(root().join("python/arvin/py.typed").is_file());
    assert!(root().join("python/arvin/__init__.pyi").is_file());

    let ver_out = Command::new(env!("CARGO_BIN_EXE_arvin"))
        .arg("--version")
        .output()
        .unwrap();
    assert_eq!(ver_out.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&ver_out.stdout), "arvin 0.2.0\n");

    let changelog = read("CHANGELOG.md");
    assert!(changelog.contains("## 0.2.0"));
    assert!(changelog.contains("## 0.1.0"));
    let security = read("SECURITY.md");
    assert!(security.contains("0.2.x"));
    assert!(security.contains("GitHub Security Advisories"));
}

#[test]
fn dm26_release_workflow_carries_the_fleet_credential_hygiene() {
    let rel_text = read(".github/workflows/release.yml");
    assert!(rel_text.contains("permissions:\n  contents: read"));
    assert!(rel_text.contains("- \"v*\""));
    assert!(rel_text.contains("workflow_dispatch:"));
    assert!(!rel_text.contains("write-all"));
    assert!(!rel_text.contains("rust-toolchain@master"));
    assert!(!rel_text.contains("python3 -"));
    let checkouts = checkout_steps_all_disable_credentials(&rel_text);
    assert_eq!(checkouts, 5);
    assert!(toolchain_pins_all_full(&rel_text));

    let write_lines: Vec<&str> = rel_text
        .lines()
        .filter(|line| line.contains(": write"))
        .collect();
    assert_eq!(
        write_lines,
        vec!["      id-token: write", "      contents: write"]
    );

    let jobs = job_sections(&rel_text);
    let names: Vec<&str> = jobs.iter().map(|(n, _)| n.as_str()).collect();
    assert_eq!(
        names,
        vec![
            "verify",
            "binaries",
            "wheels",
            "sdist",
            "publish-crates",
            "publish-pypi",
            "github-release",
        ]
    );
    for (name, body) in &jobs {
        match name.as_str() {
            "verify" => {
                assert!(body.contains("REF_TYPE:"));
                assert!(body.contains("REF_NAME:"));
                assert!(body.contains("expected = f\"v{ver}\""));
            }
            "binaries" => {
                assert!(body.contains("    needs: verify\n"));
                for triple in [
                    "x86_64-unknown-linux-gnu",
                    "aarch64-unknown-linux-gnu",
                    "aarch64-apple-darwin",
                    "x86_64-pc-windows-msvc",
                ] {
                    assert!(body.contains(triple), "missing {triple}");
                }
            }
            "wheels" => {
                assert!(body.contains("    needs: verify\n"));
                for runner in [
                    "ubuntu-latest",
                    "ubuntu-24.04-arm",
                    "macos-latest",
                    "windows-latest",
                ] {
                    assert!(body.contains(runner), "missing {runner}");
                }
                assert!(body.contains("Verify wheel PEP 561 entries"));
            }
            "sdist" => {
                assert!(body.contains("    needs: verify\n"));
            }
            "publish-crates" | "publish-pypi" | "github-release" => {
                let (header, _) = body.split_once("\n    steps:\n").expect("steps header");
                assert!(header
                    .lines()
                    .any(|l| l == "    needs: [verify, binaries, wheels, sdist]"));
                assert!(header
                    .lines()
                    .any(|l| l == "    if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')"));
                if name == "github-release" {
                    assert!(header.lines().any(|l| l == "      contents: write"));
                } else {
                    assert!(!body.contains("contents: write"));
                }
                if name == "publish-pypi" {
                    assert!(header.lines().any(|l| l == "      id-token: write"));
                } else {
                    assert!(!body.contains("id-token: write"));
                }
            }
            other => panic!("unexpected job {other}"),
        }
    }
}