req-cli 0.5.0-rc.6

Managed requirements CLI for LLM agents and humans
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
// Dedicated req_NNNN_* tests for behaviours that were implemented and genuine
// but lacked a named test, so `reverify --by-tests` could not re-anchor them.
// Writing real tests both fills the coverage gap and makes future refactors
// (e.g. the validate/verify terminology cleanup) cheaply re-anchorable.
mod common;
use common::{stderr, stdout, Sandbox};
use std::process::Command;

fn git(dir: &std::path::Path, args: &[&str]) {
    let _ = Command::new("git").current_dir(dir).args(args).output();
}

/// Run req with cwd = the sandbox (so git HEAD and "." resolve there).
fn run_in(s: &Sandbox, args: &[&str]) -> std::process::Output {
    let mut full: Vec<String> = vec!["--file".into(), s.path().to_str().unwrap().into()];
    full.extend(args.iter().map(|a| a.to_string()));
    Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args(&full)
        .env_remove("REQ_FILE")
        .output()
        .expect("invoke req")
}

/// A git-backed sandbox with one Implemented requirement; returns it + HEAD sha.
fn implemented_in_git() -> (Sandbox, String) {
    let s = Sandbox::new();
    let dir = s.dir.path();
    git(dir, &["init", "-q", "-b", "main"]);
    git(dir, &["config", "user.email", "t@example.com"]);
    git(dir, &["config", "user.name", "Tester"]);
    git(dir, &["commit", "-q", "-m", "init", "--allow-empty"]);
    s.init("p");
    let _ = run_in(
        &s,
        &[
            "add",
            "-t",
            "Halt the line cleanly",
            "-s",
            "The system shall halt the line.",
            "-r",
            "line safety constraint",
            "-k",
            "functional",
            "-a",
            "line halts within a second",
        ],
    );
    for st in ["proposed", "approved", "implemented"] {
        let _ = run_in(
            &s,
            &["update", "REQ-0001", "--status", st, "--reason", "advance"],
        );
    }
    let out = Command::new("git")
        .current_dir(dir)
        .args(["rev-parse", "HEAD"])
        .output()
        .unwrap();
    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (s, sha)
}

fn add_one(s: &Sandbox) {
    let o = s.run(&[
        "add",
        "-t",
        "Stop on demand cleanly",
        "-s",
        "The system shall stop on operator demand.",
        "-r",
        "operator safety constraint",
        "-k",
        "functional",
        "-p",
        "must",
        "-a",
        "process halts within one second",
    ]);
    assert!(o.status.success(), "add: {}", stderr(&o));
}

/// REQ-0084: the status state machine rejects irregular transitions unless
/// --force is supplied, and the error names the alternative path.
#[test]
fn req_0084_status_machine_rejects_irregular_transitions() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s);
    // AC1: draft -> verified fails without --force; error names the path.
    let o = s.run(&[
        "update",
        "REQ-0001",
        "--status",
        "verified",
        "--reason",
        "try to skip ahead",
    ]);
    assert!(!o.status.success(), "draft->verified should fail");
    let e = stderr(&o).to_lowercase();
    assert!(
        e.contains("irregular") && e.contains("--force"),
        "error should name the override path: {}",
        stderr(&o)
    );
    // AC2: draft -> approved succeeds (carve-out).
    assert!(s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "approved",
            "--reason",
            "reviewed and approved"
        ])
        .status
        .success());
    // AC3: active -> obsolete succeeds.
    assert!(s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "obsolete",
            "--reason",
            "superseded by another"
        ])
        .status
        .success());
    // AC5: obsolete -> draft requires --force.
    assert!(!s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "draft",
            "--reason",
            "revive this please"
        ])
        .status
        .success());
    assert!(s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "draft",
            "--reason",
            "revive with the force flag",
            "--force"
        ])
        .status
        .success());
    // AC4: verified -> implemented requires --force (reach verified via force).
    assert!(s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "verified",
            "--reason",
            "force to verified for test",
            "--force"
        ])
        .status
        .success());
    assert!(!s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "implemented",
            "--reason",
            "demote it back"
        ])
        .status
        .success());
}

