rho-coding-agent 3.5.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::path::Path;

use pretty_assertions::assert_eq;

use super::{
    check_target_in_roots, delete_target_in_roots, delete_targets_in_roots,
    write_linked_run_for_tests, ChildSessionNotDeleted, RunNotFinished,
};
use crate::{
    session::{
        DeleteOptions, Session, SessionInUse, SessionListing, SessionOrigin, SessionProvenance,
        SessionTarget,
    },
    subagent::RunState,
};

fn create_session(root: &Path, cwd: &Path, id: &str) -> Session {
    Session::create_with_id_in_root(root, cwd, id, None, SessionOrigin::Interactive.into()).unwrap()
}

// Covers: deleting a session deletes the child sessions it started and
// theirs, wherever they were saved, and nothing else; deleting a child keeps
// its parent; a batch that also names a child deleted with its parent
// reports no failure for it; a parent is its id in its own workspace, so a
// same-id session elsewhere keeps its children; a header naming its own
// session as its parent does not stop the delete.
// Owner: session deletion
#[test]
fn delete_takes_child_sessions_recursively() {
    /// Each deleted id with the child sessions deleted along with it.
    type Deleted<'a> = Vec<(&'a str, usize)>;
    // (label, targets, expected deletions, expected sessions gone)
    let cases: [(&str, &[&str], Deleted, Vec<&str>); 5] = [
        (
            "parent",
            &["parent"],
            vec![("parent", 2)],
            vec!["parent", "child", "grandchild"],
        ),
        (
            "child",
            &["child"],
            vec![("child", 1)],
            vec!["child", "grandchild"],
        ),
        (
            "parent and child",
            &["parent", "child"],
            vec![("parent", 2)],
            vec!["parent", "child", "grandchild"],
        ),
        (
            "same id in another workspace",
            &["twin-here"],
            vec![("twin", 1)],
            vec!["twin-here", "twin-here-child"],
        ),
        (
            "own parent",
            &["self-parent"],
            vec![("self-parent", 0)],
            vec!["self-parent"],
        ),
    ];
    for (label, targets, expected_deleted, expected_gone) in cases {
        let sessions = tempfile::tempdir().unwrap();
        let subagents = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir().unwrap();
        // A subagent can run in another workspace, such as a worktree.
        let elsewhere = tempfile::tempdir().unwrap();
        // (name, id, workspace, parent's name)
        let tree = [
            ("parent", "parent", workspace.path(), None),
            ("child", "child", workspace.path(), Some("parent")),
            ("grandchild", "grandchild", elsewhere.path(), Some("child")),
            ("other-root", "other-root", workspace.path(), None),
            ("sibling", "sibling", workspace.path(), Some("other-root")),
            // One id saved in two workspaces, each with a child here.
            ("twin-here", "twin", workspace.path(), None),
            (
                "twin-here-child",
                "twin-here-child",
                workspace.path(),
                Some("twin-here"),
            ),
            ("twin-elsewhere", "twin", elsewhere.path(), None),
            (
                "twin-elsewhere-child",
                "twin-elsewhere-child",
                workspace.path(),
                Some("twin-elsewhere"),
            ),
            (
                "self-parent",
                "self-parent",
                workspace.path(),
                Some("self-parent"),
            ),
        ];
        let target = |name: &str| {
            let (_, id, cwd, _) = tree.iter().find(|(entry, ..)| *entry == name).unwrap();
            SessionTarget::new(*id, *cwd)
        };
        let paths = tree.map(|(name, id, cwd, parent)| {
            let provenance = match parent {
                Some(parent) => SessionProvenance {
                    origin: SessionOrigin::Subagent,
                    parent: Some(target(parent)),
                    started_by: None,
                },
                None => SessionOrigin::Interactive.into(),
            };
            let session =
                Session::create_with_id_in_root(sessions.path(), cwd, id, None, provenance)
                    .unwrap();
            (name, session.path().to_path_buf())
        });
        let targets = targets.iter().copied().map(target).collect::<Vec<_>>();

        let outcome = delete_targets_in_roots(
            sessions.path(),
            subagents.path(),
            &targets,
            &DeleteOptions::default(),
        )
        .unwrap();

        let deleted = outcome
            .deleted
            .iter()
            .map(|item| (item.id.as_str(), item.deleted_child_session_count))
            .collect::<Vec<_>>();
        let failed = outcome
            .failures
            .iter()
            .map(|item| item.error.as_str())
            .collect::<Vec<_>>();
        let gone = paths
            .iter()
            .filter(|(_, path)| !path.exists())
            .map(|(name, _)| *name)
            .collect::<Vec<_>>();
        assert_eq!(
            (deleted, failed, gone),
            (expected_deleted, Vec::<&str>::new(), expected_gone),
            "{label}"
        );
    }
}

