ridl-cli 0.2.0

The `ridl` command-line toolchain: check, build, fmt, lock, diff, lsp, and mcp, 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
//! `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, Write};
use std::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 the
/// CLI/MCP agreement test 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 names: Vec<&str> = tools.tools.iter().map(|tool| tool.name.as_ref()).collect();
        assert_eq!(names, ["ridl_check"]);
        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");

        let diagnostics = output["diagnostics"]
            .as_array()
            .unwrap_or_else(|| panic!("a diagnostics array: {output}"));
        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"). No compiler pass emits a
/// fix-it today, so the
/// inner loop is a no-op on current inputs; it is here because a `fixes` entry
/// carries a span of its own and 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 fix in diagnostic["fixes"].as_array_mut().into_iter().flatten() {
            fix["span"]["path"] = blank();
        }
    }
}

/// The MCP tool and `ridl check --format json` report the same diagnostics.
///
/// The equality holds for this input class only: one standalone file, no
/// `ridl.toml` and no imports. The two faces run different front ends — the
/// CLI calls `ridlc::run_check`, which resolves a workspace, and the tool
/// calls `ridlc::check_source`, which does not — and a workspace member is
/// exactly where the two may legitimately diverge.
#[tokio::test]
async fn ridl_check_and_check_format_json_agree() {
    tokio::time::timeout(TIMEOUT, async {
        // The CLI side.
        let dir = TempDir::new("agree");
        let path = dir.write("agree.typl", THREE_KINDS_TYPL);
        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, THREE_KINDS_TYPL, "typl").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();

        // At least two on each side, or the equality below would pass over
        // a tool that truncated its diagnostics to the first one.
        assert!(
            cli.as_array().is_some_and(|array| array.len() >= 2),
            "the fixture must produce at least two diagnostics, or this proves nothing: {cli}"
        );
        assert!(
            mcp.as_array().is_some_and(|array| array.len() >= 2),
            "the tool must report at least two diagnostics, or this proves nothing: {mcp}"
        );
        blank_span_paths(&mut cli);
        blank_span_paths(&mut mcp);
        assert_eq!(cli, mcp);
    })
    .await
    .expect("ridl_check_and_check_format_json_agree 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");
}

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

/// Spawns `ridl lsp` with all three standard streams piped.
fn spawn_lsp() -> Child {
    StdCommand::new(env!("CARGO_BIN_EXE_ridl"))
        .arg("lsp")
        .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() {
    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": {} }),
    ))
    .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");
}

// ---------------------------------------------------------------------------
// 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);
    }
}