req-cli 0.5.0-rc.7

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
// Implements REQ-0049 (record test runs with git HEAD SHA + outcome + notes),
// REQ-0055 (req test run — drive cargo test, parse output, attach one
// pass/fail record per REQ), and REQ-0056 (verify-by-evidence policy:
// Verified status is backed by an automated test OR a written justification,
// recorded as a composition or inspection EvidenceKind on the same TestRecord
// shape with --promote auto-flipping status when a fresh passing record of
// any kind exists against current HEAD).
use anyhow::{anyhow, Context, Result};
use chrono::Utc;
use once_cell::sync::Lazy;
use regex::Regex;
use serde_json::json;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::process::Command;

use crate::cli::{
    TestCmd, TestListArgs, TestRecordArgs, TestResultArg, TestRunArgs, VerifyArgs, VerifyKindArg,
};
use crate::model::{EvidenceKind, Status, TestOutcome, TestRecord};
use crate::storage::{self, load_for_mutation};

pub fn run(cmd: TestCmd, file: &Option<PathBuf>) -> Result<()> {
    match cmd {
        TestCmd::Record(args) => record(args, file),
        TestCmd::Run(args) => run_suite(args, file),
        TestCmd::List(args) => list(args, file),
        // REQ-0175/0177/0181: external test-system integration.
        TestCmd::Requests(args) => super::integration::requests(args, file),
        TestCmd::Ingest(args) => super::integration::ingest(args, file),
        TestCmd::Pull(args) => super::integration::pull(args, file),
    }
}

/// REQ-0129: dedicated subcommand to inspect a requirement's test
/// record history without parsing `req show --json`. Mirrors the
/// TestRecord shape with one record per line.
fn list(mut args: TestListArgs, file: &Option<PathBuf>) -> Result<()> {
    use crate::storage::load_resolved;
    let (_, project) = load_resolved(file)?;
    args.id = super::resolve_id(&project, &args.id)?;
    let r = project
        .requirements
        .get(&args.id)
        .ok_or_else(|| anyhow!("no such requirement: {}", args.id))?;

    if args.json {
        println!("{}", serde_json::to_string_pretty(&r.tests)?);
        return Ok(());
    }
    if r.tests.is_empty() {
        println!("(no test records)");
        return Ok(());
    }
    for t in &r.tests {
        // REQ-0179: show provenance — external records name their system and
        // environment; locally-produced records are labelled as such.
        let source = match &t.external {
            Some(e) => format!(
                "ext:{}{}",
                e.system,
                e.environment
                    .as_deref()
                    .map(|env| format!("/{}", env))
                    .unwrap_or_default()
            ),
            None => "local".to_string(),
        };
        println!(
            "{}  {}  {}  {}  [{}]  {}",
            t.at.format("%Y-%m-%d %H:%M UTC"),
            short(&t.commit),
            t.outcome.as_str(),
            t.kind.as_str(),
            source,
            t.notes
        );
    }
    Ok(())
}

