rho-coding-agent 3.1.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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
#[cfg(test)]
use std::{fs, io::Write};
use std::{
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

#[cfg(test)]
use uuid::Uuid;

#[cfg(test)]
use rho_providers::model::ContentBlock;
use rho_providers::model::Message;
use rho_sdk::SessionSnapshot;
#[cfg(test)]
use rho_sdk::{CompactionState, Revision, SessionId};

mod agent_identity;
mod append_cursor;
pub(crate) mod catalog;
mod delete;
mod display_rows;
mod id_match;
mod index;
mod layout;
mod lease;
mod persistence;
pub(crate) mod recall;
pub(crate) mod search;
mod search_evidence;
mod search_index;
mod search_journal;
mod search_scope;
mod snapshot_delta;
mod snapshot_store;
#[cfg(test)]
#[path = "session_summary_tests.rs"]
mod summary_tests;
#[cfg(test)]
#[path = "session_tests.rs"]
mod tests;
mod title;
pub(crate) mod tree;
#[cfg(test)]
#[path = "session_tree_tests.rs"]
mod tree_tests;
#[cfg(test)]
#[path = "session_version_tests.rs"]
mod version_tests;
pub(crate) mod workspace_checkpoint;
mod workspace_scope;

use append_cursor::AppendCursor;
#[cfg(test)]
use layout::encode_cwd;
use persistence::{parse_timestamp, session_root, unix_timestamp_secs, SessionStore};
#[cfg(test)]
use persistence::{
    read_entries, session_dir_in_root, summarize_session_file, SessionEntry, SESSION_VERSION,
};

pub(crate) use agent_identity::SavedAgent;
pub use delete::{is_cross_project, DeleteOptions, DeleteOutcome};
pub(crate) use delete::{
    is_in_use, CleanupFailure, CleanupOutcome, ExactDelete, RunNotFinished, WorkspaceDeleteOutcome,
};
pub(crate) use id_match::SavedInManyWorkspaces;
pub(crate) use lease::SessionInUse;
use lease::{LeasePurpose, SessionLease};
pub(crate) use persistence::NoSessionFound;
pub(crate) use title::TitleRejected;
pub(crate) use workspace_scope::Workspace;

#[derive(Clone, Debug)]
pub struct Session {
    id: String,
    path: PathBuf,
    session_root: PathBuf,
    cwd: PathBuf,
    workspace_key: String,
    write_lock: Arc<Mutex<AppendCursor>>,
    _active_lease: SessionLease,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SessionSummary {
    pub id: String,
    pub path: PathBuf,
    pub cwd: PathBuf,
    pub created_at: u64,
    pub updated_at: u64,
    pub message_count: u64,
    pub title: Option<String>,
    pub first_user_message: Option<String>,
    pub last_user_message: Option<String>,
    /// Added directories as last saved, some possibly gone since.
    pub added_dirs: Vec<PathBuf>,
    /// The host that created the session; `None` for a file written before
    /// origins were recorded.
    pub origin: Option<SessionOrigin>,
}

/// Which host created a session, recorded on its header when its file is
/// created so listings can tell the sessions a person had from the ones a
/// program ran.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum SessionOrigin {
    /// The interactive TUI.
    Interactive,
    /// An ACP client, such as Zed or T3 Code, before `rho acp` became a
    /// daemon client (#1670); its sessions now record [`Self::Daemon`].
    Acp,
    /// A session a daemon client started. Whether frontends pass their own
    /// origin once the TUI (#1667) and ACP (#1670) run through the daemon is
    /// decided there.
    Daemon,
    /// `rho run`.
    Run,
    /// A Rho subagent a parent session started.
    Subagent,
    /// An agent node of a workflow run.
    WorkflowNode,
    /// A host a later Rho records that this one does not know. Reading it
    /// leniently keeps such sessions listable and resumable; this binary
    /// never creates it.
    #[serde(other)]
    Unknown,
}

impl SessionSummary {
    /// Whether person-facing listings show this session: its origin is
    /// person-facing, or the file predates origins.
    pub(crate) fn is_person_facing(&self) -> bool {
        self.origin.is_none_or(SessionOrigin::is_person_facing)
    }
}

impl SessionOrigin {
    /// Whether a person had the session, so person-facing listings show
    /// it. A script's `rho run` and a parent's subagents and workflow nodes
    /// are left out: whoever ran one already holds what it returned, and
    /// opening it by id still works. An origin this Rho does not know stays
    /// listed, like a file written before origins were recorded.
    pub(crate) fn is_person_facing(self) -> bool {
        match self {
            Self::Interactive | Self::Acp | Self::Daemon | Self::Unknown => true,
            Self::Run | Self::Subagent | Self::WorkflowNode => false,
        }
    }
}

/// Where a new session came from, as its header records it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SessionProvenance {
    /// The host that created it.
    pub(crate) origin: SessionOrigin,
    /// The saved session that started it, such as a subagent's parent, by
    /// its id and workspace: the same id can be saved in two workspaces.
    /// Deleting that session deletes this one with it.
    pub(crate) parent: Option<SessionTarget>,
}

