merry-coding 0.1.3

Coding prompts, project rules, tool catalog, permission policy, and subagent orchestration for Merry.
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
//! Parent coding-runtime composition.
//!
//! This module owns the typed assembly boundary between a coding surface and
//! the provider-neutral runtime. It constructs runtime state through
//! [`merry_runtime::RuntimeBuilder`], but it does not own that state after the
//! builder returns a [`CodingRuntime`].

use crate::child_runtime::{CodingChildRuntimeFactory, CodingRuntimeComposition};
use crate::{
    CodingAgentProfile, CodingAgentProfileBuildError, CodingAgentProfileBuilder,
    MIN_CODING_SUBAGENT_MODEL_TURNS, ProjectRulesLoadError, SubagentRoleCatalog, coding_agent,
    load_root_project_rules,
};
use merry_core::{CoreError, HostPathPolicy, SessionId};
use merry_llm::{ModelName, ModelProvider, ModelRetryPolicy, ReasoningEffort};
use merry_process::ProcessBackend;
use merry_runtime::{
    AgentLoopConfig, AgentLoopConfigError, ChildRuntimeFactory, CompactionConfig, DurableMemory,
    FileSessionStore, HistoryRetention, LoadedSession, PermissionReviewRules, RegisteredTool,
    Runtime, RuntimeBuilder, RuntimeError, RuntimeModelRole, SkillCatalog, SkillError,
    SubagentConfig, SubagentError, SubagentManager, subagent_registered_tools_with_roles,
};
use merry_tools::{BrowserProcessLauncher, WorkspaceToolLimits};
pub use permission_policy::{
    CodingAutoFallback, CodingPermissionMode, CodingPermissionPolicy, CodingPermissionPolicyError,
};
use std::{collections::BTreeSet, path::PathBuf, sync::Arc};
use thiserror::Error;

mod permission_policy;

/// A provider-neutral model/provider pair for one non-primary runtime role.
///
/// Provider adapters are represented by the Merry-owned [`ModelProvider`] trait;
/// provider wire request and response types never cross this contract.
#[derive(Clone)]
pub struct CodingModelRoleConfig {
    role: RuntimeModelRole,
    provider: Arc<dyn ModelProvider>,
    model: ModelName,
    reasoning_effort: Option<ReasoningEffort>,
}

impl CodingModelRoleConfig {
    /// Creates a role-specific model configuration.
    pub fn new(
        role: RuntimeModelRole,
        provider: Arc<dyn ModelProvider>,
        model: ModelName,
    ) -> Result<Self, CodingModelRoleConfigError> {
        if role == RuntimeModelRole::Primary {
            return Err(CodingModelRoleConfigError::PrimaryRole);
        }
        Ok(Self {
            role,
            provider,
            model,
            reasoning_effort: None,
        })
    }

    /// Sets an optional reasoning-effort override for this runtime model role.
    #[must_use]
    pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
        self.reasoning_effort = reasoning_effort;
        self
    }

    /// Returns the runtime role receiving this provider/model pair.
    #[must_use]
    pub const fn role(&self) -> RuntimeModelRole {
        self.role
    }

    /// Returns the provider handle for this role.
    #[must_use]
    pub fn provider(&self) -> Arc<dyn ModelProvider> {
        Arc::clone(&self.provider)
    }

    /// Returns the model name for this role.
    #[must_use]
    pub fn model(&self) -> &ModelName {
        &self.model
    }

    /// Returns the optional reasoning-effort override for this role.
    #[must_use]
    pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
        self.reasoning_effort.as_ref()
    }
}

/// Error returned when a secondary coding role is constructed with the
/// primary role identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum CodingModelRoleConfigError {
    /// The primary provider/model belongs to [`CodingRuntimeInput::new`].
    #[error("primary model must be configured as the coding runtime's primary provider")]
    PrimaryRole,
}

