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
981
982
983
984
985
986
987
988
989
// Exercises individual MCP tools end-to-end via the JSON-RPC stdio
// transport. Each test drives `req mcp` with a sequence of messages,
// asserts the response shape, and (where the tool mutates) verifies
// the mutation persisted via the CLI.
mod common;
use common::{stdout, Sandbox};
use std::io::Write;
use std::process::{Command, Stdio};

/// Send a sequence of newline-delimited JSON-RPC messages to a fresh
/// `req mcp` subprocess and collect the (parsed) responses in order.
/// Notifications without an `id` produce no response.
fn mcp_dialogue(s: &Sandbox, messages: &[serde_json::Value]) -> Vec<serde_json::Value> {
    let mut child = Command::new(env!("CARGO_BIN_EXE_req"))
        .args(["--file", s.path().to_str().unwrap(), "mcp"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn req mcp");
    {
        let stdin = child.stdin.as_mut().expect("stdin");
        for m in messages {
            writeln!(stdin, "{}", m).expect("write");
        }
    }
    let out = child.wait_with_output().expect("wait");
    let body = String::from_utf8_lossy(&out.stdout);
    body.lines()
        .filter(|l| !l.trim().is_empty())
        .map(|l| {
            serde_json::from_str(l).unwrap_or_else(|_| panic!("non-JSON response line: {}", l))
        })
        .collect()
}

fn initialize() -> serde_json::Value {
    serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize"})
}

fn call_tool(id: i32, name: &str, args: serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": "tools/call",
        "params": { "name": name, "arguments": args }
    })
}

