rpi-cli 0.24.2

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
use super::*;
fn put(p: impl AsRef<Path>, b: impl AsRef<[u8]>) {
    fs::create_dir_all(p.as_ref().parent().unwrap()).unwrap();
    fs::write(p, b).unwrap();
}
fn options(op: &str, kind: Kind, name: &str, source: Option<PathBuf>) -> Options {
    Options {
        op: op.into(),
        kind: Some(kind),
        name: Some(name.into()),
        scope: Some(Scope::Project),
        source,
        ..Default::default()
    }
}
fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {
    let d = tempfile::tempdir().unwrap();
    let root = d.path().join("native");
    let source = d.path().join("source");
    put(
        source.join("SKILL.md"),
        "---\nname: demo\ndescription: fixture\n---\nbody",
    );
    fs::create_dir(&root).unwrap();
    (d, root, source)
}

#[test]
fn leases_distinguish_contention_from_errors_and_keep_observation_guard() {
    let (_dir, root, _) = fixture();
    let (guard, busy) = observation_lease(&root).unwrap();
    assert!(guard.is_none() && !busy);
    assert!(!root.join(LEASE).exists());
    let a = Lease::acquire(&root, false, true).unwrap().unwrap();
    let b = Lease::acquire(&root, false, true).unwrap().unwrap();
    assert!(matches!(
        Lease::acquire(&root, true, false),
        Err(LeaseError::Contended)
    ));
    let (catalog_guard, busy) = observation_lease(&root).unwrap();
    assert!(busy);
    drop(a);
    drop(b);
    assert!(matches!(
        Lease::acquire(&root, true, false),
        Err(LeaseError::Contended)
    ));
    drop(catalog_guard);
    let (idle, busy) = observation_lease(&root).unwrap();
    assert!(!busy);
    assert!(matches!(
        Lease::acquire(&root, false, false),
        Err(LeaseError::Contended)
    ));
    drop(idle);
    assert!(matches!(
        lock_error(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
        LeaseError::Other(_)
    ));
    fs::remove_file(root.join(LEASE)).unwrap();
    fs::create_dir(root.join(LEASE)).unwrap();
    assert!(matches!(
        Lease::acquire(&root, true, false),
        Err(LeaseError::Other(_))
    ));
}

#[test]
fn copy_is_bounded_and_failure_preserves_old_install() {
    let (_dir, root, source) = fixture();
    mutate(
        &root,
        &options("install", Kind::Skill, "demo", Some(source.clone())),
    )
    .unwrap();
    let old = inventory(&root.join("skills/demo")).unwrap();
    let receipt = fs::read(root.join(RECEIPTS)).unwrap();
    let expected = inventory(&source).unwrap();
    put(
        source.join("SKILL.md"),
        "changed and larger than the previously inventoried input",
    );
    let temp = tempfile::tempdir_in(&root).unwrap();
    assert!(copy_snapshot(Kind::Skill, &source, &temp.path().join("copy"), &expected).is_err());
    assert_eq!(old, inventory(&root.join("skills/demo")).unwrap());
    assert_eq!(receipt, fs::read(root.join(RECEIPTS)).unwrap());
    fs::remove_file(source.join("SKILL.md")).unwrap();
    assert!(mutate(&root, &options("update", Kind::Skill, "demo", Some(source))).is_err());
    assert_eq!(receipt, fs::read(root.join(RECEIPTS)).unwrap());
}

fn transaction(root: &Path) -> (tempfile::TempDir, Vec<(PathBuf, Option<PathBuf>)>) {
    put(root.join("skills/demo/SKILL.md"), "old resource");
    put(root.join(RECEIPTS), "old receipts");
    put(root.join("packages.json"), "old registry");
    let s = stage_dir(root).unwrap();
    put(s.path().join("snapshot/SKILL.md"), "new resource");
    put(s.path().join("receipts"), "new receipts");
    put(s.path().join("registry"), "new registry");
    let c = vec![
        (
            PathBuf::from("skills/demo"),
            Some(s.path().join("snapshot")),
        ),
        (PathBuf::from(RECEIPTS), Some(s.path().join("receipts"))),
        (
            PathBuf::from("packages.json"),
            Some(s.path().join("registry")),
        ),
    ];
    (s, c)
}
fn assert_old(root: &Path) {
    assert_eq!(
        fs::read(root.join("skills/demo/SKILL.md")).unwrap(),
        b"old resource"
    );
    assert_eq!(fs::read(root.join(RECEIPTS)).unwrap(), b"old receipts");
    assert_eq!(
        fs::read(root.join("packages.json")).unwrap(),
        b"old registry"
    );
    assert!(!root.join(JOURNAL).exists());
}
#[test]
fn publication_failures_and_crashes_restore_every_target_boundary() {
    for checkpoint in 0..=6 {
        let (_dir, root, _) = fixture();
        let _lease = mutation_lease(&root).unwrap();
        let (stage, changes) = transaction(&root);
        let error = publish(&root, changes, stage, |step| {
            if step == checkpoint {
                Err("injected filesystem publication failure".into())
            } else {
                Ok(())
            }
        })
        .unwrap_err();
        assert!(error.contains("injected"));
        assert_old(&root);
        let (stage, changes) = transaction(&root);
        let crash = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            publish(&root, changes, stage, |step| {
                assert_ne!(step, checkpoint, "simulated process interruption");
                Ok(())
            })
        }));
        assert!(crash.is_err());
        assert!(root.join(JOURNAL).is_file());
        assert!(ensure_complete(&root).is_err());
        assert!(recover(&root).unwrap());
        assert!(!recover(&root).unwrap());
        assert_old(&root);
    }
}
#[test]
fn actual_rename_registry_write_and_remove_failures_preserve_old_bytes() {
    for target in 0..3 {
        let (_dir, root, _) = fixture();
        let _lease = mutation_lease(&root).unwrap();
        let (stage, changes) = transaction(&root);
        let doomed = changes[target].1.clone().unwrap();
        let error = publish(&root, changes, stage, |step| {
            if step == target * 2 + 1 {
                remove_path(&doomed)?;
            }
            Ok(())
        })
        .unwrap_err();
        assert!(!error.is_empty());
        assert_old(&root);
    }
    let (_dir, root, source) = fixture();
    mutate(
        &root,
        &options("install", Kind::Skill, "demo", Some(source)),
    )
    .unwrap();
    let receipt = fs::read(root.join(RECEIPTS)).unwrap();
    let content = fs::read(root.join("skills/demo/SKILL.md")).unwrap();
    let stage = stage_dir(&root).unwrap();
    // A real create_new failure while staging registry bytes, before any activation.
    fs::create_dir(stage.path().join("receipts")).unwrap();
    assert!(write_new(&stage.path().join("receipts"), b"x").is_err());
    assert_eq!(fs::read(root.join(RECEIPTS)).unwrap(), receipt);
    assert_eq!(
        fs::read(root.join("skills/demo/SKILL.md")).unwrap(),
        content
    );
    let changes = vec![
        (PathBuf::from("skills/demo"), None),
        (PathBuf::from(RECEIPTS), None),
    ];
    assert!(publish(&root, changes, stage, |step| if step == 3 {
        Err("remove publication failed".into())
    } else {
        Ok(())
    })
    .is_err());
    assert_eq!(fs::read(root.join(RECEIPTS)).unwrap(), receipt);
    assert_eq!(
        fs::read(root.join("skills/demo/SKILL.md")).unwrap(),
        content
    );
}
#[test]
fn recovery_refuses_changed_targets_and_unsafe_journal_paths() {
    let (_dir, root, _) = fixture();
    let (stage, changes) = transaction(&root);
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        publish(&root, changes, stage, |step| {
            assert_ne!(step, 2);
            Ok(())
        })
    }));
    put(root.join("skills/demo/user-file"), "do not delete");
    assert!(recover(&root).unwrap_err().contains("changed"));
    assert_eq!(
        fs::read(root.join("skills/demo/user-file")).unwrap(),
        b"do not delete"
    );
    let mut j: Journal = serde_json::from_slice(&fs::read(root.join(JOURNAL)).unwrap()).unwrap();
    j.changes[0].target = "../outside".into();
    fs::write(root.join(JOURNAL), json_bytes(&j).unwrap()).unwrap();
    assert!(recover(&root).is_err());
}
#[test]
fn catalog_cannot_observe_a_paused_half_publication_and_never_creates_locks() {
    let (_dir, root, source) = fixture();
    let o = Options {
        op: "list".into(),
        scope: Some(Scope::Project),
        ..Default::default()
    };
    assert_eq!(catalog(&root, &o).unwrap()["resources"], json!([]));
    assert!(!root.join(LEASE).exists());
    mutate(
        &root,
        &options("install", Kind::Skill, "demo", Some(source)),
    )
    .unwrap();
    let (entered, wait) = std::sync::mpsc::channel();
    let (resume, go) = std::sync::mpsc::channel();
    let thread_root = root.clone();
    let thread = std::thread::spawn(move || {
        let _lease = mutation_lease(&thread_root).unwrap();
        let stage = stage_dir(&thread_root).unwrap();
        put(stage.path().join("snapshot/SKILL.md"), "new snapshot");
        let changes = vec![(
            PathBuf::from("skills/demo"),
            Some(stage.path().join("snapshot")),
        )];
        publish(&thread_root, changes, stage, |step| {
            if step == 1 {
                entered.send(()).unwrap();
                go.recv().unwrap();
            }
            Ok(())
        })
        .unwrap();
    });
    wait.recv_timeout(std::time::Duration::from_secs(5))
        .unwrap();
    assert!(catalog(&root, &o).unwrap_err().contains("in use"));
    resume.send(()).unwrap();
    thread.join().unwrap();
    assert!(catalog(&root, &o).unwrap()["resources"][0]["diagnostics"]
        .to_string()
        .contains("differs"));
}
#[test]
fn bounded_input_depth_width_receipts_and_next_state_do_not_publish_invalid_installs() {
    let (_dir, root, source) = fixture();
    let inv = inventory(&source).unwrap();
    let mut r = Receipts::default();
    for n in 0..128 {
        let name = format!("skill-{n}");
        r.resources.push(Receipt {
            kind: Kind::Skill,
            target: Kind::Skill.target(&name),
            name,
            source: source.clone(),
            version: None,
            inventory: inv.clone(),
        });
    }
    fs::write(root.join(RECEIPTS), json_bytes(&r).unwrap()).unwrap();
    let before = fs::read(root.join(RECEIPTS)).unwrap();
    let e = mutate(
        &root,
        &options("install", Kind::Skill, "overflow", Some(source.clone())),
    )
    .unwrap_err();
    assert!(e.contains("128"), "{e}");
    assert_eq!(before, fs::read(root.join(RECEIPTS)).unwrap());
    assert!(!root.join("skills/overflow").exists());
    let args = [
        "install",
        "skill",
        "v",
        "--scope",
        "project",
        "--path",
        "source",
        "--version",
        "",
    ];
    assert!(parse(&args.map(str::to_owned)).is_err());
    let mut deep = source.clone();
    for _ in 0..34 {
        deep.push("d");
        fs::create_dir(&deep).unwrap();
    }
    assert!(inventory(&source).unwrap_err().contains("depth"));
    fs::remove_dir_all(source.join("d")).unwrap();
    for n in 0..MAX_FILES {
        put(source.join(format!("file-{n}")), "x");
    }
    assert!(inventory(&source).unwrap_err().contains("budget"));
}
#[test]
fn corrupt_metadata_missing_legacy_owners_mismatch_and_modified_installs_fail_closed() {
    let (_dir, root, source) = fixture();
    let o = options("install", Kind::Skill, "demo", Some(source.clone()));
    fs::write(root.join(RECEIPTS), "broken").unwrap();
    assert!(mutate(&root, &o).is_err());
    assert_eq!(fs::read(root.join(RECEIPTS)).unwrap(), b"broken");
    fs::remove_file(root.join(RECEIPTS)).unwrap();
    let lib = source.with_extension(std::env::consts::DLL_EXTENSION);
    put(&lib, "opaque native candidate");
    fs::write(root.join("native-packages.json"),json!([{"name":"native-owner","version":"1","artifacts":[format!("native.{}",std::env::consts::DLL_EXTENSION)]}]).to_string()).unwrap();
    assert!(mutate(
        &root,
        &options("install", Kind::Extension, "native", Some(lib))
    )
    .unwrap_err()
    .contains("legacy"));
    mutate(
        &root,
        &options("install", Kind::Package, "bundle", Some(source.clone())),
    )
    .unwrap();
    let before = fs::read(root.join(RECEIPTS)).unwrap();
    let mut p = packages(&root).unwrap();
    p.packages[0].source = "another-provider".into();
    fs::write(root.join("packages.json"), json_bytes(&p).unwrap()).unwrap();
    assert!(
        mutate(&root, &options("remove", Kind::Package, "bundle", None))
            .unwrap_err()
            .contains("disagrees")
    );
    assert_eq!(fs::read(root.join(RECEIPTS)).unwrap(), before);
    fs::write(
        root.join("packages.json"),
        json_bytes(&Packages::default()).unwrap(),
    )
    .unwrap();
    fs::write(
        root.join(RECEIPTS),
        json_bytes(&Receipts::default()).unwrap(),
    )
    .unwrap();
    mutate(&root, &o).unwrap();
    put(root.join("skills/demo/unowned"), "keep");
    assert!(mutate(&root, &options("remove", Kind::Skill, "demo", None))
        .unwrap_err()
        .contains("changed"));
    assert_eq!(fs::read(root.join("skills/demo/unowned")).unwrap(), b"keep");
}
#[cfg(windows)]
#[test]
fn legacy_target_aliases_cannot_bypass_owned_windows_paths() {
    let (_dir, root, source) = fixture();
    let library = source.with_extension("dll");
    put(&library, "native");
    mutate(
        &root,
        &options("install", Kind::Extension, "Foo", Some(library)),
    )
    .unwrap();
    assert!(legacy_unowned_targets(&root, &[root.join("extensions/foo.dll")]).is_err());
    let outside = root.parent().unwrap().join("outside");
    fs::create_dir(&outside).unwrap();
    let link = root.join("alias");
    let status = std::process::Command::new("cmd")
        .args(["/C", "mklink", "/J"])
        .arg(&link)
        .arg(&outside)
        .status()
        .unwrap();
    assert!(status.success());
    assert!(legacy_unowned_targets(&root, &[link.join("anything.dll")]).is_err());
    fs::remove_dir(link).unwrap();
}

