merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
use super::handoff::{ContextFileRef, MAX_CONTEXT_FILE_REFS};
use super::protocol::{SubagentWorkspaceMode, SubagentWorktreeBase};
use merry_core::ToolName;
use merry_llm::ReasoningEffort;
use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
};
use thiserror::Error;

/// Default foreground wait budget in seconds before handing off to background.
pub const DEFAULT_FOREGROUND_WAIT_BUDGET_SECS: u64 = 120;

/// Maximum UTF-8 task text size accepted for one child task.
pub(crate) const MAX_TASK_BYTES: usize = 16 * 1024;
/// Default minimum model-turn budget for a generic child task.
pub const DEFAULT_MIN_MODEL_TURNS: u32 = 1;
/// Default bounded child loop model-turn count.
///
/// A small single-digit budget is too restrictive for a child that needs to
/// inspect files, use tools, verify the result, and report a conclusion. The
/// limit remains bounded, but is intentionally generous and configurable at
/// the runtime level.
pub const DEFAULT_MAX_MODEL_TURNS: u32 = 1024;
/// Default maximum number of concurrent child agents.
pub(crate) const DEFAULT_MAX_THREADS: usize = 6;
/// Default child delegation depth.
pub(crate) const DEFAULT_MAX_DEPTH: u8 = 1;

/// Validation errors for subagent task contracts and configuration.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum SubagentError {
    /// The delegated task text was blank.
    #[error("task must not be blank")]
    BlankTask,
    /// The delegated task text exceeded the 16 KiB UTF-8 limit.
    #[error("task is longer than the allowed maximum")]
    TaskTooLong,
    /// The delegated task has no allowed model turns.
    #[error("max_model_turns must be greater than zero")]
    ZeroMaxModelTurns,
    /// The delegated task requested more turns than the configured runtime limit.
    #[error("max_model_turns {requested} exceeds configured maximum {maximum}")]
    ExceedsConfiguredMaxModelTurns { requested: u32, maximum: u32 },
    /// The delegated task requested fewer turns than the configured minimum.
    #[error("max_model_turns {requested} is below configured minimum {minimum}")]
    BelowConfiguredMinModelTurns { requested: u32, minimum: u32 },
    /// The configured minimum is not a valid value.
    #[error("minimum max_model_turns must be greater than zero")]
    ZeroMinModelTurns,
    /// The configured minimum is greater than the configured maximum.
    #[error("minimum max_model_turns {minimum} exceeds configured maximum {maximum}")]
    MinExceedsMaxModelTurns { minimum: u32, maximum: u32 },
    /// A path scope was not a normalized workspace-relative path.
    #[error("scope path must be relative and normalized: {path}")]
    InvalidScopePath {
        /// Rejected path display string.
        path: String,
    },
    /// Two child tasks may write the same path tree.
    #[error("overlapping write scope between task {first_index} and task {second_index}: {path}")]
    OverlappingWriteScope {
        /// Index of the first conflicting task.
        first_index: usize,
        /// Index of the second conflicting task.
        second_index: usize,
        /// Conflicting write path from the first task.
        path: String,
    },
    /// A child task requested a capability outside the parent's effective envelope.
    #[error("child task capability expansion is not allowed for {field}: {value}")]
    CapabilityExpansion {
        /// Capability category that attempted to expand.
        field: &'static str,
        /// Requested capability value.
        value: String,
    },
    /// The subagent runtime was configured with no possible concurrency.
    #[error("subagent max_threads must be greater than zero")]
    ZeroMaxThreads,
    /// The subagent runtime was configured with no child depth.
    #[error("subagent max_depth must be greater than zero")]
    ZeroMaxDepth,
    /// A context file reference was invalid or outside workspace-relative rules.
    #[error("invalid context_files entry (expected relative path or path:start-end): {value}")]
    InvalidContextFileRef {
        /// Rejected context file reference.
        value: String,
    },
    /// Too many context file references were supplied for one child task.
    #[error("context_files exceeds maximum of {maximum} entries")]
    TooManyContextFiles {
        /// Configured entry cap.
        maximum: usize,
    },
    /// A child timeout_secs value was zero.
    #[error("timeout_secs must be greater than zero")]
    ZeroTimeoutSecs,
    /// A foreground wait budget value was zero.
    #[error("foreground_wait_budget_secs must be greater than zero")]
    ZeroForegroundBudgetSecs,
    /// A child max_total_tokens value was zero.
    #[error("max_total_tokens must be greater than zero")]
    ZeroMaxTotalTokens,
    /// A child role name contained invalid characters.
    #[error("invalid subagent role name: {role}")]
    InvalidRoleName {
        /// Rejected role name.
        role: String,
    },
}

