brake 2026.11.3

A brake on breaking API changes. Checks OpenAPI, protobuf and GraphQL contracts for backward compatibility, hermetically.
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
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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
//! Tests for the binary's own surface: argument wiring, exit codes, and the
//! contract between the two.
//!
//! `main.rs` may not decide whether something is a breaking change, but it does
//! decide what gets checked and what the process exits with — and nothing else
//! exercises that. The dropped `paths` argument that made `brake check <file>`
//! check everything was invisible to library tests.

use std::fs;
use std::path::Path;
use std::process::{Command, Output};

use tempfile::{TempDir, tempdir};

const BRAKE: &str = env!("CARGO_BIN_EXE_brake");

const SPEC: &str = r#"
openapi: 3.1.0
paths:
  /payments/{id}:
    get:
      operationId: getPayment
      responses:
        "200":
          description: ok
"#;

const BROKEN: &str = r#"
openapi: 3.1.0
paths: {}
"#;

fn repo(files: &[(&str, &str)]) -> TempDir {
    let repo = tempdir().expect("tempdir");
    for (path, body) in files {
        let full = repo.path().join(path);
        fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        fs::write(full, body).expect("write");
    }
    repo
}

/// A shell command that creates `path` as a marker, in whichever shell
/// `--drift` uses.
///
/// `mkdir` rather than `touch`: it is a builtin in both `sh` and `cmd`, needs
/// no redirection, and depends on nothing being on PATH. `touch` is not a cmd
/// builtin, which made this guard half-vacuous on Windows — the "did not run"
/// assertion passed because the command failed rather than because brake
/// refused it.
///
/// Embedded in a TOML *literal* string (single quotes) by the caller, because
/// a Windows path is full of backslashes and `\U` in `C:\Users` is not a valid
/// escape in a TOML basic string. That parse failure is what made this test
/// fail on Windows — and made its first assertion pass for the wrong reason,
/// since a config that does not load runs no generator either.
fn create_file_command(path: &Path) -> String {
    format!("mkdir \"{}\"", path.display())
}

fn brake(cwd: &Path, args: &[&str]) -> Output {
    Command::new(BRAKE)
        .args(args)
        .current_dir(cwd)
        .output()
        .expect("brake should launch")
}

fn code(output: &Output) -> i32 {
    output.status.code().expect("brake should exit normally")
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

const TWO_CONTRACTS: &str = r#"
[[contract]]
name = "a"
format = "openapi"
source = "api/a.yaml"
baseline = { file = "api/a.baseline.yaml" }

[[contract]]
name = "b"
format = "openapi"
source = "api/b.yaml"
baseline = { file = "api/b.baseline.yaml" }
"#;

/// `a` is broken against its baseline, `b` is not.
fn two_contracts() -> TempDir {
    repo(&[
        ("brake.toml", TWO_CONTRACTS),
        ("api/a.baseline.yaml", SPEC),
        ("api/a.yaml", BROKEN),
        ("api/b.baseline.yaml", SPEC),
        ("api/b.yaml", SPEC),
    ])
}

#[test]
fn check_with_a_path_checks_only_that_contract() {
    let repo = two_contracts();

    let scoped = brake(repo.path(), &["check", "api/b.yaml", "--format", "text"]);
    assert_eq!(
        code(&scoped),
        0,
        "a run scoped to an untouched contract leaked another's finding:\n{}",
        stdout(&scoped)
    );

    let also_scoped = brake(repo.path(), &["check", "api/a.yaml", "--format", "text"]);
    assert_eq!(code(&also_scoped), 1);
    assert!(stdout(&also_scoped).contains("endpoint-removed"));
}

#[test]
fn check_with_no_paths_checks_everything() {
    let repo = two_contracts();
    let output = brake(repo.path(), &["check", "--format", "text"]);
    assert_eq!(code(&output), 1);
}

#[test]
fn check_accepts_the_many_paths_a_hook_passes_at_once() {
    let repo = two_contracts();
    // pre-commit passes every changed file it watches, contracts or not.
    let output = brake(
        repo.path(),
        &[
            "check",
            "api/b.yaml",
            "README.md",
            "src/main.rs",
            "--format",
            "text",
        ],
    );
    assert_eq!(code(&output), 0, "{}", stdout(&output));
}

#[test]
fn exit_codes_separate_a_broken_api_from_a_broken_gate() {
    // 1 — the API broke.
    let broken_api = two_contracts();
    assert_eq!(code(&brake(broken_api.path(), &["check"])), 1);

    // 2 — the gate broke: a configured baseline that is not there.
    let broken_gate = repo(&[
        ("brake.toml", TWO_CONTRACTS),
        ("api/a.yaml", SPEC),
        ("api/b.baseline.yaml", SPEC),
        ("api/b.yaml", SPEC),
    ]);
    assert_eq!(
        code(&brake(broken_gate.path(), &["check"])),
        2,
        "an unresolvable baseline must not be reported as an API break"
    );

    // 0 — nothing to say.
    let clean = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"b\"\nformat=\"openapi\"\nsource=\"api/b.yaml\"\nbaseline={file=\"api/b.baseline.yaml\"}\n",
        ),
        ("api/b.baseline.yaml", SPEC),
        ("api/b.yaml", SPEC),
    ]);
    assert_eq!(code(&brake(clean.path(), &["check"])), 0);
}