impl From<SessionOrigin> for SessionProvenance {
    /// A session no other session started.
    fn from(origin: SessionOrigin) -> Self {
        Self {
            origin,
            parent: None,
        }
    }
}

/// Whether a new session is ever written to the session root.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SessionPersistence {
    /// Written from its first save on, so it can be listed and reopened.
    Saved,
    /// Never written: no session file and no index row, so nothing is left
    /// to reopen. `rho run --no-save` runs this way, and so do the Rho
    /// subagents such a run starts, since their parent is nowhere on disk;
    /// its Claude subagents discard their Claude sessions.
    Ephemeral,
}

/// Which saved sessions a listing returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SessionListing {
    /// The sessions a person picks from: pickers, `rho sessions`,
    /// `--continue` and ACP lists. Only person-facing origins (see
    /// [`SessionOrigin::is_person_facing`]) and files older than origins.
    PersonFacing,
    /// Every saved session: exact-id lookups and bulk deletes that must not
    /// strand a hidden session's files.
    Everything,
}

impl SessionListing {
    fn retain(self, sessions: &mut Vec<SessionSummary>) {
        match self {
            Self::PersonFacing => sessions.retain(SessionSummary::is_person_facing),
            Self::Everything => {}
        }
    }
}

/// Exact identity for a session within its owning workspace. A child
/// session's header records its parent's as `{"id": …, "cwd": …}`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SessionTarget {
    pub id: String,
    pub cwd: PathBuf,
}

impl SessionTarget {
    pub fn new(id: impl Into<String>, cwd: impl Into<PathBuf>) -> Self {
        Self {
            id: id.into(),
            cwd: cwd.into(),
        }
    }
}

/// Encoded workspace identity used for session folders and attach scoping.
pub(crate) fn workspace_key(cwd: &Path) -> String {
    layout::workspace_key(cwd)
}

impl SessionSummary {
    pub fn target(&self) -> SessionTarget {
        SessionTarget::new(self.id.clone(), self.cwd.clone())
    }

    /// Whether the session saved anything to resume. A session file exists
    /// from just before its first save, so a process killed in between (or
    /// an older Rho's unprompted ACP session) leaves an empty one.
    pub fn has_messages(&self) -> bool {
        self.message_count > 0
    }
}

/// Result of a successful session title update.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TitleUpdate {
    pub id: String,
    pub cwd: PathBuf,
    pub title: String,
}

/// A display-history message paired with the unix timestamp it was recorded at.
#[derive(Clone, Debug)]
pub struct ExportedMessage {
    pub timestamp: Option<u64>,
    pub message: Message,
}

/// Everything needed to render a session transcript outside the TUI.
#[derive(Clone, Debug)]
pub struct SessionExport {
    pub id: String,
    pub cwd: PathBuf,
    pub created_at: u64,
    pub updated_at: u64,
    pub title: Option<String>,
    pub messages: Vec<ExportedMessage>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct SessionIndexRecord {
    pub(super) summary: SessionSummary,
    pub(super) file_size: Option<i64>,
    pub(super) file_mtime: Option<i64>,
    pub(super) node_count: u64,
    pub(super) branch_count: u64,
    pub(super) active_leaf_id: Option<String>,
    pub(super) effective_format_version: u32,
    /// The session that started this one, from its header; `None` for a
    /// file written before parents were recorded.
    pub(super) parent_session: Option<SessionTarget>,
}

impl Session {
    /// Resolves a resume prefix, with the workspace the session belongs to,
    /// which is another project's when the prefix matched none here,
    /// without opening the session or taking its writer lease. Daemon
    /// clients leave opening to the daemon.
    pub(crate) fn resolve_target(cwd: &Path, id_prefix: &str) -> anyhow::Result<SessionTarget> {
        let root = session_root()?;
        let resolved = SessionStore::new(&root, cwd).resolve(id_prefix)?;
        Ok(SessionTarget::new(resolved.id, resolved.cwd))
    }

