merry-runtime 0.1.0

Structured session, task ledger, context compaction, memory, permission, and tool runtime 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
//! Runtime capability policy and complete runtime profiles.

use crate::{
    AcceptedLocalWorkspaceProcessAdmission, BackgroundProcessControl, PermissionAdmissionSource,
    PermissionReviewMode, PermissionedProcessRunnerFactory, ProcessRunner, ProjectRules,
    PromptProfile, RegisteredTool, RuntimeTrustLevel, SkillCatalog, SubagentManager, TaskAnchor,
};
use merry_core::ToolName;
use merry_llm::ModelRetryPolicy;
use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
    sync::Arc,
};
use thiserror::Error;

/// Filesystem access granted or denied for one configured path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathAccess {
    /// The path may be read but not written by Merry-managed runtime backends.
    ReadOnly,
    /// The path may be read and written by Merry-managed runtime backends.
    ReadWrite,
    /// The path must not be made available to Merry-managed runtime backends.
    Deny,
}

impl PathAccess {
    /// Returns the stable config/API spelling for this access mode.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ReadOnly => "ro",
            Self::ReadWrite => "rw",
            Self::Deny => "deny",
        }
    }

    /// Returns whether this granted access covers a requested access.
    ///
    /// Read-write access includes read-only access. Read-only access never
    /// includes a read-write request, and deny never grants access.
    #[must_use]
    pub const fn covers(self, requested: Self) -> bool {
        matches!(
            (self, requested),
            (Self::ReadWrite, Self::ReadOnly | Self::ReadWrite) | (Self::ReadOnly, Self::ReadOnly)
        )
    }
}

/// Trust source for a path access rule.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathAccessRuleSource {
    /// Rule supplied by Merry's built-in development process baseline.
    DefaultDevelopmentBaseline,
    /// Rule came from the user's global Merry config.
    ///
    /// This is intentionally higher trust than project-local configuration,
    /// because normal coding-agent runs may edit files inside the project.
    TrustedGlobalConfig,
    /// Product-owned credentials and state unavailable to actions.
    ProductPrivate,
    /// Merry's own non-secret configuration and skill directories.
    ///
    /// These directories live outside the workspace and hold no credentials, so
    /// sandboxed commands may read and update user config and skills directly.
    ProductConfig,
    /// Automatically applied read-only protection for Git metadata paths.
    ///
    /// A reviewed action may temporarily overlay this rule for one process
    /// action, but the path is never retained as a session grant.
    GitMetadataBaseline,
    /// Rule materialized from the current permission admission result.
    PermissionReview,
    /// Durable memory notes under the XDG data home.
    ///
    /// This tree is outside the workspace. Sandboxed commands can read and
    /// write it so the agent can use the same notes the host maintains.
    DurableMemory,
}

/// One platform-neutral path access rule consumed by sandbox backends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathAccessRule {
    path: PathBuf,
    access: PathAccess,
    source: PathAccessRuleSource,
    review_required: bool,
}

impl PathAccessRule {
    /// Creates a path access rule.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>, access: PathAccess, source: PathAccessRuleSource) -> Self {
        Self {
            path: path.into(),
            access,
            source,
            review_required: false,
        }
    }

    /// Requires a fresh approval before each action may use this path subtree.
    ///
    /// This restricts the declared access; it does not increase its ceiling.
    #[must_use]
    pub const fn with_review_required(mut self) -> Self {
        self.review_required = true;
        self
    }

    /// Returns whether this subtree is unavailable without action-scoped review.
    #[must_use]
    pub const fn review_required(&self) -> bool {
        self.review_required
    }

    /// Returns the configured path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Returns the requested access.
    #[must_use]
    pub const fn access(&self) -> PathAccess {
        self.access
    }

    /// Returns the trust source for this rule.
    #[must_use]
    pub const fn source(&self) -> PathAccessRuleSource {
        self.source
    }
}

/// Merry-managed low-level capability policy.
///
/// This constrains capabilities owned by Merry-managed runners, such as file
/// and process access lanes. It is not a complete product runtime profile or a
/// trust label for arbitrary host code or in-process tool executors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeCapabilities {
    network_allowed: bool,
    path_rules: Vec<PathAccessRule>,
}