#[test]
fn brake_toml_is_found_from_a_subdirectory() {
    let repo = two_contracts();
    let nested = repo.path().join("api/nested/deeper");
    fs::create_dir_all(&nested).expect("mkdir");

    let output = brake(&nested, &["check", "--format", "text"]);
    assert_eq!(
        code(&output),
        1,
        "brake.toml was not discovered from a subdirectory:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn a_missing_config_is_a_tool_failure_with_an_actionable_message() {
    let empty = tempdir().expect("tempdir");
    let output = brake(empty.path(), &["check"]);
    assert_eq!(code(&output), 2);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("brake.toml"), "{stderr}");
}

#[test]
fn contract_flag_restricts_the_run() {
    let repo = two_contracts();
    let output = brake(
        repo.path(),
        &["check", "--contract", "b", "--format", "text"],
    );
    assert_eq!(code(&output), 0, "{}", stdout(&output));
}

#[test]
fn compatibility_flag_changes_the_verdict() {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\nbaseline={file=\"api/c.baseline.yaml\"}\n",
        ),
        ("api/c.baseline.yaml", SPEC),
        ("api/c.yaml", &SPEC.replace("getPayment", "fetchPayment")),
    ]);

    assert_eq!(code(&brake(repo.path(), &["check"])), 0);
    assert_eq!(
        code(&brake(
            repo.path(),
            &["check", "--compatibility", "surface"]
        )),
        1,
        "an operationId rename is a surface break"
    );
    assert_eq!(
        code(&brake(
            repo.path(),
            &["check", "--compatibility", "nonsense"]
        )),
        2,
        "an unknown level is a tool failure, not a silent default"
    );
}

#[test]
fn format_auto_is_json_when_piped() {
    let repo = two_contracts();
    let output = brake(repo.path(), &["check"]);
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout(&output)).expect("piped output should be JSON");
    assert!(parsed["findings"].is_array());
}

#[test]
fn every_format_renders_and_agrees_on_the_verdict() {
    let repo = two_contracts();
    for format in [
        "text",
        "json",
        "sarif",
        "github",
        "gitlab",
        "github-actions",
        "codequality",
    ] {
        let output = brake(repo.path(), &["check", "--format", format]);
        assert_eq!(code(&output), 1, "format {format} disagreed on the verdict");
        assert!(
            !stdout(&output).is_empty(),
            "format {format} rendered nothing"
        );
    }
    let bad = brake(repo.path(), &["check", "--format", "yaml"]);
    assert_eq!(code(&bad), 2);
}

#[test]
fn github_format_renders_workflow_commands() {
    let repo = two_contracts();
    let output = brake(repo.path(), &["check", "--format", "github"]);
    assert_eq!(code(&output), 1);
    let out = stdout(&output);
    assert!(
        out.contains("::error file="),
        "github format should emit workflow commands: {out}"
    );
    assert!(
        out.contains("title=endpoint-removed"),
        "github format should carry rule title: {out}"
    );
}

#[test]
fn sarif_output_parses_and_carries_fingerprints() {
    let repo = two_contracts();
    let output = brake(repo.path(), &["check", "--format", "sarif"]);
    let sarif: serde_json::Value =
        serde_json::from_str(&stdout(&output)).expect("valid SARIF JSON");

    assert_eq!(sarif["version"], "2.1.0");
    let results = sarif["runs"][0]["results"].as_array().expect("results");
    assert!(!results.is_empty());
    for result in results {
        assert!(result["partialFingerprints"]["brakeFindingV1"].is_string());
    }
}

#[test]
fn diff_reports_changes_and_never_gates() {
    let repo = two_contracts();
    let output = brake(repo.path(), &["diff", "--format", "text"]);
    assert_eq!(code(&output), 0, "diff must never fail a build");
    assert!(
        stdout(&output).contains("endpoint-removed"),
        "diff should still describe the change:\n{}",
        stdout(&output)
    );
}

#[test]
fn analyze_covers_the_repository_and_honours_fail_on() {
    let repo = two_contracts();
    assert_eq!(code(&brake(repo.path(), &["analyze", "."])), 1);
    assert_eq!(
        code(&brake(repo.path(), &["analyze", ".", "--fail-on", "error"])),
        1
    );
}

