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
// Tests for Slice B: REQ-0064 (doctor), REQ-0069 (diff), REQ-0070 (test-vs-impl).
mod common;
use common::Sandbox;
use std::fs;
use std::process::Command;

// ---------- REQ-0064: req doctor ----------

fn git(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
    Command::new("git")
        .current_dir(dir)
        .args(args)
        .output()
        .expect("git")
}

fn fresh_git_repo() -> Sandbox {
    let s = Sandbox::new();
    s.init("doctor-test");
    let _ = git(s.dir.path(), &["init", "-q", "-b", "main"]);
    let _ = git(s.dir.path(), &["config", "user.email", "t@example.com"]);
    let _ = git(s.dir.path(), &["config", "user.name", "Tester"]);
    let _ = git(s.dir.path(), &["config", "commit.gpgsign", "false"]);
    s
}

#[test]
fn req_0064_doctor_reports_missing_pre_commit() {
    let s = fresh_git_repo();
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args(["--file", s.path().to_str().unwrap(), "doctor"])
        .output()
        .expect("invoke req");
    assert!(
        !out.status.success(),
        "doctor should fail when nothing is configured"
    );
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains("pre-commit hook"));
    assert!(body.contains("FAIL"));
}

#[test]
fn req_0064_doctor_passes_after_hooks_install() {
    let s = fresh_git_repo();
    let install = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args([
            "--file",
            s.path().to_str().unwrap(),
            "hooks",
            "install",
            "--force",
        ])
        .output()
        .expect("hooks install");
    assert!(
        install.status.success(),
        "hooks install: {}",
        String::from_utf8_lossy(&install.stderr)
    );
    // Activate the merge driver as documented
    let _ = git(
        s.dir.path(),
        &[
            "config",
            "merge.req-merge.driver",
            "req renumber --base %O || true",
        ],
    );
    // Then doctor — only commit-signing should remain failing (test env has none)
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args(["--file", s.path().to_str().unwrap(), "doctor", "--json"])
        .output()
        .expect("invoke req");
    let body = String::from_utf8_lossy(&out.stdout);
    let v: serde_json::Value = serde_json::from_str(&body).expect("doctor --json shape");
    let checks = v["checks"].as_array().expect("checks array");
    let hook = checks
        .iter()
        .find(|c| c["name"] == "pre-commit hook")
        .unwrap();
    assert!(hook["ok"].as_bool().unwrap(), "pre-commit should be OK");
    let pin = checks
        .iter()
        .find(|c| c["name"] == "gitattributes line-ending pin")
        .unwrap();
    assert!(
        pin["ok"].as_bool().unwrap(),
        "gitattributes pin should be OK"
    );
}

// ---------- REQ-0103: doctor surfaces post-commit hook state ----------

#[test]
fn req_0103_doctor_surfaces_post_commit_hook_state() {
    let s = fresh_git_repo();
    let doctor_json = || {
        let out = Command::new(env!("CARGO_BIN_EXE_req"))
            .current_dir(s.dir.path())
            .args(["--file", s.path().to_str().unwrap(), "doctor", "--json"])
            .output()
            .expect("invoke req");
        let v: serde_json::Value =
            serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).expect("doctor --json");
        v
    };
    // Before install: doctor still surfaces a post-commit check, reported missing.
    let before = doctor_json();
    let post = before["checks"]
        .as_array()
        .unwrap()
        .iter()
        .find(|c| c["name"] == "post-commit hook")
        .expect("doctor must surface the post-commit hook state");
    assert!(
        !post["ok"].as_bool().unwrap(),
        "post-commit reported present before install"
    );
    // After install: the post-commit check passes.
    let install = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args([
            "--file",
            s.path().to_str().unwrap(),
            "hooks",
            "install",
            "--force",
        ])
        .output()
        .expect("hooks install");
    assert!(
        install.status.success(),
        "install: {}",
        String::from_utf8_lossy(&install.stderr)
    );
    let after = doctor_json();
    let post2 = after["checks"]
        .as_array()
        .unwrap()
        .iter()
        .find(|c| c["name"] == "post-commit hook")
        .unwrap();
    assert!(
        post2["ok"].as_bool().unwrap(),
        "post-commit should be OK after install"
    );
}

// ---------- REQ-0100: deterministic strict<->default hook swap ----------

