ridl-cli 0.6.0

The `ridl` command-line toolchain: check, baseline, build, test, fmt, diff, lock, lsp, mcp, and describe, over the shared compiler crates.
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
//! `ridl lsp` and `ridl mcp`: the two stdio servers the one binary hosts.
//!
//! Every test here spawns the built `ridl` binary and speaks a real protocol
//! to it over pipes. `crates/ridl-lsp/tests/` drives the language server
//! through an in-memory connection instead, which cannot show that the
//! subcommand wires the stdio transport at all.

use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdout, Command as StdCommand, ExitStatus, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use lsp_server::{Message, Notification, Request, RequestId, Response};
use rmcp::RoleClient;
use rmcp::ServiceExt as _;
use rmcp::model::{CallToolRequestParams, CallToolResult};
use rmcp::service::RunningService;
use rmcp::transport::TokioChildProcess;
use serde_json::json;
use tokio::process::Command;

/// How long a spawned server is given to answer or to exit. Generous, because
/// a loaded CI machine is slow; bounded, because `cargo test` has no per-test
/// timeout and a hung server would otherwise hang the whole run.
const TIMEOUT: Duration = Duration::from_secs(20);

/// One broken typl source, used by every diagnostic assertion below.
///
/// Deliberately no trailing newline: with one, the parser reports the missing
/// backing type at the position past it — line 3, column 1 — rather than at
/// the end of the `type X:` line. Measured against the built binary:
/// `FORM-101`, "expected a backing type", line 2 column 8, no fix-its.
const BROKEN_TYPL: &str = "package p\ntype X:";

/// One typl source yielding three diagnostics of three kinds, used by one of
/// the CLI/MCP agreement tests only.
///
/// Measured against the built binary: `FORM-101` (error, line 4, the
/// missing backing type — again with no trailing newline, for the reason
/// given on [`BROKEN_TYPL`]), `TYPL-103` (warning, line 2, `string` without
/// bounds) and `TYPL-104` (error, line 3, minimum above maximum), reported in
/// that order — the parse error first, then the semantic pass by line. Three
/// entries of two severities, not in line order, so a tool that truncated or
/// reordered its diagnostics would no longer agree with the CLI.
const THREE_KINDS_TYPL: &str = "package p\ntype Tag : string\ntype Bad : integer [10..5]\ntype X:";

// ---------------------------------------------------------------------------
// `ridl mcp`
// ---------------------------------------------------------------------------

/// Runs `ridl mcp` as a child, performs the MCP handshake, and returns the
/// client. The child is killed when the returned service is cancelled or
/// dropped.
async fn connect() -> RunningService<RoleClient, ()> {
    let mut command = Command::new(env!("CARGO_BIN_EXE_ridl"));
    command.arg("mcp");
    let transport = TokioChildProcess::new(command).expect("spawn ridl mcp");
    ().serve(transport).await.expect("MCP initialize handshake")
}

/// The concatenated text of a tool result's text content blocks.
fn tool_text(result: &CallToolResult) -> String {
    result
        .content
        .iter()
        .filter_map(|content| content.as_text())
        .map(|text| text.text.clone())
        .collect()
}

/// Calls `ridl_check` over `source` under `profile` and returns the parsed
/// JSON the tool's text block carries.
async fn call_ridl_check(
    client: &RunningService<RoleClient, ()>,
    source: &str,
    profile: &str,
) -> serde_json::Value {
    let arguments = json!({ "source": source, "profile": profile })
        .as_object()
        .cloned()
        .expect("the arguments are a JSON object");
    let result = client
        .call_tool(CallToolRequestParams::new("ridl_check").with_arguments(arguments))
        .await
        .expect("tools/call");
    assert_ne!(result.is_error, Some(true), "{result:?}");
    let text = tool_text(&result);
    serde_json::from_str(&text).unwrap_or_else(|err| panic!("the tool returns JSON: {err}: {text}"))
}

#[tokio::test]
async fn ridl_mcp_advertises_ridl_check() {
    tokio::time::timeout(TIMEOUT, async {
        let client = connect().await;
        let tools = client
            .list_tools(Default::default())
            .await
            .expect("tools/list");
        let mut names: Vec<&str> = tools.tools.iter().map(|tool| tool.name.as_ref()).collect();
        names.sort();
        assert_eq!(
            names,
            [
                "ridl_check",
                "ridl_dependencies",
                "ridl_describe_type",
                "ridl_diff",
                "ridl_explain",
                "ridl_list_interactions",
                "ridl_metrics",
                "ridl_references",
                "ridl_resolve"
            ]
        );
        client.cancel().await.expect("shutdown");
    })
    .await
    .expect("ridl_mcp_advertises_ridl_check did not finish within the timeout");
}

#[tokio::test]
async fn ridl_check_returns_the_diagnostic_contract() {
    tokio::time::timeout(TIMEOUT, async {
        let client = connect().await;
        let output = call_ridl_check(&client, BROKEN_TYPL, "typl").await;
        client.cancel().await.expect("shutdown");

        // TYPL-406 (`missing-docs`) is left out: the fixture has no docs.
        let diagnostics: Vec<&serde_json::Value> = output["diagnostics"]
            .as_array()
            .unwrap_or_else(|| panic!("a diagnostics array: {output}"))
            .iter()
            .filter(|diagnostic| diagnostic["code"] != "TYPL-406")
            .collect();
        assert_eq!(diagnostics.len(), 1, "{output}");
        let diagnostic = diagnostics[0];
        assert_eq!(diagnostic["code"], "FORM-101", "{output}");
        assert_eq!(diagnostic["severity"], "error", "{output}");
        assert_eq!(diagnostic["span"]["path"], "input.typl", "{output}");
        assert_eq!(diagnostic["span"]["start"]["line"], 2, "{output}");
        assert_eq!(diagnostic["span"]["start"]["column"], 8, "{output}");
        assert!(diagnostic["fixes"].is_array(), "{output}");
    })
    .await
    .expect("ridl_check_returns_the_diagnostic_contract did not finish within the timeout");
}

