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