/// REQ-0090: REQ-ID lookups normalise across case and zero-pad forms, and a
/// near-miss id suggests the nearest existing one; a far miss does not.
#[test]
fn req_0090_id_resolution_normalises_and_suggests() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s);
    // AC1: normalised forms resolve.
    for form in ["req-1", "REQ-1", "req-0001", "REQ-0001"] {
        assert!(
            s.run(&["show", form]).status.success(),
            "{} should resolve",
            form
        );
    }
    // AC2: a near-miss id suggests the nearest existing id.
    let o = s.run(&["show", "REQ-0003"]);
    assert!(!o.status.success());
    assert!(
        stderr(&o).contains("did you mean REQ-0001"),
        "near-miss hint: {}",
        stderr(&o)
    );
    // AC3: a far miss returns a plain error with no suggestion.
    let o2 = s.run(&["show", &format!("REQ-{}", 9999)]);
    assert!(!o2.status.success());
    assert!(
        stderr(&o2).contains("no such requirement") && !stderr(&o2).contains("did you mean"),
        "far-miss plain error: {}",
        stderr(&o2)
    );
}

/// REQ-0094: status values are accepted in any case and folded to canonical.
#[test]
fn req_0094_status_value_case_insensitive() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s);
    assert!(s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "Approved",
            "--reason",
            "case-insensitive approve"
        ])
        .status
        .success());
    assert!(s
        .run(&[
            "update",
            "REQ-0001",
            "--status",
            "IMPLEMENTED",
            "--reason",
            "case-insensitive implement"
        ])
        .status
        .success());
    assert!(
        stdout(&s.run(&["show", "REQ-0001"]))
            .to_lowercase()
            .contains("implemented"),
        "status folds to canonical lowercase"
    );
}

/// REQ-0091: `repair --force` re-signs a hand-edited file even with conformance
/// errors; without --force it refuses; afterwards conform surfaces the errors.
#[test]
fn req_0091_repair_force_resigns_despite_errors() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s);
    // Hand-edit: break integrity AND introduce a conformance error.
    let path = s.path();
    let body = std::fs::read_to_string(&path)
        .unwrap()
        .replace("The system shall stop on operator demand.", "short");
    std::fs::write(&path, body).unwrap();
    // AC1: repair without --force refuses on conformance errors.
    assert!(!s.run(&["repair", "--confirm-direct-edit"]).status.success());
    // AC2: repair --force re-signs and warns errors remain.
    let o = s.run(&["repair", "--confirm-direct-edit", "--force"]);
    assert!(o.status.success(), "repair --force: {}", stderr(&o));
    let out = format!("{}{}", stdout(&o), stderr(&o)).to_lowercase();
    assert!(
        out.contains("error") && out.contains("conform"),
        "warns + points to conform: {}",
        out
    );
    // AC3: the file now loads and conform reports the surviving error.
    let c = s.run(&["conform"]);
    assert!(stdout(&c).to_lowercase().contains("error") || !c.status.success());
}

/// REQ-0101: `req lint` audits quality dimensions in markdown and JSON.
#[test]
fn req_0101_lint_audits_quality_dimensions() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s);
    // lint quality findings count ACTIVE requirements; advance out of draft.
    s.run(&[
        "update",
        "REQ-0001",
        "--status",
        "approved",
        "--reason",
        "make active for lint",
    ]);
    // Scan the (markerless) sandbox dir so the source-marker finding populates,
    // rather than the surrounding repo whose source carries REQ markers.
    let dir = s.dir.path().to_str().unwrap().to_string();
    let md = stdout(&s.run(&["lint", "--path", &dir]));
    assert!(md.contains("Quality observations"), "md: {}", md);
    for needle in [
        "no source marker",
        "Rationales under",
        "acceptance criterion",
        "no test record",
    ] {
        assert!(
            md.contains(needle),
            "lint markdown missing '{}':\n{}",
            needle,
            md
        );
    }
    let js = s.run(&["lint", "--path", &dir, "--json"]);
    assert!(js.status.success());
    let v: serde_json::Value = serde_json::from_str(&stdout(&js)).expect("lint json");
    assert!(
        v["quality"].is_object() && v["conformance"].is_object(),
        "json shape: {}",
        stdout(&js)
    );
}

