nemo-relay-cli 0.6.0

Coding-agent gateway CLI for NeMo Relay observability.
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
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use serde_json::{Value, json};
use std::ffi::OsString;
use std::io::{BufReader as StdBufReader, Cursor};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};

use super::*;
use crate::installation::generation::{
    GENERATION_FILE_NAME, GenerationRetirement, InstallGeneration, write_new_generation,
};
use crate::mcp::protocol::MCP_SUPPORTED_PROTOCOL_VERSIONS;

struct BootstrapConfigHome {
    _guard: std::sync::MutexGuard<'static, ()>,
    previous: Option<OsString>,
}

impl BootstrapConfigHome {
    fn enter(path: &std::path::Path) -> Self {
        crate::test_support::enable_operational_logs();
        let guard = crate::test_support::ENV_TEST_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let previous = std::env::var_os("XDG_CONFIG_HOME");
        unsafe { std::env::set_var("XDG_CONFIG_HOME", path) };
        Self {
            _guard: guard,
            previous,
        }
    }
}

impl Drop for BootstrapConfigHome {
    fn drop(&mut self) {
        if let Some(previous) = self.previous.take() {
            unsafe { std::env::set_var("XDG_CONFIG_HOME", previous) };
        } else {
            unsafe { std::env::remove_var("XDG_CONFIG_HOME") };
        }
    }
}

struct TransparentRunEnvironment {
    _guard: std::sync::MutexGuard<'static, ()>,
    previous_run: Option<OsString>,
    previous_gateway: Option<OsString>,
}

impl TransparentRunEnvironment {
    fn without_gateway() -> Self {
        crate::test_support::enable_operational_logs();
        let guard = crate::test_support::ENV_TEST_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let previous_run = std::env::var_os(crate::configuration::TRANSPARENT_RUN_ENV);
        let previous_gateway = std::env::var_os(crate::configuration::GATEWAY_URL_ENV);
        // SAFETY: This scope holds the process-wide environment mutex.
        unsafe {
            std::env::set_var(crate::configuration::TRANSPARENT_RUN_ENV, "1");
            std::env::remove_var(crate::configuration::GATEWAY_URL_ENV);
        }
        Self {
            _guard: guard,
            previous_run,
            previous_gateway,
        }
    }
}

impl Drop for TransparentRunEnvironment {
    fn drop(&mut self) {
        // SAFETY: This restores the process environment while the mutex remains held.
        unsafe {
            match self.previous_run.take() {
                Some(value) => std::env::set_var(crate::configuration::TRANSPARENT_RUN_ENV, value),
                None => std::env::remove_var(crate::configuration::TRANSPARENT_RUN_ENV),
            }
            match self.previous_gateway.take() {
                Some(value) => std::env::set_var(crate::configuration::GATEWAY_URL_ENV, value),
                None => std::env::remove_var(crate::configuration::GATEWAY_URL_ENV),
            }
        }
    }
}

#[tokio::test]
async fn transparent_mcp_requires_the_wrapper_gateway_url() {
    let _environment = TransparentRunEnvironment::without_gateway();

    let error = run(&crate::server::GatewayOverrides::default())
        .await
        .unwrap_err()
        .to_string();

    assert!(
        error.contains(crate::configuration::GATEWAY_URL_ENV),
        "{error}"
    );
    assert!(
        error.contains(crate::configuration::TRANSPARENT_RUN_ENV),
        "{error}"
    );
}

#[test]
fn bounded_mcp_reader_accepts_the_limit_and_preserves_following_frames() {
    let mut input = vec![b'a'; MAX_MCP_FRAME_BYTES - 1];
    input.push(b'\n');
    input.extend_from_slice(b"{}\n");
    let mut reader = StdBufReader::new(Cursor::new(input));
    let mut frame = Vec::new();

    assert_eq!(
        read_bounded_frame(&mut reader, &mut frame, MAX_MCP_FRAME_BYTES).unwrap(),
        MAX_MCP_FRAME_BYTES
    );
    assert_eq!(frame.last(), Some(&b'\n'));
    frame.clear();
    assert_eq!(
        read_bounded_frame(&mut reader, &mut frame, MAX_MCP_FRAME_BYTES).unwrap(),
        3
    );
    assert_eq!(frame, b"{}\n");
}