/// Admission behavior when a spawn request exceeds `max_threads`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SubagentLimitBehavior {
    /// Queue excess children until an active slot frees up (default).
    #[default]
    Queue,
    /// Immediately reject excess children when `max_threads` is already full.
    Fail,
}

/// Runtime configuration for subagent delegation limits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubagentConfig {
    max_threads: usize,
    max_depth: u8,
    min_model_turns: u32,
    max_model_turns: u32,
    default_timeout_secs: Option<u64>,
    foreground_wait_budget_secs: u64,
    limit_behavior: SubagentLimitBehavior,
    max_total_tokens: Option<u64>,
}

impl SubagentConfig {
    /// Creates validated subagent limit configuration.
    pub fn new(max_threads: usize, max_depth: u8) -> Result<Self, SubagentError> {
        if max_threads == 0 {
            return Err(SubagentError::ZeroMaxThreads);
        }
        if max_depth == 0 {
            return Err(SubagentError::ZeroMaxDepth);
        }
        Ok(Self {
            max_threads,
            max_depth,
            min_model_turns: DEFAULT_MIN_MODEL_TURNS,
            max_model_turns: DEFAULT_MAX_MODEL_TURNS,
            default_timeout_secs: None,
            foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
            limit_behavior: SubagentLimitBehavior::Queue,
            max_total_tokens: None,
        })
    }

    /// Sets admission behavior when a batch exceeds `max_threads`.
    #[must_use]
    pub fn with_limit_behavior(mut self, behavior: SubagentLimitBehavior) -> Self {
        self.limit_behavior = behavior;
        self
    }

    /// Sets an optional per-child cumulative token circuit breaker.
    pub fn with_max_total_tokens(
        mut self,
        max_total_tokens: Option<u64>,
    ) -> Result<Self, SubagentError> {
        if max_total_tokens == Some(0) {
            return Err(SubagentError::ZeroMaxTotalTokens);
        }
        self.max_total_tokens = max_total_tokens;
        Ok(self)
    }

    /// Sets an optional default wall-clock timeout in seconds for child tasks.
    pub fn with_default_timeout_secs(
        mut self,
        timeout_secs: Option<u64>,
    ) -> Result<Self, SubagentError> {
        if timeout_secs == Some(0) {
            return Err(SubagentError::ZeroTimeoutSecs);
        }
        self.default_timeout_secs = timeout_secs;
        Ok(self)
    }

    /// Sets the foreground wait budget in seconds before `wait: "all" | "any"`
    /// gracefully hands off running children to the background.
    pub fn with_foreground_wait_budget_secs(
        mut self,
        budget_secs: u64,
    ) -> Result<Self, SubagentError> {
        if budget_secs == 0 {
            return Err(SubagentError::ZeroForegroundBudgetSecs);
        }
        self.foreground_wait_budget_secs = budget_secs;
        Ok(self)
    }

    /// Replaces the default model-turn budget inherited by child tasks that
    /// omit an explicit `max_model_turns` value.
    pub fn with_max_model_turns(mut self, max_model_turns: u32) -> Result<Self, SubagentError> {
        if max_model_turns == 0 {
            return Err(SubagentError::ZeroMaxModelTurns);
        }
        if self.min_model_turns > max_model_turns {
            return Err(SubagentError::MinExceedsMaxModelTurns {
                minimum: self.min_model_turns,
                maximum: max_model_turns,
            });
        }
        self.max_model_turns = max_model_turns;
        Ok(self)
    }