// Covers: deleting the session that started another through session control
// leaves the one it started, unlike a subagent's parent, whose delete takes
// its children.
// Owner: session deletion
#[test]
fn deleting_a_starter_leaves_the_sessions_it_started() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    create_session(sessions.path(), workspace.path(), "lead");
    let started = SessionProvenance {
        origin: SessionOrigin::Daemon,
        parent: None,
        started_by: Some("lead".into()),
    };
    Session::create_with_id_in_root(sessions.path(), workspace.path(), "worker", None, started)
        .unwrap();

    delete_target_in_roots(
        sessions.path(),
        subagents.path(),
        &SessionTarget::new("lead", workspace.path()),
        &DeleteOptions::default(),
    )
    .unwrap();

    let listed = Session::list_in_root(
        sessions.path(),
        workspace.path(),
        SessionListing::PersonFacing,
    )
    .unwrap()
    .into_iter()
    .map(|summary| summary.id)
    .collect::<Vec<_>>();
    assert_eq!(listed, vec!["worker".to_owned()]);
}

// Covers: a child session that refuses its delete stops its parent's: the
// parent and the children after the refused one stay, the error names the
// child and its parent, and the children deleted before it leave the index
// even though the delete failed.
// Owner: session deletion
#[test]
fn refused_child_session_keeps_its_parent() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let parent = SessionTarget::new("parent", workspace.path());
    // Children are deleted oldest first, so in this order.
    let ids = ["parent", "child-a", "child-b", "child-c"];
    let paths = ids.map(|id| {
        let provenance = match id {
            "parent" => SessionOrigin::Interactive.into(),
            _ => SessionProvenance {
                origin: SessionOrigin::Subagent,
                parent: Some(parent.clone()),
                started_by: None,
            },
        };
        Session::create_with_id_in_root(sessions.path(), workspace.path(), id, None, provenance)
            .unwrap()
            .path()
            .to_path_buf()
    });
    let refused = SessionTarget::new("child-b", workspace.path());

    let error = delete_target_in_roots(
        sessions.path(),
        subagents.path(),
        &parent,
        &DeleteOptions {
            force: false,
            protected_session: Some(refused.clone()),
        },
    )
    .unwrap_err();

    let named = error
        .downcast_ref::<ChildSessionNotDeleted>()
        .map(|error| (error.child.clone(), error.parent.clone()));
    let remaining = ids
        .iter()
        .zip(&paths)
        .filter(|(_, path)| path.exists())
        .map(|(id, _)| *id)
        .collect::<Vec<_>>();
    // Read the index directly: listing would reconcile leftover rows away.
    let index = rusqlite::Connection::open(sessions.path().join("index.sqlite3")).unwrap();
    let indexed = index
        .prepare("select id from sessions order by id")
        .unwrap()
        .query_map([], |row| row.get::<_, String>(0))
        .unwrap()
        .collect::<rusqlite::Result<Vec<_>>>()
        .unwrap();
    assert_eq!(
        (named, remaining, indexed),
        (
            Some((refused, parent)),
            vec!["parent", "child-b", "child-c"],
            vec!["child-b".to_string(), "child-c".into(), "parent".into()],
        )
    );
}