/// REQ-0107: lint excludes inspection-only requirements from the
/// no-test-record finding (but other findings still apply).
#[test]
fn req_0107_lint_excludes_inspection_only_from_no_test() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s); // REQ-0001: ordinary, no test record.
    let o = s.run(&[
        "add",
        "-t",
        "Inspect only requirement here",
        "-s",
        "The system shall be inspected only.",
        "-r",
        "inspection rationale phrase",
        "-k",
        "functional",
        "-p",
        "could",
        "-a",
        "passes visual inspection",
        "--tag",
        "inspection-only",
    ]);
    assert!(o.status.success(), "add inspection-only: {}", stderr(&o));
    // The no-test-record finding counts ACTIVE requirements; advance both.
    s.run(&[
        "update",
        "REQ-0001",
        "--status",
        "approved",
        "--reason",
        "make active for lint",
    ]);
    s.run(&[
        "update",
        "REQ-0002",
        "--status",
        "approved",
        "--reason",
        "make active for lint",
    ]);
    let v: serde_json::Value = serde_json::from_str(&stdout(&s.run(&["lint", "--json"]))).unwrap();
    let ntr: Vec<String> = v["quality"]["no_test_record"]
        .as_array()
        .unwrap()
        .iter()
        .map(|x| x.as_str().unwrap().to_string())
        .collect();
    assert!(
        ntr.contains(&"REQ-0001".to_string()),
        "ordinary no-test req listed: {:?}",
        ntr
    );
    assert!(
        !ntr.contains(&"REQ-0002".to_string()),
        "inspection-only excluded: {:?}",
        ntr
    );
}

/// REQ-0095: re-adding a title similar to a recently-obsolete requirement warns
/// (naming the obsolete id) but does not block the add.
#[test]
fn req_0095_warns_on_readd_similar_to_recent_obsolete() {
    let s = Sandbox::new();
    s.init("p");
    assert!(s
        .run(&[
            "add",
            "-t",
            "Stop the motor on demand",
            "-s",
            "The system shall stop the motor on demand.",
            "-r",
            "operator safety constraint",
            "-k",
            "functional",
            "-p",
            "must",
            "-a",
            "motor halts within one second",
        ])
        .status
        .success());
    s.run(&[
        "update",
        "REQ-0001",
        "--status",
        "obsolete",
        "--reason",
        "superseded by a newer approach",
    ]);
    let o = s.run(&[
        "add",
        "-t",
        "Stop the motor on demand",
        "-s",
        "The system shall stop the motor immediately on demand.",
        "-r",
        "operator safety constraint here",
        "-k",
        "functional",
        "-p",
        "must",
        "-a",
        "motor halts within one second flat",
    ]);
    // AC2: the add is not blocked — a fresh Draft is created.
    assert!(
        o.status.success(),
        "add must not be blocked: {}",
        stderr(&o)
    );
    let out = format!("{}{}", stdout(&o), stderr(&o));
    // AC1: the warning names the obsolete id.
    assert!(
        out.contains("similar") && out.contains("REQ-0001"),
        "warn names obsolete id:\n{}",
        out
    );
    assert!(
        out.contains("Added REQ-0002"),
        "draft still created:\n{}",
        out
    );
}

/// REQ-0118: a --dry-run invocation never writes project.req — two consecutive
/// dry-runs leave the file byte-identical and add no requirements.
#[test]
fn req_0118_dry_run_never_persists() {
    let s = Sandbox::new();
    s.init("p");
    let doc = s.dir.path().join("reqs.md");
    std::fs::write(
        &doc,
        "# Reqs\n\n## The system shall log every error to disk\n\nRationale: auditability.\n",
    )
    .unwrap();
    let before = std::fs::read(s.path()).unwrap();
    for _ in 0..2 {
        let _ = s.run(&[
            "import",
            "--format",
            "markdown",
            "--dry-run",
            doc.to_str().unwrap(),
        ]);
    }
    let after = std::fs::read(s.path()).unwrap();
    assert_eq!(before, after, "dry-run must not modify project.req");
    assert!(
        !stdout(&s.run(&["list"]))
            .to_lowercase()
            .contains("log every error"),
        "dry-run must not persist a requirement"
    );
}

