rpi-cli 0.35.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
// Included inside ordinary::tests::owner_registry::admission_faults.
use super::*;
use rpi_tools::env::{FileContent, ReadFile, WriterLease};
use rpi_tools::{FileError, FileErrorCode};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

struct SyncFault {
    fail: AtomicBool,
    block_once: AtomicBool,
    entered: Semaphore,
    release: Semaphore,
    blocked_sync_completed: Semaphore,
    calls: AtomicUsize,
}
impl SyncFault {
    fn new(fail: bool) -> Arc<Self> {
        Arc::new(Self {
            fail: AtomicBool::new(fail),
            block_once: AtomicBool::new(false),
            entered: Semaphore::new(0),
            release: Semaphore::new(0),
            blocked_sync_completed: Semaphore::new(0),
            calls: AtomicUsize::new(0),
        })
    }
}
struct FaultFs {
    inner: Arc<dyn FileSystem>,
    fault: Arc<SyncFault>,
}
macro_rules! delegate {
    ($($name:ident($($arg:ident: $ty:ty),*) -> $ret:ty;)*) => {
        #[async_trait]
        impl FileSystem for FaultFs {
            fn cwd(&self) -> &Path { self.inner.cwd() }
            async fn cleanup(&self) { self.inner.cleanup().await; }
            async fn sync_file_and_parent(&self, path: &str, cancel: Option<&CancellationToken>) -> Result<(), FileError> {
                self.fault.calls.fetch_add(1, Ordering::SeqCst);
                let blocked = self.fault.block_once.swap(false, Ordering::SeqCst);
                if blocked {
                    self.fault.entered.add_permits(1);
                    self.fault.release.acquire().await.unwrap().forget();
                }
                if self.fault.fail.load(Ordering::SeqCst) {
                    self.inner.sync_file(path, false, cancel).await?;
                    return Err(FileError::new(FileErrorCode::Unknown, "injected private sync failure"));
                }
                self.inner.sync_file_and_parent(path, cancel).await?;
                if blocked {
                    self.fault.blocked_sync_completed.add_permits(1);
                }
                Ok(())
            }
            $(async fn $name(&self, $($arg: $ty),*) -> Result<$ret, FileError> {
                self.inner.$name($($arg),*).await
            })*
        }
    };
}
delegate! {
    absolute_path(path: &str, cancel: Option<&CancellationToken>) -> std::path::PathBuf;
    join_path(parts: &[&str], cancel: Option<&CancellationToken>) -> std::path::PathBuf;
    read_text_file(path: &str, cancel: Option<&CancellationToken>) -> String;
    read_text_lines(path: &str, max_lines: Option<usize>, cancel: Option<&CancellationToken>) -> Vec<String>;
    read_binary_file(path: &str, cancel: Option<&CancellationToken>) -> Vec<u8>;
    write_file(path: &str, content: FileContent, cancel: Option<&CancellationToken>) -> ();
    append_file(path: &str, content: FileContent, cancel: Option<&CancellationToken>) -> ();
    open_append_file(path: &str) -> Option<Box<dyn rpi_tools::env::AppendFile>>;
    open_read_file(path: &str) -> Option<Arc<dyn ReadFile>>;
    try_acquire_writer_lease(path: &str) -> Option<Box<dyn WriterLease>>;
    sync_file(path: &str, data_only: bool, cancel: Option<&CancellationToken>) -> ();
    sync_directory(path: &str, cancel: Option<&CancellationToken>) -> ();
    truncate_file(path: &str, len: u64, cancel: Option<&CancellationToken>) -> ();
    rename_file(source: &str, dest: &str, cancel: Option<&CancellationToken>) -> ();
    file_info(path: &str, cancel: Option<&CancellationToken>) -> rpi_tools::env::FileInfo;
    list_dir(path: &str, cancel: Option<&CancellationToken>) -> Vec<rpi_tools::env::FileInfo>;
    canonical_path(path: &str, cancel: Option<&CancellationToken>) -> std::path::PathBuf;
    exists(path: &str, cancel: Option<&CancellationToken>) -> bool;
    create_dir(path: &str, recursive: bool, cancel: Option<&CancellationToken>) -> ();
    remove(path: &str, recursive: bool, force: bool, cancel: Option<&CancellationToken>) -> ();
    create_temp_dir(prefix: Option<&str>, cancel: Option<&CancellationToken>) -> std::path::PathBuf;
    create_temp_file(prefix: &str, suffix: &str, cancel: Option<&CancellationToken>) -> std::path::PathBuf;
}

