rpi-cli 0.32.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
//! Real Unix sockets with bounded synthetic peers. These tests qualify the
//! client/contract only, not a production Host service or Agent execution.
use super::*;
use serde_json::json;
use std::os::unix::fs::PermissionsExt;
use tokio::net::{UnixListener, UnixStream};

struct Endpoint {
    _directory: tempfile::TempDir,
    config: ConnectionConfig,
    listener: UnixListener,
}
impl Endpoint {
    fn new() -> Self {
        let directory = tempfile::Builder::new().prefix("hc").tempdir().unwrap();
        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
        let path = directory.path().join("s");
        let listener = UnixListener::bind(&path).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        let config = ConnectionConfig {
            socket_path: path,
            host_id: HostId::new(),
            token: AuthToken::new("fixture-only-auth-token-0123456789".into()).unwrap(),
            timeout: Duration::from_secs(2),
        };
        Self {
            _directory: directory,
            config,
            listener,
        }
    }
}
fn welcome(config: &ConnectionConfig) -> Welcome {
    Welcome {
        protocol: PROTOCOL.into(),
        version: Version::default(),
        host_id: config.host_id,
        epoch: Epoch::new(),
        capabilities: vec![
            Capability::Status,
            Capability::List,
            Capability::Inspect,
            Capability::Receipts,
            Capability::Cancel,
            Capability::Close,
        ],
        limits: Limits::default(),
    }
}
async fn authenticate(stream: &mut UnixStream, config: &ConnectionConfig, ready: &Welcome) {
    let hello: Hello = read_frame(stream, MAX_FRAME_BYTES).await.unwrap();
    assert_eq!(hello.protocol, PROTOCOL);
    assert_eq!(hello.version.major, MAJOR);
    assert_eq!(hello.host_id, config.host_id);
    assert!(hello.token.matches(&config.token));
    send(stream, ready).await;
}
async fn send(stream: &mut UnixStream, value: &impl Serialize) {
    write_frame(stream, &encode_frame(value, MAX_FRAME_BYTES).unwrap())
        .await
        .unwrap();
}
fn close_command() -> (RequestId, AgentId, Command) {
    let id = RequestId::new();
    let agent_id = AgentId::new();
    (
        id,
        agent_id,
        Command::Close {
            mutation: AgentMutation {
                request_id: id,
                agent_id,
                revision: 2,
            },
        },
    )
}

#[tokio::test]
async fn authenticated_serial_queries_and_remote_rejections_preserve_correlation() {
    let endpoint = Endpoint::new();
    let config = endpoint.config.clone();
    let client_config = config.clone();
    let ready = welcome(&config);
    let epoch = ready.epoch;
    let peer = tokio::spawn(async move {
        let _directory = endpoint._directory;
        let (mut stream, _) = endpoint.listener.accept().await.unwrap();
        authenticate(&mut stream, &config, &ready).await;
        for index in 0..3 {
            let request: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
            assert_eq!(request.epoch, epoch);
            let reply = if index == 1 {
                Reply::Error {
                    code: ErrorCode::Busy,
                }
            } else {
                Reply::Data {
                    data: json!({"sequence":index}),
                }
            };
            send(
                &mut stream,
                &Response {
                    call_id: request.call_id,
                    epoch,
                    reply,
                },
            )
            .await;
        }
        // Client detach is EOF, NOT stop/close/cancel.
        assert!(read_frame::<_, Request>(&mut stream, MAX_FRAME_BYTES)
            .await
            .is_err());
    });
    let mut client = HostClient::connect(client_config).await.unwrap();
    assert_eq!(
        client.call(Command::Status {}).await.unwrap(),
        json!({"sequence":0})
    );
    assert_eq!(
        client
            .call(Command::List {
                after: None,
                limit: 2
            })
            .await
            .unwrap_err(),
        ClientError::Rejected(ErrorCode::Busy)
    );
    assert_eq!(
        client
            .call(Command::Inspect {
                agent_id: AgentId::new()
            })
            .await
            .unwrap(),
        json!({"sequence":2})
    );
    client.detach();
    assert_eq!(
        client.call(Command::Status {}).await.unwrap_err(),
        ClientError::NotSent(Failure::Closed)
    );
    peer.await.unwrap();
}