// Covers: the check a host runs before it lets an open session go to
// delete it refuses as the delete would, for a child session something
// holds or a child's unfinished run, but deletes nothing, not even the
// children before the refused one that the delete itself would take; it
// skips the leases of the sessions that host holds and names, the session's
// own or a child's, and only those (#1670).
// Owner: session deletion
#[test]
fn delete_check_refuses_as_the_delete_would_and_deletes_nothing() {
    /// What refused the check: the child it names and what that child's
    /// error is.
    #[derive(Debug, PartialEq, Eq)]
    enum Refusal {
        InUse,
        ChildInUse(String),
        ChildRunNotFinished(String),
    }
    // (label, child session held open, child whose run is unfinished,
    // sessions the host names as its own, expected)
    let cases: [(_, _, _, &[&str], _); 5] = [
        ("clear", None, None, &["parent"], Ok(())),
        (
            "child held",
            Some("child-b"),
            None,
            &["parent"],
            Err(Refusal::ChildInUse("child-b".into())),
        ),
        (
            "child's run unfinished",
            None,
            Some("child-b"),
            &["parent"],
            Err(Refusal::ChildRunNotFinished("child-b".into())),
        ),
        (
            "child the host holds",
            Some("child-b"),
            None,
            &["parent", "child-b"],
            Ok(()),
        ),
        (
            "session held, but not named",
            None,
            None,
            &[],
            Err(Refusal::InUse),
        ),
    ];
    for (label, held_child, running_child, named, expected) in cases {
        let sessions = tempfile::tempdir().unwrap();
        let subagents = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir().unwrap();
        let parent = SessionTarget::new("parent", workspace.path());
        let ids = ["parent", "child-a", "child-b"];
        let paths = ids.map(|id| {
            let provenance = match id {
                "parent" => SessionOrigin::Interactive.into(),
                _ => SessionProvenance {
                    origin: SessionOrigin::Subagent,
                    parent: Some(parent.clone()),
                    started_by: None,
                },
            };
            Session::create_with_id_in_root(sessions.path(), workspace.path(), id, None, provenance)
                .unwrap()
                .path()
                .to_path_buf()
        });
        // The host's own hold on the session it deletes.
        let _host =
            Session::open_by_id_in_root(sessions.path(), workspace.path(), "parent").unwrap();
        let _held = held_child
            .map(|id| Session::open_by_id_in_root(sessions.path(), workspace.path(), id).unwrap());
        if let Some(id) = running_child {
            write_linked_run_for_tests(subagents.path(), "ee33ff", id, RunState::Running);
        }

        let checked = check_target_in_roots(
            sessions.path(),
            subagents.path(),
            &parent,
            &DeleteOptions::default(),
            &named.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>(),
        )
        .map_err(|error| {
            let child = error
                .downcast_ref::<ChildSessionNotDeleted>()
                .map(|refused| refused.child.id.clone());
            let in_use = error.chain().any(|cause| cause.is::<SessionInUse>());
            if let (true, None) = (in_use, &child) {
                Refusal::InUse
            } else if in_use {
                Refusal::ChildInUse(child.unwrap_or_default())
            } else if error.chain().any(|cause| cause.is::<RunNotFinished>()) {
                Refusal::ChildRunNotFinished(child.unwrap_or_default())
            } else {
                panic!("{label}: unexpected refusal: {error:#}")
            }
        });

        let remaining = ids
            .iter()
            .zip(&paths)
            .filter(|(_, path)| path.exists())
            .map(|(id, _)| *id)
            .collect::<Vec<_>>();
        assert_eq!((checked, remaining), (expected, ids.to_vec()), "{label}");
    }
}

// Covers: an exact workspace target cannot fall back to a same-id session in
// another workspace during delete.
// Owner: session deletion
#[test]
fn exact_target_delete_preserves_same_id_in_other_workspace() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace_a = tempfile::tempdir().unwrap();
    let workspace_b = tempfile::tempdir().unwrap();
    let id = "00000000-0000-0000-0000-000000000123";
    let kept = create_session(sessions.path(), workspace_a.path(), id);
    let deleted = create_session(sessions.path(), workspace_b.path(), id);
    let deleted_path = deleted.path().to_path_buf();
    drop(deleted);
    let outcome = delete_target_in_roots(
        sessions.path(),
        subagents.path(),
        &SessionTarget::new(id, workspace_b.path()),
        &DeleteOptions::default(),
    )
    .unwrap();

    assert_eq!(outcome.cwd, workspace_b.path());
    assert!(kept.path().exists());
    assert!(!deleted_path.exists());
}