/// A snapshot copy of a native artifact must be loadable, and the recorded
/// inventory must describe the copy rather than the source.
///
/// On macOS an unre-signed copy is refused by the kernel at first code-page
/// fault and the whole host is killed (no stderr, exit 137), so signing has to
/// happen while staging, before publication. Re-signing rewrites bytes, so the
/// receipt has to be built from the post-signing inventory — otherwise every
/// later ownership check reports "content changed" against a good install.
#[cfg(target_os = "macos")]
#[test]
fn staged_native_snapshot_is_signed_and_inventory_describes_the_copy() {
    let (_dir, root, _) = fixture();
    // `tempfile` lands under /var on macOS, which is a symlink to /private/var;
    // resource paths reject links, so address the real tree.
    let base = fs::canonicalize(_dir.path()).unwrap();
    // Any signed Mach-O works: only the signature/bytes relationship matters.
    let source = base.join("source/extensions/plugin.dylib");
    put(&source, fs::read("/bin/echo").unwrap());
    let observed = inventory(&source).unwrap();
    let staged = base.join("staged");
    let copied = copy_snapshot(Kind::Extension, &source, &staged, &observed).unwrap();
    assert_ne!(
        copied.files[0].sha256, observed.files[0].sha256,
        "the staged artifact was not re-signed"
    );
    assert_eq!(
        copied,
        inventory(&staged).unwrap(),
        "the returned inventory must describe the staged bytes"
    );
    let out = std::process::Command::new("/usr/bin/codesign")
        .args(["-d", "--verbose=4"])
        .arg(&staged)
        .output()
        .unwrap();
    assert!(
        !String::from_utf8_lossy(&out.stderr).contains("linker-signed"),
        "the staged artifact kept its build-time signature"
    );
    let _ = root;
}