impl RuntimeCapabilities {
    /// Creates the default capability policy.
    ///
    /// The default denies network and starts with no path grants.
    #[must_use]
    pub fn new() -> Self {
        Self {
            network_allowed: false,
            path_rules: Vec::new(),
        }
    }

    /// Allows Merry-managed network capability for this runtime.
    #[must_use]
    pub fn allow_network(mut self) -> Self {
        self.network_allowed = true;
        self
    }

    /// Denies Merry-managed network capability for this runtime.
    #[must_use]
    pub fn deny_network(mut self) -> Self {
        self.network_allowed = false;
        self
    }

    /// Adds one path access rule to this profile.
    #[must_use]
    pub fn with_path_rule(mut self, rule: PathAccessRule) -> Self {
        self.path_rules.push(rule);
        self
    }

    /// Replaces all path access rules for this profile.
    #[must_use]
    pub fn with_path_rules(mut self, rules: Vec<PathAccessRule>) -> Self {
        self.path_rules = rules;
        self
    }

    /// Returns whether Merry-managed network capability is allowed.
    #[must_use]
    pub fn network_allowed(&self) -> bool {
        self.network_allowed
    }

    /// Returns platform-neutral path access rules for Merry-managed backends.
    #[must_use]
    pub fn path_rules(&self) -> &[PathAccessRule] {
        &self.path_rules
    }
}

impl Default for RuntimeCapabilities {
    fn default() -> Self {
        Self::new()
    }
}

/// Errors raised while building a complete runtime profile.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum RuntimeProfileError {
    /// A profile tried to register the same tool more than once.
    #[error("tool {name} is already registered in runtime profile")]
    DuplicateToolRegistration {
        /// Duplicate tool name.
        name: ToolName,
    },
    /// A profile tried to register a runtime-reserved tool name.
    #[error("tool {name} is reserved by the runtime")]
    ReservedToolName {
        /// Rejected reserved tool name.
        name: ToolName,
    },
}

/// Accepted local workspace process lane carried by a runtime profile.
#[derive(Clone)]
pub struct AcceptedLocalWorkspaceProcessRunnerProfile {
    admission: AcceptedLocalWorkspaceProcessAdmission,
    runner: Arc<dyn ProcessRunner>,
}

impl AcceptedLocalWorkspaceProcessRunnerProfile {
    /// Creates a profile-owned accepted local workspace process lane.
    #[must_use]
    pub fn new(
        admission: AcceptedLocalWorkspaceProcessAdmission,
        runner: Arc<dyn ProcessRunner>,
    ) -> Self {
        Self { admission, runner }
    }

    /// Returns the accepted local workspace process admission evidence.
    #[must_use]
    pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
        self.admission
    }

    /// Returns the process runner for this lane.
    #[must_use]
    pub fn runner(&self) -> Arc<dyn ProcessRunner> {
        Arc::clone(&self.runner)
    }
}

/// Complete runtime shape applied by [`crate::RuntimeBuilder::with_profile`].
#[derive(Clone)]
pub struct RuntimeProfile {
    capabilities: RuntimeCapabilities,
    model_retry_policy: Option<ModelRetryPolicy>,
    prompt_profile: PromptProfile,
    progress_commentary: bool,
    initial_context_summaries: BTreeMap<String, String>,
    registered_tools: Vec<RegisteredTool>,
    allow_bridge_tools: bool,
    allow_low_risk_apply_patches: bool,
    low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
    read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
    accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
    runtime_trust_level: Option<RuntimeTrustLevel>,
    permission_review_mode: Option<PermissionReviewMode>,
    permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
    permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
    background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
    skill_catalog: Option<SkillCatalog>,
    project_rules: Option<ProjectRules>,
    task_anchor: Option<TaskAnchor>,
    subagent_manager: Option<SubagentManager>,
}

impl RuntimeProfile {
    /// Creates a profile builder.
    #[must_use]
    pub fn builder() -> RuntimeProfileBuilder {
        RuntimeProfileBuilder::new()
    }

