ignition-cli 1.7.1

ign — operate Ignition 8.3+ gateways from the terminal
Documentation
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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
//! 14-02 THE MCP contract wall (SC-1 / SC-5-MCP): a scripted JSON-RPC
//! client drives the REAL spawned `ign mcp serve` binary end to end.
//!
//! The harness is the byte-scan (research Pattern 5): a reader thread
//! reads stdout line-by-line and MUST parse every line as exactly one
//! JSON-RPC message before forwarding it — a single stray stdout byte
//! (a leaked tracing line, a panic, a partial write) fails the parse
//! and the test. `IGNITION_LOG=trace` plus a noisy unknown-key config
//! keep the diagnostics at maximum so the scan is proven under worst-
//! case noise (the 08 purity-harness recipe: tempdir config + ambient
//! `IGNITION_PROFILE` / `IGNITION_JSON` / `IGNITION_YES` stripped for
//! determinism).
//!
//! Every assertion is assert-based over PARSED values — never snapbox
//! goldens, so `SNAPSHOTS=overwrite` cannot sanitize a protocol
//! regression. `recv_timeout` on the reader channel means a protocol
//! death (dead writer, wedged loop) fails LOUDLY on timeout, never
//! hangs the suite.
//!
//! Request ids ride BOTH shapes the JSON-RPC spec allows — numeric and
//! string — and every test matches responses by id.

use std::cell::RefCell;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::time::{Duration, Instant};

use serde_json::{Value, json};

/// How long a single response may take to arrive. The protocol loop
/// answers initialize/ping/tools/list inline; anything slower is a
/// starvation bug, and the budget converts it into a loud failure.
const RESPONSE_BUDGET_SECS: u64 = 15;

/// The quiet window used to prove a notification produced NO response
/// bytes (JSON-RPC: notifications are never answered).
const QUIET_WINDOW_MS: u64 = 800;

/// Isolated tempdir config (the purity-harness recipe): an unknown
/// top-level key fires `warn_unknown_keys` tracing on every config
/// load — maximum noise for the byte-scan. The file need not exist for
/// protocol-only tests; tools/call tests overwrite it with a real
/// profile.
fn isolated_config() -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    std::fs::write(&path, "bogus_key = 1\n").expect("write noisy config");
    (dir, path)
}

/// One clap argument of a catalog leaf, mirror-walked from the real
/// clap tree (the round-trip smoke needs definition order + the
/// positional/flag/boolean distinctions the bridge uses).
struct LeafArg {
    key: String,
    positional: bool,
    boolean: bool,
}

/// A catalog-eligible clap leaf found by walking the real tree.
struct LeafInfo {
    path: String,
    args: Vec<LeafArg>,
}

/// The scripted MCP client over the REAL binary. The reader thread is
/// THE BYTE-SCAN: one stray stdout byte fails the test.
struct ScriptedClient {
    child: Child,
    stdin: Option<ChildStdin>,
    inbox: Inbox,
    _config_dir: tempfile::TempDir,
}

/// The receive side of the scripted client: every message the byte-scan
/// parsed, read through a plain channel. Kept apart from the spawned
/// process so the receive rules can be driven by a test that feeds the
/// channel directly, in an order it picks.
struct Inbox {
    lines: std::sync::mpsc::Receiver<Value>,
    /// Replies an id-matched wait read while looking for a different id,
    /// oldest first. They are kept for the wait that wants them, never
    /// dropped: the server may answer concurrent calls in any order.
    set_aside: RefCell<VecDeque<Value>>,
}

impl ScriptedClient {
    /// Spawn with the noisy isolated config and the ambient IGNITION_*
    /// knobs stripped (determinism); `extra_env` rides ON TOP (used to
    /// prove IGNITION_YES cannot bypass the confirm gate).
    fn spawn(extra_env: &[(&str, &str)]) -> Self {
        let (dir, config) = isolated_config();
        Self::spawn_with_config(&config, dir, extra_env)
    }

    /// Spawn against a caller-written config file (wiremock-backed
    /// profiles); the tempdir is kept alive for the client's lifetime.
    fn spawn_with_config(
        config: &Path,
        config_dir: tempfile::TempDir,
        extra_env: &[(&str, &str)],
    ) -> Self {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_ign"));
        cmd.args(["mcp", "serve"])
            .env("IGNITION_CLI_CONFIG", config)
            .env("IGNITION_LOG", "trace")
            .env_remove("IGNITION_PROFILE")
            .env_remove("IGNITION_JSON")
            .env_remove("IGNITION_YES")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            // stderr carries the trace noise; the protocol is stdout.
            .stderr(Stdio::null());
        for (key, value) in extra_env {
            cmd.env(key, value);
        }
        let mut child = cmd.spawn().expect("spawn ign mcp serve");
        let stdout = child.stdout.take().expect("piped stdout");
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let mut reader = BufReader::new(stdout);
            let mut line = String::new();
            loop {
                line.clear();
                match reader.read_line(&mut line) {
                    Ok(0) | Err(_) => break, // server exited / stdout closed
                    Ok(_) => {}
                }
                // THE BYTE-SCAN: one stray byte fails this parse. A
                // panic here disconnects the channel and the test
                // fails loudly on its next recv.
                let parsed: Value = match serde_json::from_str(line.trim_end()) {
                    Ok(value) => value,
                    Err(error) => {
                        panic!("stdout carried a non-JSON-RPC byte (line {line:?}): {error}")
                    }
                };
                if tx.send(parsed).is_err() {
                    break; // test is done reading
                }
            }
        });
        Self {
            stdin: child.stdin.take(),
            child,
            inbox: Inbox::new(rx),
            _config_dir: config_dir,
        }
    }

    /// Write one JSON value as exactly one newline-terminated stdin
    /// frame. (Compact serialization — embedded newlines would be
    /// client-side framing bugs.)
    fn send(&mut self, message: &Value) {
        let stdin = self
            .stdin
            .as_mut()
            .expect("server stdin is open (a closed stdin fails every later step)");
        stdin
            .write_all(message.to_string().as_bytes())
            .and_then(|_| stdin.write_all(b"\n"))
            .and_then(|_| stdin.flush())
            .expect("write a protocol frame to the server");
    }

    /// Write one raw (possibly non-JSON) stdin frame — the
    /// malformed-input survival probe.
    fn send_raw_line(&mut self, raw: &str) {
        let stdin = self
            .stdin
            .as_mut()
            .expect("server stdin is open (a closed stdin fails every later step)");
        stdin
            .write_all(raw.as_bytes())
            .and_then(|_| stdin.write_all(b"\n"))
            .and_then(|_| stdin.flush())
            .expect("write a raw frame to the server");
    }

    /// See [`Inbox::recv_next`].
    fn recv_next(&self, secs: u64) -> Value {
        self.inbox.recv_next(secs)
    }

    /// Send a JSON-RPC request with the given id shape (numeric OR
    /// string — the spec allows both and both are exercised).
    fn request(&mut self, id: Value, method: &str, params: Value) {
        self.send(&json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        }));
    }

    /// See [`Inbox::expect_response`].
    fn expect_response(&self, id: &Value, secs: u64) -> Value {
        self.inbox.expect_response(id, secs)
    }

    /// See [`Inbox::expect_silence`].
    fn expect_silence(&self, ms: u64) {
        self.inbox.expect_silence(ms)
    }

    /// The lifecycle opening every protocol test: initialize (numeric
    /// id) + notifications/initialized. Returns the initialize result.
    fn handshake(&mut self) -> Value {
        self.request(
            json!(1),
            "initialize",
            json!({
                "protocolVersion": "2025-06-18",
                "capabilities": {},
                "clientInfo": { "name": "contract-mcp", "version": "0" },
            }),
        );
        let response = self.expect_response(&json!(1), RESPONSE_BUDGET_SECS);
        let result = response.get("result").expect("initialize has a result");
        self.send(&json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }));
        result.clone()
    }

    /// All tool entries from tools/list, after a handshake.
    fn tools(&mut self) -> Vec<Value> {
        self.handshake();
        self.request(json!(2), "tools/list", json!({}));
        let response = self.expect_response(&json!(2), RESPONSE_BUDGET_SECS);
        response
            .pointer("/result/tools")
            .and_then(Value::as_array)
            .expect("tools/list returns tools[]")
            .clone()
    }
}