#[tokio::test]
async fn incompatible_identity_protocol_major_and_limits_fail_before_commands() {
    for variant in 0..5 {
        let endpoint = Endpoint::new();
        let config = endpoint.config.clone();
        let client_config = config.clone();
        let mut ready = welcome(&config);
        match variant {
            0 => ready.protocol = "native-rpc-is-not-shared-host".into(),
            1 => ready.version.major += 1,
            2 => ready.host_id = HostId::new(),
            3 => ready.limits.max_frame_bytes = MAX_FRAME_BYTES + 1,
            _ => ready.limits.max_in_flight = 0,
        }
        let peer = tokio::spawn(async move {
            let _directory = endpoint._directory;
            let (mut stream, _) = endpoint.listener.accept().await.unwrap();
            authenticate(&mut stream, &config, &ready).await;
            assert!(read_frame::<_, Request>(&mut stream, MAX_FRAME_BYTES)
                .await
                .is_err());
        });
        assert_eq!(
            HostClient::connect(client_config).await.unwrap_err(),
            ClientError::NotSent(Failure::IncompatiblePeer)
        );
        peer.await.unwrap();
    }
}

#[tokio::test]
async fn capabilities_page_and_revision_validation_do_not_send_and_keep_connection_usable() {
    let endpoint = Endpoint::new();
    let config = endpoint.config.clone();
    let client_config = config.clone();
    let mut ready = welcome(&config);
    ready.version.minor = u16::MAX;
    ready.limits.max_page_size = 2;
    let peer = tokio::spawn(async move {
        let _directory = endpoint._directory;
        let (mut stream, _) = endpoint.listener.accept().await.unwrap();
        authenticate(&mut stream, &config, &ready).await;
        let request: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
        assert!(matches!(request.command, Command::Status {}));
        send(
            &mut stream,
            &Response {
                call_id: request.call_id,
                epoch: ready.epoch,
                reply: Reply::Data {
                    data: json!({"ok":true}),
                },
            },
        )
        .await;
    });
    let mut client = HostClient::connect(client_config).await.unwrap();
    for limit in [0, 3, usize::MAX] {
        assert_eq!(
            client
                .call(Command::List { after: None, limit })
                .await
                .unwrap_err(),
            ClientError::NotSent(Failure::InvalidCommand)
        );
    }
    let (_, _, mut close) = close_command();
    if let Command::Close { mutation } = &mut close {
        mutation.revision = 0;
    }
    assert_eq!(
        client.call(close).await.unwrap_err(),
        ClientError::NotSent(Failure::InvalidCommand)
    );
    assert_eq!(
        client
            .call(Command::Stop {
                request_id: RequestId::new()
            })
            .await
            .unwrap_err(),
        ClientError::NotSent(Failure::UnsupportedCapability)
    );
    assert_eq!(
        client.call(Command::Status {}).await.unwrap(),
        json!({"ok":true})
    );
    peer.await.unwrap();
}

#[tokio::test]
async fn mutation_eof_bad_correlation_epoch_or_frame_is_unknown_and_never_retried() {
    for variant in 0..5 {
        let endpoint = Endpoint::new();
        let config = endpoint.config.clone();
        let client_config = config.clone();
        let ready = welcome(&config);
        let (request_id, _, command) = close_command();
        let peer = tokio::spawn(async move {
            let _directory = endpoint._directory;
            let (mut stream, _) = endpoint.listener.accept().await.unwrap();
            authenticate(&mut stream, &config, &ready).await;
            let request: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
            assert_eq!(request.command.request_id(), Some(request_id));
            match variant {
                0 => return, // EOF after a possibly committed mutation.
                1 | 2 => {
                    send(
                        &mut stream,
                        &Response {
                            call_id: if variant == 1 {
                                CallId::new()
                            } else {
                                request.call_id
                            },
                            epoch: if variant == 2 {
                                Epoch::new()
                            } else {
                                request.epoch
                            },
                            reply: Reply::Data {
                                data: json!({"ok":true}),
                            },
                        },
                    )
                    .await
                }
                3 => {
                    stream.write_u32(u32::MAX).await.unwrap();
                }
                _ => {
                    write_frame(&mut stream, b"not-json").await.unwrap();
                }
            }
            assert!(read_frame::<_, Request>(&mut stream, MAX_FRAME_BYTES)
                .await
                .is_err());
        });
        let mut client = HostClient::connect(client_config).await.unwrap();
        let expected = [
            Failure::Connection,
            Failure::Correlation,
            Failure::EpochChanged,
            Failure::FrameTooLarge,
            Failure::MalformedFrame,
        ][variant];
        assert_eq!(
            client.call(command.clone()).await.unwrap_err(),
            ClientError::OutcomeUnknown {
                request_id,
                reason: expected
            }
        );
        assert_eq!(
            client.call(command).await.unwrap_err(),
            ClientError::NotSent(Failure::Closed)
        );
        peer.await.unwrap();
    }
}