    /// Returns low-level Merry-managed capabilities.
    #[must_use]
    pub const fn capabilities(&self) -> &RuntimeCapabilities {
        &self.capabilities
    }

    /// Returns the profile model retry policy override.
    #[must_use]
    pub const fn model_retry_policy(&self) -> Option<ModelRetryPolicy> {
        self.model_retry_policy
    }

    /// Returns the stable prompt composition used by runtime request compilation.
    #[must_use]
    pub const fn prompt_profile(&self) -> &PromptProfile {
        &self.prompt_profile
    }

    /// Returns whether this profile asks the model for tool-progress commentary.
    #[must_use]
    pub const fn progress_commentary(&self) -> bool {
        self.progress_commentary
    }

    /// Returns startup context summaries keyed by stable id.
    #[must_use]
    pub fn initial_context_summaries(&self) -> &BTreeMap<String, String> {
        &self.initial_context_summaries
    }

    /// Returns registered tools carried by the profile.
    #[must_use]
    pub fn registered_tools(&self) -> &[RegisteredTool] {
        &self.registered_tools
    }

    /// Consumes the profile and returns registered tools.
    #[must_use]
    pub fn into_registered_tools(self) -> Vec<RegisteredTool> {
        self.registered_tools
    }

    /// Returns whether bridge tools are allowed.
    #[must_use]
    pub const fn allow_bridge_tools(&self) -> bool {
        self.allow_bridge_tools
    }

    /// Returns whether low-risk workspace patches are allowed.
    #[must_use]
    pub const fn allow_low_risk_apply_patches(&self) -> bool {
        self.allow_low_risk_apply_patches
    }

    /// Returns the low-risk process action runner.
    #[must_use]
    pub fn low_risk_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
        self.low_risk_process_runner.as_ref().map(Arc::clone)
    }

    /// Returns the read-only shell process runner.
    #[must_use]
    pub fn read_only_shell_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
        self.read_only_shell_process_runner.as_ref().map(Arc::clone)
    }

    /// Returns the accepted local workspace process runner lane.
    #[must_use]
    pub fn accepted_local_workspace_process_runner(
        &self,
    ) -> Option<&AcceptedLocalWorkspaceProcessRunnerProfile> {
        self.accepted_local_workspace_process_runner.as_ref()
    }

    /// Returns the profile runtime trust level override.
    #[must_use]
    pub const fn runtime_trust_level(&self) -> Option<RuntimeTrustLevel> {
        self.runtime_trust_level
    }

    /// Returns the profile permission review mode override.
    #[must_use]
    pub const fn permission_review_mode(&self) -> Option<PermissionReviewMode> {
        self.permission_review_mode
    }

    /// Returns the host-owned permission admission source.
    #[must_use]
    pub fn permission_admission_source(&self) -> Option<Arc<dyn PermissionAdmissionSource>> {
        self.permission_admission_source.as_ref().map(Arc::clone)
    }

    /// Returns the permissioned process runner factory.
    #[must_use]
    pub fn permissioned_process_runner_factory(
        &self,
    ) -> Option<Arc<dyn PermissionedProcessRunnerFactory>> {
        self.permissioned_process_runner_factory
            .as_ref()
            .map(Arc::clone)
    }

    /// Returns the profile skill catalog.
    #[must_use]
    pub const fn skill_catalog(&self) -> Option<&SkillCatalog> {
        self.skill_catalog.as_ref()
    }

    /// Returns the profile project rules.
    #[must_use]
    pub const fn project_rules(&self) -> Option<&ProjectRules> {
        self.project_rules.as_ref()
    }

    /// Returns the profile task anchor.
    #[must_use]
    pub const fn task_anchor(&self) -> Option<&TaskAnchor> {
        self.task_anchor.as_ref()
    }

    /// Returns the profile subagent manager.
    #[must_use]
    pub const fn subagent_manager(&self) -> Option<&SubagentManager> {
        self.subagent_manager.as_ref()
    }

    pub(crate) fn into_parts(self) -> RuntimeProfileParts {
        RuntimeProfileParts {
            capabilities: self.capabilities,
            model_retry_policy: self.model_retry_policy,
            prompt_profile: self.prompt_profile,
            progress_commentary: self.progress_commentary,
            initial_context_summaries: self.initial_context_summaries,
            registered_tools: self.registered_tools,
            allow_bridge_tools: self.allow_bridge_tools,
            allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
            low_risk_process_runner: self.low_risk_process_runner,
            read_only_shell_process_runner: self.read_only_shell_process_runner,
            accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
            runtime_trust_level: self.runtime_trust_level,
            permission_review_mode: self.permission_review_mode,
            permission_admission_source: self.permission_admission_source,
            permissioned_process_runner_factory: self.permissioned_process_runner_factory,
            background_process_control: self.background_process_control,
            skill_catalog: self.skill_catalog,
            project_rules: self.project_rules,
            task_anchor: self.task_anchor,
            subagent_manager: self.subagent_manager,
        }
    }
}