#[test]
fn explain_covers_every_rule_with_no_placeholder_text() {
    let here = tempdir().expect("tempdir");

    let listing = brake(here.path(), &["explain"]);
    assert_eq!(code(&listing), 0);
    let listed = stdout(&listing);

    for line in listed.lines() {
        let rule_id = line.split_whitespace().next().expect("a rule id");
        let output = brake(here.path(), &["explain", rule_id]);
        assert_eq!(code(&output), 0, "`brake explain {rule_id}` failed");

        let text = stdout(&output);
        assert!(text.contains(rule_id), "{rule_id}: id missing from output");
        assert!(
            !text.to_lowercase().contains("todo") && !text.to_lowercase().contains("tbd"),
            "{rule_id}: placeholder explanation"
        );
        assert!(
            text.len() > 200,
            "{rule_id}: explanation is too thin to be useful"
        );
    }

    assert!(
        listed.lines().count() > 25,
        "the catalogue should cover the specified ruleset, got {} rules",
        listed.lines().count()
    );
}

#[test]
fn explain_rejects_an_unknown_rule_rather_than_inventing_one() {
    let here = tempdir().expect("tempdir");
    let output = brake(here.path(), &["explain", "no-such-rule"]);
    assert_eq!(code(&output), 2);
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("no-such-rule"),
        "the error should name what was asked for"
    );
}

#[test]
fn every_rule_the_tool_can_emit_is_explainable() {
    // A finding whose rule `brake explain` does not know is a dead end for
    // whoever is blocked by it.
    let here = tempdir().expect("tempdir");
    let listing = stdout(&brake(here.path(), &["explain"]));
    let known: Vec<&str> = listing
        .lines()
        .filter_map(|line| line.split_whitespace().next())
        .collect();

    let repo = two_contracts();
    let output = brake(repo.path(), &["check", "--format", "json"]);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
    for finding in parsed["findings"].as_array().expect("findings") {
        let rule = finding["rule"].as_str().expect("rule");
        assert!(known.contains(&rule), "`{rule}` is not in the catalogue");
    }
}

#[test]
fn drift_is_unreachable_without_the_flag() {
    let witness = tempdir().expect("tempdir");
    let marker = witness.path().join("generator-ran");
    let repo = repo(&[
        (
            "brake.toml",
            &format!(
                "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
                 baseline={{file=\"api/c.baseline.yaml\"}}\n\
                 [contract.generated]\ncommand = '{}'\n",
                create_file_command(&marker)
            ),
        ),
        ("api/c.baseline.yaml", SPEC),
        ("api/c.yaml", SPEC),
    ]);

    brake(repo.path(), &["check"]);
    assert!(
        !marker.exists(),
        "brake check ran a config-declared command without --drift"
    );

    brake(repo.path(), &["check", "--drift"]);
    assert!(marker.exists(), "--drift should run the declared generator");
}

/// A repository with two releases and a break after the newer one.
fn released_repository() -> TempDir {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={latest-tag=\"v*\"}\n",
        ),
        ("api/c.yaml", SPEC),
    ]);
    let git = |args: &[&str]| {
        let output = Command::new("git")
            .args(args)
            .current_dir(repo.path())
            .output()
            .expect("git should launch");
        assert!(
            output.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    };
    git(&["init", "-b", "main"]);
    git(&["config", "user.name", "Brake Test"]);
    git(&["config", "user.email", "brake@example.com"]);
    git(&["add", "."]);
    git(&["commit", "-m", "v9"]);
    git(&["tag", "-a", "v9.0.0", "-m", "release nine"]);
    git(&["commit", "--allow-empty", "-m", "v10"]);
    git(&["tag", "v10.0.0"]);

    fs::write(repo.path().join("api/c.yaml"), BROKEN).expect("write");
    git(&["add", "."]);
    git(&["commit", "-m", "break the api"]);
    repo
}

#[test]
fn a_release_baseline_gates_against_the_last_tag() {
    let repo = released_repository();
    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);

    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
    let file = parsed["findings"][0]["file"].as_str().expect("file");
    assert_eq!(
        file, "tag:v10.0.0",
        "latest-tag must pick v10.0.0, not v9.0.0 — byte order gets this backwards"
    );
}

#[test]
fn the_baseline_flag_accepts_a_tag_a_glob_and_a_revision() {
    let repo = released_repository();
    for (flag, expected_label) in [
        ("v9.0.0", "tag:v9.0.0"),
        ("v10.0.0", "tag:v10.0.0"),
        ("latest-tag:v*", "tag:v10.0.0"),
    ] {
        let output = brake(
            repo.path(),
            &["check", "--baseline", flag, "--format", "json"],
        );
        assert_eq!(code(&output), 1, "--baseline {flag}");
        let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
        // A `rev` override and a `tag` entry label differently; both are fine
        // so long as the flag resolved to the right commit.
        let file = parsed["findings"][0]["file"].as_str().expect("file");
        assert!(
            file.ends_with(expected_label.trim_start_matches("tag:")),
            "--baseline {flag} resolved to {file}, wanted {expected_label}"
        );
    }
}

