brygge 0.7.0

Carry version-control history out of Git, Mercurial, Subversion and CVS into an intermediate representation (IR), with every inference marked and every loss recorded: decode, inspect and verify.
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
//! End-to-end subprocess tests against the real compiled binary (handoff `cli-and-verify-handoff-v2.md`
//! §5.2): properties only observable at the process boundary — real stderr, real exit codes — that a
//! unit test inside `src/` cannot see (`CARGO_BIN_EXE_brygge` is only set for `tests/*.rs`). Skips
//! without `git` on `PATH`.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

const USAGE: i32 = 2;
const FLOOR_REFUSAL: i32 = 20;
#[cfg(target_os = "linux")]
const FAILURE: i32 = 1;

static COUNTER: AtomicU64 = AtomicU64::new(0);

fn git_available() -> bool {
    Command::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

struct TempRepo {
    dir: PathBuf,
}

impl Drop for TempRepo {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

impl TempRepo {
    fn new() -> Self {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "brygge-cli-itest-{}-{nanos}-{n}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let r = Self { dir };
        r.git(&["init", "-q", "--initial-branch=main"]);
        r
    }

    fn path(&self) -> &Path {
        &self.dir
    }

    fn git(&self, args: &[&str]) -> String {
        let out = Command::new("git")
            .current_dir(&self.dir)
            .args(args)
            .env("GIT_AUTHOR_NAME", "A U Thor")
            .env("GIT_AUTHOR_EMAIL", "author@example.com")
            .env("GIT_AUTHOR_DATE", "2005-04-07T22:13:13 +0000")
            .env("GIT_COMMITTER_NAME", "C O Mitter")
            .env("GIT_COMMITTER_EMAIL", "committer@example.com")
            .env("GIT_COMMITTER_DATE", "2005-04-07T22:13:13 +0000")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .output()
            .expect("run git");
        assert!(out.status.success(), "git {args:?} failed");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    fn commit(&self, file: &str, contents: &str, msg: &str) {
        std::fs::write(self.dir.join(file), contents).unwrap();
        self.git(&["add", "-A"]);
        self.git(&["-c", "commit.gpgsign=false", "commit", "-q", "-m", msg]);
    }
}

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_brygge")
}

#[test]
fn faithfulness_statement_reaches_stderr_even_when_decode_then_fails() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("a.txt", "one\n", "c1");
    // A submodule triggers a floor refusal (decode fails) after the statement must already be printed.
    let head = repo.git(&["rev-parse", "HEAD"]);
    repo.git(&[
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("160000,{head},sub"),
    ]);
    repo.git(&[
        "-c",
        "commit.gpgsign=false",
        "commit",
        "-q",
        "-m",
        "add gitlink",
    ]);
    let out = repo.dir.join("out.ir");
    let output = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .output()
        .expect("run brygge decode");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(FLOOR_REFUSAL),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains(
            "Git: content, history and messages are carried as the source recorded them."
        ),
        "the faithfulness statement must print even though decode then fails: {stderr}"
    );
    assert!(!out.exists(), "no artifact is written on a refusal");
}

#[test]
fn faithfulness_statement_reaches_stderr_on_a_successful_decode_too() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("a.txt", "one\n", "c1");
    let out = repo.dir.join("out.ir");
    let output = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .output()
        .expect("run brygge decode");
    assert_eq!(output.status.code(), Some(0));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("Git: content, history and messages"));
    assert!(stderr.contains(&format!("wrote {}", out.display())));
}

#[test]
fn a_usage_error_exits_2_and_names_the_problem() {
    let output = Command::new(bin())
        .args(["decode", "git", "/does-not-matter"])
        .output()
        .expect("run brygge decode without --out");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("--out"), "{stderr}");
    assert!(stderr.contains("brygge decode --help"), "{stderr}");
}

#[test]
fn an_inapplicable_option_exits_2_with_the_exact_message() {
    let output = Command::new(bin())
        .args([
            "decode",
            "svn",
            "/does-not-matter",
            "--out",
            "o.ir",
            "--infer-renames",
        ])
        .output()
        .expect("run brygge decode");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--infer-renames applies to git, not to svn"),
        "{stderr}"
    );
}

