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