#[test]
fn a_release_baseline_with_no_matching_tag_is_a_tool_failure() {
    let repo = released_repository();
    fs::write(
        repo.path().join("brake.toml"),
        "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
         baseline={latest-tag=\"release-*\"}\n",
    )
    .expect("write");

    let output = brake(repo.path(), &["check", "--format", "text"]);
    assert_eq!(
        code(&output),
        2,
        "an unresolvable release baseline must not report clean"
    );
    assert!(
        stdout(&output).contains("fetch-depth"),
        "the message should name the usual cause:\n{}",
        stdout(&output)
    );
}

#[test]
fn a_baseline_setting_two_shapes_at_once_is_rejected() {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={tag=\"v1.0.0\", rev=\"abc123\"}\n",
        ),
        ("api/c.yaml", SPEC),
    ]);
    let output = brake(repo.path(), &["check"]);
    assert_eq!(code(&output), 2);
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("several"),
        "an ambiguous baseline must say so rather than picking one"
    );
}

#[test]
fn version_prints_the_calver() {
    let here = tempdir().expect("tempdir");
    let output = brake(here.path(), &["--version"]);
    assert_eq!(code(&output), 0);
    assert!(stdout(&output).contains("2026."), "{}", stdout(&output));
}

#[test]
fn as_of_defaults_to_today_so_expiry_actually_expires() {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={file=\"api/c.baseline.yaml\"}\n\
             [[contract.allow]]\nrule=\"endpoint-removed\"\nreason=\"migrated\"\n\
             expires=\"2020-01-01\"\n",
        ),
        ("api/c.baseline.yaml", SPEC),
        ("api/c.yaml", BROKEN),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
    let rules: Vec<&str> = parsed["findings"]
        .as_array()
        .expect("findings")
        .iter()
        .filter_map(|finding| finding["rule"].as_str())
        .collect();

    assert!(
        rules.contains(&"expired-allow"),
        "a suppression that expired in 2020 must not still be suppressing: {rules:?}"
    );

    // …and `--as-of` before the expiry still honours it. The removal also
    // trips `removed-without-deprecation`, which is a different rule and is
    // not covered by this suppression, so assert on the rule rather than the
    // exit code.
    let before = brake(
        repo.path(),
        &["check", "--as-of", "2019-06-01", "--format", "json"],
    );
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&before)).expect("json");
    let rules: Vec<&str> = parsed["findings"]
        .as_array()
        .expect("findings")
        .iter()
        .filter_map(|finding| finding["rule"].as_str())
        .collect();
    assert!(
        !rules.contains(&"expired-allow") && !rules.contains(&"endpoint-removed"),
        "before its expiry the suppression should still apply: {rules:?}"
    );
}

#[test]
fn a_suppression_for_an_unknown_rule_is_rejected_at_parse_time() {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={file=\"api/c.baseline.yaml\"}\n\
             [[contract.allow]]\nrule=\"endpoint-remvoed\"\nreason=\"typo\"\n",
        ),
        ("api/c.baseline.yaml", SPEC),
        ("api/c.yaml", SPEC),
    ]);

    let output = brake(repo.path(), &["check"]);
    assert_eq!(code(&output), 2);
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("endpoint-remvoed"),
        "a misspelled rule must be named, not silently ignored"
    );
}

#[test]
fn a_suppression_without_a_reason_is_rejected() {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={file=\"api/c.baseline.yaml\"}\n\
             [[contract.allow]]\nrule=\"endpoint-removed\"\n",
        ),
        ("api/c.baseline.yaml", SPEC),
        ("api/c.yaml", SPEC),
    ]);
    assert_eq!(code(&brake(repo.path(), &["check"])), 2);
}

#[test]
fn output_is_byte_identical_across_repeated_invocations() {
    let repo = two_contracts();
    for format in ["text", "json", "sarif", "github", "gitlab"] {
        let first = stdout(&brake(repo.path(), &["check", "--format", format]));
        let second = stdout(&brake(repo.path(), &["check", "--format", format]));
        assert_eq!(first, second, "format {format} is not byte-stable");
        assert!(
            !first.contains(&repo.path().to_string_lossy().to_string()),
            "format {format} embeds the absolute checkout path"
        );
    }
}

#[test]
fn every_breaking_finding_carries_a_way_out() {
    // A finding that blocks a commit and suggests nothing is a finding people
    // argue with rather than act on. Walk the catalogue and assert that every
    // rule which reports a break names at least one strategy, and that no
    // strategy reaches a user with an unbound placeholder in it.
    let here = tempdir().expect("tempdir");
    let listing = stdout(&brake(here.path(), &["explain"]));

    for line in listing.lines() {
        let rule_id = line.split_whitespace().next().expect("a rule id");
        let text = stdout(&brake(here.path(), &["explain", rule_id]));

        assert!(
            !text.contains("{subject}") && !text.contains("{endpoint}"),
            "`{rule_id}` renders an unbound placeholder"
        );

        if text.contains("ways to make the change safely:") {
            assert!(
                text.contains("costs:"),
                "`{rule_id}` lists strategies with no costs, which reads as though \
                 they are all free"
            );
        }
    }
}

