返回 CodeWhale
worker_profile.rs
根目录 / crates / agent-contract / src / worker_profile.rs
1 //! Worker runtime profile — the per-role capability contract for a CodeWhale
2 //! worker (#3217, #3211, #3213, and the child-permission-intersection issues
3 //! #414 / #426 / #1186).
4 //!
5 //! This is the **Workflow substrate**: every detached worker — whether launched
6 //! as an `agent` sub-agent or a Fleet worker — should run under a profile
7 //! that bounds what it may do (permissions, shell access, tool scope, model
8 //! route, recursion budget, foreground/background). A child profile is always
9 //! **derived** from its parent and can never escalate beyond it.
10 //!
11 //! Scope: this module defines the contract and the parent→child derivation with
12 //! tests. `agent` and Fleet worker records now build and persist these
13 //! profiles so parent-visible worker projections have a single capability
14 //! contract. Runtime enforcement of every declared field remains incremental
15 //! follow-up work (#3217).
16
17 use crate::role::FleetRole;
18 use serde::{Deserialize, Serialize};
19
20 /// Coarse capability classes a worker may exercise, beyond read access (reads
21 /// are always permitted). A child may only ever hold a *subset* of its parent's
22 /// capabilities.
23 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
24 pub struct PermissionSet {
25 /// May modify the workspace (`write_file` / `edit_file` / `apply_patch`).
26 pub write: bool,
27 /// May use network-capable tools (web search/fetch, networked MCP servers).
28 pub network: bool,
29 }
30
31 impl PermissionSet {
32 /// Full capabilities (write + network).
33 pub const fn full() -> Self {
34 Self {
35 write: true,
36 network: true,
37 }
38 }
39
40 /// Read-only: no write, no network.
41 pub const fn read_only() -> Self {
42 Self {
43 write: false,
44 network: false,
45 }
46 }
47
48 /// Read-only inspection: read-only on the workspace, but network-capable.
49 ///
50 /// The read-only investigator posture (scout/reviewer): it must not
51 /// mutate the workspace, but real read-only inspection needs
52 /// `git`/`gh`/web reach — the old `read_only()` default left such lanes
53 /// with no way to run any command or reach any remote, which made default
54 /// scout lanes useless for the inspection they exist for.
55 pub const fn read_only_with_network() -> Self {
56 Self {
57 write: false,
58 network: true,
59 }
60 }
61
62 /// Intersection: a capability is granted only if **both** sets grant it.
63 /// This is the core non-escalation primitive — `parent.intersect(child)`
64 /// can never produce a capability the parent lacks.
65 #[must_use]
66 pub fn intersect(self, other: Self) -> Self {
67 Self {
68 write: self.write && other.write,
69 network: self.network && other.network,
70 }
71 }
72 }
73
74 /// Shell access policy — the replacement for the legacy per-worker shell boolean
75 /// (#3217). Ordered from most to least restrictive so `min` yields the safer of
76 /// two policies.
77 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
78 #[serde(rename_all = "snake_case")]
79 pub enum ShellPolicy {
80 /// No shell access.
81 None,
82 /// Read-only / non-mutating commands only (the policy enforcement lives in
83 /// the exec/sandbox layer; this is the declared intent).
84 ReadOnly,
85 /// Full shell access.
86 Full,
87 }
88
89 impl ShellPolicy {
90 /// Convert the legacy top-level shell opt-in into the typed shell policy.
91 #[must_use]
92 pub const fn from_legacy_allow_shell(allow_shell: bool) -> Self {
93 if allow_shell { Self::Full } else { Self::None }
94 }
95
96 /// Whether any shell tools should be exposed under this policy.
97 #[must_use]
98 pub const fn allows_shell(self) -> bool {
99 !matches!(self, Self::None)
100 }
101
102 /// The more restrictive (safer) of two policies. A child can never exceed
103 /// its parent's shell policy.
104 #[must_use]
105 pub fn min_with(self, other: Self) -> Self {
106 if self <= other { self } else { other }
107 }
108 }
109
110 /// Which tools a worker may call. Mirrors the existing `AgentWorkerToolProfile`
111 /// (`Inherited` / `Explicit`) so the two can be reconciled when this is wired in.
112 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
113 #[serde(rename_all = "snake_case")]
114 pub enum ToolScope {
115 /// Inherit the parent's tool surface.
116 Inherit,
117 /// Only the explicitly listed tool names.
118 Explicit(Vec<String>),
119 }
120
121 /// File-system authority axis of a [`ChildGrant`]. Ordered least to most
122 /// permissive so `Ord::min` is the non-escalation primitive.
123 ///
124 /// `None` is not "no writes" — it is "no file access of any kind", which is
125 /// what a child with an empty tool surface experiences. `Read` permits
126 /// evidence collection only; `Write` permits mutation inside the session's
127 /// write policy (workspace boundary, exact-file claims, approval posture).
128 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
129 pub enum FileGrant {
130 None,
131 Read,
132 Write,
133 }
134
135 /// Process authority axis of a [`ChildGrant`]. Ordered least to most
136 /// permissive so `Ord::min` is the non-escalation primitive.
137 ///
138 /// `Inspect` is the read-only shell: canonical `bash` only, and only calls
139 /// the agent read-only classifier proves mutation-free (the explore /
140 /// reviewer / planner posture). `Verify` is the bounded built-in verification
141 /// surface — default workspace checks, pure test selection, and bounded Git
142 /// fetch/merge-tree — with no shell grammar (the test/verifier posture). A
143 /// child asking for a surface its parent does not hold degrades to the
144 /// narrower side (`Inspect ∩ Verify = Inspect`): bounded inspection is a
145 /// subset of bounded process authority, never a widening.
146 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
147 pub enum ShellGrant {
148 None,
149 Inspect,
150 Verify,
151 Full,
152 }
153
154 /// The named tool surface a grant exposes, before the explicit scope narrows
155 /// it. This is the role-preset axis of `tools` — distinct from
156 /// [`ChildGrant::scope`], which is the caller's own allowlist.
157 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
158 pub enum ToolSurface {
159 /// Every registered tool the grant's other axes admit.
160 Inherited,
161 /// The read-only evidence surface — `readonly_evidence_tool` plus
162 /// `agent` (delegation). The explore / reviewer preset.
163 Evidence,
164 }
165
166 /// The single authority object a delegated child runs under (#5633).
167 ///
168 /// Roles are *presets over this object*, never a second permission system:
169 /// [`ChildGrant::for_role`] gives the widest grant a role can hold, and
170 /// [`ChildGrant::resolve`] intersects it with the effective parent-derived
171 /// profile and the caller's explicit scope. One projection serves every
172 /// consumer — the child's tool catalog, its dispatch refusals, and its
173 /// capability envelope all read the same fields, so a tool that is visible
174 /// is callable and a tool that is denied never appears.
175 ///
176 /// This is deliberately a *projection*, not a second persisted record:
177 /// [`WorkerRuntimeProfile`] remains the wire/persistence shape and
178 /// `ChildAuthority` /
179 /// `ToolAuthorityEnvelope`
180 /// remain the transports that carry the same authority across the durable
181 /// Fleet and `codewhale exec` subprocess boundaries. What this object retires
182 /// is the *semantic* duplication — posture sentinel entries read back off a
183 /// deny list, and role-keyed re-derivation inside the registry.
184 #[derive(Debug, Clone, PartialEq, Eq)]
185 pub struct ChildGrant {
186 /// File-system authority.
187 pub files: FileGrant,
188 /// Process authority.
189 pub shell: ShellGrant,
190 /// May reach the network through any surface.
191 pub network: bool,
192 /// May drive the operator's machine (computer-use / desktop tools).
193 /// Children never hold this today; the field is declared so every
194 /// surface reports the same denial rather than implying a grant.
195 pub desktop: bool,
196 /// The named tool surface before explicit scope narrowing.
197 pub surface: ToolSurface,
198 /// The caller's explicit allowlist, already intersected with the parent's
199 /// scope at spawn. `Some(vec![])` — the `tools = false` posture — permits
200 /// nothing at all.
201 pub scope: Option<Vec<String>>,
202 /// May delegate children of its own (remaining spawn depth).
203 pub spawn: bool,
204 }
205
206 impl ChildGrant {
207 /// The widest grant a role can ever hold — the role preset.
208 ///
209 /// This is the role-to-authority table, expressed once: everything else
210 /// only narrows it. Read-only roles stay read-only on the workspace by
211 /// intent; network reach is a read, and a worker cut off from it for no
212 /// role reason cannot do its job. `desktop` is never in any preset.
213 #[must_use]
214 pub fn for_role(role: &FleetRole) -> Self {
215 let (files, shell, surface) = match role {
216 // Read-only investigators: evidence collection only, with the
217 // classifier-bounded inspection shell.
218 FleetRole::Scout | FleetRole::Reviewer => {
219 (FileGrant::Read, ShellGrant::Inspect, ToolSurface::Evidence)
220 }
221 // Planner: analysis only, same bounded shell, broader read
222 // surface — a plan may consult any read the session offers.
223 FleetRole::Planner => (FileGrant::Read, ShellGrant::Inspect, ToolSurface::Inherited),
224 // Counsel only: reads to ground advice, never acts — no process
225 // surface at all (#4752).
226 FleetRole::Consultant => (FileGrant::Read, ShellGrant::None, ToolSurface::Inherited),
227 // Verifier: bounded workspace checks and bounded Git reference
228 // reads, no shell grammar.
229 FleetRole::Verifier => (FileGrant::Read, ShellGrant::Verify, ToolSurface::Inherited),
230 // Doers, and Custom: the preset asks for everything; the parent
231 // profile and explicit scope do all the narrowing.
232 FleetRole::Builder | FleetRole::Worker | FleetRole::Custom => {
233 (FileGrant::Write, ShellGrant::Full, ToolSurface::Inherited)
234 }
235 };
236 Self {
237 files,
238 shell,
239 network: true,
240 desktop: false,
241 surface,
242 scope: None,
243 spawn: true,
244 }
245 }
246
247 /// Resolve the grant a child actually runs under: the role preset
248 /// intersected with the effective parent-derived profile, carrying the
249 /// caller's explicit scope and the remaining delegation depth.
250 ///
251 /// Every field takes the more restrictive side, so the result can never
252 /// name authority the parent lacked. This is the in-process counterpart
253 /// of [`crate::role::ChildAuthority::clamp`].
254 #[must_use]
255 pub fn resolve(
256 role: &FleetRole,
257 profile: &WorkerRuntimeProfile,
258 scope: Option<Vec<String>>,
259 can_spawn: bool,
260 ) -> Self {
261 let preset = Self::for_role(role);
262 let profile_shell = match profile.shell {
263 ShellPolicy::None => ShellGrant::None,
264 ShellPolicy::ReadOnly => ShellGrant::Inspect,
265 ShellPolicy::Full => ShellGrant::Full,
266 };
267 // The posture deny lists are the transport the ceiling clamps install;
268 // the grant folds their sentinels into the semantic axes so the two
269 // can never disagree. `fetch_url` stands for "no network"; `run_tests`
270 // stands for "no shell authority at all" — it removes process-start
271 // grants (`Verify`/`Full` → `None`) while `Inspect` survives, because
272 // classifier-bounded evidence reads were never shell authority.
273 // `exec_shell` (raw shell gone) is deliberately *not* folded: a
274 // write-denied verifier installs it while keeping shell authority.
275 let denied = |name: &str| {
276 codewhale_execpolicy::tool_rules::tool_denied(
277 Some(profile.denied_tools.as_slice()),
278 name,
279 )
280 };
281 let resolved_shell = preset.shell.min(profile_shell);
282 let shell = if denied(crate::role::SHELL_AUTHORITY_SENTINEL) {
283 match resolved_shell {
284 ShellGrant::Inspect => ShellGrant::Inspect,
285 _ => ShellGrant::None,
286 }
287 } else {
288 resolved_shell
289 };
290 let no_tools = matches!(scope.as_deref(), Some([]));
291 Self {
292 files: if no_tools {
293 FileGrant::None
294 } else {
295 preset.files.min(if profile.permissions.write {
296 FileGrant::Write
297 } else {
298 FileGrant::Read
299 })
300 },
301 shell,
302 network: preset.network
303 && profile.permissions.network
304 && !denied(crate::role::NETWORK_DENIAL_SENTINEL),
305 desktop: false,
306 surface: preset.surface,
307 scope,
308 spawn: can_spawn,
309 }
310 }
311
312 /// The transport shell policy the registered surface and `BashTool`
313 /// enforce for this grant.
314 ///
315 /// `Verify` maps to `ShellPolicy::Full`: the bounded verification surface
316 /// is a process-start authority the profile transports as Full, while the
317 /// grant itself — not the transport — decides that raw shell names never
318 /// reach the catalog. Keeping the transport at Full also preserves the
319 /// ceiling a verifier may pass to its own children.
320 #[must_use]
321 pub const fn shell_policy(&self) -> ShellPolicy {
322 match self.shell {
323 ShellGrant::None => ShellPolicy::None,
324 ShellGrant::Inspect => ShellPolicy::ReadOnly,
325 ShellGrant::Verify | ShellGrant::Full => ShellPolicy::Full,
326 }
327 }
328 }
329
330 /// How a worker's model is selected. New model-facing spawns default to the
331 /// parent/session model; a child only takes a smaller/faster family sibling when
332 /// the parent explicitly asks for that route.
333 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
334 #[serde(rename_all = "snake_case")]
335 pub enum ModelRoute {
336 /// Same model as the parent / session.
337 Inherit,
338 /// Explicitly request a smaller/faster same-family sibling when known.
339 Faster,
340 /// Legacy persisted route from the old hidden auto-router. New spawns do
341 /// not emit this; runtime treats it like `Faster` for compatibility.
342 Auto,
343 /// An explicit model id, validated against the active provider at spawn time.
344 Fixed(String),
345 }
346
347 /// The capability contract a single worker runs under.
348 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
349 pub struct WorkerRuntimeProfile {
350 pub role: FleetRole,
351 pub permissions: PermissionSet,
352 pub shell: ShellPolicy,
353 pub tools: ToolScope,
354 pub model: ModelRoute,
355 /// Explicit provider override; `None` inherits the parent/session provider.
356 pub provider: Option<String>,
357 /// Explicit reasoning/thinking tier; `None` inherits the parent/session tier.
358 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub reasoning_effort: Option<String>,
360 /// Tool deny-list inherited from the parent session's `--disallowed-tools`
361 /// (#4042). Deny always wins over allow, even over the explicit allowlist
362 /// and the role posture. Entries support wildcard matching: an exact name
363 /// (`exec_shell`) or a `prefix*` glob (`mcp_*`), compared case-insensitively.
364 ///
365 /// A child can only ever *add* entries — `derive_child()` takes the union of
366 /// the parent's and the child's deny lists, so a descendant can never drop a
367 /// restriction an ancestor imposed. The legacy `inherit_disallowed_tools:
368 /// false` input remains accepted but cannot remove this ceiling.
369 #[serde(default, skip_serializing_if = "Vec::is_empty")]
370 pub denied_tools: Vec<String>,
371 /// Absolute recursion ceiling. Older profiles stored a remaining allowance;
372 /// interpreting that smaller value as absolute fails closed on recovery.
373 /// `spawn_depth` records this worker's position on the same axis.
374 pub max_spawn_depth: u32,
375 #[serde(default)]
376 pub spawn_depth: u32,
377 /// Whole-run wall time, including queued, model and tool work.
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub wall_time_secs: Option<u64>,
380 /// Persisted wall-clock deadline; continuations cannot restart the clock.
381 #[serde(default, skip_serializing_if = "Option::is_none")]
382 pub wall_deadline_ms: Option<u64>,
383 /// Optional model-turn cap. Zero means unbounded, matching the normal
384 /// Codex and GrokBuild agent loop; an operator may still set a cap.
385 #[serde(default = "default_general_max_steps")]
386 pub max_steps: u32,
387 /// Whether the worker runs detached (background) or inline (foreground).
388 pub background: bool,
389 }
390
391 impl WorkerRuntimeProfile {
392 pub const EXPLORE_MAX_STEPS: u32 = 0;
393 pub const READ_ONLY_MAX_STEPS: u32 = 0;
394 pub const GENERAL_MAX_STEPS: u32 = 0;
395
396 /// Return the default model-turn cap for this role (zero = unbounded).
397 #[must_use]
398 pub const fn default_max_steps(role: FleetRole) -> u32 {
399 match role {
400 FleetRole::Scout => Self::EXPLORE_MAX_STEPS,
401 FleetRole::Reviewer
402 | FleetRole::Planner
403 | FleetRole::Verifier
404 | FleetRole::Consultant => Self::READ_ONLY_MAX_STEPS,
405 FleetRole::Builder | FleetRole::Worker | FleetRole::Custom => Self::GENERAL_MAX_STEPS,
406 }
407 }
408
409 /// The default profile for a role — the per-role posture. Mirrors the role
410 /// stances documented in `docs/SUBAGENTS.md` (explore/plan/review are
411 /// read-only; verifier runs tests; implementer/general write).
412 #[must_use]
413 pub fn for_role(role: FleetRole) -> Self {
414 // A role's default is what the role *intends*, expressed as the widest
415 // posture the role can be given; the parent's effective posture is the
416 // ceiling (`derive_child` intersects, never widens). Read-only roles
417 // stay read-only on the workspace by intent. Nothing else is taken
418 // away by default: network reach is a read, and a worker cut off from
419 // the network or from shell for no role reason cannot do its job.
420 let (permissions, shell) = match role {
421 // Read-only investigators: no workspace writes, but network reach
422 // and the bounded verification surface so a scout/reviewer lane
423 // can run git/gh/web inspection. Raw shell stays denied by the
424 // registry clamp (read-only classifier), so this widens capability
425 // without widening mutation authority.
426 FleetRole::Scout | FleetRole::Reviewer => {
427 (PermissionSet::read_only_with_network(), ShellPolicy::Full)
428 }
429 // Planner: analysis only. Reads the workspace and the web and may
430 // run read-only shell probes (`git log`, `rg`) under the read-only
431 // classifier; never mutates.
432 FleetRole::Planner => (
433 PermissionSet::read_only_with_network(),
434 ShellPolicy::ReadOnly,
435 ),
436 // Consultant: counsel only. Reads (workspace and web) to ground
437 // its advice; never acts on the workspace, so no shell (#4752).
438 FleetRole::Consultant => (PermissionSet::read_only_with_network(), ShellPolicy::None),
439 // Verifier: doesn't modify code, but runs the bounded built-in
440 // verification surface (test/check selections) under a full shell
441 // ceiling clamped by ChildAuthority: writes are denied and
442 // unbounded shell forms are refused (#5186). The old wording
443 // promised "runs the test suite" without saying the surface is
444 // bounded. See the roster description and VERIFIER_AGENT_INTRO.
445 FleetRole::Verifier => (PermissionSet::read_only_with_network(), ShellPolicy::Full),
446 // Doers, and Custom: inherit the parent's effective posture. A
447 // custom worker is narrowed by its explicit tool list and by the
448 // spawning call, not by a silent locked-down default.
449 FleetRole::Builder | FleetRole::Worker | FleetRole::Custom => {
450 (PermissionSet::full(), ShellPolicy::Full)
451 }
452 };
453 Self {
454 role: role.clone(),
455 permissions,
456 shell,
457 tools: ToolScope::Inherit,
458 model: ModelRoute::Inherit,
459 provider: None,
460 // A Consultant is asked for judgement, so it defaults to the highest
461 // reasoning tier rather than inheriting the session's (#4752).
462 // Still only a default: an explicit spawn-time or profile value
463 // wins via `derive_child`, same as every other role.
464 reasoning_effort: matches!(role, FleetRole::Consultant).then(|| "high".to_string()),
465 denied_tools: Vec::new(),
466 max_spawn_depth: codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH,
467 spawn_depth: 0,
468 wall_time_secs: None,
469 wall_deadline_ms: None,
470 max_steps: Self::default_max_steps(role.clone()),
471 background: true,
472 }
473 }
474
475 /// Derive a child profile from this (parent) profile and a `requested` child
476 /// profile. The result is the **intersection** of the two — it can never
477 /// grant the child something the parent lacks (#414 / #426 / #1186):
478 ///
479 /// - permissions are AND-ed,
480 /// - shell takes the more restrictive policy,
481 /// - an explicit parent tool set bounds the child's tool set,
482 /// - the spawn-depth budget decrements by one level and clamps to the ceiling,
483 /// - the tool deny-list is the **union** of the two — a child may add
484 /// restrictions but never drop one an ancestor imposed (#4042).
485 ///
486 /// The child keeps its own requested role, model route, and
487 /// foreground/background preference (these don't grant capability), but its
488 /// provider falls back to the parent's when unset.
489 #[must_use]
490 pub fn derive_child(&self, requested: &WorkerRuntimeProfile) -> WorkerRuntimeProfile {
491 let permissions = self.permissions.intersect(requested.permissions);
492 let shell = self.shell.min_with(requested.shell);
493 // Deny-lists union: a child can never drop a restriction an ancestor
494 // imposed. Wildcard entries are merged verbatim (no expansion).
495 let mut denied_tools = self.denied_tools.clone();
496 for rule in &requested.denied_tools {
497 if !denied_tools.contains(rule) {
498 denied_tools.push(rule.clone());
499 }
500 }
501 let tools = match (&self.tools, &requested.tools) {
502 // Parent restricts to a set → the child can only narrow within it.
503 (ToolScope::Explicit(parent), ToolScope::Explicit(child)) => ToolScope::Explicit(
504 child
505 .iter()
506 .filter(|name| parent.contains(name))
507 .cloned()
508 .collect(),
509 ),
510 (ToolScope::Explicit(parent), ToolScope::Inherit) => {
511 ToolScope::Explicit(parent.clone())
512 }
513 // Parent inherits the full surface → the child's request stands.
514 (ToolScope::Inherit, child) => child.clone(),
515 };
516 // Depth stays absolute; only the current position increments. Every
517 // authority projection compares the position against this same ceiling.
518 let max_spawn_depth = requested.max_spawn_depth.min(self.max_spawn_depth);
519 WorkerRuntimeProfile {
520 role: requested.role.clone(),
521 permissions,
522 shell,
523 tools,
524 model: requested.model.clone(),
525 provider: requested.provider.clone().or_else(|| self.provider.clone()),
526 reasoning_effort: requested
527 .reasoning_effort
528 .clone()
529 .or_else(|| self.reasoning_effort.clone()),
530 denied_tools,
531 max_spawn_depth,
532 spawn_depth: self.spawn_depth.saturating_add(1),
533 wall_time_secs: narrow_optional_limit(self.wall_time_secs, requested.wall_time_secs),
534 wall_deadline_ms: narrow_optional_limit(
535 self.wall_deadline_ms,
536 requested.wall_deadline_ms,
537 ),
538 max_steps: narrow_model_steps(self.max_steps, requested.max_steps),
539 background: requested.background,
540 }
541 }
542
543 /// Remaining generations, projected from the one absolute ceiling.
544 #[must_use]
545 pub fn remaining_spawn_depth(&self) -> u32 {
546 self.max_spawn_depth.saturating_sub(self.spawn_depth)
547 }
548
549 #[must_use]
550 pub fn can_spawn_child(&self) -> bool {
551 self.spawn_depth < self.max_spawn_depth
552 }
553 }
554
555 /// Omission inherits; neither a child request nor a replay can widen a cap.
556 pub fn narrow_optional_limit<T: Ord>(inherited: Option<T>, requested: Option<T>) -> Option<T> {
557 match (inherited, requested) {
558 (Some(inherited), Some(requested)) => Some(inherited.min(requested)),
559 (inherited, requested) => inherited.or(requested),
560 }
561 }
562
563 /// Zero is the operator/internal unbounded sentinel, never a widening request.
564 pub fn narrow_model_steps(inherited: u32, requested: u32) -> u32 {
565 narrow_optional_limit(
566 (inherited > 0).then_some(inherited),
567 (requested > 0).then_some(requested),
568 )
569 .unwrap_or(0)
570 }
571
572 const fn default_general_max_steps() -> u32 {
573 WorkerRuntimeProfile::GENERAL_MAX_STEPS
574 }
575
576 impl Default for WorkerRuntimeProfile {
577 fn default() -> Self {
578 Self::for_role(FleetRole::Worker)
579 }
580 }
581
582 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
583 pub struct WorkerWriteScope {
584 #[serde(default, skip_serializing_if = "Vec::is_empty")]
585 pub writable_roots: Vec<String>,
586 #[serde(default, skip_serializing_if = "Vec::is_empty")]
587 pub writable_files: Vec<String>,
588 #[serde(default, skip_serializing_if = "Vec::is_empty")]
589 pub coordination_contracts: Vec<String>,
590 }
591
592 impl WorkerWriteScope {
593 #[must_use]
594 pub fn read_only() -> Self {
595 Self::default()
596 }
597
598 #[must_use]
599 pub fn is_read_only(&self) -> bool {
600 self.writable_roots.is_empty()
601 && self.writable_files.is_empty()
602 && self.coordination_contracts.is_empty()
603 }
604 }
605
606 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
607 pub struct WorkerPoolAdmission {
608 pub provider_id: String,
609 pub wire_model_id: String,
610 pub pool_mode: String,
611 pub pool_revision: u64,
612 }
613
614 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
615 pub struct ChildActivationIdentity {
616 pub owner_session_id: String,
617 pub session_boot_id: String,
618 pub public_child_id: String,
619 pub child_id: String,
620 pub run_id: String,
621 pub generation: u32,
622 pub initial_submission_id: String,
623 }
624
625 #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
626 #[serde(rename_all = "snake_case")]
627 pub enum ChildActivationDelivery {
628 #[default]
629 Parent,
630 Caller,
631 }
632
633 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
634 pub struct FrozenChildConfiguration {
635 pub persona: Option<String>,
636 pub denied_tools: Vec<String>,
637 pub delivery: ChildActivationDelivery,
638 }
639
640 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
641 pub struct ChildInitialAdmission {
642 pub submission_id: String,
643 pub turn_id: String,
644 pub message_index: usize,
645 pub prefix_sha256: String,
646 }
647
648 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
649 #[serde(rename_all = "kebab-case")]
650 pub enum ChildActivationStopReason {
651 Completed,
652 Aborted,
653 Error,
654 MaxTokens,
655 Refusal,
656 }
657
658 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
659 pub struct ChildActivationOutput {
660 pub transcript_message_index: usize,
661 pub content_sha256: String,
662 }
663
664 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
665 pub struct ChildActivationManifest {
666 pub identity: ChildActivationIdentity,
667 pub configuration: Option<FrozenChildConfiguration>,
668 pub admission: Option<ChildInitialAdmission>,
669 #[serde(default)]
670 pub output_captured: bool,
671 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub stop_reason: Option<ChildActivationStopReason>,
673 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub output: Option<ChildActivationOutput>,
675 }
676
677 /// Unified pre-launch manifest for a child agent (#414).
678 ///
679 /// Everything needed to provision, launch, and resume a child — prompt, role,
680 /// model, tools, permissions, workspace boundary, budget, and identity — comes
681 /// from this single persisted record. No field is derived ad-hoc at launch time.
682 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
683 pub struct ChildLaunchManifest {
684 #[serde(default, skip_serializing_if = "Option::is_none")]
685 pub activation: Option<ChildActivationManifest>,
686 pub owner_session: String,
687 pub child_id: String,
688 pub profile: WorkerRuntimeProfile,
689 pub prompt: String,
690 pub cwd: Option<String>,
691 pub worktree: bool,
692 pub writable_roots: Vec<String>,
693 #[serde(default)]
694 pub writable_files: Vec<String>,
695 #[serde(default)]
696 pub coordination_contracts: Vec<String>,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
698 pub expected_artifact: Option<String>,
699 #[serde(default, skip_serializing_if = "Vec::is_empty")]
700 pub deliverables: Vec<String>,
701 pub resume_identity: Option<String>,
702 #[serde(default)]
703 pub generation: u32,
704 /// Agent id this child was resumed from via `resume_from`, if any.
705 /// Carries provenance across continuation chains so receipts can trace
706 /// the lineage without inspecting the transcript.
707 #[serde(default, skip_serializing_if = "Option::is_none")]
708 pub resume_from_agent_id: Option<String>,
709 }
710
711 #[cfg(test)]
712 mod tests {
713 use super::*;
714
715 #[test]
716 fn permission_intersection_never_escalates() {
717 let parent = PermissionSet::read_only();
718 let greedy_child = PermissionSet::full();
719 // Even though the child asks for everything, the read-only parent wins.
720 let got = parent.intersect(greedy_child);
721 assert_eq!(got, PermissionSet::read_only());
722 }
723
724 #[test]
725 fn shell_policy_min_takes_the_safer() {
726 assert_eq!(
727 ShellPolicy::ReadOnly.min_with(ShellPolicy::Full),
728 ShellPolicy::ReadOnly
729 );
730 assert_eq!(
731 ShellPolicy::None.min_with(ShellPolicy::ReadOnly),
732 ShellPolicy::None
733 );
734 assert_eq!(
735 ShellPolicy::Full.min_with(ShellPolicy::Full),
736 ShellPolicy::Full
737 );
738 }
739
740 #[test]
741 fn for_role_postures_match_role_stances() {
742 let explore = WorkerRuntimeProfile::for_role(FleetRole::Scout);
743 assert!(!explore.permissions.write, "explore must not write");
744 assert!(
745 explore.permissions.network,
746 "explore/read-only inspection lanes keep network reach"
747 );
748 assert_eq!(
749 explore.shell,
750 ShellPolicy::Full,
751 "explore/read-only inspection lanes hold shell authority so the bounded verification surface survives the clamp (raw shell still requires write)"
752 );
753 assert_eq!(
754 explore.model,
755 ModelRoute::Inherit,
756 "explore should not silently downgrade the child model"
757 );
758
759 let implementer = WorkerRuntimeProfile::for_role(FleetRole::Builder);
760 assert!(implementer.permissions.write, "implementer writes");
761 assert_eq!(implementer.shell, ShellPolicy::Full);
762
763 let verifier = WorkerRuntimeProfile::for_role(FleetRole::Verifier);
764 assert!(
765 !verifier.permissions.write,
766 "verifier reports, does not patch"
767 );
768 assert_eq!(
769 verifier.shell,
770 ShellPolicy::Full,
771 "verifier holds shell authority for the bounded verification surface (unbounded forms are refused by the policy seam)"
772 );
773 }
774
775 #[test]
776 fn all_role_step_budgets_stay_unbounded_by_default() {
777 for role in [
778 FleetRole::Scout,
779 FleetRole::Consultant,
780 FleetRole::Reviewer,
781 FleetRole::Planner,
782 FleetRole::Verifier,
783 FleetRole::Builder,
784 FleetRole::Worker,
785 FleetRole::Custom,
786 ] {
787 assert_eq!(WorkerRuntimeProfile::for_role(role.clone()).max_steps, 0);
788 assert_eq!(
789 WorkerRuntimeProfile::for_role(role.clone()).max_steps,
790 WorkerRuntimeProfile::default_max_steps(role)
791 );
792 }
793 }
794
795 /// #4752: Consultant is counsel, not labour. Its posture has to be read-only
796 /// and shell-less by construction, not by the caller remembering to pass
797 /// `write_authority: read-only`.
798 #[test]
799 fn consultant_is_read_only_shell_less_and_high_reasoning_by_default() {
800 let consultant = WorkerRuntimeProfile::for_role(FleetRole::Consultant);
801
802 assert!(
803 !consultant.permissions.write,
804 "a consultant advises, it never writes"
805 );
806 assert_eq!(
807 consultant.shell,
808 ShellPolicy::None,
809 "a consultant has no reason to run commands"
810 );
811 assert_eq!(
812 consultant.reasoning_effort.as_deref(),
813 Some("high"),
814 "the point of asking a consultant is the reasoning tier"
815 );
816 assert_eq!(
817 consultant.model,
818 ModelRoute::Inherit,
819 "tier is a reasoning-effort default, not a hardcoded model"
820 );
821 assert_eq!(
822 consultant.max_steps,
823 WorkerRuntimeProfile::READ_ONLY_MAX_STEPS,
824 "consultants are unbounded by default"
825 );
826 }
827
828 /// The reasoning default must not become a ceiling: an explicit request
829 /// still wins, exactly as it does for every other role.
830 #[test]
831 fn an_explicit_reasoning_tier_overrides_the_consultant_default() {
832 let parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
833 let mut requested = WorkerRuntimeProfile::for_role(FleetRole::Consultant);
834 requested.reasoning_effort = Some("max".to_string());
835
836 let child = parent.derive_child(&requested);
837
838 assert_eq!(child.reasoning_effort.as_deref(), Some("max"));
839 assert!(!child.permissions.write, "still read-only");
840 }
841
842 #[test]
843 fn child_cannot_escalate_beyond_a_readonly_parent() {
844 // Scout now carries the read-only inspection posture: no writes, but network reach
845 // and full shell authority (bounded verification surface; raw shell
846 // still requires write at the clamp).
847 let parent = WorkerRuntimeProfile::for_role(FleetRole::Scout); // read-only inspection
848 let greedy = WorkerRuntimeProfile::for_role(FleetRole::Builder); // wants write + full shell
849 let child = parent.derive_child(&greedy);
850 assert!(
851 !child.permissions.write,
852 "a read-only parent cannot bear a writing child"
853 );
854 assert!(
855 child.permissions.network,
856 "child inherits the read-only inspection parent's network reach"
857 );
858 assert_eq!(
859 child.shell,
860 ShellPolicy::Full,
861 "child shell clamped to parent's read-only inspection posture"
862 );
863 }
864
865 #[test]
866 fn child_explicit_tools_are_bounded_by_parent() {
867 let mut parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
868 parent.tools = ToolScope::Explicit(vec!["read_file".into(), "grep_files".into()]);
869 let mut requested = WorkerRuntimeProfile::for_role(FleetRole::Worker);
870 requested.tools = ToolScope::Explicit(vec!["read_file".into(), "write_file".into()]);
871 let child = parent.derive_child(&requested);
872 match child.tools {
873 ToolScope::Explicit(names) => {
874 assert_eq!(
875 names,
876 vec!["read_file".to_string()],
877 "write_file not in parent set is dropped"
878 );
879 }
880 ToolScope::Inherit => panic!("expected explicit tool scope"),
881 }
882 }
883
884 #[test]
885 fn absolute_spawn_depth_is_preserved_and_position_increments() {
886 let mut parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
887 parent.max_spawn_depth = 2;
888 let mut requested = WorkerRuntimeProfile::for_role(FleetRole::Worker);
889 requested.max_spawn_depth = 99; // tries to grab more than the parent has
890 let child = parent.derive_child(&requested);
891 assert_eq!(
892 child.max_spawn_depth, 2,
893 "the absolute ceiling is unchanged, never the requested 99"
894 );
895 assert_eq!(child.spawn_depth, 1);
896 assert!(child.can_spawn_child());
897
898 let mut leaf_parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
899 leaf_parent.max_spawn_depth = 1;
900 let grandchild = leaf_parent.derive_child(&requested);
901 assert_eq!(grandchild.max_spawn_depth, 1);
902 assert_eq!(grandchild.spawn_depth, 1);
903 assert!(
904 !grandchild.can_spawn_child(),
905 "budget exhausted at the leaf"
906 );
907 }
908
909 #[test]
910 fn child_provider_falls_back_to_parent() {
911 let mut parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
912 parent.provider = Some("moonshot".to_string());
913 let requested = WorkerRuntimeProfile::for_role(FleetRole::Scout); // provider None
914 let child = parent.derive_child(&requested);
915 assert_eq!(child.provider.as_deref(), Some("moonshot"));
916 }
917
918 #[test]
919 fn child_reasoning_effort_uses_requested_then_parent() {
920 let mut parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
921 parent.reasoning_effort = Some("low".to_string());
922
923 let requested = WorkerRuntimeProfile::for_role(FleetRole::Scout);
924 let inherited = parent.derive_child(&requested);
925 assert_eq!(inherited.reasoning_effort.as_deref(), Some("low"));
926
927 let mut requested = WorkerRuntimeProfile::for_role(FleetRole::Scout);
928 requested.reasoning_effort = Some("max".to_string());
929 let overridden = parent.derive_child(&requested);
930 assert_eq!(overridden.reasoning_effort.as_deref(), Some("max"));
931 }
932
933 #[test]
934 fn child_denied_tools_union_never_drops_parent_restriction() {
935 // A child may only *add* deny entries; it can never drop a restriction
936 // an ancestor imposed (#4042 non-escalation invariant).
937 let mut parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
938 parent.denied_tools = vec!["exec_shell".into(), "mcp_*".into()];
939
940 // Child asks for its own deny list and (tryingly) tries to omit the
941 // parent's exec_shell — the union keeps both.
942 let mut requested = WorkerRuntimeProfile::for_role(FleetRole::Builder);
943 requested.denied_tools = vec!["write_file".into()];
944
945 let child = parent.derive_child(&requested);
946 assert!(child.denied_tools.contains(&"exec_shell".to_string()));
947 assert!(child.denied_tools.contains(&"mcp_*".to_string()));
948 assert!(child.denied_tools.contains(&"write_file".to_string()));
949 }
950
951 /// Every built-in role keeps network reads by default: a worker cut off
952 /// from the network for no role reason cannot do its job. Only workspace
953 /// mutation is a role intent.
954 #[test]
955 fn every_role_default_keeps_network_reads_and_only_read_only_roles_withhold_writes() {
956 for role in [
957 FleetRole::Scout,
958 FleetRole::Reviewer,
959 FleetRole::Planner,
960 FleetRole::Verifier,
961 FleetRole::Consultant,
962 FleetRole::Builder,
963 FleetRole::Worker,
964 FleetRole::Custom,
965 ] {
966 let profile = WorkerRuntimeProfile::for_role(role.clone());
967 assert!(
968 profile.permissions.network,
969 "{role:?} must keep network reads"
970 );
971 let read_only_by_intent = matches!(
972 role,
973 FleetRole::Scout
974 | FleetRole::Reviewer
975 | FleetRole::Planner
976 | FleetRole::Verifier
977 | FleetRole::Consultant
978 );
979 assert_eq!(
980 profile.permissions.write, !read_only_by_intent,
981 "{role:?} write default"
982 );
983 }
984 // Custom inherits (full ceiling); Planner probes read-only shell;
985 // Consultant never acts on the workspace.
986 assert_eq!(
987 WorkerRuntimeProfile::for_role(FleetRole::Custom).shell,
988 ShellPolicy::Full
989 );
990 assert_eq!(
991 WorkerRuntimeProfile::for_role(FleetRole::Planner).shell,
992 ShellPolicy::ReadOnly
993 );
994 assert_eq!(
995 WorkerRuntimeProfile::for_role(FleetRole::Consultant).shell,
996 ShellPolicy::None
997 );
998 }
999
1000 /// The parent's effective posture is the ceiling: a full-default child role
1001 /// under a read-only, no-network, read-only-shell parent inherits exactly
1002 /// that, never more.
1003 #[test]
1004 fn derive_child_inherits_the_parent_ceiling_and_never_widens() {
1005 let mut parent = WorkerRuntimeProfile::for_role(FleetRole::Worker);
1006 parent.permissions = PermissionSet::read_only();
1007 parent.shell = ShellPolicy::ReadOnly;
1008 for role in [FleetRole::Custom, FleetRole::Builder, FleetRole::Worker] {
1009 let child = parent.derive_child(&WorkerRuntimeProfile::for_role(role.clone()));
1010 assert!(!child.permissions.write, "{role:?} widened write");
1011 assert!(!child.permissions.network, "{role:?} widened network");
1012 assert_eq!(child.shell, ShellPolicy::ReadOnly, "{role:?} widened shell");
1013 }
1014 // And a full parent hands a doer its full posture.
1015 let full = WorkerRuntimeProfile::for_role(FleetRole::Worker)
1016 .derive_child(&WorkerRuntimeProfile::for_role(FleetRole::Custom));
1017 assert!(full.permissions.write && full.permissions.network);
1018 assert_eq!(full.shell, ShellPolicy::Full);
1019 }
1020 }
1021
1021 lines RUST