/// REQ-0180: an ingested test result is bound to the payload commit, and a
/// payload omitting the commit is rejected.
#[test]
fn req_0180_ingest_binds_commit_and_rejects_missing() {
    let (s, sha) = implemented_in_git();
    let p = s.dir.path().join("r.json");
    std::fs::write(
        &p,
        format!(
            r#"{{"schema":"req-test-result-v1","system":"at_test","commit":"{}","results":[{{"req_id":"REQ-0001","verdict":"pass","notes":"bench"}}]}}"#,
            sha
        ),
    )
    .unwrap();
    assert!(run_in(&s, &["test", "ingest", p.to_str().unwrap()])
        .status
        .success());
    let v: serde_json::Value =
        serde_json::from_str(&stdout(&run_in(&s, &["show", "REQ-0001", "--json"]))).unwrap();
    let last = v["tests"].as_array().unwrap().last().unwrap();
    assert_eq!(
        last["commit"].as_str().unwrap(),
        sha,
        "record bound to the payload commit"
    );
    // AC3: a payload with no commit is rejected.
    let p2 = s.dir.path().join("nocommit.json");
    std::fs::write(
        &p2,
        r#"{"schema":"req-test-result-v1","system":"at_test","results":[{"req_id":"REQ-0001","verdict":"pass"}]}"#,
    )
    .unwrap();
    assert!(
        !run_in(&s, &["test", "ingest", p2.to_str().unwrap()])
            .status
            .success(),
        "a payload missing the commit must be rejected"
    );
}

/// REQ-0183: an external decision (plan/analysis/statement) populates the
/// dossier when its commit matches the anchor; a mismatched commit does not.
#[test]
fn req_0183_external_decision_populates_dossier() {
    let (s, sha) = implemented_in_git();
    let p = s.dir.path().join("d.json");
    std::fs::write(
        &p,
        format!(
            r#"{{"schema":"req-test-result-v1","system":"at_test","commit":"{}","results":[{{"req_id":"REQ-0001","verdict":"pass","decision":{{"plan":"bench plan here","analysis":"reviewed on bench","statement":"meets the obligation"}}}}]}}"#,
            sha
        ),
    )
    .unwrap();
    assert!(run_in(&s, &["test", "ingest", p.to_str().unwrap()])
        .status
        .success());
    let v: serde_json::Value =
        serde_json::from_str(&stdout(&run_in(&s, &["show", "REQ-0001", "--json"]))).unwrap();
    let ver = &v["verification"];
    assert_eq!(ver["plan"].as_str().unwrap(), "bench plan here");
    assert_eq!(ver["statement"].as_str().unwrap(), "meets the obligation");
    assert_eq!(
        ver["analysis"]["summary"].as_str().unwrap(),
        "reviewed on bench"
    );
    // AC3: a decision whose commit does not match the anchor must not apply.
    let p2 = s.dir.path().join("d2.json");
    std::fs::write(
        &p2,
        r#"{"schema":"req-test-result-v1","system":"at_test","commit":"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef","results":[{"req_id":"REQ-0001","verdict":"pass","decision":{"plan":"mismatched plan here"}}]}"#,
    )
    .unwrap();
    let _ = run_in(&s, &["test", "ingest", p2.to_str().unwrap()]);
    let v2: serde_json::Value =
        serde_json::from_str(&stdout(&run_in(&s, &["show", "REQ-0001", "--json"]))).unwrap();
    assert_ne!(
        v2["verification"]["plan"].as_str().unwrap(),
        "mismatched plan here",
        "a decision with a non-matching commit must not overwrite the dossier"
    );
}