#[test]
fn a_finding_names_the_field_its_advice_is_about() {
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={file=\"api/c.baseline.yaml\"}\n",
        ),
        (
            "api/c.baseline.yaml",
            "openapi: 3.1.0\npaths:\n  /p:\n    post:\n      operationId: createPayment\n\
             \x20     responses:\n        \"201\": {description: ok}\n",
        ),
        (
            "api/c.yaml",
            "openapi: 3.1.0\npaths:\n  /p:\n    post:\n      operationId: createPayment\n\
             \x20     parameters:\n        - {name: tenant, in: query, required: true, \
             schema: {type: string}}\n      responses:\n        \"201\": {description: ok}\n",
        ),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
    let finding = &parsed["findings"][0];

    assert_eq!(finding["subject"], "tenant");
    let summary = finding["remediation"][0]["summary"]
        .as_str()
        .expect("a bound summary");
    assert!(
        summary.contains("`tenant`"),
        // A parameter's JSON pointer ends in its index, so deriving the
        // subject from it once produced "keep `0` optional".
        "the advice must name the parameter, not its position: {summary}"
    );

    // The text rendering agrees with the structured one.
    let text = stdout(&brake(repo.path(), &["check", "--format", "text"]));
    assert!(text.contains("optional-with-default"), "{text}");
    assert!(text.contains("`tenant`"), "{text}");
}

#[test]
fn the_mcp_subcommand_is_listed_whether_or_not_it_is_built() {
    // A capability that silently does not exist is one nobody can discover,
    // which is the CLI equivalent of a clean result brake cannot justify. The
    // subcommand is always registered; only its implementation is gated.
    let here = tempdir().expect("tempdir");
    let help = stdout(&brake(here.path(), &["--help"]));
    assert!(
        help.contains("mcp"),
        "`brake --help` does not mention the MCP server:\n{help}"
    );
}