impl Drop for ScriptedClient {
    fn drop(&mut self) {
        // Close stdin (EOF ends the serve loop), then force-kill any
        // lingering process (a hung in-flight call holds the writer
        // open past the test's patience) and reap the zombie.
        self.stdin.take();
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

impl Inbox {
    fn new(lines: std::sync::mpsc::Receiver<Value>) -> Self {
        Self {
            lines,
            set_aside: RefCell::new(VecDeque::new()),
        }
    }

    /// THE next message with a hard budget — no id matching, no
    /// skipping: the strict-ordering assertions need the FIRST arrival
    /// after a send, unfiltered. Replies an id-matched wait set aside
    /// arrived earlier than anything still in the channel, so they come
    /// out first, oldest first, and arrival order holds.
    fn recv_next(&self, secs: u64) -> Value {
        if let Some(message) = self.set_aside.borrow_mut().pop_front() {
            return message;
        }
        match self.lines.recv_timeout(Duration::from_secs(secs)) {
            Ok(message) => message,
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                panic!("no stdout message arrived within {secs}s — protocol death or starvation")
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => panic!(
                "the reader thread died — stdout closed mid-protocol or the byte-scan \
                 rejected a stray byte (see the panicked thread's message above)"
            ),
        }
    }

    /// THE id-matched receive with a hard budget: waits for the next
    /// response whose id matches, failing LOUDLY on timeout (a wedged
    /// protocol loop must never hang the suite silently). A reply an
    /// earlier wait set aside is claimed first; a reply for another id
    /// read now is set aside for its own wait.
    fn expect_response(&self, id: &Value, secs: u64) -> Value {
        {
            let mut set_aside = self.set_aside.borrow_mut();
            if let Some(index) = set_aside
                .iter()
                .position(|message| message.get("id") == Some(id))
            {
                return set_aside
                    .remove(index)
                    .expect("position() returned an index inside the deque");
            }
        }
        let deadline = Instant::now() + Duration::from_secs(secs);
        loop {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_default();
            match self.lines.recv_timeout(remaining) {
                Ok(message) => {
                    assert_eq!(
                        message.get("jsonrpc").and_then(Value::as_str),
                        Some("2.0"),
                        "every response carries jsonrpc 2.0: {message}"
                    );
                    if message.get("id") == Some(id) {
                        return message;
                    }
                    // A different id's response: legal out-of-order
                    // delivery (JSON-RPC id matching). Keep it for the
                    // wait that wants it, and keep waiting for this one.
                    self.set_aside.borrow_mut().push_back(message);
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!(
                    "no response with id {id} arrived within {secs}s — protocol death or \
                     starvation (see stderr for the server's trace log by rerunning with \
                     stderr inherited)"
                ),
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => panic!(
                    "the reader thread died — stdout closed mid-protocol or the byte-scan \
                     rejected a stray byte (see the panicked thread's message above)"
                ),
            }
        }
    }

    /// THE quiet window: NO stdout message may arrive within `ms`
    /// milliseconds (proves notifications get no response). A set-aside
    /// reply nobody claimed is a message the server sent, so it fails
    /// the window too.
    fn expect_silence(&self, ms: u64) {
        if let Some(message) = self.set_aside.borrow().front() {
            panic!(
                "expected a quiet window ({ms}ms) but a reply the server sent is still \
                 unclaimed: {message}"
            );
        }
        match self.lines.recv_timeout(Duration::from_millis(ms)) {
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} // quiet, as contracted
            Ok(message) => {
                panic!("expected a quiet window ({ms}ms) but the server answered: {message}")
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                panic!("reader thread died during the quiet window")
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Harness receive rules (the inbox fed through a plain channel, no server)
// ---------------------------------------------------------------------------

/// An -32601 reply for `id`, the shape the server sends for an unknown
/// tool.
fn unknown_tool_reply(id: &Value) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": -32601, "message": format!("unknown tool (request {id})") },
    })
}

/// An inbox already holding one reply per id, in the order given. The
/// sender is returned so the caller keeps the channel open: a closed
/// channel fails on the disconnect, not on the reply the inbox lost.
fn inbox_fed(ids: &[Value]) -> (Inbox, std::sync::mpsc::Sender<Value>) {
    let (tx, rx) = std::sync::mpsc::channel();
    for id in ids {
        tx.send(unknown_tool_reply(id)).expect("feed the inbox");
    }
    (Inbox::new(rx), tx)
}

/// The server runs each tools/call as its own task, so two calls sent back
/// to back can be answered in either order, which JSON-RPC allows. This is
/// the order `mcp_tools_call_write_verbs_unknown` hit on CI: 32 lands
/// before 31, and the slow call's 30 comes last. Waiting for 31 must keep
/// 32 for the next wait, and waiting for 32 must keep 30.
#[test]
fn inbox_keeps_an_out_of_order_reply_for_a_later_wait() {
    let (inbox, _tx) = inbox_fed(&[json!(32), json!(31), json!(30)]);
    for id in [json!(31), json!(32), json!(30)] {
        let reply = inbox.expect_response(&id, 1);
        assert_eq!(reply.get("id"), Some(&id), "{reply}");
    }
}

/// `recv_next` returns the replies an id-matched wait set aside before
/// anything that arrived after them, oldest first, so a strict-ordering
/// check still sees arrival order. Both id shapes ride along.
#[test]
fn inbox_recv_next_returns_set_aside_replies_first_in_arrival_order() {
    let (inbox, _tx) = inbox_fed(&[json!("b"), json!(33), json!(31), json!(34)]);
    let _ = inbox.expect_response(&json!(31), 1);
    for expected in [json!("b"), json!(33), json!(34)] {
        let next = inbox.recv_next(1);
        assert_eq!(next.get("id"), Some(&expected), "arrival order: {next}");
    }
}

/// A reply that was set aside and never claimed is still a message the
/// server sent, so a quiet window must not pass while one is waiting.
#[test]
#[should_panic(expected = "quiet window")]
fn inbox_expect_silence_fails_while_a_reply_is_set_aside() {
    let (inbox, _tx) = inbox_fed(&[json!(32), json!(31)]);
    let _ = inbox.expect_response(&json!(31), 1);
    inbox.expect_silence(50);
}

// ---------------------------------------------------------------------------
// Lifecycle contract (SC-1 / SC-5-MCP)
// ---------------------------------------------------------------------------

/// initialize echoes the pinned 2025-06-18 revision EXACTLY, names the
/// server `ign`, and advertises tool capabilities — with BOTH id
/// shapes the spec allows (numeric and string), responses matched by
/// id.
#[test]
fn initialize_echoes_the_pinned_revision_with_both_id_shapes() {
    let mut client = ScriptedClient::spawn(&[]);

    // Numeric id.
    client.request(
        json!(1),
        "initialize",
        json!({
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": { "name": "contract-mcp", "version": "0" },
        }),
    );
    let response = client.expect_response(&json!(1), RESPONSE_BUDGET_SECS);
    let result = response.get("result").expect("initialize answers a result");
    assert_eq!(
        result.get("protocolVersion").and_then(Value::as_str),
        Some("2025-06-18"),
        "the supported revision is echoed exactly"
    );
    assert_eq!(
        result.pointer("/serverInfo/name").and_then(Value::as_str),
        Some("ign"),
        "serverInfo.name is ign"
    );
    assert!(
        result.get("capabilities").map(|c| c.get("tools")).is_some(),
        "capabilities.tools is advertised: {result}"
    );

    // String id (spec-legal; the ping spec example itself uses "123").
    client.request(
        json!("str-id-9"),
        "initialize",
        json!({
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": { "name": "contract-mcp", "version": "0" },
        }),
    );
    let response = client.expect_response(&json!("str-id-9"), RESPONSE_BUDGET_SECS);
    assert_eq!(
        response.get("id"),
        Some(&json!("str-id-9")),
        "string ids ride back verbatim"
    );
    assert!(response.get("result").is_some());
}

/// An OLDER requested revision negotiates to the server's single
/// supported revision (2025-06-18 spec negotiation rule) — the server
/// never echoes an unsupported version.
#[test]
fn initialize_older_version_negotiates_to_the_server_revision() {
    let mut client = ScriptedClient::spawn(&[]);
    client.request(
        json!(3),
        "initialize",
        json!({
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": { "name": "contract-mcp", "version": "0" },
        }),
    );
    let response = client.expect_response(&json!(3), RESPONSE_BUDGET_SECS);
    assert_eq!(
        response
            .pointer("/result/protocolVersion")
            .and_then(Value::as_str),
        Some("2025-06-18"),
        "an older request negotiates to the server's revision"
    );
}

/// `notifications/initialized` is a NOTIFICATION: no response bytes
/// may ever arrive (JSON-RPC notifications are unanswered) — proven by
/// a quiet window on the byte-scanned stream.
#[test]
fn initialized_notification_produces_no_response_bytes() {
    let mut client = ScriptedClient::spawn(&[]);
    client.request(
        json!(1),
        "initialize",
        json!({
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": { "name": "contract-mcp", "version": "0" },
        }),
    );
    let _ = client.expect_response(&json!(1), RESPONSE_BUDGET_SECS);

    client.send(&json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }));
    client.expect_silence(QUIET_WINDOW_MS);
}

/// ping answers `result: {}` PROMPTLY (spec: "MUST respond promptly
/// with an empty response") — inline, not queued behind dispatch.
#[test]
fn ping_answers_promptly_with_an_empty_result() {
    let mut client = ScriptedClient::spawn(&[]);
    client.handshake();
    let start = Instant::now();
    client.request(json!(7), "ping", json!({}));
    let response = client.expect_response(&json!(7), 2);
    assert_eq!(
        response.get("result"),
        Some(&json!({})),
        "ping's result is exactly the empty object"
    );
    assert!(
        start.elapsed() < Duration::from_secs(2),
        "ping answered within the 2s promptness contract (took {:?})",
        start.elapsed()
    );
}

/// tools/list returns a NON-EMPTY catalog where every entry carries
/// name/description/inputSchema — and the catalog spot-pins cannot
/// drift: `project_delete` is guarded (confirm in properties, ABSENT
/// from required — optional confirm, 14-06 round 2), `status` is
/// read-only (no confirm), and the planner-locked exclusions
/// (mcp/lsp/tui/completions/edit) are absent.
#[test]
fn tools_list_carries_the_catalog_with_the_pinned_shape() {
    let mut client = ScriptedClient::spawn(&[]);
    let tools = client.tools();

    assert!(!tools.is_empty(), "the catalog is non-empty");
    let mut names = Vec::new();
    for tool in &tools {
        let name = tool
            .get("name")
            .and_then(Value::as_str)
            .expect("every tool has a string name")
            .to_string();
        assert!(
            tool.get("description")
                .and_then(Value::as_str)
                .is_some_and(|d| !d.is_empty()),
            "every tool carries a non-empty description ({name})"
        );
        let schema = tool.get("inputSchema").expect("every tool has inputSchema");
        assert_eq!(
            schema.get("type").and_then(Value::as_str),
            Some("object"),
            "every inputSchema is an object schema ({name})"
        );
        assert!(
            schema.get("properties").is_some(),
            "every inputSchema has properties ({name})"
        );
        names.push(name);
    }

    fn required_of(tools: &[Value], name: &str) -> Vec<String> {
        tools
            .iter()
            .find(|t| t.get("name").and_then(Value::as_str) == Some(name))
            .map(|t| {
                t.pointer("/inputSchema/required")
                    .and_then(Value::as_array)
                    .expect("required array")
                    .iter()
                    .map(|v| v.as_str().expect("string name").to_string())
                    .collect()
            })
            .unwrap_or_else(|| panic!("tool {name} present in the catalog"))
    }

    // SC-2's catalog half over the wire: the guarded verb advertises
    // confirm as an OPTIONAL boolean — present in properties, ABSENT
    // from required (schema-required would invite agents to auto-fill
    // confirm:true and defeat the gate; 14-06 checkpoint round 2).
    let delete_required = required_of(&tools, "project_delete");
    assert!(
        !delete_required.iter().any(|r| r == "confirm"),
        "confirm must be OPTIONAL on the wire — absent from required: {delete_required:?}"
    );
    let delete_props = tools
        .iter()
        .find(|t| t.get("name").and_then(Value::as_str) == Some("project_delete"))
        .and_then(|t| t.pointer("/inputSchema/properties/confirm"))
        .expect("project_delete carries a confirm property");
    assert_eq!(
        delete_props.get("type").and_then(Value::as_str),
        Some("boolean"),
        "confirm is a boolean property on the wire"
    );
    assert!(
        delete_props
            .get("description")
            .and_then(Value::as_str)
            .is_some_and(|d| d.contains("true")),
        "the confirm description tells the agent what true does: {delete_props}"
    );

    let status = tools
        .iter()
        .find(|t| t.get("name").and_then(Value::as_str) == Some("status"))
        .expect("status present");
    assert!(
        status.pointer("/inputSchema/properties/confirm").is_none(),
        "the read-only status verb carries no confirm property"
    );

    // The planner-locked exclusions are absent as tools.
    for absent in ["mcp", "lsp", "tui", "completions", "edit"] {
        assert!(
            !names.iter().any(|n| n == absent),
            "excluded verb {absent} must not appear in the catalog: {names:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// SC-1 round-trip smoke: catalog names cannot drift from parseable argv
// ---------------------------------------------------------------------------

/// An INDEPENDENT walk of the real clap tree (the mcp.rs builder's
/// leaf rule) that keeps each eligible leaf's path + args in
/// definition order — the data the round-trip smoke needs to rebuild
/// the bridge's argv construction.
fn clap_leaf_map() -> std::collections::BTreeMap<String, LeafInfo> {
    use clap::CommandFactory;
    use ignition_cli::cli::Cli;

    fn walk(
        cmd: &clap::Command,
        prefix: &str,
        out: &mut std::collections::BTreeMap<String, LeafInfo>,
    ) {
        for sub in cmd.get_subcommands() {
            if sub.get_name() == "help" || sub.is_hide_set() {
                continue;
            }
            let path = if prefix.is_empty() {
                sub.get_name().to_string()
            } else {
                format!("{prefix} {}", sub.get_name())
            };
            let excluded = path
                .split(' ')
                .any(|segment| ["completions", "mcp", "lsp", "tui", "edit"].contains(&segment));
            let has_real_children = sub.get_subcommands().any(|c| c.get_name() != "help");
            if (!has_real_children || !sub.is_subcommand_required_set()) && !excluded {
                let mut args = Vec::new();
                for arg in sub.get_arguments() {
                    if arg.is_hide_set() || arg.is_global_set() {
                        continue;
                    }
                    let id = arg.get_id().as_str().to_string();
                    if id == "help" || id == "version" {
                        continue;
                    }
                    let key = if arg.is_positional() {
                        id.clone()
                    } else {
                        arg.get_long().unwrap_or(id.as_str()).to_string()
                    };
                    args.push(LeafArg {
                        key,
                        positional: arg.is_positional(),
                        boolean: matches!(arg.get_action(), clap::ArgAction::SetTrue),
                    });
                }
                out.insert(
                    path.replace(' ', "_"),
                    LeafInfo {
                        path: path.clone(),
                        args,
                    },
                );
            }
            walk(sub, &path, out);
        }
    }

    let mut out = std::collections::BTreeMap::new();
    walk(&Cli::command(), "", &mut out);
    out
}

/// A sample token for one required schema property: the first enum
/// value when the property enumerates, otherwise a plain "x".
fn sample_token(property: &Value) -> String {
    property
        .get("enum")
        .and_then(Value::as_array)
        .and_then(|values| values.first())
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| "x".to_string())
}

/// SC-1 round-trip smoke: for a deterministic sample of catalog tools
/// — EVERY wire-guarded verb (properties carry `confirm`) plus five
/// read verbs — the bridge's argv construction (`["ign"] + leaf path +
/// one token per schema-required arg`, confirm → `--yes`) must PARSE
/// against the real clap tree. Catalog names cannot drift from
/// parseable argv.
#[test]
fn catalog_sample_round_trips_through_clap_parse() {
    let mut client = ScriptedClient::spawn(&[]);
    let tools = client.tools();
    let leaves = clap_leaf_map();

    // The deterministic sample: every guarded-on-the-wire verb
    // (confirm in properties — required never carries it, 14-06 round
    // 2) plus a fixed set of read verbs spanning the family shapes.
    let mut sample: Vec<String> = tools
        .iter()
        .filter(|tool| tool.pointer("/inputSchema/properties/confirm").is_some())
        .filter_map(|tool| tool.get("name").and_then(Value::as_str))
        .map(str::to_string)
        .collect();
    for read in ["version", "status", "modules", "metrics", "profile_list"] {
        sample.push(read.to_string());
    }
    assert!(
        sample.len() >= 23 + 5,
        "the sample must cover all wire-guarded verbs + 5 reads (got {})",
        sample.len()
    );

    for name in &sample {
        let entry = tools
            .iter()
            .find(|tool| tool.get("name").and_then(Value::as_str) == Some(name.as_str()))
            .unwrap_or_else(|| panic!("sampled tool {name} missing from tools/list"));
        let leaf = leaves
            .get(name)
            .unwrap_or_else(|| panic!("tool {name} has no clap leaf — catalog drift"));

        let required: Vec<String> = entry
            .pointer("/inputSchema/required")
            .and_then(Value::as_array)
            .expect("required array")
            .iter()
            .map(|v| v.as_str().expect("string").to_string())
            .collect();
        let properties = entry
            .pointer("/inputSchema/properties")
            .and_then(Value::as_object)
            .expect("properties object");

        // The bridge's argv shape: leaf-path segments in order, then
        // one token per REQUIRED arg (positionals raw, value flags as
        // --long=value with the wire enum's first value, booleans as
        // bare flags), then --yes for the guarded verb's synthetic
        // confirm (the confirm:true execution form).
        let mut argv: Vec<String> = vec!["ign".to_string()];
        argv.extend(leaf.path.split(' ').map(str::to_string));
        for arg in &leaf.args {
            if !required.contains(&arg.key) {
                continue;
            }
            if arg.positional {
                let property = properties.get(&arg.key).unwrap_or(&Value::Null);
                argv.push(sample_token(property));
            } else if arg.boolean {
                argv.push(format!("--{}", arg.key));
            } else {
                let property = properties.get(&arg.key).unwrap_or(&Value::Null);
                argv.push(format!("--{}={}", arg.key, sample_token(property)));
            }
        }
        if properties.contains_key("confirm") {
            argv.push("--yes".to_string());
        }

        use clap::Parser;
        let parsed = ignition_cli::cli::Cli::try_parse_from(&argv);
        assert!(
            parsed.is_ok(),
            "catalog tool {name} (leaf {:?}) does not round-trip to parseable argv \
             {argv:?}: {:?}",
            leaf.path,
            parsed.err().map(|e| e.to_string())
        );
    }
}

// ---------------------------------------------------------------------------
// tools/call contract (SC-2 + frozen-envelope + error mapping + SC-5 pin)
// ---------------------------------------------------------------------------

use assert_cmd::Command as AssertCommand;

/// The live-captured gateway-info fixture (contract_status.rs verbatim).
async fn mount_gateway_info(server: &wiremock::MockServer) {
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/data/api/v1/gateway-info"))
        .respond_with(
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "name": "ign-mock",
                "redundancyRole": "Independent",
                "edition": "standard",
                "ignitionVersion": "8.3.6 (b2026042713)",
                "jvmVersion": "17.0.11",
                "license": {"mode": "Trial", "expirationDate": "2026-08-24T19:00:00Z"}
            })),
        )
        .expect(1..)
        .mount(server)
        .await;
}

