rho-coding-agent 3.0.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Session delete with cascade cleanup of parent-linked subagent runs and
//! of the child sessions a session started, recursively.

use std::{
    collections::HashSet,
    fmt, fs,
    io::ErrorKind,
    path::{Path, PathBuf},
};

#[cfg(test)]
use crate::subagent::RunStatus;
use crate::subagent::{self, RunIndexCleanup, RunState, RESULT_FILE_NAME};

use super::{
    id_match::short_id,
    index,
    lease::{self, LeasePurpose},
    persistence::{workspace_key, ResolvedSession, SessionStore, SessionUnit},
    SessionSummary, SessionTarget,
};

/// Controls for [`super::Session::delete_target`] and batch deletion.
#[derive(Clone, Debug, Default)]
pub struct DeleteOptions {
    /// When true, delete even if a parent-linked run is still non-terminal.
    ///
    /// Only intended for stale `Running`/`Starting` artifacts left behind after a
    /// crash. Live runs may still be writing; prefer waiting for completion.
    pub force: bool,
    /// Refuse delete when the resolved session has this exact workspace identity.
    pub protected_session: Option<SessionTarget>,
}

/// Result of a successful session delete.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeleteOutcome {
    pub id: String,
    pub cwd: PathBuf,
    pub path: PathBuf,
    /// Number of nested and global parent-linked run directories removed,
    /// child sessions' included.
    pub deleted_run_count: usize,
    /// Run ids force-deleted while still non-terminal, child sessions'
    /// included.
    pub forced_run_ids: Vec<String>,
    /// Number of child sessions deleted with this one, such as its
    /// subagents', grandchildren included.
    pub deleted_child_session_count: usize,
}

/// One session that cleanup could not remove.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CleanupFailure {
    pub(crate) id: String,
    pub(crate) cwd: PathBuf,
    pub(crate) error: String,
    /// Refused because the session, or one it started, is open elsewhere:
    /// whoever holds it, such as the daemon, can still delete it.
    pub(crate) in_use: bool,
}

impl CleanupFailure {
    fn new(target: &SessionTarget, error: &anyhow::Error) -> Self {
        Self {
            id: target.id.clone(),
            cwd: target.cwd.clone(),
            error: format!("{error:#}"),
            in_use: is_in_use(error),
        }
    }
}

/// Whether a delete was refused because something holds the session or a
/// session it started.
pub(crate) fn is_in_use(error: &anyhow::Error) -> bool {
    error.chain().any(|cause| cause.is::<super::SessionInUse>())
}

/// Result of an explicit cleanup of sessions for missing workspace directories.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct CleanupOutcome {
    pub(crate) deleted: Vec<DeleteOutcome>,
    pub(crate) failures: Vec<CleanupFailure>,
    /// Candidates skipped because their workspace reappeared after preview.
    pub(crate) restored_workspaces: usize,
}

/// Result of deleting every deletable session owned by one workspace.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct WorkspaceDeleteOutcome {
    pub(crate) deleted: Vec<DeleteOutcome>,
    pub(crate) failures: Vec<CleanupFailure>,
    pub(crate) kept_protected: Vec<SessionTarget>,
}

/// What [`super::Session::delete_exact`] found saved under the id.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ExactDelete {
    /// The session was saved, and is deleted with its child sessions.
    Deleted(DeleteOutcome),
    /// Nothing is saved under the id: never saved, or already deleted.
    NothingSaved,
}

/// A child session's delete failed, which stops its parent's. Names both,
/// so a refusal of the child does not read as one of its parent, and keeps
/// the child's error as its source, so a caller still finds the refusal's
/// type, such as [`super::SessionInUse`], in the error's chain.
#[derive(Debug)]
struct ChildSessionNotDeleted {
    child: SessionTarget,
    parent: SessionTarget,
    source: anyhow::Error,
}

impl fmt::Display for ChildSessionNotDeleted {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "could not delete child session '{}' of '{}'",
            short_id(&self.child.id),
            short_id(&self.parent.id),
        )
    }
}

impl std::error::Error for ChildSessionNotDeleted {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.source.as_ref())
    }
}

/// Refusal to delete a session while a run linked to it, such as a
/// subagent run it started, has not finished: the run may still write.
#[derive(Debug)]
pub(crate) struct RunNotFinished {
    session: String,
    run: String,
    state: Option<RunState>,
}