/// Blanks the file path out of every span in a diagnostic array, in place.
///
/// The two faces register the source under different names by construction —
/// the tool under the synthetic `input.typl`, the CLI under the real file it
/// read — so the path is the one field the agreement test must set aside
/// (`crates/ridl-mcp/README.md`, "What this tool shares with `ridl check
/// --format json <file>`, and where it differs"). A label and a fix-it each
/// carry a span of their own, so each would otherwise reintroduce the
/// difference.
fn blank_span_paths(diagnostics: &mut serde_json::Value) {
    let blank = || serde_json::Value::String(String::new());
    for diagnostic in diagnostics.as_array_mut().into_iter().flatten() {
        diagnostic["span"]["path"] = blank();
        for label in diagnostic["labels"].as_array_mut().into_iter().flatten() {
            label["span"]["path"] = blank();
        }
        for fix in diagnostic["fixes"].as_array_mut().into_iter().flatten() {
            fix["span"]["path"] = blank();
        }
    }
}

/// Asserts that the MCP tool and `ridl check --format json` report the same
/// diagnostics for `source`, written to `file_name` for the CLI and sent with
/// `profile` to the tool, and that the CLI reports exactly `codes`, in order.
///
/// The equality holds for this input class only: one standalone file, no
/// `ridl.toml` and no imports. The two faces load the source differently — the
/// CLI calls `ridlc::run_check`, which reads a workspace from disk, and the
/// tool calls `ridlc::check_source`, which builds a one-file workspace from the
/// text — and a workspace member is exactly where the two may legitimately
/// diverge.
async fn assert_faces_agree(file_name: &str, source: &str, profile: &str, codes: &[&str]) {
    // The CLI side.
    let dir = TempDir::new("agree");
    let path = dir.write(file_name, source);
    let cli = StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
        .args(["check", "--format", "json"])
        .arg(&path)
        .output()
        .expect("run ridl check");
    // Checked first: on every exit-2 path `--format json` returns before it
    // prints anything, so stdout is empty and the parse below would report a
    // JSON error instead of the real failure.
    assert_eq!(cli.status.code(), Some(1), "{cli:?}");
    let mut cli: serde_json::Value =
        serde_json::from_slice(&cli.stdout).expect("the CLI prints JSON to stdout");

    // The MCP side.
    let client = connect().await;
    let mut mcp = call_ridl_check(&client, source, profile).await;
    client.cancel().await.expect("shutdown");
    // The tool wraps its array in an object; the CLI prints the bare array.
    let mut mcp = mcp["diagnostics"].take();

    // The CLI's codes are pinned, or the equality below would pass over a
    // fixture that stopped drawing the diagnostic it is here for.
    // TYPL-406 (`missing-docs`) is left out: the fixture has no docs.
    let cli_codes: Vec<&str> = cli
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|diagnostic| diagnostic["code"].as_str())
        .filter(|code| *code != "TYPL-406")
        .collect();
    assert_eq!(cli_codes, codes, "{cli}");
    blank_span_paths(&mut cli);
    blank_span_paths(&mut mcp);
    assert_eq!(cli, mcp);
}

/// The two faces agree on three diagnostics of two severities, not in line
/// order, so a tool that truncated or reordered its diagnostics would no
/// longer agree with the CLI.
#[tokio::test]
async fn ridl_check_and_check_format_json_agree() {
    tokio::time::timeout(
        TIMEOUT,
        assert_faces_agree(
            "agree.typl",
            THREE_KINDS_TYPL,
            "typl",
            &["FORM-101", "TYPL-103", "TYPL-104"],
        ),
    )
    .await
    .expect("ridl_check_and_check_format_json_agree did not finish within the timeout");
}

/// The two faces agree on a diagnostic of the service catalog, a
/// workspace-wide pass: RIDL-140, whose label points at the first declaration
/// (issue #345).
#[tokio::test]
async fn ridl_check_and_check_format_json_agree_on_the_service_catalog() {
    tokio::time::timeout(
        TIMEOUT,
        assert_faces_agree(
            "dup.ridl",
            "package p\ninterface I {}\nservice p.s : I\nservice p.s : I\n",
            "ridl",
            &["RIDL-140"],
        ),
    )
    .await
    .expect("the service catalog agreement test did not finish within the timeout");
}

/// The two faces agree on a diagnostic of the rsdl system query, the other
/// workspace-wide pass: RSDL-602, a system member line that names nothing.
#[tokio::test]
async fn ridl_check_and_check_format_json_agree_on_the_rsdl_system() {
    tokio::time::timeout(
        TIMEOUT,
        assert_faces_agree(
            "sys.rsdl",
            "package p\nsystem S { Missing }\n",
            "rsdl",
            &["RSDL-602"],
        ),
    )
    .await
    .expect("the rsdl system agreement test did not finish within the timeout");
}

/// Spawns `ridl mcp` with all three standard streams piped, bypassing the
/// `rmcp` client: [`connect`] and `client.cancel()` drive the process through
/// the SDK, which does not expose the child's own exit status, so the two
/// exit-code tests below speak raw newline-delimited JSON-RPC instead, the
/// same way the `ridl lsp` tests speak raw LSP framing.
fn spawn_mcp() -> Child {
    StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
        .arg("mcp")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn ridl mcp")
}

