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
// Tests for the final round: REQ-0075 (directory storage), REQ-0076
// (duplicate-intent detection), REQ-0077 (verifies-without-evidence),
// REQ-0078 (schema), REQ-0079 (audit gate), REQ-0080 (CHANGELOG).
mod common;
use common::Sandbox;
use std::fs;
use std::process::Command;

// ---------- REQ-0075: directory-backed storage ----------

#[test]
fn req_0075_init_directory_layout_writes_index_and_requirements_dir() {
    let s = Sandbox::new();
    let dir = s.dir.path().join("proj");
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "init",
            "-n",
            "dir-proj",
            "-o",
            dir.to_str().unwrap(),
            "--layout",
            "directory",
        ])
        .output()
        .expect("init");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(dir.join("index.req").exists());
    assert!(dir.join("requirements").is_dir());
}

#[test]
fn req_0075_add_persists_one_file_per_requirement() {
    let s = Sandbox::new();
    let dir = s.dir.path().join("proj");
    Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "init",
            "-n",
            "dir-proj",
            "-o",
            dir.to_str().unwrap(),
            "--layout",
            "directory",
        ])
        .output()
        .expect("init");
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "--file",
            dir.to_str().unwrap(),
            "add",
            "--title",
            "Persisted under the directory layout here",
            "--statement",
            "The system shall write this requirement to its own file under requirements/.",
            "--rationale",
            "Test fixture.",
            "--kind",
            "constraint",
            "--priority",
            "could",
        ])
        .output()
        .expect("add");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        dir.join("requirements/REQ-0001.req").exists(),
        "REQ-0001.req should exist under requirements/"
    );
}

#[test]
fn req_0075_integrity_detects_per_file_tamper() {
    let s = Sandbox::new();
    let dir = s.dir.path().join("proj");
    Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "init",
            "-n",
            "dir-proj",
            "-o",
            dir.to_str().unwrap(),
            "--layout",
            "directory",
        ])
        .output()
        .expect("init");
    Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "--file",
            dir.to_str().unwrap(),
            "add",
            "--title",
            "Will be tampered with in this test",
            "--statement",
            "The system shall persist this so we can mutate the file.",
            "--rationale",
            "Test.",
            "--kind",
            "constraint",
            "--priority",
            "could",
        ])
        .output()
        .expect("add");
    // Tamper the per-requirement file.
    let req_path = dir.join("requirements/REQ-0001.req");
    let text = fs::read_to_string(&req_path).unwrap();
    fs::write(&req_path, text.replace("\"Could\"", "\"Should\"")).unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_req"))
        .args(["--file", dir.to_str().unwrap(), "list"])
        .output()
        .expect("list");
    assert!(
        !out.status.success(),
        "list should refuse after per-file tamper"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("integrity check failed"));
}

// ---------- REQ-0076: duplicate-intent detection ----------

#[test]
fn req_0076_near_clone_triggers_dup_intent_warning() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Persist user sessions across restarts forever",
        "--statement",
        "The system shall persist user sessions across process restarts.",
        "--rationale",
        "Users lose work today.",
        "--kind",
        "functional",
        "--priority",
        "should",
        "--accept",
        "Session survives restart in fixture",
    ]);
    // Near-clone: same intent, very similar wording
    let _ = s.run(&[
        "add",
        "--title",
        "Persist user sessions across process restarts",
        "--statement",
        "The system shall persist user sessions across process restarts always.",
        "--rationale",
        "Same intent, different words.",
        "--kind",
        "functional",
        "--priority",
        "should",
        "--accept",
        "Session survives restart in fixture as well",
    ]);
    let out = s.run(&["conform"]);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        text.contains("REQ-V-0020"),
        "expected duplicate-intent warning, got:\n{}",
        text
    );
}

// ---------- REQ-0077: verifies link without evidence ----------