// Covers: workspace batch deletion owns current-session protection and deletes
// every other persisted session.
// Owner: session deletion
#[test]
fn workspace_delete_keeps_exact_protected_session() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let kept_id = "00000000-0000-0000-0000-000000000124";
    let deleted_id = "00000000-0000-0000-0000-000000000125";
    let kept = create_session(sessions.path(), workspace.path(), kept_id);
    let deleted = create_session(sessions.path(), workspace.path(), deleted_id);
    let deleted_path = deleted.path().to_path_buf();
    drop(deleted);
    let protected = SessionTarget::new(kept_id, workspace.path());

    let outcome = delete_targets_in_roots(
        sessions.path(),
        subagents.path(),
        &[
            protected.clone(),
            SessionTarget::new(deleted_id, workspace.path()),
        ],
        &DeleteOptions {
            force: false,
            protected_session: Some(protected.clone()),
        },
    )
    .unwrap();

    assert_eq!(outcome.kept_protected, vec![protected]);
    assert_eq!(
        outcome
            .deleted
            .iter()
            .map(|item| item.id.as_str())
            .collect::<Vec<_>>(),
        vec![deleted_id]
    );
    assert!(outcome.failures.is_empty());
    assert!(kept.path().exists());
    assert!(!deleted_path.exists());
}

// Covers: a child spawned while the session was open keeps a copy of the
// lease handle until exec, so closing the session must release the lease itself.
// Owner: session deletion
#[cfg(unix)]
#[test]
fn closed_session_is_deletable_while_an_inherited_lease_handle_is_open() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let id = "00000000-0000-0000-0000-000000000127";
    let session = create_session(sessions.path(), workspace.path(), id);
    let inherited = session
        .active_lease_for_tests()
        .inherited_handle_for_tests();
    let path = session.path().to_path_buf();
    drop(session);

    delete_target_in_roots(
        sessions.path(),
        subagents.path(),
        &SessionTarget::new(id, workspace.path()),
        &DeleteOptions::default(),
    )
    .unwrap();
    assert!(!path.exists());
    drop(inherited);
}

// Covers: batch deletion removes only targets reviewed before confirmation, so
// a session created between preview and confirmation survives.
// Owner: session deletion
#[test]
fn target_batch_does_not_delete_session_created_after_preview() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let reviewed_id = "00000000-0000-0000-0000-000000000127";
    let later_id = "00000000-0000-0000-0000-000000000128";
    let reviewed = create_session(sessions.path(), workspace.path(), reviewed_id);
    let reviewed_path = reviewed.path().to_path_buf();
    let reviewed_targets = vec![SessionTarget::new(reviewed_id, workspace.path())];
    drop(reviewed);

    let later = create_session(sessions.path(), workspace.path(), later_id);
    let later_path = later.path().to_path_buf();
    drop(later);

    let outcome = delete_targets_in_roots(
        sessions.path(),
        subagents.path(),
        &reviewed_targets,
        &DeleteOptions::default(),
    )
    .unwrap();

    assert_eq!(outcome.deleted.len(), 1);
    assert!(!reviewed_path.exists());
    assert!(later_path.exists());
}

// Covers: a batch keeps going past a session it cannot delete, and drops the
// index rows of the ones it did delete even though that happens at batch end.
// Owner: session deletion
#[test]
fn batch_delete_skips_blocked_session_and_drops_deleted_index_rows() {
    let sessions = tempfile::tempdir().unwrap();
    let subagents = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let ids = [
        "00000000-0000-0000-0000-000000000131",
        "00000000-0000-0000-0000-000000000132",
        "00000000-0000-0000-0000-000000000133",
    ];
    for id in &ids {
        drop(create_session(sessions.path(), workspace.path(), id));
    }
    // An open session holds its active lease, which blocks its delete.
    let blocked = Session::open_by_id_in_root(sessions.path(), workspace.path(), ids[1])
        .unwrap()
        .0;

    let outcome = delete_targets_in_roots(
        sessions.path(),
        subagents.path(),
        &ids.map(|id| SessionTarget::new(id, workspace.path())),
        &DeleteOptions::default(),
    )
    .unwrap();

    let deleted = outcome
        .deleted
        .iter()
        .map(|item| item.id.as_str())
        .collect::<Vec<_>>();
    let failed = outcome
        .failures
        .iter()
        .map(|item| item.id.as_str())
        .collect::<Vec<_>>();
    assert_eq!((deleted, failed), (vec![ids[0], ids[2]], vec![ids[1]]));
    drop(blocked);
    // Read the index directly: listing would reconcile leftover rows away.
    let index = rusqlite::Connection::open(sessions.path().join("index.sqlite3")).unwrap();
    let indexed = index
        .prepare("select id from sessions order by id")
        .unwrap()
        .query_map([], |row| row.get::<_, String>(0))
        .unwrap()
        .collect::<rusqlite::Result<Vec<_>>>()
        .unwrap();
    assert_eq!(indexed, vec![ids[1].to_string()]);
}