/// The live-captured overview fixture (contract_status.rs verbatim —
/// every number pinned, so the status envelope is fixture-stable).
async fn mount_overview(server: &wiremock::MockServer) {
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/data/api/v1/overview"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "version": "8.3.6 (b2026042713)",
            "redundancy": {"role": "Independent", "activityLevel": "ACTIVE", "projectState": "RUNNING"},
            "java": {"version": "17.0.11", "vendor": "Azul Systems, Inc.", "name": "OpenJDK 64-Bit Server VM"},
            "os": {"name": "Linux", "arch": "amd64", "version": "5.15.0"},
            "uptime": 338137,
            "memory": [338137088i64, 1073741824i64],
            "cpu": 0.0031,
            "disk": {"total": 62661259264i64, "used": 12272824320i64},
            "license": {"state": "trial", "trialRemaining": 7017}
        })))
        .expect(1..)
        .mount(server)
        .await;
}

/// The readiness probe fixture.
async fn mount_status_ping(server: &wiremock::MockServer) {
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/StatusPing"))
        .respond_with(
            wiremock::ResponseTemplate::new(200)
                .set_body_json(serde_json::json!({"state": "RUNNING"})),
        )
        .expect(1..)
        .mount(server)
        .await;
}

/// All three endpoints the `status` verb touches — the envelope is
/// fixture-stable, which is what makes byte-equality with a direct run
/// possible.
async fn mount_status_fixtures(server: &wiremock::MockServer) {
    mount_gateway_info(server).await;
    mount_overview(server).await;
    mount_status_ping(server).await;
}