/// REQ-0190: the well-formedness command is `req conform`; `req validate` is gone.
#[test]
fn req_0190_conform_replaces_validate() {
    let s = Sandbox::new();
    s.init("p");
    assert!(s.run(&["conform"]).status.success(), "conform should run");
    let o = s.run(&["validate"]);
    assert!(!o.status.success(), "validate must be gone");
    assert!(
        stderr(&o).to_lowercase().contains("unrecognized")
            || stderr(&o).to_lowercase().contains("unexpected"),
        "validate should be an unknown subcommand: {}",
        stderr(&o)
    );
}

/// REQ-0196: the IEC 61508 terminology reference is available via `req help`.
#[test]
fn req_0196_terminology_reference_available() {
    let s = Sandbox::new();
    s.init("p");
    let body = stdout(&s.run(&["help", "terminology"]));
    let up = body.to_uppercase();
    assert!(
        up.contains("VERIFICATION")
            && up.contains("VALIDATION")
            && body.to_lowercase().contains("conform"),
        "terminology reference must define the V&V vocabulary:\n{}",
        body
    );
}

/// REQ-0092: `req status --tag` scopes the report to a milestone slice.
#[test]
fn req_0092_status_tag_scopes_report() {
    let s = Sandbox::new();
    s.init("p");
    s.run(&[
        "add",
        "-t",
        "Alpha thing here",
        "-s",
        "The system shall do alpha.",
        "-r",
        "alpha rationale here",
        "-k",
        "functional",
        "-a",
        "alpha works",
        "--tag",
        "alpha",
    ]);
    s.run(&[
        "add",
        "-t",
        "Beta thing here",
        "-s",
        "The system shall do beta.",
        "-r",
        "beta rationale here",
        "-k",
        "functional",
        "-a",
        "beta works",
        "--tag",
        "beta",
    ]);
    let v: serde_json::Value =
        serde_json::from_str(&stdout(&s.run(&["status", "--json", "--tag", "alpha"]))).unwrap();
    assert_eq!(v["total"].as_i64().unwrap(), 1, "tag must scope to one req");
    assert_eq!(v["filter"]["tags"][0].as_str().unwrap(), "alpha");
}

/// REQ-0022: atomic temp-and-rename leaves no partial/.tmp file after a save.
#[test]
fn req_0022_atomic_write_leaves_no_tmp() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s);
    let leftover: Vec<_> = std::fs::read_dir(s.dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
        .collect();
    assert!(
        leftover.is_empty(),
        "no .tmp file should remain after an atomic save"
    );
}

/// REQ-0102: conformance findings name both the cause and the fix.
#[test]
fn req_0102_findings_name_cause_and_fix() {
    let s = Sandbox::new();
    s.init("p");
    // A compound statement triggers REQ-V-0010, whose message names the cause
    // (compound) and the fix (`req split`).
    s.run(&[
        "add",
        "-t",
        "Compound thing here",
        "-s",
        "The system shall do A and shall do B and shall do C.",
        "-r",
        "exercise the finding message",
        "-k",
        "functional",
        "-a",
        "does a and b and c",
    ]);
    let out = stdout(&s.run(&["conform"]));
    assert!(
        out.contains("REQ-V-0010"),
        "expected the compound finding:\n{}",
        out
    );
    assert!(
        out.contains("split"),
        "finding should name the `req split` fix:\n{}",
        out
    );
}

/// REQ-0051: a candidate rejected by the conformance check does not burn a REQ ID.
#[test]
fn req_0051_failed_add_does_not_burn_id() {
    let s = Sandbox::new();
    s.init("p");
    add_one(&s); // REQ-0001
    let bad = s.run(&[
        "add",
        "-t",
        "X",
        "-s",
        "too short",
        "-r",
        "x",
        "-k",
        "functional",
        "-a",
        "a",
    ]);
    assert!(!bad.status.success(), "invalid add must be rejected");
    let ok = s.run(&[
        "add",
        "-t",
        "Second valid thing",
        "-s",
        "The system shall do the second thing.",
        "-r",
        "second rationale here",
        "-k",
        "functional",
        "-a",
        "second works",
    ]);
    assert!(ok.status.success(), "valid add: {}", stderr(&ok));
    assert!(
        stdout(&ok).contains("REQ-0002"),
        "rejected add must not burn the ID:\n{}",
        stdout(&ok)
    );
}