impl RunNotFinished {
    /// The id of the session the run is linked to.
    pub(crate) fn session(&self) -> &str {
        &self.session
    }

    /// The run's id.
    pub(crate) fn run(&self) -> &str {
        &self.run
    }

    /// The run's state, as its status file names it.
    pub(crate) fn state(&self) -> &'static str {
        self.state.map(RunState::as_str).unwrap_or("unknown")
    }
}

impl fmt::Display for RunNotFinished {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let crash_hint = if self.state.is_some_and(RunState::is_live) {
            " (use --force only for stale runs left after a crash)"
        } else {
            ""
        };
        write!(
            formatter,
            "refusing to delete session '{}': related run {} is still {}{crash_hint}; wait for it to finish or pass --force",
            short_id(&self.session),
            self.run,
            self.state(),
        )
    }
}

impl std::error::Error for RunNotFinished {}

/// Whether a delete check takes the checked session's own lease.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OwnLease {
    Take,
    /// Its caller holds it open, and lets go only once the check passes.
    Skip,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RunCleanup {
    Structural,
    Explicit,
}

#[derive(Clone, Debug)]
struct LinkedRun {
    dir: PathBuf,
    id: String,
    state: Option<RunState>,
    cleanup: RunCleanup,
}

pub(super) fn list_missing_workspaces_in_root(
    session_root: &Path,
) -> anyhow::Result<Vec<SessionSummary>> {
    index::list_all_sessions(session_root)?
        .into_iter()
        .filter_map(
            |session| match workspace_directory_is_missing(&session.cwd) {
                Ok(true) => Some(Ok(session)),
                Ok(false) => None,
                Err(error) => Some(Err(error)),
            },
        )
        .collect()
}

#[cfg(test)]
pub(super) fn cleanup_missing_workspaces_in_roots(
    session_root: &Path,
    subagents_root: &Path,
    options: &DeleteOptions,
) -> anyhow::Result<CleanupOutcome> {
    let targets = list_missing_workspaces_in_root(session_root)?
        .into_iter()
        .map(|session| session.target())
        .collect::<Vec<_>>();
    cleanup_missing_targets_in_roots(session_root, subagents_root, &targets, options)
}

pub(super) fn cleanup_missing_targets_in_roots(
    session_root: &Path,
    subagents_root: &Path,
    targets: &[SessionTarget],
    options: &DeleteOptions,
) -> anyhow::Result<CleanupOutcome> {
    let mut batch = BatchDelete::open(session_root, subagents_root, options)?;
    let mut outcome = CleanupOutcome::default();
    for target in targets {
        // Confirmation and deletion are separate operations. Re-check only the
        // reviewed target so restored workspaces are kept and new sessions are
        // never swept into an old confirmation.
        match workspace_directory_is_missing(&target.cwd) {
            Ok(true) => {}
            Ok(false) => {
                outcome.restored_workspaces += 1;
                continue;
            }
            Err(error) => {
                outcome.failures.push(CleanupFailure::new(target, &error));
                continue;
            }
        }
        // Gone with a parent deleted earlier in the batch.
        if batch.has_deleted(target) {
            continue;
        }
        match batch.delete_target(target) {
            Ok(deleted) => outcome.deleted.push(deleted),
            Err(error) => outcome.failures.push(CleanupFailure::new(target, &error)),
        }
    }
    batch.finish();
    Ok(outcome)
}

pub(super) fn workspace_directory_is_missing(cwd: &Path) -> anyhow::Result<bool> {
    match fs::metadata(cwd) {
        Ok(metadata) => Ok(!metadata.is_dir()),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(true),
        Err(error) => Err(anyhow::anyhow!(
            "could not inspect workspace directory {}: {error}",
            cwd.display()
        )),
    }
}

#[cfg(test)]
pub(super) fn delete_in_roots(
    session_root: &Path,
    subagents_root: &Path,
    cwd: &Path,
    id_prefix: &str,
    options: &DeleteOptions,
) -> anyhow::Result<DeleteOutcome> {
    let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
    let mut batch = BatchDelete::open(session_root, subagents_root, options)?;
    let outcome = batch.delete_resolved(resolved);
    batch.finish();
    outcome
}