#[tokio::test]
async fn result_query_requires_its_capability_and_is_never_a_mutation() {
    for supported in [false, true] {
        let endpoint = Endpoint::new();
        let config = endpoint.config.clone();
        let client_config = config.clone();
        let mut ready = welcome(&config);
        // A v1.4 peer can serve old commands without granting results.
        ready.version.minor = if supported { MINOR } else { 4 };
        if supported {
            ready.capabilities.push(Capability::Results);
        }
        let peer = tokio::spawn(async move {
            let _directory = endpoint._directory;
            let (mut stream, _) = endpoint.listener.accept().await.unwrap();
            authenticate(&mut stream, &config, &ready).await;
            if supported {
                let request: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
                assert!(matches!(request.command, Command::Result { .. }));
                assert!(request.command.request_id().is_none());
                // Deliberately lose a read-only response, never an execution.
            } else {
                assert!(read_frame::<_, Request>(&mut stream, MAX_FRAME_BYTES)
                    .await
                    .is_err());
            }
        });
        let mut client = HostClient::connect(client_config).await.unwrap();
        let command = Command::Result {
            agent_id: AgentId::new(),
            request_id: RequestId::new(),
            run_id: None,
            offset: 0,
            max_bytes: 4096,
        };
        let error = client.call(command.clone()).await.unwrap_err();
        if supported {
            assert!(matches!(error, ClientError::QueryFailed(_)));
            assert_eq!(
                client.call(command).await.unwrap_err(),
                ClientError::NotSent(Failure::Closed)
            );
        } else {
            assert_eq!(error, ClientError::NotSent(Failure::UnsupportedCapability));
        }
        drop(client);
        peer.await.unwrap();
    }
}

#[tokio::test]
async fn query_failure_is_not_a_mutation_receipt_and_poisoned_socket_is_closed() {
    let endpoint = Endpoint::new();
    let config = endpoint.config.clone();
    let client_config = config.clone();
    let ready = welcome(&config);
    let peer = tokio::spawn(async move {
        let _directory = endpoint._directory;
        let (mut stream, _) = endpoint.listener.accept().await.unwrap();
        authenticate(&mut stream, &config, &ready).await;
        let _: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
        write_frame(&mut stream, b"{\"private-path\":\"do-not-echo\"}")
            .await
            .unwrap();
    });
    let mut client = HostClient::connect(client_config).await.unwrap();
    let error = client.call(Command::Status {}).await.unwrap_err();
    assert_eq!(error, ClientError::QueryFailed(Failure::MalformedFrame));
    assert!(!error.to_string().contains("do-not-echo"));
    assert_eq!(
        client.call(Command::Status {}).await.unwrap_err(),
        ClientError::NotSent(Failure::Closed)
    );
    peer.await.unwrap();
}