#[test]
fn req_0100_no_strict_downgrades_strict_hook() {
    let s = fresh_git_repo();
    let hook_path = s.dir.path().join(".git/hooks/pre-commit");
    let path = s.path();
    let path_s = path.to_str().unwrap();
    let install = |extra: &[&str]| {
        let mut a = vec!["--file", path_s, "hooks", "install", "--force"];
        a.extend_from_slice(extra);
        let out = Command::new(env!("CARGO_BIN_EXE_req"))
            .current_dir(s.dir.path())
            .args(&a)
            .output()
            .expect("install");
        assert!(
            out.status.success(),
            "install {:?}: {}",
            extra,
            String::from_utf8_lossy(&out.stderr)
        );
        fs::read_to_string(&hook_path).unwrap()
    };
    assert!(
        install(&["--strict"]).contains("# mode: strict"),
        "--strict installs strict mode"
    );
    assert!(
        install(&[]).contains("# mode: strict"),
        "bare re-run preserves strict (no accidental downgrade)"
    );
    assert!(
        install(&["--no-strict"]).contains("# mode: default"),
        "--no-strict downgrades deterministically to default"
    );
    assert!(
        install(&["--strict"]).contains("# mode: strict"),
        "--strict upgrades again"
    );
}

// ---------- REQ-0069: req diff ----------