fn text_of(response: &serde_json::Value) -> String {
    response["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or("")
        .to_string()
}

// ---------- REQ-0083: TUI parity guard ----------

/// CLI commands that don't need a TUI menu entry. Same exclusion set
/// as MCP plus a couple that are awkward in an interactive menu:
/// `check` and `renumber` need a git ref typed in (still doable, but
/// the menu would be a thin wrapper), and `migrate`/`schema`/`batch`/
/// `import` are file-driven operations users typically run from the
/// shell.
const HUMANS_ONLY_TUI: &[&str] = &[
    "init",
    "tui",
    "serve",
    "mcp",
    "hooks",
    "renumber",
    // REQ-0207: `req merge` is a git merge driver invoked by git (not by a
    // human menu), exactly like `renumber`.
    "merge",
    "repair",
    "migrate",
    "schema",
    "batch",
    "import",
    "test",
    "verify",
    "check",
    "help",
    "setup",
    "precheck",
    "purpose",
    "adopt",
    // REQ-0138: `req safety` (disclaimer acceptance + calibration) is a
    // deliberate governance action driven from the shell, not the menu.
    "safety",
    // REQ-0139: `req verification` is a multi-step, free-text dossier flow
    // (plan/analysis/test/conclude) driven from the CLI/MCP, like `verify`
    // and `test` above — not a single-shot human menu action.
    "verification",
    // REQ-0156: `req impact` is a read-only safety-graph preview whose
    // arguments mirror the human-only calibration/link decisions it informs;
    // it lives with the `req safety` governance surface, not the menu.
    "impact",
];

#[test]
fn req_0083_tui_menu_covers_every_agent_relevant_cli_command() {
    // Source-level introspection: parse the MENU const out of src/tui.rs.
    let src = std::fs::read_to_string("src/tui.rs").expect("read tui.rs");
    let start = src.find("pub const MENU").expect("MENU const present");
    // Find the `=` that opens the literal, then the next `[` after that.
    let eq = src[start..].find('=').expect("= after MENU") + start;
    let open_rel = src[eq..].find('[').expect("[ after =");
    let open = eq + open_rel;
    let close = src[open..].find(']').expect("] after [") + open;
    let body = &src[open + 1..close];
    let menu_labels: Vec<String> = body
        .split(',')
        .map(|s| s.trim().trim_matches('"').trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    // Re-derive the CLI command set.
    let help = common::req(&["--help"]);
    let help_body = stdout(&help);
    let mut cli: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    let mut in_commands = false;
    for line in help_body.lines() {
        let trimmed = line.trim_start();
        if trimmed == "Commands:" {
            in_commands = true;
            continue;
        }
        if !in_commands {
            continue;
        }
        if trimmed.is_empty()
            || trimmed.starts_with("Options:")
            || trimmed.starts_with("Arguments:")
        {
            in_commands = false;
            continue;
        }
        let leading = line.chars().take_while(|c| *c == ' ').count();
        if leading != 2 {
            continue;
        }
        if let Some(first) = trimmed.split_whitespace().next() {
            if first.chars().all(|c| c.is_ascii_lowercase() || c == '-') {
                cli.insert(first.to_string());
            }
        }
    }
    for excl in HUMANS_ONLY_TUI {
        cli.remove(*excl);
    }

    // For each remaining CLI command, find a menu entry that mentions it
    // (parens-form like "Browse (list + show)" or substring match).
    let menu_lc: Vec<String> = menu_labels.iter().map(|s| s.to_lowercase()).collect();
    let missing: Vec<&String> = cli
        .iter()
        .filter(|cmd| {
            let needle = cmd.to_lowercase();
            !menu_lc.iter().any(|label| label.contains(&needle))
        })
        .collect();
    assert!(
        missing.is_empty(),
        "REQ-0083 — CLI commands without a TUI menu entry (and not in HUMANS_ONLY_TUI): {:?}\n\
         Menu items:\n  {:?}\n\
         Add a menu line to src/tui.rs::MENU or list the command in HUMANS_ONLY_TUI \
         in tests/mcp_tools.rs with a one-line justification.",
        missing,
        menu_labels
    );
}

// ---------- REQ-0083: MCP/CLI parity guard ----------

/// CLI subcommands that DELIBERATELY do not have an MCP tool. Adding a
/// command here is an opt-out; the test below ensures every other CLI
/// command appears as a req_* MCP tool. See REQ-0083.
const HUMANS_ONLY_CLI: &[&str] = &[
    "init", "tui", "serve", "mcp", "hooks", "renumber", "repair", "setup", "precheck", "purpose",
    "adopt",
    // REQ-0207: `req merge` is a git merge driver invoked by git during a
    // merge, not an agent tool — opted out like `renumber`.
    "merge",
    // REQ-0138: accepting the liability disclaimer and recalibrating risk
    // are deliberate human governance actions — `req safety` is kept off
    // the agent/MCP surface on purpose.
    "safety",
    // REQ-0156: `req impact` is a read-only safety-graph preview tied to the
    // human-reviewed calibration/link decisions; kept with the human-only
    // safety surface rather than exposed as an agent tool.
    "impact",
];

#[test]
fn req_0083_mcp_tool_surface_covers_every_agent_relevant_cli_command() {
    let help = common::req(&["--help"]);
    let body = stdout(&help);
    // Parse only the `Commands:` section of --help. clap formats it as a
    // header line "Commands:" followed by indented subcommand rows until
    // the next blank line or an "Options:" section.
    let mut in_commands = false;
    let mut cli: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for line in body.lines() {
        let trimmed = line.trim_start();
        if trimmed == "Commands:" {
            in_commands = true;
            continue;
        }
        if !in_commands {
            continue;
        }
        if trimmed.is_empty()
            || trimmed.starts_with("Options:")
            || trimmed.starts_with("Arguments:")
        {
            in_commands = false;
            continue;
        }
        // Only top-level subcommand lines have exactly 2 leading spaces;
        // continuation lines (wrapped descriptions) are indented further.
        let leading = line.chars().take_while(|c| *c == ' ').count();
        if leading != 2 {
            continue;
        }
        if let Some(first) = trimmed.split_whitespace().next() {
            if first.chars().all(|c| c.is_ascii_lowercase() || c == '-') {
                cli.insert(first.to_string());
            }
        }
    }
    for excl in HUMANS_ONLY_CLI {
        cli.remove(*excl);
    }
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}),
        ],
    );
    let tools = responses[1]["result"]["tools"]
        .as_array()
        .expect("tools/list returns array");
    let mcp_names: std::collections::BTreeSet<String> = tools
        .iter()
        .filter_map(|t| {
            t["name"]
                .as_str()
                .map(|n| n.trim_start_matches("req_").to_string())
        })
        .collect();
    let mcp_root_names: std::collections::BTreeSet<String> = mcp_names
        .iter()
        .map(|n| n.split('_').next().unwrap_or(n).to_string())
        .collect();
    let missing: Vec<&String> = cli
        .iter()
        .filter(|c| !mcp_root_names.contains(*c) && !mcp_names.contains(*c))
        .collect();
    assert!(
        missing.is_empty(),
        "REQ-0083 — CLI subcommands without an MCP tool (and not in HUMANS_ONLY_CLI): {:?}\n\
         Either expose it as a req_* tool in src/mcp.rs or add it to HUMANS_ONLY_CLI.",
        missing
    );
}

