rho-coding-agent 1.40.1

A lightweight agent harness inspired by Pi
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
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
#[cfg(test)]
use std::{fs, io::Write};
use std::{
    fs::{File, OpenOptions},
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

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

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

mod delete;
mod index;
mod layout;
#[cfg(test)]
mod performance_benchmarks;
mod persistence;
mod snapshot_delta;
mod snapshot_store;
#[cfg(test)]
#[path = "session_summary_tests.rs"]
mod summary_tests;
#[cfg(test)]
#[path = "session_tests.rs"]
mod tests;
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;

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

pub use delete::{is_cross_project, DeleteOptions, DeleteOutcome};
pub(crate) use delete::{CleanupOutcome, WorkspaceDeleteOutcome};

#[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: Arc<File>,
}

#[derive(Clone, Debug)]
pub struct SessionHistories {
    pub model: Vec<Message>,
    pub display: Vec<Message>,
}

#[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>,
}

/// Exact identity for a session within its owning workspace.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
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(),
        }
    }
}

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

/// 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)]
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,
}
#[derive(Clone, Copy)]
enum LeaseMode {
    Active,
    Delete,
}

fn acquire_session_lease(
    session_root: &Path,
    cwd: &Path,
    id: &str,
    mode: LeaseMode,
) -> anyhow::Result<File> {
    let dir = session_dir_in_root(session_root, cwd);
    std::fs::create_dir_all(&dir)?;
    let path = dir.join(format!(".{id}.active.lock"));
    let file = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&path)?;
    layout::set_private_file_permissions(&file)?;
    let lock = match mode {
        LeaseMode::Active => fs2::FileExt::try_lock_shared(&file),
        LeaseMode::Delete => fs2::FileExt::try_lock_exclusive(&file),
    };
    match lock {
        Ok(()) => Ok(file),
        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => match mode {
            LeaseMode::Active => anyhow::bail!(
                "session '{}' is being deleted by another Rho process; refresh the session list",
                delete::short_id(id)
            ),
            LeaseMode::Delete => anyhow::bail!(
                "refusing to delete active session '{}'; close it in the other Rho process first",
                delete::short_id(id)
            ),
        },
        Err(error) => Err(error.into()),
    }
}

fn acquire_delete_session_lease(session_root: &Path, cwd: &Path, id: &str) -> anyhow::Result<File> {
    acquire_session_lease(session_root, cwd, id, LeaseMode::Delete)
}