/// SR-0001: a project.req whose content fails its integrity hash is refused at
/// load with a pointer to `req repair` (not silently mis-read).
#[test]
fn sr_0001_integrity_tamper_refused_with_repair_pointer() {
    let s = Sandbox::new();
    s.init("p");
    let p = s.path();
    let body = std::fs::read_to_string(&p)
        .unwrap()
        .replace("\"name\": \"p\"", "\"name\": \"X\"");
    std::fs::write(&p, body).unwrap();
    let o = s.run(&["list"]);
    assert!(!o.status.success(), "a tampered file must refuse to load");
    let e = stderr(&o).to_lowercase();
    assert!(
        e.contains("integrity") && e.contains("repair"),
        "error must flag integrity and point to repair:\n{}",
        stderr(&o)
    );
}

/// SR-0004: the verification provenance report classifies every Verified item
/// into the provenance categories with counts (genuine / exempt / stale /
/// unconfirmed / ungated).
#[test]
fn sr_0004_provenance_report_classifies_categories() {
    let s = Sandbox::new();
    s.init("p");
    let v: serde_json::Value =
        serde_json::from_str(&stdout(&s.run(&["verification", "report", "--json"]))).unwrap();
    let counts = &v["counts"];
    for k in [
        "genuine",
        "exempt_backfilled",
        "exempt_no_dossier",
        "stale",
        "unconfirmed",
        "ungated",
    ] {
        assert!(
            counts.get(k).is_some(),
            "provenance report must report category '{}':\n{}",
            k,
            v["counts"]
        );
    }
}

/// SR-0006: a conformance (well-formedness) check must not present as V&V status
/// and must point to the command that reports true verification standing —
/// on the human and the --json paths.
#[test]
fn sr_0006_conform_disclaims_vv_and_points_to_status() {
    let s = Sandbox::new();
    s.init("p");
    let human = stdout(&s.run(&["conform"]));
    assert!(
        human.contains("well-formedness") && human.contains("verification status"),
        "conform output must disclaim V&V and point to `req verification status`:\n{}",
        human
    );
    let v: serde_json::Value =
        serde_json::from_str(&stdout(&s.run(&["conform", "--json"]))).unwrap();
    let note = v["note"].as_str().unwrap_or("");
    assert!(
        note.contains("well-formedness") && note.contains("verification status"),
        "conform --json must carry the same disclaimer in `note`: {}",
        note
    );
}