pub(crate) struct RuntimeProfileParts {
    pub(crate) capabilities: RuntimeCapabilities,
    pub(crate) model_retry_policy: Option<ModelRetryPolicy>,
    pub(crate) prompt_profile: PromptProfile,
    pub(crate) progress_commentary: bool,
    pub(crate) initial_context_summaries: BTreeMap<String, String>,
    pub(crate) registered_tools: Vec<RegisteredTool>,
    pub(crate) allow_bridge_tools: bool,
    pub(crate) allow_low_risk_apply_patches: bool,
    pub(crate) low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
    pub(crate) read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
    pub(crate) accepted_local_workspace_process_runner:
        Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
    pub(crate) runtime_trust_level: Option<RuntimeTrustLevel>,
    pub(crate) permission_review_mode: Option<PermissionReviewMode>,
    pub(crate) permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
    pub(crate) permissioned_process_runner_factory:
        Option<Arc<dyn PermissionedProcessRunnerFactory>>,
    pub(crate) background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
    pub(crate) skill_catalog: Option<SkillCatalog>,
    pub(crate) project_rules: Option<ProjectRules>,
    pub(crate) task_anchor: Option<TaskAnchor>,
    pub(crate) subagent_manager: Option<SubagentManager>,
}

/// Builder for a complete runtime profile.
pub struct RuntimeProfileBuilder {
    capabilities: RuntimeCapabilities,
    model_retry_policy: Option<ModelRetryPolicy>,
    prompt_profile: PromptProfile,
    progress_commentary: bool,
    initial_context_summaries: BTreeMap<String, String>,
    registered_tools: Vec<RegisteredTool>,
    allow_bridge_tools: bool,
    allow_low_risk_apply_patches: bool,
    low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
    read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
    accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
    runtime_trust_level: Option<RuntimeTrustLevel>,
    permission_review_mode: Option<PermissionReviewMode>,
    permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
    permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
    background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
    skill_catalog: Option<SkillCatalog>,
    project_rules: Option<ProjectRules>,
    task_anchor: Option<TaskAnchor>,
    subagent_manager: Option<SubagentManager>,
}

impl RuntimeProfileBuilder {
    /// Creates an empty runtime profile builder with default-deny capabilities.
    #[must_use]
    pub fn new() -> Self {
        Self {
            capabilities: RuntimeCapabilities::default(),
            model_retry_policy: None,
            prompt_profile: PromptProfile::default(),
            progress_commentary: false,
            initial_context_summaries: BTreeMap::new(),
            registered_tools: Vec::new(),
            allow_bridge_tools: false,
            allow_low_risk_apply_patches: false,
            low_risk_process_runner: None,
            read_only_shell_process_runner: None,
            accepted_local_workspace_process_runner: None,
            runtime_trust_level: None,
            permission_review_mode: None,
            permission_admission_source: None,
            permissioned_process_runner_factory: None,
            background_process_control: None,
            skill_catalog: None,
            project_rules: None,
            task_anchor: None,
            subagent_manager: None,
        }
    }

