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
// Tests for REQ-0016 (local read-only web server). Spawns `req serve`,
// hits each route over raw TCP (avoids adding an HTTP client dep), kills
// the child, asserts status codes + response shape.
mod common;
use common::Sandbox;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

const HOST: &str = "127.0.0.1";

/// Pick a free port by binding ephemerally and immediately dropping. Race
/// window is tiny; tests serialise via --test-threads=1 anyway.
fn pick_free_port() -> u16 {
    let listener = std::net::TcpListener::bind(format!("{}:0", HOST)).expect("bind ephemeral");
    listener.local_addr().expect("local_addr").port()
}

fn spawn_server(s: &Sandbox, port: u16) -> Child {
    Command::new(env!("CARGO_BIN_EXE_req"))
        .args([
            "--file",
            s.path().to_str().unwrap(),
            "serve",
            "--host",
            HOST,
            "--port",
            &port.to_string(),
            "--read-only",
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn req serve")
}

fn wait_for_bind(port: u16, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if TcpStream::connect_timeout(
            &format!("{}:{}", HOST, port).parse().unwrap(),
            Duration::from_millis(200),
        )
        .is_ok()
        {
            return true;
        }
        std::thread::sleep(Duration::from_millis(75));
    }
    false
}

/// Minimal HTTP/1.1 GET: returns (status_code, body).
fn http_get(port: u16, path: &str) -> (u16, String) {
    let mut stream = TcpStream::connect(format!("{}:{}", HOST, port)).expect("connect to server");
    stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
    write!(
        stream,
        "GET {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n\r\n",
        path, HOST, port
    )
    .expect("write request");
    let mut buf = String::new();
    stream.read_to_string(&mut buf).ok();
    // Parse the status line and split off the body.
    let mut lines = buf.splitn(2, "\r\n");
    let status_line = lines.next().unwrap_or("");
    let rest = lines.next().unwrap_or("");
    let body = rest
        .split_once("\r\n\r\n")
        .map(|x| x.1)
        .unwrap_or("")
        .to_string();
    // Status line shape: HTTP/1.1 200 OK
    let code = status_line
        .split_whitespace()
        .nth(1)
        .and_then(|s| s.parse::<u16>().ok())
        .unwrap_or(0);
    (code, body)
}

/// Helper that always kills the child even on panic.
struct GuardedChild(Option<Child>);
impl Drop for GuardedChild {
    fn drop(&mut self) {
        if let Some(mut c) = self.0.take() {
            let _ = c.kill();
            let _ = c.wait();
        }
    }
}

fn fixture() -> (Sandbox, GuardedChild, u16) {
    let s = Sandbox::new();
    s.init("p");
    // Stage one known requirement so route /r/REQ-0001 has something to return.
    let _ = s.run(&[
        "add",
        "--title",
        "Hosted on the local web server for inspection",
        "--statement",
        "The system shall render this requirement at GET /r/REQ-0001.",
        "--rationale",
        "Fixture for serve smoke tests.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let port = pick_free_port();
    let child = spawn_server(&s, port);
    let bound = wait_for_bind(port, Duration::from_secs(10));
    assert!(
        bound,
        "req serve did not bind to {}:{} within 10s",
        HOST, port
    );
    (s, GuardedChild(Some(child)), port)
}

// ---------- REQ-0016 ----------

#[test]
fn req_0016_serve_root_returns_html_index() {
    let (_s, _child, port) = fixture();
    let (code, body) = http_get(port, "/");
    assert_eq!(code, 200, "index should return 200, got {}", code);
    assert!(
        body.contains("<html"),
        "body should be HTML: {}",
        &body[..body.len().min(200)]
    );
    assert!(body.contains("REQ-0001"), "index should list REQ-0001");
}

#[test]
fn req_0016_serve_show_route_returns_html_detail() {
    let (_s, _child, port) = fixture();
    let (code, body) = http_get(port, "/r/REQ-0001");
    assert_eq!(code, 200);
    assert!(body.contains("REQ-0001"));
    assert!(body.contains("Hosted on the local web server"));
    assert!(body.contains("Statement") || body.contains("statement"));
}

#[test]
fn req_0016_serve_api_list_returns_json_array() {
    let (_s, _child, port) = fixture();
    let (code, body) = http_get(port, "/api/list");
    assert_eq!(code, 200);
    let v: serde_json::Value = serde_json::from_str(&body)
        .unwrap_or_else(|_| panic!("/api/list should return JSON, got: {}", body));
    let arr = v.as_array().expect("array of requirements");
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["id"].as_str().unwrap(), "REQ-0001");
}

#[test]
fn req_0016_serve_api_show_returns_json_object() {
    let (_s, _child, port) = fixture();
    let (code, body) = http_get(port, "/api/r/REQ-0001");
    assert_eq!(code, 200);
    let v: serde_json::Value = serde_json::from_str(&body).expect("json object");
    assert_eq!(v["id"].as_str().unwrap(), "REQ-0001");
}

#[test]
fn req_0016_serve_unknown_id_returns_404() {
    let (_s, _child, port) = fixture();
    // Construct via format! so the four-digit literal never appears in
    // this source (project-wide coverage scan would otherwise pick it
    // up as a ghost marker).
    let bogus = format!("REQ-{:04}", 9999);
    let url = format!("/api/r/{}", bogus);
    let (code, _body) = http_get(port, &url);
    assert_eq!(code, 404);
}

#[test]
fn req_0016_serve_html_escapes_user_supplied_strings() {
    // Stage a requirement whose title contains characters the HTML
    // renderer must escape; assert they don't appear raw in the body.
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Has <script>tag and \"quotes\" in title",
        "--statement",
        "The system shall escape these characters on render.",
        "--rationale",
        "Fixture for HTML-escape behaviour in serve.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let port = pick_free_port();
    let child = spawn_server(&s, port);
    let _guard = GuardedChild(Some(child));
    assert!(wait_for_bind(port, Duration::from_secs(10)));
    let (code, body) = http_get(port, "/");
    assert_eq!(code, 200);
    assert!(
        !body.contains("<script>tag"),
        "raw < entity leaked through escape: {}",
        &body[..body.len().min(400)]
    );
    assert!(
        body.contains("&lt;script&gt;tag") || body.contains("&lt;script&gt;"),
        "expected &lt; entity in escaped output"
    );
}

// ---------- REQ-0134: functional-safety web view ----------

#[test]
fn req_0134_serve_safety_view_and_api() {
    let s = Sandbox::new();
    s.init("p");
    s.enable_safety();
    let _ = s.run(&[
        "hazard",
        "add",
        "-t",
        "Hazardous mode",
        "--harm",
        "operator could be hurt",
        "-C",
        "C_C",
        "-F",
        "F_B",
        "-P",
        "P_B",
        "-W",
        "W3",
    ]);
    let _ = s.run(&["sf", "add", "-t", "Interlock", "--mitigates", "HAZ-0001"]);
    let port = pick_free_port();
    let child = spawn_server(&s, port);
    assert!(
        wait_for_bind(port, Duration::from_secs(10)),
        "serve did not bind"
    );
    let _guard = GuardedChild(Some(child));

    // The index links to the safety view when hazards exist.
    let (code, body) = http_get(port, "/");
    assert_eq!(code, 200);
    assert!(body.contains("/safety"), "index should link to /safety");

    // The HARA view renders the hazard, its SIL, and the disclaimer.
    let (code, body) = http_get(port, "/safety");
    assert_eq!(code, 200, "/safety should return 200");
    assert!(body.contains("HAZ-0001"), "/safety should list the hazard");
    assert!(body.contains("SIL3"), "/safety should show the derived SIL");
    assert!(
        body.contains("not qualified per IEC 61508-3"),
        "/safety must carry the disclaimer"
    );

    // The JSON API returns the safety artifacts.
    let (code, body) = http_get(port, "/api/safety");
    assert_eq!(code, 200, "/api/safety should return 200");
    assert!(body.contains("\"hazards\""), "api should include hazards");
    assert!(body.contains("HAZ-0001"));
}

// ---------- REQ-0147: web relationship navigation across safety + verification ----------

#[test]
fn req_0147_web_navigates_safety_chain_and_verification() {
    let s = Sandbox::new();
    s.init("p");
    s.enable_safety();
    s.run(&[
        "hazard", "add", "-t", "H", "--harm", "hurt", "-C", "C_C", "-F", "F_B", "-P", "P_B", "-W",
        "W3",
    ]);
    s.run(&["sf", "add", "-t", "Stop fn", "--mitigates", "HAZ-0001"]);
    s.run(&[
        "sreq",
        "add",
        "-t",
        "Stop the blade",
        "-s",
        "The system shall stop the blade on demand.",
        "-r",
        "operator safety",
        "-a",
        "stops",
        "--realizes",
        "SF-0001",
    ]);
    s.run(&[
        "sreq", "update", "SR-0001", "--status", "approved", "--reason", "r",
    ]);
    s.run(&[
        "sreq",
        "update",
        "SR-0001",
        "--status",
        "implemented",
        "--reason",
        "r",
    ]);
    s.run(&[
        "sreq",
        "verify",
        "SR-0001",
        "--by",
        "automated",
        "--notes",
        "bench",
    ]);
    s.run(&["verification", "plan", "SR-0001", "--plan", "p"]);
    s.run(&[
        "verification",
        "analysis",
        "SR-0001",
        "--findings",
        "reviewed",
        "--result",
        "pass",
    ]);
    s.run(&[
        "verification",
        "test",
        "SR-0001",
        "--findings",
        "bench",
        "--result",
        "pass",
    ]);
    s.run(&[
        "verification",
        "conclude",
        "SR-0001",
        "--statement",
        "meets",
        "--promote",
    ]);
    s.run(&["verification", "confirm", "SR-0001"]); // human (REQ_ACTOR_KIND unset in tests)

    let port = pick_free_port();
    let _child = GuardedChild(Some(spawn_server(&s, port)));
    assert!(
        wait_for_bind(port, Duration::from_secs(10)),
        "req serve did not bind"
    );

    // /safety links each hazard into its detail page.
    let (c0, safety) = http_get(port, "/safety");
    assert_eq!(c0, 200);
    assert!(
        safety.contains("/s/HAZ-0001"),
        "safety page must link the hazard to its detail page:\n{safety}"
    );

    // The hazard page renders the full SF → SR chain (both navigable).
    let (c1, haz) = http_get(port, "/s/HAZ-0001");
    assert_eq!(c1, 200);
    assert!(
        haz.contains("/s/SF-0001") && haz.contains("/s/SR-0001"),
        "hazard page must render the SF→SR chain as links:\n{haz}"
    );

    // The safety-function page links back to the hazard and down to the SR.
    let (_c2, sf) = http_get(port, "/s/SF-0001");
    assert!(
        sf.contains("/s/HAZ-0001") && sf.contains("/s/SR-0001"),
        "SF page must link the hazard it mitigates and the SR that realizes it:\n{sf}"
    );

    // The safety-requirement page links to its function AND shows the
    // verification dossier with the human confirmation.
    let (c3, sr) = http_get(port, "/s/SR-0001");
    assert_eq!(c3, 200);
    assert!(
        sr.contains("/s/SF-0001"),
        "SR page must link the safety function it realizes:\n{sr}"
    );
    assert!(
        sr.contains("Verification dossier") && sr.contains("co-signed"),
        "SR page must show the verification dossier with the human co-sign:\n{sr}"
    );
}

// REQ-0205: the browser renders the adequacy walk-through (SF coverage notes +
// hazard adequacy dossier), breadcrumbs, and standing badges.
#[test]
fn req_0205_browser_renders_adequacy_walkthrough_and_badges() {
    let s = Sandbox::new();
    s.init("p");
    s.enable_safety();
    s.run(&[
        "hazard",
        "add",
        "-t",
        "Runaway",
        "--harm",
        "operator crushed",
        "-C",
        "C_A",
        "-F",
        "F_A",
        "-P",
        "P_A",
        "-W",
        "W1",
    ]);
    s.run(&[
        "sf",
        "add",
        "-t",
        "Estop",
        "--safe-state",
        "halted",
        "--mitigates",
        "HAZ-0001",
    ]);
    s.run(&[
        "sreq",
        "add",
        "-t",
        "Halt on demand",
        "-s",
        "The system shall halt all motion within 200 milliseconds of a demand.",
        "-r",
        "runaway injures the operator",
        "-a",
        "halts",
        "--realizes",
        "SF-0001",
    ]);
    // Record the SF→SR adequacy walk-through (cover works on an open dossier).
    s.run(&[
        "verification",
        "plan",
        "SF-0001",
        "--plan",
        "verify the function",
    ]);
    s.run(&[
        "verification",
        "cover",
        "SF-0001",
        "--child",
        "SR-0001",
        "--note",
        "SR-0001 IMPLEMENTS THE HALT",
    ]);
    // Open the hazard adequacy dossier and cover the mitigating SF.
    s.run(&[
        "hazard",
        "adequacy",
        "plan",
        "HAZ-0001",
        "--plan",
        "argue adequacy",
    ]);
    s.run(&[
        "hazard",
        "adequacy",
        "cover",
        "HAZ-0001",
        "--sf",
        "SF-0001",
        "--note",
        "ESTOP COVERS RUNAWAY",
    ]);

    let port = pick_free_port();
    let child = spawn_server(&s, port);
    let _guard = GuardedChild(Some(child));
    assert!(
        wait_for_bind(port, Duration::from_secs(10)),
        "serve did not bind"
    );

    // Landing: standing column + badges + co-sign roll-up scaffolding.
    let (_c, safety) = http_get(port, "/safety");
    assert!(
        safety.contains("Standing") && safety.contains("badge b-"),
        "landing badges:\n{safety}"
    );

    // Hazard page: the staged adequacy dossier with the per-SF coverage note + breadcrumb.
    let (_c, haz) = http_get(port, "/s/HAZ-0001");
    assert!(
        haz.contains("Mitigation adequacy")
            && haz.contains("ESTOP COVERS RUNAWAY")
            && haz.contains("Functional safety"),
        "hazard page must show the adequacy dossier + coverage + breadcrumb:\n{haz}"
    );

    // SF page: the verification dossier with the realizing-SR walk-through note.
    let (_c, sf) = http_get(port, "/s/SF-0001");
    assert!(
        sf.contains("Adequacy walk-through") && sf.contains("SR-0001 IMPLEMENTS THE HALT"),
        "SF page must show the realizing-SR adequacy walk-through:\n{sf}"
    );
}