/// Parent/child policy that must be applied to every coding runtime builder.
///
/// The policy contains only validated provider-neutral inputs. Runtime owns the
/// meaning of model roles and permission admission; this type only forwards the
/// same values to the parent and child builders.
#[derive(Clone, Default)]
pub(crate) struct CodingRuntimePolicy {
    model_roles: Vec<CodingModelRoleConfig>,
    permission: CodingPermissionPolicy,
    permission_review_rules: PermissionReviewRules,
    permission_review_guidance: merry_runtime::SessionReviewGuidance,
    workspace_review_notes: merry_runtime::WorkspaceReviewNotes,
    permission_review_workspace_root: Option<PathBuf>,
}

impl CodingRuntimePolicy {
    pub(crate) fn try_new(
        model_roles: Vec<CodingModelRoleConfig>,
        permission: CodingPermissionPolicy,
    ) -> Result<Self, CodingRuntimeBuildError> {
        let mut configured_roles = BTreeSet::new();
        for role in &model_roles {
            if !configured_roles.insert(role.role()) {
                return Err(CodingRuntimeBuildError::DuplicateModelRole { role: role.role() });
            }
        }
        Ok(Self {
            model_roles,
            permission,
            permission_review_rules: PermissionReviewRules::default(),
            permission_review_guidance: merry_runtime::SessionReviewGuidance::new(),
            workspace_review_notes: merry_runtime::WorkspaceReviewNotes::new(),
            permission_review_workspace_root: None,
        })
    }

    pub(crate) fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
        self.permission_review_rules = rules;
        self
    }

    pub(crate) fn with_workspace_review_notes(mut self, notes: Vec<String>) -> Self {
        self.workspace_review_notes = merry_runtime::WorkspaceReviewNotes::from_notes(notes);
        self
    }

    pub(crate) fn with_permission_review_workspace_root(
        mut self,
        root: impl Into<PathBuf>,
    ) -> Self {
        self.permission_review_workspace_root = Some(root.into());
        self
    }

    pub(crate) fn apply_to(&self, mut builder: RuntimeBuilder) -> RuntimeBuilder {
        for role in &self.model_roles {
            builder = builder.model_provider_for_role_with_reasoning(
                role.role(),
                role.provider(),
                role.model().clone(),
                role.reasoning_effort().cloned(),
            );
        }
        if !self.permission_review_rules.is_empty() {
            builder = builder.permission_review_rules(self.permission_review_rules.clone());
        }
        builder = builder
            .session_review_guidance(self.permission_review_guidance.clone())
            .workspace_review_notes(self.workspace_review_notes.clone());
        if let Some(root) = &self.permission_review_workspace_root {
            builder = builder.permission_review_workspace_root(root.clone());
        }
        self.permission.apply_to(builder)
    }
}

/// Typed subagent composition policy for a parent coding runtime.
#[derive(Clone, Default)]
pub struct CodingSubagentsConfig {
    installed: bool,
    enabled: bool,
    limits: SubagentConfig,
    role_catalog: SubagentRoleCatalog,
}

impl CodingSubagentsConfig {
    /// Installs and enables subagent tools with the supplied runtime limits.
    #[must_use]
    pub fn enabled(limits: SubagentConfig) -> Self {
        Self {
            installed: true,
            enabled: true,
            limits,
            role_catalog: SubagentRoleCatalog::builtin(),
        }
    }

    /// Installs subagent tools while leaving their runtime admission controlled
    /// by `enabled`.
    #[must_use]
    pub fn runtime_controlled(enabled: bool, limits: SubagentConfig) -> Self {
        Self {
            installed: true,
            enabled,
            limits,
            role_catalog: SubagentRoleCatalog::builtin(),
        }
    }

    /// Attaches a customized role catalog (built-in + `.merry/roles/*.toml` +
    /// `[subagents.roles.*]` + `[subagents.default]` + `[subagents.toggle]`).
    #[must_use]
    pub fn with_role_catalog(mut self, role_catalog: SubagentRoleCatalog) -> Self {
        self.role_catalog = role_catalog;
        self
    }

    /// Returns whether the parent should advertise subagent tools.
    #[must_use]
    pub const fn is_installed(&self) -> bool {
        self.installed
    }

    /// Returns whether new subagent work is enabled by the parent policy.
    #[must_use]
    pub const fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Returns the runtime-owned subagent limits.
    #[must_use]
    pub const fn limits(&self) -> SubagentConfig {
        self.limits
    }