#[test]
fn brake_mcp_either_serves_or_says_how_to_get_it() {
    let here = tempdir().expect("tempdir");

    if cfg!(feature = "mcp") {
        // Built in: it would block on stdio, so assert on the help text
        // rather than starting it. tests/mcp.rs drives the real thing.
        let help = stdout(&brake(here.path(), &["mcp", "--help"]));
        assert!(help.contains("--as-of"), "{help}");
        return;
    }

    let output = brake(here.path(), &["mcp", "."]);
    assert_eq!(
        code(&output),
        2,
        "a subcommand that cannot run must exit 2, not pretend to succeed"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    // The message has to be actionable: naming the feature is not enough if
    // the reader still has to work out the command.
    assert!(stderr.contains("--features mcp"), "{stderr}");
    assert!(stderr.contains("cargo install brake"), "{stderr}");
}

/// A repository the way someone actually meets brake: real specs, ordinary
/// CI config, no brake.toml yet.
fn unconfigured_repo() -> TempDir {
    let repo = repo(&[
        ("api/payments-openapi.yaml", SPEC),
        ("api/payments-openapi.baseline.yaml", SPEC),
        (
            ".github/workflows/api-tests.yaml",
            "name: api-tests\non: push\n",
        ),
        ("package.json", r#"{"name":"app","version":"1.0.0"}"#),
        (
            "docker-compose.yml",
            "services:\n  api:\n    image: nginx\n",
        ),
    ]);
    let git = |args: &[&str]| {
        let ok = Command::new("git")
            .args(args)
            .current_dir(repo.path())
            .output()
            .expect("git should launch")
            .status
            .success();
        assert!(ok, "git {args:?}");
    };
    git(&["init", "-b", "main"]);
    git(&["config", "user.name", "Brake Test"]);
    git(&["config", "user.email", "brake@example.com"]);
    git(&["add", "."]);
    git(&["commit", "-m", "init"]);
    repo
}

#[test]
fn the_first_command_a_new_user_runs_names_the_one_that_fixes_it() {
    let repo = unconfigured_repo();
    let output = brake(repo.path(), &["check"]);

    assert_eq!(code(&output), 2);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("brake init"),
        "\"create one\" is not actionable without saying how:\n{stderr}"
    );
}

#[test]
fn init_declares_the_real_contracts_and_ignores_everything_else() {
    let repo = unconfigured_repo();
    let output = brake(repo.path(), &["init"]);
    assert_eq!(
        code(&output),
        0,
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    let written = fs::read_to_string(repo.path().join("brake.toml")).expect("brake.toml");
    assert!(written.contains("api/payments-openapi.yaml"), "{written}");

    // The files a filename heuristic would have claimed.
    assert!(!written.contains("api-tests.yaml"), "{written}");
    assert!(!written.contains("package.json"), "{written}");
    assert!(!written.contains("docker-compose"), "{written}");
    // A baseline is a previous version, not a second contract.
    assert!(!written.contains("baseline.yaml\""), "{written}");
}

#[test]
fn what_init_writes_works_on_the_very_next_command() {
    // The loop that matters: if the generated config does not survive contact
    // with `check`, init has moved the wall rather than removed it.
    let repo = unconfigured_repo();
    assert_eq!(code(&brake(repo.path(), &["init"])), 0);

    let output = brake(
        repo.path(),
        &["check", "api/payments-openapi.yaml", "--format", "text"],
    );
    assert_eq!(
        code(&output),
        0,
        "the generated config failed immediately:\nstdout: {}\nstderr: {}",
        stdout(&output),
        String::from_utf8_lossy(&output.stderr)
    );

    // …and it is a real gate, not one that passes because it checked nothing.
    fs::write(repo.path().join("api/payments-openapi.yaml"), BROKEN).expect("write");
    let output = brake(
        repo.path(),
        &["check", "api/payments-openapi.yaml", "--format", "text"],
    );
    assert_eq!(code(&output), 1, "{}", stdout(&output));
    assert!(stdout(&output).contains("endpoint-removed"));
}

#[test]
fn init_refuses_to_overwrite_without_being_told_to() {
    let repo = unconfigured_repo();
    assert_eq!(code(&brake(repo.path(), &["init"])), 0);

    fs::write(
        repo.path().join("brake.toml"),
        "# hand-written, do not lose\n",
    )
    .expect("write");
    let output = brake(repo.path(), &["init"]);
    assert_eq!(code(&output), 2);
    assert!(String::from_utf8_lossy(&output.stderr).contains("--force"));
    assert_eq!(
        fs::read_to_string(repo.path().join("brake.toml")).expect("read"),
        "# hand-written, do not lose\n",
        "suppressions and their reasons are the most expensive thing in that file"
    );

    assert_eq!(code(&brake(repo.path(), &["init", "--force"])), 0);
}

#[test]
fn init_dry_run_writes_nothing() {
    let repo = unconfigured_repo();
    let output = brake(repo.path(), &["init", "--dry-run"]);

    assert_eq!(code(&output), 0);
    assert!(
        stdout(&output).contains("[[contract]]"),
        "{}",
        stdout(&output)
    );
    assert!(!repo.path().join("brake.toml").exists());
}

#[test]
fn an_ordinary_ci_file_does_not_trip_the_contract_notice() {
    // `01-thesis.md`: false positives are how a hook gets uninstalled. This
    // one was loud, and fired on any commit touching CI in a repo with `api`
    // in a path.
    let repo = unconfigured_repo();
    assert_eq!(code(&brake(repo.path(), &["init"])), 0);

    let output = brake(
        repo.path(),
        &[
            "check",
            ".github/workflows/api-tests.yaml",
            "package.json",
            "docker-compose.yml",
            "--format",
            "text",
        ],
    );
    assert_eq!(code(&output), 0);
    assert!(
        !stdout(&output).contains("contract-unconfigured"),
        "brake called ordinary files APIs:\n{}",
        stdout(&output)
    );
}

#[test]
fn a_genuinely_undeclared_contract_is_still_pointed_out() {
    let repo = unconfigured_repo();
    assert_eq!(code(&brake(repo.path(), &["init"])), 0);
    fs::write(repo.path().join("api/ledger-openapi.yaml"), SPEC).expect("write");

    let output = brake(
        repo.path(),
        &["check", "api/ledger-openapi.yaml", "--format", "text"],
    );
    assert_eq!(code(&output), 0, "a note must not block a commit");
    let text = stdout(&output);
    assert!(text.contains("contract-unconfigured"), "{text}");
    // The note is about a file; naming it `contract:` claimed it was one.
    assert!(text.contains("file: `api/ledger-openapi.yaml`"), "{text}");
}

#[test]
fn a_field_level_finding_points_at_the_field_not_the_response() {
    // The JSON pointer was always exact; the underlined line was the enclosing
    // response, which is the right file and the wrong line — and the line is
    // what a reader checks first.
    let spec = |fields: &str| {
        format!(
            "openapi: 3.1.0\npaths:\n  /payments/{{id}}:\n    get:\n\
             \x20     operationId: getPayment\n      responses:\n        \"200\":\n\
             \x20         description: ok\n          content:\n\
             \x20           application/json:\n              schema:\n\
             \x20               type: object\n                required: [id]\n\
             \x20               properties:\n{fields}"
        )
    };
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"api/c.yaml\"\n\
             baseline={file=\"api/c.baseline.yaml\"}\n",
        ),
        (
            "api/c.baseline.yaml",
            &spec(
                "                  id: { type: string }\n                  customer_id: { type: string }\n",
            ),
        ),
        (
            "api/c.yaml",
            &spec("                  id: { type: string }\n"),
        ),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
    let finding = &parsed["findings"][0];
    assert_eq!(finding["rule"], "response-field-removed");

    // `customer_id` is declared on line 16 of the baseline; the response
    // block it lives in starts at line 7, which is what used to be reported.
    let line = finding["line"].as_u64().expect("line");
    assert_eq!(
        line,
        16,
        "expected the line declaring `customer_id`, got {line}:\n{}",
        stdout(&output)
    );

    let text = stdout(&brake(repo.path(), &["check", "--format", "text"]));
    assert!(
        text.contains("customer_id: { type: string }"),
        "the diagnostic should quote the field's own line:\n{text}"
    );
}

#[test]
fn a_finding_with_no_field_span_still_locates_the_payload() {
    // protobuf supplies no field-level spans, so those findings fall back to
    // the method's span. That is the previous behaviour and still the right
    // file — the fallback must not produce a missing or zero location.
    let proto = |payment: &str| {
        format!(
            "syntax = \"proto3\";\npackage pay;\nmessage Req {{ string id = 1; }}\n\
             message Payment {{ {payment} }}\n\
             service S {{ rpc Get(Req) returns (Payment); }}\n"
        )
    };
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"p\"\nformat=\"proto\"\nsource=\"api/p.proto\"\n\
             baseline={file=\"api/p.baseline.proto\"}\n",
        ),
        (
            "api/p.baseline.proto",
            &proto("string id = 1; string note = 2;"),
        ),
        ("api/p.proto", &proto("string id = 1;")),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("json");
    let finding = &parsed["findings"][0];

    assert!(
        finding["file"]
            .as_str()
            .is_some_and(|f| f.ends_with(".proto"))
    );
    assert!(
        finding["line"].as_u64().is_some_and(|line| line > 0),
        "a fallback span must still be a real location: {finding}"
    );
}