    /// Replaces the minimum model-turn budget accepted for explicit child tasks.
    pub fn with_min_model_turns(mut self, min_model_turns: u32) -> Result<Self, SubagentError> {
        if min_model_turns == 0 {
            return Err(SubagentError::ZeroMinModelTurns);
        }
        if min_model_turns > self.max_model_turns {
            return Err(SubagentError::MinExceedsMaxModelTurns {
                minimum: min_model_turns,
                maximum: self.max_model_turns,
            });
        }
        self.min_model_turns = min_model_turns;
        Ok(self)
    }

    /// Replaces both model-turn bounds in one validated operation.
    pub fn with_model_turn_bounds(
        mut self,
        min_model_turns: u32,
        max_model_turns: u32,
    ) -> Result<Self, SubagentError> {
        if min_model_turns == 0 {
            return Err(SubagentError::ZeroMinModelTurns);
        }
        if max_model_turns == 0 {
            return Err(SubagentError::ZeroMaxModelTurns);
        }
        if min_model_turns > max_model_turns {
            return Err(SubagentError::MinExceedsMaxModelTurns {
                minimum: min_model_turns,
                maximum: max_model_turns,
            });
        }
        self.min_model_turns = min_model_turns;
        self.max_model_turns = max_model_turns;
        Ok(self)
    }

    /// Validates one explicit child budget against this runtime configuration.
    pub fn validate_task_max_model_turns(self, requested: u32) -> Result<(), SubagentError> {
        validate_task_max_model_turns(requested, self.min_model_turns, self.max_model_turns)
    }

    /// Returns the minimum model-turn budget accepted for an explicit child task.
    #[must_use]
    pub fn min_model_turns(self) -> u32 {
        self.min_model_turns
    }

    /// Returns the maximum number of child agents allowed to run concurrently.
    #[must_use]
    pub fn max_threads(self) -> usize {
        self.max_threads
    }

    /// Returns the maximum allowed child delegation depth.
    #[must_use]
    pub fn max_depth(self) -> u8 {
        self.max_depth
    }

    /// Returns the default maximum number of model turns for one child task.
    #[must_use]
    pub fn max_model_turns(self) -> u32 {
        self.max_model_turns
    }

    /// Returns the optional default wall-clock timeout in seconds for child tasks.
    #[must_use]
    pub fn default_timeout_secs(self) -> Option<u64> {
        self.default_timeout_secs
    }

    /// Returns the foreground wait budget in seconds.
    #[must_use]
    pub fn foreground_wait_budget_secs(self) -> u64 {
        self.foreground_wait_budget_secs
    }

    /// Returns admission behavior when `max_threads` is full.
    #[must_use]
    pub fn limit_behavior(self) -> SubagentLimitBehavior {
        self.limit_behavior
    }

    /// Returns the optional per-child cumulative token circuit breaker.
    #[must_use]
    pub fn max_total_tokens(self) -> Option<u64> {
        self.max_total_tokens
    }
}

impl Default for SubagentConfig {
    fn default() -> Self {
        Self {
            max_threads: DEFAULT_MAX_THREADS,
            max_depth: DEFAULT_MAX_DEPTH,
            min_model_turns: DEFAULT_MIN_MODEL_TURNS,
            max_model_turns: DEFAULT_MAX_MODEL_TURNS,
            default_timeout_secs: None,
            foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
            limit_behavior: SubagentLimitBehavior::Queue,
            max_total_tokens: None,
        }
    }
}