    /// Returns the configured role catalog.
    #[must_use]
    pub fn role_catalog(&self) -> &SubagentRoleCatalog {
        &self.role_catalog
    }
}

/// Typed parent coding-runtime inputs shared by full and read-only variants.
///
/// The full constructor requires a [`ProcessBackend`]. The read-only
/// constructor intentionally has no process backend, making it impossible for
/// the command-generation variant to install a process session by accident.
#[derive(Clone)]
pub struct CodingRuntimeInput {
    session_id: SessionId,
    root: PathBuf,
    provider: Arc<dyn ModelProvider>,
    model: ModelName,
    process_backend: Option<Arc<dyn ProcessBackend>>,
    extra_tools: Vec<RegisteredTool>,
    automatic_compaction: CompactionConfig,
    history_retention: HistoryRetention,
    retry_policy: Option<ModelRetryPolicy>,
    model_roles: Vec<CodingModelRoleConfig>,
    skill_roots: Vec<PathBuf>,
    host_path_policy: HostPathPolicy,
    subagents: CodingSubagentsConfig,
    workspace_tool_limits: WorkspaceToolLimits,
    /// When false, the workspace is read-only: `AGENTS.md` stays unloaded and
    /// `apply_patch` cannot write.
    workspace_writable: bool,
    durable_memory: Option<Arc<DurableMemory>>,
    browser_process_launcher: Option<Arc<dyn BrowserProcessLauncher>>,
    permission_review_rules: PermissionReviewRules,
    workspace_review_notes: Vec<String>,
    max_parallel_tool_calls: Option<std::num::NonZeroUsize>,
    context_window_tokens: Option<std::num::NonZeroU64>,
}

impl CodingRuntimeInput {
    /// Creates full coding-runtime inputs with a typed process backend.
    #[must_use]
    pub fn new(
        session_id: SessionId,
        root: impl Into<PathBuf>,
        provider: Arc<dyn ModelProvider>,
        model: ModelName,
        process_backend: Arc<dyn ProcessBackend>,
    ) -> Self {
        Self {
            session_id,
            root: root.into(),
            provider,
            model,
            process_backend: Some(process_backend),
            extra_tools: Vec::new(),
            automatic_compaction: CompactionConfig::default(),
            history_retention: HistoryRetention::default(),
            retry_policy: None,
            model_roles: Vec::new(),
            skill_roots: Vec::new(),
            host_path_policy: HostPathPolicy::new(),
            subagents: CodingSubagentsConfig::default(),
            workspace_tool_limits: WorkspaceToolLimits::default(),
            workspace_writable: true,
            durable_memory: None,
            browser_process_launcher: None,
            permission_review_rules: PermissionReviewRules::default(),
            workspace_review_notes: Vec::new(),
            max_parallel_tool_calls: None,
            context_window_tokens: None,
        }
    }

    /// Sets whether the workspace is writable (`false` keeps it read-only and
    /// skips `AGENTS.md`).
    #[must_use]
    pub fn read_only_workspace(mut self) -> Self {
        self.workspace_writable = false;
        self
    }

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

    /// Returns the workspace root directory owned by this input.
    #[must_use]
    pub fn root(&self) -> &std::path::Path {
        &self.root
    }

    /// Creates read-only command-generation inputs without a process backend.
    #[must_use]
    pub fn read_only(
        session_id: SessionId,
        root: impl Into<PathBuf>,
        provider: Arc<dyn ModelProvider>,
        model: ModelName,
    ) -> Self {
        Self {
            session_id,
            root: root.into(),
            provider,
            model,
            process_backend: None,
            extra_tools: Vec::new(),
            automatic_compaction: CompactionConfig::default(),
            history_retention: HistoryRetention::default(),
            retry_policy: None,
            model_roles: Vec::new(),
            skill_roots: Vec::new(),
            host_path_policy: HostPathPolicy::new(),
            subagents: CodingSubagentsConfig::default(),
            workspace_tool_limits: WorkspaceToolLimits::default(),
            workspace_writable: true,
            durable_memory: None,
            browser_process_launcher: None,
            permission_review_rules: PermissionReviewRules::default(),
            workspace_review_notes: Vec::new(),
            max_parallel_tool_calls: None,
            context_window_tokens: None,
        }
    }