#[test]
fn github_actions_and_gitlab_formats_render_properly() {
    let repo = two_contracts();
    let gh = stdout(&brake(repo.path(), &["check", "--format", "github"]));
    assert!(gh.contains("::error"));
    assert!(gh.contains("title=endpoint-removed"));

    let gl = stdout(&brake(repo.path(), &["check", "--format", "gitlab"]));
    let parsed: serde_json::Value = serde_json::from_str(&gl).expect("valid gitlab json array");
    assert!(parsed.is_array());
    assert!(!parsed.as_array().unwrap().is_empty());
    assert_eq!(parsed[0]["check_name"], "endpoint-removed");
}

#[test]
fn analyze_and_diff_render_with_github_and_gitlab_formats() {
    let repo = two_contracts();
    let analyze_gl = stdout(&brake(repo.path(), &["analyze", ".", "--format", "gitlab"]));
    let parsed_analyze: serde_json::Value =
        serde_json::from_str(&analyze_gl).expect("valid gitlab json from analyze");
    assert!(parsed_analyze.is_array());

    let analyze_gh = stdout(&brake(repo.path(), &["analyze", ".", "--format", "github"]));
    assert!(analyze_gh.contains("::error"));

    let diff_gh = stdout(&brake(repo.path(), &["diff", "--format", "github"]));
    assert!(diff_gh.contains("endpoint-removed"));

    let diff_gl = stdout(&brake(repo.path(), &["diff", "--format", "gitlab"]));
    let parsed_diff: serde_json::Value =
        serde_json::from_str(&diff_gl).expect("valid gitlab json from diff");
    assert!(parsed_diff.is_array());
}

#[test]
fn protobuf_reserved_fields_prevent_silent_reuse_in_cli() {
    let proto_base = r#"
syntax = "proto3";
package pay;
message Payment {
  string id = 1;
}
service S { rpc Get(Payment) returns (Payment); }
"#;
    let proto_with_collision = r#"
syntax = "proto3";
package pay;
message Payment {
  reserved 1, 4 to 8;
  reserved "bad_field";
  string id = 1;
}
service S { rpc Get(Payment) returns (Payment); }
"#;
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"p\"\nformat=\"proto\"\nsource=\"api/p.proto\"\n\
             baseline={file=\"api/p.baseline.proto\"}\n",
        ),
        ("api/p.baseline.proto", proto_base),
        ("api/p.proto", proto_with_collision),
    ]);

    let output = brake(
        repo.path(),
        &["analyze", ".", "--fail-on", "warning", "--format", "json"],
    );
    assert_eq!(
        code(&output),
        1,
        "contract with reserved collision must fail when gating on warnings"
    );
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("valid json");
    assert_eq!(parsed["findings"][0]["rule"], "contract-partial");
    assert!(
        parsed["findings"][0]["message"]
            .as_str()
            .unwrap()
            .contains("reuses reserved number range")
    );
}