/// Parent-authored specification for a bounded child agent task.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubagentTaskSpec {
    display_name: Option<String>,
    role: Option<String>,
    task: String,
    max_model_turns: u32,
    max_model_turns_explicit: bool,
    timeout_secs: Option<u64>,
    max_total_tokens: Option<u64>,
    allowed_tools: Vec<ToolName>,
    allowed_tools_explicit: bool,
    read_scope: Vec<PathBuf>,
    read_scope_explicit: bool,
    write_scope: Vec<PathBuf>,
    write_scope_explicit: bool,
    forbidden_paths: Vec<PathBuf>,
    forbidden_paths_explicit: bool,
    context_files: Vec<ContextFileRef>,
    expected_output: Option<String>,
    reasoning_effort: Option<ReasoningEffort>,
    workspace_mode: SubagentWorkspaceMode,
    worktree_base: SubagentWorktreeBase,
}

pub(crate) fn validate_task_max_model_turns(
    requested: u32,
    minimum: u32,
    maximum: u32,
) -> Result<(), SubagentError> {
    if requested == 0 {
        return Err(SubagentError::ZeroMaxModelTurns);
    }
    if requested < minimum {
        return Err(SubagentError::BelowConfiguredMinModelTurns { requested, minimum });
    }
    if requested > maximum {
        return Err(SubagentError::ExceedsConfiguredMaxModelTurns { requested, maximum });
    }
    Ok(())
}

impl SubagentTaskSpec {
    /// Creates a child task specification from validated task text and model-turn bound.
    pub fn new(task: impl Into<String>, max_model_turns: u32) -> Result<Self, SubagentError> {
        let task = task.into();
        validate_task_text(&task)?;
        if max_model_turns == 0 {
            return Err(SubagentError::ZeroMaxModelTurns);
        }
        Ok(Self {
            display_name: None,
            role: None,
            task,
            max_model_turns,
            max_model_turns_explicit: true,
            timeout_secs: None,
            max_total_tokens: None,
            allowed_tools: Vec::new(),
            allowed_tools_explicit: false,
            read_scope: Vec::new(),
            read_scope_explicit: false,
            write_scope: Vec::new(),
            write_scope_explicit: false,
            forbidden_paths: Vec::new(),
            forbidden_paths_explicit: false,
            context_files: Vec::new(),
            expected_output: None,
            reasoning_effort: None,
            workspace_mode: SubagentWorkspaceMode::Shared,
            worktree_base: SubagentWorktreeBase::WorkingTree,
        })
    }

    pub(crate) fn with_max_model_turns_unchecked(mut self, max_model_turns: u32) -> Self {
        self.max_model_turns = max_model_turns;
        self
    }

    /// Marks whether `max_model_turns` was explicitly requested by the parent
    /// (as opposed to filled from the runtime default).
    #[must_use]
    pub fn with_max_model_turns_explicit(mut self, explicit: bool) -> Self {
        self.max_model_turns_explicit = explicit;
        self
    }

    /// Returns true when the parent explicitly requested `max_model_turns`.
    #[must_use]
    pub const fn max_model_turns_is_explicit(&self) -> bool {
        self.max_model_turns_explicit
    }

    /// Returns the optional cumulative token circuit breaker for this task.
    #[must_use]
    pub const fn max_total_tokens(&self) -> Option<u64> {
        self.max_total_tokens
    }

    /// Sets an optional cumulative token circuit breaker for this task.
    #[must_use]
    pub fn with_max_total_tokens(mut self, max_total_tokens: Option<u64>) -> Self {
        self.max_total_tokens = max_total_tokens.filter(|value| *value > 0);
        self
    }

    /// Returns the optional role name requested for this child task.
    #[must_use]
    pub fn role(&self) -> Option<&str> {
        self.role.as_deref()
    }

    /// Returns the optional wall-clock timeout in seconds for this child task.
    #[must_use]
    pub const fn timeout_secs(&self) -> Option<u64> {
        self.timeout_secs
    }

    /// Returns the validated workspace-relative `context_files` references to preload.
    #[must_use]
    pub fn context_files(&self) -> &[ContextFileRef] {
        &self.context_files
    }

    /// Returns the child work description.
    ///
    /// Workspace capability belongs to the structured scope fields and the
    /// runtime-derived scope context, not this task text.
    #[must_use]
    pub fn task(&self) -> &str {
        &self.task
    }