    /// Attaches durable memory for this runtime and the children it spawns.
    ///
    /// The parent maintains memory after completed user turns. Children see the
    /// same store with maintenance disabled.
    #[must_use]
    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
        self.durable_memory = Some(memory);
        self
    }

    /// Overrides the headless browser process launcher used by `browser_tab`
    /// for this runtime and its spawned subagents (for example in `rootshell`
    /// hosts that disable local browser launches or supply a custom launcher).
    #[must_use]
    pub fn with_browser_process_launcher(
        mut self,
        launcher: Arc<dyn BrowserProcessLauncher>,
    ) -> Self {
        self.browser_process_launcher = Some(launcher);
        self
    }

    /// Adds provider-neutral tools owned by the calling surface or adapter.
    #[must_use]
    pub fn with_extra_tools<I>(mut self, tools: I) -> Self
    where
        I: IntoIterator<Item = RegisteredTool>,
    {
        self.extra_tools.extend(tools);
        self
    }

    /// Sets automatic context compaction policy.
    #[must_use]
    pub fn with_automatic_compaction(mut self, config: CompactionConfig) -> Self {
        self.automatic_compaction = config;
        self
    }

    /// Sets how compacted history is retained in memory and on disk.
    #[must_use]
    pub fn with_history_retention(mut self, retention: HistoryRetention) -> Self {
        self.history_retention = retention;
        self
    }

    /// Sets the model retry/recovery policy shared by parent and child runtimes.
    #[must_use]
    pub fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
        self.retry_policy = Some(policy);
        self
    }

    /// Adds one non-primary runtime model role.
    #[must_use]
    pub fn with_model_role(mut self, role: CodingModelRoleConfig) -> Self {
        self.model_roles.push(role);
        self
    }

    /// Adds model roles in the supplied deterministic order.
    #[must_use]
    pub fn with_model_roles<I>(mut self, roles: I) -> Self
    where
        I: IntoIterator<Item = CodingModelRoleConfig>,
    {
        self.model_roles.extend(roles);
        self
    }

    /// Sets the read-only skill/resource roots.
    #[must_use]
    pub fn with_skill_roots<I, P>(mut self, roots: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.skill_roots = roots.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the shared host path policy so in-process file tools enforce the
    /// exact same private-path and read-only session-journal boundaries as the
    /// process sandbox, inherited by parent and child runtimes.
    #[must_use]
    pub fn with_host_path_policy(mut self, policy: HostPathPolicy) -> Self {
        self.host_path_policy = policy;
        self
    }

    /// Sets the parent subagent policy.
    #[must_use]
    pub fn with_subagents(mut self, subagents: CodingSubagentsConfig) -> Self {
        self.subagents = subagents;
        self
    }

    /// Sets the workspace tool limits for the coding profile.
    #[must_use]
    pub fn with_workspace_tool_limits(mut self, limits: WorkspaceToolLimits) -> Self {
        self.workspace_tool_limits = limits;
        self
    }

    /// Sets user-trusted custom rules for AI permission review, inherited by
    /// both parent and child coding runtimes.
    #[must_use]
    pub fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
        self.permission_review_rules = rules;
        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.workspace_review_notes = notes;
        self
    }

    /// Sets the maximum number of parallel-safe tool calls executed together in
    /// one model turn for both parent and child runtimes.
    #[must_use]
    pub fn with_max_parallel_tool_calls(mut self, limit: std::num::NonZeroUsize) -> Self {
        self.max_parallel_tool_calls = Some(limit);
        self
    }

    /// Sets an explicit context-window override in tokens for budget and
    /// automatic compaction calculations.
    #[must_use]
    pub fn with_context_window_tokens(mut self, tokens: std::num::NonZeroU64) -> Self {
        self.context_window_tokens = Some(tokens);
        self
    }
}

/// Internal parent coding-runtime variant selected by the surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CodingRuntimeVariant {
    /// Full coding runtime with process, patch, plan, and optional subagent lanes.
    FullCoding,
    /// Read-only workspace runtime for command generation.
    ReadOnlyCommandGeneration,
}