/// Refuses as deleting `target` would, but deletes nothing: for a linked run
/// of it or of a session it started that has not finished, or for a session
/// it started that something holds. `target`'s own lease is not checked,
/// since the caller holds it open; it checks before it lets the session go
/// to delete it, as the daemon does (#1670).
fn check_target_in_roots(
    session_root: &Path,
    subagents_root: &Path,
    target: &SessionTarget,
    options: &DeleteOptions,
) -> anyhow::Result<()> {
    let resolved = SessionStore::new(session_root, &target.cwd).resolve_in_workspace(&target.id)?;
    let mut batch = BatchDelete::open(session_root, subagents_root, options)?;
    batch.check_resolved(resolved, OwnLease::Skip)
}

pub(super) fn delete_target_in_roots(
    session_root: &Path,
    subagents_root: &Path,
    target: &SessionTarget,
    options: &DeleteOptions,
) -> anyhow::Result<DeleteOutcome> {
    let mut batch = BatchDelete::open(session_root, subagents_root, options)?;
    let outcome = batch.delete_target(target);
    // Even after a failure: child sessions deleted before it leave the index.
    batch.finish();
    outcome
}

pub(super) fn delete_targets_in_roots(
    session_root: &Path,
    subagents_root: &Path,
    targets: &[SessionTarget],
    options: &DeleteOptions,
) -> anyhow::Result<WorkspaceDeleteOutcome> {
    let mut batch = BatchDelete::open(session_root, subagents_root, options)?;
    let mut outcome = WorkspaceDeleteOutcome::default();
    for target in targets {
        if options.protected_session.as_ref() == Some(target) {
            outcome.kept_protected.push(target.clone());
            continue;
        }
        // Gone with a parent deleted earlier in the batch.
        if batch.has_deleted(target) {
            continue;
        }
        match batch.delete_target(target) {
            Ok(deleted) => outcome.deleted.push(deleted),
            Err(error) => outcome.failures.push(CleanupFailure::new(target, &error)),
        }
    }
    batch.finish();
    Ok(outcome)
}

/// One delete pass over any number of sessions.
///
/// Index bookkeeping, not file removal, dominated bulk cleanup: each session
/// reopened the WAL run index three times (each close checkpoints and syncs)
/// and made its own session-index commit, about 18ms per session and 10s for
/// 523 sessions. The batch keeps one run-index handle open and drops
/// session-index rows in one transaction in [`Self::finish`]. Deferring those
/// rows is safe: every reader either reconciles first or skips rows whose
/// transcript is gone, and reconciliation drops rows `finish` never reached.
struct BatchDelete<'a> {
    session_root: &'a Path,
    subagents_root: &'a Path,
    runs: RunIndexCleanup,
    options: &'a DeleteOptions,
    /// Index rows of sessions removed from disk.
    removed: Vec<index::IndexKey>,
    /// Workspaces whose index rows were synced to disk this batch, so child
    /// sessions are found by their recorded parent.
    synced_workspaces: HashSet<String>,
    /// Index rows of the sessions being deleted right now: the innermost
    /// one and the parents waiting on its delete. A header that names its
    /// own session or one of these as its parent makes a cycle, which must
    /// neither recurse forever nor block the delete.
    deleting: HashSet<index::IndexKey>,
}

impl<'a> BatchDelete<'a> {
    fn open(
        session_root: &'a Path,
        subagents_root: &'a Path,
        options: &'a DeleteOptions,
    ) -> anyhow::Result<Self> {
        Ok(Self {
            session_root,
            subagents_root,
            runs: RunIndexCleanup::open(subagents_root)?,
            options,
            removed: Vec::new(),
            synced_workspaces: HashSet::new(),
            deleting: HashSet::new(),
        })
    }

    fn delete_target(&mut self, target: &SessionTarget) -> anyhow::Result<DeleteOutcome> {
        let resolved =
            SessionStore::new(self.session_root, &target.cwd).resolve_in_workspace(&target.id)?;
        self.delete_resolved(resolved)
    }

    /// Whether this batch already deleted `target`, such as a child session
    /// that went with its parent.
    fn has_deleted(&self, target: &SessionTarget) -> bool {
        let key = (workspace_key(&target.cwd), target.id.clone());
        self.removed.contains(&key)
    }