// ---------- REQ-0017: tool surface ----------

#[test]
fn req_0017_mcp_req_list_returns_count() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "First listed via MCP",
        "--statement",
        "The system shall be returned by the req_list tool.",
        "--rationale",
        "MCP list fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_list", serde_json::json!({})),
        ],
    );
    let list_text = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&list_text).expect("inner json");
    assert_eq!(v["count"], 1);
    assert_eq!(v["requirements"][0]["id"].as_str().unwrap(), "REQ-0001");
}

#[test]
fn req_0017_mcp_req_show_returns_full_requirement() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Shown by the req_show MCP tool",
        "--statement",
        "The system shall be returned in full by req_show.",
        "--rationale",
        "MCP show fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_show", serde_json::json!({"id": "REQ-0001"})),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("requirement json");
    assert_eq!(v["id"].as_str().unwrap(), "REQ-0001");
    assert!(v["statement"].as_str().unwrap().contains("req_show"));
}

#[test]
fn req_0017_mcp_req_add_persists_through_storage() {
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_add",
                serde_json::json!({
                    "title": "Added through the MCP req_add tool",
                    "statement": "The system shall persist an MCP-driven add via storage::save.",
                    "rationale": "Verify the MCP write path uses the same storage layer as the CLI.",
                    "kind": "constraint", "priority": "could"
                }),
            ),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("add json");
    assert_eq!(v["id"].as_str().unwrap(), "REQ-0001");
    // Now the CLI must see it too — round-trip through storage.
    let list = stdout(&s.run(&["list", "--json"]));
    assert!(list.contains("REQ-0001"));
}

#[test]
fn req_0017_mcp_req_add_verification_failure_returns_iserror() {
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_add",
                serde_json::json!({
                    "title": "Bad",  // too short
                    "statement": "too short",
                    "rationale": "x",
                    "kind": "constraint", "priority": "could"
                }),
            ),
        ],
    );
    let r = &responses[1]["result"];
    assert_eq!(
        r["isError"], true,
        "conformance failure should set isError=true: {}",
        r
    );
    let msg = r["content"][0]["text"].as_str().unwrap();
    assert!(
        msg.contains("rejected"),
        "error message should name the rejection: {}",
        msg
    );
}

#[test]
fn req_0017_mcp_req_update_records_reason_in_history() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Subject of an MCP update",
        "--statement",
        "The system shall accept an MCP-driven update with a reason.",
        "--rationale",
        "Fixture for req_update MCP tool.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let _ = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_update",
                serde_json::json!({
                    "id": "REQ-0001",
                    "reason": "Updated via the MCP tool for test purposes",
                    "add_tag": ["mcp-touched"]
                }),
            ),
        ],
    );
    let show = stdout(&s.run(&["show", "REQ-0001"]));
    assert!(show.contains("mcp-touched"));
    assert!(show.contains("Updated via the MCP tool"));
}