#[tokio::test]
async fn timeout_preserves_request_id_for_explicit_receipt_query_on_new_connection() {
    let endpoint = Endpoint::new();
    let config = endpoint.config.clone();
    let mut client_config = config.clone();
    client_config.timeout = Duration::from_millis(100);
    let ready = welcome(&config);
    let epoch = ready.epoch;
    let (request_id, agent_id, command) = close_command();
    let peer = tokio::spawn(async move {
        let _directory = endpoint._directory;
        let (mut first, _) = endpoint.listener.accept().await.unwrap();
        authenticate(&mut first, &config, &ready).await;
        let request: Request = read_frame(&mut first, MAX_FRAME_BYTES).await.unwrap();
        assert_eq!(request.command.request_id(), Some(request_id));
        assert!(read_frame::<_, Request>(&mut first, MAX_FRAME_BYTES)
            .await
            .is_err());
        let (mut second, _) = endpoint.listener.accept().await.unwrap();
        authenticate(&mut second, &config, &ready).await;
        let query: Request = read_frame(&mut second, MAX_FRAME_BYTES).await.unwrap();
        assert!(matches!(
            query.command,
            Command::Receipt {
                agent_id: queried_agent,
                request_id: queried_request,
            } if queried_agent == agent_id && queried_request == request_id
        ));
        send(
            &mut second,
            &Response {
                call_id: query.call_id,
                epoch,
                reply: Reply::Data {
                    data: json!({"state":"outcome_unknown"}),
                },
            },
        )
        .await;
    });
    let mut first = HostClient::connect(client_config.clone()).await.unwrap();
    assert_eq!(
        first.call(command).await.unwrap_err(),
        ClientError::OutcomeUnknown {
            request_id,
            reason: Failure::Timeout
        }
    );
    client_config.timeout = Duration::from_secs(2);
    let mut second = HostClient::connect(client_config).await.unwrap();
    assert_eq!(
        second
            .call(Command::Receipt {
                agent_id,
                request_id
            })
            .await
            .unwrap(),
        json!({"state":"outcome_unknown"})
    );
    peer.await.unwrap();
}

#[tokio::test]
async fn dropping_a_waiter_retires_the_socket_without_canceling_remote_work() {
    let endpoint = Endpoint::new();
    let config = endpoint.config.clone();
    let client_config = config.clone();
    let ready = welcome(&config);
    let (received, receipt) = tokio::sync::oneshot::channel();
    let peer = tokio::spawn(async move {
        let _directory = endpoint._directory;
        let (mut stream, _) = endpoint.listener.accept().await.unwrap();
        authenticate(&mut stream, &config, &ready).await;
        let _: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
        received.send(()).unwrap();
        assert!(read_frame::<_, Request>(&mut stream, MAX_FRAME_BYTES)
            .await
            .is_err());
    });
    let mut client = HostClient::connect(client_config).await.unwrap();
    {
        let pending = client.call(close_command().2);
        tokio::pin!(pending);
        tokio::select! {
            _ = receipt => {},
            result = &mut pending => panic!("peer has not answered: {result:?}"),
        }
        // Drop the exchange future while the peer still owns its operation.
    }
    assert_eq!(
        client.call(Command::Status {}).await.unwrap_err(),
        ClientError::NotSent(Failure::Closed)
    );
    peer.await.unwrap();
}

#[tokio::test]
async fn endpoint_requires_private_current_uid_directory_and_socket_and_rejects_links() {
    let endpoint = Endpoint::new();
    let path = &endpoint.config.socket_path;
    let parent = path.parent().unwrap();
    assert!(check_endpoint(path).await.is_ok());
    std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o755)).unwrap();
    assert_eq!(
        check_endpoint(path).await.unwrap_err(),
        Failure::UnsafeEndpoint
    );
    std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).unwrap();
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660)).unwrap();
    assert_eq!(
        check_endpoint(path).await.unwrap_err(),
        Failure::UnsafeEndpoint
    );
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
    let linked = parent.join("link");
    std::os::unix::fs::symlink(path, &linked).unwrap();
    assert_eq!(
        check_endpoint(&linked).await.unwrap_err(),
        Failure::UnsafeEndpoint
    );
    let file = parent.join("file");
    std::fs::write(&file, "not a socket").unwrap();
    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();
    assert_eq!(
        check_endpoint(&file).await.unwrap_err(),
        Failure::UnsafeEndpoint
    );
    let mut config = endpoint.config.clone();
    config.socket_path = PathBuf::from("relative");
    assert_eq!(
        HostClient::connect(config).await.unwrap_err(),
        ClientError::NotSent(Failure::InvalidConfiguration)
    );
    let mut config = endpoint.config.clone();
    config.timeout = Duration::ZERO;
    assert_eq!(
        HostClient::connect(config).await.unwrap_err(),
        ClientError::NotSent(Failure::InvalidConfiguration)
    );
    let mut config = endpoint.config.clone();
    config.socket_path = linked;
    assert_eq!(
        HostClient::connect(config).await.unwrap_err(),
        ClientError::NotSent(Failure::UnsafeEndpoint)
    );
    assert!(!format!("{:?}", endpoint.config).contains(&path.to_string_lossy().to_string()));
}