/// SR-0002 (full scope): the SIL-rigour gate blocks inspection-only promotion
/// at SIL4 (not just SIL3), and an audited --force --reason exception is
/// recorded on the resulting test record.
#[test]
fn sr_0002_sil_gate_at_sil4_records_audited_exception() {
    let s = Sandbox::new();
    s.init("p");
    s.enable_safety();
    // Force a leaf to SIL4 so the chain inherits SIL4 deterministically.
    s.run(&["safety", "calibrate", "--set", "C_D/F_B/P_B=W3:4,W2:3,W1:2"]);
    s.run(&[
        "hazard",
        "add",
        "-t",
        "Severe hazard",
        "--harm",
        "death",
        "-C",
        "C_D",
        "-F",
        "F_B",
        "-P",
        "P_B",
        "-W",
        "W3",
    ]);
    s.run(&[
        "sf",
        "add",
        "-t",
        "Protective function",
        "--mitigates",
        "HAZ-0001",
    ]);
    s.run(&[
        "sreq",
        "add",
        "-t",
        "Stop the blade now",
        "-s",
        "The system shall stop the blade on demand.",
        "-r",
        "operator safety during cleaning",
        "-a",
        "blade stops within 200ms",
        "--realizes",
        "SF-0001",
    ]);
    assert!(
        stdout(&s.run(&["sreq", "show", "SR-0001"])).contains("SIL4"),
        "SR must inherit SIL4"
    );
    for st in ["approved", "implemented"] {
        s.run(&[
            "sreq",
            "update",
            "SR-0001",
            "--status",
            st,
            "--reason",
            "advance step",
        ]);
    }
    // Genuine dossier so the dossier gate is satisfied (SIL gate is under test).
    s.run(&[
        "verification",
        "plan",
        "SR-0001",
        "--plan",
        "review + bench test",
    ]);
    s.run(&[
        "verification",
        "analysis",
        "SR-0001",
        "--result",
        "pass",
        "--findings",
        "stop logic reviewed",
    ]);
    s.run(&[
        "verification",
        "test",
        "SR-0001",
        "--result",
        "pass",
        "--findings",
        "bench measured the stop",
    ]);
    s.run(&[
        "verification",
        "conclude",
        "SR-0001",
        "--statement",
        "meets the stop obligation",
    ]);
    // Gate blocks inspection-only promotion at SIL4.
    let blocked = s.run(&[
        "sreq",
        "verify",
        "SR-0001",
        "--by",
        "inspection",
        "--promote",
    ]);
    assert!(
        !blocked.status.success(),
        "SIL4 inspection promote must be blocked"
    );
    assert!(
        stderr(&blocked).contains("SIL-rigour gate"),
        "stderr: {}",
        stderr(&blocked)
    );
    // --force --reason succeeds AND records the audited exception.
    let forced = s.run(&[
        "sreq",
        "verify",
        "SR-0001",
        "--by",
        "inspection",
        "--promote",
        "--force",
        "--reason",
        "accepted at design review",
    ]);
    assert!(forced.status.success(), "force+reason: {}", stderr(&forced));
    let v: serde_json::Value =
        serde_json::from_str(&stdout(&s.run(&["sreq", "show", "SR-0001", "--json"]))).unwrap();
    let last = v["tests"].as_array().unwrap().last().unwrap();
    assert_eq!(
        last["sil_gate_exception"], true,
        "audited exception must be recorded on the record"
    );
}

/// SR-0003 (full scope): a reasoned, attributed history entry is appended for a
/// mutation of EACH safety family — hazard, safety function, AND safety
/// requirement — not just the safety requirement.
#[test]
fn sr_0003_history_appended_for_hazard_sf_and_sr() {
    let s = Sandbox::new();
    s.init("p");
    s.enable_safety();
    s.run(&[
        "hazard", "add", "-t", "A hazard", "--harm", "hurt", "-C", "C_C", "-F", "F_B", "-P", "P_B",
        "-W", "W3",
    ]);
    s.run(&["sf", "add", "-t", "A function", "--mitigates", "HAZ-0001"]);
    s.run(&[
        "sreq",
        "add",
        "-t",
        "Stop the blade now",
        "-s",
        "The system shall stop the blade.",
        "-r",
        "operator safety here",
        "-a",
        "stops",
        "--realizes",
        "SF-0001",
    ]);
    // Mutate each family with a reason.
    s.run(&[
        "hazard",
        "update",
        "HAZ-0001",
        "-t",
        "A hazard renamed",
        "--reason",
        "retitle hazard for clarity",
    ]);
    s.run(&[
        "sf",
        "update",
        "SF-0001",
        "-t",
        "A function renamed",
        "--reason",
        "retitle function for clarity",
    ]);
    s.run(&[
        "sreq",
        "update",
        "SR-0001",
        "--status",
        "approved",
        "--reason",
        "approve the requirement",
    ]);
    for (cmd, id) in [
        ("hazard", "HAZ-0001"),
        ("sf", "SF-0001"),
        ("sreq", "SR-0001"),
    ] {
        let v: serde_json::Value =
            serde_json::from_str(&stdout(&s.run(&[cmd, "show", id, "--json"]))).unwrap();
        let hist = v["history"].as_array().unwrap();
        assert!(
            hist.len() >= 2,
            "{} must accumulate history (append-only): {:?}",
            id,
            hist
        );
        let last = hist.last().unwrap();
        assert!(
            last["actor"].as_str().filter(|s| !s.is_empty()).is_some()
                && last["action"].as_str().filter(|s| !s.is_empty()).is_some()
                && last["reason"].as_str().filter(|s| !s.is_empty()).is_some(),
            "{} latest history entry must carry actor + action + reason: {}",
            id,
            last
        );
    }
}