#[test]
fn req_0017_mcp_req_link_creates_typed_edge() {
    let s = Sandbox::new();
    s.init("p");
    for i in 1..=2 {
        let _ = s.run(&[
            "add",
            "--title",
            &format!("Node {} for MCP linking", i),
            "--statement",
            "The system shall be linkable through the MCP req_link tool.",
            "--rationale",
            "Fixture.",
            "--kind",
            "constraint",
            "--priority",
            "could",
        ]);
    }
    let _ = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_link",
                serde_json::json!({
                    "from": "REQ-0001", "to": "REQ-0002", "link_kind": "parent"
                }),
            ),
        ],
    );
    let show = stdout(&s.run(&["show", "REQ-0001"]));
    assert!(
        show.contains("parent -> REQ-0002"),
        "link should be persisted, got:\n{}",
        show
    );
}

#[test]
fn req_0017_mcp_req_delete_soft_marks_obsolete() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Retired via the MCP req_delete tool",
        "--statement",
        "The system shall be soft-deleted by the MCP tool.",
        "--rationale",
        "Fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let _ = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_delete",
                serde_json::json!({
                    "id": "REQ-0001", "reason": "Retired via MCP tool"
                }),
            ),
        ],
    );
    let show = stdout(&s.run(&["show", "REQ-0001"]));
    assert!(show.to_lowercase().contains("obsolete"));
}

// ---------- REQ-0129: req_test_list MCP tool ----------

// The agent-facing read of a requirement's test-record history, mirroring
// the CLI `req test list`. Closes the MCP/CLI parity gap where records
// could be written (req_test_record / req_test_run) but not read back.
#[test]
fn req_0129_mcp_test_list_returns_recorded_history() {
    let s = Sandbox::new();
    s.init("p");
    let dir = s.dir.path();
    for a in [
        vec!["init", "-q", "-b", "main"],
        vec!["config", "user.email", "t@e.com"],
        vec!["config", "user.name", "T"],
        vec!["config", "commit.gpgsign", "false"],
        vec!["add", "project.req"],
        vec!["commit", "-q", "-m", "init"],
    ] {
        let _ = Command::new("git").current_dir(dir).args(&a).output();
    }
    let _ = s.run(&[
        "add",
        "--title",
        "Carries a test record read back over MCP",
        "--statement",
        "The system shall expose its test-record history through req_test_list.",
        "--rationale",
        "REQ-0129 MCP read-path fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let rec = Command::new(env!("CARGO_BIN_EXE_req"))
        .current_dir(dir)
        .args([
            "--file",
            s.path().to_str().unwrap(),
            "test",
            "record",
            "REQ-0001",
            "--result",
            "pass",
            "--notes",
            "smoke run for the MCP read path",
        ])
        .output()
        .expect("test record");
    assert!(
        rec.status.success(),
        "test record stderr: {}",
        String::from_utf8_lossy(&rec.stderr)
    );

    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_test_list", serde_json::json!({"id": "REQ-0001"})),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("records json");
    let arr = v.as_array().expect("records array");
    assert_eq!(arr.len(), 1, "one record expected, got {:?}", arr);
    assert_eq!(arr[0]["outcome"], "Pass");
}

#[test]
fn req_0129_mcp_test_list_empty_history_is_empty_array() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Never tested via the MCP read path",
        "--statement",
        "The system shall report an empty history when no record exists.",
        "--rationale",
        "REQ-0129 empty-history fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            // padded/short id form must resolve too.
            call_tool(2, "req_test_list", serde_json::json!({"id": "1"})),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("records json");
    assert_eq!(v.as_array().expect("array").len(), 0);
}

#[test]
fn req_0017_mcp_req_validate_emits_finding_counts() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Valid baseline requirement here",
        "--statement",
        "The system shall conform cleanly under the MCP tool.",
        "--rationale",
        "Fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_conform", serde_json::json!({})),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("conform json");
    assert_eq!(v["errors"], 0);
    assert!(v["warnings"].is_number());
}