/// Builder for parent coding runtime composition.
pub struct CodingRuntimeBuilder {
    input: CodingRuntimeInput,
    variant: CodingRuntimeVariant,
    permission: CodingPermissionPolicy,
    loaded_session: Option<LoadedSession>,
    session_store: Option<FileSessionStore>,
}

impl CodingRuntimeBuilder {
    /// Creates a full coding-runtime builder.
    #[must_use]
    pub fn new(input: CodingRuntimeInput) -> Self {
        Self {
            input,
            variant: CodingRuntimeVariant::FullCoding,
            permission: CodingPermissionPolicy::default(),
            loaded_session: None,
            session_store: None,
        }
    }

    /// Creates the explicit read-only command-generation variant.
    ///
    /// Full-only inputs such as a process backend and subagent configuration
    /// are intentionally ignored by this variant. The read-only profile is
    /// selected by construction so those capabilities cannot be advertised or
    /// admitted accidentally.
    #[must_use]
    pub fn for_command_generation(input: CodingRuntimeInput) -> Self {
        Self {
            input,
            variant: CodingRuntimeVariant::ReadOnlyCommandGeneration,
            permission: CodingPermissionPolicy::default(),
            loaded_session: None,
            session_store: None,
        }
    }

    /// Sets the complete permission policy shared by parent and child runtimes.
    #[must_use]
    pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
        self.permission = policy;
        self
    }

    /// Installs an already loaded session without performing another store read.
    #[must_use]
    pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
        self.loaded_session = Some(loaded);
        self
    }

    /// Configures automatic incremental session persistence into `store`.
    #[must_use]
    pub fn session_store(mut self, store: FileSessionStore) -> Self {
        self.session_store = Some(store);
        self
    }

    /// Builds a new parent runtime and its stable coding loop policy.
    pub fn build(self) -> Result<CodingRuntime, CodingRuntimeBuildError> {
        let mut reservation = None;
        self.build_with_reservation(&mut reservation)
    }

    /// Builds a new parent runtime and transfers an already-acquired
    /// [`merry_runtime::SessionReservation`] into the runtime once validation
    /// succeeds.
    pub fn build_with_reservation(
        self,
        reservation: &mut Option<merry_runtime::SessionReservation>,
    ) -> Result<CodingRuntime, CodingRuntimeBuildError> {
        let (builder, profile) = self.compose()?;
        let loop_config = profile.loop_config()?;
        let runtime = builder
            .build_with_reservation(reservation)
            .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
        Ok(CodingRuntime {
            runtime,
            profile,
            loop_config,
        })
    }

    /// Resumes a parent runtime without automatic savepoints.
    pub async fn resume_from_store_without_automatic_savepoints(
        self,
        store: FileSessionStore,
    ) -> Result<CodingRuntime, CodingRuntimeBuildError> {
        let (builder, profile) = self.compose()?;
        let loop_config = profile.loop_config()?;
        let runtime = builder
            .resume_from_store_without_automatic_savepoints(store)
            .await
            .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
        Ok(CodingRuntime {
            runtime,
            profile,
            loop_config,
        })
    }

    fn compose(
        self,
    ) -> Result<(merry_runtime::RuntimeBuilder, CodingAgentProfile), CodingRuntimeBuildError> {
        let Self {
            input,
            variant,
            permission,
            loaded_session,
            session_store,
        } = self;
        let CodingRuntimeInput {
            session_id,
            root,
            provider,
            model,
            process_backend,
            extra_tools,
            automatic_compaction,
            history_retention,
            retry_policy,
            model_roles,
            skill_roots,
            host_path_policy,
            subagents,
            workspace_tool_limits,
            workspace_writable,
            durable_memory,
            browser_process_launcher,
            permission_review_rules,
            workspace_review_notes,
            max_parallel_tool_calls,
            context_window_tokens,
        } = input;

        let policy = CodingRuntimePolicy::try_new(model_roles, permission)?
            .with_permission_review_rules(permission_review_rules)
            .with_workspace_review_notes(workspace_review_notes)
            .with_permission_review_workspace_root(root.clone());

        let project_rules = if workspace_writable {
            load_root_project_rules(&root)?
        } else {
            None
        };
        let skill_catalog = if skill_roots.is_empty() {
            None
        } else {
            Some(SkillCatalog::load_from_roots(skill_roots.clone())?)
        };
        if let Some(catalog) = skill_catalog.as_ref() {
            const MAX_LOGGED_SKILL_NAMES: usize = 64;
            let skill_names = catalog
                .skills()
                .iter()
                .take(MAX_LOGGED_SKILL_NAMES)
                .map(|skill| skill.name())
                .collect::<Vec<_>>();
            tracing::info!(
                event = "runtime.skill_catalog.load",
                session_id = %session_id,
                configured_root_count = skill_roots.len(),
                readable_root_count = skill_roots.iter().filter(|root| root.is_dir()).count(),
                skill_count = catalog.skills().len(),
                warning_count = catalog.warnings().len(),
                skill_names = ?skill_names,
                "runtime skill catalog loaded"
            );
        }
        let mut runtime_builder = Runtime::builder(session_id.clone())
            .automatic_compaction(automatic_compaction.clone())
            .history_retention(history_retention)
            .model_provider(Arc::clone(&provider), model.clone());
        if let Some(limit) = max_parallel_tool_calls {
            runtime_builder = runtime_builder.max_parallel_tool_calls(limit);
        }
        if let Some(tokens) = context_window_tokens {
            runtime_builder = runtime_builder.context_window_tokens(tokens);
        }
        if matches!(variant, CodingRuntimeVariant::FullCoding) {
            runtime_builder = runtime_builder.coordinator_plan_tools();
        }

        let mut profile_builder: CodingAgentProfileBuilder = coding_agent(&root)
            .readonly_resource_roots(skill_roots.clone())
            .host_path_policy(host_path_policy)
            .limits(workspace_tool_limits)
            .register_tools(extra_tools);
        if let Some(project_rules) = project_rules {
            profile_builder = profile_builder.project_rules(project_rules);
        }
        if let Some(skill_catalog) = skill_catalog {
            profile_builder = profile_builder.skill_catalog(skill_catalog);
        }
        if let Some(policy) = retry_policy {
            profile_builder = profile_builder.retry_policy(policy);
        }
        if let Some(memory) = durable_memory.clone() {
            profile_builder = profile_builder.durable_memory(memory);
        }
        if let Some(launcher) = browser_process_launcher {
            profile_builder = profile_builder.browser_process_launcher(launcher);
        }

        let mut profile_tools = Vec::new();
        if matches!(variant, CodingRuntimeVariant::FullCoding) {
            let process_backend =
                process_backend.ok_or(CodingRuntimeBuildError::MissingProcessBackend)?;
            let process_session = process_backend.new_session();
            let parent_process_permissions = process_session.permission_view();
            profile_builder = profile_builder.patch_tool().web_tools();
            // For static non-live backends without a live policy handle, keep
            // `read_only_patch_scope()` enforced when starting read-only; live
            // backends (`LiveProcessBackend`) govern `workspace_writable`
            // dynamically via `LivePolicyHandle` so toggling `workspace (ro)
            // <-> off` unlocks/locks `apply_patch` immediately.
            if !workspace_writable && !process_session.has_live_policy() {
                profile_builder = profile_builder.read_only_patch_scope();
            }
            let child_profile_builder = profile_builder.clone();
            profile_builder = profile_builder.accepted_process_session(process_session);

            if subagents.is_installed() {
                let subagent_config = subagents.limits().with_model_turn_bounds(
                    MIN_CODING_SUBAGENT_MODEL_TURNS,
                    subagents.limits().max_model_turns(),
                )?;
                tracing::info!(
                    event = "runtime.subagents.enabled",
                    session_id = %session_id,
                    enabled = subagents.is_enabled(),
                    max_threads = subagent_config.max_threads(),
                    max_depth = subagent_config.max_depth(),
                    min_model_turns = subagent_config.min_model_turns(),
                    max_model_turns = subagent_config.max_model_turns(),
                    "runtime subagent tools installed"
                );
                let role_catalog = subagents.role_catalog().clone();
                let role_summaries = role_catalog.enabled_role_summaries();
                let composition = CodingRuntimeComposition {
                    profile_builder: child_profile_builder,
                    provider: Arc::clone(&provider),
                    model: model.clone(),
                    process_backend,
                    parent_process_permissions,
                    parent_workspace_writable: workspace_writable,
                    subagent_config,
                    role_catalog,
                    automatic_compaction,
                    max_parallel_tool_calls,
                    policy: policy.clone(),
                    worktree_manager: crate::WorktreeIsolationManager::new(),
                };
                let child_factory: Arc<dyn ChildRuntimeFactory> =
                    Arc::new(CodingChildRuntimeFactory::from_composition(composition));
                let manager = SubagentManager::runtime_controlled(
                    session_id.clone(),
                    subagent_config,
                    child_factory,
                    subagents.is_enabled(),
                );
                let [spawn_tool, send_tool, wait_tool, cancel_tool] =
                    subagent_registered_tools_with_roles(manager.clone(), &role_summaries)?;
                runtime_builder = runtime_builder.subagent_manager(manager);
                profile_tools.extend([spawn_tool, send_tool, wait_tool, cancel_tool]);
            }
        }

        let profile = profile_builder.register_tools(profile_tools).build()?;
        runtime_builder = profile
            .apply_to(runtime_builder)
            .map_err(|source| CodingRuntimeBuildError::RuntimeProfileApply { source })?;
        runtime_builder = policy.apply_to(runtime_builder);
        if let Some(memory) = durable_memory {
            runtime_builder = runtime_builder.durable_memory(memory, true);
        }
        if let Some(loaded_session) = loaded_session {
            runtime_builder = runtime_builder.with_loaded_session(loaded_session);
        }
        if let Some(store) = session_store {
            runtime_builder = runtime_builder.session_store(store);
        }

        Ok((runtime_builder, profile))
    }
}