    /// Returns the maximum number of bounded child model turns.
    #[must_use]
    pub fn max_model_turns(&self) -> u32 {
        self.max_model_turns
    }

    /// Returns the provider/tool names the child may use.
    #[must_use]
    pub fn allowed_tools(&self) -> &[ToolName] {
        &self.allowed_tools
    }

    #[must_use]
    pub fn allowed_tools_are_explicit(&self) -> bool {
        self.allowed_tools_explicit
    }

    pub(crate) fn read_scope_is_explicit(&self) -> bool {
        self.read_scope_explicit
    }

    /// Returns whether the parent explicitly supplied the write scope,
    /// including an explicit empty scope for a read-only child.
    #[must_use]
    pub fn write_scope_is_explicit(&self) -> bool {
        self.write_scope_explicit
    }

    pub(crate) fn forbidden_paths_are_explicit(&self) -> bool {
        self.forbidden_paths_explicit
    }

    /// Returns the optional compact display name.
    #[must_use]
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// Returns the workspace-relative read scope.
    #[must_use]
    pub fn read_scope(&self) -> &[PathBuf] {
        &self.read_scope
    }

    /// Returns the workspace-relative write scope.
    #[must_use]
    pub fn write_scope(&self) -> &[PathBuf] {
        &self.write_scope
    }

    /// Returns workspace-relative paths the child must not access.
    #[must_use]
    pub fn forbidden_paths(&self) -> &[PathBuf] {
        &self.forbidden_paths
    }

    /// Returns the optional expected-output instruction.
    #[must_use]
    pub fn expected_output(&self) -> Option<&str> {
        self.expected_output.as_deref()
    }

    /// Returns the optional reasoning-effort override for this child task.
    #[must_use]
    pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
        self.reasoning_effort.as_ref()
    }

    /// Returns the requested filesystem isolation mode (`shared` or `worktree`).
    #[must_use]
    pub const fn workspace_mode(&self) -> SubagentWorkspaceMode {
        self.workspace_mode
    }

    /// Returns the requested snapshot base when `workspace_mode` is `worktree`.
    #[must_use]
    pub const fn worktree_base(&self) -> SubagentWorktreeBase {
        self.worktree_base
    }

    /// Replaces the child's allowed tool list.
    #[must_use]
    pub fn with_allowed_tools<I>(mut self, tools: I) -> Self
    where
        I: IntoIterator<Item = ToolName>,
    {
        self.allowed_tools = tools.into_iter().collect();
        self.allowed_tools_explicit = true;
        self
    }

    /// Replaces the optional display name, treating blank names as absent.
    #[must_use]
    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
        self.display_name = display_name.filter(|value| !value.trim().is_empty());
        self
    }

    /// Sets the optional role name after validating it contains safe identifier characters.
    pub fn with_role(mut self, role: Option<String>) -> Result<Self, SubagentError> {
        let Some(role) = role
            .map(|value| value.trim().to_owned())
            .filter(|value| !value.is_empty())
        else {
            self.role = None;
            return Ok(self);
        };
        if role.len() > 64
            || !role
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
        {
            return Err(SubagentError::InvalidRoleName { role });
        }
        self.role = Some(role);
        Ok(self)
    }

    /// Sets an optional wall-clock timeout in seconds for this child task.
    pub fn with_timeout_secs(mut self, timeout_secs: Option<u64>) -> Result<Self, SubagentError> {
        if timeout_secs == Some(0) {
            return Err(SubagentError::ZeroTimeoutSecs);
        }
        self.timeout_secs = timeout_secs;
        Ok(self)
    }

    /// Sets validated workspace-relative `context_files` to preload before turn 1.
    pub fn with_context_files<I, S>(mut self, entries: I) -> Result<Self, SubagentError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut parsed = Vec::new();
        for entry in entries {
            if parsed.len() >= MAX_CONTEXT_FILE_REFS {
                return Err(SubagentError::TooManyContextFiles {
                    maximum: MAX_CONTEXT_FILE_REFS,
                });
            }
            parsed.push(ContextFileRef::parse(entry.as_ref())?);
        }
        self.context_files = parsed;
        Ok(self)
    }

    /// Replaces the read scope after validating each path.
    pub fn with_read_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.read_scope = validate_scope_paths(paths)?;
        self.read_scope_explicit = true;
        Ok(self)
    }

    /// Replaces the write scope after validating each path.
    pub fn with_write_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.write_scope = validate_scope_paths(paths)?;
        self.write_scope_explicit = true;
        Ok(self)
    }

    /// Replaces the forbidden path scope after validating each path.
    pub fn with_forbidden_paths<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.forbidden_paths = validate_scope_paths(paths)?;
        self.forbidden_paths_explicit = true;
        Ok(self)
    }

    /// Replaces the optional expected-output instruction, treating blank text as absent.
    #[must_use]
    pub fn with_expected_output(mut self, expected_output: Option<String>) -> Self {
        self.expected_output = expected_output.filter(|value| !value.trim().is_empty());
        self
    }

    /// Replaces the optional reasoning-effort override for this child task.
    #[must_use]
    pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
        self.reasoning_effort = reasoning_effort;
        self
    }

    /// Sets the child's filesystem isolation mode (`shared` or `worktree`).
    #[must_use]
    pub const fn with_workspace_mode(mut self, workspace_mode: SubagentWorkspaceMode) -> Self {
        self.workspace_mode = workspace_mode;
        self
    }

    /// Sets the worktree snapshot base (`working_tree` or `head`).
    #[must_use]
    pub const fn with_worktree_base(mut self, worktree_base: SubagentWorktreeBase) -> Self {
        self.worktree_base = worktree_base;
        self
    }
}