/// Reads newline-delimited JSON-RPC messages off `stdout` on a worker thread
/// and forwards them, the same bounded-wait shape [`read_messages`] gives the
/// LSP tests. A line that fails to parse is dropped rather than sent: the
/// server writes nothing but JSON-RPC on stdout, so a parse failure here
/// would be this test's own bug, not a message worth asserting on.
fn read_json_lines(stdout: ChildStdout) -> mpsc::Receiver<serde_json::Value> {
    let (sender, receiver) = mpsc::channel();
    std::thread::spawn(move || {
        let mut stdout = BufReader::new(stdout);
        let mut line = String::new();
        loop {
            line.clear();
            match stdout.read_line(&mut line) {
                Ok(0) => break,
                Ok(_) => {
                    let Ok(value) = serde_json::from_str(&line) else {
                        continue;
                    };
                    if sender.send(value).is_err() {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
    });
    receiver
}

/// Waits up to [`TIMEOUT`] for the next line on `messages`.
fn next_json_line(messages: &mpsc::Receiver<serde_json::Value>) -> serde_json::Value {
    messages
        .recv_timeout(TIMEOUT)
        .unwrap_or_else(|err| panic!("no JSON-RPC line within {TIMEOUT:?}: {err}"))
}

/// One `initialize` request, as a compact JSON-RPC line: the shape
/// `InitializeRequestParams` (`rmcp::model`) deserializes, confirmed directly
/// against the built binary before this test was written.
fn initialize_request() -> serde_json::Value {
    json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": { "name": "servers-test", "version": "0.0.0" }
        }
    })
}

#[test]
fn ridl_mcp_serves_the_handshake_and_exits_zero_on_shutdown() {
    let mut child = spawn_mcp();
    let mut stdin = child.stdin.take().expect("piped stdin");
    let messages = read_json_lines(child.stdout.take().expect("piped stdout"));

    writeln!(stdin, "{}", initialize_request()).expect("write initialize");
    let response = next_json_line(&messages);
    // Not merely "something answered": the server info is the RIDL MCP
    // server's own, so a subcommand that only opened a transport fails here.
    assert_eq!(
        response["result"]["serverInfo"]["name"], "ridl-mcp",
        "{response}"
    );
    // The version `ridl mcp` advertises is this build's own
    // `RIDL_BUILD_VERSION` (crates/ridl/build.rs), not `ridl-mcp`'s crate
    // version — the same value `ridl lsp` advertises, so a bug report names
    // one build regardless of which server the reporter happened to query.
    assert_eq!(
        response["result"]["serverInfo"]["version"],
        env!("RIDL_BUILD_VERSION"),
        "{response}"
    );

    writeln!(
        stdin,
        "{}",
        json!({ "jsonrpc": "2.0", "method": "notifications/initialized" })
    )
    .expect("write initialized notification");
    drop(stdin);

    let status = wait_for_exit(&mut child, "ridl mcp");
    assert_eq!(status.code(), Some(0), "a clean shutdown exits 0");
}

#[test]
fn ridl_mcp_exits_two_when_stdin_closes_before_initialize() {
    let mut child = spawn_mcp();
    // Close stdin without sending a request: the server must notice the
    // transport ending and exit, not hang.
    drop(child.stdin.take().expect("piped stdin"));

    let status = wait_for_exit(&mut child, "ridl mcp");
    // A client that disappears before the handshake is a transport error, not
    // a clean shutdown: exit 2, the "could not answer" code of ADR-0010
    // decision 1 — the same code, and the same cause, as the `ridl lsp`
    // counterpart below.
    assert_eq!(status.code(), Some(2), "a lost transport exits 2");
}

fn workspace_fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../ridl-mcp/tests/fixtures")
        .join(name)
}
async fn call_workspace_tool(
    client: &RunningService<RoleClient, ()>,
    name: &str,
    args: serde_json::Value,
) -> CallToolResult {
    client
        .call_tool(
            CallToolRequestParams::new(name.to_owned())
                .with_arguments(args.as_object().unwrap().clone()),
        )
        .await
        .expect("tools/call")
}
#[tokio::test]
async fn path_mode_check_equals_the_cli() {
    tokio::time::timeout(TIMEOUT, async {
        let path = workspace_fixture("ws-diag");
        let cli = StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
            .args(["check", "--format", "json"])
            .arg(&path)
            .output()
            .unwrap();
        assert_eq!(cli.status.code(), Some(1));
        let expected: serde_json::Value = serde_json::from_slice(&cli.stdout).unwrap();
        let client = connect().await;
        let result = call_workspace_tool(&client, "ridl_check", json!({"path":path})).await;
        assert_ne!(result.is_error, Some(true));
        assert_eq!(result.structured_content.unwrap()["diagnostics"], expected);
        client.cancel().await.unwrap();
    })
    .await
    .expect("workspace check timeout");
}
#[tokio::test]
async fn an_unsaved_overlay_reports_diagnostics_without_changing_disk() {
    tokio::time::timeout(TIMEOUT, async {
        let root = workspace_fixture("ws");
        let path = root.join("b/b.ridl");
        let disk = std::fs::read_to_string(&path).unwrap();
        let source = disk.replace("signal speed: Speed @10ms", "signal speed: Missing @10ms");
        assert_ne!(source, disk);
        let client = connect().await;
        let result = call_workspace_tool(
            &client,
            "ridl_check",
            json!({"path":root,"overlays":[{"path":path,"source":source}]}),
        )
        .await;
        assert_ne!(result.is_error, Some(true));
        let output = result.structured_content.unwrap();
        assert_eq!(output["workspace"]["errors"], 1);
        assert!(
            output["diagnostics"]
                .as_array()
                .unwrap()
                .iter()
                .any(|d| d["message"].as_str().unwrap().contains("Missing")
                    && d["span"]["path"] == path.to_string_lossy().as_ref())
        );
        assert_eq!(std::fs::read_to_string(&path).unwrap(), disk);
        client.cancel().await.unwrap();
    })
    .await
    .expect("unsaved overlay timeout");
}

