merry 0.1.4

Rust SDK facade for the Merry coding agent runtime (CLI available as `merry-cli`).
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
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
//! High-level coding session facade shared by terminal UI, headless CLI,
//! WebUI backends, and Rust SDK hosts.
//!
//! [`CodingSession`] owns the full coding-agent session lifecycle—including
//! exclusive OS-level session locking, resume error classification, durable
//! memory attachment, interactive and single-shot execution, and read-only
//! observability—without requiring callers to manipulate `merry-runtime`
//! primitives directly.

use crate::observability::TrajectoryHandle;
pub(crate) mod surface {
    pub use merry_coding::{
        CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT, CODING_AGENT_POLICY_PROMPT, CODING_AGENT_PROFILE_ID,
        CODING_AGENT_STABLE_PREFIX_LAYOUT, CODING_LOOP_PROCESS_TOOL, CodingAgentProfile,
        CodingAgentProfileBuildError, CodingAgentProfileBuilder, CodingAgentProfileHash,
        CodingAgentRunPolicy, CodingAgentRunPolicyError, CodingAutoFallback,
        CodingFinalReportPolicy, CodingModelRoleConfig, CodingModelRoleConfigError,
        CodingPermissionMode, CodingPermissionPolicy, CodingPermissionPolicyError, CodingRuntime,
        CodingRuntimeBuildError, CodingRuntimeBuilder, CodingRuntimeInput, CodingSubagentsConfig,
        CodingWorkflowCommand, DEFAULT_CODING_AGENT_MAX_MODEL_TURNS,
        DEFAULT_CODING_SUBAGENT_MAX_MODEL_TURNS, MAX_ROLE_PROMPT_FILE_BYTES,
        MAX_ROOT_PROJECT_RULES_BYTES, MIN_CODING_SUBAGENT_MODEL_TURNS, ProjectRulesLoadError,
        ROOT_PROJECT_RULES_FILE, ResolvedSubagentRuntime, SubagentDefaultOverride,
        SubagentModelOverride, SubagentResolutionInput, SubagentRoleCatalog, SubagentRoleError,
        SubagentRoleOverlay, SubagentRoleSpec, SubagentWorkspaceAccess, WorkspaceToolLimits,
        WorktreeError, WorktreeGcReport, WorktreeIsolationManager, cleanup_orphaned_worktrees,
        cleanup_orphaned_worktrees_default, coding_agent, default_worktree_base_dir,
        load_root_project_rules, load_workspace_prompt_file, resolve_subagent_runtime,
    };
}
use merry_core::{
    PlanDocument, PlanSessionSnapshot, SessionId, SessionUsage, SubagentId, TodoItem, ToolCallId,
    ToolOutput,
};
use merry_llm::GenerationConfig;
pub use merry_runtime::{
    AgentLoopConfig, AgentLoopControl, AgentLoopInput, AgentLoopResult, AgentRun, AgentRunMessage,
    BackgroundProcessId, BackgroundProcessLookupError, BackgroundProcessOutput,
    BackgroundProcessStop, BackgroundProcessSummary, CitationCompactionPolicy,
    DEFAULT_CONTEXT_WINDOW_FALLBACK_TOKENS, DEFAULT_FOREGROUND_WAIT_BUDGET_SECS, DurableMemory,
    FileSessionStore, InteractiveError, InteractiveProcessExecutionUpdate,
    InteractiveRunEventStream, InteractiveRunMessage, InteractiveSettingsUpdate,
    InteractiveSubagentSettings, MemoryLayout, RuntimeError, RuntimeModelRole, SessionStoreError,
    SessionTranscriptItem, SkillMetadata, SubagentActivityReceiver, SubagentConfig,
    SubagentInspectSession, SubagentLimitBehavior, SubagentStatusView, WaitSubagentsOutput,
};
use merry_runtime::{LoadedSession, Runtime, SessionReservation, StepContext, StepInput};
use std::path::{Path, PathBuf};
pub use surface::*;
use thiserror::Error;

/// Whether [`CodingSessionBuilder::open`] starts a fresh session or resumes a
/// previously saved session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodingSessionOpenMode {
    /// Start a new session and fail if persisted state already exists for this
    /// session ID.
    New,
    /// Resume an existing persisted session from the session store.
    Resume,
}

/// Structured classification for why a saved session cannot be resumed
/// directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodingSessionResumeFailure {
    /// Another active process currently holds the exclusive session lock.
    AlreadyOpen,
    /// The saved session files are corrupt, unreadable, or from an incompatible
    /// schema version.
    IncompatibleFormat,
}