/// A one-profile config pointing at `url` (the contract_status recipe)
/// plus the byte-scan's unknown-key noise. Auth rides IGNITION_TOKEN.
fn write_wiremock_profile_config(config: &Path, url: &str) {
    std::fs::write(
        config,
        format!(
            "bogus_key = 1\nactive = \"dev\"\n\n[profiles.dev]\nurl = \
             \"{url}\"\nauth = {{ token_env = \"IGNITION_TOKEN\" }}\n"
        ),
    )
    .expect("write wiremock profile config");
}

const MOCK_TOKEN: &str = "mock:name-key";

/// THE frozen-envelope verbatim pin (SC-2's wire half): a tools/call
/// over the real binary against a wiremock-backed profile returns the
/// tool-result text that is BYTE-FOR-BYTE the envelope the same
/// invocation prints directly (`ign --json --compact status`) — the
/// protocol path may never reshape an envelope.
#[tokio::test]
async fn tools_call_returns_the_frozen_envelope_verbatim() {
    let server = wiremock::MockServer::start().await;
    mount_status_fixtures(&server).await;

    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    write_wiremock_profile_config(&config, &server.uri());

    let mut client =
        ScriptedClient::spawn_with_config(&config, dir, &[("IGNITION_TOKEN", MOCK_TOKEN)]);
    client.handshake();
    client.request(
        json!(10),
        "tools/call",
        json!({ "name": "status", "arguments": {} }),
    );
    let response = client.expect_response(&json!(10), RESPONSE_BUDGET_SECS);
    let result = response.get("result").expect("tools/call answers a result");
    assert_eq!(
        result.get("isError"),
        Some(&json!(false)),
        "a successful envelope is isError:false: {result}"
    );
    let text = result
        .pointer("/content/0/text")
        .and_then(Value::as_str)
        .expect("the tool result carries text content");
    let envelope: Value = serde_json::from_str(text).expect("the envelope text parses");
    assert_eq!(envelope.get("ok").and_then(Value::as_bool), Some(true));
    assert_eq!(
        envelope.get("profile").and_then(Value::as_str),
        Some("dev"),
        "the envelope echoes the resolved profile"
    );

    // The SAME invocation, run directly: byte-for-byte equality of the
    // two envelope strings (the direct stdout's single trailing
    // println! newline stripped).
    let direct = AssertCommand::cargo_bin("ign")
        .expect("binary 'ign' not found")
        .args(["--json", "--compact", "status"])
        .env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_TOKEN", MOCK_TOKEN)
        .env("IGNITION_LOG", "trace")
        .env_remove("IGNITION_PROFILE")
        .env_remove("IGNITION_JSON")
        .env_remove("IGNITION_YES")
        .output()
        .expect("spawn ign status directly");
    assert!(
        direct.status.success(),
        "direct run must succeed: {}",
        String::from_utf8_lossy(&direct.stderr)
    );
    let direct_stdout = String::from_utf8(direct.stdout).expect("utf-8 stdout");
    assert_eq!(
        text,
        direct_stdout.strip_suffix('\n').unwrap_or(&direct_stdout),
        "MCP tool result must equal the direct CLI envelope byte-for-byte"
    );
}