#[test]
fn bounded_mcp_reader_rejects_one_oversized_unterminated_frame() {
    let input = vec![b'a'; MAX_MCP_FRAME_BYTES + 1];
    let mut reader = StdBufReader::new(Cursor::new(input));
    let mut frame = Vec::new();

    let error = read_bounded_frame(&mut reader, &mut frame, MAX_MCP_FRAME_BYTES).unwrap_err();

    assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
    assert!(error.to_string().contains("MCP frame exceeds"));
}

#[test]
fn initialize_reports_native_server_and_supported_protocol() {
    for protocol_version in MCP_SUPPORTED_PROTOCOL_VERSIONS {
        let response = response_for(&json!({
            "jsonrpc": "2.0",
            "id": 7,
            "method": "initialize",
            "params": { "protocolVersion": protocol_version }
        }))
        .unwrap();

        assert_eq!(response["jsonrpc"], json!("2.0"));
        assert_eq!(response["id"], json!(7));
        assert_eq!(
            response["result"]["protocolVersion"],
            json!(protocol_version)
        );
        assert_eq!(response["result"]["capabilities"], json!({}));
        assert_eq!(
            response["result"]["serverInfo"]["name"],
            json!("nemo-relay")
        );
        assert_eq!(
            response["result"]["serverInfo"]["version"],
            json!(env!("CARGO_PKG_VERSION"))
        );
    }

    let response = response_for(&json!({
        "jsonrpc": "2.0",
        "id": 7,
        "method": "initialize",
        "params": { "protocolVersion": "2024-11-05" }
    }))
    .unwrap();
    assert_eq!(
        response["result"]["protocolVersion"],
        json!(MCP_PROTOCOL_VERSION)
    );
}

#[test]
fn supported_requests_and_notifications_have_minimal_mcp_behavior() {
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "id":"tools", "method":"tools/list"})),
        Some(json!({"jsonrpc":"2.0", "id":"tools", "result":{"tools":[]}}))
    );
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "id":2, "method":"ping"})),
        Some(json!({"jsonrpc":"2.0", "id":2, "result":{}}))
    );
    assert_eq!(
        response_for(&json!({
            "jsonrpc":"2.0",
            "method":"notifications/initialized"
        })),
        None
    );
}

#[test]
fn invalid_and_unknown_requests_return_jsonrpc_errors() {
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "id":3})),
        Some(jsonrpc_error(json!(3), -32600, "Invalid Request"))
    );
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "id":4, "method":"resources/list"})),
        Some(jsonrpc_error(json!(4), -32601, "Method not found"))
    );
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "id":5, "method":"initialize", "params":{}})),
        Some(jsonrpc_error(json!(5), -32602, "Missing protocolVersion"))
    );
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0"})),
        Some(jsonrpc_error(Value::Null, -32600, "Invalid Request"))
    );
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "id":true, "method":"ping"})),
        Some(jsonrpc_error(Value::Null, -32600, "Invalid Request"))
    );
    assert_eq!(
        response_for(&json!({"jsonrpc":"2.0", "method":7})),
        Some(jsonrpc_error(Value::Null, -32600, "Invalid Request"))
    );
}

#[test]
fn invalid_jsonrpc_returns_invalid_request() {
    let action = crate::mcp::protocol::evaluate_frame(
        r#"{"jsonrpc":"1.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
    );

    assert_eq!(
        action.response,
        Some(jsonrpc_error(json!(1), -32600, "Invalid Request"))
    );
}