/// Errors raised while opening or resuming a persisted [`CodingSession`].
#[derive(Debug, Error)]
pub enum CodingSessionOpenError {
    /// A new session was requested for an ID that already has saved state.
    #[error("session {session_id} already has saved state")]
    SessionAlreadyExists {
        /// Conflicting session identifier.
        session_id: SessionId,
    },
    /// A saved session cannot be resumed directly (locked or incompatible).
    #[error("could not resume session {session_id}: {message}")]
    ResumeUnavailable {
        /// Why resuming failed.
        kind: CodingSessionResumeFailure,
        /// Session identifier that could not be resumed.
        session_id: SessionId,
        /// On-disk session directory path for diagnostics or recovery UI.
        session_dir: PathBuf,
        /// Underlying failure details.
        message: String,
    },
    /// The session store failed while reserving or inspecting session state.
    #[error("session store error: {source}")]
    SessionStore {
        /// Underlying session store failure.
        #[source]
        source: SessionStoreError,
    },
    /// Building the coding runtime failed.
    #[error(transparent)]
    Build {
        /// Underlying coding runtime build error.
        #[from]
        source: CodingRuntimeBuildError,
    },
}

/// Classifies whether a [`RuntimeError`] from loading a saved session maps to a
/// structured [`CodingSessionResumeFailure`].
#[must_use]
pub fn classify_resume_error(error: &RuntimeError) -> Option<CodingSessionResumeFailure> {
    match error {
        RuntimeError::SessionStore {
            source: SessionStoreError::SessionAlreadyReserved { .. },
        } => Some(CodingSessionResumeFailure::AlreadyOpen),
        RuntimeError::SessionStore {
            source:
                SessionStoreError::UnsupportedFormatVersion { .. }
                | SessionStoreError::InvalidDocument { .. }
                | SessionStoreError::Json { .. }
                | SessionStoreError::SessionIdMismatch { .. }
                | SessionStoreError::Io { .. },
        } => Some(CodingSessionResumeFailure::IncompatibleFormat),
        _ => None,
    }
}

/// Opens durable memory under an explicit `memory_root` for `input.root()`,
/// attaching it when available or logging a warning and continuing without it.
#[must_use]
pub fn attach_durable_memory_at(
    input: CodingRuntimeInput,
    memory_root: &Path,
) -> CodingRuntimeInput {
    let root = input.root().to_path_buf();
    match MemoryLayout::at(memory_root, &root).and_then(DurableMemory::open) {
        Ok(memory) => input.durable_memory(memory),
        Err(error) => {
            tracing::warn!(
                event = "memory.open_failed",
                error = %error,
                "durable memory is unavailable; continuing without it"
            );
            input
        }
    }
}

/// Opens XDG durable memory for `input.root()`, attaching it when available or
/// logging a warning and continuing without durable memory on error.
#[must_use]
pub fn attach_durable_memory_from_env(input: CodingRuntimeInput) -> CodingRuntimeInput {
    let root = input.root().to_path_buf();
    match DurableMemory::open_from_env(&root) {
        Ok(memory) => input.durable_memory(memory),
        Err(error) => {
            tracing::warn!(
                event = "memory.open_failed",
                error = %error,
                "durable memory is unavailable; continuing without it"
            );
            input
        }
    }
}

/// Builder for a high-level [`CodingSession`].
///
/// Wraps [`CodingRuntimeBuilder`] with session locking, resume classification,
/// optional MCP toolset attachment, and environment-backed durable memory so
/// TUI, headless CLI, WebUI, and SDK hosts share one lifecycle contract.
pub struct CodingSessionBuilder {
    input: CodingRuntimeInput,
    permission_policy: CodingPermissionPolicy,
    session_store: Option<FileSessionStore>,
    loaded_session: Option<LoadedSession>,
}

impl CodingSessionBuilder {
    /// Creates a new coding session builder from validated coding runtime inputs.
    #[must_use]
    pub fn new(input: CodingRuntimeInput) -> Self {
        Self {
            input,
            permission_policy: CodingPermissionPolicy::default(),
            session_store: None,
            loaded_session: None,
        }
    }