/// SC-2, refusal half, TRANSPORT-AWARE BOTH WAYS + the IGNITION_YES
/// env-proof (14-06 checkpoint round 2): `tools/call project_delete`
/// with confirm OMITTED returns isError:true with EXACTLY ONE text
/// block — the refusal envelope whose SHAPE is byte-stable (same
/// locked field order, ok:false, code confirmation_required, profile
/// null, endpoint null) but whose message/hint PROSE is MCP-native:
/// the message names `confirm: true`, the hint spells
/// `{"confirm": true}` out and marks `--yes`/`IGNITION_YES` CLI-only.
/// The SAME test file proves the other direction: the direct CLI
/// refusal STILL prints the frozen `--yes` prose — the two envelopes
/// are shape-twins differing in exactly those two prose fields — and
/// `IGNITION_YES=1` exported into the spawned server's environment
/// changes nothing (the apply_env_defaults bypass is behavioral,
/// pinned here over the real binary).
#[tokio::test]
async fn confirm_omitted_refuses_with_mcp_native_prose_and_cli_prose_survives_directly() {
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    std::fs::write(&config, "bogus_key = 1\n").expect("write noisy config");
    let mut client = ScriptedClient::spawn_with_config(&config, dir, &[("IGNITION_YES", "1")]);
    client.handshake();
    client.request(
        json!(11),
        "tools/call",
        json!({ "name": "project_delete", "arguments": { "name": "x" } }),
    );
    let response = client.expect_response(&json!(11), RESPONSE_BUDGET_SECS);
    let result = response.get("result").expect("tools/call answers a result");
    assert_eq!(
        result.get("isError"),
        Some(&json!(true)),
        "the refusal rides isError:true (IGNITION_YES=1 could not confirm it): {result}"
    );
    let content = result
        .get("content")
        .and_then(Value::as_array)
        .expect("the refusal carries content blocks");
    assert_eq!(
        content.len(),
        1,
        "the refusal is ONE self-sufficient block (the JSON itself is MCP-native): {content:?}"
    );

    let envelope_text = content[0]
        .get("text")
        .and_then(Value::as_str)
        .expect("the single block is text content");
    let envelope: Value = serde_json::from_str(envelope_text)
        .expect("the refusal text parses as the frozen envelope");
    assert_eq!(envelope.get("ok").and_then(Value::as_bool), Some(false));
    assert_eq!(
        envelope.pointer("/error/code").and_then(Value::as_str),
        Some("confirmation_required"),
        "the stable slug is unchanged: {envelope}"
    );
    assert!(
        envelope.get("profile").is_some_and(Value::is_null),
        "profile echoes null on the pre-network refusal"
    );
    assert!(
        envelope
            .pointer("/error/endpoint")
            .is_some_and(Value::is_null),
        "endpoint is null (zero requests)"
    );

    // The MCP-native prose lives INSIDE the JSON — an agent that
    // parses only the envelope gets advice that works on its own
    // transport.
    let message = envelope
        .pointer("/error/message")
        .and_then(Value::as_str)
        .expect("message present");
    assert!(
        message.contains("confirm: true"),
        "the message names the MCP-native confirmation: {message}"
    );
    let hint = envelope
        .pointer("/error/hint")
        .and_then(Value::as_str)
        .expect("hint present");
    assert!(
        hint.contains("confirm"),
        "the hint names the confirm argument: {hint}"
    );
    assert!(
        hint.contains("CLI-only"),
        "the hint marks --yes/IGNITION_YES CLI-only: {hint}"
    );
    assert!(
        hint.contains("IGNITION_YES"),
        "the hint names the env var as CLI-only: {hint}"
    );

    // Byte-stable shape: the serialization rides the LOCKED field
    // order (ok, profile, error{code, message, ...}) — the bytes start
    // exactly where the frozen envelope starts.
    let stable_prefix = r#"{"ok":false,"profile":null,"error":{"code":"confirmation_required","#;
    assert!(
        envelope_text.starts_with(stable_prefix),
        "the MCP refusal must serialize in the LOCKED field order: {envelope_text}"
    );

    // THE BOTH-WAYS TRANSPORT PROOF: the direct CLI refusal of the
    // same invocation STILL prints the frozen `--yes` prose (the CLI
    // contract is untouched) and carries none of the MCP-native
    // wording. The refusal is pre-network (zero requests), so no
    // auth/profile is needed. The direct stderr may carry tracing
    // diagnostics ahead of it — the envelope is the FINAL line.
    let direct = AssertCommand::cargo_bin("ign")
        .expect("binary 'ign' not found")
        .args(["--json", "--compact", "project", "delete", "x"])
        .env("IGNITION_CLI_CONFIG", &config)
        .env_remove("IGNITION_PROFILE")
        .env_remove("IGNITION_JSON")
        .env_remove("IGNITION_YES")
        .output()
        .expect("spawn ign project delete directly");
    assert!(
        !direct.status.success(),
        "the direct refusal must fail (usage-class exit)"
    );
    let direct_stderr = String::from_utf8(direct.stderr).expect("utf-8 stderr");
    let direct_envelope_text = direct_stderr.lines().last().unwrap_or_default();
    let direct_envelope: Value = serde_json::from_str(direct_envelope_text)
        .expect("the direct CLI prints a parseable refusal envelope");
    let direct_message = direct_envelope
        .pointer("/error/message")
        .and_then(Value::as_str)
        .expect("direct message present");
    assert!(
        direct_message.contains("--yes"),
        "the CLI golden prose names --yes, unchanged: {direct_message}"
    );
    assert!(
        !direct_message.contains("confirm: true"),
        "the CLI prose must NOT carry MCP wording: {direct_message}"
    );
    let direct_hint = direct_envelope
        .pointer("/error/hint")
        .and_then(Value::as_str)
        .expect("direct hint present");
    assert!(
        direct_hint.contains("IGNITION_YES"),
        "the CLI hint still names the env confirmation: {direct_hint}"
    );

    // Shape-twins: restoring the CLI's two prose strings into the MCP
    // envelope makes the payloads EQUAL — only message/hint adapt to
    // the transport (parsed comparison is key-order-insensitive; the
    // byte-prefix pin above covers order).
    let mut repaired = envelope.clone();
    repaired["error"]["message"] = direct_envelope["error"]["message"].clone();
    repaired["error"]["hint"] = direct_envelope["error"]["hint"].clone();
    assert_eq!(
        repaired, direct_envelope,
        "only message/hint prose may differ between the transports"
    );
}