    /// The workspace the session saved under exactly `id` belongs to, from
    /// any workspace, or `None` when nothing is saved under it. Opening it
    /// there is [`Self::open_exact_in_workspace`].
    pub(crate) fn workspace_of(id: &str) -> anyhow::Result<Option<PathBuf>> {
        SessionStore::workspace_of(&session_root()?, id)
    }

    /// Opens the session saved under exactly `id` in `cwd`'s workspace, with
    /// its model history, or `None` when nothing is. `id` is never read as a
    /// prefix and no other workspace is searched.
    pub(crate) fn open_exact_in_workspace(
        cwd: &Path,
        id: &str,
    ) -> anyhow::Result<Option<(Self, Vec<Message>)>> {
        let session_root = session_root()?;
        let Some(resolved) = SessionStore::new(&session_root, cwd).resolve_exact_local(id)? else {
            return Ok(None);
        };
        Self::open_resolved_with_history(&session_root, resolved).map(Some)
    }

    #[cfg(test)]
    pub(crate) fn open_by_id_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<(Self, Vec<Message>)> {
        let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
        Self::open_resolved_with_history(session_root, resolved)
    }

    fn open_resolved_with_history(
        session_root: &Path,
        resolved: persistence::ResolvedSession,
    ) -> anyhow::Result<(Self, Vec<Message>)> {
        anyhow::ensure!(
            resolved.cwd.is_dir(),
            "session '{}' belongs to workspace {}, which is no longer an accessible directory. \
             Restore or recreate that directory and resume from there; its transcript \
             is preserved under ~/.rho/sessions.",
            resolved.id,
            resolved.cwd.display(),
        );
        let active_lease = lease::acquire(
            session_root,
            &resolved.cwd,
            &resolved.id,
            LeasePurpose::Open,
        )?;
        let tree = tree::SessionTree::load(&resolved.path)?;
        let history = persistence::history_from_tree(&tree)?;
        let session = Self::from_parts_with_lease(
            session_root,
            resolved.cwd,
            resolved.id,
            resolved.path,
            active_lease,
        );
        session.cache_loaded_tree(tree);
        Ok((session, history))
    }