    /// Sets the coding permission review policy.
    #[must_use]
    pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
        self.permission_policy = policy;
        self
    }

    /// Attaches a session store for automatic savepoints when building directly
    /// with [`Self::build`].
    #[must_use]
    pub fn session_store(mut self, store: FileSessionStore) -> Self {
        self.session_store = Some(store);
        self
    }

    /// Attaches discovered MCP meta-tools without exposing internal runtime
    /// tool registration types.
    #[cfg(feature = "mcp")]
    #[must_use]
    pub fn mcp_tools(mut self, toolset: crate::mcp::McpToolset) -> Self {
        let (tools, _warnings) = toolset.into_parts();
        self.input = self.input.with_extra_tools(tools);
        self
    }

    /// Opens durable memory under an explicit `memory_root` instead of reading
    /// XDG/HOME environment variables, logging a warning and continuing without
    /// durable memory if it is unavailable.
    #[must_use]
    pub fn with_durable_memory_at(mut self, memory_root: &Path) -> Self {
        self.input = attach_durable_memory_at(self.input, memory_root);
        self
    }

    /// Opens XDG durable memory for the workspace root, logging a warning and
    /// continuing without durable memory if it is unavailable.
    #[must_use]
    pub fn with_durable_memory_from_env(mut self) -> Self {
        self.input = attach_durable_memory_from_env(self.input);
        self
    }

    /// Sets saved per-workspace AI review guidance notes inherited live by
    /// both parent and child coding runtimes.
    #[must_use]
    pub fn with_workspace_review_notes(mut self, notes: Vec<String>) -> Self {
        self.input = self.input.with_workspace_review_notes(notes);
        self
    }

    /// Builds an in-memory or pre-configured [`CodingSession`] without
    /// acquiring a new reservation from a store.
    pub fn build(self) -> Result<CodingSession, CodingRuntimeBuildError> {
        let mut reservation = None;
        self.build_with_reservation(&mut reservation)
    }

    fn build_with_reservation(
        self,
        reservation: &mut Option<SessionReservation>,
    ) -> Result<CodingSession, CodingRuntimeBuildError> {
        let mut builder =
            CodingRuntimeBuilder::new(self.input).permission_policy(self.permission_policy);
        if let Some(loaded) = self.loaded_session {
            builder = builder.with_loaded_session(loaded);
        }
        if let Some(store) = self.session_store {
            builder = builder.session_store(store);
        }
        let coding_runtime = builder.build_with_reservation(reservation)?;
        let loop_config = coding_runtime.loop_config();
        let runtime = coding_runtime.into_runtime();
        let agent = crate::Agent::from_runtime_parts(
            runtime,
            loop_config,
            GenerationConfig::default(),
            None,
        );
        Ok(CodingSession { agent })
    }

    /// Reserves the session lock in `store`, validates new-vs-resume state,
    /// loads any saved transcript when resuming, and builds a [`CodingSession`]
    /// whose underlying [`Runtime`] owns the exclusive lock for its lifetime.
    pub async fn open(
        mut self,
        store: FileSessionStore,
        mode: CodingSessionOpenMode,
    ) -> Result<CodingSession, CodingSessionOpenError> {
        let session_id = self.input.session_id().clone();
        let mut reservation = match store.reserve_session(&session_id).await {
            Ok(reservation) => Some(reservation),
            Err(SessionStoreError::SessionAlreadyReserved { .. })
                if mode == CodingSessionOpenMode::Resume =>
            {
                return Err(CodingSessionOpenError::ResumeUnavailable {
                    kind: CodingSessionResumeFailure::AlreadyOpen,
                    session_dir: store.session_dir(&session_id),
                    session_id,
                    message: "session is already open in another process".to_owned(),
                });
            }
            Err(source) => return Err(CodingSessionOpenError::SessionStore { source }),
        };

        match mode {
            CodingSessionOpenMode::New => {
                let exists = match store.contains_session(&session_id).await {
                    Ok(exists) => exists,
                    Err(source) => {
                        if let Some(res) = reservation.take() {
                            store.release_empty_reservation(&session_id, res).await;
                        }
                        return Err(CodingSessionOpenError::SessionStore { source });
                    }
                };
                if exists {
                    if let Some(res) = reservation.take() {
                        store.release_empty_reservation(&session_id, res).await;
                    }
                    return Err(CodingSessionOpenError::SessionAlreadyExists { session_id });
                }
            }
            CodingSessionOpenMode::Resume => {
                let loaded = match LoadedSession::load(&store, &session_id).await {
                    Ok(loaded) => loaded,
                    Err(error) => {
                        if let Some(res) = reservation.take() {
                            store.release_empty_reservation(&session_id, res).await;
                        }
                        return Err(CodingSessionOpenError::ResumeUnavailable {
                            kind: classify_resume_error(&error)
                                .unwrap_or(CodingSessionResumeFailure::IncompatibleFormat),
                            session_dir: store.session_dir(&session_id),
                            session_id: session_id.clone(),
                            message: error.to_string(),
                        });
                    }
                };
                self.loaded_session = Some(loaded);
            }
        }

        self.session_store = Some(store.clone());
        match self.build_with_reservation(&mut reservation) {
            Ok(session) => Ok(session),
            Err(source) => {
                if let Some(res) = reservation.take() {
                    store.release_empty_reservation(&session_id, res).await;
                }
                Err(CodingSessionOpenError::Build { source })
            }
        }
    }
}