#[tokio::test]
async fn handshake_deadline_covers_partial_frames_and_no_automatic_reconnect() {
    let endpoint = Endpoint::new();
    let mut config = endpoint.config.clone();
    config.timeout = Duration::from_millis(100);
    let peer = tokio::spawn(async move {
        let _directory = endpoint._directory;
        let (mut stream, _) = endpoint.listener.accept().await.unwrap();
        let _: Hello = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
        stream.write_u32(100).await.unwrap();
        stream.write_all(b"{").await.unwrap();
        // The client times out instead of accepting a partial hello, retrying,
        // or leaving a background reader alive.
        let mut byte = [0];
        assert_eq!(stream.read(&mut byte).await.unwrap(), 0);
    });
    assert_eq!(
        HostClient::connect(config).await.unwrap_err(),
        ClientError::NotSent(Failure::Timeout)
    );
    peer.await.unwrap();
}

#[tokio::test]
async fn frame_lengths_checked_before_body_and_json_is_strict() {
    for length in [0, (MAX_FRAME_BYTES + 1) as u32, u32::MAX] {
        let (mut writer, mut reader) = tokio::io::duplex(8);
        writer.write_u32(length).await.unwrap();
        assert_eq!(
            read_frame::<_, serde_json::Value>(&mut reader, MAX_FRAME_BYTES)
                .await
                .unwrap_err(),
            Failure::FrameTooLarge
        );
    }
    for bytes in [b"{} trailing".as_slice(), b"{", b"{\"x\":1}\n{\"x\":2}"] {
        let (mut writer, mut reader) = tokio::io::duplex(64);
        write_frame(&mut writer, bytes).await.unwrap();
        assert_eq!(
            read_frame::<_, serde_json::Value>(&mut reader, MAX_FRAME_BYTES)
                .await
                .unwrap_err(),
            Failure::MalformedFrame
        );
    }
    assert_eq!(
        encode_frame(&json!({"large":"1234567890"}), 5).unwrap_err(),
        Failure::FrameTooLarge
    );
}

#[tokio::test]
async fn administrative_execution_lost_reply_retains_original_mutation_identity() {
    for operation in 0..5 {
        for wait_for_timeout in [false, true] {
            let endpoint = Endpoint::new();
            let config = endpoint.config.clone();
            let client_config = config.clone();
            let mut ready = welcome(&config);
            ready.capabilities.extend([
                Capability::AdministrativeCreate,
                Capability::AdministrativeRestore,
                Capability::AdministrativeClose,
                Capability::AdministrativeCancel,
                Capability::AdministrativeStop,
            ]);
            let agent_id = AgentId::new();
            let profile = ProfileRef {
                agent_id,
                version: ProfileVersion::new(),
            };
            let action = match operation {
                0 => AdministrativeAction::CreateProfile { profile },
                1 => AdministrativeAction::RestoreProfile {
                    profile,
                    revision: 1,
                },
                2 => AdministrativeAction::Close {
                    agent_id,
                    revision: 1,
                },
                3 => AdministrativeAction::CancelSubmitted {
                    agent_id,
                    revision: 1,
                    submitted_request_id: RequestId::new(),
                },
                _ => AdministrativeAction::Stop {},
            };
            let intent = AdministrativeRequest {
                scope: ControlScopeId::new(),
                request_id: RequestId::new(),
                epoch: ready.epoch,
                action,
            };
            let id = intent.request_id;
            let command = match operation {
                0 => Command::AdministrativeCreate { request: intent },
                1 => Command::AdministrativeRestore { request: intent },
                2 => Command::AdministrativeClose { request: intent },
                3 => Command::AdministrativeCancel { request: intent },
                _ => Command::AdministrativeStop { request: intent },
            };
            let (release, released) = tokio::sync::oneshot::channel::<()>();
            let peer = tokio::spawn(async move {
                let _directory = endpoint._directory;
                let (mut stream, _) = endpoint.listener.accept().await.unwrap();
                authenticate(&mut stream, &config, &ready).await;
                let request: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
                assert_eq!(request.command.request_id(), Some(id));
                assert!(request.command.valid(Limits::default()));
                if wait_for_timeout {
                    let _ = released.await;
                }
            });
            let mut client = HostClient::connect(client_config).await.unwrap();
            let failure = client.call(command).await.unwrap_err();
            assert!(
                matches!(failure, ClientError::OutcomeUnknown { request_id, .. } if request_id == id)
            );
            if wait_for_timeout {
                assert!(matches!(
                    failure,
                    ClientError::OutcomeUnknown {
                        reason: Failure::Timeout,
                        ..
                    }
                ));
            }
            let _ = release.send(());
            peer.await.unwrap();
        }
    }
}