    pub(crate) fn tree_facts_by_id(
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<tree::SessionTreeFacts> {
        let store = SessionStore::new(&session_root()?, cwd);
        let resolved = store.resolve(id_prefix)?;
        Ok(resolved.tree()?.facts())
    }

    /// Session `id_prefix`'s tree as `/tree` lists it, read without opening
    /// the session, which another process may hold.
    pub(crate) fn tree_turn_items_by_id(
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<Vec<tree::SessionTreeItem>> {
        let store = SessionStore::new(&session_root()?, cwd);
        store.resolve(id_prefix)?.tree()?.turn_items()
    }

    /// The prompt of each of `turns`, nodes of session `id_prefix`'s tree
    /// (see [`tree::SessionTree::turn_prompt`]), read without opening the
    /// session, which another process may hold.
    pub(crate) fn turn_prompts_by_id(
        cwd: &Path,
        id_prefix: &str,
        turns: impl IntoIterator<Item = tree::NodeId>,
    ) -> anyhow::Result<std::collections::HashMap<tree::NodeId, String>> {
        let tree = SessionStore::new(&session_root()?, cwd)
            .resolve(id_prefix)?
            .tree()?;
        Ok(turns
            .into_iter()
            .filter_map(|turn| tree.turn_prompt(&turn).map(|prompt| (turn, prompt)))
            .collect())
    }

    /// Session `id_prefix`'s workspace checkpoints, reached without opening
    /// the session, which another process may hold.
    pub(crate) fn workspace_checkpoint_store_by_id(
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<Option<workspace_checkpoint::WorkspaceCheckpointStore>> {
        let resolved = SessionStore::new(&session_root()?, cwd).resolve(id_prefix)?;
        workspace_checkpoint::WorkspaceCheckpointStore::at(
            &resolved.path,
            &resolved.id,
            workspace_checkpoint::CheckpointLimits::default(),
        )
    }

    pub fn export_by_id(cwd: &Path, id_prefix: &str) -> anyhow::Result<SessionExport> {
        Self::export_by_id_in_root(&session_root()?, cwd, id_prefix)
    }

    pub(crate) fn export_by_id_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<SessionExport> {
        let store = SessionStore::new(session_root, cwd);
        let resolved = store.resolve(id_prefix)?;
        let (record, tree) = resolved.summary_with_tree(cwd)?;
        let title = SessionStore::new(session_root, &resolved.cwd)
            .title(&resolved.id)
            .ok()
            .flatten();

        let messages = match tree.active_leaf_id() {
            Some(active_leaf_id) => persistence::insert_interrupted_display_placeholders(
                tree.projected_display(active_leaf_id)?,
            ),
            None => Vec::new(),
        };
        Ok(SessionExport {
            id: record.summary.id,
            cwd: record.summary.cwd,
            created_at: record.summary.created_at,
            updated_at: record.summary.updated_at,
            title,
            messages: messages
                .into_iter()
                .map(|message| ExportedMessage {
                    timestamp: parse_timestamp(&message.timestamp),
                    message: message.message,
                })
                .collect(),
        })
    }

    pub(crate) fn stored_agent_identity(&self) -> anyhow::Result<Option<(String, String)>> {
        agent_identity::read_agent_identity(&self.path)
    }

    /// The root agent the session reopens under: its own agent, or the
    /// root `/agent:` rebound it from. `None` for a delegated session
    /// written before launch identities were saved; an error for a root
    /// session whose header names no agent.
    pub(crate) fn root_agent(&self) -> anyhow::Result<Option<SavedAgent>> {
        agent_identity::read_root_agent(&self.path)
    }

    /// Rebinds the session to a delegated child agent, only before any
    /// history has been persisted. An initial snapshot is committed atomically
    /// with the identity so reload cannot observe half of the child binding.
    pub(crate) fn rebind_fresh_delegated_agent(
        &self,
        agent_id: &str,
        fingerprint: &str,
        initial_snapshot: Option<&SessionSnapshot>,
    ) -> anyhow::Result<()> {
        self.rewrite_fresh_delegated_identity(agent_id, fingerprint, initial_snapshot)
    }

    /// The host that created the session, or `None` for a file written
    /// before origins were recorded.
    pub(crate) fn origin(&self) -> anyhow::Result<Option<SessionOrigin>> {
        agent_identity::read_origin(&self.path)
    }

    /// The child agent id when the session was rebound as a delegated agent.
    pub(crate) fn delegated_agent_id(&self) -> anyhow::Result<Option<String>> {
        agent_identity::read_delegated_agent_id(&self.path)
    }

    /// Resume check that accepts the current fingerprint or an exact legacy
    /// v1 fingerprint for definitions whose behavior still maps to the old
    /// encoding.
    pub(crate) fn validate_agent_definition_identity(
        &self,
        definition: &crate::agent::AgentDefinition,
    ) -> anyhow::Result<()> {
        agent_identity::validate(&self.path, definition)
    }

    /// [`Self::validate_agent_definition_identity`] for session `target`,
    /// read without opening the session, which another process may hold.
    pub(crate) fn validate_agent_definition_identity_of(
        target: &SessionTarget,
        definition: &crate::agent::AgentDefinition,
    ) -> anyhow::Result<()> {
        let resolved =
            SessionStore::new(&session_root()?, &target.cwd).resolve_in_workspace(&target.id)?;
        agent_identity::validate(&resolved.path, definition)
    }

    /// Lists `listing`'s sessions in workspace `cwd`, newest first.
    pub(crate) fn list(cwd: &Path, listing: SessionListing) -> anyhow::Result<Vec<SessionSummary>> {
        Self::list_in_root(&session_root()?, cwd, listing)
    }

    /// Lists `listing`'s sessions across every workspace under the session
    /// root, newest first.
    pub(crate) fn list_all(listing: SessionListing) -> anyhow::Result<Vec<SessionSummary>> {
        Self::list_all_in_root(&session_root()?, listing)
    }

    /// Lists sessions whose recorded workspace path is no longer a directory.
    ///
    /// Permission and other metadata errors fail closed instead of treating an
    /// inaccessible workspace as deleted.
    pub(crate) fn list_missing_workspaces() -> anyhow::Result<Vec<SessionSummary>> {
        delete::list_missing_workspaces_in_root(&session_root()?)
    }

    pub(crate) fn workspace_directory_is_missing(cwd: &Path) -> anyhow::Result<bool> {
        delete::workspace_directory_is_missing(cwd)
    }

    pub(crate) fn cleanup_missing_targets(
        targets: &[SessionTarget],
        options: DeleteOptions,
    ) -> anyhow::Result<CleanupOutcome> {
        delete::cleanup_missing_targets_in_roots(
            &session_root()?,
            &crate::paths::rho_dir()?.join("subagents"),
            targets,
            &options,
        )
    }

    /// Finds sessions by id prefix without a full cross-project resync.
    ///
    /// Local workspace matches win (same rule as delete/resume). Falls back to
    /// the global session index for other workspaces.
    pub fn find_by_id_prefix(cwd: &Path, id_prefix: &str) -> anyhow::Result<Vec<SessionSummary>> {
        Self::find_by_id_prefix_in_root(&session_root()?, cwd, id_prefix)
    }

    /// Sets a session title after local-then-global id resolution. A title
    /// that is empty once trimmed, holds a control character, or runs over
    /// its budget is refused as [`TitleRejected`].
    ///
    /// Returns the resolved session identity and the stored title so callers
    /// (CLI rename, notices) do not need a second lookup.
    pub fn set_title(cwd: &Path, id_prefix: &str, title: &str) -> anyhow::Result<TitleUpdate> {
        Self::set_title_in_root(&session_root()?, cwd, id_prefix, title)
    }

    /// Auto-title write: sets the title only if the session still has none.
    ///
    /// Returns `Ok(None)` when a manual title already exists (in-process lock or
    /// external `sessions rename`), so generated titles never overwrite it.
    pub(crate) fn set_generated_title(
        cwd: &Path,
        id_prefix: &str,
        title: &str,
    ) -> anyhow::Result<Option<TitleUpdate>> {
        Self::set_generated_title_in_root(&session_root()?, cwd, id_prefix, title)
    }

    /// Whether the resolved session already has a stored title.
    pub(crate) fn title_is_set(cwd: &Path, id_prefix: &str) -> anyhow::Result<bool> {
        Self::title_is_set_in_root(&session_root()?, cwd, id_prefix)
    }

    /// Stored title for the resolved session, if any.
    pub(crate) fn title(cwd: &Path, id_prefix: &str) -> anyhow::Result<Option<String>> {
        Self::title_in_root(&session_root()?, cwd, id_prefix)
    }

    /// Deletes one exact workspace-scoped session.
    pub fn delete_target(
        target: &SessionTarget,
        options: DeleteOptions,
    ) -> anyhow::Result<DeleteOutcome> {
        delete::delete_target_in_roots(
            &session_root()?,
            &crate::paths::rho_dir()?.join("subagents"),
            target,
            &options,
        )
    }

    pub(crate) fn delete_targets(
        targets: &[SessionTarget],
        options: DeleteOptions,
    ) -> anyhow::Result<WorkspaceDeleteOutcome> {
        delete::delete_targets_in_roots(
            &session_root()?,
            &crate::paths::rho_dir()?.join("subagents"),
            targets,
            &options,
        )
    }

    fn set_title_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
        title: &str,
    ) -> anyhow::Result<TitleUpdate> {
        let title = title::checked(title)?;
        // Resolve local-first, then any workspace, so CLI rename matches rm/resume.
        let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
        SessionStore::new(session_root, &resolved.cwd).set_title(&resolved.id, title)?;
        Ok(TitleUpdate {
            id: resolved.id,
            cwd: resolved.cwd,
            title: title.to_string(),
        })
    }

    fn set_generated_title_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
        title: &str,
    ) -> anyhow::Result<Option<TitleUpdate>> {
        let title = title.trim();
        if title.is_empty() {
            anyhow::bail!("title must not be empty");
        }
        let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
        let store = SessionStore::new(session_root, &resolved.cwd);
        if !store.set_title_if_absent(&resolved.id, title)? {
            return Ok(None);
        }
        Ok(Some(TitleUpdate {
            id: resolved.id,
            cwd: resolved.cwd,
            title: title.to_string(),
        }))
    }

    fn title_is_set_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<bool> {
        Ok(Self::title_in_root(session_root, cwd, id_prefix)?.is_some())
    }

    fn title_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<Option<String>> {
        let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
        SessionStore::new(session_root, &resolved.cwd).title(&resolved.id)
    }

    fn list_in_root(
        session_root: &Path,
        cwd: &Path,
        listing: SessionListing,
    ) -> anyhow::Result<Vec<SessionSummary>> {
        let mut sessions = SessionStore::new(session_root, cwd).list()?;
        listing.retain(&mut sessions);
        Ok(sessions)
    }

    #[cfg(test)]
    pub(crate) fn list_in_root_for_test(
        session_root: &Path,
        cwd: &Path,
        listing: SessionListing,
    ) -> anyhow::Result<Vec<SessionSummary>> {
        Self::list_in_root(session_root, cwd, listing)
    }

    #[cfg(test)]
    pub(crate) fn set_title_in_root_for_test(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
        title: &str,
    ) -> anyhow::Result<TitleUpdate> {
        Self::set_title_in_root(session_root, cwd, id_prefix, title)
    }

    #[cfg(test)]
    pub(crate) fn set_generated_title_in_root_for_test(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
        title: &str,
    ) -> anyhow::Result<Option<TitleUpdate>> {
        Self::set_generated_title_in_root(session_root, cwd, id_prefix, title)
    }

    pub(crate) fn list_all_in_root(
        session_root: &Path,
        listing: SessionListing,
    ) -> anyhow::Result<Vec<SessionSummary>> {
        let mut sessions = index::list_all_sessions(session_root)?;
        listing.retain(&mut sessions);
        Ok(sessions)
    }

    #[cfg(test)]
    pub(crate) fn list_missing_workspaces_in_root_for_test(
        session_root: &Path,
    ) -> anyhow::Result<Vec<SessionSummary>> {
        delete::list_missing_workspaces_in_root(session_root)
    }

    #[cfg(test)]
    pub(crate) fn cleanup_missing_workspaces_in_roots_for_test(
        session_root: &Path,
        subagents_root: &Path,
        options: DeleteOptions,
    ) -> anyhow::Result<CleanupOutcome> {
        delete::cleanup_missing_workspaces_in_roots(session_root, subagents_root, &options)
    }

    fn find_by_id_prefix_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<Vec<SessionSummary>> {
        let local = SessionStore::new(session_root, cwd)
            .list()?
            .into_iter()
            .filter(|session| session.id.starts_with(id_prefix))
            .collect::<Vec<_>>();
        let local = id_match::prefer_exact(local, id_prefix, |session| Some(session.id.clone()));
        if !local.is_empty() {
            return Ok(local);
        }
        index::reconcile_all_workspaces(session_root)?;
        index::summaries_matching_id_prefix(session_root, id_prefix)
    }

    #[cfg(test)]
    pub(crate) fn delete_by_id_in_roots(
        session_root: &Path,
        subagents_root: &Path,
        cwd: &Path,
        id_prefix: &str,
        options: DeleteOptions,
    ) -> anyhow::Result<DeleteOutcome> {
        delete::delete_in_roots(session_root, subagents_root, cwd, id_prefix, &options)
    }

    /// Creates the file of session `id`, which came from `provenance` as
    /// the agent `agent_id` with `agent_fingerprint`.
    pub(crate) fn create_with_id(
        cwd: &Path,
        id: &str,
        agent_id: &str,
        agent_fingerprint: &str,
        provenance: SessionProvenance,
    ) -> anyhow::Result<Self> {
        Self::create_with_id_in_root(
            &session_root()?,
            cwd,
            id,
            Some((agent_id, agent_fingerprint)),
            provenance,
        )
    }

    #[cfg(test)]
    pub(crate) fn create_in_root(session_root: &Path, cwd: &Path) -> anyhow::Result<Self> {
        Self::create_with_id_in_root(
            session_root,
            cwd,
            &Uuid::new_v4().to_string(),
            None,
            SessionOrigin::Interactive.into(),
        )
    }

    #[cfg(test)]
    pub(crate) fn create_with_id_in_root_for_test(
        session_root: &Path,
        cwd: &Path,
        id: &str,
    ) -> anyhow::Result<Self> {
        Self::create_with_id_in_root(
            session_root,
            cwd,
            id,
            None,
            SessionOrigin::Interactive.into(),
        )
    }

    #[cfg(test)]
    pub(crate) fn create_in_root_with_agent(
        session_root: &Path,
        cwd: &Path,
        agent_id: &str,
        agent_fingerprint: &str,
    ) -> anyhow::Result<Self> {
        Self::create_with_id_in_root(
            session_root,
            cwd,
            &Uuid::new_v4().to_string(),
            Some((agent_id, agent_fingerprint)),
            SessionOrigin::Interactive.into(),
        )
    }

    fn create_with_id_in_root(
        session_root: &Path,
        cwd: &Path,
        id: &str,
        agent: Option<(&str, &str)>,
        provenance: SessionProvenance,
    ) -> anyhow::Result<Self> {
        let store = SessionStore::new(session_root, cwd);
        let id = id.to_string();
        let created_at = unix_timestamp_secs();
        let path = store.create_path(&id, created_at)?;
        let session = Self::from_parts(session_root, cwd, id.clone(), path)?;
        session.append_session_metadata(id, created_at, agent, provenance)?;
        Ok(session)
    }

    #[cfg(test)]
    pub fn append_message(&self, message: &Message) -> anyhow::Result<()> {
        self.append_stored_message(message, None)
    }

    #[cfg(test)]
    pub fn append_message_with_display(
        &self,
        message: &Message,
        display_message: &Message,
    ) -> anyhow::Result<()> {
        self.append_stored_message(message, Some(display_message))
    }

    #[cfg(test)]
    pub fn replace_history(&self, messages: &[Message]) -> anyhow::Result<()> {
        self.append_replaced_history(messages)
    }

    fn from_parts(
        session_root: &Path,
        cwd: &Path,
        id: String,
        path: PathBuf,
    ) -> anyhow::Result<Self> {
        let active_lease = lease::acquire(session_root, cwd, &id, LeasePurpose::Open)?;
        Ok(Self::from_parts_with_lease(
            session_root,
            cwd.to_path_buf(),
            id,
            path,
            active_lease,
        ))
    }

    fn from_parts_with_lease(
        session_root: &Path,
        cwd: PathBuf,
        id: String,
        path: PathBuf,
        active_lease: SessionLease,
    ) -> Self {
        Self {
            workspace_key: workspace_key(&cwd),
            id,
            path,
            session_root: session_root.to_path_buf(),
            cwd,
            write_lock: Arc::new(Mutex::new(AppendCursor::default())),
            _active_lease: active_lease,
        }
    }

    #[cfg(test)]
    pub(crate) fn active_lease_for_tests(&self) -> &SessionLease {
        &self._active_lease
    }

    #[cfg(test)]
    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    /// Delegated run artifact directory owned by this folder-layout session.
    pub(crate) fn subagents_dir(&self) -> Option<PathBuf> {
        persistence::SessionUnit::from_path(&self.path)?.subagents_dir()
    }

    /// Elided tool-result originals owned by this folder-layout session.
    pub(crate) fn recall_dir(&self) -> Option<PathBuf> {
        persistence::SessionUnit::from_path(&self.path)?.recall_dir()
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// The workspace directory this session belongs to. For a session resumed by
    /// id from another directory, this is its original workspace, not the
    /// process cwd.
    pub(crate) fn cwd(&self) -> &Path {
        &self.cwd
    }
}