/// Interactive handles returned by [`CodingSession::start_interactive`].
pub struct InteractiveCodingRun {
    /// Live stream of runtime events and turn messages.
    pub stream: InteractiveRunEventStream,
    /// Handle for submitting user prompts and queued inputs.
    pub input: AgentLoopInput,
    /// Handle for interrupting turns, compacting context, updating settings,
    /// and saving the session while running.
    pub control: AgentLoopControl,
    /// Watch channel carrying live UI-only subagent activity snapshots.
    pub subagent_activity: SubagentActivityReceiver,
    /// Loaded skill metadata available in this session.
    pub skills: Vec<SkillMetadata>,
}

/// High-level owned coding session with lifecycle lock management.
///
/// Hosts (TUI, headless CLI, WebUI, or Rust SDK applications) own one
/// `CodingSession` per active session and clone [`CodingSessionHandle`] into
/// background tasks, HTTP handlers, or UI effect loops. The session is backed
/// directly by [`crate::Agent`] so callers can also use [`Self::as_agent`] or
/// [`Self::into_agent`] for unified single-shot, structured, and streaming APIs.
pub struct CodingSession {
    agent: crate::Agent,
}

impl CodingSession {
    /// Creates a [`CodingSessionBuilder`] for the supplied coding inputs.
    #[must_use]
    pub fn builder(input: CodingRuntimeInput) -> CodingSessionBuilder {
        CodingSessionBuilder::new(input)
    }

    /// Borrows the unified [`crate::Agent`] facade backing this coding session.
    #[must_use]
    pub fn as_agent(&self) -> &crate::Agent {
        &self.agent
    }

    /// Consumes this coding session and returns its underlying [`crate::Agent`]
    /// facade while retaining the runtime-owned session reservation.
    #[must_use]
    pub fn into_agent(self) -> crate::Agent {
        self.agent
    }

    /// Returns the session identifier.
    #[must_use]
    pub fn session_id(&self) -> &SessionId {
        self.agent.session_id()
    }

    /// Returns a cheap, cloneable handle for session inspection, subagent
    /// control, background process control, and persistence.
    #[must_use]
    pub fn handle(&self) -> CodingSessionHandle {
        self.agent.session_handle()
    }

    /// Returns a read-only trajectory handle suitable for `merry-web` or other
    /// observability surfaces.
    #[must_use]
    pub fn trajectory_handle(&self) -> TrajectoryHandle {
        self.agent.trajectory_handle()
    }

    /// Returns the coding agent loop configuration for this session.
    #[must_use]
    pub fn loop_config(&self) -> AgentLoopConfig {
        self.agent.loop_config().clone()
    }

    /// Starts an interactive coding run with live event streaming, input queue,
    /// runtime settings control, and subagent activity watch channel.
    pub async fn start_interactive(
        &self,
        generation: GenerationConfig,
    ) -> Result<InteractiveCodingRun, RuntimeError> {
        let handle = self.handle();
        let skills = handle.skills().await;
        let interactive = self.agent.runtime().start_interactive_agent_run(
            StepContext::default().with_generation_config(generation),
            self.loop_config(),
        )?;
        let subagent_activity = handle.subscribe_subagent_activity();
        let (stream, input, control) = interactive.split();
        Ok(InteractiveCodingRun {
            stream,
            input,
            control,
            subagent_activity,
            skills,
        })
    }

    /// Starts a single-shot streaming coding run (used by headless CLI or
    /// non-interactive Web/SDK tasks).
    pub fn run_stream(
        &self,
        task: &str,
        generation: GenerationConfig,
    ) -> Result<AgentRun, RuntimeError> {
        self.handle()
            .run_agent_loop_stream(task, generation, self.loop_config())
    }

    /// Closes the underlying session, releasing any held session reservation
    /// and removing the session directory if the session exited without
    /// writing persisted files.
    pub async fn discard_if_empty(&mut self) {
        let _ = self.agent.close().await;
    }

    /// Consumes this session and returns the underlying runtime handle for
    /// advanced low-level integrations.
    #[doc(hidden)]
    #[must_use]
    pub fn into_runtime(self) -> Runtime {
        self.agent.into_runtime()
    }
}

impl From<CodingSession> for crate::Agent {
    fn from(session: CodingSession) -> Self {
        session.into_agent()
    }
}

/// Cloneable inspection and control handle for an active [`CodingSession`].
///
/// Designed to be shared across TUI effect workers, WebUI HTTP/WebSocket
/// handlers, and SDK orchestration tasks without exposing `merry-runtime`
/// internals.
#[derive(Clone)]
pub struct CodingSessionHandle {
    runtime: Runtime,
}

impl CodingSessionHandle {
    /// Creates a handle from a low-level runtime (internal escape hatch for
    /// fixtures and tests).
    #[doc(hidden)]
    #[must_use]
    pub fn from_runtime(runtime: Runtime) -> Self {
        Self { runtime }
    }