    /// The saved child sessions `resolved` started that this batch has not
    /// deleted and is not deleting. Its workspace's index rows are synced
    /// first, once a batch, so a child the index has not seen yet is still
    /// found; a child saved in another workspace is found by the row its
    /// creation recorded.
    fn child_sessions(&mut self, resolved: &ResolvedSession) -> anyhow::Result<Vec<SessionTarget>> {
        if self.synced_workspaces.insert(workspace_key(&resolved.cwd)) {
            index::sync_workspace(self.session_root, &resolved.cwd)?;
        }
        let parent = SessionTarget::new(resolved.id.clone(), resolved.cwd.clone());
        Ok(index::child_sessions(self.session_root, &parent)?
            .into_iter()
            .filter(|child| {
                let key = (workspace_key(&child.cwd), child.id.clone());
                !self.deleting.contains(&key) && !self.removed.contains(&key)
            })
            .collect())
    }

    /// Deletes child session `child`, or returns `None` when it is gone
    /// since [`Self::child_sessions`] found it, as already deleted.
    fn delete_child(&mut self, child: &SessionTarget) -> anyhow::Result<Option<DeleteOutcome>> {
        match SessionStore::new(self.session_root, &child.cwd).resolve_local(&child.id)? {
            Some(resolved) => self.delete_resolved(resolved).map(Some),
            None => Ok(None),
        }
    }

    /// The runs linked to session `id` stored in `unit`, and the ones
    /// `--force` must delete while non-terminal. Fails when a non-terminal
    /// run would be deleted without `--force`.
    fn linked_runs(
        &self,
        unit: &SessionUnit,
        id: &str,
    ) -> anyhow::Result<(Vec<LinkedRun>, Vec<String>)> {
        let mut linked = find_nested_runs(unit)?;
        linked.extend(find_parent_linked_runs(self.subagents_root, id)?);
        linked.sort_by(|left, right| {
            left.id
                .cmp(&right.id)
                .then_with(|| left.dir.cmp(&right.dir))
        });

        let mut forced_run_ids = Vec::new();
        for run in &linked {
            if run.state.is_some_and(RunState::is_terminal) {
                continue;
            }
            if !self.options.force {
                return Err(RunNotFinished {
                    session: id.to_owned(),
                    run: run.id.clone(),
                    state: run.state,
                }
                .into());
            }
            forced_run_ids.push(run.id.clone());
        }
        Ok((linked, forced_run_ids))
    }

    /// Deletes `resolved` and its child sessions, marked as being deleted
    /// until it returns so a cycle back to it is skipped.
    fn delete_resolved(&mut self, resolved: ResolvedSession) -> anyhow::Result<DeleteOutcome> {
        let key = (workspace_key(&resolved.cwd), resolved.id.clone());
        self.deleting.insert(key.clone());
        let outcome = self.delete_marked(resolved);
        self.deleting.remove(&key);
        outcome
    }

    /// Refuses as [`Self::delete_resolved`] would, through the same checks,
    /// but deletes nothing: each session the delete would reach is leased
    /// for its delete, its own unless `own_lease` skips it, and its linked
    /// runs are checked. A parent's lease is held while its children are
    /// checked, as the delete holds it.
    fn check_resolved(
        &mut self,
        resolved: ResolvedSession,
        own_lease: OwnLease,
    ) -> anyhow::Result<()> {
        let key = (workspace_key(&resolved.cwd), resolved.id.clone());
        self.deleting.insert(key.clone());
        let checked = self.check_marked(&resolved, own_lease);
        self.deleting.remove(&key);
        checked
    }

    fn check_marked(
        &mut self,
        resolved: &ResolvedSession,
        own_lease: OwnLease,
    ) -> anyhow::Result<()> {
        self.refuse_protected(resolved)?;
        let unit = session_unit(resolved)?;
        let _session_lease = match own_lease {
            OwnLease::Take => Some(self.lease_for_delete(resolved)?),
            OwnLease::Skip => None,
        };
        self.linked_runs(&unit, &resolved.id)?;
        for child in self.child_sessions(resolved)? {
            let checked =
                match SessionStore::new(self.session_root, &child.cwd).resolve_local(&child.id) {
                    Ok(Some(found)) => self.check_resolved(found, OwnLease::Take),
                    // Gone since the index named it.
                    Ok(None) => Ok(()),
                    Err(error) => Err(error),
                };
            checked.map_err(|error| child_not_deleted(&child, resolved, error))?;
        }
        Ok(())
    }