async fn fault_restore(
    service: &HostService,
    fixture: &Fixture,
    record: &AgentRecord,
    provider: Arc<FauxProvider>,
    tool_gate: Option<Arc<Gate>>,
    fault: Arc<SyncFault>,
) -> OrdinaryClient {
    service
        .restore_bound(
            record.spec.id,
            fixture.catalog.guard(record),
            OrdinaryLimits::default(),
            OrdinaryBinding {
                environment: None,
                binder: BindingResolver::Immediate(binder(provider, tool_gate, None)),
                instruction_resources: None,
                extensions: None,
                filesystem: Some(Arc::new(FaultFs {
                    inner: Arc::new(OsExecutionEnv::with_cwd(record.spec.launch.cwd.clone())),
                    fault,
                })),
            },
        )
        .await
        .unwrap()
}
async fn settled(client: &OrdinaryClient) {
    tokio::time::timeout(DEADLINE, async {
        loop {
            match client.snapshot().await {
                Ok(snapshot)
                    if snapshot.active.is_none() && snapshot.record.state == AgentState::Idle =>
                {
                    break
                }
                Ok(_) | Err(BackendError::Busy) => {}
                Err(error) => panic!("unexpected snapshot error: {error}"),
            }
            tokio::time::sleep(Duration::from_millis(2)).await;
        }
    })
    .await
    .unwrap();
}

#[tokio::test(flavor = "current_thread")]
async fn backend_sync_failure_retry_and_receipt_fail_closed_until_reproved() {
    let fixture = Fixture::new(1).await;
    let service = HostService::new(fixture.catalog.clone());
    let provider = FauxProvider::new(FauxScript::new().with_text("must-not-execute"));
    let record = fixture.record("sync-fail", &provider, false).await;
    let fault = SyncFault::new(true);
    let client = fault_restore(&service, &fixture, &record, provider, None, fault.clone()).await;
    let id = uuid::Uuid::now_v7().to_string();
    let messages = vec![UserMessage::new("uncertain custody", 0).into()];
    let ticket = client
        .submit_admitted("host".into(), id.clone(), messages.clone())
        .await
        .unwrap();
    assert!(matches!(
        ticket.wait_admitted().await,
        Err(BackendError::AdmissionUncertain)
    ));
    let report = ticket.wait().await.unwrap();
    assert!(matches!(
        report.outcome,
        Err(BackendError::AdmissionUncertain)
    ));
    let visible = bytes(&record);
    assert!(String::from_utf8_lossy(&visible).contains(&id));
    assert!(!String::from_utf8_lossy(&visible).contains("operation_started"));
    for _ in 0..2 {
        assert!(matches!(
            client
                .submit_admitted("host".into(), id.clone(), messages.clone())
                .await,
            Err(BackendError::AdmissionUncertain)
        ));
        assert!(matches!(
            client.admission(&id).await,
            Err(BackendError::AdmissionUncertain)
        ));
        assert!(matches!(
            client.admissions().await,
            Err(BackendError::AdmissionUncertain)
        ));
    }
    assert_eq!(bytes(&record), visible);
    // Identity conflicts must not be "repaired" into another request's receipt.
    assert!(matches!(
        client
            .submit_admitted("other-host".into(), id.clone(), messages.clone())
            .await,
        Err(BackendError::Admission(_))
    ));
    fault.fail.store(false, Ordering::SeqCst);
    let replay = client
        .submit_admitted("host".into(), id.clone(), messages)
        .await
        .unwrap();
    assert_eq!(replay.wait_admitted().await.unwrap().entry_seq, 1);
    assert!(matches!(
        replay.wait().await.unwrap().outcome,
        Ok(OrdinaryOutput::AlreadyAdmitted)
    ));
    assert_eq!(
        bytes(&record),
        visible,
        "re-proving custody must not execute or append"
    );
    assert!(fault.calls.load(Ordering::SeqCst) >= 8);
    assert!(matches!(
        client.admission(&id).await.unwrap().unwrap().execution,
        rpi_harness::agent_harness::HostAdmissionExecution::Admitted {}
    ));
    service.shutdown().await.unwrap();
}

