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
//! Worker runtime profile — the per-role capability contract for a CodeWhale
//! worker (#3217, #3211, #3213, and the child-permission-intersection issues
//! #414 / #426 / #1186).
//!
//! This is the **WhaleFlow substrate**: every detached worker — whether launched
//! as an `agent` sub-agent or a Fleet worker — should run under a profile
//! that bounds what it may do (permissions, shell access, tool scope, model
//! route, recursion budget, foreground/background). A child profile is always
//! **derived** from its parent and can never escalate beyond it.
//!
//! Scope: this module defines the contract and the parent→child derivation with
//! tests. `agent` and Fleet worker records now build and persist these
//! profiles so parent-visible worker projections have a single capability
//! contract. Runtime enforcement of every declared field remains incremental
//! follow-up work (#3217).
#![allow(dead_code)] // foundation: consumers are wired in a follow-up (#3217).
use crate::tools::subagent::SubAgentType;
use serde::{Deserialize, Serialize};
/// Coarse capability classes a worker may exercise, beyond read access (reads
/// are always permitted). A child may only ever hold a *subset* of its parent's
/// capabilities.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct PermissionSet {
/// May modify the workspace (`write_file` / `edit_file` / `apply_patch`).
pub write: bool,
/// May use network-capable tools (web search/fetch, networked MCP servers).
pub network: bool,
}
impl PermissionSet {
/// Full capabilities (write + network).
pub const fn full() -> Self {
Self {
write: true,
network: true,
}
}
/// Read-only: no write, no network.
pub const fn read_only() -> Self {
Self {
write: false,
network: false,
}
}
/// Intersection: a capability is granted only if **both** sets grant it.
/// This is the core non-escalation primitive — `parent.intersect(child)`
/// can never produce a capability the parent lacks.
#[must_use]
pub fn intersect(self, other: Self) -> Self {
Self {
write: self.write && other.write,
network: self.network && other.network,
}
}
}
/// Shell access policy — the replacement for the legacy per-worker shell boolean
/// (#3217). Ordered from most to least restrictive so `min` yields the safer of
/// two policies.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum ShellPolicy {
/// No shell access.
None,
/// Read-only / non-mutating commands only (the policy enforcement lives in
/// the exec/sandbox layer; this is the declared intent).
ReadOnly,
/// Full shell access.
Full,
}
impl ShellPolicy {
/// Convert the legacy top-level shell opt-in into the typed shell policy.
#[must_use]
pub const fn from_legacy_allow_shell(allow_shell: bool) -> Self {
if allow_shell { Self::Full } else { Self::None }
}
/// Whether any shell tools should be exposed under this policy.
#[must_use]
pub const fn allows_shell(self) -> bool {
!matches!(self, Self::None)
}
/// The more restrictive (safer) of two policies. A child can never exceed
/// its parent's shell policy.
#[must_use]
pub fn min_with(self, other: Self) -> Self {
if self <= other { self } else { other }
}
}
/// Which tools a worker may call. Mirrors the existing `AgentWorkerToolProfile`
/// (`Inherited` / `Explicit`) so the two can be reconciled when this is wired in.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolScope {
/// Inherit the parent's tool surface.
Inherit,
/// Only the explicitly listed tool names.
Explicit(Vec<String>),
}
/// How a worker's model is selected. New model-facing spawns default to the
/// parent/session model; a child only takes a smaller/faster family sibling when
/// the parent explicitly asks for that route.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ModelRoute {
/// Same model as the parent / session.
Inherit,
/// Explicitly request a smaller/faster same-family sibling when known.
Faster,
/// Legacy persisted route from the old hidden auto-router. New spawns do
/// not emit this; runtime treats it like `Faster` for compatibility.
Auto,
/// An explicit model id, validated against the active provider at spawn time.
Fixed(String),
}
/// The capability contract a single worker runs under.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkerRuntimeProfile {
pub role: SubAgentType,
pub permissions: PermissionSet,
pub shell: ShellPolicy,
pub tools: ToolScope,
pub model: ModelRoute,
/// Explicit provider override; `None` inherits the parent/session provider.
pub provider: Option<String>,
/// Remaining nested-delegation budget. A worker may spawn children while
/// `max_spawn_depth > 0`; each level decrements it. Clamped to the workspace
/// ceiling.
pub max_spawn_depth: u32,
/// Whether the worker runs detached (background) or inline (foreground).
pub background: bool,
}
impl WorkerRuntimeProfile {
/// The default profile for a role — the per-role posture. Mirrors the role
/// stances documented in `docs/SUBAGENTS.md` (explore/plan/review are
/// read-only; verifier runs tests; implementer/general write).
#[must_use]
pub fn for_role(role: SubAgentType) -> Self {
let (permissions, shell) = match role {
// Read-only investigators.
SubAgentType::Explore | SubAgentType::Review => {
(PermissionSet::read_only(), ShellPolicy::ReadOnly)
}
// Planner: analysis only, no shell.
SubAgentType::Plan => (PermissionSet::read_only(), ShellPolicy::None),
// Verifier: doesn't modify code, but runs the test suite.
SubAgentType::Verifier => (PermissionSet::read_only(), ShellPolicy::Full),
// Doers.
SubAgentType::Implementer | SubAgentType::General => {
(PermissionSet::full(), ShellPolicy::Full)
}
// Custom starts locked down; the caller opens specific tools explicitly.
SubAgentType::Custom => (PermissionSet::read_only(), ShellPolicy::None),
};
Self {
role,
permissions,
shell,
tools: ToolScope::Inherit,
model: ModelRoute::Inherit,
provider: None,
max_spawn_depth: codewhale_config::DEFAULT_SPAWN_DEPTH,
background: true,
}
}
/// Derive a child profile from this (parent) profile and a `requested` child
/// profile. The result is the **intersection** of the two — it can never
/// grant the child something the parent lacks (#414 / #426 / #1186):
///
/// - permissions are AND-ed,
/// - shell takes the more restrictive policy,
/// - an explicit parent tool set bounds the child's tool set,
/// - the spawn-depth budget decrements by one level and clamps to the ceiling.
///
/// The child keeps its own requested role, model route, and
/// foreground/background preference (these don't grant capability), but its
/// provider falls back to the parent's when unset.
#[must_use]
pub fn derive_child(&self, requested: &WorkerRuntimeProfile) -> WorkerRuntimeProfile {
let permissions = self.permissions.intersect(requested.permissions);
let shell = self.shell.min_with(requested.shell);
let tools = match (&self.tools, &requested.tools) {
// Parent restricts to a set → the child can only narrow within it.
(ToolScope::Explicit(parent), ToolScope::Explicit(child)) => ToolScope::Explicit(
child
.iter()
.filter(|name| parent.contains(name))
.cloned()
.collect(),
),
(ToolScope::Explicit(parent), ToolScope::Inherit) => {
ToolScope::Explicit(parent.clone())
}
// Parent inherits the full surface → the child's request stands.
(ToolScope::Inherit, child) => child.clone(),
};
// The child gets at most one level less budget than the parent, and never
// more than it requested, clamped to the hard ceiling.
let max_spawn_depth = requested
.max_spawn_depth
.min(self.max_spawn_depth.saturating_sub(1))
.min(codewhale_config::MAX_SPAWN_DEPTH_CEILING);
WorkerRuntimeProfile {
role: requested.role.clone(),
permissions,
shell,
tools,
model: requested.model.clone(),
provider: requested.provider.clone().or_else(|| self.provider.clone()),
max_spawn_depth,
background: requested.background,
}
}
/// Whether this worker may still spawn a child (budget remaining).
#[must_use]
pub fn can_spawn_child(&self) -> bool {
self.max_spawn_depth > 0
}
}
impl Default for WorkerRuntimeProfile {
fn default() -> Self {
Self::for_role(SubAgentType::General)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn permission_intersection_never_escalates() {
let parent = PermissionSet::read_only();
let greedy_child = PermissionSet::full();
// Even though the child asks for everything, the read-only parent wins.
let got = parent.intersect(greedy_child);
assert_eq!(got, PermissionSet::read_only());
}
#[test]
fn shell_policy_min_takes_the_safer() {
assert_eq!(
ShellPolicy::ReadOnly.min_with(ShellPolicy::Full),
ShellPolicy::ReadOnly
);
assert_eq!(
ShellPolicy::None.min_with(ShellPolicy::ReadOnly),
ShellPolicy::None
);
assert_eq!(
ShellPolicy::Full.min_with(ShellPolicy::Full),
ShellPolicy::Full
);
}
#[test]
fn for_role_postures_match_role_stances() {
let explore = WorkerRuntimeProfile::for_role(SubAgentType::Explore);
assert!(!explore.permissions.write, "explore must not write");
assert_eq!(explore.shell, ShellPolicy::ReadOnly);
assert_eq!(
explore.model,
ModelRoute::Inherit,
"explore should not silently downgrade the child model"
);
let implementer = WorkerRuntimeProfile::for_role(SubAgentType::Implementer);
assert!(implementer.permissions.write, "implementer writes");
assert_eq!(implementer.shell, ShellPolicy::Full);
let verifier = WorkerRuntimeProfile::for_role(SubAgentType::Verifier);
assert!(
!verifier.permissions.write,
"verifier reports, does not patch"
);
assert_eq!(
verifier.shell,
ShellPolicy::Full,
"verifier runs the test suite"
);
}
#[test]
fn child_cannot_escalate_beyond_a_readonly_parent() {
let parent = WorkerRuntimeProfile::for_role(SubAgentType::Explore); // read-only
let greedy = WorkerRuntimeProfile::for_role(SubAgentType::Implementer); // wants write + full shell
let child = parent.derive_child(&greedy);
assert!(
!child.permissions.write,
"a read-only parent cannot bear a writing child"
);
assert!(!child.permissions.network);
assert_eq!(
child.shell,
ShellPolicy::ReadOnly,
"child shell clamped to parent's"
);
}
#[test]
fn child_explicit_tools_are_bounded_by_parent() {
let mut parent = WorkerRuntimeProfile::for_role(SubAgentType::General);
parent.tools = ToolScope::Explicit(vec!["read_file".into(), "grep_files".into()]);
let mut requested = WorkerRuntimeProfile::for_role(SubAgentType::General);
requested.tools = ToolScope::Explicit(vec!["read_file".into(), "write_file".into()]);
let child = parent.derive_child(&requested);
match child.tools {
ToolScope::Explicit(names) => {
assert_eq!(
names,
vec!["read_file".to_string()],
"write_file not in parent set is dropped"
);
}
ToolScope::Inherit => panic!("expected explicit tool scope"),
}
}
#[test]
fn spawn_depth_decrements_and_clamps() {
let mut parent = WorkerRuntimeProfile::for_role(SubAgentType::General);
parent.max_spawn_depth = 2;
let mut requested = WorkerRuntimeProfile::for_role(SubAgentType::General);
requested.max_spawn_depth = 99; // tries to grab more than the parent has
let child = parent.derive_child(&requested);
assert_eq!(
child.max_spawn_depth, 1,
"child budget is at most parent-1, never the requested 99"
);
assert!(child.can_spawn_child());
let mut leaf_parent = WorkerRuntimeProfile::for_role(SubAgentType::General);
leaf_parent.max_spawn_depth = 1;
let grandchild = leaf_parent.derive_child(&requested);
assert_eq!(grandchild.max_spawn_depth, 0);
assert!(
!grandchild.can_spawn_child(),
"budget exhausted at the leaf"
);
}
#[test]
fn child_provider_falls_back_to_parent() {
let mut parent = WorkerRuntimeProfile::for_role(SubAgentType::General);
parent.provider = Some("moonshot".to_string());
let requested = WorkerRuntimeProfile::for_role(SubAgentType::Explore); // provider None
let child = parent.derive_child(&requested);
assert_eq!(child.provider.as_deref(), Some("moonshot"));
}
}