#[test]
fn encode_with_no_target_is_a_usage_error() {
    let output = Command::new(bin())
        .arg("encode")
        .output()
        .expect("run brygge encode");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("encode needs a target"), "{stderr}");
}

#[test]
fn encode_prikk_exits_2_with_its_own_message_even_with_a_plugin_on_path() {
    // `prikk` is reserved (RFC 017 D-3): never looked up on PATH, even when a real
    // `brygge-encode-prikk` is there.
    let dir = std::env::temp_dir().join(format!(
        "brygge-cli-itest-prikk-path-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let plugin_name = if cfg!(windows) {
        "brygge-encode-prikk.exe"
    } else {
        "brygge-encode-prikk"
    };
    let plugin_path = dir.join(plugin_name);
    std::fs::write(&plugin_path, b"").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&plugin_path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    let output = Command::new(bin())
        .args(["encode", "prikk", "out.ir"])
        .env("PATH", &dir)
        .output()
        .expect("run brygge encode prikk");
    let _ = std::fs::remove_dir_all(&dir);
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("'encode prikk' is not available yet"),
        "{stderr}"
    );
}

#[test]
fn help_lists_only_existing_commands() {
    let output = Command::new(bin())
        .arg("--help")
        .output()
        .expect("run brygge --help");
    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("decode"));
    assert!(stdout.contains("inspect"));
    assert!(stdout.contains("verify"));
    assert!(
        !stdout.contains("summary"),
        "the removed verb must not be listed"
    );
    assert!(
        stdout.contains("encode"),
        "encode is a real command now (RFC 017 D-3), not a placeholder"
    );
}

#[test]
fn infer_renames_for_hg_exits_2_because_mercurial_records_its_renames() {
    let output = Command::new(bin())
        .args([
            "decode",
            "hg",
            "/does-not-matter",
            "--out",
            "o.ir",
            "--infer-renames",
        ])
        .output()
        .expect("run brygge decode hg --infer-renames");
    assert_eq!(output.status.code(), Some(USAGE));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--infer-renames applies to git, not to hg"),
        "{stderr}"
    );
    assert!(stderr.contains("brygge decode --help"), "{stderr}");
    // ... and the help says so too.
    let help = Command::new(bin()).arg("--help").output().unwrap();
    let help = String::from_utf8_lossy(&help.stdout);
    assert!(help.contains("--infer-renames (git)"), "{help}");
}

/// Every machine line is `key=value` with a key of dot-separated `[a-z0-9_]` segments.
fn assert_keys_follow_the_rule(stdout: &str, what: &str) {
    for line in stdout.lines() {
        let (key, _) = line
            .split_once('=')
            .unwrap_or_else(|| panic!("{what}: a machine line without `=`: {line:?}"));
        assert!(!key.is_empty(), "{what}: empty key in {line:?}");
        for seg in key.split('.') {
            assert!(
                !seg.is_empty()
                    && seg
                        .bytes()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_'),
                "{what}: key {key:?} breaks `^[a-z0-9_]+(\\.[a-z0-9_]+)*$`"
            );
        }
    }
}

fn percent_decode(s: &str) -> Vec<u8> {
    let b = s.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            out.push(
                u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap(), 16).unwrap(),
            );
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    out
}