/// SC-2, execution half: `confirm:true` is the ONLY way `--yes` is
/// reachable — the guarded verb executes against the gateway (the
/// wiremock records the DELETE carrying the server's own confirm=true
/// query param) and returns the success envelope.
#[tokio::test]
async fn confirm_true_executes_the_guarded_verb_on_the_wire() {
    let server = wiremock::MockServer::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path("/data/api/v1/projects/x"))
        .and(wiremock::matchers::query_param("confirm", "true"))
        .respond_with(wiremock::ResponseTemplate::new(200))
        .expect(1..)
        .mount_as_scoped(&server)
        .await;

    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    write_wiremock_profile_config(&config, &server.uri());

    let mut client =
        ScriptedClient::spawn_with_config(&config, dir, &[("IGNITION_TOKEN", MOCK_TOKEN)]);
    client.handshake();
    client.request(
        json!(12),
        "tools/call",
        json!({ "name": "project_delete", "arguments": { "name": "x", "confirm": true } }),
    );
    let response = client.expect_response(&json!(12), RESPONSE_BUDGET_SECS);
    let result = response.get("result").expect("tools/call answers a result");
    assert_eq!(
        result.get("isError"),
        Some(&json!(false)),
        "confirm:true executes: {result}"
    );
    let text = result
        .pointer("/content/0/text")
        .and_then(Value::as_str)
        .expect("text content");
    let envelope: Value = serde_json::from_str(text).expect("envelope parses");
    assert_eq!(envelope.get("ok").and_then(Value::as_bool), Some(true));
    assert_eq!(
        envelope.pointer("/data/deleted").and_then(Value::as_str),
        Some("x"),
        "the frozen success envelope rides verbatim: {envelope}"
    );

    // The wire proof: exactly one DELETE, carrying confirm=true.
    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1, "one DELETE per invocation");
    let query = requests[0].url.query().expect("query present");
    assert!(
        query.contains("confirm=true"),
        "the server's own guard rode the wire: {query}"
    );
}