#[tokio::test]
async fn diff_tool_equals_the_cli() {
    tokio::time::timeout(TIMEOUT, async {
        let old = workspace_fixture("ws");
        let new = workspace_fixture("ws-v2");
        let cli = StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
            .args(["diff", "--format", "json"])
            .arg(&old)
            .arg(&new)
            .output()
            .unwrap();
        assert_eq!(cli.status.code(), Some(1));
        let expected: serde_json::Value = serde_json::from_slice(&cli.stdout).unwrap();
        let client = connect().await;
        let result = call_workspace_tool(&client, "ridl_diff", json!({"old":old,"new":new})).await;
        assert_ne!(result.is_error, Some(true));
        assert_eq!(result.structured_content.unwrap(), expected);
        client.cancel().await.unwrap();
    })
    .await
    .expect("workspace diff timeout");
}
#[tokio::test]
async fn dirty_workspace_lookups_preserve_valid_declarations() {
    tokio::time::timeout(TIMEOUT, async {
        let path = workspace_fixture("ws");
        let client = connect().await;
        let overlays = json!([{"path":path.join("a/a.ridl"), "source":""}]);
        for (name, from) in [
            ("fx.a.sub.Gear", None),
            ("Gear", None),
            ("Gear", Some("fx.a.sub")),
        ] {
            for tool in ["ridl_resolve", "ridl_describe_type"] {
                let result = call_workspace_tool(
                    &client,
                    tool,
                    json!({"path":path, "name":name, "from":from, "overlays":overlays}),
                )
                .await;
                assert_ne!(result.is_error, Some(true), "{result:?}");
                let output = result.structured_content.unwrap();
                assert_eq!(output["package"], "fx.a.sub");
                assert!(output["workspace"]["errors"].as_u64().unwrap() > 0);
                if tool == "ridl_resolve" {
                    assert_eq!(output["name"], "Gear");
                } else {
                    assert_eq!(output["declaration"]["name"], "Gear");
                }
            }
        }
        client.cancel().await.unwrap();
    })
    .await
    .expect("dirty workspace lookup timeout");
}
#[tokio::test]
async fn diff_compile_errors_preserve_structured_diagnostics() {
    tokio::time::timeout(TIMEOUT, async {
        let path = workspace_fixture("ws-diag");
        let cli = StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
            .args(["check", "--format", "json"])
            .arg(&path)
            .output()
            .unwrap();
        assert_eq!(cli.status.code(), Some(1));
        let expected: serde_json::Value = serde_json::from_slice(&cli.stdout).unwrap();
        let client = connect().await;
        let clean = workspace_fixture("ws");
        for (old, new, message) in [
            (&clean, &path, "the new side does not compile"),
            (&path, &clean, "the old side does not compile"),
        ] {
            let result =
                call_workspace_tool(&client, "ridl_diff", json!({"old":old, "new":new})).await;
            assert_eq!(result.is_error, Some(true));
            let text: serde_json::Value = serde_json::from_str(&tool_text(&result)).unwrap();
            let output = result.structured_content.unwrap();
            assert_eq!(text, output);
            assert_eq!(output["message"], message);
            assert_eq!(output["diagnostics"], expected);
            assert_eq!(
                output["diagnostics"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|d| d["code"].as_str().unwrap())
                    // TYPL-406 (`missing-docs`) is left out: the fixture has no docs.
                    .filter(|code| *code != "TYPL-406")
                    .collect::<Vec<_>>(),
                ["TYPL-103", "TYPL-011"]
            );
        }
        client.cancel().await.unwrap();
    })
    .await
    .expect("structured diff diagnostic timeout");
}
#[tokio::test]
async fn every_tool_leaves_the_tree_unchanged() {
    tokio::time::timeout(TIMEOUT, async {
        fn copy(from: &std::path::Path, to: &std::path::Path) {
            std::fs::create_dir_all(to).unwrap();
            for entry in std::fs::read_dir(from).unwrap() {
                let entry = entry.unwrap();
                let dest = to.join(entry.file_name());
                if entry.path().is_dir() {
                    copy(&entry.path(), &dest);
                } else {
                    std::fs::copy(entry.path(), dest).unwrap();
                }
            }
        }
        fn record(root: &std::path::Path) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
            fn walk(
                root: &std::path::Path,
                dir: &std::path::Path,
                entries: &mut Vec<(PathBuf, u64, std::time::SystemTime)>,
            ) {
                for entry in std::fs::read_dir(dir).unwrap() {
                    let entry = entry.unwrap();
                    let metadata = entry.metadata().unwrap();
                    if metadata.is_dir() {
                        walk(root, &entry.path(), entries);
                    } else {
                        entries.push((
                            entry.path().strip_prefix(root).unwrap().into(),
                            metadata.len(),
                            metadata.modified().unwrap(),
                        ));
                    }
                }
            }
            let mut entries = Vec::new();
            walk(root, root, &mut entries);
            entries.sort();
            entries
        }
        let temp = TempDir::new("read-only");
        copy(&workspace_fixture("ws"), &temp.0);
        let before = record(&temp.0);
        let overlay_path = temp.0.join("a/a.ridl");
        let source = std::fs::read_to_string(&overlay_path)
            .unwrap()
            .replace("250.0", "200.0");
        let source = source + "\ntype Probe: integer [0..10]\n";
        let interface_path = temp.0.join("b/b.ridl");
        let interface_source = std::fs::read_to_string(&interface_path).unwrap()
            .replace("import fx.a.Speed", "import fx.a.Speed\nimport fx.a.Probe\nimport fx.a.sub.Gear")
            .replace("signal speed: Speed", "signal speed: Gear")
            .replace("  fixed softwareVersion: Version", "  fixed softwareVersion: Version\n  query probe(sample: Probe): Probe @[..100ms]");
        let overlays = json!([{"path":overlay_path,"source":source}, {"path":interface_path,"source":interface_source}]);
        let client = connect().await;
        for (name, arguments) in [
            ("ridl_check", json!({"path":temp.0,"overlays":overlays})),
            ("ridl_explain", json!({"code":"TYPL-002"})),
            (
                "ridl_resolve",
                json!({"path":temp.0,"name":"Probe","overlays":overlays}),
            ),
            (
                "ridl_describe_type",
                json!({"path":temp.0,"name":"Speed","overlays":overlays}),
            ),
            (
                "ridl_list_interactions",
                json!({"path":temp.0,"interface":"Status","overlays":overlays}),
            ),
            (
                "ridl_references",
                json!({"path":temp.0,"name":"Speed","overlays":overlays}),
            ),
            (
                "ridl_dependencies",
                json!({"path":temp.0,"overlays":overlays}),
            ),
            ("ridl_metrics", json!({"path":temp.0})),
            (
                "ridl_diff",
                json!({"old":temp.0,"new":temp.0,"overlays":overlays}),
            ),
        ] {
            let result = call_workspace_tool(&client, name, arguments).await;
            assert_ne!(result.is_error, Some(true), "{name}: {result:?}");
            let text: serde_json::Value = serde_json::from_str(&tool_text(&result)).unwrap();
            let output = result.structured_content.unwrap();
            assert_eq!(text, output, "{name}");
            match name {
                "ridl_check" => {
                    // Preserve the incoming allowance for undocumented fixture items.
                    let diagnostics = output["diagnostics"]
                        .as_array()
                        .expect("a diagnostics array")
                        .iter()
                        .filter(|diagnostic| diagnostic["lint"] != "missing-docs")
                        .collect::<Vec<_>>();
                    assert_eq!(serde_json::to_value(diagnostics).unwrap(), json!([]));
                },
                "ridl_explain" => {
                    assert_eq!(output["kind"], "diagnostic");
                    assert_eq!(output["code"], "TYPL-002");
                }
                "ridl_resolve" => {
                    assert_eq!(output["name"], "Probe");
                    assert_eq!(output["package"], "fx.a");
                }
                "ridl_describe_type" => {
                    assert_eq!(output["declaration"]["name"], "Speed");
                    assert_eq!(output["package"], "fx.a");
                    assert!(output["declaration"].to_string().contains("200"));
                }
                "ridl_list_interactions" => {
                    assert_eq!(output["interface"]["name"], "Status");
                    assert_eq!(output["interactions"].as_array().unwrap().len(), 6);
                    assert_eq!(output["interactions"][5]["name"], "probe");
                }
                "ridl_references" => {
                    assert_eq!(output["target"], "fx.a.Speed");
                    assert_eq!(output["references"].as_array().unwrap().len(), 1);
                    assert_eq!(output["references"][0]["declaration"], "fx.b.diag");
                }
                "ridl_dependencies" => {
                    assert_eq!(output["packages"].as_array().unwrap().len(), 3);
                    let package = output["packages"].as_array().unwrap().iter().find(|p| p["name"] == "fx.b").unwrap();
                    assert_eq!(package["depends_on"], json!(["fx.a", "fx.a.sub"]));
                },
                "ridl_metrics" => assert_eq!(output, json!({
                    "packages": [
                        {"name":"fx.a", "fanIn":1, "fanOut":0, "instability":0.0, "dependsOn":[]},
                        {"name":"fx.a.sub", "fanIn":0, "fanOut":0, "instability":null, "dependsOn":[]},
                        {"name":"fx.b", "fanIn":0, "fanOut":1, "instability":1.0, "dependsOn":["fx.a"]}
                    ],
                    "interfaces": [{"name":"fx.b.Status", "members":5,
                        "groups":[["speed"],["reading"],["setLevel"],["outcome"]]}],
                    "workspace": {"root":temp.0, "errors":0, "warnings":22, "notes":[]}
                })),
                "ridl_diff" => assert_eq!(output["verdict"], "breaking"),
                _ => unreachable!(),
            }
        }
        client.cancel().await.unwrap();
        assert_eq!(record(&temp.0), before);
        assert!(!temp.0.join("ridl.lock").exists());
        assert!(!temp.0.join(".ridl").exists());
    })
    .await
    .expect("read-only tools timeout");
}
#[tokio::test]
async fn a_wrong_request_is_is_error_not_a_protocol_error() {
    tokio::time::timeout(TIMEOUT, async {
        let client = connect().await;
        let result = call_workspace_tool(
            &client,
            "ridl_resolve",
            json!({"path":workspace_fixture("ws"),"name":"Unknown"}),
        )
        .await;
        assert_eq!(result.is_error, Some(true));
        client.cancel().await.unwrap();
    })
    .await
    .expect("tool error timeout");
}