#[test]
fn a_real_run_prints_only_rule_following_keys_one_atoms_line_and_the_exact_message_bytes() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("old.txt", "some content that will move\n", "c1");
    // A non-UTF-8 commit message (Latin-1 é). Git converts an invalid-UTF-8 message to UTF-8 unless the
    // repository declares its commit encoding, so declare Latin-1: the bytes are then stored as given.
    std::fs::rename(repo.dir.join("old.txt"), repo.dir.join("new.txt")).unwrap();
    repo.git(&["add", "-A"]);
    let msg_file = repo
        .dir
        .join("..")
        .join(format!("brygge-msg-{}.txt", std::process::id()));
    std::fs::write(&msg_file, b"caf\xe9 100%\n").unwrap();
    repo.git(&[
        "-c",
        "commit.gpgsign=false",
        "-c",
        "i18n.commitEncoding=ISO-8859-1",
        "commit",
        "-q",
        "-F",
        msg_file.to_str().unwrap(),
    ]);
    let _ = std::fs::remove_file(&msg_file);

    let out = repo.dir.join("out.ir");
    let decode = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .args(["--infer-renames", "--format", "machine"])
        .output()
        .unwrap();
    let decode_out = String::from_utf8(decode.stdout).unwrap();
    assert_keys_follow_the_rule(&decode_out, "decode");
    assert!(
        decode_out.lines().any(|l| l == "report_version=3"),
        "{decode_out}"
    );
    assert!(
        decode_out
            .lines()
            .any(|l| l == "skipped_non_critical_fields=0")
    );
    assert!(
        decode_out
            .lines()
            .any(|l| l.starts_with("derived.inferred_rename=")),
        "{decode_out}"
    );

    let inspect = Command::new(bin())
        .args(["inspect"])
        .arg(&out)
        .args(["--atoms", "--format", "machine"])
        .output()
        .unwrap();
    assert_eq!(inspect.status.code(), Some(0));
    let inspect_out = String::from_utf8(inspect.stdout).unwrap();
    assert_keys_follow_the_rule(&inspect_out, "inspect --atoms");
    assert_eq!(
        inspect_out
            .lines()
            .filter(|l| l.starts_with("atoms="))
            .count(),
        1,
        "one key, one line:\n{inspect_out}"
    );
    assert!(inspect_out.lines().any(|l| l == "inspect_version=4"));
    let message = inspect_out
        .lines()
        .filter_map(|l| l.strip_prefix("atom.1.message="))
        .next()
        .unwrap_or_else(|| panic!("no atom.1.message in\n{inspect_out}"));
    assert_eq!(
        percent_decode(message),
        b"caf\xe9 100%\n",
        "the exact bytes"
    );

    let verify = Command::new(bin())
        .args(["verify"])
        .arg(&out)
        .args(["--format", "machine"])
        .output()
        .unwrap();
    assert_eq!(verify.status.code(), Some(0));
    let verify_out = String::from_utf8(verify.stdout).unwrap();
    assert_keys_follow_the_rule(&verify_out, "verify");
    for line in [
        "verify_version=4",
        "verify.skipped_non_critical_fields=0",
        "verify.check.source_invariants=pass",
        "verify.check.loss_boundary=pass",
        "verify.result=pass",
    ] {
        assert!(
            verify_out.lines().any(|l| l == line),
            "{line} in\n{verify_out}"
        );
    }
}

#[test]
fn a_check_that_could_not_run_says_not_checked_in_both_forms_and_its_detail_follows_its_line() {
    // An artifact that fails to decode: `integrity` fails, and every other check cannot run.
    let path = std::env::temp_dir().join(format!("brygge-garbage-{}.ir", std::process::id()));
    std::fs::write(&path, b"this is not an artifact").unwrap();

    let machine = Command::new(bin())
        .args(["verify"])
        .arg(&path)
        .args(["--format", "machine"])
        .output()
        .unwrap();
    assert_eq!(machine.status.code(), Some(50));
    let m = String::from_utf8(machine.stdout).unwrap();
    assert_keys_follow_the_rule(&m, "verify (garbage)");
    let lines: Vec<&str> = m.lines().collect();
    let structure = lines
        .iter()
        .position(|l| *l == "verify.check.structure=not-checked")
        .unwrap_or_else(|| panic!("{m}"));
    assert!(
        lines[structure + 1].starts_with("verify.check.structure.detail="),
        "{m}"
    );
    assert!(
        lines
            .iter()
            .any(|l| l.starts_with("verify.check.integrity.detail="))
    );
    assert!(!m.contains("n/a"), "{m}");

    let human = Command::new(bin())
        .args(["verify"])
        .arg(&path)
        .output()
        .unwrap();
    let h = String::from_utf8(human.stdout).unwrap();
    assert!(h.contains("[not-checked] structure"), "{h}");
    assert!(!h.contains("n/a"), "{h}");
    let _ = std::fs::remove_file(&path);
}