    /// Sets low-level Merry-managed capabilities.
    #[must_use]
    pub fn capabilities(mut self, capabilities: RuntimeCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Sets provider-neutral model retry policy for runtimes using this profile.
    #[must_use]
    pub fn model_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
        self.model_retry_policy = Some(policy);
        self
    }

    /// Sets the stable prompt composition used by runtime request compilation.
    #[must_use]
    pub fn prompt_profile(mut self, profile: PromptProfile) -> Self {
        self.prompt_profile = profile;
        self
    }

    /// Controls whether the profile asks the model to emit brief tool-progress commentary.
    ///
    /// This is prompt guidance only. Runtime state and final output remain
    /// separate from commentary, and model-authored commentary is still recorded
    /// if a provider emits it while this is disabled.
    #[must_use]
    pub fn progress_commentary(mut self, enabled: bool) -> Self {
        self.progress_commentary = enabled;
        self
    }

    /// Adds a startup context summary.
    #[must_use]
    pub fn initial_context_summary(mut self, id: &str, text: &str) -> Self {
        self.initial_context_summaries
            .insert(id.to_owned(), text.to_owned());
        self
    }

    /// Registers a runtime-owned tool in this profile.
    #[must_use]
    pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
        self.registered_tools.push(tool);
        self
    }

    /// Allows bridge tools registered through this profile.
    #[must_use]
    pub fn allow_bridge_tools(mut self) -> Self {
        self.allow_bridge_tools = true;
        self
    }

    /// Allows validated low-risk workspace patch proposals.
    #[must_use]
    pub fn allow_low_risk_apply_patches(mut self) -> Self {
        self.allow_low_risk_apply_patches = true;
        self
    }

    /// Sets the low-risk process action runner.
    #[must_use]
    pub fn allow_low_risk_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
        self.low_risk_process_runner = Some(runner);
        self
    }

    /// Sets the read-only shell process runner.
    #[must_use]
    pub fn allow_read_only_shell_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
        self.read_only_shell_process_runner = Some(runner);
        self
    }

    /// Sets the accepted local workspace process runner lane.
    #[must_use]
    pub fn allow_accepted_local_workspace_process_actions(
        mut self,
        admission: AcceptedLocalWorkspaceProcessAdmission,
        runner: Arc<dyn ProcessRunner>,
    ) -> Self {
        self.accepted_local_workspace_process_runner = Some(
            AcceptedLocalWorkspaceProcessRunnerProfile::new(admission, runner),
        );
        self
    }

    /// Sets the profile trust level.
    #[must_use]
    pub fn runtime_trust_level(mut self, trust_level: RuntimeTrustLevel) -> Self {
        self.runtime_trust_level = Some(trust_level);
        self
    }

    /// Sets the profile permission review mode.
    #[must_use]
    pub fn permission_review_mode(mut self, mode: PermissionReviewMode) -> Self {
        self.permission_review_mode = Some(mode);
        self
    }

    /// Sets the host-owned permission admission source.
    #[must_use]
    pub fn permission_admission_source(
        mut self,
        source: Arc<dyn PermissionAdmissionSource>,
    ) -> Self {
        self.permission_admission_source = Some(source);
        self
    }

    /// Keeps the board that lists, reads, and stops background processes.
    #[must_use]
    pub fn background_process_control(
        mut self,
        control: Arc<dyn BackgroundProcessControl>,
    ) -> Self {
        self.background_process_control = Some(control);
        self
    }

    /// Sets the permissioned process runner factory.
    #[must_use]
    pub fn permissioned_process_runner_factory(
        mut self,
        factory: Arc<dyn PermissionedProcessRunnerFactory>,
    ) -> Self {
        self.permissioned_process_runner_factory = Some(factory);
        self
    }

    /// Sets the profile skill catalog.
    #[must_use]
    pub fn skill_catalog(mut self, catalog: SkillCatalog) -> Self {
        self.skill_catalog = Some(catalog);
        self
    }

    /// Sets profile project rules.
    #[must_use]
    pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
        self.project_rules = Some(project_rules);
        self
    }

    /// Sets the profile task anchor.
    #[must_use]
    pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
        self.task_anchor = Some(task_anchor);
        self
    }

    /// Sets the profile subagent manager.
    #[must_use]
    pub fn subagent_manager(mut self, manager: SubagentManager) -> Self {
        self.subagent_manager = Some(manager);
        self
    }

    /// Builds the runtime profile.
    pub fn build(self) -> Result<RuntimeProfile, RuntimeProfileError> {
        let mut names = BTreeSet::new();
        for tool in &self.registered_tools {
            let name = tool.spec().name().clone();
            if name.as_str() == crate::FINAL_OUTPUT_TOOL_NAME {
                return Err(RuntimeProfileError::ReservedToolName { name });
            }
            if !names.insert(name.clone()) {
                return Err(RuntimeProfileError::DuplicateToolRegistration { name });
            }
        }

        Ok(RuntimeProfile {
            capabilities: self.capabilities,
            model_retry_policy: self.model_retry_policy,
            prompt_profile: self.prompt_profile,
            progress_commentary: self.progress_commentary,
            initial_context_summaries: self.initial_context_summaries,
            registered_tools: self.registered_tools,
            allow_bridge_tools: self.allow_bridge_tools,
            allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
            low_risk_process_runner: self.low_risk_process_runner,
            read_only_shell_process_runner: self.read_only_shell_process_runner,
            accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
            runtime_trust_level: self.runtime_trust_level,
            permission_review_mode: self.permission_review_mode,
            permission_admission_source: self.permission_admission_source,
            permissioned_process_runner_factory: self.permissioned_process_runner_factory,
            background_process_control: self.background_process_control,
            skill_catalog: self.skill_catalog,
            project_rules: self.project_rules,
            task_anchor: self.task_anchor,
            subagent_manager: self.subagent_manager,
        })
    }
}