#[test]
fn req_0069_diff_reports_added_and_changed() {
    let s = fresh_git_repo();
    // baseline: add one req, commit
    let add1 = s.run(&[
        "add",
        "--title",
        "Baseline requirement here",
        "--statement",
        "The system shall start with this established baseline.",
        "--rationale",
        "Setup.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    assert!(add1.status.success());
    let _ = git(s.dir.path(), &["add", "project.req"]);
    let _ = git(s.dir.path(), &["commit", "-q", "-m", "baseline"]);

    // head: add a second and update the first
    let add2 = s.run(&[
        "add",
        "--title",
        "Second requirement appears now",
        "--statement",
        "The system shall now also do this additional thing.",
        "--rationale",
        "Added.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    assert!(add2.status.success());
    // Walk the lifecycle naturally — Draft -> Implemented now requires --force.
    for status in ["proposed", "approved", "implemented"] {
        let upd = s.run(&[
            "update",
            "REQ-0001",
            "--status",
            status,
            "--reason",
            "Done in this branch",
        ]);
        assert!(upd.status.success(), "step to {}", status);
    }
    let _ = git(s.dir.path(), &["add", "project.req"]);
    let _ = git(s.dir.path(), &["commit", "-q", "-m", "head"]);

    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args(["--file", s.path().to_str().unwrap(), "diff", "HEAD~1..HEAD"])
        .output()
        .expect("invoke req");
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        body.contains("ADDED"),
        "should report ADDED section: {}",
        body
    );
    assert!(body.contains("REQ-0002"));
    assert!(body.contains("CHANGED"));
    assert!(body.contains("REQ-0001"));
    assert!(body.contains("status:"));
}

#[test]
fn req_0069_diff_empty_when_no_changes() {
    let s = fresh_git_repo();
    s.run(&[
        "add",
        "--title",
        "Single requirement only",
        "--statement",
        "The system shall have just this requirement, nothing more.",
        "--rationale",
        "Setup.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let _ = git(s.dir.path(), &["add", "project.req"]);
    let _ = git(s.dir.path(), &["commit", "-q", "-m", "only"]);
    let _ = git(
        s.dir.path(),
        &["commit", "-q", "--allow-empty", "-m", "empty"],
    );
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args(["--file", s.path().to_str().unwrap(), "diff", "HEAD~1..HEAD"])
        .output()
        .expect("req diff");
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains("no requirement-level changes"));
}

// ---------- REQ-0070: test-vs-impl classification ----------

#[test]
fn req_0070_test_only_marker_is_distinct_from_referenced() {
    use crate::common as common_alias;
    let _ = common_alias::req(&["--help"]);
    // Use the coverage helper directly via the production binary against a
    // sandbox tree that has one impl marker and one test-only marker.
    let s = Sandbox::new();
    s.init("p");
    // Allocate REQ-0001 and REQ-0002 (will be REQ-0001..REQ-0002).
    let _ = s.run(&[
        "add",
        "--title",
        "Impl-only requirement",
        "--statement",
        "The system shall be referenced from src only.",
        "--rationale",
        "Test fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let _ = s.run(&[
        "add",
        "--title",
        "Test-only requirement",
        "--statement",
        "The system shall be referenced from tests only.",
        "--rationale",
        "Test fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    // Create the file tree
    fs::create_dir_all(s.dir.path().join("src")).unwrap();
    fs::create_dir_all(s.dir.path().join("tests")).unwrap();
    fs::write(
        s.dir.path().join("src/lib.rs"),
        "// REQ-0001 implementation site\nfn _foo() {}\n",
    )
    .unwrap();
    fs::write(
        s.dir.path().join("tests/coverage_test.rs"),
        "// REQ-0002 test-only reference\nfn _t() {}\n",
    )
    .unwrap();

    // Run coverage in --json mode and assert classification
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "--file",
            s.path().to_str().unwrap(),
            "coverage",
            "--path",
            s.dir.path().to_str().unwrap(),
            "--json",
        ])
        .output()
        .expect("coverage --json");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("coverage --json shape");
    assert!(
        v["referenced"]
            .as_object()
            .unwrap()
            .contains_key("REQ-0001"),
        "REQ-0001 should be referenced: {}",
        v
    );
    assert!(
        v["test_only"].as_object().unwrap().contains_key("REQ-0002"),
        "REQ-0002 should be test-only: {}",
        v
    );
    assert!(
        !v["referenced"]
            .as_object()
            .unwrap()
            .contains_key("REQ-0002"),
        "REQ-0002 must NOT count as fully-referenced"
    );
}

// ---------- REQ-0159: renumber rewrites safety-artifact links ----------

fn req_in(dir: &std::path::Path, file: &std::path::Path, args: &[&str]) -> std::process::Output {
    let mut full: Vec<String> = vec!["--file".into(), file.to_str().unwrap().into()];
    full.extend(args.iter().map(|s| s.to_string()));
    Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(dir) // so `git show` inside renumber targets this repo
        .args(&full)
        .env_remove("REQ_FILE")
        .output()
        .expect("invoke req")
}

#[test]
fn req_0159_renumber_rewrites_safety_links() {
    let s = fresh_git_repo();
    let dir = s.dir.path();
    let file = s.path();
    common::enable_safety(&file);
    // Build a hazard + a safety function that mitigates it.
    let _ = req_in(
        dir,
        &file,
        &[
            "hazard",
            "add",
            "-t",
            "Base hazard",
            "--harm",
            "a hand is severed",
            "-C",
            "C_C",
            "-F",
            "F_B",
            "-P",
            "P_B",
            "-W",
            "W3",
        ],
    );
    let _ = req_in(
        dir,
        &file,
        &[
            "sf",
            "add",
            "-t",
            "Guard interlock",
            "--mitigates",
            "HAZ-0001",
        ],
    );
    // Commit this as the merge base on `main`.
    let _ = git(dir, &["add", "-A"]);
    let _ = git(dir, &["commit", "-q", "-m", "base"]);
    // Diverge HAZ-0001 so it collides with base's HAZ-0001 (different title).
    let up = req_in(
        dir,
        &file,
        &[
            "hazard",
            "update",
            "HAZ-0001",
            "--title",
            "Diverged hazard",
            "--reason",
            "simulate a merge-time id collision",
        ],
    );
    assert!(
        up.status.success(),
        "hazard update: {}",
        String::from_utf8_lossy(&up.stderr)
    );
    // Renumber against the base.
    let out = req_in(dir, &file, &["renumber", "--base", "main"]);
    assert!(
        out.status.success(),
        "renumber: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        body.contains("HAZ-0001 -> HAZ-0002"),
        "expected HAZ rename, got: {}",
        body
    );
    // The SF's mitigates link must now point at HAZ-0002, not a dangling HAZ-0001.
    let conform = req_in(dir, &file, &["conform"]);
    assert!(
        conform.status.success(),
        "conform after renumber: {}",
        String::from_utf8_lossy(&conform.stdout)
    );
    let trace = req_in(dir, &file, &["trace", "HAZ-0002"]);
    let tbody = String::from_utf8_lossy(&trace.stdout);
    assert!(
        tbody.contains("SF-0001"),
        "trace should link SF-0001 to HAZ-0002, got: {}",
        tbody
    );
}