#[test]
fn req_0077_verifies_link_without_test_record_warns() {
    let s = Sandbox::new();
    s.init("p");
    // Two reqs, neither has any test record
    for i in 1..=2 {
        s.run(&[
            "add",
            "--title",
            &format!("Subject of the verification {}", i),
            "--statement",
            "The system shall have this perfectly fine baseline behaviour.",
            "--rationale",
            "Setup.",
            "--kind",
            "constraint",
            "--priority",
            "could",
        ]);
    }
    // REQ-0002 verifies REQ-0001 but has no test record.
    // REQ-0093: REQ-V-0019 only fires when the source is Implemented
    // or later. Walk REQ-0002 there first so the rule has something
    // to flag.
    s.run(&["link", "REQ-0002", "REQ-0001", "-k", "verifies"]);
    for status in ["proposed", "approved", "implemented"] {
        s.run(&[
            "update",
            "REQ-0002",
            "--status",
            status,
            "--reason",
            "test setup",
        ]);
    }
    let out = s.run(&["conform"]);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        text.contains("REQ-V-0019"),
        "expected verifies-without-evidence warning, got:\n{}",
        text
    );
}

// ---------- REQ-0078: req schema ----------

#[test]
fn req_0078_schema_add_is_valid_json_with_format() {
    let out = common::req(&["schema", "add"]);
    assert!(out.status.success());
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("schema add is JSON");
    assert_eq!(
        v["$schema"].as_str().unwrap(),
        "https://json-schema.org/draft/2020-12/schema"
    );
    assert!(
        v["$id"]
            .as_str()
            .unwrap()
            .starts_with("urn:req-cli:schema:"),
        "schema $id should be a stable urn:, got: {}",
        v["$id"]
    );
    assert!(v["properties"]["title"].is_object());
    assert!(v["properties"]["statement"].is_object());
    assert_eq!(v["_format"].as_str().unwrap(), "req-v4");
}