// ---------------------------------------------------------------------------
// `ridl lsp`
// ---------------------------------------------------------------------------

/// Spawns `ridl lsp` followed by `args`, with all three standard streams
/// piped.
fn spawn_lsp(args: &[&str]) -> Child {
    StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
        .arg("lsp")
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn ridl lsp")
}

/// Reads LSP messages off `stdout` on a worker thread and forwards them.
/// Reading on a thread is what lets the test bound each wait: a blocking
/// `Message::read` against a server that never answers would hang the run.
fn read_messages(stdout: ChildStdout) -> mpsc::Receiver<Message> {
    let (sender, receiver) = mpsc::channel();
    std::thread::spawn(move || {
        let mut stdout = BufReader::new(stdout);
        while let Ok(Some(message)) = Message::read(&mut stdout) {
            if sender.send(message).is_err() {
                break;
            }
        }
    });
    receiver
}

/// Waits for the response to `id`, skipping the notifications the server
/// sends on its own (`textDocument/publishDiagnostics`).
fn response_to(messages: &mpsc::Receiver<Message>, id: RequestId) -> Response {
    let deadline = Instant::now() + TIMEOUT;
    loop {
        let remaining = deadline.saturating_duration_since(Instant::now());
        match messages.recv_timeout(remaining) {
            Ok(Message::Response(response)) if response.id == id => return response,
            Ok(_) => {}
            Err(err) => panic!("no response to request {id} within {TIMEOUT:?}: {err}"),
        }
    }
}