#[test]
fn req_0017_mcp_req_help_index_lists_section_names() {
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_help", serde_json::json!({"section": "_index"})),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("help index json");
    let sections: Vec<&str> = v["sections"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|s| s["name"].as_str())
        .collect();
    for expected in ["agents", "best-practice", "errors", "verification"] {
        assert!(
            sections.contains(&expected),
            "{} missing from index",
            expected
        );
    }
}

#[test]
fn req_0017_mcp_req_help_named_section_returns_body() {
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_help", serde_json::json!({"section": "agents"})),
        ],
    );
    let body = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&body).expect("section json");
    assert_eq!(v["name"], "agents");
    assert!(v["body"].as_str().unwrap().len() > 100);
}

#[test]
fn req_0017_mcp_req_export_renders_markdown() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Exported via MCP req_export",
        "--statement",
        "The system shall be rendered to markdown by the MCP tool.",
        "--rationale",
        "Fixture for the export tool.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_export", serde_json::json!({"format": "markdown"})),
        ],
    );
    let body = text_of(&responses[1]);
    assert!(body.contains("REQ-0001"));
    assert!(body.contains("Exported via MCP"));
    assert!(body.contains("##") || body.contains("**Statement"));
}

#[test]
fn req_0017_mcp_self_link_rejected_with_iserror() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "--title",
        "Cannot self-link via MCP",
        "--statement",
        "The system shall reject self-links from the MCP tool.",
        "--rationale",
        "Fixture.",
        "--kind",
        "constraint",
        "--priority",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_link",
                serde_json::json!({
                    "from": "REQ-0001", "to": "REQ-0001", "link_kind": "parent"
                }),
            ),
        ],
    );
    let r = &responses[1]["result"];
    assert_eq!(r["isError"], true);
}

#[test]
fn req_0017_mcp_ping_returns_empty_object() {
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            serde_json::json!({"jsonrpc":"2.0","id":2,"method":"ping"}),
        ],
    );
    assert_eq!(responses[1]["result"], serde_json::json!({}));
}

#[test]
fn req_import_missing_source_returns_clean_envelope() {
    // Regression: req_import shelled out to `req import` and stuffed
    // the subprocess's whole stderr into the error string — including
    // anyhow's multi-line Display chain after the JSON envelope. The
    // returned text was no longer parseable as JSON. The fix prefers
    // the first `{...}`-shaped line of stderr so agents that
    // JSON.parse() the error don't choke on trailing chain text.
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_import",
                serde_json::json!({
                    "format": "markdown",
                    "source": "DOES_NOT_EXIST_REGRESSION.md"
                }),
            ),
        ],
    );
    let r = &responses[1]["result"];
    assert_eq!(r["isError"], true, "missing source should set isError");
    let text = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(text.trim()).unwrap_or_else(|e| {
        panic!(
            "req_import error text should be a single JSON envelope, got parse error {} on:\n{}",
            e, text
        )
    });
    assert_eq!(v["code"], "REQ-E-IO", "envelope code should be REQ-E-IO");
    assert!(
        v["message"].is_string(),
        "envelope should carry a message field: {}",
        v
    );
}

#[test]
fn mcp_validate_reports_link_cycles() {
    // REQ-V-0021 is graph-level; MCP req_conform must surface it too.
    let s = Sandbox::new();
    s.init("p");
    // Build two reqs and inject a depends-on cycle directly (the
    // direct CLI rejects it; we need a way to test the conformance checker's
    // detection independent of the prevention).
    for (i, title) in [
        "MCP cycle fixture requirement number one",
        "MCP cycle fixture requirement number two",
    ]
    .iter()
    .enumerate()
    {
        let _ = s.run(&[
            "add",
            "--title",
            title,
            "--statement",
            &format!("The system shall expose MCP cycle detection {}.", i + 1),
            "--rationale",
            "MCP cycle fixture.",
            "--kind",
            "constraint",
            "--priority",
            "could",
        ]);
    }
    let _ = s.run(&["link", "REQ-0001", "REQ-0002", "-k", "depends-on"]);
    let text = std::fs::read_to_string(s.path()).unwrap();
    let mut v: serde_json::Value = serde_json::from_str(&text).unwrap();
    v["requirements"]["REQ-0002"]["links"] =
        serde_json::json!([{"kind":"DependsOn","target":"REQ-0001"}]);
    std::fs::write(s.path(), serde_json::to_string_pretty(&v).unwrap()).unwrap();
    let _ = s.run(&["repair", "--confirm-direct-edit", "--force"]);

    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_conform", serde_json::json!({})),
        ],
    );
    let text = text_of(&responses[1]);
    assert!(
        text.contains("REQ-V-0021"),
        "MCP req_conform should surface REQ-V-0021: {}",
        text
    );
}