impl Default for RuntimeProfileBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{PathAccess, PathAccessRule, PathAccessRuleSource, RuntimeCapabilities};
    use std::path::Path;

    #[test]
    fn runtime_capabilities_control_network_without_tool_network_field() {
        let capabilities = RuntimeCapabilities::default().allow_network();

        assert!(capabilities.network_allowed());
    }

    #[test]
    fn runtime_capabilities_deny_network_by_default() {
        let capabilities = RuntimeCapabilities::default();

        assert!(!capabilities.network_allowed());
    }

    #[test]
    fn runtime_capabilities_carry_platform_neutral_path_rules() {
        let rule = PathAccessRule::new(
            "/var/log/foo",
            PathAccess::ReadOnly,
            PathAccessRuleSource::TrustedGlobalConfig,
        );
        let capabilities = RuntimeCapabilities::default().with_path_rule(rule);

        assert_eq!(capabilities.path_rules().len(), 1);
        assert_eq!(
            capabilities.path_rules()[0].path(),
            Path::new("/var/log/foo")
        );
        assert_eq!(capabilities.path_rules()[0].access(), PathAccess::ReadOnly);
        assert_eq!(
            capabilities.path_rules()[0].source(),
            PathAccessRuleSource::TrustedGlobalConfig
        );
    }

    #[test]
    fn path_access_has_stable_config_spelling() {
        assert_eq!(PathAccess::ReadOnly.as_str(), "ro");
        assert_eq!(PathAccess::ReadWrite.as_str(), "rw");
        assert_eq!(PathAccess::Deny.as_str(), "deny");
    }

    #[test]
    fn path_access_coverage_keeps_read_only_and_read_write_distinct() {
        assert!(PathAccess::ReadWrite.covers(PathAccess::ReadOnly));
        assert!(PathAccess::ReadWrite.covers(PathAccess::ReadWrite));
        assert!(PathAccess::ReadOnly.covers(PathAccess::ReadOnly));
        assert!(!PathAccess::ReadOnly.covers(PathAccess::ReadWrite));
        assert!(!PathAccess::Deny.covers(PathAccess::ReadOnly));
        assert!(!PathAccess::Deny.covers(PathAccess::ReadWrite));
    }
}