#[tokio::test(flavor = "current_thread")]
async fn active_run_retry_requires_a_new_barrier_without_reexecuting_or_cancelling() {
    let fixture = Fixture::new(1).await;
    let service = HostService::new(fixture.catalog.clone());
    let gate = Gate::new();
    let fault = SyncFault::new(false);
    let provider = FauxProvider::new(
        FauxScript::new()
            .with_tool_call("gate", serde_json::json!({}))
            .with_text("once"),
    );
    let record = fixture.record("sync-active", &provider, true).await;
    let client = fault_restore(
        &service,
        &fixture,
        &record,
        provider,
        Some(gate.clone()),
        fault.clone(),
    )
    .await;
    let id = uuid::Uuid::now_v7().to_string();
    let messages = vec![UserMessage::new("execute once", 0).into()];
    let ticket = client
        .submit_admitted("host".into(), id.clone(), messages.clone())
        .await
        .unwrap();
    let receipt = ticket.wait_admitted().await.unwrap();
    permits(&gate.entered, 1).await;
    let active_run = client.snapshot().await.unwrap().active.unwrap().run_id;
    fault.fail.store(true, Ordering::SeqCst);
    assert!(matches!(
        client
            .submit_admitted("host".into(), id.clone(), messages.clone())
            .await,
        Err(BackendError::AdmissionUncertain)
    ));
    assert!(matches!(
        client.admission(&id).await,
        Err(BackendError::AdmissionUncertain)
    ));
    assert_eq!(
        client.snapshot().await.unwrap().active.unwrap().run_id,
        active_run
    );
    fault.fail.store(false, Ordering::SeqCst);
    let replay = client
        .submit_admitted("host".into(), id, messages)
        .await
        .unwrap();
    assert_eq!(*replay.wait_admitted().await.unwrap(), *receipt);
    assert!(matches!(
        replay.wait().await.unwrap().outcome,
        Ok(OrdinaryOutput::AlreadyAdmitted)
    ));
    assert_eq!(gate.entered.available_permits(), 0);
    gate.release.add_permits(1);
    assert!(matches!(
        ticket.wait().await.unwrap().outcome,
        Ok(OrdinaryOutput::Run(_))
    ));
    service.shutdown().await.unwrap();
}

#[tokio::test(flavor = "current_thread")]
async fn ipc_sync_failure_never_returns_a_durable_receipt_from_visible_bytes() {
    use crate::host::{
        client::{ClientError, HostClient},
        protocol::{Command, ErrorCode, RequestId},
    };
    let (fixture, mut daemon, connection) = daemon_fixture().await;
    let provider = FauxProvider::new(FauxScript::new().with_text("never"));
    let record = fixture.record("sync-ipc", &provider, false).await;
    let fault = SyncFault::new(true);
    let client = fault_restore(
        daemon.service(),
        &fixture,
        &record,
        provider,
        None,
        fault.clone(),
    )
    .await;
    let mut ipc = HostClient::connect(connection).await.unwrap();
    let agent_id = record.spec.id.to_string().try_into().unwrap();
    let request_id = RequestId::new();
    let submit = Command::Submit {
        agent_id,
        request_id,
        prompt: "IPC uncertain input".into(),
    };
    let receipt = Command::Receipt {
        agent_id,
        request_id,
    };
    assert_eq!(
        ipc.call(submit.clone()).await,
        Err(ClientError::Rejected(ErrorCode::PersistenceUncertain))
    );
    settled(&client).await;
    let visible = bytes(&record);
    assert_eq!(
        ipc.call(submit.clone()).await,
        Err(ClientError::Rejected(ErrorCode::PersistenceUncertain))
    );
    assert_eq!(
        ipc.call(receipt.clone()).await,
        Err(ClientError::Rejected(ErrorCode::PersistenceUncertain))
    );
    assert_eq!(bytes(&record), visible);
    let absent = ipc
        .call(Command::Receipt {
            agent_id,
            request_id: RequestId::new(),
        })
        .await
        .unwrap();
    assert_eq!(absent["found"], false);
    fault.fail.store(false, Ordering::SeqCst);
    let observed = ipc.call(receipt).await.unwrap();
    assert_eq!(observed["found"], true);
    assert_eq!(observed["execution"]["state"], "admitted");
    assert_eq!(
        ipc.call(submit).await.unwrap()["receipt"],
        observed["receipt"]
    );
    assert_eq!(bytes(&record), visible);
    daemon.shutdown().await.unwrap();
}