/// Waits for `child` to exit, killing it and failing the test if it does not
/// within [`TIMEOUT`]. Polling rather than a blocking `wait` is what lets the
/// child be killed instead of orphaned when the test fails.
fn wait_for_exit(child: &mut Child, what: &str) -> ExitStatus {
    let deadline = Instant::now() + TIMEOUT;
    loop {
        match child.try_wait().expect("poll the child") {
            Some(status) => return status,
            None if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                panic!("{what} did not exit within {TIMEOUT:?}");
            }
            None => std::thread::sleep(Duration::from_millis(20)),
        }
    }
}

#[test]
fn ridl_lsp_serves_the_handshake_and_exits_zero_on_shutdown() {
    assert_lsp_handshake_and_clean_shutdown(&[]);
}

/// The command line the VS Code client builds: `vscode-languageclient`
/// appends `--stdio` to the server's arguments whenever the transport is
/// `TransportKind.stdio`, which is what `editors/vscode/src/extension.ts`
/// sets. Before `ridl lsp` accepted the flag, clap refused it with exit 2 and
/// the extension never had a server to talk to.
#[test]
fn ridl_lsp_accepts_the_stdio_flag_an_editor_client_passes() {
    assert_lsp_handshake_and_clean_shutdown(&["--stdio"]);
}

/// The LSP specification (3.17, "Implementation Considerations") recommends
/// that a server accept `--clientProcessId` next to the transport flag. The
/// server ignores the value: `initialize` carries the same process id. Each
/// flag is accepted without the other, and the value in either clap form.
#[test]
fn ridl_lsp_accepts_the_client_process_id_the_lsp_specification_recommends() {
    assert_lsp_handshake_and_clean_shutdown(&["--stdio", "--clientProcessId=4242"]);
    assert_lsp_handshake_and_clean_shutdown(&["--clientProcessId", "4242"]);
}

/// Stdio is the only transport: a client asking for a pipe or a socket is
/// refused with exit 2 rather than served over stdio, where it would never
/// connect. Exit 2 alone does not prove the refusal, because an accepted flag
/// followed by stdin closing before `initialize` also exits 2, so the test
/// also reads the refusal on stderr.
#[test]
fn ridl_lsp_refuses_a_transport_other_than_stdio() {
    for flag in ["--pipe=ridl-test-pipe", "--socket=7777"] {
        let mut child = spawn_lsp(&[flag]);
        drop(child.stdin.take().expect("piped stdin"));
        let status = wait_for_exit(&mut child, "ridl lsp");
        let mut stderr = String::new();
        child
            .stderr
            .take()
            .expect("piped stderr")
            .read_to_string(&mut stderr)
            .expect("read stderr");
        assert_eq!(
            status.code(),
            Some(2),
            "{flag}: an unsupported transport exits 2"
        );
        assert!(
            stderr.contains("unexpected argument"),
            "{flag}: refused as an argument, not served: {stderr}"
        );
    }
}

/// Runs `ridl lsp` with `args` through the `initialize` handshake and a
/// `shutdown`/`exit` pair, and asserts the server answers as itself and
/// exits 0.
fn assert_lsp_handshake_and_clean_shutdown(args: &[&str]) {
    let mut child = spawn_lsp(args);
    let mut stdin = child.stdin.take().expect("piped stdin");
    let messages = read_messages(child.stdout.take().expect("piped stdout"));

    let initialize = RequestId::from(1);
    Message::Request(Request::new(
        initialize.clone(),
        "initialize".to_string(),
        json!({ "capabilities": {} }),
    ))
    .write(&mut stdin)
    .expect("write initialize");
    let result = response_to(&messages, initialize)
        .response_result
        .expect("an initialize result, not an error");
    // Not merely "something answered": the capability set is the language
    // server's own, so a subcommand that only opened a transport fails here.
    assert!(
        result["capabilities"]["textDocumentSync"].is_object(),
        "{result}"
    );
    // The version `ridl lsp` advertises is this build's own
    // `RIDL_BUILD_VERSION` (crates/ridl/build.rs) — the same value the
    // `ridl_mcp_serves_the_handshake_and_exits_zero_on_shutdown` test below
    // asserts `ridl mcp` advertises, so a bug report names one build
    // regardless of which server the reporter queried. `run_lsp` calling
    // plain `run` instead of `run_with_version` would leave `serverInfo`
    // with no `version` field at all, which fails this too.
    assert_eq!(
        result["serverInfo"]["version"],
        env!("RIDL_BUILD_VERSION"),
        "{result}"
    );

    Message::Notification(Notification::new("initialized".to_string(), json!({})))
        .write(&mut stdin)
        .expect("write initialized");
    let shutdown = RequestId::from(2);
    Message::Request(Request::new(
        shutdown.clone(),
        "shutdown".to_string(),
        json!(null),
    ))
    .write(&mut stdin)
    .expect("write shutdown");
    response_to(&messages, shutdown)
        .response_result
        .expect("a shutdown result, not an error");
    Message::Notification(Notification::new("exit".to_string(), json!(null)))
        .write(&mut stdin)
        .expect("write exit");
    drop(stdin);

    let status = wait_for_exit(&mut child, "ridl lsp");
    assert_eq!(status.code(), Some(0), "a clean shutdown exits 0");
}

#[test]
fn ridl_lsp_exits_two_when_stdin_closes_before_initialize() {
    let mut child = spawn_lsp(&[]);
    // Close stdin without sending a request: the server must notice the
    // transport ending and exit, not hang.
    drop(child.stdin.take().expect("piped stdin"));

    let status = wait_for_exit(&mut child, "ridl lsp");
    // A client that disappears before the handshake is a transport error, not
    // a clean shutdown: exit 2, the "could not answer" code of ADR-0010
    // decision 1.
    assert_eq!(status.code(), Some(2), "a lost transport exits 2");
}

// ---------------------------------------------------------------------------
// `ridl lsp` and the `[lints]` levels
// ---------------------------------------------------------------------------

