Skip to main content

merry_runtime/
profile.rs

1//! Runtime capability policy and complete runtime profiles.
2
3use crate::{
4    AcceptedLocalWorkspaceProcessAdmission, BackgroundProcessControl, PermissionAdmissionSource,
5    PermissionReviewMode, PermissionedProcessRunnerFactory, ProcessRunner, ProjectRules,
6    PromptProfile, RegisteredTool, RuntimeTrustLevel, SkillCatalog, SubagentManager, TaskAnchor,
7};
8use merry_core::ToolName;
9use merry_llm::ModelRetryPolicy;
10use std::{
11    collections::{BTreeMap, BTreeSet},
12    path::{Path, PathBuf},
13    sync::Arc,
14};
15use thiserror::Error;
16
17/// Filesystem access granted or denied for one configured path.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum PathAccess {
20    /// The path may be read but not written by Merry-managed runtime backends.
21    ReadOnly,
22    /// The path may be read and written by Merry-managed runtime backends.
23    ReadWrite,
24    /// The path must not be made available to Merry-managed runtime backends.
25    Deny,
26}
27
28impl PathAccess {
29    /// Returns the stable config/API spelling for this access mode.
30    #[must_use]
31    pub const fn as_str(self) -> &'static str {
32        match self {
33            Self::ReadOnly => "ro",
34            Self::ReadWrite => "rw",
35            Self::Deny => "deny",
36        }
37    }
38
39    /// Returns whether this granted access covers a requested access.
40    ///
41    /// Read-write access includes read-only access. Read-only access never
42    /// includes a read-write request, and deny never grants access.
43    #[must_use]
44    pub const fn covers(self, requested: Self) -> bool {
45        matches!(
46            (self, requested),
47            (Self::ReadWrite, Self::ReadOnly | Self::ReadWrite) | (Self::ReadOnly, Self::ReadOnly)
48        )
49    }
50}
51
52/// Trust source for a path access rule.
53#[non_exhaustive]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
55pub enum PathAccessRuleSource {
56    /// Rule supplied by Merry's built-in development process baseline.
57    DefaultDevelopmentBaseline,
58    /// Rule came from the user's global Merry config.
59    ///
60    /// This is intentionally higher trust than project-local configuration,
61    /// because normal coding-agent runs may edit files inside the project.
62    TrustedGlobalConfig,
63    /// Product-owned credentials and state unavailable to actions.
64    ProductPrivate,
65    /// Merry's own non-secret configuration and skill directories.
66    ///
67    /// These directories live outside the workspace and hold no credentials, so
68    /// sandboxed commands may read and update user config and skills directly.
69    ProductConfig,
70    /// Automatically applied read-only protection for Git metadata paths.
71    ///
72    /// A reviewed action may temporarily overlay this rule for one process
73    /// action, but the path is never retained as a session grant.
74    GitMetadataBaseline,
75    /// Rule materialized from the current permission admission result.
76    PermissionReview,
77    /// Durable memory notes under the XDG data home.
78    ///
79    /// This tree is outside the workspace. Sandboxed commands can read and
80    /// write it so the agent can use the same notes the host maintains.
81    DurableMemory,
82}
83
84/// One platform-neutral path access rule consumed by sandbox backends.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct PathAccessRule {
87    path: PathBuf,
88    access: PathAccess,
89    source: PathAccessRuleSource,
90    review_required: bool,
91}
92
93impl PathAccessRule {
94    /// Creates a path access rule.
95    #[must_use]
96    pub fn new(path: impl Into<PathBuf>, access: PathAccess, source: PathAccessRuleSource) -> Self {
97        Self {
98            path: path.into(),
99            access,
100            source,
101            review_required: false,
102        }
103    }
104
105    /// Requires a fresh approval before each action may use this path subtree.
106    ///
107    /// This restricts the declared access; it does not increase its ceiling.
108    #[must_use]
109    pub const fn with_review_required(mut self) -> Self {
110        self.review_required = true;
111        self
112    }
113
114    /// Returns whether this subtree is unavailable without action-scoped review.
115    #[must_use]
116    pub const fn review_required(&self) -> bool {
117        self.review_required
118    }
119
120    /// Returns the configured path.
121    #[must_use]
122    pub fn path(&self) -> &Path {
123        &self.path
124    }
125
126    /// Returns the requested access.
127    #[must_use]
128    pub const fn access(&self) -> PathAccess {
129        self.access
130    }
131
132    /// Returns the trust source for this rule.
133    #[must_use]
134    pub const fn source(&self) -> PathAccessRuleSource {
135        self.source
136    }
137}
138
139/// Merry-managed low-level capability policy.
140///
141/// This constrains capabilities owned by Merry-managed runners, such as file
142/// and process access lanes. It is not a complete product runtime profile or a
143/// trust label for arbitrary host code or in-process tool executors.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct RuntimeCapabilities {
146    network_allowed: bool,
147    path_rules: Vec<PathAccessRule>,
148}
149
150impl RuntimeCapabilities {
151    /// Creates the default capability policy.
152    ///
153    /// The default denies network and starts with no path grants.
154    #[must_use]
155    pub fn new() -> Self {
156        Self {
157            network_allowed: false,
158            path_rules: Vec::new(),
159        }
160    }
161
162    /// Allows Merry-managed network capability for this runtime.
163    #[must_use]
164    pub fn allow_network(mut self) -> Self {
165        self.network_allowed = true;
166        self
167    }
168
169    /// Denies Merry-managed network capability for this runtime.
170    #[must_use]
171    pub fn deny_network(mut self) -> Self {
172        self.network_allowed = false;
173        self
174    }
175
176    /// Adds one path access rule to this profile.
177    #[must_use]
178    pub fn with_path_rule(mut self, rule: PathAccessRule) -> Self {
179        self.path_rules.push(rule);
180        self
181    }
182
183    /// Replaces all path access rules for this profile.
184    #[must_use]
185    pub fn with_path_rules(mut self, rules: Vec<PathAccessRule>) -> Self {
186        self.path_rules = rules;
187        self
188    }
189
190    /// Returns whether Merry-managed network capability is allowed.
191    #[must_use]
192    pub fn network_allowed(&self) -> bool {
193        self.network_allowed
194    }
195
196    /// Returns platform-neutral path access rules for Merry-managed backends.
197    #[must_use]
198    pub fn path_rules(&self) -> &[PathAccessRule] {
199        &self.path_rules
200    }
201}
202
203impl Default for RuntimeCapabilities {
204    fn default() -> Self {
205        Self::new()
206    }
207}
208
209/// Errors raised while building a complete runtime profile.
210#[derive(Debug, Error, Clone, PartialEq, Eq)]
211pub enum RuntimeProfileError {
212    /// A profile tried to register the same tool more than once.
213    #[error("tool {name} is already registered in runtime profile")]
214    DuplicateToolRegistration {
215        /// Duplicate tool name.
216        name: ToolName,
217    },
218    /// A profile tried to register a runtime-reserved tool name.
219    #[error("tool {name} is reserved by the runtime")]
220    ReservedToolName {
221        /// Rejected reserved tool name.
222        name: ToolName,
223    },
224}
225
226/// Accepted local workspace process lane carried by a runtime profile.
227#[derive(Clone)]
228pub struct AcceptedLocalWorkspaceProcessRunnerProfile {
229    admission: AcceptedLocalWorkspaceProcessAdmission,
230    runner: Arc<dyn ProcessRunner>,
231}
232
233impl AcceptedLocalWorkspaceProcessRunnerProfile {
234    /// Creates a profile-owned accepted local workspace process lane.
235    #[must_use]
236    pub fn new(
237        admission: AcceptedLocalWorkspaceProcessAdmission,
238        runner: Arc<dyn ProcessRunner>,
239    ) -> Self {
240        Self { admission, runner }
241    }
242
243    /// Returns the accepted local workspace process admission evidence.
244    #[must_use]
245    pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
246        self.admission
247    }
248
249    /// Returns the process runner for this lane.
250    #[must_use]
251    pub fn runner(&self) -> Arc<dyn ProcessRunner> {
252        Arc::clone(&self.runner)
253    }
254}
255
256/// Complete runtime shape applied by [`crate::RuntimeBuilder::with_profile`].
257#[derive(Clone)]
258pub struct RuntimeProfile {
259    capabilities: RuntimeCapabilities,
260    model_retry_policy: Option<ModelRetryPolicy>,
261    prompt_profile: PromptProfile,
262    progress_commentary: bool,
263    initial_context_summaries: BTreeMap<String, String>,
264    registered_tools: Vec<RegisteredTool>,
265    allow_bridge_tools: bool,
266    allow_low_risk_apply_patches: bool,
267    low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
268    read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
269    accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
270    runtime_trust_level: Option<RuntimeTrustLevel>,
271    permission_review_mode: Option<PermissionReviewMode>,
272    permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
273    permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
274    background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
275    skill_catalog: Option<SkillCatalog>,
276    project_rules: Option<ProjectRules>,
277    task_anchor: Option<TaskAnchor>,
278    subagent_manager: Option<SubagentManager>,
279}
280
281impl RuntimeProfile {
282    /// Creates a profile builder.
283    #[must_use]
284    pub fn builder() -> RuntimeProfileBuilder {
285        RuntimeProfileBuilder::new()
286    }
287
288    /// Returns low-level Merry-managed capabilities.
289    #[must_use]
290    pub const fn capabilities(&self) -> &RuntimeCapabilities {
291        &self.capabilities
292    }
293
294    /// Returns the profile model retry policy override.
295    #[must_use]
296    pub const fn model_retry_policy(&self) -> Option<ModelRetryPolicy> {
297        self.model_retry_policy
298    }
299
300    /// Returns the stable prompt composition used by runtime request compilation.
301    #[must_use]
302    pub const fn prompt_profile(&self) -> &PromptProfile {
303        &self.prompt_profile
304    }
305
306    /// Returns whether this profile asks the model for tool-progress commentary.
307    #[must_use]
308    pub const fn progress_commentary(&self) -> bool {
309        self.progress_commentary
310    }
311
312    /// Returns startup context summaries keyed by stable id.
313    #[must_use]
314    pub fn initial_context_summaries(&self) -> &BTreeMap<String, String> {
315        &self.initial_context_summaries
316    }
317
318    /// Returns registered tools carried by the profile.
319    #[must_use]
320    pub fn registered_tools(&self) -> &[RegisteredTool] {
321        &self.registered_tools
322    }
323
324    /// Consumes the profile and returns registered tools.
325    #[must_use]
326    pub fn into_registered_tools(self) -> Vec<RegisteredTool> {
327        self.registered_tools
328    }
329
330    /// Returns whether bridge tools are allowed.
331    #[must_use]
332    pub const fn allow_bridge_tools(&self) -> bool {
333        self.allow_bridge_tools
334    }
335
336    /// Returns whether low-risk workspace patches are allowed.
337    #[must_use]
338    pub const fn allow_low_risk_apply_patches(&self) -> bool {
339        self.allow_low_risk_apply_patches
340    }
341
342    /// Returns the low-risk process action runner.
343    #[must_use]
344    pub fn low_risk_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
345        self.low_risk_process_runner.as_ref().map(Arc::clone)
346    }
347
348    /// Returns the read-only shell process runner.
349    #[must_use]
350    pub fn read_only_shell_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
351        self.read_only_shell_process_runner.as_ref().map(Arc::clone)
352    }
353
354    /// Returns the accepted local workspace process runner lane.
355    #[must_use]
356    pub fn accepted_local_workspace_process_runner(
357        &self,
358    ) -> Option<&AcceptedLocalWorkspaceProcessRunnerProfile> {
359        self.accepted_local_workspace_process_runner.as_ref()
360    }
361
362    /// Returns the profile runtime trust level override.
363    #[must_use]
364    pub const fn runtime_trust_level(&self) -> Option<RuntimeTrustLevel> {
365        self.runtime_trust_level
366    }
367
368    /// Returns the profile permission review mode override.
369    #[must_use]
370    pub const fn permission_review_mode(&self) -> Option<PermissionReviewMode> {
371        self.permission_review_mode
372    }
373
374    /// Returns the host-owned permission admission source.
375    #[must_use]
376    pub fn permission_admission_source(&self) -> Option<Arc<dyn PermissionAdmissionSource>> {
377        self.permission_admission_source.as_ref().map(Arc::clone)
378    }
379
380    /// Returns the permissioned process runner factory.
381    #[must_use]
382    pub fn permissioned_process_runner_factory(
383        &self,
384    ) -> Option<Arc<dyn PermissionedProcessRunnerFactory>> {
385        self.permissioned_process_runner_factory
386            .as_ref()
387            .map(Arc::clone)
388    }
389
390    /// Returns the profile skill catalog.
391    #[must_use]
392    pub const fn skill_catalog(&self) -> Option<&SkillCatalog> {
393        self.skill_catalog.as_ref()
394    }
395
396    /// Returns the profile project rules.
397    #[must_use]
398    pub const fn project_rules(&self) -> Option<&ProjectRules> {
399        self.project_rules.as_ref()
400    }
401
402    /// Returns the profile task anchor.
403    #[must_use]
404    pub const fn task_anchor(&self) -> Option<&TaskAnchor> {
405        self.task_anchor.as_ref()
406    }
407
408    /// Returns the profile subagent manager.
409    #[must_use]
410    pub const fn subagent_manager(&self) -> Option<&SubagentManager> {
411        self.subagent_manager.as_ref()
412    }
413
414    pub(crate) fn into_parts(self) -> RuntimeProfileParts {
415        RuntimeProfileParts {
416            capabilities: self.capabilities,
417            model_retry_policy: self.model_retry_policy,
418            prompt_profile: self.prompt_profile,
419            progress_commentary: self.progress_commentary,
420            initial_context_summaries: self.initial_context_summaries,
421            registered_tools: self.registered_tools,
422            allow_bridge_tools: self.allow_bridge_tools,
423            allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
424            low_risk_process_runner: self.low_risk_process_runner,
425            read_only_shell_process_runner: self.read_only_shell_process_runner,
426            accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
427            runtime_trust_level: self.runtime_trust_level,
428            permission_review_mode: self.permission_review_mode,
429            permission_admission_source: self.permission_admission_source,
430            permissioned_process_runner_factory: self.permissioned_process_runner_factory,
431            background_process_control: self.background_process_control,
432            skill_catalog: self.skill_catalog,
433            project_rules: self.project_rules,
434            task_anchor: self.task_anchor,
435            subagent_manager: self.subagent_manager,
436        }
437    }
438}
439
440pub(crate) struct RuntimeProfileParts {
441    pub(crate) capabilities: RuntimeCapabilities,
442    pub(crate) model_retry_policy: Option<ModelRetryPolicy>,
443    pub(crate) prompt_profile: PromptProfile,
444    pub(crate) progress_commentary: bool,
445    pub(crate) initial_context_summaries: BTreeMap<String, String>,
446    pub(crate) registered_tools: Vec<RegisteredTool>,
447    pub(crate) allow_bridge_tools: bool,
448    pub(crate) allow_low_risk_apply_patches: bool,
449    pub(crate) low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
450    pub(crate) read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
451    pub(crate) accepted_local_workspace_process_runner:
452        Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
453    pub(crate) runtime_trust_level: Option<RuntimeTrustLevel>,
454    pub(crate) permission_review_mode: Option<PermissionReviewMode>,
455    pub(crate) permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
456    pub(crate) permissioned_process_runner_factory:
457        Option<Arc<dyn PermissionedProcessRunnerFactory>>,
458    pub(crate) background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
459    pub(crate) skill_catalog: Option<SkillCatalog>,
460    pub(crate) project_rules: Option<ProjectRules>,
461    pub(crate) task_anchor: Option<TaskAnchor>,
462    pub(crate) subagent_manager: Option<SubagentManager>,
463}
464
465/// Builder for a complete runtime profile.
466pub struct RuntimeProfileBuilder {
467    capabilities: RuntimeCapabilities,
468    model_retry_policy: Option<ModelRetryPolicy>,
469    prompt_profile: PromptProfile,
470    progress_commentary: bool,
471    initial_context_summaries: BTreeMap<String, String>,
472    registered_tools: Vec<RegisteredTool>,
473    allow_bridge_tools: bool,
474    allow_low_risk_apply_patches: bool,
475    low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
476    read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
477    accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
478    runtime_trust_level: Option<RuntimeTrustLevel>,
479    permission_review_mode: Option<PermissionReviewMode>,
480    permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
481    permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
482    background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
483    skill_catalog: Option<SkillCatalog>,
484    project_rules: Option<ProjectRules>,
485    task_anchor: Option<TaskAnchor>,
486    subagent_manager: Option<SubagentManager>,
487}
488
489impl RuntimeProfileBuilder {
490    /// Creates an empty runtime profile builder with default-deny capabilities.
491    #[must_use]
492    pub fn new() -> Self {
493        Self {
494            capabilities: RuntimeCapabilities::default(),
495            model_retry_policy: None,
496            prompt_profile: PromptProfile::default(),
497            progress_commentary: false,
498            initial_context_summaries: BTreeMap::new(),
499            registered_tools: Vec::new(),
500            allow_bridge_tools: false,
501            allow_low_risk_apply_patches: false,
502            low_risk_process_runner: None,
503            read_only_shell_process_runner: None,
504            accepted_local_workspace_process_runner: None,
505            runtime_trust_level: None,
506            permission_review_mode: None,
507            permission_admission_source: None,
508            permissioned_process_runner_factory: None,
509            background_process_control: None,
510            skill_catalog: None,
511            project_rules: None,
512            task_anchor: None,
513            subagent_manager: None,
514        }
515    }
516
517    /// Sets low-level Merry-managed capabilities.
518    #[must_use]
519    pub fn capabilities(mut self, capabilities: RuntimeCapabilities) -> Self {
520        self.capabilities = capabilities;
521        self
522    }
523
524    /// Sets provider-neutral model retry policy for runtimes using this profile.
525    #[must_use]
526    pub fn model_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
527        self.model_retry_policy = Some(policy);
528        self
529    }
530
531    /// Sets the stable prompt composition used by runtime request compilation.
532    #[must_use]
533    pub fn prompt_profile(mut self, profile: PromptProfile) -> Self {
534        self.prompt_profile = profile;
535        self
536    }
537
538    /// Controls whether the profile asks the model to emit brief tool-progress commentary.
539    ///
540    /// This is prompt guidance only. Runtime state and final output remain
541    /// separate from commentary, and model-authored commentary is still recorded
542    /// if a provider emits it while this is disabled.
543    #[must_use]
544    pub fn progress_commentary(mut self, enabled: bool) -> Self {
545        self.progress_commentary = enabled;
546        self
547    }
548
549    /// Adds a startup context summary.
550    #[must_use]
551    pub fn initial_context_summary(mut self, id: &str, text: &str) -> Self {
552        self.initial_context_summaries
553            .insert(id.to_owned(), text.to_owned());
554        self
555    }
556
557    /// Registers a runtime-owned tool in this profile.
558    #[must_use]
559    pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
560        self.registered_tools.push(tool);
561        self
562    }
563
564    /// Allows bridge tools registered through this profile.
565    #[must_use]
566    pub fn allow_bridge_tools(mut self) -> Self {
567        self.allow_bridge_tools = true;
568        self
569    }
570
571    /// Allows validated low-risk workspace patch proposals.
572    #[must_use]
573    pub fn allow_low_risk_apply_patches(mut self) -> Self {
574        self.allow_low_risk_apply_patches = true;
575        self
576    }
577
578    /// Sets the low-risk process action runner.
579    #[must_use]
580    pub fn allow_low_risk_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
581        self.low_risk_process_runner = Some(runner);
582        self
583    }
584
585    /// Sets the read-only shell process runner.
586    #[must_use]
587    pub fn allow_read_only_shell_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
588        self.read_only_shell_process_runner = Some(runner);
589        self
590    }
591
592    /// Sets the accepted local workspace process runner lane.
593    #[must_use]
594    pub fn allow_accepted_local_workspace_process_actions(
595        mut self,
596        admission: AcceptedLocalWorkspaceProcessAdmission,
597        runner: Arc<dyn ProcessRunner>,
598    ) -> Self {
599        self.accepted_local_workspace_process_runner = Some(
600            AcceptedLocalWorkspaceProcessRunnerProfile::new(admission, runner),
601        );
602        self
603    }
604
605    /// Sets the profile trust level.
606    #[must_use]
607    pub fn runtime_trust_level(mut self, trust_level: RuntimeTrustLevel) -> Self {
608        self.runtime_trust_level = Some(trust_level);
609        self
610    }
611
612    /// Sets the profile permission review mode.
613    #[must_use]
614    pub fn permission_review_mode(mut self, mode: PermissionReviewMode) -> Self {
615        self.permission_review_mode = Some(mode);
616        self
617    }
618
619    /// Sets the host-owned permission admission source.
620    #[must_use]
621    pub fn permission_admission_source(
622        mut self,
623        source: Arc<dyn PermissionAdmissionSource>,
624    ) -> Self {
625        self.permission_admission_source = Some(source);
626        self
627    }
628
629    /// Keeps the board that lists, reads, and stops background processes.
630    #[must_use]
631    pub fn background_process_control(
632        mut self,
633        control: Arc<dyn BackgroundProcessControl>,
634    ) -> Self {
635        self.background_process_control = Some(control);
636        self
637    }
638
639    /// Sets the permissioned process runner factory.
640    #[must_use]
641    pub fn permissioned_process_runner_factory(
642        mut self,
643        factory: Arc<dyn PermissionedProcessRunnerFactory>,
644    ) -> Self {
645        self.permissioned_process_runner_factory = Some(factory);
646        self
647    }
648
649    /// Sets the profile skill catalog.
650    #[must_use]
651    pub fn skill_catalog(mut self, catalog: SkillCatalog) -> Self {
652        self.skill_catalog = Some(catalog);
653        self
654    }
655
656    /// Sets profile project rules.
657    #[must_use]
658    pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
659        self.project_rules = Some(project_rules);
660        self
661    }
662
663    /// Sets the profile task anchor.
664    #[must_use]
665    pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
666        self.task_anchor = Some(task_anchor);
667        self
668    }
669
670    /// Sets the profile subagent manager.
671    #[must_use]
672    pub fn subagent_manager(mut self, manager: SubagentManager) -> Self {
673        self.subagent_manager = Some(manager);
674        self
675    }
676
677    /// Builds the runtime profile.
678    pub fn build(self) -> Result<RuntimeProfile, RuntimeProfileError> {
679        let mut names = BTreeSet::new();
680        for tool in &self.registered_tools {
681            let name = tool.spec().name().clone();
682            if name.as_str() == crate::FINAL_OUTPUT_TOOL_NAME {
683                return Err(RuntimeProfileError::ReservedToolName { name });
684            }
685            if !names.insert(name.clone()) {
686                return Err(RuntimeProfileError::DuplicateToolRegistration { name });
687            }
688        }
689
690        Ok(RuntimeProfile {
691            capabilities: self.capabilities,
692            model_retry_policy: self.model_retry_policy,
693            prompt_profile: self.prompt_profile,
694            progress_commentary: self.progress_commentary,
695            initial_context_summaries: self.initial_context_summaries,
696            registered_tools: self.registered_tools,
697            allow_bridge_tools: self.allow_bridge_tools,
698            allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
699            low_risk_process_runner: self.low_risk_process_runner,
700            read_only_shell_process_runner: self.read_only_shell_process_runner,
701            accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
702            runtime_trust_level: self.runtime_trust_level,
703            permission_review_mode: self.permission_review_mode,
704            permission_admission_source: self.permission_admission_source,
705            permissioned_process_runner_factory: self.permissioned_process_runner_factory,
706            background_process_control: self.background_process_control,
707            skill_catalog: self.skill_catalog,
708            project_rules: self.project_rules,
709            task_anchor: self.task_anchor,
710            subagent_manager: self.subagent_manager,
711        })
712    }
713}
714
715impl Default for RuntimeProfileBuilder {
716    fn default() -> Self {
717        Self::new()
718    }
719}
720
721#[cfg(test)]
722mod tests {
723    use super::{PathAccess, PathAccessRule, PathAccessRuleSource, RuntimeCapabilities};
724    use std::path::Path;
725
726    #[test]
727    fn runtime_capabilities_control_network_without_tool_network_field() {
728        let capabilities = RuntimeCapabilities::default().allow_network();
729
730        assert!(capabilities.network_allowed());
731    }
732
733    #[test]
734    fn runtime_capabilities_deny_network_by_default() {
735        let capabilities = RuntimeCapabilities::default();
736
737        assert!(!capabilities.network_allowed());
738    }
739
740    #[test]
741    fn runtime_capabilities_carry_platform_neutral_path_rules() {
742        let rule = PathAccessRule::new(
743            "/var/log/foo",
744            PathAccess::ReadOnly,
745            PathAccessRuleSource::TrustedGlobalConfig,
746        );
747        let capabilities = RuntimeCapabilities::default().with_path_rule(rule);
748
749        assert_eq!(capabilities.path_rules().len(), 1);
750        assert_eq!(
751            capabilities.path_rules()[0].path(),
752            Path::new("/var/log/foo")
753        );
754        assert_eq!(capabilities.path_rules()[0].access(), PathAccess::ReadOnly);
755        assert_eq!(
756            capabilities.path_rules()[0].source(),
757            PathAccessRuleSource::TrustedGlobalConfig
758        );
759    }
760
761    #[test]
762    fn path_access_has_stable_config_spelling() {
763        assert_eq!(PathAccess::ReadOnly.as_str(), "ro");
764        assert_eq!(PathAccess::ReadWrite.as_str(), "rw");
765        assert_eq!(PathAccess::Deny.as_str(), "deny");
766    }
767
768    #[test]
769    fn path_access_coverage_keeps_read_only_and_read_write_distinct() {
770        assert!(PathAccess::ReadWrite.covers(PathAccess::ReadOnly));
771        assert!(PathAccess::ReadWrite.covers(PathAccess::ReadWrite));
772        assert!(PathAccess::ReadOnly.covers(PathAccess::ReadOnly));
773        assert!(!PathAccess::ReadOnly.covers(PathAccess::ReadWrite));
774        assert!(!PathAccess::Deny.covers(PathAccess::ReadOnly));
775        assert!(!PathAccess::Deny.covers(PathAccess::ReadWrite));
776    }
777}