impl Session {
    pub fn open_by_id_with_histories(
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<(Self, SessionHistories)> {
        Self::open_by_id_with_histories_in_root(&session_root()?, cwd, id_prefix)
    }

    /// Opens one exact workspace-scoped session without falling back to another workspace.
    pub fn open_target_with_histories(
        target: &SessionTarget,
    ) -> anyhow::Result<(Self, SessionHistories)> {
        Self::open_target_with_histories_in_root(&session_root()?, target)
    }

    #[cfg(test)]
    fn open_by_id_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<(Self, Vec<Message>)> {
        let (session, histories) =
            Self::open_by_id_with_histories_in_root(session_root, cwd, id_prefix)?;
        Ok((session, histories.model))
    }

    pub(crate) fn open_by_id_with_histories_in_root(
        session_root: &Path,
        cwd: &Path,
        id_prefix: &str,
    ) -> anyhow::Result<(Self, SessionHistories)> {
        let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
        Self::open_resolved_with_histories(session_root, resolved)
    }

    pub(crate) fn open_target_with_histories_in_root(
        session_root: &Path,
        target: &SessionTarget,
    ) -> anyhow::Result<(Self, SessionHistories)> {
        let resolved =
            SessionStore::new(session_root, &target.cwd).resolve_in_workspace(&target.id)?;
        Self::open_resolved_with_histories(session_root, resolved)
    }

    fn open_resolved_with_histories(
        session_root: &Path,
        resolved: persistence::ResolvedSession,
    ) -> anyhow::Result<(Self, SessionHistories)> {
        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 =
            acquire_session_lease(session_root, &resolved.cwd, &resolved.id, LeaseMode::Active)?;
        let histories = resolved.histories()?;
        let session = Self::from_parts_with_lease(
            session_root,
            resolved.cwd,
            resolved.id,
            resolved.path,
            active_lease,
        );
        Ok((session, histories))
    }

    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())
    }

    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 = Self::list_in_root(session_root, cwd)
            .ok()
            .and_then(|summaries| {
                summaries
                    .into_iter()
                    .find(|summary| summary.id == resolved.id)
                    .and_then(|summary| summary.title)
            });

        let mut messages = match tree.active_leaf_id() {
            Some(active_leaf_id) => tree.projected_display(active_leaf_id)?,
            None => Vec::new(),
        };
        let complete_len = drop_incomplete_tool_turn_tail(
            messages.iter().map(|entry| entry.message.clone()).collect(),
        )
        .len();
        messages.truncate(complete_len);
        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)>> {
        persistence::read_agent_identity(&self.path)
    }

    /// Provider/API/model identity stored on the session snapshot, when present.
    pub(crate) fn stored_provider_identity(&self) -> anyhow::Result<Option<ModelIdentity>> {
        Ok(persistence::read_session_state(&self.path)?
            .snapshot
            .as_ref()
            .map(|snapshot| snapshot.provider().clone()))
    }

    /// 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<()> {
        self.validate_agent_identity_with(definition.id.as_str(), |stored| {
            definition.accepts_stored_fingerprint(stored)
        })
    }

    fn validate_agent_identity_with(
        &self,
        selected_id: &str,
        accepts_fingerprint: impl FnOnce(&str) -> bool,
    ) -> anyhow::Result<()> {
        let Some((stored_id, stored_fingerprint)) = self.stored_agent_identity()? else {
            anyhow::bail!(
                "cannot resume this session as agent '{selected_id}': the session has no stored agent definition identity"
            );
        };
        if stored_id != selected_id {
            anyhow::bail!(
                "cannot resume session created by agent '{stored_id}' as selected agent '{selected_id}'"
            );
        }
        if !accepts_fingerprint(&stored_fingerprint) {
            anyhow::bail!(
                "cannot resume agent '{selected_id}': its definition changed since the session was created"
            );
        }
        Ok(())
    }

    pub fn list(cwd: &Path) -> anyhow::Result<Vec<SessionSummary>> {
        Self::list_in_root(&session_root()?, cwd)
    }

    /// Lists sessions across every workspace under the session root.
    pub fn list_all() -> anyhow::Result<Vec<SessionSummary>> {
        Self::list_all_in_root(&session_root()?)
    }

    /// 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.
    ///
    /// 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)
    }

    /// 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.trim();
        if title.is_empty() {
            anyhow::bail!("title must not be empty");
        }
        // 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> {
        let resolved = SessionStore::new(session_root, cwd).resolve(id_prefix)?;
        Ok(SessionStore::new(session_root, &resolved.cwd)
            .title(&resolved.id)?
            .is_some())
    }

    fn list_in_root(session_root: &Path, cwd: &Path) -> anyhow::Result<Vec<SessionSummary>> {
        SessionStore::new(session_root, cwd).list()
    }

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

    #[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) -> anyhow::Result<Vec<SessionSummary>> {
        index::list_all_sessions(session_root)
    }

    #[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<_>>();
        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)
    }

    pub(crate) fn create_with_id(
        cwd: &Path,
        id: &str,
        agent_id: &str,
        agent_fingerprint: &str,
    ) -> anyhow::Result<Self> {
        Self::create_with_id_in_root(
            &session_root()?,
            cwd,
            id,
            Some((agent_id, agent_fingerprint)),
        )
    }

    #[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)
    }

    #[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)),
        )
    }

    fn create_with_id_in_root(
        session_root: &Path,
        cwd: &Path,
        id: &str,
        agent: Option<(&str, &str)>,
    ) -> 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)?;
        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 = acquire_session_lease(session_root, cwd, &id, LeaseMode::Active)?;
        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: File,
    ) -> 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: Arc::new(active_lease),
        }
    }

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

    /// Web-access sidecar directory for this session, when the on-disk layout supports one.
    pub(crate) fn web_dir(&self) -> Option<PathBuf> {
        session_web_dir(&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()
    }

    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
    }
}

fn drop_incomplete_tool_turn_tail(mut messages: Vec<Message>) -> Vec<Message> {
    let mut index = 0usize;
    while index < messages.len() {
        let Some(blocks) = messages[index].completed_assistant_content() else {
            index += 1;
            continue;
        };
        let tool_call_ids = blocks
            .iter()
            .filter_map(|block| match block {
                rho_providers::model::ContentBlock::ToolCall(call) => Some(call.id.as_str()),
                rho_providers::model::ContentBlock::Text(_)
                | rho_providers::model::ContentBlock::Image(_) => None,
            })
            .collect::<Vec<_>>();
        if tool_call_ids.is_empty() {
            index += 1;
            continue;
        }

        let results_start = index + 1;
        let results_end = results_start + tool_call_ids.len();
        if results_end > messages.len() {
            messages.truncate(index);
            return messages;
        }

        let complete = tool_call_ids.iter().enumerate().all(|(offset, id)| {
            matches!(
                &messages[results_start + offset],
                Message::ToolResult(result) if result.id == *id
            )
        });
        if !complete {
            messages.truncate(index);
            return messages;
        }
        index = results_end;
    }
    messages
}