pub fn verify(mut args: VerifyArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    args.id = super::resolve_id(&project, &args.id)?;
    let kind = match args.by {
        VerifyKindArg::Composition => EvidenceKind::Composition,
        VerifyKindArg::Inspection => EvidenceKind::Inspection,
    };
    let commit = current_head_sha_opt().unwrap_or_else(|| "(no git)".into());
    let cites_prefix = if args.cites.is_empty() {
        String::new()
    } else {
        format!("cites: {}", args.cites.join(", "))
    };
    let record = TestRecord {
        at: Utc::now(),
        actor: super::current_actor(),
        commit: commit.clone(),
        outcome: TestOutcome::Pass,
        notes: format!("{}{}", cites_prefix, args.notes),
        kind,
        content_hash: None,
        linked_files: None,
        sil_gate_exception: false,
        sil_at_verification: None,
        external: None,
    };
    // REQ-0139: evaluate the verification-dossier gate before taking the
    // mutable borrow (the gate needs to read project config + the dossier).
    let dossier_ok = project.requirements[&args.id]
        .verification
        .as_ref()
        .map(|v| v.passed())
        .unwrap_or(false);
    let exempt_by_tag = project.req_is_verification_exempt(&project.requirements[&args.id]);
    let r = project.requirements.get_mut(&args.id).unwrap();
    r.tests.push(record.clone());
    r.history.push(super::history(
        format!(
            "{} evidence recorded against commit {}",
            kind.as_str(),
            short(&commit)
        ),
        Some(args.notes.clone()),
    ));
    r.updated = Utc::now();
    let mut promoted = false;
    if args.promote {
        // Promotion bypassed the lifecycle entirely before: Draft was
        // promoted straight to Verified. Now Implemented is the only
        // status that auto-promotes; everything else requires --force
        // so the user has to acknowledge the skip.
        let eligible = matches!(r.status, Status::Implemented);
        if eligible || args.force {
            if !matches!(r.status, Status::Verified | Status::Obsolete) {
                // REQ-0139: a passing dossier (or a tag/`--no-dossier`
                // exemption) is the precondition for Verified.
                if !dossier_ok && !exempt_by_tag {
                    if args.no_dossier {
                        let reason = args.reason.clone().unwrap_or_default();
                        r.verification = Some(super::verification::exemption_dossier(
                            &reason,
                            super::current_actor(),
                            commit.clone(),
                        ));
                    } else {
                        // REQ-0165: enumerate the legal routes (shared with MCP).
                        return Err(anyhow!(
                            "{}",
                            super::verification::promotion_blocked_message(&args.id)
                        ));
                    }
                }
                r.status = Status::Verified;
                r.history.push(super::history(
                    format!(
                        "status promoted to verified ({} evidence on HEAD)",
                        kind.as_str()
                    ),
                    None,
                ));
                promoted = true;
            }
        } else if !matches!(r.status, Status::Verified | Status::Obsolete) {
            return Err(anyhow!(
                "{} is at status '{}'; --promote only auto-promotes from \
                 'implemented'. Move it to implemented first (`req update \
                 {} --status implemented --reason ...`), or pass --force \
                 to skip the precondition.",
                args.id,
                r.status.as_str(),
                args.id
            ));
        }
    }
    project.updated = Utc::now();
    storage::save(&path, &project)?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "id": args.id, "kind": kind.as_str(),
                "commit": commit, "promoted": promoted,
                "requirement": project.requirements[&args.id],
            }))?
        );
    } else {
        println!(
            "Recorded {} evidence on {} against commit {}.{}",
            kind.as_str(),
            args.id,
            short(&commit),
            if promoted {
                " Promoted to Verified."
            } else {
                ""
            }
        );
    }
    Ok(())
}

fn record(mut args: TestRecordArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    args.id = super::resolve_id(&project, &args.id)?;
    let commit = current_head_sha()
        .context("not in a git working tree — cannot record a test run without a commit SHA")?;
    let outcome = match args.result {
        TestResultArg::Pass => TestOutcome::Pass,
        TestResultArg::Fail => TestOutcome::Fail,
    };
    // REQ-0112: content-hash the linked source files at record time
    // so `req stale` can fire on actual content changes rather than
    // any HEAD movement. Auto-discovered via `// REQ-NNNN:` markers.
    let auto_linked = auto_linked_files(&args.id, std::path::Path::new("."));
    let content_hash = if auto_linked.is_empty() {
        None
    } else {
        Some(hash_files(&auto_linked))
    };
    let record = TestRecord {
        at: Utc::now(),
        actor: super::current_actor(),
        commit,
        outcome,
        notes: args.notes,
        kind: EvidenceKind::Automated,
        content_hash,
        linked_files: if auto_linked.is_empty() {
            None
        } else {
            Some(
                auto_linked
                    .iter()
                    .map(|p| p.to_string_lossy().to_string())
                    .collect(),
            )
        },
        sil_gate_exception: false,
        sil_at_verification: None,
        external: None,
    };
    let r = project.requirements.get_mut(&args.id).unwrap();
    r.tests.push(record.clone());
    r.history.push(super::history(
        format!(
            "test {} recorded against commit {}",
            outcome.as_str(),
            short(&record.commit)
        ),
        Some(record.notes.clone()).filter(|s| !s.is_empty()),
    ));
    r.updated = Utc::now();
    project.updated = Utc::now();
    storage::save(&path, &project)?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&project.requirements[&args.id])?
        );
    } else {
        println!(
            "Recorded {} test for {} against {}.",
            outcome.as_str(),
            args.id,
            short(&record.commit)
        );
    }
    Ok(())
}