// Reference initialize_then's underscored argument so clippy stays quiet.
#[allow(dead_code)]
fn _silence_unused() {
    let _ = initialize;
}

// ---------- REQ-0163/0164/0165: agent-surface improvements ----------

#[test]
fn req_0163_mcp_list_paginates_with_total() {
    let s = Sandbox::new();
    s.init("p");
    for i in 0..4 {
        let title = format!("Seed requirement number {}", i);
        let stmt = format!("The system shall handle case number {}.", i);
        let _ = s.run(&[
            "add",
            "-t",
            &title,
            "-s",
            &stmt,
            "-r",
            "seed",
            "-k",
            "constraint",
            "-p",
            "could",
        ]);
    }
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(2, "req_list", serde_json::json!({ "limit": 2 })),
        ],
    );
    let text = text_of(&responses[1]);
    let v: serde_json::Value = serde_json::from_str(&text).expect("list json");
    assert_eq!(v["total"], 4, "total should be the full match count");
    assert_eq!(v["count"], 2, "page capped at limit");
    assert_eq!(v["requirements"].as_array().unwrap().len(), 2);
}

#[test]
fn req_0164_mcp_rejection_carries_rule_code() {
    let s = Sandbox::new();
    s.init("p");
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_add",
                serde_json::json!({
                    "title": "Statement without a modal verb",
                    "statement": "the system simply does several assorted things",
                    "rationale": "provoke a verification error",
                    "kind": "constraint", "priority": "could"
                }),
            ),
        ],
    );
    let r = &responses[1]["result"];
    assert_eq!(r["isError"], true, "rejection should set isError: {}", r);
    let code = r["code"].as_str().unwrap_or("");
    assert!(
        code.starts_with("REQ-V-"),
        "discrete code field expected, got: {}",
        r
    );
    assert!(
        r["codes"]
            .as_array()
            .map(|a| !a.is_empty())
            .unwrap_or(false),
        "codes array expected: {}",
        r
    );
}

#[test]
fn req_0165_mcp_blocked_promotion_lists_routes() {
    let s = Sandbox::new();
    s.init("p");
    let _ = s.run(&[
        "add",
        "-t",
        "Requirement awaiting evidence",
        "-s",
        "The system shall do the thing.",
        "-r",
        "seed",
        "-k",
        "constraint",
        "-p",
        "could",
    ]);
    let responses = mcp_dialogue(
        &s,
        &[
            initialize(),
            call_tool(
                2,
                "req_verify",
                serde_json::json!({
                    "id": "REQ-0001", "by": "inspection", "notes": "looked at it",
                    "promote": true, "force": true
                }),
            ),
        ],
    );
    let r = &responses[1]["result"];
    assert_eq!(
        r["isError"], true,
        "blocked promotion should set isError: {}",
        r
    );
    let routes = r["routes"].as_array().expect("routes array");
    assert_eq!(routes.len(), 3, "three legal routes expected: {}", r);
    let joined = routes
        .iter()
        .filter_map(|x| x.as_str())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        joined.contains("dossier"),
        "routes name the dossier flow: {}",
        joined
    );
    assert!(
        joined.contains("no-dossier"),
        "routes name the waiver: {}",
        joined
    );
    assert!(
        joined.contains("exempt"),
        "routes name the exempt tag: {}",
        joined
    );
}