/// Error mapping + survival: unknown tool → -32601; invalid params
/// (missing required arg, hostile unknown key) → -32602; a malformed
/// (non-JSON) stdin line produces NO stdout bytes and the server keeps
/// serving — a subsequent ping answers promptly.
#[tokio::test]
async fn protocol_errors_map_correctly_and_survive_malformed_input() {
    let mut client = ScriptedClient::spawn(&[]);
    client.handshake();

    // Unknown tool → -32601.
    client.request(
        json!(20),
        "tools/call",
        json!({ "name": "no_such_tool", "arguments": {} }),
    );
    let response = client.expect_response(&json!(20), RESPONSE_BUDGET_SECS);
    assert_eq!(
        response.pointer("/error/code").and_then(Value::as_i64),
        Some(-32601),
        "unknown tool is a protocol-level method error: {response}"
    );
    assert!(
        response
            .pointer("/error/message")
            .and_then(Value::as_str)
            .is_some_and(|m| m.contains("no_such_tool")),
        "the error names the offending tool"
    );

    // Missing required argument → -32602 (clap parse failure is NEVER
    // e.exit() — the process must survive the protocol).
    client.request(
        json!(21),
        "tools/call",
        json!({ "name": "tags_read", "arguments": {} }),
    );
    let response = client.expect_response(&json!(21), RESPONSE_BUDGET_SECS);
    assert_eq!(
        response.pointer("/error/code").and_then(Value::as_i64),
        Some(-32602),
        "invalid params map to -32602: {response}"
    );

    // THE SC-2 wire probe: a hostile `yes` property (not in any tool
    // schema — globals are excluded) refuses -32602 and can never
    // reach --yes.
    client.request(
        json!(22),
        "tools/call",
        json!({ "name": "status", "arguments": { "yes": true } }),
    );
    let response = client.expect_response(&json!(22), RESPONSE_BUDGET_SECS);
    assert_eq!(
        response.pointer("/error/code").and_then(Value::as_i64),
        Some(-32602),
        "the hostile-yes probe refuses as invalid params: {response}"
    );
    assert!(
        response
            .pointer("/error/message")
            .and_then(Value::as_str)
            .is_some_and(|m| m.contains("yes")),
        "the refusal names the offending key"
    );

    // A malformed stdin line: NO recoverable id → the server stays
    // QUIET (warns on stderr only), keeps serving, and answers the
    // next ping promptly.
    client.send_raw_line("this is not json at all");
    client.expect_silence(QUIET_WINDOW_MS);
    let start = Instant::now();
    client.request(json!(23), "ping", json!({}));
    let response = client.expect_response(&json!(23), 2);
    assert_eq!(
        response.get("result"),
        Some(&json!({})),
        "the protocol survived the malformed input"
    );
    assert!(
        start.elapsed() < Duration::from_secs(2),
        "post-malformed ping still prompt: {:?}",
        start.elapsed()
    );
}