fn validate_task_text(task: &str) -> Result<(), SubagentError> {
    if task.trim().is_empty() {
        return Err(SubagentError::BlankTask);
    }
    if task.len() > MAX_TASK_BYTES {
        return Err(SubagentError::TaskTooLong);
    }
    Ok(())
}

fn validate_scope_paths<I, P>(paths: I) -> Result<Vec<PathBuf>, SubagentError>
where
    I: IntoIterator<Item = P>,
    P: Into<PathBuf>,
{
    let paths = paths
        .into_iter()
        .map(|path| validate_scope_path(path.into()))
        .collect::<Result<BTreeSet<_>, _>>()?;
    Ok(paths.into_iter().collect())
}

pub(super) fn validate_scope_path(path: PathBuf) -> Result<PathBuf, SubagentError> {
    let path_label = path.display().to_string();
    if !crate::workspace_scope::is_valid_workspace_scope(&path) {
        return Err(SubagentError::InvalidScopePath { path: path_label });
    }

    Ok(path)
}

/// Rejects child batches where two shared-workspace write scopes overlap.
///
/// Tasks running in isolated `worktree` mode operate in distinct physical
/// directories and do not conflict with shared or sibling worktree writers.
pub fn validate_no_write_scope_conflicts(tasks: &[SubagentTaskSpec]) -> Result<(), SubagentError> {
    for (first_index, first) in tasks.iter().enumerate() {
        if first.workspace_mode() != SubagentWorkspaceMode::Shared {
            continue;
        }
        for (second_offset, second) in tasks[first_index + 1..].iter().enumerate() {
            if second.workspace_mode() != SubagentWorkspaceMode::Shared {
                continue;
            }
            let second_index = first_index + 1 + second_offset;
            for first_path in first.write_scope() {
                for second_path in second.write_scope() {
                    if paths_overlap(first_path, second_path) {
                        return Err(SubagentError::OverlappingWriteScope {
                            first_index,
                            second_index,
                            path: first_path.display().to_string(),
                        });
                    }
                }
            }
        }
    }
    Ok(())
}

/// Returns true when two relative paths name the same path or parent/child trees.
#[must_use]
fn paths_overlap(first: &Path, second: &Path) -> bool {
    crate::workspace_scope::workspace_scopes_overlap(first, second)
}