/// A `signal` with no timing annotation, which draws RIDL-100
/// (`missing-timing`, a Warning by default) and nothing else.
const UNTIMED_SIGNAL: &str = "package {name}\n\ntype Speed: integer [0..300]\n\ninterface Sensor {\n  \
                              signal speed: Speed\n}\n";

/// Three interfaces whose queries share one error type, which draws RIDL-405
/// (`shared-error-type`, an Info by default) three times — one per interface
/// — and nothing else. A file body with no `package` line, appended to one.
const SHARED_ERROR: &str = "\
struct FaultPage {
  count : integer [0..64]
}

error enum DiagError {
  STORAGE_BUSY  = 0
  ACCESS_DENIED = 1
}

interface Cluster {
  query faults(): FaultPage | DiagError @[..50ms]
}

interface Powertrain {
  query faults(): FaultPage | DiagError @[..50ms]
}

interface Infotainment {
  query faults(): FaultPage | DiagError @[..50ms]
}
";

/// A two-member workspace whose `[lints]` tables exercise every level the
/// language server must honor. The root sets `missing-timing = "deny"` and
/// `shared-error-type = "allow"`, raises `unknown-lint = "info"`, and has one
/// key that names no lint (MANI-010 on the root manifest). MANI-010 is a
/// loader diagnostic, which the server converts at load time and `analyze`
/// never sees; at `info` rather than its default Warning, the level applied
/// at load time is pinned. Member `a` sets `missing-timing = "info"`
/// over the root, so a diagnostic under `a` tells the member's table (Info)
/// from the root's (Error) and from the registry default (Warning). Member `b`
/// has no table of its own. Expected after the levels apply:
///
/// - `ridl.toml`: MANI-010, Info;
/// - `a/a.ridl`: RIDL-100, Info;
/// - `b/b.ridl`: RIDL-100, Error; the three RIDL-405 are removed.
///
/// Returns the workspace root.
fn lint_workspace(dir: &TempDir) -> PathBuf {
    dir.write(
        "ridl.toml",
        "[workspace]\nmembers = [\"a\", \"b\"]\n\n[lints]\nmissing-timing = \"deny\"\n\
         shared-error-type = \"allow\"\nunknown-lint = \"info\"\nnot-a-lint = \"warn\"\n",
    );
    std::fs::create_dir_all(dir.0.join("a")).expect("create member a");
    std::fs::create_dir_all(dir.0.join("b")).expect("create member b");
    dir.write(
        "a/ridl.toml",
        "[package]\nname = \"a\"\nversion = \"1.0.0\"\n\n[lints]\nmissing-timing = \"info\"\n",
    );
    dir.write("a/a.ridl", &UNTIMED_SIGNAL.replace("{name}", "a"));
    dir.write(
        "b/ridl.toml",
        "[package]\nname = \"b\"\nversion = \"1.0.0\"\n",
    );
    dir.write(
        "b/b.ridl",
        &format!("{}\n{SHARED_ERROR}", UNTIMED_SIGNAL.replace("{name}", "b")),
    );
    dir.0.clone()
}

/// The `file://` URI of an absolute path, as text, built by the conversion
/// the server itself uses for the URIs it publishes, so the two compare byte
/// for byte.
fn file_uri(path: &Path) -> String {
    let path = path.to_str().expect("a UTF-8 scratch path");
    ridl_lsp::convert::path_to_uri(path)
        .unwrap_or_else(|| panic!("`{path}` is absolute and converts to a URI"))
        .as_str()
        .to_string()
}

/// The `(code, severity)` pairs `ridl check --format json` reports for
/// `root`, with the severity as the LSP number: `error` 1, `warning` 2,
/// `info` 3. Sorted, so two reports compare as multisets.
fn cli_code_severity_pairs(root: &Path) -> Vec<(String, u8)> {
    let cli = StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
        .args(["check", "--format", "json"])
        .arg(root)
        .output()
        .expect("run ridl check");
    // Checked first: on every exit-2 path `--format json` returns before it
    // prints anything, so the parse below would report a JSON error instead
    // of the real failure. Exit 1, not 0: the root's `deny` makes RIDL-100
    // an error in `b`.
    assert_eq!(cli.status.code(), Some(1), "{cli:?}");
    let diagnostics: serde_json::Value =
        serde_json::from_slice(&cli.stdout).expect("the CLI prints JSON to stdout");
    // TYPL-406 (`missing-docs`) is left out: the fixture has no docs.
    let mut pairs: Vec<(String, u8)> = diagnostics
        .as_array()
        .expect("a JSON array")
        .iter()
        .filter(|diagnostic| diagnostic["code"] != "TYPL-406")
        .map(|diagnostic| {
            let code = diagnostic["code"].as_str().expect("a code").to_string();
            let severity = match diagnostic["severity"].as_str() {
                Some("error") => 1,
                Some("warning") => 2,
                Some("info") => 3,
                other => panic!("an unexpected severity {other:?} in {diagnostic}"),
            };
            (code, severity)
        })
        .collect();
    pairs.sort();
    pairs
}

/// The `(code, severity)` pairs of one `publishDiagnostics` parameter object.
fn published_code_severity_pairs(params: &serde_json::Value) -> Vec<(String, u8)> {
    // TYPL-406 (`missing-docs`) is left out: the fixture has no docs.
    params["diagnostics"]
        .as_array()
        .expect("a diagnostics array")
        .iter()
        .filter(|diagnostic| diagnostic["code"] != "TYPL-406")
        .map(|diagnostic| {
            let code = diagnostic["code"].as_str().expect("a code").to_string();
            let severity = diagnostic["severity"].as_u64().expect("a numeric severity") as u8;
            (code, severity)
        })
        .collect()
}