    /// Refuses the delete of the session [`DeleteOptions::protected_session`]
    /// names.
    fn refuse_protected(&self, resolved: &ResolvedSession) -> anyhow::Result<()> {
        if self
            .options
            .protected_session
            .as_ref()
            .is_some_and(|protected| protected.id == resolved.id && protected.cwd == resolved.cwd)
        {
            anyhow::bail!(
                "refusing to delete the current session '{}'; start a new session or resume another first",
                short_id(&resolved.id)
            );
        }
        Ok(())
    }

    /// The lease that deletes `resolved`, refused with
    /// [`super::SessionInUse`] while something holds it.
    fn lease_for_delete(&self, resolved: &ResolvedSession) -> anyhow::Result<lease::SessionLease> {
        lease::acquire(
            self.session_root,
            &resolved.cwd,
            &resolved.id,
            LeasePurpose::Delete,
        )
    }

    fn delete_marked(&mut self, resolved: ResolvedSession) -> anyhow::Result<DeleteOutcome> {
        self.refuse_protected(&resolved)?;
        let unit = session_unit(&resolved)?;
        let _session_lease = self.lease_for_delete(&resolved)?;

        // Child sessions go first, each through this same delete, so a
        // failed one leaves its parent to retry. Check the parent's own
        // refusals before any of them, so a refused delete keeps them all.
        // A child's refusal is found only when its turn comes: the children
        // before it stay deleted, and deleting the parent again finishes.
        let children = self.child_sessions(&resolved)?;
        let mut child_runs = 0;
        let mut child_forced_run_ids = Vec::new();
        let mut deleted_child_session_count = 0;
        if !children.is_empty() {
            self.linked_runs(&unit, &resolved.id)?;
        }
        for child in &children {
            let deleted = self
                .delete_child(child)
                .map_err(|error| child_not_deleted(child, &resolved, error))?;
            let Some(deleted) = deleted else {
                continue;
            };
            child_runs += deleted.deleted_run_count;
            child_forced_run_ids.extend(deleted.forced_run_ids);
            deleted_child_session_count += 1 + deleted.deleted_child_session_count;
        }

        let cleanup_guard = self.runs.lock_parent(&resolved.id)?;
        let (linked, mut forced_run_ids) = self.linked_runs(&unit, &resolved.id)?;

        // Finish every fallible side cleanup while the transcript still exists,
        // so any error leaves an exact target that the caller can retry.
        for run in linked
            .iter()
            .filter(|run| run.cleanup == RunCleanup::Explicit)
        {
            match fs::remove_dir_all(&run.dir) {
                Ok(()) => {}
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => {
                    return Err(anyhow::anyhow!(
                        "could not remove related run {} before deleting session '{}': {error}",
                        run.id,
                        resolved.id
                    ));
                }
            }
        }
        cleanup_guard.clear_index()?;
        unit.delete_from_disk()?;
        drop(cleanup_guard);
        self.removed
            .push((workspace_key(&resolved.cwd), resolved.id.clone()));

        forced_run_ids.extend(child_forced_run_ids);
        Ok(DeleteOutcome {
            deleted_run_count: linked.len() + child_runs,
            id: resolved.id,
            cwd: resolved.cwd,
            path: resolved.path,
            forced_run_ids,
            deleted_child_session_count,
        })
    }

    /// Drop index rows for every deleted session in one commit.
    ///
    /// Best effort: the sessions are already gone from disk, and a leftover
    /// row is ignored by readers and dropped by the next reconcile, so an
    /// index failure must not report a finished delete as failed.
    fn finish(self) {
        if let Err(error) = index::remove_sessions(self.session_root, &self.removed) {
            tracing::warn!(%error, "could not drop deleted sessions from the session index");
        }
    }
}

/// The on-disk unit of `resolved`'s files.
fn session_unit(resolved: &ResolvedSession) -> anyhow::Result<SessionUnit> {
    SessionUnit::from_path(&resolved.path).ok_or_else(|| {
        anyhow::anyhow!(
            "session '{}' has an unrecognized on-disk layout at {}",
            resolved.id,
            resolved.path.display()
        )
    })
}

/// `error`, which refused the delete of `child`, as the refusal of its
/// parent `parent`'s.
fn child_not_deleted(
    child: &SessionTarget,
    parent: &ResolvedSession,
    error: anyhow::Error,
) -> anyhow::Error {
    anyhow::Error::new(ChildSessionNotDeleted {
        child: child.clone(),
        parent: SessionTarget::new(parent.id.clone(), parent.cwd.clone()),
        source: error,
    })
}