#[tokio::test(flavor = "current_thread")]
async fn ipc_admission_timeout_keeps_the_native_sync_and_run_owned() {
    use crate::host::{
        client::{ClientError, HostClient},
        protocol::{Command, RequestId},
    };
    let (fixture, mut daemon, connection) = daemon_fixture().await;
    let provider = FauxProvider::new(
        FauxScript::new()
            .with_tool_call("gate", serde_json::json!({}))
            .with_text("after-disconnect"),
    );
    let record = fixture.record("sync-disconnect", &provider, true).await;
    let fault = SyncFault::new(false);
    fault.block_once.store(true, Ordering::SeqCst);
    let tool = Gate::new();
    let client = fault_restore(
        daemon.service(),
        &fixture,
        &record,
        provider,
        Some(tool.clone()),
        fault.clone(),
    )
    .await;
    let mut short = connection.clone();
    short.timeout = Duration::from_millis(100);
    let mut ipc = HostClient::connect(short).await.unwrap();
    let agent_id = record.spec.id.to_string().try_into().unwrap();
    let request_id = RequestId::new();
    let submit = Command::Submit {
        agent_id,
        request_id,
        prompt: "disconnect while syncing".into(),
    };
    let call = tokio::spawn(async move { ipc.call(submit).await });
    permits(&fault.entered, 1).await;
    assert!(
        matches!(call.await.unwrap(), Err(ClientError::OutcomeUnknown { request_id: id, .. }) if id == request_id)
    );
    assert_eq!(tool.entered.available_permits(), 0);
    let mut ipc = HostClient::connect(connection).await.unwrap();
    assert_eq!(ipc.call(Command::Status {}).await.unwrap()["owners"], 1);
    fault.release.add_permits(1);
    permits(&tool.entered, 1).await;
    let receipt = Command::Receipt {
        agent_id,
        request_id,
    };
    assert_eq!(ipc.call(receipt.clone()).await.unwrap()["found"], true);
    tool.release.add_permits(1);
    settled(&client).await;
    let observed = ipc.call(receipt).await.unwrap();
    assert_eq!(observed["execution"]["finished"], true);
    assert!(String::from_utf8_lossy(&bytes(&record)).contains("after-disconnect"));
    assert_eq!(client.admissions().await.unwrap().len(), 1);
    daemon.shutdown().await.unwrap();
}

#[tokio::test(flavor = "current_thread")]
async fn cancelled_receipt_wait_retains_the_barrier_without_executing_input() {
    use crate::host::{
        client::{ClientError, HostClient},
        protocol::{Command, RequestId},
    };
    let (fixture, mut daemon, connection) =
        daemon_fixture_with_timeout(Duration::from_secs(1)).await;
    let provider = FauxProvider::new(FauxScript::new().with_text("must-not-run"));
    let record = fixture.record("sync-query-cancel", &provider, false).await;
    let fault = SyncFault::new(true);
    let client = fault_restore(
        daemon.service(),
        &fixture,
        &record,
        provider,
        None,
        fault.clone(),
    )
    .await;
    let request_id = RequestId::new();
    let ticket = client
        .submit_admitted(
            String::from(connection.host_id),
            String::from(request_id),
            vec![UserMessage::new("unexecuted input", 0).into()],
        )
        .await
        .unwrap();
    assert!(ticket.wait_admitted().await.is_err());
    assert!(matches!(
        ticket.wait().await.unwrap().outcome,
        Err(BackendError::AdmissionUncertain)
    ));
    let visible = bytes(&record);
    fault.fail.store(false, Ordering::SeqCst);
    fault.block_once.store(true, Ordering::SeqCst);
    // Let the server's dispatch deadline drop the native observation future,
    // not just the client-side waiter. The storage-owned barrier must survive.
    let mut ipc = HostClient::connect(connection.clone()).await.unwrap();
    let agent_id = record.spec.id.to_string().try_into().unwrap();
    let query = Command::Receipt {
        agent_id,
        request_id,
    };
    let waiting_query = query.clone();
    let wait = tokio::spawn(async move { ipc.call(waiting_query).await });
    permits(&fault.entered, 1).await;
    assert!(matches!(
        wait.await.unwrap(),
        Err(ClientError::QueryFailed(_))
    ));
    let mut ipc = HostClient::connect(connection).await.unwrap();
    assert_eq!(ipc.call(Command::Status {}).await.unwrap()["owners"], 1);
    fault.release.add_permits(1);
    // The synchronization entered by the cancelled request must complete.
    // Wait for it before starting a second request with its own deadline.
    permits(&fault.blocked_sync_completed, 1).await;
    let observed = ipc.call(query).await.unwrap();
    assert_eq!(observed["found"], true);
    assert_eq!(observed["execution"]["state"], "admitted");
    assert_eq!(bytes(&record), visible);
    daemon.shutdown().await.unwrap();
}