返回 CodeWhale
role.rs
1 //! Fleet roles — the lightweight role surface for exec and sub-agent spawning.
2 //!
3 //! Learned from the OMP sub-agent role system: an agent type is a **name**
4 //! plus a small static posture (tool allowlist, model, reasoning level), and
5 //! exec consumes exactly that — never the roster, ledger, or worker
6 //! machinery. The durable Fleet runs (manager / executor / worker_runtime /
7 //! exact workflow driver) remain the one consumer of the heavy machinery and
8 //! resolve roles through this same surface, so both paths share one posture.
9 //!
10 //! What lives here (and only here) for spawn-time decisions:
11 //! - [`FleetRole`]: the closed 8-role set, parsing, and canonical labels.
12 //! - Per-role posture: [`role_requires_read_only_shell`],
13 //! [`effective_runtime_profile_for_role`], [`fleet_effective_permissions`].
14 //! - The tool deny lists + [`ChildAuthority`]: how a
15 //! role posture becomes the concrete child surface (allowlist, deny list,
16 //! write authority, delegation budget, fingerprint).
17 //!
18 //! Deliberately dependency-light: protocol + workflow ceiling types,
19 //! [`crate::worker_profile`], std. Nothing from fleet control / store /
20 //! ledger / executor / worker_runtime / roster / profile / identity /
21 //! members, and nothing from tools.
22
23 use codewhale_protocol::fleet::{FleetEffectivePermissions, migrate_legacy_role_token};
24 use codewhale_protocol::fleet::{PermissionCeiling, ShellCeiling};
25
26 use crate::worker_profile::{ShellPolicy, ToolScope, WorkerRuntimeProfile};
27
28 /// Canonical model-facing Fleet role values, in schema order. This is the
29 /// closed `enum` advertised on the Agent tool's `type` property. Legacy
30 /// aliases are accepted only at replay/deserialization boundaries
31 /// ([`migrate_legacy_role_token`]) and are never advertised to models.
32 pub const FLEET_ROLE_SCHEMA_VALUES: [&str; 8] = [
33 "general",
34 "explore",
35 "planner",
36 "reviewer",
37 "implement",
38 "test",
39 "advisor",
40 "custom",
41 ];
42
43 /// Human-readable hint listing every token [`FleetRole::parse`] accepts,
44 /// for spawn-time error messages. Keep in sync with
45 /// [`migrate_legacy_role_token`] and the `from_str` match arms; those two are
46 /// the only role parser (#2649 was a second table in the spawn tool drifting
47 /// from this set).
48 pub const VALID_ROLE_ALIASES: &str = "general; explore; planner; reviewer; implement; test; advisor; custom \
49 (legacy aliases remain accepted: worker; scout; builder; verifier; consultant; default; general-purpose; general_purpose; exploration; explorer; plan; planning; awaiter; review; code-review; code_review; implementer; implementation; verify; verification; validator; tester; oracle)";
50
51 /// Canonical Fleet role for a delegated worker, with specialized behavior
52 /// and tool access per role.
53 ///
54 /// **Public vocabulary is Fleet roles** (`general`, `explore`, `planner`,
55 /// `reviewer`, `implement`, `test`, `advisor`, `custom`) and the variants match that
56 /// vocabulary one-to-one. Serialization, prompts, receipts, and UI always
57 /// use [`Self::as_str`]. Legacy wire spellings (`worker`, `scout`, `plan`,
58 /// `review`, `implementer`, …) are accepted only through
59 /// [`migrate_legacy_role_token`] at deserialization / parse boundaries.
60 ///
61 /// This is the closed runtime role set. It is distinct from
62 /// `codewhale_config::FleetRole`, which is the open config-side role
63 /// *declaration* (free-form name plus instruction overlay) carried by a
64 /// Fleet profile. The `FleetRole` type name remains a compatibility identifier.
65 #[derive(Debug, Clone, PartialEq, Eq, Default)]
66 pub enum FleetRole {
67 /// General-purpose worker - full tool access for multi-step tasks.
68 #[default]
69 Worker,
70 /// Fast exploration - read-only tools for codebase search.
71 Scout,
72 /// Planning — grounded strategy. Reads the workspace and the web and
73 /// may run classifier-bounded shell probes; never mutates.
74 Planner,
75 /// Code review - read + analysis tools.
76 Reviewer,
77 /// Implementation — focused on writing / patching code to satisfy
78 /// a specific change. Distinct from `Worker` in that the prompt
79 /// posture pushes hard on landing the change cleanly with the
80 /// minimum surrounding edit (#404).
81 Builder,
82 /// Verification — focused on running the test suite or other
83 /// validation gates and reporting pass/fail with evidence.
84 /// Distinct from `Reviewer` in that Reviewer reads code and grades it;
85 /// Verifier *runs* tests and reports the outcome (#404).
86 Verifier,
87 /// Advisory counsel — a strong-model second opinion the operator can ask
88 /// for guidance, judgement calls, and design critique (#4752).
89 ///
90 /// Read-only and shell-less by construction: a Consultant reasons about the
91 /// code (and may read the web to ground that counsel) and says what it
92 /// thinks. It is distinct from `Reviewer`, which grades a specific change
93 /// against a standard, and from `Planner`, which produces a plan to execute.
94 /// A Consultant answers "what should we do here, and what are we not seeing".
95 Consultant,
96 /// Custom tool access defined at spawn time. Inherits the parent's
97 /// write/network/shell ceiling and is narrowed by the explicit tool list
98 /// or an explicit write_authority, never by a silent lock-down.
99 Custom,
100 }
101
102 impl serde::Serialize for FleetRole {
103 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
104 where
105 S: serde::Serializer,
106 {
107 serializer.serialize_str(self.as_str())
108 }
109 }
110
111 impl<'de> serde::Deserialize<'de> for FleetRole {
112 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
113 where
114 D: serde::Deserializer<'de>,
115 {
116 let raw = String::deserialize(deserializer)?;
117 Self::parse(&raw)
118 .ok_or_else(|| serde::de::Error::unknown_variant(&raw, &FLEET_ROLE_SCHEMA_VALUES))
119 }
120 }
121
122 impl FleetRole {
123 /// Parse a Fleet role from user input or a serialized boundary.
124 ///
125 /// Accepts Fleet role names and, at this parse boundary only, legacy
126 /// aliases (`scout` → explore, `plan` → planner, …).
127 #[must_use]
128 pub fn parse(s: &str) -> Option<Self> {
129 let normalized = s.trim().to_ascii_lowercase();
130 // Boundary migration first, then canonical Fleet names.
131 let token = migrate_legacy_role_token(&normalized).unwrap_or(normalized.as_str());
132 match token {
133 "general" => Some(Self::Worker),
134 "explore" => Some(Self::Scout),
135 "planner" => Some(Self::Planner),
136 "reviewer" => Some(Self::Reviewer),
137 "implement" => Some(Self::Builder),
138 "test" => Some(Self::Verifier),
139 "advisor" => Some(Self::Consultant),
140 "custom" => Some(Self::Custom),
141 _ => None,
142 }
143 }
144
145 /// Canonical Fleet role label for runtime, schemas, prompts, receipts, UI.
146 #[must_use]
147 pub fn as_str(&self) -> &'static str {
148 match self {
149 Self::Worker => "general",
150 Self::Scout => "explore",
151 Self::Planner => "planner",
152 Self::Reviewer => "reviewer",
153 Self::Builder => "implement",
154 Self::Verifier => "test",
155 Self::Consultant => "advisor",
156 Self::Custom => "custom",
157 }
158 }
159
160 /// One-line model-facing description of what this role does. Backs the
161 /// role catalog returned by the agent roster action.
162 #[must_use]
163 pub fn description(&self) -> &'static str {
164 match self {
165 Self::Worker => "General-purpose worker with full tool access for multi-step tasks.",
166 Self::Scout => "Fast read-only exploration for codebase search and analysis.",
167 Self::Planner => {
168 "Grounded strategy: reads the workspace and the web, runs read-only probes, never mutates."
169 }
170 Self::Reviewer => "Reads and grades code against a standard.",
171 Self::Builder => {
172 "Lands focused code changes cleanly with the minimum surrounding edit."
173 }
174 Self::Verifier => {
175 "Runs the test suite and validation gates, reports pass/fail with evidence."
176 }
177 Self::Consultant => {
178 "Read-only high-reasoning counsel for judgement calls and design critique."
179 }
180 Self::Custom => "Custom tool access defined at spawn time by the parent's posture.",
181 }
182 }
183
184 /// All canonical roles in schema order, for catalog responses.
185 #[must_use]
186 pub fn all() -> [Self; 8] {
187 [
188 Self::Worker,
189 Self::Scout,
190 Self::Planner,
191 Self::Reviewer,
192 Self::Builder,
193 Self::Verifier,
194 Self::Consultant,
195 Self::Custom,
196 ]
197 }
198 }
199
200 /// Public label for any role token (canonical or legacy alias).
201 /// Canonical/legacy tokens collapse to the advertised name;
202 /// anything else passes through trimmed.
203 #[must_use]
204 pub fn public_role_label(token: &str) -> String {
205 FleetRole::parse(token).map_or_else(
206 || token.trim().to_string(),
207 |role| role.as_str().to_string(),
208 )
209 }
210
211 // ── Child authority: the ceiling, as the child actually experiences it ───────
212
213 /// Tool names that give a model its own reach onto the network.
214 ///
215 /// `network_tool = false` must remove **all** of them from the child's
216 /// model-visible surface, not merely block them at call time — a model that can
217 /// see a tool will try it, and a refusal is a worse experience than an absent
218 /// capability. The child registry hides denied tools from
219 /// `tools_for_model` and refuses them in `is_tool_allowed`, so one deny list
220 /// covers both.
221 ///
222 /// The `mcp*` wildcards are load-bearing: a remote MCP server's tools arrive
223 /// under a runtime-generated name, so they cannot be enumerated here and must be
224 /// matched by prefix. `is_tool_denied` supports `prefix*` globs for exactly this.
225 pub const NETWORK_TOOL_DENYLIST: &[&str] = &[
226 // Web search / fetch / browse, and the canonical family that fronts them.
227 //
228 // The `Web` family name itself is deliberately NOT denied. Its `search`
229 // and `fetch` actions are the read-only web surface a network-denied
230 // member is entitled to (parity with an ordinary scout), and the family
231 // is classified read-only at the capability envelope, so removing the
232 // *name* from this list grants exactly those two actions and nothing
233 // else. What this list removes is every other spelling of the browsing
234 // surface: the separate `web.run` browse tool, the legacy `web_search` /
235 // `fetch_url` / `wait_for_dev_server` action aliases, and the `web_*` /
236 // `web.*` name families, so a deny list that stops at `Web` can never
237 // leave `web.run` visible and callable, which is the entire browsing
238 // capability by another spelling. The explicit names are kept because
239 // they document intent and because two of them (`fetch_url`,
240 // `wait_for_dev_server`) are not matched by either glob.
241 //
242 // The captured ChildGrant action ceiling enforced by Core's tool registry
243 // lets a network-denied child keep exactly `Web{search, fetch}` past the
244 // denied aliases, and the URL-input guard refuses a URL-addressed
245 // `fetch` at dispatch, so the reach stays closed.
246 "web_*",
247 "web.*",
248 "web.run",
249 "web_run",
250 "web_search",
251 "web.fetch",
252 "web_fetch",
253 "fetch_url",
254 "wait_for_dev_server",
255 "browse",
256 "browser",
257 // Networked service tools.
258 "github",
259 // The RLM session family's two reaching actions.
260 //
261 // `rlm_open` accepts a `url` and fetches it by calling `FetchUrlTool`
262 // *in-process*, under its own name — so denying `fetch_url` never sees the
263 // call. `rlm_eval` runs operator-supplied Python against a live kernel,
264 // which owns a socket API no inspection of the *call* can bound.
265 //
266 // Both are denied outright rather than gated on the input. The narrower
267 // contract was considered and rejected: `rlm_open` chooses its source from
268 // *input fields* (`file_path` / `content` / `url` / `session_object`), not
269 // from the action name, and the action-policy seam
270 // (`codewhale_execpolicy::canonical_action`) resolves names, not field shapes —
271 // it cannot prove a source is local before execution. So this fails closed.
272 // A network-denied member loses `rlm` loading and evaluation entirely,
273 // including the purely local `file_path` form, and keeps only the bounded
274 // metadata actions (`session_objects` / `configure` / `close`), which the
275 // per-action alias entries make expressible. See `docs/FLEET.md`.
276 "rlm_open",
277 "rlm_eval",
278 // Every MCP surface, including remote servers registered at runtime.
279 "mcp*",
280 "start_mcp_server",
281 "list_mcp_resources",
282 "list_mcp_resource_templates",
283 "read_mcp_resource",
284 ];
285
286 /// The deny-list entry that stands for "this child has no network".
287 ///
288 /// The deny list is how `network_tool = false` reaches a child across the
289 /// durable-Fleet and `codewhale exec` boundaries (through
290 /// `worker_profile.denied_tools` / `context.disallowed_tools`). `fetch_url` is
291 /// the sentinel because every network denial installs it and no narrower deny
292 /// list does — the `web_*` / `web.*` globs deliberately do not match it,
293 /// which is why it is spelled out above. The in-process child reads its
294 /// network axis off the resolved grant, which folds this sentinel in at
295 /// resolve time — so the transport denial and the semantic answer can never
296 /// disagree.
297 pub const NETWORK_DENIAL_SENTINEL: &str = "fetch_url";
298
299 /// Tool names that mutate the workspace directly.
300 ///
301 /// A member whose clamped ceiling says `write = false` must not merely be
302 /// *labelled* read-only — the mutating tools have to be gone from the surface
303 /// it can see and call. Only the action aliases are listed, never the `File`
304 /// family itself: denying `File` would take `read`/`list`/`search` with it, and
305 /// the registry already resolves `File{action:"write"}` through the alias table
306 /// to `write_file`, so denying the alias covers both spellings.
307 ///
308 /// `rlm_eval` is here for the same reason it is on the network list and not for
309 /// a different one: the Python it runs against a live kernel calls `open(...,
310 /// "w")` as readily as it opens a socket. It is a mutation primitive that
311 /// happens to be spelled as an analysis tool, and leaving it on a `write =
312 /// false` surface would let a read-only member rewrite the workspace while the
313 /// receipt said otherwise. The rest of the family — including the local
314 /// `file_path` load — survives a write denial, because reading a large file
315 /// into a kernel is exactly what a read-only member is for.
316 pub const MUTATING_TOOL_DENYLIST: &[&str] = &[
317 "write_file",
318 "edit_file",
319 "apply_patch",
320 "fim_edit",
321 "revert_turn",
322 "rlm_eval",
323 ];
324
325 /// The raw shell surface — arbitrary operator-supplied commands.
326 ///
327 /// A read-only member with `shell = "full"` is the honest-labelling problem
328 /// this list exists for. `full` was saved so the member could *run checks*, but
329 /// raw shell is a general mutation primitive: `rm`, `git checkout`, or a `>`
330 /// redirect writes the workspace just as surely as `write_file`, while the
331 /// receipt says `write=false`. Denying the raw shell entries and leaving the
332 /// bounded verification surface (`Run` / `run_tests` / `run_verifiers`) intact
333 /// keeps the verifier able to do its job under a contract that is true.
334 /// Scout/reviewer read-only inspection selectively removes only canonical `Bash` from this
335 /// deny list after the role is known; its input-specific read-only classifier
336 /// remains the authority for that narrow exception.
337 ///
338 /// That surface is bounded only in its **default** form, and the distinction is
339 /// load-bearing: `run_tests` accepts a raw `args` string, a general command
340 /// primitive by another name — `--config target.runner="sh -c ..."` is
341 /// precisely the raw shell this list just removed. Denying the tools outright
342 /// would take the verifier's whole purpose with them, so the *unbounded
343 /// arguments* are refused at the execution seam instead; see `reject_unbounded_verification` in
344 /// `crate::tools::subagent`. The name deny list and that guard are one
345 /// contract split across the only two places that can each see half of it.
346 pub const RAW_SHELL_DENYLIST: &[&str] = &[
347 "Bash",
348 "exec_shell",
349 "exec_shell_wait",
350 "exec_wait",
351 "exec_shell_interact",
352 "exec_interact",
353 "exec_shell_cancel",
354 "task_shell_start",
355 "task_shell_wait",
356 // The persistent PTY surface registers as `terminal_run`, `terminal_send`,
357 // … with hidden legacy `terminal/*` aliases — both globs stay denied.
358 "terminal_*",
359 "terminal/*",
360 ];
361
362 /// The deny-list entry that stands for "this child has no raw shell".
363 ///
364 /// Same construction as [`NETWORK_DENIAL_SENTINEL`], and for the same reason:
365 /// posture is read back off the list that enforces it rather than carried as a
366 /// second field that could disagree. `exec_shell` is the sentinel because every
367 /// raw-shell denial installs it and no narrower deny list does.
368 ///
369 /// Read by the tests that assert the raw-shell denial actually landed. It is
370 /// deliberately *not* what decides a child's shell authority — that question
371 /// is answered by the resolved grant's `shell` axis, which distinguishes
372 /// "no process surface" from "bounded verification surface" by grant field
373 /// rather than by a sentinel name.
374 #[cfg(any(test, feature = "test-support"))]
375 pub const RAW_SHELL_SENTINEL: &str = "exec_shell";
376
377 /// The built-in verification surface: the workspace's own configured checks.
378 ///
379 /// Bounded in its arguments (see `crate::tools::execution_envelope`) but not
380 /// free of consequence — every entry forks a process. A member whose shell
381 /// ceiling is narrower than `full` holds no authority to start one, so this
382 /// list comes off its surface entirely. A `write = false, shell = "full"`
383 /// member keeps it, because running the checks is what that preset is for.
384 pub const VERIFICATION_SURFACE_DENYLIST: &[&str] = &["Run", "run_tests", "run_verifiers"];
385
386 /// The deny-list entry that stands for "this child holds no shell authority".
387 ///
388 /// Distinct from `RAW_SHELL_SENTINEL`, and the distinction is the point.
389 /// `exec_shell` is installed whenever the *raw* shell is removed, which
390 /// includes the write-denied verifier that still holds shell authority — so
391 /// reading shell authority off it would take the verification surface away
392 /// from the one role that exists to use it. `run_tests` is installed only
393 /// when the shell *ceiling* itself is narrower than `full`, which is exactly
394 /// the posture that has no authority to start a process. The grant folds
395 /// this sentinel into its `shell` axis at resolve time: `Verify`/`Full`
396 /// collapse to `None`, while `Inspect` — classifier-bounded evidence reads,
397 /// not process-start authority — survives.
398 pub const SHELL_AUTHORITY_SENTINEL: &str = "run_tests";
399
400 /// Execution primitives that are **not** spelled as shell.
401 ///
402 /// Every entry runs an operator-supplied program or schedules one: `gate_run`
403 /// takes a command line, the mutating `automation` actions execute or schedule
404 /// a stored automation with its own cwd and prompt, `start_mcp_server` spawns a
405 /// process, and `pr_attempt_*` writes durable work state. They are listed here
406 /// so a write-denied child never *sees* them; the authoritative refusal is
407 /// capability-derived and lives in `crate::tools::execution_envelope`, which
408 /// also covers the ones no list can name — repository plugin tools and MCP
409 /// server tools registered at runtime.
410 ///
411 /// Listing the per-action alias rather than the family is deliberate and is
412 /// what the canonical-action seam exists for: denying `tasks` outright would
413 /// take `list`/`read` with it, and durable-task bookkeeping is exactly what a
414 /// read-only member should keep.
415 pub const NON_SHELL_EXECUTION_DENYLIST: &[&str] = &[
416 "task_gate_run",
417 "task_create",
418 "task_cancel",
419 "pr_attempt_record",
420 "pr_attempt_preflight",
421 "automation_run",
422 "automation_create",
423 "automation_update",
424 "automation_pause",
425 "automation_resume",
426 "automation_delete",
427 "start_mcp_server",
428 ];
429
430 /// Whether a deny rule belongs to an enforced role posture. Operator and
431 /// ancestor denials are also immutable; this identifies posture rules for
432 /// authority diagnostics and tests, not a child opt-out exception.
433 #[cfg(any(test, feature = "test-support"))]
434 #[must_use]
435 pub fn is_posture_denial(rule: &str) -> bool {
436 [
437 NETWORK_TOOL_DENYLIST,
438 MUTATING_TOOL_DENYLIST,
439 RAW_SHELL_DENYLIST,
440 VERIFICATION_SURFACE_DENYLIST,
441 NON_SHELL_EXECUTION_DENYLIST,
442 ]
443 .iter()
444 .flat_map(|list| list.iter())
445 .any(|entry| entry.eq_ignore_ascii_case(rule.trim()))
446 }
447
448 /// A Runtime role policy intersected with the live parent and translated into
449 /// the concrete knobs a child spawn actually carries.
450 #[derive(Debug, Clone, PartialEq, Eq)]
451 pub struct ChildAuthority {
452 /// The clamped ceiling. Never wider than either input.
453 pub ceiling: PermissionCeiling,
454 /// `Some(list)` narrows the child's model-visible surface to exactly
455 /// `list`. `Some(vec![])` — the `tools = false` case — means *no tools at
456 /// all*, which is what the child registry's empty-allowlist path produces.
457 /// `None` means full inheritance from the parent surface.
458 pub allowed_tools: Option<Vec<String>>,
459 /// Names/globs the child must never see or call. Deny wins over allow.
460 pub disallowed_tools: Vec<String>,
461 /// Spawn write authority implied by the clamped ceiling.
462 pub write_authority: &'static str,
463 /// Nested-delegation budget, clamped.
464 pub max_depth: u32,
465 /// Canonical posture role that governs the child's tool posture.
466 pub posture_role: &'static str,
467 }
468
469 impl ChildAuthority {
470 /// Intersect one Runtime-requested posture with the live parent posture.
471 ///
472 /// Every field takes the more restrictive side, so a child can never widen
473 /// live authority.
474 #[must_use]
475 pub fn clamp(requested: PermissionCeiling, session: PermissionCeiling) -> Self {
476 let ceiling = requested.clamp_to(session);
477
478 // `tools = false` is total: an empty allowlist leaves the child with no
479 // model-visible tools and nothing it is permitted to call.
480 let allowed_tools = (!ceiling.tools).then(Vec::new);
481
482 // The deny list expresses the effective Runtime posture. The spawn
483 // registry separately unions it with inherited parent restrictions, so
484 // a descendant can never drop something an ancestor
485 // imposed.
486 let mut disallowed_tools = Vec::new();
487 if !ceiling.network_tool {
488 disallowed_tools.extend(NETWORK_TOOL_DENYLIST.iter().map(|name| (*name).to_string()));
489 }
490 // Raw shell requires the ceiling to *say* `shell = "full"`. Any narrower
491 // shell posture — `none` or `read_only` — loses the raw command surface
492 // outright. `from_runtime_role` may subsequently
493 // retain canonical `Bash` for a named scout/reviewer, whose concrete
494 // calls are bounded by the strict read-only classifier.
495 //
496 // This is deliberately keyed on the shell field rather than only on
497 // `write`, and that is the whole repair: the execution envelope reads
498 // its `shell` bit back off this deny list
499 // ([`RAW_SHELL_SENTINEL`]), so a ceiling whose shell posture never
500 // installed a denial was invisible to it. A clamped ceiling of
501 // `write = true, shell = none` — which any write-capable member inherits
502 // inside a session that has no shell authority — therefore reached the
503 // envelope claiming full shell authority and could start a process the
504 // ceiling had refused it.
505 if !(ceiling.write && ceiling.shell == ShellCeiling::Full) {
506 disallowed_tools.extend(RAW_SHELL_DENYLIST.iter().map(|name| (*name).to_string()));
507 }
508 // Losing the *raw* shell and holding no shell authority at all are two
509 // different postures, and only the second one loses the bounded
510 // verification surface.
511 //
512 // A `verifier`/`tester` member (`write = false, shell = "full"`) is the
513 // case that separates them: the rule above takes its raw shell away as
514 // a mutation control, but the member still holds shell authority and
515 // running the workspace's own checks is its entire purpose. A ceiling
516 // whose shell posture is narrower than `full` holds no such authority,
517 // so for it the checks are just another way to start a process.
518 if ceiling.shell != ShellCeiling::Full {
519 disallowed_tools.extend(
520 VERIFICATION_SURFACE_DENYLIST
521 .iter()
522 .map(|name| (*name).to_string()),
523 );
524 }
525 if !ceiling.write {
526 // `write = false` has to be a fact about the child's tool surface,
527 // not a word on a receipt, so the mutating file tools go. The raw
528 // shell is already gone by the rule above; a Runtime scout/reviewer
529 // may regain only canonical Bash in `from_runtime_role`, behind its
530 // input-specific read-only classifier. The bounded verification
531 // surface (`Run` / `run_tests` / `run_verifiers`) is deliberately
532 // left for a full-shell verifier.
533 disallowed_tools.extend(
534 MUTATING_TOOL_DENYLIST
535 .iter()
536 .map(|name| (*name).to_string()),
537 );
538 // Removing the shell is not enough on its own. An execution
539 // primitive spelled as bookkeeping — a verification gate that takes
540 // a command line, an automation that runs one on a schedule, an MCP
541 // server that spawns a process — mutates the workspace exactly as
542 // well as the shell just removed, while the receipt says
543 // `write=false`. These names take them off the visible surface;
544 // `crate::tools::execution_envelope` refuses them by capability,
545 // including the ones no list can name.
546 disallowed_tools.extend(
547 NON_SHELL_EXECUTION_DENYLIST
548 .iter()
549 .map(|name| (*name).to_string()),
550 );
551 }
552
553 Self {
554 ceiling,
555 allowed_tools,
556 disallowed_tools,
557 write_authority: if ceiling.write {
558 "workspace_write"
559 } else {
560 "read_only"
561 },
562 max_depth: ceiling.delegation_depth,
563 posture_role: posture_role_for(ceiling),
564 }
565 }
566
567 /// A stable, content-free fingerprint of the envelope this authority
568 /// actually installs.
569 ///
570 /// This is the value that turns "the Fleet computed a ceiling" into
571 /// something a later layer can *check*. It covers every field a spawn
572 /// carries — allowlist, deny list, write authority, delegation budget, and
573 /// posture role — so a request that drifted between admission, routing, and
574 /// construction cannot pass for the one the Fleet resolved. Two authorities
575 /// with the same fingerprint install the same child surface; that is the
576 /// whole contract.
577 ///
578 /// Deliberately human-readable rather than hashed: it appears verbatim in
579 /// the fail-closed error, and an operator debugging a refused launch should
580 /// be able to see which side differs without a lookup table.
581 #[must_use]
582 pub fn fingerprint(&self) -> String {
583 let allowed = match &self.allowed_tools {
584 None => "inherit".to_string(),
585 Some(list) if list.is_empty() => "none".to_string(),
586 Some(list) => {
587 let mut list = list.clone();
588 list.sort();
589 list.join(",")
590 }
591 };
592 let mut denied = self.disallowed_tools.clone();
593 denied.sort();
594 denied.dedup();
595 format!(
596 "v1;posture={};write={};depth={};tools={};network={};shell={};allow={};deny={}",
597 self.posture_role,
598 self.write_authority,
599 self.max_depth,
600 self.ceiling.tools,
601 self.ceiling.network_tool,
602 self.ceiling.shell.as_str(),
603 allowed,
604 denied.join(","),
605 )
606 }
607
608 /// Derive authority exclusively from Runtime policy after Fleet identity
609 /// selection. Free-form semantic roles map to Runtime `custom`; neither
610 /// the Fleet definition nor its legacy `permissions` key participates.
611 #[must_use]
612 pub fn from_runtime_role(role: &str, session: PermissionCeiling) -> Self {
613 let runtime_role = runtime_role_for_member(role);
614 let requested = runtime_permission_ceiling(&runtime_role);
615 let mut authority = Self::clamp(requested, session);
616 authority.posture_role = runtime_role.as_str();
617
618 if matches!(
619 runtime_role,
620 FleetRole::Scout | FleetRole::Reviewer | FleetRole::Planner
621 ) && authority.ceiling.shell != ShellCeiling::None
622 {
623 // Runtime's Scout/Reviewer policy permits classifier-bounded Bash
624 // inspection. Keep the canonical entry while all other shell and
625 // execution aliases remain denied.
626 authority
627 .disallowed_tools
628 .retain(|name| !name.eq_ignore_ascii_case("Bash"));
629 }
630 authority
631 }
632 }
633
634 /// Org-chart aliases for Fleet **member** role labels: roster slot names and
635 /// coordination titles that select a runtime posture but are not part of the
636 /// model-facing spawn vocabulary.
637 ///
638 /// Deliberately *not* folded into [`migrate_legacy_role_token`]. That table
639 /// feeds [`FleetRole::parse`], which is also the closed vocabulary the
640 /// `agent` tool validates its `type` against, and — decisively — the test the
641 /// spawn parser uses to decide whether a `role` string is a posture alias or a
642 /// roster profile key. Teaching `from_str` about `manager` or `smoke-runner`
643 /// would stop those names resolving as roster members there. So the aliases
644 /// live here, one step out, and reach exactly the one consumer that wants
645 /// them: [`runtime_role_for_member`].
646 ///
647 /// Every entry maps to the posture the durable Fleet driver already gave it,
648 /// so folding them in only ever *narrows* the exact driver (which previously
649 /// dropped all of these into write-capable `custom`); none of them widens
650 /// authority on either path.
651 fn member_role_alias(token: &str) -> Option<FleetRole> {
652 match token {
653 // Coordination happens through delegation, which needs the full
654 // General surface (#fleet-roster cutover (v0.8.67)). The operator is
655 // the helm of the overall work (it assigns managers to Workflows);
656 // the manager is the middle manager of one Workflow. Both coordinate,
657 // so both get the General surface — explicitly, not by fall-through.
658 "manager" | "coordinator" | "operator" => Some(FleetRole::Worker),
659 // Synthesis is read-only (planner posture: network reads and
660 // read-only probes, never workspace writes). It must never fall
661 // through to General's full-write posture (#fleet-roster cutover
662 // (v0.8.67)).
663 "synthesizer" | "summarizer" | "reducer" => Some(FleetRole::Planner),
664 // Documented Fleet task role spellings (`docs/FLEET.md`).
665 "smoke-runner" => Some(FleetRole::Verifier),
666 "read-only" => Some(FleetRole::Scout),
667 _ => None,
668 }
669 }
670
671 /// Map the Fleet's open semantic role label onto Runtime's closed role policy.
672 ///
673 /// **This is the only name → posture mapper.** Both Fleet drivers resolve
674 /// through it: the exact/named-Fleet driver via
675 /// [`ChildAuthority::from_runtime_role`], and the durable driver via
676 /// `worker_runtime::roster_member_agent_type` and the task-role call sites.
677 /// A second table anywhere is the defect this function exists to prevent —
678 /// before #5575 the durable driver carried its own alias list, so the same
679 /// string (`synthesizer`, `smoke-runner`, `read-only`) resolved to a
680 /// read-only posture on one driver and to write-capable `custom` on the other.
681 ///
682 /// Resolution order, and nothing else:
683 /// 1. an empty label means *unspecified*, which is the documented general
684 /// default a Fleet task without a `role` has always had;
685 /// 2. [`FleetRole::parse`] — the declared closed vocabulary plus its
686 /// documented legacy aliases ([`VALID_ROLE_ALIASES`]);
687 /// 3. `member_role_alias` — the org-chart/slot spellings above;
688 /// 4. **fail closed.**
689 ///
690 /// Step 4 is the privilege boundary. An unrecognized label is still useful
691 /// identity (`auditor`, `release-lead`, …) and keeps its name on every receipt
692 /// via [`public_role_label`], but a name nobody declared must not be able to
693 /// hand a worker write authority. It therefore executes on the narrowest
694 /// posture that can still do useful work — `explore`: no workspace writes, no
695 /// raw shell, network reads and classifier-bounded `Bash` inspection. An
696 /// operator who genuinely wants "inherit whatever the parent has" spells that
697 /// `custom`, which is a declared role and resolves at step 2.
698 pub fn runtime_role_for_member(role: &str) -> FleetRole {
699 let token = role.trim().to_ascii_lowercase();
700 if token.is_empty() {
701 return FleetRole::Worker;
702 }
703 FleetRole::parse(&token)
704 .or_else(|| member_role_alias(&token))
705 .unwrap_or(FleetRole::Scout)
706 }
707
708 fn runtime_permission_ceiling(role: &FleetRole) -> PermissionCeiling {
709 let profile = WorkerRuntimeProfile::for_role(role.clone());
710 let shell = match profile.shell {
711 ShellPolicy::None => ShellCeiling::None,
712 ShellPolicy::ReadOnly => ShellCeiling::ReadOnly,
713 ShellPolicy::Full => ShellCeiling::Full,
714 };
715 let tools = match profile.tools {
716 ToolScope::Inherit => true,
717 ToolScope::Explicit(ref tools) => !tools.is_empty(),
718 };
719 PermissionCeiling {
720 write: profile.permissions.write,
721 network_tool: profile.permissions.network,
722 shell,
723 delegation_depth: profile.remaining_spawn_depth(),
724 tools,
725 }
726 }
727
728 /// Intersect a worker shell policy with the session's legacy shell opt-in.
729 #[must_use]
730 pub fn session_shell_ceiling(shell: ShellPolicy, allow_shell: bool) -> ShellCeiling {
731 match shell {
732 ShellPolicy::None => ShellCeiling::None,
733 ShellPolicy::ReadOnly => ShellCeiling::ReadOnly,
734 ShellPolicy::Full if allow_shell => ShellCeiling::Full,
735 ShellPolicy::Full => ShellCeiling::None,
736 }
737 }
738
739 /// Map a permission ceiling onto the canonical posture role that governs the
740 /// child's tool surface.
741 #[must_use]
742 pub fn posture_role_for(ceiling: PermissionCeiling) -> &'static str {
743 if !ceiling.tools {
744 // No tools at all; the narrowest posture, and the allowlist is empty
745 // anyway.
746 return "explore";
747 }
748 if ceiling.write {
749 return "implement";
750 }
751 match ceiling.shell {
752 ShellCeiling::None | ShellCeiling::ReadOnly => "explore",
753 ShellCeiling::Full => "test",
754 }
755 }
756
757 /// Whether a Fleet role is never allowed a mutating shell, whatever its
758 /// requested runtime profile says. Spawn narrows the child to a read-only
759 /// shell for these roles, and every receipt must report that same posture.
760 #[must_use]
761 pub fn role_requires_read_only_shell(role: &FleetRole) -> bool {
762 matches!(
763 role,
764 FleetRole::Scout | FleetRole::Reviewer | FleetRole::Planner
765 )
766 }
767
768 /// The runtime profile a worker of `role` actually runs under: the requested
769 /// profile with the shell narrowed for read-only roles. Receipts and headers
770 /// derive from this, never from the requested profile alone (#5542 review).
771 #[must_use]
772 pub fn effective_runtime_profile_for_role(
773 role: &FleetRole,
774 requested: &WorkerRuntimeProfile,
775 ) -> WorkerRuntimeProfile {
776 let mut effective = requested.clone();
777 if role_requires_read_only_shell(role) && effective.shell.allows_shell() {
778 effective.shell = ShellPolicy::ReadOnly;
779 }
780 effective
781 }
782
783 fn shell_policy_label(shell: ShellPolicy) -> &'static str {
784 match shell {
785 ShellPolicy::None => "none",
786 ShellPolicy::ReadOnly => "read_only",
787 ShellPolicy::Full => "full",
788 }
789 }
790
791 fn tool_scope_label(tools: &ToolScope) -> &'static str {
792 match tools {
793 ToolScope::Inherit => "inherit",
794 ToolScope::Explicit(_) => "explicit",
795 }
796 }
797
798 /// Effective non-secret runtime permissions for a worker of `role` running
799 /// under `requested`. This is the single posture truth for both in-process
800 /// sub-agent snapshots and durable Fleet receipts: the requested profile with
801 /// the shell narrowed for read-only roles. `profile_id` / `profile_origin`
802 /// identify a saved Fleet member when one selected the role; `None` for
803 /// direct role dispatches.
804 #[must_use]
805 pub fn fleet_effective_permissions(
806 role: &FleetRole,
807 requested: &WorkerRuntimeProfile,
808 profile_id: Option<&str>,
809 profile_origin: Option<&str>,
810 ) -> FleetEffectivePermissions {
811 let profile = effective_runtime_profile_for_role(role, requested);
812 FleetEffectivePermissions {
813 write: profile.permissions.write,
814 network: profile.permissions.network,
815 shell: shell_policy_label(profile.shell).to_string(),
816 tool_scope: tool_scope_label(&profile.tools).to_string(),
817 tools: match &profile.tools {
818 ToolScope::Inherit => Vec::new(),
819 ToolScope::Explicit(tools) => tools.clone(),
820 },
821 background: profile.background,
822 max_spawn_depth: profile.max_spawn_depth,
823 profile_id: profile_id.map(str::to_string),
824 profile_origin: profile_origin.map(str::to_string),
825 source: "worker_runtime_profile".to_string(),
826 }
827 }
828
828 lines RUST