Skip to main content

merry_runtime/subagent/
spec.rs

1use super::handoff::{ContextFileRef, MAX_CONTEXT_FILE_REFS};
2use super::protocol::{SubagentWorkspaceMode, SubagentWorktreeBase};
3use merry_core::ToolName;
4use merry_llm::ReasoningEffort;
5use std::{
6    collections::BTreeSet,
7    path::{Path, PathBuf},
8};
9use thiserror::Error;
10
11/// Default foreground wait budget in seconds before handing off to background.
12pub const DEFAULT_FOREGROUND_WAIT_BUDGET_SECS: u64 = 120;
13
14/// Maximum UTF-8 task text size accepted for one child task.
15pub(crate) const MAX_TASK_BYTES: usize = 16 * 1024;
16/// Default minimum model-turn budget for a generic child task.
17pub const DEFAULT_MIN_MODEL_TURNS: u32 = 1;
18/// Default bounded child loop model-turn count.
19///
20/// A small single-digit budget is too restrictive for a child that needs to
21/// inspect files, use tools, verify the result, and report a conclusion. The
22/// limit remains bounded, but is intentionally generous and configurable at
23/// the runtime level.
24pub const DEFAULT_MAX_MODEL_TURNS: u32 = 1024;
25/// Default maximum number of concurrent child agents.
26pub(crate) const DEFAULT_MAX_THREADS: usize = 6;
27/// Default child delegation depth.
28pub(crate) const DEFAULT_MAX_DEPTH: u8 = 1;
29
30/// Validation errors for subagent task contracts and configuration.
31#[derive(Debug, Error, Clone, PartialEq, Eq)]
32pub enum SubagentError {
33    /// The delegated task text was blank.
34    #[error("task must not be blank")]
35    BlankTask,
36    /// The delegated task text exceeded the 16 KiB UTF-8 limit.
37    #[error("task is longer than the allowed maximum")]
38    TaskTooLong,
39    /// The delegated task has no allowed model turns.
40    #[error("max_model_turns must be greater than zero")]
41    ZeroMaxModelTurns,
42    /// The delegated task requested more turns than the configured runtime limit.
43    #[error("max_model_turns {requested} exceeds configured maximum {maximum}")]
44    ExceedsConfiguredMaxModelTurns { requested: u32, maximum: u32 },
45    /// The delegated task requested fewer turns than the configured minimum.
46    #[error("max_model_turns {requested} is below configured minimum {minimum}")]
47    BelowConfiguredMinModelTurns { requested: u32, minimum: u32 },
48    /// The configured minimum is not a valid value.
49    #[error("minimum max_model_turns must be greater than zero")]
50    ZeroMinModelTurns,
51    /// The configured minimum is greater than the configured maximum.
52    #[error("minimum max_model_turns {minimum} exceeds configured maximum {maximum}")]
53    MinExceedsMaxModelTurns { minimum: u32, maximum: u32 },
54    /// A path scope was not a normalized workspace-relative path.
55    #[error("scope path must be relative and normalized: {path}")]
56    InvalidScopePath {
57        /// Rejected path display string.
58        path: String,
59    },
60    /// Two child tasks may write the same path tree.
61    #[error("overlapping write scope between task {first_index} and task {second_index}: {path}")]
62    OverlappingWriteScope {
63        /// Index of the first conflicting task.
64        first_index: usize,
65        /// Index of the second conflicting task.
66        second_index: usize,
67        /// Conflicting write path from the first task.
68        path: String,
69    },
70    /// A child task requested a capability outside the parent's effective envelope.
71    #[error("child task capability expansion is not allowed for {field}: {value}")]
72    CapabilityExpansion {
73        /// Capability category that attempted to expand.
74        field: &'static str,
75        /// Requested capability value.
76        value: String,
77    },
78    /// The subagent runtime was configured with no possible concurrency.
79    #[error("subagent max_threads must be greater than zero")]
80    ZeroMaxThreads,
81    /// The subagent runtime was configured with no child depth.
82    #[error("subagent max_depth must be greater than zero")]
83    ZeroMaxDepth,
84    /// A context file reference was invalid or outside workspace-relative rules.
85    #[error("invalid context_files entry (expected relative path or path:start-end): {value}")]
86    InvalidContextFileRef {
87        /// Rejected context file reference.
88        value: String,
89    },
90    /// Too many context file references were supplied for one child task.
91    #[error("context_files exceeds maximum of {maximum} entries")]
92    TooManyContextFiles {
93        /// Configured entry cap.
94        maximum: usize,
95    },
96    /// A child timeout_secs value was zero.
97    #[error("timeout_secs must be greater than zero")]
98    ZeroTimeoutSecs,
99    /// A foreground wait budget value was zero.
100    #[error("foreground_wait_budget_secs must be greater than zero")]
101    ZeroForegroundBudgetSecs,
102    /// A child max_total_tokens value was zero.
103    #[error("max_total_tokens must be greater than zero")]
104    ZeroMaxTotalTokens,
105    /// A child role name contained invalid characters.
106    #[error("invalid subagent role name: {role}")]
107    InvalidRoleName {
108        /// Rejected role name.
109        role: String,
110    },
111}
112
113/// Admission behavior when a spawn request exceeds `max_threads`.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub enum SubagentLimitBehavior {
116    /// Queue excess children until an active slot frees up (default).
117    #[default]
118    Queue,
119    /// Immediately reject excess children when `max_threads` is already full.
120    Fail,
121}
122
123/// Runtime configuration for subagent delegation limits.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct SubagentConfig {
126    max_threads: usize,
127    max_depth: u8,
128    min_model_turns: u32,
129    max_model_turns: u32,
130    default_timeout_secs: Option<u64>,
131    foreground_wait_budget_secs: u64,
132    limit_behavior: SubagentLimitBehavior,
133    max_total_tokens: Option<u64>,
134}
135
136impl SubagentConfig {
137    /// Creates validated subagent limit configuration.
138    pub fn new(max_threads: usize, max_depth: u8) -> Result<Self, SubagentError> {
139        if max_threads == 0 {
140            return Err(SubagentError::ZeroMaxThreads);
141        }
142        if max_depth == 0 {
143            return Err(SubagentError::ZeroMaxDepth);
144        }
145        Ok(Self {
146            max_threads,
147            max_depth,
148            min_model_turns: DEFAULT_MIN_MODEL_TURNS,
149            max_model_turns: DEFAULT_MAX_MODEL_TURNS,
150            default_timeout_secs: None,
151            foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
152            limit_behavior: SubagentLimitBehavior::Queue,
153            max_total_tokens: None,
154        })
155    }
156
157    /// Sets admission behavior when a batch exceeds `max_threads`.
158    #[must_use]
159    pub fn with_limit_behavior(mut self, behavior: SubagentLimitBehavior) -> Self {
160        self.limit_behavior = behavior;
161        self
162    }
163
164    /// Sets an optional per-child cumulative token circuit breaker.
165    pub fn with_max_total_tokens(
166        mut self,
167        max_total_tokens: Option<u64>,
168    ) -> Result<Self, SubagentError> {
169        if max_total_tokens == Some(0) {
170            return Err(SubagentError::ZeroMaxTotalTokens);
171        }
172        self.max_total_tokens = max_total_tokens;
173        Ok(self)
174    }
175
176    /// Sets an optional default wall-clock timeout in seconds for child tasks.
177    pub fn with_default_timeout_secs(
178        mut self,
179        timeout_secs: Option<u64>,
180    ) -> Result<Self, SubagentError> {
181        if timeout_secs == Some(0) {
182            return Err(SubagentError::ZeroTimeoutSecs);
183        }
184        self.default_timeout_secs = timeout_secs;
185        Ok(self)
186    }
187
188    /// Sets the foreground wait budget in seconds before `wait: "all" | "any"`
189    /// gracefully hands off running children to the background.
190    pub fn with_foreground_wait_budget_secs(
191        mut self,
192        budget_secs: u64,
193    ) -> Result<Self, SubagentError> {
194        if budget_secs == 0 {
195            return Err(SubagentError::ZeroForegroundBudgetSecs);
196        }
197        self.foreground_wait_budget_secs = budget_secs;
198        Ok(self)
199    }
200
201    /// Replaces the default model-turn budget inherited by child tasks that
202    /// omit an explicit `max_model_turns` value.
203    pub fn with_max_model_turns(mut self, max_model_turns: u32) -> Result<Self, SubagentError> {
204        if max_model_turns == 0 {
205            return Err(SubagentError::ZeroMaxModelTurns);
206        }
207        if self.min_model_turns > max_model_turns {
208            return Err(SubagentError::MinExceedsMaxModelTurns {
209                minimum: self.min_model_turns,
210                maximum: max_model_turns,
211            });
212        }
213        self.max_model_turns = max_model_turns;
214        Ok(self)
215    }
216
217    /// Replaces the minimum model-turn budget accepted for explicit child tasks.
218    pub fn with_min_model_turns(mut self, min_model_turns: u32) -> Result<Self, SubagentError> {
219        if min_model_turns == 0 {
220            return Err(SubagentError::ZeroMinModelTurns);
221        }
222        if min_model_turns > self.max_model_turns {
223            return Err(SubagentError::MinExceedsMaxModelTurns {
224                minimum: min_model_turns,
225                maximum: self.max_model_turns,
226            });
227        }
228        self.min_model_turns = min_model_turns;
229        Ok(self)
230    }
231
232    /// Replaces both model-turn bounds in one validated operation.
233    pub fn with_model_turn_bounds(
234        mut self,
235        min_model_turns: u32,
236        max_model_turns: u32,
237    ) -> Result<Self, SubagentError> {
238        if min_model_turns == 0 {
239            return Err(SubagentError::ZeroMinModelTurns);
240        }
241        if max_model_turns == 0 {
242            return Err(SubagentError::ZeroMaxModelTurns);
243        }
244        if min_model_turns > max_model_turns {
245            return Err(SubagentError::MinExceedsMaxModelTurns {
246                minimum: min_model_turns,
247                maximum: max_model_turns,
248            });
249        }
250        self.min_model_turns = min_model_turns;
251        self.max_model_turns = max_model_turns;
252        Ok(self)
253    }
254
255    /// Validates one explicit child budget against this runtime configuration.
256    pub fn validate_task_max_model_turns(self, requested: u32) -> Result<(), SubagentError> {
257        validate_task_max_model_turns(requested, self.min_model_turns, self.max_model_turns)
258    }
259
260    /// Returns the minimum model-turn budget accepted for an explicit child task.
261    #[must_use]
262    pub fn min_model_turns(self) -> u32 {
263        self.min_model_turns
264    }
265
266    /// Returns the maximum number of child agents allowed to run concurrently.
267    #[must_use]
268    pub fn max_threads(self) -> usize {
269        self.max_threads
270    }
271
272    /// Returns the maximum allowed child delegation depth.
273    #[must_use]
274    pub fn max_depth(self) -> u8 {
275        self.max_depth
276    }
277
278    /// Returns the default maximum number of model turns for one child task.
279    #[must_use]
280    pub fn max_model_turns(self) -> u32 {
281        self.max_model_turns
282    }
283
284    /// Returns the optional default wall-clock timeout in seconds for child tasks.
285    #[must_use]
286    pub fn default_timeout_secs(self) -> Option<u64> {
287        self.default_timeout_secs
288    }
289
290    /// Returns the foreground wait budget in seconds.
291    #[must_use]
292    pub fn foreground_wait_budget_secs(self) -> u64 {
293        self.foreground_wait_budget_secs
294    }
295
296    /// Returns admission behavior when `max_threads` is full.
297    #[must_use]
298    pub fn limit_behavior(self) -> SubagentLimitBehavior {
299        self.limit_behavior
300    }
301
302    /// Returns the optional per-child cumulative token circuit breaker.
303    #[must_use]
304    pub fn max_total_tokens(self) -> Option<u64> {
305        self.max_total_tokens
306    }
307}
308
309impl Default for SubagentConfig {
310    fn default() -> Self {
311        Self {
312            max_threads: DEFAULT_MAX_THREADS,
313            max_depth: DEFAULT_MAX_DEPTH,
314            min_model_turns: DEFAULT_MIN_MODEL_TURNS,
315            max_model_turns: DEFAULT_MAX_MODEL_TURNS,
316            default_timeout_secs: None,
317            foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
318            limit_behavior: SubagentLimitBehavior::Queue,
319            max_total_tokens: None,
320        }
321    }
322}
323
324/// Parent-authored specification for a bounded child agent task.
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct SubagentTaskSpec {
327    display_name: Option<String>,
328    role: Option<String>,
329    task: String,
330    max_model_turns: u32,
331    max_model_turns_explicit: bool,
332    timeout_secs: Option<u64>,
333    max_total_tokens: Option<u64>,
334    allowed_tools: Vec<ToolName>,
335    allowed_tools_explicit: bool,
336    read_scope: Vec<PathBuf>,
337    read_scope_explicit: bool,
338    write_scope: Vec<PathBuf>,
339    write_scope_explicit: bool,
340    forbidden_paths: Vec<PathBuf>,
341    forbidden_paths_explicit: bool,
342    context_files: Vec<ContextFileRef>,
343    expected_output: Option<String>,
344    reasoning_effort: Option<ReasoningEffort>,
345    workspace_mode: SubagentWorkspaceMode,
346    worktree_base: SubagentWorktreeBase,
347}
348
349pub(crate) fn validate_task_max_model_turns(
350    requested: u32,
351    minimum: u32,
352    maximum: u32,
353) -> Result<(), SubagentError> {
354    if requested == 0 {
355        return Err(SubagentError::ZeroMaxModelTurns);
356    }
357    if requested < minimum {
358        return Err(SubagentError::BelowConfiguredMinModelTurns { requested, minimum });
359    }
360    if requested > maximum {
361        return Err(SubagentError::ExceedsConfiguredMaxModelTurns { requested, maximum });
362    }
363    Ok(())
364}
365
366impl SubagentTaskSpec {
367    /// Creates a child task specification from validated task text and model-turn bound.
368    pub fn new(task: impl Into<String>, max_model_turns: u32) -> Result<Self, SubagentError> {
369        let task = task.into();
370        validate_task_text(&task)?;
371        if max_model_turns == 0 {
372            return Err(SubagentError::ZeroMaxModelTurns);
373        }
374        Ok(Self {
375            display_name: None,
376            role: None,
377            task,
378            max_model_turns,
379            max_model_turns_explicit: true,
380            timeout_secs: None,
381            max_total_tokens: None,
382            allowed_tools: Vec::new(),
383            allowed_tools_explicit: false,
384            read_scope: Vec::new(),
385            read_scope_explicit: false,
386            write_scope: Vec::new(),
387            write_scope_explicit: false,
388            forbidden_paths: Vec::new(),
389            forbidden_paths_explicit: false,
390            context_files: Vec::new(),
391            expected_output: None,
392            reasoning_effort: None,
393            workspace_mode: SubagentWorkspaceMode::Shared,
394            worktree_base: SubagentWorktreeBase::WorkingTree,
395        })
396    }
397
398    pub(crate) fn with_max_model_turns_unchecked(mut self, max_model_turns: u32) -> Self {
399        self.max_model_turns = max_model_turns;
400        self
401    }
402
403    /// Marks whether `max_model_turns` was explicitly requested by the parent
404    /// (as opposed to filled from the runtime default).
405    #[must_use]
406    pub fn with_max_model_turns_explicit(mut self, explicit: bool) -> Self {
407        self.max_model_turns_explicit = explicit;
408        self
409    }
410
411    /// Returns true when the parent explicitly requested `max_model_turns`.
412    #[must_use]
413    pub const fn max_model_turns_is_explicit(&self) -> bool {
414        self.max_model_turns_explicit
415    }
416
417    /// Returns the optional cumulative token circuit breaker for this task.
418    #[must_use]
419    pub const fn max_total_tokens(&self) -> Option<u64> {
420        self.max_total_tokens
421    }
422
423    /// Sets an optional cumulative token circuit breaker for this task.
424    #[must_use]
425    pub fn with_max_total_tokens(mut self, max_total_tokens: Option<u64>) -> Self {
426        self.max_total_tokens = max_total_tokens.filter(|value| *value > 0);
427        self
428    }
429
430    /// Returns the optional role name requested for this child task.
431    #[must_use]
432    pub fn role(&self) -> Option<&str> {
433        self.role.as_deref()
434    }
435
436    /// Returns the optional wall-clock timeout in seconds for this child task.
437    #[must_use]
438    pub const fn timeout_secs(&self) -> Option<u64> {
439        self.timeout_secs
440    }
441
442    /// Returns the validated workspace-relative `context_files` references to preload.
443    #[must_use]
444    pub fn context_files(&self) -> &[ContextFileRef] {
445        &self.context_files
446    }
447
448    /// Returns the child work description.
449    ///
450    /// Workspace capability belongs to the structured scope fields and the
451    /// runtime-derived scope context, not this task text.
452    #[must_use]
453    pub fn task(&self) -> &str {
454        &self.task
455    }
456
457    /// Returns the maximum number of bounded child model turns.
458    #[must_use]
459    pub fn max_model_turns(&self) -> u32 {
460        self.max_model_turns
461    }
462
463    /// Returns the provider/tool names the child may use.
464    #[must_use]
465    pub fn allowed_tools(&self) -> &[ToolName] {
466        &self.allowed_tools
467    }
468
469    #[must_use]
470    pub fn allowed_tools_are_explicit(&self) -> bool {
471        self.allowed_tools_explicit
472    }
473
474    pub(crate) fn read_scope_is_explicit(&self) -> bool {
475        self.read_scope_explicit
476    }
477
478    /// Returns whether the parent explicitly supplied the write scope,
479    /// including an explicit empty scope for a read-only child.
480    #[must_use]
481    pub fn write_scope_is_explicit(&self) -> bool {
482        self.write_scope_explicit
483    }
484
485    pub(crate) fn forbidden_paths_are_explicit(&self) -> bool {
486        self.forbidden_paths_explicit
487    }
488
489    /// Returns the optional compact display name.
490    #[must_use]
491    pub fn display_name(&self) -> Option<&str> {
492        self.display_name.as_deref()
493    }
494
495    /// Returns the workspace-relative read scope.
496    #[must_use]
497    pub fn read_scope(&self) -> &[PathBuf] {
498        &self.read_scope
499    }
500
501    /// Returns the workspace-relative write scope.
502    #[must_use]
503    pub fn write_scope(&self) -> &[PathBuf] {
504        &self.write_scope
505    }
506
507    /// Returns workspace-relative paths the child must not access.
508    #[must_use]
509    pub fn forbidden_paths(&self) -> &[PathBuf] {
510        &self.forbidden_paths
511    }
512
513    /// Returns the optional expected-output instruction.
514    #[must_use]
515    pub fn expected_output(&self) -> Option<&str> {
516        self.expected_output.as_deref()
517    }
518
519    /// Returns the optional reasoning-effort override for this child task.
520    #[must_use]
521    pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
522        self.reasoning_effort.as_ref()
523    }
524
525    /// Returns the requested filesystem isolation mode (`shared` or `worktree`).
526    #[must_use]
527    pub const fn workspace_mode(&self) -> SubagentWorkspaceMode {
528        self.workspace_mode
529    }
530
531    /// Returns the requested snapshot base when `workspace_mode` is `worktree`.
532    #[must_use]
533    pub const fn worktree_base(&self) -> SubagentWorktreeBase {
534        self.worktree_base
535    }
536
537    /// Replaces the child's allowed tool list.
538    #[must_use]
539    pub fn with_allowed_tools<I>(mut self, tools: I) -> Self
540    where
541        I: IntoIterator<Item = ToolName>,
542    {
543        self.allowed_tools = tools.into_iter().collect();
544        self.allowed_tools_explicit = true;
545        self
546    }
547
548    /// Replaces the optional display name, treating blank names as absent.
549    #[must_use]
550    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
551        self.display_name = display_name.filter(|value| !value.trim().is_empty());
552        self
553    }
554
555    /// Sets the optional role name after validating it contains safe identifier characters.
556    pub fn with_role(mut self, role: Option<String>) -> Result<Self, SubagentError> {
557        let Some(role) = role
558            .map(|value| value.trim().to_owned())
559            .filter(|value| !value.is_empty())
560        else {
561            self.role = None;
562            return Ok(self);
563        };
564        if role.len() > 64
565            || !role
566                .bytes()
567                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
568        {
569            return Err(SubagentError::InvalidRoleName { role });
570        }
571        self.role = Some(role);
572        Ok(self)
573    }
574
575    /// Sets an optional wall-clock timeout in seconds for this child task.
576    pub fn with_timeout_secs(mut self, timeout_secs: Option<u64>) -> Result<Self, SubagentError> {
577        if timeout_secs == Some(0) {
578            return Err(SubagentError::ZeroTimeoutSecs);
579        }
580        self.timeout_secs = timeout_secs;
581        Ok(self)
582    }
583
584    /// Sets validated workspace-relative `context_files` to preload before turn 1.
585    pub fn with_context_files<I, S>(mut self, entries: I) -> Result<Self, SubagentError>
586    where
587        I: IntoIterator<Item = S>,
588        S: AsRef<str>,
589    {
590        let mut parsed = Vec::new();
591        for entry in entries {
592            if parsed.len() >= MAX_CONTEXT_FILE_REFS {
593                return Err(SubagentError::TooManyContextFiles {
594                    maximum: MAX_CONTEXT_FILE_REFS,
595                });
596            }
597            parsed.push(ContextFileRef::parse(entry.as_ref())?);
598        }
599        self.context_files = parsed;
600        Ok(self)
601    }
602
603    /// Replaces the read scope after validating each path.
604    pub fn with_read_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
605    where
606        I: IntoIterator<Item = P>,
607        P: Into<PathBuf>,
608    {
609        self.read_scope = validate_scope_paths(paths)?;
610        self.read_scope_explicit = true;
611        Ok(self)
612    }
613
614    /// Replaces the write scope after validating each path.
615    pub fn with_write_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
616    where
617        I: IntoIterator<Item = P>,
618        P: Into<PathBuf>,
619    {
620        self.write_scope = validate_scope_paths(paths)?;
621        self.write_scope_explicit = true;
622        Ok(self)
623    }
624
625    /// Replaces the forbidden path scope after validating each path.
626    pub fn with_forbidden_paths<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
627    where
628        I: IntoIterator<Item = P>,
629        P: Into<PathBuf>,
630    {
631        self.forbidden_paths = validate_scope_paths(paths)?;
632        self.forbidden_paths_explicit = true;
633        Ok(self)
634    }
635
636    /// Replaces the optional expected-output instruction, treating blank text as absent.
637    #[must_use]
638    pub fn with_expected_output(mut self, expected_output: Option<String>) -> Self {
639        self.expected_output = expected_output.filter(|value| !value.trim().is_empty());
640        self
641    }
642
643    /// Replaces the optional reasoning-effort override for this child task.
644    #[must_use]
645    pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
646        self.reasoning_effort = reasoning_effort;
647        self
648    }
649
650    /// Sets the child's filesystem isolation mode (`shared` or `worktree`).
651    #[must_use]
652    pub const fn with_workspace_mode(mut self, workspace_mode: SubagentWorkspaceMode) -> Self {
653        self.workspace_mode = workspace_mode;
654        self
655    }
656
657    /// Sets the worktree snapshot base (`working_tree` or `head`).
658    #[must_use]
659    pub const fn with_worktree_base(mut self, worktree_base: SubagentWorktreeBase) -> Self {
660        self.worktree_base = worktree_base;
661        self
662    }
663}
664
665fn validate_task_text(task: &str) -> Result<(), SubagentError> {
666    if task.trim().is_empty() {
667        return Err(SubagentError::BlankTask);
668    }
669    if task.len() > MAX_TASK_BYTES {
670        return Err(SubagentError::TaskTooLong);
671    }
672    Ok(())
673}
674
675fn validate_scope_paths<I, P>(paths: I) -> Result<Vec<PathBuf>, SubagentError>
676where
677    I: IntoIterator<Item = P>,
678    P: Into<PathBuf>,
679{
680    let paths = paths
681        .into_iter()
682        .map(|path| validate_scope_path(path.into()))
683        .collect::<Result<BTreeSet<_>, _>>()?;
684    Ok(paths.into_iter().collect())
685}
686
687pub(super) fn validate_scope_path(path: PathBuf) -> Result<PathBuf, SubagentError> {
688    let path_label = path.display().to_string();
689    if !crate::workspace_scope::is_valid_workspace_scope(&path) {
690        return Err(SubagentError::InvalidScopePath { path: path_label });
691    }
692
693    Ok(path)
694}
695
696/// Rejects child batches where two shared-workspace write scopes overlap.
697///
698/// Tasks running in isolated `worktree` mode operate in distinct physical
699/// directories and do not conflict with shared or sibling worktree writers.
700pub fn validate_no_write_scope_conflicts(tasks: &[SubagentTaskSpec]) -> Result<(), SubagentError> {
701    for (first_index, first) in tasks.iter().enumerate() {
702        if first.workspace_mode() != SubagentWorkspaceMode::Shared {
703            continue;
704        }
705        for (second_offset, second) in tasks[first_index + 1..].iter().enumerate() {
706            if second.workspace_mode() != SubagentWorkspaceMode::Shared {
707                continue;
708            }
709            let second_index = first_index + 1 + second_offset;
710            for first_path in first.write_scope() {
711                for second_path in second.write_scope() {
712                    if paths_overlap(first_path, second_path) {
713                        return Err(SubagentError::OverlappingWriteScope {
714                            first_index,
715                            second_index,
716                            path: first_path.display().to_string(),
717                        });
718                    }
719                }
720            }
721        }
722    }
723    Ok(())
724}
725
726/// Returns true when two relative paths name the same path or parent/child trees.
727#[must_use]
728fn paths_overlap(first: &Path, second: &Path) -> bool {
729    crate::workspace_scope::workspace_scopes_overlap(first, second)
730}