fn find_nested_runs(unit: &SessionUnit) -> anyhow::Result<Vec<LinkedRun>> {
    let Some(subagents_dir) = unit.subagents_dir() else {
        return Ok(Vec::new());
    };
    if !subagent::is_trusted_directory(&subagents_dir) {
        return Ok(Vec::new());
    }

    let mut runs = Vec::new();
    for entry in fs::read_dir(subagents_dir)? {
        let dir = entry?.path();
        if !subagent::is_trusted_directory(&dir) {
            continue;
        }
        let Some(id) = dir
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(|id| subagent::normalize_id(id).ok())
        else {
            continue;
        };
        let state = subagent::read_status(&dir.join(RESULT_FILE_NAME)).map(|status| status.state);
        runs.push(LinkedRun {
            dir,
            id,
            state,
            cleanup: RunCleanup::Structural,
        });
    }
    Ok(runs)
}

fn find_parent_linked_runs(
    subagents_root: &Path,
    parent_session_id: &str,
) -> anyhow::Result<Vec<LinkedRun>> {
    let mut runs = Vec::new();
    if !subagent::is_trusted_directory(subagents_root) {
        return Ok(runs);
    }
    for entry in fs::read_dir(subagents_root)? {
        let dir = entry?.path();
        if !subagent::is_trusted_directory(&dir) {
            continue;
        }
        let Some(id) = dir
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(|id| subagent::normalize_id(id).ok())
        else {
            continue;
        };
        let status_path = dir.join(RESULT_FILE_NAME);
        let Some(status) = subagent::read_status(&status_path) else {
            continue;
        };
        if status.parent_session_id.as_deref() != Some(parent_session_id) {
            continue;
        }
        runs.push(LinkedRun {
            dir,
            id,
            state: Some(status.state),
            cleanup: RunCleanup::Explicit,
        });
    }
    Ok(runs)
}

impl super::Session {
    /// Deletes the session saved under exactly `id`, in whichever workspace
    /// it is, with the sessions it started, as `rho sessions rm` does. Hosts
    /// name whole ids, and ids need not be UUIDs, so `id` is never read as a
    /// prefix; one id saved in two workspaces is refused as
    /// [`super::SavedInManyWorkspaces`].
    pub(crate) fn delete_exact(id: &str) -> anyhow::Result<ExactDelete> {
        let Some(target) = saved_target(id)? else {
            return Ok(ExactDelete::NothingSaved);
        };
        Self::delete_target(&target, DeleteOptions::default()).map(ExactDelete::Deleted)
    }

    /// Refuses as [`Self::delete_exact`] would, but deletes nothing and
    /// skips the session's own lease, which the caller holds open: see
    /// [`check_target_in_roots`]. Nothing saved under `id` passes.
    pub(crate) fn check_delete_exact(id: &str) -> anyhow::Result<()> {
        let Some(target) = saved_target(id)? else {
            return Ok(());
        };
        check_target_in_roots(
            &super::session_root()?,
            &crate::paths::rho_dir()?.join("subagents"),
            &target,
            &DeleteOptions::default(),
        )
    }
}

/// The session saved under exactly `id`, in whichever workspace it is.
fn saved_target(id: &str) -> anyhow::Result<Option<SessionTarget>> {
    Ok(super::Session::workspace_of(id)?.map(|cwd| SessionTarget::new(id, cwd)))
}

/// True when the session belongs to a different workspace than `cwd`.
pub fn is_cross_project(session_cwd: &Path, cwd: &Path) -> bool {
    workspace_key(session_cwd) != workspace_key(cwd)
}

#[cfg(test)]
pub(super) fn write_linked_run_for_tests(
    subagents_root: &Path,
    run_id: &str,
    parent_session_id: &str,
    state: RunState,
) -> PathBuf {
    let dir = subagents_root.join(run_id);
    fs::create_dir_all(&dir).unwrap();
    let status = RunStatus {
        state,
        parent_session_id: Some(parent_session_id.to_string()),
        agent_id: Some("worker".into()),
        ..RunStatus::default()
    };
    subagent::initialize_status(&dir.join(RESULT_FILE_NAME), &status).unwrap();
    dir
}

#[cfg(test)]
#[path = "delete_tests.rs"]
mod tests;