    /// Returns the session identifier.
    #[must_use]
    pub fn session_id(&self) -> &SessionId {
        self.runtime.session_id()
    }

    /// Returns a read-only trajectory handle for observability and Web viewers.
    #[must_use]
    pub fn trajectory_handle(&self) -> TrajectoryHandle {
        TrajectoryHandle::from_runtime(self.runtime.clone())
    }

    /// Returns loaded skill metadata for this session.
    pub async fn skills(&self) -> Vec<SkillMetadata> {
        self.runtime.skills().await
    }

    /// Subscribes to live UI-only subagent activity snapshots.
    #[must_use]
    pub fn subscribe_subagent_activity(&self) -> SubagentActivityReceiver {
        self.runtime.subscribe_subagent_activity()
    }

    /// Returns aggregated session token usage, if any model turn has completed.
    pub async fn usage(&self) -> Option<SessionUsage> {
        self.runtime.usage().await
    }

    /// Returns the projected session transcript items.
    pub async fn session_transcript(&self) -> Result<Vec<SessionTranscriptItem>, RuntimeError> {
        self.runtime.session_transcript().await
    }

    /// Lists archived compacted segment numbers for lazy history loading.
    pub async fn archived_segment_numbers(&self) -> Result<Vec<u32>, RuntimeError> {
        self.runtime.archived_segment_numbers().await
    }

    /// Loads transcript items from one archived compacted segment.
    pub async fn read_archived_segment_transcript(
        &self,
        segment_number: u32,
    ) -> Result<Vec<SessionTranscriptItem>, RuntimeError> {
        self.runtime
            .read_archived_segment_transcript(segment_number)
            .await
    }

    /// Reads the full recorded output of a tool call.
    pub async fn read_tool_output(
        &self,
        call_id: &ToolCallId,
    ) -> Result<Option<ToolOutput>, RuntimeError> {
        self.runtime.read_tool_output(call_id).await
    }

    /// Returns the current Plan Mode snapshot.
    pub async fn plan_session_snapshot(&self) -> PlanSessionSnapshot {
        self.runtime.plan_session_snapshot().await
    }

    /// Returns all Markdown plan documents authored in this session.
    pub async fn plan_documents(&self) -> Vec<PlanDocument> {
        self.runtime.plan_documents().await
    }

    /// Returns the current session todo items.
    pub async fn todo_items(&self) -> Vec<TodoItem> {
        self.runtime.todo_items().await
    }

    /// Returns the already-cached session topic without waiting on background
    /// topic generation.
    pub async fn cached_session_topic(&self) -> Option<String> {
        self.runtime.cached_session_topic().await
    }

    /// Returns the session topic, awaiting any in-flight topic generation task.
    pub async fn session_topic(&self) -> Option<String> {
        self.runtime.session_topic().await
    }

    /// Returns current status views for all managed subagents, if subagents are
    /// configured.
    pub async fn subagent_snapshot(&self) -> Option<Vec<SubagentStatusView>> {
        self.runtime.subagent_snapshot().await
    }

    /// Opens an inspection handle (task, transcript, live event stream) for one
    /// subagent.
    pub async fn inspect_subagent(&self, agent_id: &SubagentId) -> Option<SubagentInspectSession> {
        self.runtime.inspect_subagent(agent_id).await
    }

    /// Sends a follow-up message to a managed subagent.
    pub async fn send_subagent_message(
        &self,
        agent_id: &SubagentId,
        message: String,
    ) -> Result<(), RuntimeError> {
        self.runtime.send_subagent_message(agent_id, message).await
    }

    /// Cancels a running subagent.
    pub async fn cancel_subagent(
        &self,
        agent_id: &SubagentId,
    ) -> Result<WaitSubagentsOutput, RuntimeError> {
        self.runtime.cancel_subagent(agent_id).await
    }

    /// Lists retained background processes owned by this session.
    #[must_use]
    pub fn background_processes(&self) -> Vec<BackgroundProcessSummary> {
        self.runtime.background_processes()
    }

    /// Reads captured output for one retained background process.
    pub fn read_background_process(
        &self,
        id: &BackgroundProcessId,
    ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
        self.runtime.read_background_process(id)
    }

    /// Stops one retained background process group.
    pub fn stop_background_process(
        &self,
        id: &BackgroundProcessId,
    ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
        self.runtime.stop_background_process(id)
    }

    /// Returns a point-in-time snapshot of all active session-scoped permission
    /// grants and user-authored session review guidance notes.
    #[must_use]
    pub fn active_permission_grants(&self) -> crate::permissions::ActivePermissionGrants {
        self.runtime.active_permission_grants()
    }

    /// Revokes one active session-scoped permission grant by its stable ID.
    pub fn revoke_session_grant(
        &self,
        id: crate::permissions::SessionGrantId,
    ) -> Result<bool, crate::process::ProcessRunnerError> {
        self.runtime.revoke_session_grant(id)
    }