/// A built parent coding runtime and the policy that governs its loop.
pub struct CodingRuntime {
    runtime: Runtime,
    profile: CodingAgentProfile,
    loop_config: AgentLoopConfig,
}

impl CodingRuntime {
    /// Borrows the runtime state handle owned by this composition result.
    #[must_use]
    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

    /// Consumes the composition result and returns its runtime handle.
    #[must_use]
    pub fn into_runtime(self) -> Runtime {
        self.runtime
    }

    /// Borrows the shared coding profile used by this runtime.
    #[must_use]
    pub fn profile(&self) -> &CodingAgentProfile {
        &self.profile
    }

    /// Clones the loop configuration derived from the shared coding profile.
    #[must_use]
    pub fn loop_config(&self) -> AgentLoopConfig {
        self.loop_config.clone()
    }
}

/// Errors raised while composing a parent coding runtime.
#[derive(Debug, Error)]
pub enum CodingRuntimeBuildError {
    /// A full coding runtime was requested without its process backend.
    #[error("full coding runtime requires a process backend")]
    MissingProcessBackend,
    /// A role was configured more than once.
    #[error("coding model role {role:?} was configured more than once")]
    DuplicateModelRole { role: RuntimeModelRole },
    /// A provider-neutral protocol value failed validation.
    #[error(transparent)]
    Core(#[from] CoreError),
    /// Project rules could not be loaded safely.
    #[error(transparent)]
    ProjectRules(#[from] ProjectRulesLoadError),
    /// The skill catalog could not be loaded.
    #[error(transparent)]
    SkillCatalog(#[from] SkillError),
    /// The coding profile was invalid.
    #[error(transparent)]
    CodingProfile(#[from] CodingAgentProfileBuildError),
    /// The profile's coding loop policy was invalid.
    #[error(transparent)]
    LoopConfig(#[from] AgentLoopConfigError),
    /// The coding profile's child-agent model-turn bounds were invalid.
    #[error(transparent)]
    SubagentConfig(#[from] SubagentError),
    /// Applying the profile to the runtime builder failed.
    #[error("failed to apply coding profile to runtime builder: {source}")]
    RuntimeProfileApply { source: RuntimeError },
    /// Runtime construction or resume failed.
    #[error("failed to build coding runtime: {source}")]
    RuntimeBuild { source: RuntimeError },
}