/// Only `extensions/` artifacts are native; a same-suffix data file elsewhere in
/// a Package is not.
///
/// The kernel only ever maps the direct children of `extensions/` (that is what
/// `validate_source` accepts), so `skills/x/assets/data.dylib` is ordinary data.
/// Re-signing it would rewrite a file the host treats as content.
#[cfg(target_os = "macos")]
#[test]
fn package_resigns_only_direct_extension_artifacts() {
    assert!(is_package_artifact(Path::new("extensions/plugin.dylib")));
    assert!(is_package_artifact(Path::new("extensions/nested.dylib")));
    assert!(!is_package_artifact(Path::new(
        "skills/demo/assets/data.dylib"
    )));
    assert!(!is_package_artifact(Path::new("prompts/foo.dylib")));
    assert!(!is_package_artifact(Path::new("themes/bar.dylib")));
    assert!(!is_package_artifact(Path::new("extensions/plugin.txt")));
    assert!(!is_package_artifact(Path::new("extensions/a/b.dylib")));
}

/// Re-signing must be stable: two installs of the same source have to leave the
/// same bytes behind, so the second one reports `unchanged` instead of
/// "already installed".
///
/// `codesign --sign -` would otherwise derive the ad-hoc identifier from the file
/// NAME, so the same bytes staged under two different names sign to different
/// bytes — an unchanged install would then look changed. The identifier is pinned
/// for exactly that reason; this stages under two different names to prove it.
#[cfg(target_os = "macos")]
#[test]
fn repeated_native_install_is_idempotent() {
    let (_dir, _root, _) = fixture();
    let base = fs::canonicalize(_dir.path()).unwrap();
    let source = base.join("source/extensions/plugin.dylib");
    put(&source, fs::read("/bin/echo").unwrap());
    let observed = inventory(&source).unwrap();
    fs::create_dir_all(base.join("txn-a")).unwrap();
    fs::create_dir_all(base.join("txn-b")).unwrap();
    let first =
        copy_snapshot(Kind::Extension, &source, &base.join("txn-a/one"), &observed).unwrap();
    let second =
        copy_snapshot(Kind::Extension, &source, &base.join("txn-b/two"), &observed).unwrap();
    assert_eq!(
        first.files[0].sha256, second.files[0].sha256,
        "signing the same source twice produced different bytes"
    );
    assert_eq!(first, second);
}