// ---- the CLI must not panic when its reader closes the pipe (handoff `cli-broken-pipe-handoff-v1.md`) ---

use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read as _};

/// Spawn `args`, read at most one line of stdout, then drop that handle (closing our end of the pipe)
/// before waiting for the child. Returns the exit code and the full stderr text.
fn run_and_close_stdout_after_one_line(args: &[&str]) -> (Option<i32>, String) {
    let mut child = Command::new(bin())
        .args(args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("spawn brygge");
    {
        let stdout = child.stdout.take().expect("piped stdout");
        let mut reader = BufReader::new(stdout);
        let mut line = String::new();
        let _ = reader.read_line(&mut line); // best effort; some reports are a single short line
        // `reader` (and the `ChildStdout` it owns) is dropped here, closing our read end before `wait`.
    }
    let status = child.wait().expect("wait for brygge");
    let mut stderr = String::new();
    child
        .stderr
        .take()
        .expect("piped stderr")
        .read_to_string(&mut stderr)
        .expect("read stderr");
    (status.code(), stderr)
}

/// A synthetic artifact with `n` atoms (one file, modified `n` times), so `inspect --atoms` renders a
/// report far bigger than any pipe buffer (RFC 010-scale default is 64 KiB on Linux): the writer is then
/// genuinely still writing, not merely racing a reader that already drained everything, when our one-line
/// read closes the pipe underneath it.
fn big_artifact(n: usize) -> std::path::PathBuf {
    let mut builder = brygge_ir::builder::IrBuilder::new(brygge_ir::ImportProvenance {
        source: brygge_ir::SourceIdentity {
            kind: brygge_ir::SourceKind::Git,
            repo_id: b"r".to_vec(),
            atom_id: b"r".to_vec(),
            signatures: Vec::new(),
            extras: Vec::new(),
        },
        brygge_version: "0.1.0".into(),
        decoder: "brygge-decode-git".into(),
        decoder_version: "0.1.0".into(),
        params: BTreeMap::new(),
    });
    let mut parent = None;
    for i in 0..n {
        let blob = builder
            .add_blob(format!("content {i}").into_bytes())
            .unwrap();
        let op = if i == 0 {
            brygge_ir::model::PathOp::Add {
                path: "f".into(),
                blob,
                mode: 0o100_644,
                status: brygge_ir::status::EpistemicStatus::Stated,
            }
        } else {
            brygge_ir::model::PathOp::Modify {
                path: "f".into(),
                blob,
                mode: 0o100_644,
                status: brygge_ir::status::EpistemicStatus::Stated,
            }
        };
        let id = builder
            .add_atom(brygge_ir::builder::AtomDraft {
                parents: parent.into_iter().collect(),
                ops: vec![op],
                copies: Vec::new(),
                metadata: brygge_ir::model::MetadataClaims::default(),
                source: brygge_ir::model::SourceIdentity {
                    kind: brygge_ir::SourceKind::Git,
                    repo_id: b"r".to_vec(),
                    atom_id: format!("c{i}").into_bytes(),
                    signatures: Vec::new(),
                    extras: Vec::new(),
                },
                status: brygge_ir::status::EpistemicStatus::Stated,
            })
            .expect("add_atom");
        parent = Some(id);
    }
    let ir = builder.finish().expect("finish");
    let bytes = brygge_ir::to_bytes(&ir);
    let path = std::env::temp_dir().join(format!("brygge-cli-big-{}.ir", std::process::id()));
    std::fs::write(&path, &bytes).unwrap();
    path
}

#[test]
fn version_through_a_closed_pipe_does_not_panic() {
    let (code, stderr) = run_and_close_stdout_after_one_line(&["--version"]);
    assert_eq!(code, Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
}

#[test]
fn inspect_of_a_large_report_through_a_closed_pipe_does_not_panic() {
    // Large enough that the single `write_all` of the rendered report cannot complete in one pipe
    // buffer: the writer is still blocked, mid-write, when our read end closes.
    let path = big_artifact(5_000);
    let (code, stderr) =
        run_and_close_stdout_after_one_line(&["inspect", path.to_str().unwrap(), "--atoms"]);
    let _ = std::fs::remove_file(&path);
    assert_eq!(code, Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
}

#[test]
fn decode_through_a_closed_pipe_still_writes_a_complete_verifying_artifact() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    repo.commit("a.txt", "one\n", "c1");
    let out = repo.dir.join("out.ir");
    let (code, stderr) = run_and_close_stdout_after_one_line(&[
        "decode",
        "git",
        repo.path().to_str().unwrap(),
        "--out",
        out.to_str().unwrap(),
    ]);
    assert_eq!(code, Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
    // The artifact itself does not depend on anyone having read the stdout report.
    assert!(out.exists());
    let verify = Command::new(bin())
        .args(["verify"])
        .arg(&out)
        .output()
        .unwrap();
    assert_eq!(verify.status.code(), Some(0));
}

#[cfg(unix)]
#[test]
fn a_stdout_write_error_that_is_not_a_broken_pipe_exits_failure_with_a_message() {
    // /dev/full always answers ENOSPC: a real, non-pipe stdout write error.
    let full = match std::fs::OpenOptions::new().write(true).open("/dev/full") {
        Ok(f) => f,
        Err(_) => {
            eprintln!("skipping: /dev/full is not available");
            return;
        }
    };
    let out = Command::new(bin())
        .args(["--version"])
        .stdout(full)
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("run brygge");
    assert_eq!(
        out.status.code(),
        Some(1),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("cannot write to stdout"), "{stderr}");
    assert!(!stderr.contains("panicked"), "{stderr}");
}

// ---- RFC 015 D-3a: the spill file is never left behind, however the process ends ------------------

/// A `git fast-import` stream of `n` trivial commits on one file, all pointing at the same blob (so the
/// import itself stays fast) — large enough that `brygge decode` is still running a short time after it
/// starts, which `killing_a_decode_mid_run_leaves_no_spill_file_on_windows` relies on (review 076/077
/// F-1: Unix's cleanup is already proven by "no entry once created"; Windows needs a decode caught
/// genuinely still open when the process ends some other way than a normal return).
#[cfg(windows)]
fn fast_import_stream(n: u32) -> String {
    let mut s = String::with_capacity(64 + n as usize * 96);
    s.push_str("blob\nmark :1\ndata 6\nhello\n");
    let mut prev: Option<u32> = None;
    for i in 0..n {
        let mark = i + 2;
        s.push_str(&format!("commit refs/heads/main\nmark :{mark}\n"));
        s.push_str("author A U Thor <a@example.com> 1112912793 +0000\n");
        s.push_str("committer C O Mitter <c@example.com> 1112912793 +0000\n");
        let msg = format!("c{i}");
        s.push_str(&format!("data {}\n{msg}\n", msg.len()));
        if let Some(p) = prev {
            s.push_str(&format!("from :{p}\n"));
        }
        s.push_str("M 100644 :1 a.txt\n");
        prev = Some(mark);
    }
    s
}

#[cfg(windows)]
fn fast_import(repo: &TempRepo, stream: &str) {
    use std::io::Write as _;
    let mut fi = Command::new("git")
        .current_dir(repo.path())
        .args(["fast-import", "--quiet"])
        .stdin(std::process::Stdio::piped())
        .spawn()
        .expect("spawn git fast-import");
    fi.stdin
        .take()
        .expect("fast-import stdin")
        .write_all(stream.as_bytes())
        .expect("write the fast-import stream");
    assert!(fi.wait().expect("wait on fast-import").success());
}

#[cfg(windows)]
#[test]
fn killing_a_decode_mid_run_leaves_no_spill_file_on_windows() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = TempRepo::new();
    // 200,000 commits: a few seconds for `brygge decode` to walk and verify, ample margin over the
    // short sleep below on any CI runner.
    fast_import(&repo, &fast_import_stream(200_000));

    let out = repo.dir.join("out.ir");
    let spill_dir = repo.dir.join("spill");
    std::fs::create_dir_all(&spill_dir).unwrap();

    let mut child = Command::new(bin())
        .args(["decode", "git"])
        .arg(repo.path())
        .arg("--out")
        .arg(&out)
        .arg("--spill-dir")
        .arg(&spill_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .expect("spawn brygge decode");

    std::thread::sleep(std::time::Duration::from_millis(300));
    let still_running = matches!(child.try_wait(), Ok(None));
    child.kill().expect("terminate the decode");
    let _ = child.wait();

    assert!(
        still_running,
        "the decode already finished before it could be killed; make the fixture larger"
    );
    assert!(!out.exists(), "no artifact from a killed decode");
    let remaining: Vec<_> = std::fs::read_dir(&spill_dir)
        .expect("read the spill directory")
        .collect();
    assert!(
        remaining.is_empty(),
        "a spill file was left behind: {remaining:?}"
    );
}

/// On Unix, [`ContentStore::spilling`]'s own unit tests already prove the directory holds no entry at
/// all once the spill file opens (`content/spill/tests.rs`); that covers a killed process too, since
/// there is never a directory entry for a signal to leave behind.
#[cfg(unix)]
#[test]
fn on_unix_a_killed_decode_is_covered_by_the_no_entry_once_created_proof() {}

/// `--spill-dir` into a filesystem that fills up partway through a decode: a typed error naming the
/// spill directory, a non-zero exit, no artifact, and no leftover temp file (review 076/077 F-3,
/// handoff §5.3). Needs an unprivileged user+mount namespace (`unshare --user --map-root-user`) to
/// create a tiny `tmpfs` without root; skips with a message where that is not available.
#[cfg(target_os = "linux")]
#[test]
fn spill_dir_disk_full_is_a_typed_error_with_no_artifact_and_no_leftover_temp() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    if !Command::new("unshare")
        .args(["--mount", "--user", "--map-root-user", "true"])
        .status()
        .is_ok_and(|s| s.success())
    {
        eprintln!("skipping: unprivileged user+mount namespaces are not available here");
        return;
    }

    let repo = TempRepo::new();
    // A blob well over the 1 MiB tmpfs below, so the spill write fails partway through the decode.
    let big = "x".repeat(2 * 1024 * 1024);
    repo.commit("big.txt", &big, "a big file");

    let out = repo.dir.join("out.ir");
    let spill_dir = repo.dir.join("spill");
    std::fs::create_dir_all(&spill_dir).unwrap();

    let script = format!(
        "mount -t tmpfs -o size=1m tmpfs {} && exec {} decode git {} --out {} --spill-dir {}",
        shell_quote(&spill_dir),
        shell_quote(Path::new(bin())),
        shell_quote(repo.path()),
        shell_quote(&out),
        shell_quote(&spill_dir),
    );
    let output = Command::new("unshare")
        .args(["--mount", "--user", "--map-root-user", "sh", "-c"])
        .arg(&script)
        .output()
        .expect("run brygge decode inside the size-limited tmpfs");

    assert_eq!(output.status.code(), Some(FAILURE), "{output:?}");
    assert!(
        !out.exists(),
        "no artifact when the spill file could not be written"
    );
    let leftovers: Vec<_> = std::fs::read_dir(&repo.dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().contains("brygge-tmp"))
        .collect();
    assert!(
        leftovers.is_empty(),
        "a temporary artifact was left behind: {leftovers:?}"
    );
}

/// Single-quote `path` for a POSIX shell (the fixture paths here are plain temp-dir paths with no
/// single quote in them, so this is simple escaping, not a general-purpose shell-safety claim).
#[cfg(target_os = "linux")]
fn shell_quote(path: &Path) -> String {
    format!("'{}'", path.display())
}