/// Edge DSURF-02 concurrency (23-14, T-23-58): a `tools/call` naming
/// `deploy_apply` or `deploy_rollback` is answered as an unknown tool and
/// runs nothing, whatever else the server is doing. The fake gateway answers
/// every request slowly, so a `status` call is in flight while the two write
/// calls arrive; both are answered at once with -32601 naming the tool, and
/// the gateway never sees a lock, scan, backup or restart request.
#[tokio::test]
async fn mcp_tools_call_write_verbs_unknown() {
    let server = wiremock::MockServer::start().await;
    wiremock::Mock::given(wiremock::matchers::any())
        .respond_with(
            wiremock::ResponseTemplate::new(200)
                .set_body_json(json!({}))
                .set_delay(Duration::from_secs(3)),
        )
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    write_wiremock_profile_config(&config, &server.uri());
    let mut client =
        ScriptedClient::spawn_with_config(&config, dir, &[("IGNITION_TOKEN", MOCK_TOKEN)]);
    let tools = client.tools();
    for name in ["deploy_apply", "deploy_rollback"] {
        assert!(
            !tools.iter().any(|t| t["name"] == name),
            "{name} is not in the catalog"
        );
    }

    // A slow call is in flight.
    client.request(
        json!(30),
        "tools/call",
        json!({ "name": "status", "arguments": {} }),
    );
    let started = Instant::now();
    let calls = [
        (
            31,
            "deploy_apply",
            json!({ "env": "dev", "plan-sha256": "0".repeat(64), "confirm": true }),
        ),
        (
            32,
            "deploy_rollback",
            json!({ "env": "dev", "run": "20261016T000000Z-aaaaaa", "confirm": true }),
        ),
    ];
    for (id, name, arguments) in &calls {
        client.request(
            json!(id),
            "tools/call",
            json!({ "name": name, "arguments": arguments }),
        );
    }
    for (id, name, _) in &calls {
        let response = client.expect_response(&json!(id), RESPONSE_BUDGET_SECS);
        assert_eq!(
            response.pointer("/error/code").and_then(Value::as_i64),
            Some(-32601),
            "{name} is an unknown tool: {response}"
        );
        assert!(
            response
                .pointer("/error/message")
                .and_then(Value::as_str)
                .is_some_and(|m| m.contains(*name)),
            "the error names {name}: {response}"
        );
        assert!(response.get("result").is_none(), "{name} ran nothing");
    }
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "the refusals did not wait behind the slow call: {:?}",
        started.elapsed()
    );

    // Let the slow call finish, so every request it makes is recorded.
    let _ = client.expect_response(&json!(30), RESPONSE_BUDGET_SECS);
    let paths: Vec<String> = server
        .received_requests()
        .await
        .unwrap_or_default()
        .iter()
        .map(|r| r.url.path().to_string())
        .collect();
    assert!(
        !paths.is_empty(),
        "the in-flight status call reached the gateway, so the check below looks at something"
    );
    for forbidden in ["scan", "lock", "backup", "restart", "webdev", "resource"] {
        assert!(
            !paths.iter().any(|p| p.contains(forbidden)),
            "the gateway saw {forbidden}: {paths:?}"
        );
    }
}

/// SC-5, THE PERMANENT STARVATION PIN: with an in-flight tools/call
/// hung on a dead gateway (a bound-but-never-accepting listener — the
/// TCP connect SUCCEEDS into the kernel backlog, so the reqwest client
/// is stuck waiting for a response that never comes until its own
/// 30s timeout), the ping response must arrive FIRST. Starvation is
/// structurally impossible: tools/call runs off the reader loop and
/// ping answers inline.
#[tokio::test]
async fn ping_never_starves_behind_an_in_flight_dead_gateway_call() {
    // The dead gateway: bound, never accepted. Held alive to the end
    // of the test — dropping it would RST the connection and could
    // error the call early.
    let dead_gateway = std::net::TcpListener::bind("127.0.0.1:0").expect("bind dead gateway");
    let dead_url = format!(
        "http://127.0.0.1:{}/",
        dead_gateway.local_addr().unwrap().port()
    );

    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    write_wiremock_profile_config(&config, &dead_url);

    let mut client =
        ScriptedClient::spawn_with_config(&config, dir, &[("IGNITION_TOKEN", MOCK_TOKEN)]);
    client.handshake();

    // The call first (its gateway check hangs ≥ the client's own
    // 30s timeout), then IMMEDIATELY the ping.
    client.request(
        json!(30),
        "tools/call",
        json!({ "name": "version", "arguments": {} }),
    );
    client.request(json!(31), "ping", json!({}));

    // ORDERING: the FIRST message after the sends must be the ping.
    let first = client.recv_next(10);
    assert_eq!(
        first.get("id"),
        Some(&json!(31)),
        "ping must answer BEFORE the hung tool result: {first}"
    );
    assert_eq!(first.get("result"), Some(&json!({})), "ping's empty result");

    // Then the tool result lands (after the client's own gateway
    // timeout) — completing the ordering fact and proving the server
    // neither wedged nor dropped the call.
    let second = client.recv_next(75);
    assert_eq!(
        second.get("id"),
        Some(&json!(30)),
        "the in-flight call's result still arrives: {second}"
    );
    assert!(
        second.get("result").is_some() || second.get("error").is_some(),
        "the dead-gateway call resolves into a well-formed response: {second}"
    );
}

// ---------------------------------------------------------------------------
// Python mcp-SDK conformance oracle (optional gate, green-skips without uv)
// ---------------------------------------------------------------------------

/// The oracle's optional gate (the 10-USER-SETUP live-gate green-skip
/// genre): a REAL mcp-SDK Python client drives the full lifecycle over
/// the spawned binary against a wiremock-backed profile. Run
/// explicitly — NEVER a Cargo dependency on Python:
///
/// ```text
/// cargo test -p ignition-cli --test contract_mcp mcp_oracle -- --ignored
/// ```
///
/// Without `uv` on PATH this gate green-skips (prints the reason and
/// passes); with uv it runs `uv run --with mcp` — the mcp SDK is
/// fetched test-time only.
#[tokio::test]
#[ignore = "conformance oracle: needs uv + the mcp SDK — run with `cargo test -p \
            ignition-cli --test contract_mcp mcp_oracle -- --ignored`"]
async fn mcp_oracle_gate_drives_a_real_mcp_sdk_client() {
    let probe = Command::new("uv").arg("--version").output();
    let probe = match probe {
        Ok(output) if output.status.success() => output,
        _ => {
            eprintln!("green-skip: uv not available — the mcp SDK oracle gate is skipped");
            return;
        }
    };
    let _ = probe;

    let server = wiremock::MockServer::start().await;
    mount_status_fixtures(&server).await;

    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    write_wiremock_profile_config(&config, &server.uri());

    let oracle = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/mcp_oracle.py");
    let output = Command::new("uv")
        .args([
            "run",
            "--with",
            "mcp",
            "python",
            oracle.to_string_lossy().as_ref(),
            "--",
            env!("CARGO_BIN_EXE_ign"),
        ])
        .env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_TOKEN", MOCK_TOKEN)
        .output()
        .expect("run the oracle under uv");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "the mcp SDK oracle failed\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(
        stdout.contains("ORACLE OK"),
        "the oracle did not report success: {stdout}"
    );
}