/// A Skill directory never has native artifacts signed.
///
/// `validate_source` for `Kind::Skill` only requires `SKILL.md`; it does not
/// reserve an `extensions/` subtree. A skill may therefore legitimately carry an
/// ordinary asset such as `extensions/example.dylib`, and that file is content.
/// Signing it would rewrite a file the host never loads as a library.
#[cfg(target_os = "macos")]
#[test]
fn skill_directory_never_resigns_same_suffix_assets() {
    let (_dir, _root, _) = fixture();
    let base = fs::canonicalize(_dir.path()).unwrap();
    let source = base.join("skill");
    put(source.join("SKILL.md"), "---\nname: demo\n---\nbody");
    // Non-Mach-O data that happens to use the library suffix, in a path that a
    // Package would have treated as an artifact.
    put(source.join("extensions/example.dylib"), b"plain data\n");
    let observed = inventory(&source).unwrap();
    let copied = copy_snapshot(Kind::Skill, &source, &base.join("skill-copy"), &observed).unwrap();
    assert_eq!(
        copied, observed,
        "a Skill snapshot must be byte-identical to its source"
    );
    assert_eq!(
        fs::read(base.join("skill-copy/extensions/example.dylib")).unwrap(),
        b"plain data\n"
    );
}

/// The same path *is* an artifact when the source is a Package.
#[cfg(target_os = "macos")]
#[test]
fn package_artifact_selection_differs_from_skill() {
    assert!(is_package_artifact(Path::new("extensions/example.dylib")));
    // Skill selection is empty regardless of path, which the kind match encodes;
    // this guards the helper boundary the reviewer called out.
    assert!(!is_package_artifact(Path::new("assets/example.dylib")));
}