#[test]
fn multi_document_openapi_references_resolve_in_cli() {
    let base_root = r#"
openapi: 3.1.0
paths:
  /users:
    get:
      responses:
        "200":
          description: ok
          content:
            application/json:
              schema:
                $ref: "./models/user_base.yaml#/User"
"#;
    let head_root = r#"
openapi: 3.1.0
paths:
  /users:
    get:
      responses:
        "200":
          description: ok
          content:
            application/json:
              schema:
                $ref: "./models/user.yaml#/User"
"#;
    let base_user = r#"
User:
  type: object
  required: [id, email]
  properties:
    id:
      type: string
    email:
      type: string
"#;
    let head_user_broken = r#"
User:
  type: object
  required: [id]
  properties:
    id:
      type: string
"#;
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"users\"\nformat=\"openapi\"\nsource=\"api/users.yaml\"\n\
             baseline={file=\"api/users.baseline.yaml\"}\n",
        ),
        ("api/users.baseline.yaml", base_root),
        ("api/users.yaml", head_root),
        ("api/models/user_base.yaml", base_user),
        ("api/models/user.yaml", head_user_broken),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("valid json");
    assert_eq!(parsed["findings"][0]["rule"], "response-field-removed");
    assert_eq!(parsed["findings"][0]["subject"], "email");
}

#[test]
fn asyncapi_breaking_changes_detected_in_cli() {
    let base_asyncapi = r#"
asyncapi: '2.6.0'
info:
  title: Order Events
  version: 1.0.0
channels:
  orders/created:
    publish:
      message:
        payload:
          type: object
          required: [orderId, customerId]
          properties:
            orderId:
              type: string
            customerId:
              type: string
"#;
    let head_asyncapi = r#"
asyncapi: '2.6.0'
info:
  title: Order Events
  version: 1.0.0
channels:
  orders/created:
    publish:
      message:
        payload:
          type: object
          required: [orderId]
          properties:
            orderId:
              type: string
"#;
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"orders\"\nformat=\"asyncapi\"\nsource=\"api/orders.yaml\"\n\
             baseline={file=\"api/orders.baseline.yaml\"}\n",
        ),
        ("api/orders.baseline.yaml", base_asyncapi),
        ("api/orders.yaml", head_asyncapi),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("valid json");
    assert_eq!(parsed["findings"][0]["rule"], "response-field-removed");
    assert_eq!(parsed["findings"][0]["subject"], "customerId");
}

#[test]
fn openapi_31_discriminator_and_tuple_changes_detected_in_cli() {
    let base_spec = r#"
openapi: 3.1.0
paths:
  /geo:
    get:
      responses:
        "200":
          description: ok
          content:
            application/json:
              schema:
                type: array
                prefixItems:
                  - type: number
                  - type: number
"#;
    let head_spec = r#"
openapi: 3.1.0
paths:
  /geo:
    get:
      responses:
        "200":
          description: ok
          content:
            application/json:
              schema:
                type: array
                prefixItems:
                  - type: number
"#;
    let repo = repo(&[
        (
            "brake.toml",
            "[[contract]]\nname=\"geo\"\nformat=\"openapi\"\nsource=\"api/geo.yaml\"\n\
             baseline={file=\"api/geo.baseline.yaml\"}\n",
        ),
        ("api/geo.baseline.yaml", base_spec),
        ("api/geo.yaml", head_spec),
    ]);

    let output = brake(repo.path(), &["check", "--format", "json"]);
    assert_eq!(code(&output), 1);
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&output)).expect("valid json");
    assert_eq!(parsed["findings"][0]["rule"], "response-type-changed");
    assert!(
        parsed["findings"][0]["message"]
            .as_str()
            .unwrap()
            .contains("tuple prefixItems")
    );
}

// ── brake compare ───────────────────────────────────────────────────────────

#[test]
fn compare_needs_no_configuration_and_names_the_files_it_was_given() {
    // No brake.toml anywhere: the two files are the whole input.
    let dir = repo(&[("old.yaml", SPEC), ("new.yaml", BROKEN)]);

    let broken = brake(
        dir.path(),
        &["compare", "-f", "json", "old.yaml", "new.yaml"],
    );
    assert_eq!(code(&broken), 1, "{}", stdout(&broken));
    let report: serde_json::Value = serde_json::from_str(&stdout(&broken)).expect("json");
    let files: Vec<&str> = report["findings"]
        .as_array()
        .expect("findings")
        .iter()
        .filter_map(|finding| finding["file"].as_str())
        .collect();
    assert!(!files.is_empty(), "{report}");
    assert!(
        files
            .iter()
            .all(|file| *file == "old.yaml" || *file == "new.yaml"),
        "a CI annotation must point at a file the caller named: {files:?}"
    );

    let clean = brake(
        dir.path(),
        &["compare", "-f", "json", "old.yaml", "old.yaml"],
    );
    assert_eq!(code(&clean), 0, "{}", stdout(&clean));
}

#[test]
fn compare_refuses_a_head_it_cannot_identify() {
    let dir = repo(&[("old.yaml", SPEC), ("notes.txt", "not a contract\n")]);

    let output = brake(dir.path(), &["compare", "old.yaml", "notes.txt"]);
    assert_eq!(code(&output), 2);
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("--contract-format"),
        "the error must say how to proceed"
    );
}