fn current_head_sha() -> Result<String> {
    let out = Command::new("git").args(["rev-parse", "HEAD"]).output()?;
    if !out.status.success() {
        return Err(anyhow!(
            "git rev-parse HEAD failed: {}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

pub fn current_head_sha_opt() -> Option<String> {
    current_head_sha().ok()
}

pub fn short(sha: &str) -> String {
    sha.chars().take(9).collect()
}

// ---------- staleness ----------

/// Three-state staleness signal for a TestRecord, computed by intersecting
/// "files referencing this requirement in code" with "files changed in git
/// between the record commit and HEAD". `Fresh` means the record commit is
/// HEAD. `Drifted` means HEAD moved but no linked file changed. `Stale`
/// means at least one linked file changed since the record commit.
pub enum Staleness {
    Fresh,
    /// HEAD moved but none of the requirement's linked files changed.
    /// The number is how many linked files exist.
    Drifted {
        linked: usize,
    },
    /// At least one linked file changed since the record commit.
    /// `linked` is kept on the variant so `req stale --json` callers can
    /// see how many files the requirement is linked to alongside the
    /// changed-files list. Read by the JSON renderer in commands/stale.rs.
    #[allow(dead_code)]
    Stale {
        changed: Vec<String>,
        linked: usize,
    },
    /// No git context — neither fresh nor stale can be computed.
    Unknown,
}

impl Staleness {
    pub fn tag(&self) -> String {
        match self {
            Staleness::Fresh => "[matches HEAD]".to_string(),
            Staleness::Drifted { linked: 0 } => "[drifted — no linked files]".to_string(),
            Staleness::Drifted { linked } => {
                format!("[drifted — no changes to {} linked file(s)]", linked)
            }
            Staleness::Stale { changed, .. } => {
                format!("[STALE — changed: {}]", changed.join(", "))
            }
            Staleness::Unknown => "[HEAD unknown]".to_string(),
        }
    }
}

/// Files under `root` that contain `REQ-NNNN` for the given id.
/// REQ-0112: auto-discover linked files for a test record. Wraps
/// `files_referencing` with a stable ordering so the content hash is
/// reproducible across runs.
pub fn auto_linked_files(req_id: &str, root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut files = files_referencing(req_id, root);
    files.sort();
    files
}

/// REQ-0112: hash a list of files (sha256 over each file's contents,
/// concatenated with a path separator). Missing files produce an empty
/// byte block; the path is always included so deletion vs same-content
/// renames are distinguishable.
///
/// REQ-0152: the digest is platform-independent. The path component is
/// normalized to forward slashes so a dossier anchored on Windows (which
/// stores `.\src\x.rs`) matches the same logical file on a Linux/macOS CI
/// checkout, and the file is also READ through that normalized path so a
/// backslash path stored on Windows still resolves on a POSIX host. Carriage
/// returns are stripped from the content so a CRLF working tree hashes the same
/// as an LF one (autocrlf must not change a staleness verdict).
pub fn hash_files(files: &[std::path::PathBuf]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    for p in files {
        let norm = p.to_string_lossy().replace('\\', "/");
        hasher.update(norm.as_bytes());
        hasher.update(b"\0");
        if let Ok(bytes) = std::fs::read(&norm) {
            // CRLF -> LF: hash logical content, not the host's line-ending style.
            let lf: Vec<u8> = bytes.into_iter().filter(|&b| b != b'\r').collect();
            hasher.update(&lf);
        }
        hasher.update(b"\n");
    }
    format!("{:x}", hasher.finalize())
}

/// REQ-0153: the pre-REQ-0152 hashing algorithm — path string verbatim, raw
/// file bytes, no normalization. Kept ONLY so `req verification refresh-anchors`
/// can prove a dossier's source is byte-identical to what it anchored: if the
/// legacy hash of the current source still equals the stored hash, the bytes
/// have not changed since the anchor (so the new normalized hash can be
/// substituted safely, without re-verification). Never use for new anchors.
pub fn hash_files_legacy(files: &[std::path::PathBuf]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    for p in files {
        hasher.update(p.to_string_lossy().as_bytes());
        hasher.update(b"\0");
        if let Ok(bytes) = std::fs::read(p) {
            hasher.update(&bytes);
        }
        hasher.update(b"\n");
    }
    format!("{:x}", hasher.finalize())
}

pub fn files_referencing(req_id: &str, root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let exts: Vec<String> = [
        "rs", "py", "js", "ts", "tsx", "go", "java", "md", "toml", "c", "cpp", "h",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    let mut hits = Vec::new();
    // REQ-0124: source_walk honours .gitignore so test-record linked-file
    // discovery doesn't pick up artefacts in tmp/, dist/, etc.
    crate::source_walk::walk_source_tree(root, &exts, |path| {
        // REQ-0149: in a markdown file the only real comment is an HTML
        // comment (`<!-- ... -->`); `#` starts a heading and `*`/`-` start
        // list items, none of which are code markers. Scanning them as
        // "comments" wrongly linked every requirement cited in a CHANGELOG
        // heading (e.g. `### Added — … (REQ-0112)`) to CHANGELOG.md, so a
        // release's changelog edit falsely drifted dozens of requirements.
        let is_markdown = matches!(
            path.extension().and_then(|e| e.to_str()),
            Some("md") | Some("markdown")
        );
        if let Ok(text) = std::fs::read_to_string(path) {
            // REQ-0149: an item depends on a file only when the file carries
            // the id in a CODE COMMENT (a genuine `// SR-NNNN` / `// REQ-NNNN`
            // marker), not when the id merely appears in prose or a string
            // literal (README text, help-text examples, test arguments). This
            // scopes staleness to real implementation changes, so editing
            // unrelated prose or examples no longer invalidates a requirement.
            if text
                .lines()
                .filter_map(|line| comment_portion(line, is_markdown))
                .any(|c| c.contains(req_id))
            {
                hits.push(path.to_path_buf());
            }
        }
    });
    hits
}

/// REQ-0149: return the comment text of a line that *is* a comment. For code
/// files the trimmed line must begin with a comment delimiter (`//`, `/*`, `*`
/// doc continuation, `#`, `--`, `;`); for markdown (`is_markdown`) only an HTML
/// comment (`<!--`) counts, because `#`/`*`/`-` there are headings and list
/// items, not comments. Returns None otherwise, so an id that merely appears in
/// prose, a string literal, or a markdown heading is NOT treated as a
/// dependency marker — keeping a requirement's dependencies to genuine source
/// comment markers.
fn comment_portion(line: &str, is_markdown: bool) -> Option<&str> {
    let trimmed = line.trim_start();
    if is_markdown {
        return trimmed.starts_with("<!--").then_some(trimmed);
    }
    for delim in ["//", "/*", "*", "#", "--", ";"] {
        if trimmed.starts_with(delim) {
            return Some(trimmed);
        }
    }
    None
}

/// Files changed in git between `record_commit` and HEAD.
fn git_changed_since(record_commit: &str) -> Option<std::collections::BTreeSet<String>> {
    let out = std::process::Command::new("git")
        .args(["diff", "--name-only", &format!("{}..HEAD", record_commit)])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(
        String::from_utf8_lossy(&out.stdout)
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty())
            .collect(),
    )
}

/// REQ-0112: staleness check using a stored content_hash. Compares
/// the hash of the currently-linked files (auto-discovered, or the
/// explicit `linked_files` override) against `stored_hash`. STALE
/// when they differ; Fresh when they match. Always returns the count
/// of linked files for diagnostics.
pub fn staleness_by_content(
    stored_hash: &str,
    explicit_linked: Option<&Vec<String>>,
    req_id: &str,
    source_root: &std::path::Path,
) -> Staleness {
    let files: Vec<std::path::PathBuf> = match explicit_linked {
        Some(list) => list.iter().map(std::path::PathBuf::from).collect(),
        None => auto_linked_files(req_id, source_root),
    };
    let current_hash = hash_files(&files);
    if current_hash == stored_hash {
        Staleness::Fresh
    } else {
        // We don't have a per-file diff here — surface the linked set
        // so the user knows where to look. The `changed` vec carries
        // the linked files rather than just the deltas; this is more
        // useful in practice (you re-check all of them) and avoids a
        // second git invocation when content hashing already told us
        // something moved.
        let changed: Vec<String> = files
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect();
        if changed.is_empty() {
            Staleness::Drifted { linked: 0 }
        } else {
            Staleness::Stale {
                linked: changed.len(),
                changed,
            }
        }
    }
}

pub fn staleness(record_commit: &str, req_id: &str, source_root: &std::path::Path) -> Staleness {
    let head = match current_head_sha_opt() {
        Some(h) => h,
        None => return Staleness::Unknown,
    };
    if head == record_commit {
        return Staleness::Fresh;
    }
    let linked = files_referencing(req_id, source_root);
    let linked_strs: std::collections::BTreeSet<String> = linked
        .iter()
        .map(|p| p.to_string_lossy().replace('\\', "/"))
        .collect();
    let changed = match git_changed_since(record_commit) {
        Some(c) => c,
        None => return Staleness::Unknown,
    };
    let mut overlap: Vec<String> = linked_strs
        .iter()
        .filter(|f| {
            changed
                .iter()
                .any(|c| c.replace('\\', "/").ends_with(f.as_str()) || f.ends_with(c))
        })
        .cloned()
        .collect();
    overlap.sort();
    overlap.dedup();
    if overlap.is_empty() {
        Staleness::Drifted {
            linked: linked.len(),
        }
    } else {
        Staleness::Stale {
            changed: overlap,
            linked: linked.len(),
        }
    }
}

// ---------- req test run ----------

static TEST_LINE: Lazy<Regex> = Lazy::new(|| {
    // REQ-0135: matches `test req_0006_some_name ... ok|FAILED|ignored`
    // and the safety variant `test sr_0007_some_name ... ok`, so a SIL
    // 3/4 safety requirement's automated evidence is produced by a real
    // run, not a hand-asserted record.
    Regex::new(r"(?m)^test\s+(?:[\w:]+::)?((req|sr)_(\d{4})\w*)\s+\.\.\.\s+(ok|FAILED|ignored)")
        .unwrap()
});

#[derive(Debug, Default)]
pub(crate) struct ReqResult {
    pub(crate) passed: Vec<String>,
    pub(crate) failed: Vec<String>,
    pub(crate) ignored: Vec<String>,
}

/// REQ-0200: run (or ingest via `from_file`) the test command and parse its
/// output into a per-requirement pass/fail/ignored map. Shared by `req test
/// run` and `req verification reverify --by-tests` so both read results the
/// same way. Returns the map and whether the command exited successfully.
pub(crate) fn collect_results(
    cmd: &str,
    from_file: Option<&std::path::Path>,
    map_file: Option<&std::path::Path>,
) -> Result<(BTreeMap<String, ReqResult>, bool)> {
    // Either parse a pre-captured log file (--from-file) or run the test
    // command and parse its combined stdout+stderr. The file path bypasses
    // shell quoting entirely, which matters for tests on Windows where
    // splitting --cmd on whitespace drops cmd.exe's /C argument boundaries.
    let (combined, exec_success) = if let Some(p) = from_file {
        let body = std::fs::read_to_string(p)
            .with_context(|| format!("read --from-file {}", p.display()))?;
        (body, true)
    } else {
        let parts: Vec<&str> = cmd.split_whitespace().collect();
        if parts.is_empty() {
            return Err(anyhow!("empty test command"));
        }
        let out = Command::new(parts[0])
            .args(&parts[1..])
            .output()
            .with_context(|| format!("invoke {}", cmd))?;
        let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
        let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
        (format!("{}\n{}", stdout, stderr), out.status.success())
    };

    let mut by_req: BTreeMap<String, ReqResult> = BTreeMap::new();
    for cap in TEST_LINE.captures_iter(&combined) {
        let test_name = cap[1].to_string();
        let id = format!("{}-{}", cap[2].to_uppercase(), &cap[3]);
        let verdict = &cap[4];
        let bucket = by_req.entry(id).or_default();
        match verdict {
            "ok" => bucket.passed.push(test_name),
            "FAILED" => bucket.failed.push(test_name),
            "ignored" => bucket.ignored.push(test_name),
            _ => {}
        }
    }

    // REQ-0128: load an external test-name → REQ-ID map and walk a
    // generic verdict regex over the same combined output. This is
    // the Node/Python/etc. path: tests don't follow `req_NNNN_*` so
    // the mapping is explicit. Format: `{ "<test name>": ["REQ-NNNN", ...] }`.
    if let Some(map_path) = map_file {
        let body = std::fs::read_to_string(map_path)
            .with_context(|| format!("read --map {}", map_path.display()))?;
        let map: BTreeMap<String, Vec<String>> = serde_json::from_str(&body)
            .with_context(|| format!("parse --map {} as JSON", map_path.display()))?;
        // Generic verdict line: "<test name> ... ok|FAILED|ignored". We
        // anchor on the exact test name (as a substring of any line) and
        // look for one of the verdict tokens on the same line. This is a
        // forgiving match that works for mocha/pytest/jest in default
        // reporters.
        for (test_name, ids) in &map {
            for line in combined.lines() {
                if !line.contains(test_name) {
                    continue;
                }
                let verdict = if line.contains("FAILED") || line.contains("FAIL") {
                    Some("FAILED")
                } else if line.contains(" ok") || line.contains("PASS") || line.contains("pass") {
                    Some("ok")
                } else if line.contains("ignored") || line.contains("SKIP") || line.contains("skip")
                {
                    Some("ignored")
                } else {
                    None
                };
                if let Some(v) = verdict {
                    for id in ids {
                        let bucket = by_req.entry(id.clone()).or_default();
                        match v {
                            "ok" => bucket.passed.push(test_name.clone()),
                            "FAILED" => bucket.failed.push(test_name.clone()),
                            "ignored" => bucket.ignored.push(test_name.clone()),
                            _ => {}
                        }
                    }
                    break; // one verdict per test name
                }
            }
        }
    }

    Ok((by_req, exec_success))
}

fn run_suite(args: TestRunArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;

    let (by_req, exec_success) = collect_results(
        &args.cmd,
        args.from_file.as_deref(),
        args.map_file.as_deref(),
    )?;

    if by_req.is_empty() {
        let msg = "no test names matched the `req_NNNN_*` convention";
        if args.json {
            println!(
                "{}",
                serde_json::to_string_pretty(
                    &json!({ "ok": exec_success, "matched": 0, "message": msg })
                )?
            );
        } else {
            eprintln!("{}", msg);
        }
        return Ok(());
    }

    let commit = current_head_sha_opt();
    let actor = super::current_actor();

    let mut records_to_apply: Vec<(String, TestRecord)> = Vec::new();
    let mut summary: Vec<serde_json::Value> = Vec::new();
    for (req_id, res) in &by_req {
        let exists = project.requirements.contains_key(req_id)
            || project.safety_requirements.contains_key(req_id);
        let outcome = if !res.failed.is_empty() {
            TestOutcome::Fail
        } else {
            TestOutcome::Pass
        };
        let total = res.passed.len() + res.failed.len() + res.ignored.len();
        let notes = format!(
            "cargo test: {} pass / {} fail / {} ignored — {}",
            res.passed.len(),
            res.failed.len(),
            res.ignored.len(),
            if res.failed.is_empty() {
                res.passed
                    .iter()
                    .chain(res.ignored.iter())
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            } else {
                res.failed.join(", ")
            }
        );
        summary.push(json!({
            "req_id": req_id,
            "exists_in_project": exists,
            "outcome": outcome.as_str(),
            "tests": total,
            "passed": res.passed.len(),
            "failed": res.failed.len(),
            "ignored": res.ignored.len(),
            "test_names": {
                "passed": res.passed,
                "failed": res.failed,
                "ignored": res.ignored,
            },
        }));
        if !exists || args.dry_run {
            continue;
        }
        // REQ-0112: content-hash auto-discovered linked files.
        let auto_linked = auto_linked_files(req_id, std::path::Path::new("."));
        let content_hash = if auto_linked.is_empty() {
            None
        } else {
            Some(hash_files(&auto_linked))
        };
        let record = TestRecord {
            at: Utc::now(),
            actor: actor.clone(),
            commit: commit.clone().unwrap_or_else(|| "(no git)".into()),
            outcome,
            notes,
            kind: EvidenceKind::Automated,
            content_hash,
            linked_files: if auto_linked.is_empty() {
                None
            } else {
                Some(
                    auto_linked
                        .iter()
                        .map(|p| p.to_string_lossy().to_string())
                        .collect(),
                )
            },
            sil_gate_exception: false,
            sil_at_verification: None,
            external: None,
        };
        records_to_apply.push((req_id.clone(), record));
    }

    let mut promoted: Vec<String> = Vec::new();
    if !args.dry_run {
        for (req_id, record) in &records_to_apply {
            // REQ-0135: route to the requirements or the safety-requirements
            // map, so `sr_NNNN_*` tests attach automated evidence to SRs.
            let (tests, history, updated) = if let Some(r) = project.requirements.get_mut(req_id) {
                (&mut r.tests, &mut r.history, &mut r.updated)
            } else if let Some(sr) = project.safety_requirements.get_mut(req_id) {
                (&mut sr.tests, &mut sr.history, &mut sr.updated)
            } else {
                continue;
            };
            tests.push(record.clone());
            history.push(super::history(
                format!(
                    "test {} recorded against commit {} via req test run",
                    record.outcome.as_str(),
                    short(&record.commit)
                ),
                None,
            ));
            *updated = Utc::now();
        }
        // Auto-promote pass after writing records, so the latest record is
        // already on tests when we evaluate "is there fresh evidence?".
        if args.promote {
            // REQ-0139: a bulk test run promotes only items that already
            // carry a passing verification dossier (or, for ordinary reqs, a
            // tag exemption). Items without one are left for the explicit
            // `req verification` flow rather than erroring the whole run.
            let dossier_ok: std::collections::BTreeSet<String> = records_to_apply
                .iter()
                .filter_map(|(id, _)| {
                    let ok = if let Some(r) = project.requirements.get(id) {
                        r.verification.as_ref().map(|v| v.passed()).unwrap_or(false)
                            || project.req_is_verification_exempt(r)
                    } else if let Some(sr) = project.safety_requirements.get(id) {
                        sr.verification
                            .as_ref()
                            .map(|v| v.passed())
                            .unwrap_or(false)
                    } else {
                        false
                    };
                    if ok {
                        Some(id.clone())
                    } else {
                        None
                    }
                })
                .collect();
            let head = current_head_sha_opt();
            for (req_id, _) in &records_to_apply {
                if !dossier_ok.contains(req_id) {
                    continue;
                }
                let (status, tests, history): (&mut Status, &Vec<TestRecord>, &mut Vec<_>) =
                    if let Some(r) = project.requirements.get_mut(req_id) {
                        (&mut r.status, &r.tests, &mut r.history)
                    } else if let Some(sr) = project.safety_requirements.get_mut(req_id) {
                        (&mut sr.status, &sr.tests, &mut sr.history)
                    } else {
                        continue;
                    };
                if matches!(*status, Status::Verified | Status::Obsolete) {
                    continue;
                }
                let fresh = match &head {
                    Some(h) => tests
                        .iter()
                        .any(|t| t.outcome == TestOutcome::Pass && &t.commit == h),
                    None => false,
                };
                if fresh {
                    *status = Status::Verified;
                    history.push(super::history(
                        "status promoted to verified (req test run --promote, fresh passing record on HEAD)",
                        None,
                    ));
                    promoted.push(req_id.clone());
                }
            }
        }
        if !records_to_apply.is_empty() || !promoted.is_empty() {
            project.updated = Utc::now();
            storage::save(&path, &project)?;
        }
    }

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&json!({
                "ok": exec_success,
                "dry_run": args.dry_run,
                "source": args.from_file.as_ref().map(|p| p.display().to_string())
                    .unwrap_or_else(|| args.cmd.clone()),
                "matched_requirements": summary.len(),
                "recorded": if args.dry_run { 0 } else { records_to_apply.len() },
                "results": summary,
            }))?
        );
    } else {
        let mode = if args.dry_run { " (dry-run)" } else { "" };
        println!("req test run{} — `{}`", mode, args.cmd);
        for entry in &summary {
            let id = entry["req_id"].as_str().unwrap();
            let exists = entry["exists_in_project"].as_bool().unwrap();
            let outcome = entry["outcome"].as_str().unwrap();
            let p = entry["passed"].as_u64().unwrap();
            let f = entry["failed"].as_u64().unwrap();
            let i = entry["ignored"].as_u64().unwrap();
            let tag = if !exists { " (unknown REQ)" } else { "" };
            println!(
                "  {} {:<4} {} pass / {} fail / {} ignored{}",
                id,
                outcome.to_uppercase(),
                p,
                f,
                i,
                tag
            );
        }
        if !args.dry_run {
            println!();
            println!("Recorded {} test record(s).", records_to_apply.len());
            if args.promote {
                println!("Promoted {} requirement(s) to Verified.", promoted.len());
            }
        }
    }

    if !exec_success {
        std::process::exit(1);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// REQ-0152: hash_files must produce an identical digest regardless of the
    /// host's path-separator or line-ending conventions, so a dossier anchored
    /// on Windows is not falsely STALE on a Linux/macOS CI checkout.
    #[test]
    fn req_0152_hash_is_platform_independent() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        let file = src.join("x.rs");

        // Same logical file referenced via forward-slash vs backslash path.
        std::fs::write(&file, b"line1\nline2\n").unwrap();
        let base = dir.path().to_string_lossy().replace('\\', "/");
        let fwd = std::path::PathBuf::from(format!("{base}/src/x.rs"));
        let back = std::path::PathBuf::from(format!("{base}/src/x.rs").replace('/', "\\"));
        assert_eq!(
            hash_files(std::slice::from_ref(&fwd)),
            hash_files(std::slice::from_ref(&back)),
            "path separator must not change the digest"
        );

        // Same logical content with CRLF vs LF line endings.
        std::fs::write(&file, b"line1\r\nline2\r\n").unwrap();
        let crlf = hash_files(std::slice::from_ref(&fwd));
        std::fs::write(&file, b"line1\nline2\n").unwrap();
        let lf = hash_files(std::slice::from_ref(&fwd));
        assert_eq!(crlf, lf, "CRLF and LF content must hash identically");
    }

    /// REQ-0149: a markdown heading or list item that cites a requirement id is
    /// NOT a code marker, so it must not make the doc a staleness dependency;
    /// only an HTML comment (`<!-- ... -->`) counts in markdown.
    #[test]
    fn req_0149_markdown_headings_are_not_markers() {
        // markdown: heading citation is not a comment; HTML comment is.
        assert!(comment_portion("### Added — staleness (REQ-0112)", true).is_none());
        assert!(comment_portion("- bullet mentioning REQ-0112", true).is_none());
        assert!(comment_portion("<!-- REQ-0080: changelog marker -->", true).is_some());
        // code files: `#`/`//` lines remain comments (toml/shell/rust).
        assert!(comment_portion("# Implements REQ-0021 (single binary)", false).is_some());
        assert!(comment_portion("// REQ-0001: marker", false).is_some());

        // files_referencing: a heading citation does not link the markdown file,
        // but an HTML-comment marker does. Build the test ids dynamically so the
        // literal tokens never appear in this source (they would otherwise read
        // as coverage ghosts — markers to non-existent requirements).
        let heading_id = format!("REQ-{}", 9001);
        let comment_id = format!("REQ-{}", 9002);
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("CHANGELOG.md"),
            format!("### Added - feature ({heading_id})\n- prose about {heading_id}\n"),
        )
        .unwrap();
        std::fs::write(
            dir.path().join("NOTES.md"),
            format!("<!-- {comment_id}: design note -->\n# {comment_id} heading\n"),
        )
        .unwrap();
        let cl = files_referencing(&heading_id, dir.path());
        assert!(
            cl.is_empty(),
            "a markdown heading citation must not link the doc: {cl:?}"
        );
        let nt = files_referencing(&comment_id, dir.path());
        assert!(
            nt.iter().any(|p| p.to_string_lossy().contains("NOTES.md")),
            "an HTML-comment marker must link the doc: {nt:?}"
        );
    }
}