#[tokio::test]
async fn administrative_receipt_disconnect_and_timeout_are_queries_not_unknown_mutations() {
    for wait_for_timeout in [false, true] {
        let endpoint = Endpoint::new();
        let config = endpoint.config.clone();
        let client_config = config.clone();
        let mut ready = welcome(&config);
        ready.capabilities.push(Capability::AdministrativeReceipts);
        let target = AdministrativeRequest {
            scope: ControlScopeId::new(),
            request_id: RequestId::new(),
            epoch: Epoch::new(),
            action: AdministrativeAction::Stop {},
        };
        let expected = target.clone();
        let (release, released) = tokio::sync::oneshot::channel::<()>();
        let peer = tokio::spawn(async move {
            let _directory = endpoint._directory;
            let (mut stream, _) = endpoint.listener.accept().await.unwrap();
            authenticate(&mut stream, &config, &ready).await;
            let request: Request = read_frame(&mut stream, MAX_FRAME_BYTES).await.unwrap();
            assert_eq!(request.epoch, ready.epoch);
            assert_ne!(request.epoch, expected.epoch);
            assert_eq!(request.command.request_id(), None);
            assert!(
                matches!(request.command, Command::AdministrativeReceipt { request } if request == expected)
            );
            if wait_for_timeout {
                let _ = released.await;
            }
        });
        let mut client = HostClient::connect(client_config).await.unwrap();
        let failure = client
            .call(Command::AdministrativeReceipt { request: target })
            .await
            .unwrap_err();
        if wait_for_timeout {
            assert_eq!(failure, ClientError::QueryFailed(Failure::Timeout));
        } else {
            assert!(matches!(failure, ClientError::QueryFailed(_)));
        }
        assert_eq!(
            client.call(Command::Status {}).await.unwrap_err(),
            ClientError::NotSent(Failure::Closed)
        );
        let _ = release.send(());
        peer.await.unwrap();
    }
}

#[tokio::test]
async fn mini_minor_gate_and_lost_replies_preserve_full_volatile_intent_without_retry() {
    for case in 0..3 {
        let endpoint = Endpoint::new();
        let config = endpoint.config.clone();
        let client_config = config.clone();
        let mut ready = welcome(&config);
        ready.version.minor = if case == 0 { 5 } else { 6 };
        ready.capabilities.push(Capability::Mini);
        let intent = MiniRequest {
            scope: ControlScopeId::new(),
            epoch: Epoch::new(),
            request_id: RequestId::new(),
            action: MiniAction::Submit {
                agent_id: AgentId::new(),
                prompt: "literal {{mini}}".into(),
            },
        };
        let expected = intent.clone();
        let peer = tokio::spawn(async move {
            let _directory = endpoint._directory;
            let (mut stream, _) = endpoint.listener.accept().await.unwrap();
            authenticate(&mut stream, &config, &ready).await;
            let frame = read_frame::<_, Request>(&mut stream, MAX_FRAME_BYTES).await;
            if case == 0 {
                assert!(frame.is_err());
            } else {
                let frame = frame.unwrap();
                assert_eq!(frame.epoch, ready.epoch);
                match frame.command {
                    Command::MiniExecute { request } if case == 1 => assert_eq!(request, expected),
                    Command::MiniReceipt { request } if case == 2 => assert_eq!(request, expected),
                    _ => panic!("Mini intent was rewritten"),
                }
                // Deliberately lose the reply. Never replay in this client.
            }
        });
        let mut client = HostClient::connect(client_config).await.unwrap();
        let command = if case == 2 {
            Command::MiniReceipt {
                request: intent.clone(),
            }
        } else {
            Command::MiniExecute {
                request: intent.clone(),
            }
        };
        let error = client.call(command).await.unwrap_err();
        match case {
            0 => assert_eq!(error, ClientError::NotSent(Failure::UnsupportedCapability)),
            1 => assert!(
                matches!(error, ClientError::OutcomeUnknown { request_id, .. } if request_id == intent.request_id)
            ),
            _ => assert!(matches!(error, ClientError::QueryFailed(_))),
        }
        client.detach();
        peer.await.unwrap();
    }
}