    /// Clears all active session-scoped permission grants immediately.
    pub fn clear_session_grants(&self) -> Result<(), crate::process::ProcessRunnerError> {
        self.runtime.clear_session_grants()
    }

    /// Revokes one session-scoped human review guidance note by its stable ID.
    #[must_use]
    pub fn revoke_review_guidance(&self, id: crate::permissions::ReviewGuidanceId) -> bool {
        self.runtime.revoke_review_guidance(id)
    }

    /// Replaces the live workspace-scoped AI review guidance notes observed by
    /// this session and its managed subagents.
    pub fn set_workspace_review_notes(&self, notes: Vec<String>) {
        self.runtime.set_workspace_review_notes(notes);
    }

    /// Marks any pending tool calls as failed so an interrupted session can be
    /// saved and safely resumed.
    pub async fn abandon_pending_tool_calls(&self, reason: &str) -> Result<usize, RuntimeError> {
        self.runtime.abandon_pending_tool_calls(reason).await
    }

    /// Saves the session state to `store`.
    pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), RuntimeError> {
        self.runtime.save_session_to(store).await
    }

    /// Starts a single-shot agent loop stream with an explicit loop config and
    /// generation settings.
    pub fn run_agent_loop_stream(
        &self,
        task: &str,
        generation: GenerationConfig,
        loop_config: AgentLoopConfig,
    ) -> Result<AgentRun, RuntimeError> {
        let input = StepInput::user_text(task)?;
        let context = StepContext::default().with_generation_config(generation);
        self.runtime
            .run_agent_loop_stream(input, context, loop_config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use merry_llm::{
        FinishReason, ModelCapabilities, ModelError, ModelEvent, ModelEventStream, ModelName,
        ModelOutput, ModelProvider, ModelProviderFuture, ModelRequest, ModelResponse,
        ModelStreamContext,
    };
    use merry_process::{LocalProcessBackend, ProcessBackendMode, ProcessBackendOptions};
    use std::sync::{Arc, OnceLock};

    struct StaticProvider;

    impl ModelProvider for StaticProvider {
        fn name(&self) -> &merry_core::ProviderName {
            static NAME: OnceLock<merry_core::ProviderName> = OnceLock::new();
            NAME.get_or_init(|| merry_core::ProviderName::new("coding-session-test").unwrap())
        }

        fn capabilities(&self) -> &ModelCapabilities {
            static CAPS: OnceLock<ModelCapabilities> = OnceLock::new();
            CAPS.get_or_init(|| {
                ModelCapabilities::new(true, true, false, true, None, None).unwrap()
            })
        }

        fn stream_model<'a>(
            &'a self,
            _request: ModelRequest,
            _context: ModelStreamContext,
        ) -> ModelProviderFuture<'a, Result<ModelEventStream, ModelError>> {
            Box::pin(async move {
                let response =
                    ModelResponse::new(vec![ModelOutput::text("ok")], FinishReason::Stop, None);
                let stream: ModelEventStream = Box::pin(futures_util::stream::iter([
                    Ok(ModelEvent::Started),
                    Ok(ModelEvent::Completed { response }),
                ]));
                Ok(stream)
            })
        }
    }

    fn test_input(session_id: &str, workspace: &std::path::Path) -> CodingRuntimeInput {
        let backend = Arc::new(
            LocalProcessBackend::new(
                workspace,
                ProcessBackendMode::Host,
                ProcessBackendOptions::new(),
            )
            .expect("host backend should build"),
        );
        CodingRuntimeInput::new(
            SessionId::new(session_id).expect("valid session id"),
            workspace,
            Arc::new(StaticProvider),
            ModelName::new("test-model").expect("valid model"),
            backend,
        )
    }

    #[tokio::test]
    async fn coding_session_open_enforces_lock_and_new_collision_and_resume() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        let store = FileSessionStore::new(temp.path().join("sessions"));

        // 1. Open new session, hold lock, verify concurrent resume returns AlreadyOpen.
        let session = CodingSession::builder(test_input("webui-session-1", &workspace))
            .open(store.clone(), CodingSessionOpenMode::New)
            .await
            .expect("new coding session should open");
        assert_eq!(session.session_id().as_str(), "webui-session-1");
        assert_eq!(
            session.trajectory_handle().session_id().as_str(),
            "webui-session-1"
        );

        let locked = CodingSession::builder(test_input("webui-session-1", &workspace))
            .open(store.clone(), CodingSessionOpenMode::Resume)
            .await;
        assert!(matches!(
            locked,
            Err(CodingSessionOpenError::ResumeUnavailable {
                kind: CodingSessionResumeFailure::AlreadyOpen,
                ..
            })
        ));

        // 2. Save session, release lock, verify New refuses existing state and Resume succeeds.
        session
            .handle()
            .save_session_to(store.clone())
            .await
            .expect("session should save");
        drop(session);

        let collision = CodingSession::builder(test_input("webui-session-1", &workspace))
            .open(store.clone(), CodingSessionOpenMode::New)
            .await;
        assert!(matches!(
            collision,
            Err(CodingSessionOpenError::SessionAlreadyExists { .. })
        ));

        let resumed = CodingSession::builder(test_input("webui-session-1", &workspace))
            .open(store.clone(), CodingSessionOpenMode::Resume)
            .await
            .expect("saved session should resume");
        let interactive = resumed
            .start_interactive(GenerationConfig::default())
            .await
            .expect("interactive run should start");
        assert!(interactive.skills.is_empty());
    }

    #[test]
    fn classify_resume_error_matches_locked_and_corrupt_store_errors() {
        assert_eq!(
            classify_resume_error(&RuntimeError::SessionStore {
                source: SessionStoreError::UnsupportedFormatVersion { actual: 6 },
            }),
            Some(CodingSessionResumeFailure::IncompatibleFormat)
        );
        assert_eq!(
            classify_resume_error(&RuntimeError::SessionStore {
                source: SessionStoreError::InvalidDocument {
                    reason: "legacy journal",
                },
            }),
            Some(CodingSessionResumeFailure::IncompatibleFormat)
        );
        assert_eq!(
            classify_resume_error(&RuntimeError::SessionStore {
                source: SessionStoreError::SessionAlreadyReserved {
                    session_id: SessionId::new("busy").expect("valid id"),
                },
            }),
            Some(CodingSessionResumeFailure::AlreadyOpen)
        );
    }

    #[tokio::test]
    async fn coding_session_discard_if_empty_removes_untouched_dir() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        let store = FileSessionStore::new(temp.path().join("sessions"));
        let session_id = SessionId::new("untouched-session").expect("valid session id");

        let mut session = CodingSession::builder(test_input("untouched-session", &workspace))
            .open(store.clone(), CodingSessionOpenMode::New)
            .await
            .expect("session should open");
        assert!(store.session_dir(&session_id).exists());

        session.discard_if_empty().await;
        assert!(!store.session_dir(&session_id).exists());
    }

    #[tokio::test]
    async fn coding_session_builder_with_durable_memory_at_creates_scoped_memory_without_env() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        let memory_root = temp.path().join("explicit-memory");
        std::fs::create_dir_all(&workspace).expect("workspace dir");

        let _session = CodingSession::builder(test_input("memory-root-session", &workspace))
            .with_durable_memory_at(&memory_root)
            .build()
            .expect("session with explicit memory root should build");

        assert!(memory_root.join("global").join("MEMORY.md").is_file());
        assert!(memory_root.join("workspaces").is_dir());
    }

    #[tokio::test]
    async fn coding_session_delegates_to_unified_agent_facade() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace dir");

        let session = CodingSession::builder(test_input("unified-agent-session", &workspace))
            .build()
            .expect("coding session should build");
        assert_eq!(session.session_id(), session.as_agent().session_id());

        let result = session
            .as_agent()
            .run("hello from unified facade")
            .await
            .expect("agent run should succeed");
        assert_eq!(result.final_output(), Some("ok"));

        let transcript = session
            .handle()
            .session_transcript()
            .await
            .expect("transcript should load");
        assert!(
            !transcript.is_empty(),
            "CodingSession and its underlying Agent must share one runtime session"
        );

        let agent = session.into_agent();
        assert_eq!(
            agent.session_handle().session_id().as_str(),
            "unified-agent-session"
        );
    }

    #[tokio::test]
    async fn coding_session_into_agent_preserves_session_reservation_until_agent_drops() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        let store = FileSessionStore::new(temp.path().join("sessions"));

        let session = CodingSession::builder(test_input("into-agent-lock", &workspace))
            .open(store.clone(), CodingSessionOpenMode::New)
            .await
            .expect("coding session should open");
        session
            .handle()
            .save_session_to(store.clone())
            .await
            .expect("session should save");

        let agent = session.into_agent();
        let agent_clone = agent.clone();

        // While the Agent (or any clone) is alive, concurrent resume must still see AlreadyOpen.
        let locked = CodingSession::builder(test_input("into-agent-lock", &workspace))
            .open(store.clone(), CodingSessionOpenMode::Resume)
            .await;
        assert!(matches!(
            locked,
            Err(CodingSessionOpenError::ResumeUnavailable {
                kind: CodingSessionResumeFailure::AlreadyOpen,
                ..
            })
        ));

        drop(agent);
        let still_locked = CodingSession::builder(test_input("into-agent-lock", &workspace))
            .open(store.clone(), CodingSessionOpenMode::Resume)
            .await;
        assert!(matches!(
            still_locked,
            Err(CodingSessionOpenError::ResumeUnavailable {
                kind: CodingSessionResumeFailure::AlreadyOpen,
                ..
            })
        ));

        // Once the last Agent clone drops, the reservation releases and resume succeeds.
        drop(agent_clone);
        let resumed = CodingSession::builder(test_input("into-agent-lock", &workspace))
            .open(store, CodingSessionOpenMode::Resume)
            .await
            .expect("resume should succeed after Agent drops");
        assert_eq!(resumed.session_id().as_str(), "into-agent-lock");
    }

    #[tokio::test]
    async fn coding_session_into_runtime_retains_lock_and_into_agent_close_releases_it() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        let store = FileSessionStore::new(temp.path().join("sessions"));

        let session = CodingSession::builder(test_input("into-runtime-lock", &workspace))
            .open(store.clone(), CodingSessionOpenMode::New)
            .await
            .expect("coding session should open");
        session
            .handle()
            .save_session_to(store.clone())
            .await
            .expect("session should save");

        let runtime = session.into_runtime();
        let locked = CodingSession::builder(test_input("into-runtime-lock", &workspace))
            .open(store.clone(), CodingSessionOpenMode::Resume)
            .await;
        assert!(
            matches!(
                locked,
                Err(CodingSessionOpenError::ResumeUnavailable {
                    kind: CodingSessionResumeFailure::AlreadyOpen,
                    ..
                })
            ),
            "into_runtime() must preserve exclusive session reservation"
        );
        runtime.close().await.expect("runtime close should succeed");

        let reopened = CodingSession::builder(test_input("into-runtime-lock", &workspace))
            .open(store.clone(), CodingSessionOpenMode::Resume)
            .await
            .expect("resume should succeed immediately after runtime.close()");
        let agent = reopened.into_agent();
        let _clone_still_alive = agent.clone();
        agent.close().await.expect("agent close should succeed");

        let reopened_again = CodingSession::builder(test_input("into-runtime-lock", &workspace))
            .open(store, CodingSessionOpenMode::Resume)
            .await
            .expect("into_agent().close() must release session reservation even with live clones");
        assert_eq!(reopened_again.session_id().as_str(), "into-runtime-lock");
    }

    #[tokio::test]
    async fn runtime_builder_with_profile_preserves_explicit_retry_policy() {
        use merry_llm::{ModelError, ModelRetryPolicy};
        use std::sync::atomic::{AtomicUsize, Ordering};

        #[derive(Clone)]
        struct AlwaysTransientErrorProvider {
            attempts: Arc<AtomicUsize>,
        }

        impl ModelProvider for AlwaysTransientErrorProvider {
            fn name(&self) -> &merry_core::ProviderName {
                static NAME: OnceLock<merry_core::ProviderName> = OnceLock::new();
                NAME.get_or_init(|| merry_core::ProviderName::new("retry-test").unwrap())
            }

            fn capabilities(&self) -> &ModelCapabilities {
                static CAPS: OnceLock<ModelCapabilities> = OnceLock::new();
                CAPS.get_or_init(|| {
                    ModelCapabilities::new(true, true, false, true, None, None).unwrap()
                })
            }

            fn stream_model<'a>(
                &'a self,
                _request: ModelRequest,
                _context: ModelStreamContext,
            ) -> ModelProviderFuture<'a, Result<ModelEventStream, ModelError>> {
                let attempts = Arc::clone(&self.attempts);
                Box::pin(async move {
                    attempts.fetch_add(1, Ordering::SeqCst);
                    Err(ModelError::provider(
                        merry_llm::ProviderErrorKind::Unavailable,
                        "transient outage",
                    ))
                })
            }
        }

        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace dir");

        let attempts = Arc::new(AtomicUsize::new(0));
        let provider = Arc::new(AlwaysTransientErrorProvider {
            attempts: Arc::clone(&attempts),
        });
        let single_attempt = ModelRetryPolicy::disabled();
        let profile = crate::profiles::coding_agent(&workspace)
            .build()
            .expect("coding profile");
        let agent =
            crate::AgentBuilder::new(SessionId::new("retry-order-check").expect("session id"))
                .provider(
                    crate::providers::ConfiguredModelProvider::primary(
                        provider,
                        ModelName::new("test-model").expect("valid model"),
                    )
                    .with_retry_policy(single_attempt),
                )
                .profile(profile)
                .expect("profile apply")
                .build()
                .expect("agent build");

        let _ = agent.run("hello").await;
        assert_eq!(
            attempts.load(Ordering::SeqCst),
            1,
            "profile default retry policy must not clobber explicit provider retry policy"
        );
    }
}