// REQ-0127: --by-req is the inverse of --by-file.
#[test]
fn req_0127_coverage_by_req_groups_files_under_each_req() {
    let s = Sandbox::new();
    s.init("p");
    std::fs::create_dir_all(s.dir.path().join("src")).unwrap();
    std::fs::write(
        s.dir.path().join("src/a.rs"),
        "// REQ-0001: first\nfn a() {}\n",
    )
    .unwrap();
    std::fs::write(
        s.dir.path().join("src/b.rs"),
        "// REQ-0001: also here\nfn b() {}\n",
    )
    .unwrap();
    std::fs::write(
        s.dir.path().join("src/c.rs"),
        "// REQ-0002: somewhere else\nfn c() {}\n",
    )
    .unwrap();
    let out = s.run(&[
        "coverage",
        "--by-req",
        "--path",
        s.dir.path().to_str().unwrap(),
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(&common::stdout(&out)).expect("JSON");
    let r1 = v["REQ-0001"].as_array().expect("REQ-0001 array");
    assert_eq!(
        r1.len(),
        2,
        "REQ-0001 should reference two files; got {:?}",
        r1
    );
    let r2 = v["REQ-0002"].as_array().expect("REQ-0002 array");
    assert_eq!(
        r2.len(),
        1,
        "REQ-0002 should reference one file; got {:?}",
        r2
    );
}

// REQ-0121: coverage surfaces both `orphans` (strict-gated) and
// `drafts_unmarked` (informational) so adopters see the full picture
// of which requirements lack source markers.
#[test]
fn req_0121_coverage_reports_drafts_unmarked_separately() {
    let s = Sandbox::new();
    s.init("p");
    // One Draft (default status), no marker → should land in drafts_unmarked.
    s.run(&[
        "add",
        "--title",
        "Draft with no marker yet",
        "--statement",
        "The system shall implement this once we get to it.",
        "--rationale",
        "Fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    // One Implemented, no marker → should land in orphans.
    s.run(&[
        "add",
        "--title",
        "Implemented but missing marker",
        "--statement",
        "The system shall carry this real obligation right now.",
        "--rationale",
        "Fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let _ = s.run(&[
        "update",
        "REQ-0002",
        "--status",
        "implemented",
        "--reason",
        "fixture: forced past Draft to test orphans bucket",
        "--force",
    ]);
    let out = s.run(&[
        "coverage",
        "--path",
        s.dir.path().to_str().unwrap(),
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(&common::stdout(&out)).expect("JSON");
    let orphans = v["orphans"].as_array().expect("orphans array");
    let drafts = v["drafts_unmarked"]
        .as_array()
        .expect("drafts_unmarked array");
    assert!(
        orphans.iter().any(|x| x == "REQ-0002"),
        "REQ-0002 (Implemented, no marker) should be an orphan; got: {:?}",
        orphans
    );
    assert!(
        drafts.iter().any(|x| x == "REQ-0001"),
        "REQ-0001 (Draft, no marker) should be in drafts_unmarked; got: {:?}",
        drafts
    );
}

// REQ-0120: installed AGENTS.md must not carry literal cli_req REQ-IDs.
#[test]
fn req_0120_installed_agents_uses_placeholder_req_ids() {
    let s = Sandbox::new();
    s.init("p");
    let agents = s.dir.path().join("AGENTS.md");
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(s.dir.path())
        .args(["help", "agents", "--install"])
        .output()
        .expect("install agents");
    assert!(
        out.status.success(),
        "install: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let body = std::fs::read_to_string(&agents).expect("read AGENTS.md");
    let re = regex::Regex::new(r"REQ-\d{4}").unwrap();
    let leaked: Vec<&str> = re.find_iter(&body).map(|m| m.as_str()).collect();
    assert!(
        leaked.is_empty(),
        "installed AGENTS.md must not carry literal REQ-NNNN; found: {:?}",
        leaked
    );
    assert!(
        body.contains("REQ-NNNN"),
        "expected placeholder REQ-NNNN to appear in the installed text"
    );
}

// REQ-0119: import schema must agree with the conformance checker on what's required.
#[test]
fn req_0119_import_schema_requires_rationale() {
    let out = common::req(&["schema", "import"]);
    assert!(out.status.success());
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("schema import is JSON");
    let required = v["items"]["required"]
        .as_array()
        .expect("items.required is an array");
    let required_strs: Vec<&str> = required.iter().filter_map(|x| x.as_str()).collect();
    assert!(
        required_strs.contains(&"rationale"),
        "import schema must list rationale as required (the conformance checker does); got: {:?}",
        required_strs
    );
}

#[test]
fn req_0078_schema_batch_describes_oneof_mutations() {
    let out = common::req(&["schema", "batch"]);
    assert!(out.status.success());
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("schema batch is JSON");
    let mutations = &v["properties"]["mutations"]["items"]["oneOf"];
    assert!(
        mutations.is_array(),
        "batch schema should describe mutation alternatives"
    );
    assert_eq!(mutations.as_array().unwrap().len(), 4);
}

// ---------- REQ-0079: audit gate ----------

#[test]
fn req_0079_audit_gate_exits_nonzero_without_signing() {
    // Build a temp git repo, commit something touching project.req
    let s = Sandbox::new();
    s.init("p");
    let dir = s.dir.path();
    let _ = std::process::Command::new("git")
        .current_dir(dir)
        .args(["init", "-q", "-b", "main"])
        .output();
    let _ = std::process::Command::new("git")
        .current_dir(dir)
        .args(["config", "user.email", "t@example.com"])
        .output();
    let _ = std::process::Command::new("git")
        .current_dir(dir)
        .args(["config", "user.name", "T"])
        .output();
    let _ = std::process::Command::new("git")
        .current_dir(dir)
        .args(["add", "project.req"])
        .output();
    // Explicit `commit.gpgsign=false` here: the developer's global git
    // config may have `commit.gpgsign=true` (with SSH/GPG signing wired
    // up), which would silently sign this fixture commit and defeat the
    // "unsigned commit should violate gate" assertion. Pin the commit
    // to unsigned so the test reflects what it claims to test.
    let _ = std::process::Command::new("git")
        .current_dir(dir)
        .args(["-c", "commit.gpgsign=false", "commit", "-q", "-m", "init"])
        .output();
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(dir)
        .args([
            "--file",
            s.path().to_str().unwrap(),
            "audit",
            "--gate",
            "--require-good-signature",
        ])
        .output()
        .expect("audit gate");
    assert!(!out.status.success(), "unsigned commit should violate gate");
}

// ---------- REQ-0080: CHANGELOG.md ----------

#[test]
fn req_0080_changelog_exists_with_unreleased_section() {
    let text = fs::read_to_string("CHANGELOG.md").expect("CHANGELOG.md present");
    assert!(text.contains("# Changelog"));
    assert!(text.contains("[Unreleased]"));
    assert!(text.to_lowercase().contains("keep a changelog"));
}