/// A spawned `ridl lsp` after its `initialize` handshake over `root`, with
/// `initialized` sent.
struct LspSession {
    child: Child,
    stdin: std::process::ChildStdin,
    messages: mpsc::Receiver<Message>,
}

impl LspSession {
    fn start(root: &Path) -> LspSession {
        let mut child = spawn_lsp(&[]);
        let mut stdin = child.stdin.take().expect("piped stdin");
        let messages = read_messages(child.stdout.take().expect("piped stdout"));
        let initialize = RequestId::from(1);
        Message::Request(Request::new(
            initialize.clone(),
            "initialize".to_string(),
            json!({
                "capabilities": {},
                "workspaceFolders": [{ "uri": file_uri(root), "name": "lints" }],
            }),
        ))
        .write(&mut stdin)
        .expect("write initialize");
        response_to(&messages, initialize)
            .response_result
            .expect("an initialize result, not an error");
        Message::Notification(Notification::new("initialized".to_string(), json!({})))
            .write(&mut stdin)
            .expect("write initialized");
        LspSession {
            child,
            stdin,
            messages,
        }
    }

    fn notify(&mut self, method: &str, params: serde_json::Value) {
        Message::Notification(Notification::new(method.to_string(), params))
            .write(&mut self.stdin)
            .unwrap_or_else(|err| panic!("write {method}: {err}"));
    }

    /// Sends `shutdown` and returns every `publishDiagnostics` the server sent
    /// before answering it, newest last. Dispatch is sequential, so every
    /// publish an earlier message caused precedes the `shutdown` response.
    /// Then sends `exit` and asserts the server exits 0. The request id is 2:
    /// `initialize` was 1, and no other request is sent in between.
    fn shutdown_collecting_publishes(mut self) -> Vec<serde_json::Value> {
        let shutdown = RequestId::from(2);
        Message::Request(Request::new(
            shutdown.clone(),
            "shutdown".to_string(),
            json!(null),
        ))
        .write(&mut self.stdin)
        .expect("write shutdown");
        let mut publishes = Vec::new();
        let deadline = Instant::now() + TIMEOUT;
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            match self.messages.recv_timeout(remaining) {
                Ok(Message::Response(response)) if response.id == shutdown => {
                    response
                        .response_result
                        .expect("a shutdown result, not an error");
                    break;
                }
                Ok(Message::Notification(notification))
                    if notification.method == "textDocument/publishDiagnostics" =>
                {
                    publishes.push(notification.params);
                }
                Ok(_) => {}
                Err(err) => panic!("no response to shutdown within {TIMEOUT:?}: {err}"),
            }
        }
        self.notify("exit", json!(null));
        drop(self.stdin);
        let status = wait_for_exit(&mut self.child, "ridl lsp");
        assert_eq!(status.code(), Some(0), "a clean shutdown exits 0");
        publishes
    }
}

/// The language server publishes the same `(code, severity)` pairs that
/// `ridl check --format json` reports, after the `[lints]` levels apply
/// (ADR-0024 decision 6): `deny` is LSP severity 1, `info` is 3,
/// `allow` removes the diagnostic on both faces, and the MANI-010 of the
/// unknown key is an Info on both, the root's `unknown-lint = "info"` applied
/// to a loader diagnostic. Both faces walk the same workspace
/// from disk, so the comparison is a multiset over every published file.
#[test]
fn lsp_matches_check_with_lints() {
    let dir = TempDir::new("lsp-lints");
    let root = lint_workspace(&dir);
    let cli = cli_code_severity_pairs(&root);
    // Pinned, or the equality below would pass over a fixture that stopped
    // drawing the diagnostics it is here for.
    assert_eq!(
        cli,
        vec![
            ("MANI-010".to_string(), 3),
            ("RIDL-100".to_string(), 1),
            ("RIDL-100".to_string(), 3),
        ],
    );

    let session = LspSession::start(&root);
    let publishes = session.shutdown_collecting_publishes();
    let mut lsp: Vec<(String, u8)> = publishes
        .iter()
        .flat_map(published_code_severity_pairs)
        .collect();
    lsp.sort();

    assert_eq!(lsp, cli, "published: {publishes:#?}");
}

/// A file the editor creates after the workspace loaded has no load-time
/// entry, so its levels resolve by directory: a new file under member `a`
/// takes `a`'s `missing-timing = "info"` (LSP severity 3), not the root's
/// `deny` (1) and not the registry default (2). Review focus 3.
#[test]
fn lsp_new_file_uses_member_levels() {
    let dir = TempDir::new("lsp-new-file");
    let root = lint_workspace(&dir);
    let new_file = root.join("a").join("fresh.ridl");
    let uri = file_uri(&new_file);

    let mut session = LspSession::start(&root);
    session.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": {
                "uri": uri,
                "languageId": "ridl",
                "version": 1,
                "text": UNTIMED_SIGNAL.replace("{name}", "fresh"),
            }
        }),
    );
    let publishes = session.shutdown_collecting_publishes();

    let for_new_file = publishes
        .iter()
        .rev()
        .find(|params| params["uri"] == uri)
        .unwrap_or_else(|| panic!("a publish for `{uri}` in {publishes:#?}"));
    assert_eq!(
        published_code_severity_pairs(for_new_file),
        vec![("RIDL-100".to_string(), 3)],
        "{for_new_file:#?}"
    );
}

// ---------------------------------------------------------------------------
// Scratch files
// ---------------------------------------------------------------------------

/// A unique directory under the system temp dir, removed on drop.
struct TempDir(PathBuf);

impl TempDir {
    fn new(label: &str) -> Self {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        let mut path = std::env::temp_dir();
        path.push(format!(
            "ridl-servers-{label}-{}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::SeqCst),
        ));
        std::fs::create_dir_all(&path).expect("create the temp dir");
        Self(path)
    }

    fn write(&self, relative: &str, text: &str) -> PathBuf {
        let path = self.0.join(relative);
        std::fs::write(&path, text).expect("write the fixture file");
        path
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}