#[tokio::test]
async fn stdio_loop_recovers_from_parse_errors_and_ignores_notifications() {
    let (mut client, server) = tokio::io::duplex(4096);
    let (server_reader, server_writer) = tokio::io::split(server);
    let task = tokio::spawn(serve_stdio(BufReader::new(server_reader), server_writer));

    client
        .write_all(
            b"not-json\n{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"ping\"}\n",
        )
        .await
        .unwrap();
    client.shutdown().await.unwrap();
    let mut output = String::new();
    client.read_to_string(&mut output).await.unwrap();
    task.await.unwrap().unwrap();

    let responses = output
        .lines()
        .map(|line| serde_json::from_str::<Value>(line).unwrap())
        .collect::<Vec<_>>();
    assert_eq!(responses.len(), 2);
    assert_eq!(
        responses[0],
        jsonrpc_error(Value::Null, -32700, "Parse error")
    );
    assert_eq!(responses[1], json!({"jsonrpc":"2.0", "id":5, "result":{}}));
}

#[tokio::test]
async fn mcp_session_serves_stdio_and_stops_heartbeat_on_eof() {
    let (client, server_io) = tokio::io::duplex(4096);
    let (client_reader, mut client_writer) = tokio::io::split(client);
    let (server_reader, server_writer) = tokio::io::split(server_io);
    let task = tokio::spawn(run_session(BufReader::new(server_reader), server_writer));

    client_writer
        .write_all(
            b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\"}}\n",
        )
        .await
        .unwrap();
    let mut client_reader = BufReader::new(client_reader);
    let mut response = String::new();
    tokio::time::timeout(
        std::time::Duration::from_secs(5),
        client_reader.read_line(&mut response),
    )
    .await
    .expect("MCP initialization response timed out")
    .unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&response).unwrap()["result"]["serverInfo"]["name"],
        json!("nemo-relay")
    );

    client_writer.shutdown().await.unwrap();
    tokio::time::timeout(std::time::Duration::from_secs(5), task)
        .await
        .expect("MCP session did not stop after stdin EOF")
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn heartbeat_keeps_a_compatible_gateway_session_alive() {
    let _plugin_guard = crate::test_support::PLUGIN_CONFIG_TEST_LOCK.lock().await;
    let temp = tempfile::tempdir().unwrap();
    let _bootstrap_home = BootstrapConfigHome::enter(&temp.path().join("xdg"));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let bind = listener.local_addr().unwrap();
    let config = crate::configuration::GatewayConfig {
        bind,
        ..crate::configuration::GatewayConfig::default()
    };
    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
    let fingerprint = "test-fingerprint";
    let gateway = tokio::spawn(crate::server::serve_listener_with_bootstrap(
        listener,
        config,
        fingerprint.into(),
        Some(shutdown_rx),
    ));
    let url = format!("http://{bind}");
    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let probe_url = url.clone();
            if tokio::task::spawn_blocking(move || {
                crate::gateway::client::healthz_compatible(&probe_url, fingerprint)
            })
            .await
            .unwrap()
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("compatible gateway did not become healthy");

    let health_calls = Arc::new(AtomicUsize::new(0));
    let restart_calls = Arc::new(AtomicUsize::new(0));
    let (observed_tx, mut observed_rx) = tokio::sync::mpsc::unbounded_channel();
    let heartbeat = tokio::spawn(maintain_gateway_with(
        bind,
        url,
        Duration::from_millis(10),
        {
            let health_calls = health_calls.clone();
            move |url| {
                let health_calls = health_calls.clone();
                let observed_tx = observed_tx.clone();
                async move {
                    let healthy = tokio::task::spawn_blocking(move || {
                        crate::gateway::client::healthz_compatible(&url, fingerprint)
                    })
                    .await
                    .map_err(|error| {
                        CliError::Launch(format!("gateway heartbeat task failed: {error}"))
                    })?;
                    if healthy {
                        let call = health_calls.fetch_add(1, Ordering::SeqCst) + 1;
                        if call == 3 {
                            let _ = observed_tx.send(());
                        }
                    }
                    Ok(healthy)
                }
            }
        },
        {
            let restart_calls = restart_calls.clone();
            move |address, _expected_instance| {
                restart_calls.fetch_add(1, Ordering::SeqCst);
                async move {
                    Ok(crate::bootstrap::GatewayEndpoint {
                        address,
                        url: "http://unexpected-restart".into(),
                        instance_id: "unexpected".into(),
                    })
                }
            }
        },
    ));

    tokio::time::timeout(Duration::from_secs(5), observed_rx.recv())
        .await
        .expect("heartbeat did not complete three compatible health checks")
        .expect("heartbeat stopped before completing three compatible health checks");
    assert!(!heartbeat.is_finished());
    assert!(health_calls.load(Ordering::SeqCst) >= 3);
    assert_eq!(restart_calls.load(Ordering::SeqCst), 0);
    heartbeat.abort();
    assert!(heartbeat.await.unwrap_err().is_cancelled());

    let _ = shutdown_tx.send(());
    tokio::time::timeout(Duration::from_secs(5), gateway)
        .await
        .expect("compatible gateway did not stop")
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn borrowed_transparent_gateway_is_authenticated_and_monitored() {
    let _plugin_guard = crate::test_support::PLUGIN_CONFIG_TEST_LOCK.lock().await;
    let temp = tempfile::tempdir().unwrap();
    let _bootstrap_home = BootstrapConfigHome::enter(&temp.path().join("xdg"));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let bind = listener.local_addr().unwrap();
    let url = format!("http://{bind}");
    let fingerprint = crate::configuration::transparent_gateway_fingerprint(&url);
    let config = crate::configuration::GatewayConfig {
        bind,
        ..crate::configuration::GatewayConfig::default()
    };
    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
    let gateway = tokio::spawn(crate::server::serve_transparent_listener_with_dynamic(
        listener,
        config,
        Vec::new(),
        fingerprint.clone(),
        crate::provider_auth::TransparentProxyCredential::generate().unwrap(),
        Some(shutdown_rx),
    ));
    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let probe_url = url.clone();
            let probe_fingerprint = fingerprint.clone();
            if tokio::task::spawn_blocking(move || {
                crate::gateway::client::healthz_compatible(&probe_url, &probe_fingerprint)
            })
            .await
            .unwrap()
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("transparent gateway did not become healthy");

    let mut lease =
        gateway::GatewayLease::borrow_with_interval(url, fingerprint, Duration::from_millis(10))
            .await
            .expect("authenticated gateway should be borrowable");
    let _ = shutdown_tx.send(());
    tokio::time::timeout(Duration::from_secs(5), gateway)
        .await
        .expect("transparent gateway did not stop")
        .unwrap()
        .unwrap();

    let error = tokio::time::timeout(Duration::from_secs(5), lease.wait())
        .await
        .expect("borrowed gateway heartbeat did not detect shutdown")
        .unwrap_err()
        .to_string();
    assert!(error.contains("no longer available"), "{error}");
}

#[tokio::test]
async fn heartbeat_performs_one_restart_and_tracks_the_recovered_gateway() {
    let bind = "127.0.0.1:47632".parse().unwrap();
    let restart_calls = Arc::new(AtomicUsize::new(0));
    let observed_urls = Arc::new(Mutex::new(Vec::new()));
    let (recovered_tx, mut recovered_rx) = tokio::sync::mpsc::unbounded_channel();
    let heartbeat = tokio::spawn(maintain_gateway_with(
        bind,
        "http://dead-gateway".into(),
        Duration::from_millis(1),
        {
            let observed_urls = observed_urls.clone();
            move |url| {
                let observed_urls = observed_urls.clone();
                let recovered_tx = recovered_tx.clone();
                async move {
                    let recovered = url == "http://recovered-gateway";
                    observed_urls.lock().unwrap().push(url);
                    if recovered {
                        let _ = recovered_tx.send(());
                    }
                    Ok(recovered)
                }
            }
        },
        {
            let restart_calls = restart_calls.clone();
            move |address, _expected_instance| {
                let restart_calls = restart_calls.clone();
                async move {
                    restart_calls.fetch_add(1, Ordering::SeqCst);
                    Ok(crate::bootstrap::GatewayEndpoint {
                        address,
                        url: "http://recovered-gateway".into(),
                        instance_id: "recovered".into(),
                    })
                }
            }
        },
    ));

    tokio::time::timeout(Duration::from_secs(5), recovered_rx.recv())
        .await
        .expect("heartbeat did not observe the recovered gateway")
        .expect("heartbeat stopped before observing the recovered gateway");
    assert!(!heartbeat.is_finished());
    assert_eq!(restart_calls.load(Ordering::SeqCst), 1);
    assert!(
        observed_urls
            .lock()
            .unwrap()
            .iter()
            .any(|url| url == "http://recovered-gateway")
    );
    heartbeat.abort();
    assert!(heartbeat.await.unwrap_err().is_cancelled());
}

#[tokio::test]
async fn heartbeat_ignores_isolated_transient_health_failures() {
    let health_calls = Arc::new(AtomicUsize::new(0));
    let restart_calls = Arc::new(AtomicUsize::new(0));
    let (observed_tx, mut observed_rx) = tokio::sync::mpsc::unbounded_channel();
    let heartbeat = tokio::spawn(maintain_gateway_with(
        "127.0.0.1:47632".parse().unwrap(),
        "http://gateway".into(),
        Duration::from_millis(1),
        {
            let health_calls = health_calls.clone();
            move |_url| {
                let observed_tx = observed_tx.clone();
                let call = health_calls.fetch_add(1, Ordering::SeqCst) + 1;
                async move {
                    if call == 9 {
                        let _ = observed_tx.send(());
                    }
                    Ok(call.is_multiple_of(3))
                }
            }
        },
        {
            let restart_calls = restart_calls.clone();
            move |address, _expected_instance| {
                restart_calls.fetch_add(1, Ordering::SeqCst);
                async move {
                    Ok(crate::bootstrap::GatewayEndpoint {
                        address,
                        url: "http://gateway".into(),
                        instance_id: "gateway".into(),
                    })
                }
            }
        },
    ));

    tokio::time::timeout(Duration::from_secs(5), observed_rx.recv())
        .await
        .expect("heartbeat did not complete three transient-failure cycles")
        .expect("heartbeat stopped before completing three transient-failure cycles");
    assert!(!heartbeat.is_finished());
    assert!(health_calls.load(Ordering::SeqCst) >= 9);
    assert_eq!(restart_calls.load(Ordering::SeqCst), 0);
    heartbeat.abort();
    assert!(heartbeat.await.unwrap_err().is_cancelled());
}

#[tokio::test]
async fn heartbeat_rediscovery_consumes_the_shared_restart_allowance() {
    let restart_calls = Arc::new(AtomicUsize::new(0));
    let error = maintain_gateway_with(
        "127.0.0.1:47632".parse().unwrap(),
        "http://gateway".into(),
        Duration::from_millis(1),
        |_url| async { Ok(false) },
        {
            let restart_calls = restart_calls.clone();
            move |address, _expected_instance| {
                let restart_calls = restart_calls.clone();
                async move {
                    let attempt = restart_calls.fetch_add(1, Ordering::SeqCst);
                    Ok(crate::bootstrap::GatewayEndpoint {
                        address,
                        url: "http://gateway".into(),
                        instance_id: format!("gateway-{attempt}"),
                    })
                }
            }
        },
    )
    .await
    .unwrap_err();

    assert_eq!(restart_calls.load(Ordering::SeqCst), 1);
    assert!(error.to_string().contains("after its coordinated restart"));
}

#[tokio::test]
async fn heartbeat_exits_with_the_restart_failure() {
    let error = maintain_gateway_with(
        "127.0.0.1:47632".parse().unwrap(),
        "http://dead-gateway".into(),
        Duration::from_millis(1),
        |_url| async { Ok(false) },
        |_bind, _expected_instance| async {
            Err(CliError::Launch("coordinated restart failed".into()))
        },
    )
    .await
    .unwrap_err();

    assert!(error.to_string().contains("coordinated restart failed"));
}

#[tokio::test]
async fn heartbeat_attempts_at_most_one_successful_restart() {
    let restart_calls = Arc::new(AtomicUsize::new(0));
    let error = maintain_gateway_with(
        "127.0.0.1:47632".parse().unwrap(),
        "http://dead-gateway".into(),
        Duration::from_millis(1),
        |_url| async { Ok(false) },
        {
            let restart_calls = restart_calls.clone();
            move |address, _expected_instance| {
                let restart_calls = restart_calls.clone();
                async move {
                    restart_calls.fetch_add(1, Ordering::SeqCst);
                    Ok(crate::bootstrap::GatewayEndpoint {
                        address,
                        url: "http://still-unhealthy".into(),
                        instance_id: "still-unhealthy".into(),
                    })
                }
            }
        },
    )
    .await
    .unwrap_err();

    assert_eq!(restart_calls.load(Ordering::SeqCst), 1);
    assert!(error.to_string().contains("after its coordinated restart"));
}

#[tokio::test]
async fn old_mcp_maintenance_loop_exits_when_install_generation_is_replaced() {
    let dir = tempfile::tempdir().unwrap();
    let plugin_root = dir.path().join("plugin");
    let generation_path = plugin_root.join(GENERATION_FILE_NAME);
    let generation_lock = dir.path().join("generation-transaction.lock");
    crate::installation::generation::write_new_generation_with_token_at(
        &generation_path,
        &generation_lock,
    )
    .unwrap();
    let generation = InstallGeneration::capture(generation_path.clone()).unwrap();
    let health_calls = Arc::new(AtomicUsize::new(0));
    let restart_calls = Arc::new(AtomicUsize::new(0));
    let (observed_tx, observed_rx) = tokio::sync::oneshot::channel();
    let observed_tx = Arc::new(Mutex::new(Some(observed_tx)));
    let heartbeat = tokio::spawn(maintain_gateway_with_generation(
        "127.0.0.1:47632".parse().unwrap(),
        "http://old-gateway".into(),
        Duration::from_millis(100),
        {
            let health_calls = health_calls.clone();
            move |_url| {
                health_calls.fetch_add(1, Ordering::SeqCst);
                let observed_tx = observed_tx.clone();
                async move {
                    if let Some(sender) = observed_tx.lock().unwrap().take() {
                        let _ = sender.send(());
                    }
                    Ok(false)
                }
            }
        },
        {
            let restart_calls = restart_calls.clone();
            move |address, _expected_instance| {
                restart_calls.fetch_add(1, Ordering::SeqCst);
                async move {
                    Ok(crate::bootstrap::GatewayEndpoint {
                        address,
                        url: "http://unexpected-restart".into(),
                        instance_id: "unexpected".into(),
                    })
                }
            }
        },
        move || {
            let generation = generation.clone();
            async move { generation.verify_current().map_err(CliError::Launch) }
        },
    ));

    tokio::time::timeout(Duration::from_secs(5), observed_rx)
        .await
        .expect("old MCP maintenance loop did not perform its first health check")
        .expect("old MCP maintenance loop stopped before its first health check");
    let mut retirement = GenerationRetirement::acquire(&generation_path)
        .unwrap()
        .expect("installed generation should be retired");
    retirement.invalidate_for_replacement().unwrap();
    // Force installation swaps the whole plugin tree while retaining its external transaction
    // lock until the replacement is committed.
    std::fs::rename(&plugin_root, dir.path().join("retired-plugin")).unwrap();
    crate::installation::generation::write_staged_generation_with_token(
        &generation_path,
        &generation_lock,
    )
    .unwrap();
    retirement.commit_replacement();
    drop(retirement);

    let error = tokio::time::timeout(Duration::from_secs(5), heartbeat)
        .await
        .expect("old MCP maintenance loop did not observe generation replacement")
        .unwrap()
        .unwrap_err();
    assert!(error.to_string().contains("has been retired"));
    assert_eq!(health_calls.load(Ordering::SeqCst), 1);
    assert_eq!(restart_calls.load(Ordering::SeqCst), 0);
}

#[test]
fn invalidated_install_generation_can_be_restored_before_rollback_registration() {
    let dir = tempfile::tempdir().unwrap();
    let generation_path = dir.path().join(GENERATION_FILE_NAME);
    write_new_generation(&generation_path).unwrap();
    let original = InstallGeneration::capture(generation_path.clone()).unwrap();
    let mut retirement = GenerationRetirement::acquire(&generation_path)
        .unwrap()
        .expect("installed generation should be retired");

    retirement.invalidate_for_replacement().unwrap();
    let (result_tx, result_rx) = std::sync::mpsc::channel();
    let verifier = std::thread::spawn(move || result_tx.send(original.verify_current()).unwrap());
    assert!(
        result_rx.recv_timeout(Duration::from_millis(50)).is_err(),
        "MCP lifecycle verification observed an uncommitted retirement"
    );

    retirement.restore_after_rollback().unwrap();
    result_rx
        .recv_timeout(Duration::from_secs(1))
        .unwrap()
        .unwrap();
    verifier.join().unwrap();
    InstallGeneration::capture(generation_path).unwrap();
}

#[test]
fn retired_install_generation_remains_retryable_but_not_adoptable() {
    let dir = tempfile::tempdir().unwrap();
    let generation_path = dir.path().join(GENERATION_FILE_NAME);
    write_new_generation(&generation_path).unwrap();
    let mut retirement = GenerationRetirement::acquire(&generation_path)
        .unwrap()
        .expect("installed generation should be retired");
    retirement.invalidate_for_replacement().unwrap();
    retirement.commit_replacement();
    drop(retirement);

    let mut resumed = GenerationRetirement::acquire(&generation_path)
        .unwrap()
        .expect("a retired generation should support cleanup retry");
    resumed.invalidate_for_replacement().unwrap();
    resumed.commit_replacement();
    drop(resumed);

    let error = InstallGeneration::capture(generation_path).unwrap_err();
    assert!(error.contains("has been retired"), "{error}");
}

#[test]
fn default_mcp_gateway_uses_plugin_provider_port() {
    assert_eq!(default_mcp_bind().to_string(), "127.0.0.1:47632");
}

#[test]
fn persistent_mcp_server_contract_is_host_neutral_and_generation_fenced() {
    let server = persistent_server(
        std::path::Path::new("/opt/nemo relay/bin/nemo-relay"),
        std::path::Path::new("/tmp/plugin/.nemo-relay-generation"),
        "generation-token",
    );

    assert_eq!(server["command"], "/opt/nemo relay/bin/nemo-relay");
    assert_eq!(server["args"], json!(["mcp"]));
    assert_eq!(
        server["env"]["NEMO_RELAY_GATEWAY_BIND"],
        crate::bootstrap::DEFAULT_BIND
    );
    assert_eq!(
        server["env"]["NEMO_RELAY_MCP_GENERATION_FILE"],
        "/tmp/plugin/.nemo-relay-generation"
    );
    assert_eq!(
        server["env"]["NEMO_RELAY_MCP_GENERATION"],
        "generation-token"
    );
}