返回 CodeWhale
exact.rs
根目录 / crates / engine / src / fleet / exact.rs
1 //! Runtime for an **exact named Fleet** (`schema = "exact"`).
2 //!
3 //! The saved Fleet is the Fleet that runs. At Workflow start its definition is
4 //! read from the standard `FleetSearchRoot` locations, every worker route is
5 //! **preflighted and frozen**, the attached Reasoning Router service is
6 //! resolved, and the whole thing is captured into an immutable
7 //! [`FleetSnapshot`] projected onto the roster/profile machinery the in-process
8 //! spawn path already uses.
9 //!
10 //! Five invariants govern everything below.
11 //!
12 //! 1. **Routes freeze first, and are checked while freezing.** Provider
13 //! identity, canonical wire model, endpoint, local credential readiness, and
14 //! reasoning capability are all resolved before the Workflow starts — and
15 //! certainly before any Router is asked anything. Nothing downstream may
16 //! move them: not a task option, not the Router.
17 //! 2. **Admission comes before cost.** A task is resolved against the roster,
18 //! checked against gates, and given a concurrency slot *before* the Router
19 //! is called. A rejected or capacity-blocked task spends no Router tokens
20 //! and discloses nothing to a Router's provider.
21 //! 3. **Auto is a reasoning decision, and the attached Router makes it.**
22 //! `reasoning = "auto"` always goes to the Fleet's Reasoning Router — no
23 //! provider-native-adaptive bypass, no legacy model routing, no local
24 //! keyword heuristic. A manual tier calls no Router at all.
25 //! 4. **Runtime owns authority.** After exact member selection, Runtime maps
26 //! the semantic role onto its closed role policy and intersects that policy
27 //! with the live parent. Fleet identity never grants or withholds project
28 //! trust, tools, writes, network reach, shell, or delegation.
29 //! 5. **Receipts are truthful and content-free.** The tier a selector picked,
30 //! the control a provider actually receives, and what a Router cost are
31 //! recorded separately; task text never is.
32
33 use std::sync::Arc;
34
35 use async_trait::async_trait;
36 use codewhale_protocol::fleet::PermissionCeiling;
37 #[cfg(test)]
38 use codewhale_protocol::fleet::ShellCeiling;
39 use codewhale_workflow::{
40 CapturedReasoningRouter, CredentialReadiness, EffectiveReasoning, EndpointIdentity,
41 FleetDocument, FleetRouterRef, FleetSearchRoot, FleetSnapshot, FleetSnapshotMember,
42 FleetTaskReceipt, NamedFleetError, PreflightError, PreflightedRoute, ProviderReasoningControl,
43 QualifiedFleetId, ReasoningCapability, ReasoningRouterProfile, ReasoningTier,
44 ResolvedReasoning, RoutePreflight, RouterAvailability, RouterCallInput, RouterCallPlan,
45 RouterIdentity, RoutingDisclosure, bounded_routing_payload, captured_legacy_inline_router,
46 parse_router_decision, resolve_exact_member_reasoning, router_call_plan, router_system_prompt,
47 router_user_message,
48 };
49
50 use crate::llm_client::LlmClient;
51 use crate::reasoning_preference::ReasoningEffort;
52 use codewhale_agent_contract::role::{ChildAuthority, public_role_label};
53 #[cfg(test)]
54 use codewhale_agent_contract::role::{
55 NETWORK_DENIAL_SENTINEL, NETWORK_TOOL_DENYLIST, RAW_SHELL_SENTINEL, is_posture_denial,
56 session_shell_ceiling,
57 };
58 use codewhale_config::ProviderKind;
59 use codewhale_models::Role;
60 use codewhale_runtime::config::Config;
61
62 /// Where exact Fleet definitions and Reasoning Router profiles are looked up,
63 /// labelled so an identity can be qualified (`workspace/glm-pair`) instead of
64 /// silently shadowed.
65 fn personal_fleet_root() -> anyhow::Result<std::path::PathBuf> {
66 codewhale_config::codewhale_home()
67 }
68
69 pub fn personal_fleet_definitions_dir() -> anyhow::Result<std::path::PathBuf> {
70 Ok(personal_fleet_root()?.join("fleets"))
71 }
72
73 /// The workspace has two origins. `workspace` is `<workspace>/.codewhale`, the
74 /// directory the Fleet store saves workspace-scoped Fleets to, so a Fleet
75 /// saved from the Fleet UI is found by name. `workspace_root` is the workspace
76 /// directory itself, which keeps checked-in `fleets/<name>.toml` rosters
77 /// loading as they always have.
78 #[must_use]
79 pub fn fleet_search_roots(workspace: &std::path::Path) -> Vec<FleetSearchRoot> {
80 let mut roots = Vec::new();
81 if let Ok(home) = personal_fleet_root() {
82 roots.push(FleetSearchRoot::new("codewhale_home", home));
83 }
84 roots.push(
85 FleetSearchRoot::new(
86 "workspace",
87 codewhale_util::files::workspace_state_dir(workspace),
88 )
89 .with_reader(super::store::read_repository_fleet_file),
90 );
91 roots.push(
92 FleetSearchRoot::new("workspace_root", workspace.to_path_buf())
93 .with_reader(super::store::read_repository_fleet_file),
94 );
95 roots
96 }
97
98 /// Load a Fleet document by (optionally qualified) name from the standard
99 /// roots. Ambiguity between origins is surfaced, never resolved by shadowing.
100 ///
101 /// Saved v2 Fleets (`schema = "fleet"`, from `.codewhale/fleets/` or
102 /// `$CODEWHALE_HOME/fleets/`) are looked up first and frozen into an exact
103 /// snapshot here — see [`freeze_saved_fleet`]. A miss falls through to the
104 /// workflow crate's legacy/exact loader. A bare name that exists both as a v2
105 /// Fleet and as a legacy/exact file is ambiguous: neither shadows the other,
106 /// and the error names every path. v2 Fleets qualify as `user/<name>` and
107 /// `folder/<name>` (the store's own scope labels); a search-root origin
108 /// (`codewhale_home/`, `workspace/`, `workspace_root/`) reads that root's file
109 /// in whichever form it is.
110 ///
111 /// `config` is the session config the caller preflights with: inheriting
112 /// members resolve against it at this point, immediately before the same
113 /// config preflights the frozen routes, so a receipt names the route that ran.
114 ///
115 /// Synchronous file loading: async callers must run this on the blocking pool.
116 pub fn load_fleet_document(
117 name: &str,
118 workspace: &std::path::Path,
119 config: Option<&Config>,
120 ) -> Result<(FleetDocument, QualifiedFleetId), NamedFleetError> {
121 use super::store::{self, FleetScope};
122
123 let roots = fleet_search_roots(workspace);
124 // Validates the bare name before any path below is built from it.
125 let (origin, bare) = codewhale_workflow::split_qualified_fleet_name(name)?;
126 let store_error = |error: store::FleetStoreError| match error {
127 store::FleetStoreError::NotFound(what) => NamedFleetError::NotFound(what),
128 store::FleetStoreError::Io { path, message } => NamedFleetError::Io { path, message },
129 store::FleetStoreError::Parse { path, message } => NamedFleetError::Parse { path, message },
130 other => NamedFleetError::Parse {
131 path: bare.to_string(),
132 message: other.to_string(),
133 },
134 };
135 let v2_scope = match origin.map(str::to_ascii_lowercase).as_deref() {
136 None => None,
137 Some("user" | "personal") => Some(FleetScope::Personal),
138 Some("folder") => Some(FleetScope::Workspace),
139 // Any other origin names a legacy/exact search root. A saved v2
140 // Fleet can live there too (the personal `fleets/` directory is
141 // shared), so the qualified file is read in whichever form it is.
142 Some(origin) => {
143 let saved = roots
144 .iter()
145 .find(|root| root.origin.eq_ignore_ascii_case(origin))
146 .map(|root| {
147 root.root
148 .join(store::FLEET_DIR)
149 .join(format!("{bare}.toml"))
150 })
151 .filter(|path| store::declares_v2_schema(path));
152 let Some(path) = saved else {
153 return FleetDocument::load_by_name(name, &roots);
154 };
155 let (fleet, scope) = store::load_fleet_at(&path).map_err(store_error)?;
156 return freeze_saved_fleet(&fleet, scope, &path, config);
157 }
158 };
159
160 if let Some(scope) = v2_scope {
161 let (fleet, path) =
162 store::load_fleet_in_scope(bare, scope, workspace).map_err(store_error)?;
163 return freeze_saved_fleet(&fleet, scope, &path, config);
164 }
165
166 // Legacy/exact files under the same bare name, in any root. A v2 file in
167 // the shared personal directory is the store's, not a second Fleet.
168 let file_name = format!("{bare}.toml");
169 let other_forms: Vec<String> = roots
170 .iter()
171 .filter_map(|root| {
172 let path = root.root.join(store::FLEET_DIR).join(&file_name);
173 let schema = store::read_declared_schema(&path)?;
174 (schema.as_deref() != Some(store::FLEET_SCHEMA_KIND))
175 .then(|| format!("{}/{bare} ({})", root.origin, path.display()))
176 })
177 .collect();
178
179 let v2_candidates = store::v2_fleet_candidates(bare, workspace);
180 let v2_labels = || {
181 v2_candidates
182 .iter()
183 .map(|(scope, path)| format!("{}/{bare} ({})", scope.label(), path.display()))
184 };
185 if v2_candidates.len() > 1 || (!v2_candidates.is_empty() && !other_forms.is_empty()) {
186 return Err(NamedFleetError::AmbiguousFleet {
187 name: bare.to_string(),
188 origins: v2_labels().chain(other_forms).collect(),
189 });
190 }
191 match store::load_fleet(bare, workspace) {
192 Ok((fleet, scope, path)) => freeze_saved_fleet(&fleet, scope, &path, config),
193 Err(store::FleetStoreError::NotFound(_)) => FleetDocument::load_by_name(name, &roots),
194 Err(error) => Err(store_error(error)),
195 }
196 }
197
198 /// Freeze a saved v2 Fleet into an exact snapshot document.
199 ///
200 /// Every executable member leaves here with one concrete provider/model and
201 /// one concrete reasoning request: an explicit member pin wins, then the
202 /// Fleet's operator route, then the live session route from `config`. The
203 /// result is rendered as an exact document and parsed by the workflow crate's
204 /// own exact parser, so it passes the same validation as a hand-written exact
205 /// file, and the snapshot hash covers what was frozen. Editing the v2 file
206 /// afterwards changes only the next Workflow.
207 ///
208 /// Member `instructions` and `requires` are refused rather than dropped: the
209 /// exact snapshot has no field for either, and a Workflow that silently ran a
210 /// member without its instructions or capability requirement would not be the
211 /// saved Fleet.
212 fn freeze_saved_fleet(
213 fleet: &super::store::FleetFile,
214 scope: super::store::FleetScope,
215 path: &std::path::Path,
216 config: Option<&Config>,
217 ) -> Result<(FleetDocument, QualifiedFleetId), NamedFleetError> {
218 #[derive(serde::Serialize)]
219 struct FrozenFleet {
220 schema: &'static str,
221 schema_revision: u32,
222 name: String,
223 #[serde(skip_serializing_if = "Option::is_none")]
224 description: Option<String>,
225 members: Vec<FrozenMember>,
226 }
227 #[derive(serde::Serialize)]
228 struct FrozenMember {
229 id: String,
230 role: String,
231 provider: String,
232 model: String,
233 reasoning: String,
234 }
235
236 let slug = fleet.file_slug();
237 let fail = |message: String| NamedFleetError::Parse {
238 path: path.display().to_string(),
239 message,
240 };
241 let operator = fleet.operator.as_ref();
242 // A saved Fleet stores reasoning in the session vocabulary (`xhigh`,
243 // `ultra`, `minimal`, ... — what an imported agent profile carries); the
244 // exact schema names tiers. Map through the same effort-to-tier table the
245 // preflight uses, keep an explicit `auto` as a Router request, and treat a
246 // blank value as absent (inherit), as the selected-Fleet path does.
247 let frozen_reasoning = |raw: Option<&str>| -> Result<Option<String>, String> {
248 let Some(value) = raw.map(str::trim).filter(|value| !value.is_empty()) else {
249 return Ok(None);
250 };
251 let effort =
252 ReasoningEffort::parse_strict(value).map_err(|error| format!("reasoning: {error}"))?;
253 Ok(Some(
254 tier_of(effort)
255 .map_or("auto", ReasoningTier::as_str)
256 .to_string(),
257 ))
258 };
259 let session_route = config
260 .map(|config| {
261 config
262 .active_provider_identity()
263 .map(|identity| (identity.key.to_string(), config.default_model()))
264 })
265 .transpose()
266 .map_err(fail)?;
267 let session_reasoning = || {
268 let effort = config
269 .and_then(Config::reasoning_effort)
270 .map(ReasoningEffort::from_setting)
271 .unwrap_or_default();
272 // A session-level `auto` is per-turn adaptivity, not a Router
273 // request; a frozen member takes the concrete default tier instead.
274 tier_of(effort)
275 .unwrap_or(ReasoningTier::Max)
276 .as_str()
277 .to_string()
278 };
279
280 let mut unsupported = Vec::new();
281 let mut members = Vec::new();
282 for member in fleet.members.iter().filter(|member| !member.shortlist) {
283 let id = member.id.trim().to_string();
284 if member
285 .instructions
286 .as_deref()
287 .is_some_and(|text| !text.trim().is_empty())
288 {
289 unsupported.push(format!("`{id}` has instructions"));
290 }
291 if !member.requires.is_empty() {
292 unsupported.push(format!("`{id}` has requires"));
293 }
294 let (provider, model) = match (&member.provider, &member.model, operator, &session_route) {
295 (Some(provider), Some(model), _, _) => (provider.clone(), model.clone()),
296 (None, None, Some(operator), _) => (operator.provider.clone(), operator.model.clone()),
297 (None, None, None, Some((provider, model))) => (provider.clone(), model.clone()),
298 (None, None, None, None) => {
299 return Err(fail(format!(
300 "member `{id}` inherits the session route, but no session config is \
301 available to resolve it"
302 )));
303 }
304 _ => {
305 return Err(fail(format!(
306 "member `{id}` has a partial provider/model pin"
307 )));
308 }
309 };
310 let reasoning = match frozen_reasoning(member.reasoning.as_deref())
311 .map_err(|error| fail(format!("member `{id}` {error}")))?
312 {
313 Some(tier) => tier,
314 None => frozen_reasoning(operator.and_then(|operator| operator.reasoning.as_deref()))
315 .map_err(|error| fail(format!("operator {error}")))?
316 .unwrap_or_else(session_reasoning),
317 };
318 members.push(FrozenMember {
319 role: member.role_label().to_string(),
320 id,
321 provider,
322 model,
323 reasoning,
324 });
325 }
326 if !unsupported.is_empty() {
327 return Err(fail(format!(
328 "saved Fleet `{}` cannot run as a Workflow Fleet yet: {}. Workflow snapshots freeze \
329 each member's route and reasoning only; remove those fields or run the members \
330 with `agent`.",
331 fleet.name,
332 unsupported.join(", ")
333 )));
334 }
335
336 let frozen = FrozenFleet {
337 schema: codewhale_workflow::EXACT_FLEET_SCHEMA_KIND,
338 schema_revision: codewhale_workflow::EXACT_FLEET_SCHEMA_REVISION,
339 name: slug.clone(),
340 description: fleet.description.clone(),
341 members,
342 };
343 let text = toml::to_string(&frozen)
344 .map_err(|error| fail(format!("failed to freeze saved Fleet: {error}")))?;
345 let document = FleetDocument::from_frozen_saved_fleet(&text, path).map_err(|error| {
346 fail(format!(
347 "saved Fleet `{}` cannot run as a Workflow Fleet: {error}",
348 fleet.name
349 ))
350 })?;
351 Ok((
352 document,
353 QualifiedFleetId {
354 name: slug,
355 origin: scope.label().to_string(),
356 },
357 ))
358 }
359
360 // ── Preflight: freeze the route, and check it while freezing ─────────────────
361
362 /// Derive a route's real reasoning capability from the request shaping the
363 /// client actually performs, rather than from a hand-maintained claims table.
364 ///
365 /// The probe builds the request body this exact route would receive for every
366 /// tier and compares them. Two tiers that produce a byte-identical body are not
367 /// two provider-effective tiers, whatever the selector calls them — this is why
368 /// Z.AI's GLM routes come back as
369 /// [`ProviderReasoningControl::EnabledDisabled`] and why nothing here can claim
370 /// provider-native adaptive for a route whose body does not say so.
371 #[must_use]
372 pub fn reasoning_capability_for_route(
373 provider: ProviderKind,
374 base_url: &str,
375 wire_model: &str,
376 ) -> ReasoningCapability {
377 let body_for = |effort: ReasoningEffort| -> String {
378 let mut body = serde_json::json!({});
379 let value = effort.api_value_for_route(provider, base_url, wire_model);
380 crate::client::reasoning_effort::apply_reasoning_effort(&mut body, value, provider);
381 // `reasoning_split` is a transport concern the client sets for every
382 // tier; it carries no reasoning depth, so it must not make tiers look
383 // distinct or make a no-control route look controllable.
384 if let Some(object) = body.as_object_mut() {
385 object.remove("reasoning_split");
386 }
387 body.to_string()
388 };
389
390 let off = body_for(ReasoningEffort::Off);
391 let above_off: Vec<String> = [
392 ReasoningEffort::Low,
393 ReasoningEffort::Medium,
394 ReasoningEffort::High,
395 ReasoningEffort::Max,
396 ]
397 .into_iter()
398 .map(body_for)
399 .collect();
400
401 let empty = "{}";
402 let all_empty = off == empty && above_off.iter().all(|body| body == empty);
403
404 let mut distinct = above_off.clone();
405 distinct.sort();
406 distinct.dedup();
407
408 let control = if all_empty {
409 ProviderReasoningControl::None
410 } else if distinct.len() == 1 && distinct[0] == off && off.contains("adaptive") {
411 // Every tier — including off — produces the same adaptive body: the
412 // provider genuinely chooses its own depth. Source-backed, not assumed.
413 ProviderReasoningControl::NativeAdaptive
414 } else if distinct.len() > 1 {
415 ProviderReasoningControl::Tiers
416 } else {
417 ProviderReasoningControl::EnabledDisabled
418 };
419
420 // What each requested tier actually becomes on the wire, straight from the
421 // route normalizer that shapes the real request.
422 //
423 // This subsumes a min/max floor-and-ceiling and expresses what one cannot:
424 // most non-Codex routes coerce `low` and `medium` to `high` while leaving
425 // `off` alone (first-party DeepSeek routes are the documented exception —
426 // their wire carries a real `low`), and an always-thinking route raises
427 // `off` instead. Reporting a `low` a route silently sends as `high` is
428 // the invisible substitution receipts exist to prevent, so the map — not
429 // a clamp — is the authority.
430 let wire_tiers = [
431 ReasoningEffort::Off,
432 ReasoningEffort::Low,
433 ReasoningEffort::Medium,
434 ReasoningEffort::High,
435 ReasoningEffort::Max,
436 ]
437 .map(|effort| {
438 tier_of(effort.normalize_for_route(provider, base_url, wire_model))
439 .unwrap_or(ReasoningTier::Off)
440 });
441
442 ReasoningCapability {
443 control,
444 min_tier: None,
445 max_tier: None,
446 wire_tiers: None,
447 }
448 .with_wire_tiers(wire_tiers)
449 }
450
451 fn tier_of(effort: ReasoningEffort) -> Option<ReasoningTier> {
452 match effort {
453 ReasoningEffort::Off => Some(ReasoningTier::Off),
454 ReasoningEffort::Minimal => Some(ReasoningTier::Low),
455 ReasoningEffort::Low => Some(ReasoningTier::Low),
456 ReasoningEffort::Medium => Some(ReasoningTier::Medium),
457 ReasoningEffort::High => Some(ReasoningTier::High),
458 ReasoningEffort::XHigh => Some(ReasoningTier::Max),
459 ReasoningEffort::Ultra => Some(ReasoningTier::Max),
460 ReasoningEffort::Max => Some(ReasoningTier::Max),
461 ReasoningEffort::Auto => None,
462 }
463 }
464
465 /// The **provider-facing** reasoning value for one tier on one exact route.
466 ///
467 /// A tier label (`off`, `max`) is a selector concept; what a request may carry
468 /// is a provider concept, and the two are not the same string. OpenAI Codex
469 /// routes spell the top tier `xhigh` and cannot express `off` at all, so
470 /// placing a bare tier label on a Codex request either sends a value the
471 /// provider does not accept or silently sends nothing and takes the provider
472 /// default while the receipt claims the tier. Reading the value back out of the
473 /// same route normalizer the client uses is what keeps the request and the
474 /// receipt describing each other.
475 #[must_use]
476 pub fn route_reasoning_setting(
477 provider: ProviderKind,
478 base_url: &str,
479 wire_model: &str,
480 tier: ReasoningTier,
481 ) -> String {
482 effort_of(tier)
483 .as_setting_for_route(provider, base_url, wire_model)
484 .to_string()
485 }
486
487 fn effort_of(tier: ReasoningTier) -> ReasoningEffort {
488 match tier {
489 ReasoningTier::Off => ReasoningEffort::Off,
490 ReasoningTier::Low => ReasoningEffort::Low,
491 ReasoningTier::Medium => ReasoningEffort::Medium,
492 ReasoningTier::High => ReasoningEffort::High,
493 ReasoningTier::Max => ReasoningEffort::Max,
494 }
495 }
496
497 /// Preflight one exact route: resolve the provider, canonicalize the model,
498 /// identify the endpoint, decide credential readiness **from local config**,
499 /// and derive the reasoning capability.
500 ///
501 /// No provider is contacted. Everything here is a configuration lookup, which
502 /// is what makes it safe to run before the operator's gates have fired.
503 pub fn preflight_route(
504 member_id: &str,
505 provider: &str,
506 model: &str,
507 config: &Config,
508 ) -> Result<PreflightedRoute, PreflightError> {
509 let identity = config
510 .resolve_provider_identity(provider.trim())
511 .map_err(|detail| PreflightError::ProviderUnresolved {
512 member: member_id.to_string(),
513 provider: provider.to_string(),
514 detail,
515 })?;
516
517 // The canonical wire model, resolved once. The receipt and the child spawn
518 // both read this value, so they cannot disagree about what actually ran.
519 let wire_model = codewhale_config::route::resolve_model(identity.provider, model.trim(), None)
520 .map(|resolved| resolved.logical)
521 .map_err(|_| PreflightError::ModelUnresolved {
522 member: member_id.to_string(),
523 provider: identity.key.to_string(),
524 model: model.to_string(),
525 detail: "not a known model for this provider".to_string(),
526 })?;
527 codewhale_runtime::config::validate_route(identity.provider, &wire_model).map_err(
528 |detail| PreflightError::ModelUnresolved {
529 member: member_id.to_string(),
530 provider: identity.key.to_string(),
531 model: wire_model.clone(),
532 detail,
533 },
534 )?;
535
536 let mut scoped = config.clone();
537 scoped
538 .scope_to_provider_identity(&identity)
539 .map_err(|detail| PreflightError::ProviderUnresolved {
540 member: member_id.to_string(),
541 provider: provider.to_string(),
542 detail,
543 })?;
544 let base_url = scoped.active_route_base_url();
545
546 // Locally decided. A concrete loopback/self-hosted route is keyless by
547 // design, and that is a valid, first-class state — not a downgrade and
548 // not a missing credential. Ollama Cloud is hosted and falls through to
549 // the ordinary credential checks.
550 let credential = if codewhale_runtime::config::provider_route_is_keyless_self_hosted(
551 identity.provider,
552 &base_url,
553 ) {
554 CredentialReadiness::KeylessLocal
555 } else if crate::provider_readiness::has_api_key_for(&scoped, &identity) {
556 CredentialReadiness::Configured
557 } else {
558 // The discriminant only. `Missing { detail }` names the provider table
559 // key, which for a custom route is the customer's own string.
560 codewhale_telemetry::session_counters()
561 .bump_error(codewhale_telemetry::ErrorCounter::AuthPreflightFailed);
562 CredentialReadiness::Missing {
563 detail: format!("no credential configured for `{}`", identity.key),
564 }
565 };
566
567 Ok(PreflightedRoute {
568 member_id: member_id.to_string(),
569 provider_id: identity.key.to_string(),
570 provider_config_id: identity
571 .migrated_legacy_ollama_cloud_route()
572 .then(|| provider.trim().to_string()),
573 provider_kind: if identity.provider == ProviderKind::OllamaCloud {
574 identity.provider.as_str().to_string()
575 } else {
576 format!("{:?}", identity.provider).to_ascii_lowercase()
577 },
578 declared_model: model.trim().to_string(),
579 wire_model: wire_model.clone(),
580 endpoint: EndpointIdentity::from_base_url(&base_url),
581 credential,
582 capability: reasoning_capability_for_route(identity.provider, &base_url, &wire_model),
583 })
584 }
585
586 /// Build the client one worker route would actually run on, and throw it away.
587 ///
588 /// Preflight resolves a route from *configuration*; this proves the same route
589 /// can be turned into a working client — the step that fails on a malformed
590 /// base URL, an unusable auth mode, or a transport CodeWhale cannot construct.
591 /// Doing it at Workflow start, for every member, is what stops a Fleet from
592 /// paying for a Router decision and only then discovering that the worker it
593 /// decided for could never have been launched.
594 ///
595 /// The client is deliberately not retained: the spawn path builds the child's
596 /// own client from the member's roster profile, and keeping a second one here
597 /// would create two objects that could drift apart.
598 fn validate_route_client(route: &PreflightedRoute, config: &Config) -> Result<(), String> {
599 let mut scoped = config.clone();
600 let identity = config.resolve_provider_identity(route.provider_config_id())?;
601 scoped.scope_to_provider_identity(&identity)?;
602 crate::client::CodewhaleClient::new(&scoped)
603 .map(|_| ())
604 .map_err(|error| {
605 format!(
606 "member `{}` is pinned to provider `{}` (model `{}`), whose client could not be \
607 built on this machine: {error}",
608 route.member_id, route.provider_id, route.wire_model
609 )
610 })
611 }
612
613 // ── The Reasoning Router, as a service ──────────────────────────────────────
614
615 /// The seam a Reasoning Router call goes through. Implemented live against the
616 /// provider client, and by a fixture in tests so the whole reasoning path is
617 /// exercised without a network.
618 #[async_trait]
619 pub trait FleetRouterCaller: Send + Sync + std::fmt::Debug {
620 /// Return the router's raw text response for one worker task.
621 async fn decide(&self, input: &RouterCallInput) -> Result<String, String>;
622
623 /// The Router service's exact identity, for the receipt.
624 fn identity(&self) -> RouterIdentity;
625 }
626
627 /// A Reasoning Router bound to its own exact preflighted route.
628 #[derive(Clone)]
629 pub struct LiveFleetRouter {
630 accounting_origin: Option<crate::cost_status::NativeUsageOrigin>,
631 client: crate::client::CodewhaleClient,
632 captured: CapturedReasoningRouter,
633 route: PreflightedRoute,
634 /// The Router route's provider kind and base URL, kept so the call's
635 /// reasoning value can be shaped by the *actual* configured route rather
636 /// than by a generic tier label. Never serialized — the base URL can carry
637 /// a credential and receipts are durable.
638 provider: ProviderKind,
639 base_url: String,
640 /// What the Router call is actually made at, plus the four-sided disclosure
641 /// for the receipt. Configured by the operator (`off` or `low`), normalized
642 /// only against what the Router's own route can express.
643 call: RouterCallPlan,
644 }
645
646 impl std::fmt::Debug for LiveFleetRouter {
647 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
648 f.debug_struct("LiveFleetRouter")
649 .field("router", &self.captured.qualified())
650 .field("provider", &self.route.provider_id)
651 .field("model", &self.route.wire_model)
652 .field("call_reasoning", &self.call.tier)
653 .field("client", &"<redacted>")
654 .finish()
655 }
656 }
657
658 impl LiveFleetRouter {
659 /// Resolve the Router service's exact configured route and build its client.
660 ///
661 /// A Router that cannot be resolved is an error here — at Workflow start,
662 /// before any worker is dispatched — not a silent downgrade to legacy
663 /// routing. Readiness is decided from local configuration; no live probe.
664 pub fn bind(
665 captured: &CapturedReasoningRouter,
666 config: &Config,
667 accounting_origin: Option<crate::cost_status::NativeUsageOrigin>,
668 ) -> Result<Self, RouterBindError> {
669 let route = preflight_route(
670 &captured.id,
671 &captured.route.provider,
672 &captured.route.model,
673 config,
674 )
675 .map_err(|error| RouterBindError {
676 reason: error.to_string(),
677 })?;
678 route.require_ready().map_err(|error| RouterBindError {
679 reason: error.to_string(),
680 })?;
681
682 let identity = config
683 .resolve_provider_identity(route.provider_config_id())
684 .map_err(|detail| RouterBindError {
685 reason: format!(
686 "reasoning router provider `{}` did not resolve: {detail}",
687 route.provider_id
688 ),
689 })?;
690 let mut scoped = config.clone();
691 scoped
692 .scope_to_provider_identity(&identity)
693 .map_err(|reason| RouterBindError { reason })?;
694 let base_url = scoped.active_route_base_url();
695 let client =
696 crate::client::CodewhaleClient::new(&scoped).map_err(|error| RouterBindError {
697 reason: format!(
698 "reasoning router provider `{}` client could not be built: {error}",
699 route.provider_id
700 ),
701 })?;
702
703 let call = router_call_plan(captured.requested_call_reasoning, &route.capability);
704
705 Ok(Self {
706 accounting_origin,
707 client,
708 captured: captured.clone(),
709 route,
710 provider: identity.provider,
711 base_url,
712 call,
713 })
714 }
715
716 /// The preflighted Router route, for cross-provider disclosure.
717 #[must_use]
718 pub fn route(&self) -> &PreflightedRoute {
719 &self.route
720 }
721 }
722
723 #[derive(Debug, Clone, PartialEq, Eq)]
724 pub struct RouterBindError {
725 pub reason: String,
726 }
727
728 #[async_trait]
729 impl FleetRouterCaller for LiveFleetRouter {
730 fn identity(&self) -> RouterIdentity {
731 RouterIdentity::from_captured(
732 &self.captured,
733 Some(&self.route),
734 Some(self.call.disclosure.clone()),
735 )
736 }
737
738 async fn decide(&self, input: &RouterCallInput) -> Result<String, String> {
739 use codewhale_models::{ContentBlock, Message, MessageRequest, SystemPrompt};
740
741 // The bounded, redacted summary is transmitted exactly once, in the
742 // user turn. The system prompt carries the contract and the frozen
743 // route, and no task content at all — sending it twice would double
744 // what leaves for this provider while the receipt counted one copy.
745 let request = MessageRequest {
746 model: self.route.wire_model.clone(),
747 messages: vec![Message {
748 role: Role::User,
749 content: vec![ContentBlock::Text {
750 text: router_user_message(input),
751 cache_control: None,
752 }],
753 }],
754 max_tokens: self
755 .client
756 .effective_max_output_tokens(&self.route.wire_model),
757 system: Some(SystemPrompt::Text(router_system_prompt(input))),
758 // A router receives no tools. Ever.
759 tools: None,
760 tool_choice: None,
761 metadata: None,
762 thinking: None,
763 // The operator-configured call tier remains authoritative. The
764 // normal route allowance above leaves room for its hidden
765 // reasoning before the small JSON answer is emitted.
766 reasoning_effort: Some(route_reasoning_setting(
767 self.provider,
768 &self.base_url,
769 &self.route.wire_model,
770 self.call.tier,
771 )),
772 stream: Some(false),
773 temperature: None,
774 top_p: None,
775 safety_check: None,
776 title: None,
777 };
778
779 let route = self
780 .client
781 .effective_route_envelope(&self.route.wire_model, chrono::Utc::now());
782 let source = crate::cost_status::NativeUsageSource::capture_with_origin(
783 format!("fleet-router:{}", uuid::Uuid::new_v4()),
784 crate::cost_status::UsageSpendOwner::Auxiliary,
785 self.accounting_origin.clone(),
786 );
787 let observation = source.observation();
788 let wire = observation.wire_observations.clone();
789 let response = crate::llm_client::observe_request_retries(
790 Some(observation),
791 self.client.create_message(request),
792 )
793 .await;
794 let wire = wire.drain();
795 let record = source.response_record(&route, &response, &wire);
796 if let Some(origin) = source.origin() {
797 crate::cost_status::record_runtime_usage_async(origin.scope(), Some(origin), &record)
798 .await;
799 }
800 let response = response.map_err(|error| error.to_string())?;
801 if codewhale_models::is_incomplete_stop_reason(response.stop_reason.as_deref()) {
802 return Err(format!(
803 "reasoning router response incomplete: provider stop reason `{}`",
804 codewhale_models::stop_reason_detail(response.stop_reason.as_deref())
805 ));
806 }
807 let text = response
808 .content
809 .into_iter()
810 .filter_map(|block| match block {
811 ContentBlock::Text { text, .. } => Some(text),
812 _ => None,
813 })
814 .collect::<Vec<_>>()
815 .join("");
816 if text.trim().is_empty() {
817 return Err("reasoning router returned an empty response".to_string());
818 }
819 Ok(text)
820 }
821 }
822
823 // ── The Workflow ───────────────────────────────────────────────────────────
824
825 /// An exact Fleet, frozen at Workflow start.
826 ///
827 /// The snapshot and the preflight are immutable for the life of the run:
828 /// editing `fleets/<name>.toml` afterwards changes only the next Workflow.
829 /// Durable runs and in-process spawns bind the same frozen member. The
830 /// in-process path projects only that member onto its existing profile binder;
831 /// it does not read or replace the currently selected Fleet.
832 #[derive(Clone)]
833 pub struct ExactFleetWorkflow {
834 snapshot: Arc<FleetSnapshot>,
835 preflight: Arc<RoutePreflight>,
836 router: Option<Arc<dyn FleetRouterCaller>>,
837 router_unavailable: Option<String>,
838 }
839
840 impl std::fmt::Debug for ExactFleetWorkflow {
841 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
842 f.debug_struct("ExactFleetWorkflow")
843 .field("fleet", &self.snapshot.fleet().qualified())
844 .field("members", &self.snapshot.members().len())
845 .field("router", &self.router.is_some())
846 .finish()
847 }
848 }
849
850 /// Whether `tool` is removed by a deny entry (exact, case-insensitive, or a
851 /// trailing-`*` prefix glob).
852 fn tool_denied_by(tool: &str, denied: &[String]) -> bool {
853 denied.iter().any(|entry| match entry.strip_suffix('*') {
854 Some(prefix) => tool
855 .to_ascii_lowercase()
856 .starts_with(&prefix.to_ascii_lowercase()),
857 None => entry.eq_ignore_ascii_case(tool),
858 })
859 }
860
861 /// Refuse a task whose explicitly requested tools do not all survive the
862 /// role ceiling and deny list (SHA-6734). The error names the requested
863 /// tools, what the role allows, and what was dropped, so the caller can fix
864 /// the request instead of launching a child that flounders without tools.
865 fn refuse_dropped_requested_tools(
866 member_id: &str,
867 member_role: &str,
868 requested: &[String],
869 ceiling: &ChildAuthority,
870 authority: &ChildAuthority,
871 ) -> Result<(), String> {
872 let mut requested: Vec<String> = requested.to_vec();
873 requested.sort();
874 requested.dedup();
875 if requested.is_empty() {
876 // An explicit empty list is a deliberate tool-free child.
877 return Ok(());
878 }
879 let survives = |tool: &String| {
880 authority
881 .allowed_tools
882 .as_ref()
883 .is_none_or(|allowed| allowed.contains(tool))
884 && !tool_denied_by(tool, &authority.disallowed_tools)
885 };
886 let dropped: Vec<&String> = requested.iter().filter(|tool| !survives(tool)).collect();
887 if dropped.is_empty() {
888 return Ok(());
889 }
890 let kept = requested.len() - dropped.len();
891 let role_allows = match ceiling.allowed_tools.as_ref() {
892 Some(allowed) if allowed.is_empty() => "no tools".to_string(),
893 Some(allowed) => format!("[{}]", allowed.join(", ")),
894 None if ceiling.disallowed_tools.is_empty() => "all inherited tools".to_string(),
895 None => format!(
896 "all inherited tools except [{}]",
897 ceiling.disallowed_tools.join(", ")
898 ),
899 };
900 let join = |tools: &[&String]| {
901 tools
902 .iter()
903 .map(|tool| tool.as_str())
904 .collect::<Vec<_>>()
905 .join(", ")
906 };
907 let requested_refs: Vec<&String> = requested.iter().collect();
908 let headline = if kept == 0 {
909 format!("Agent '{member_id}' (role {member_role}) would start with no tools")
910 } else {
911 format!("Agent '{member_id}' (role {member_role}) would lose requested tools")
912 };
913 Err(format!(
914 "{headline}: requested [{}], role allows {role_allows}, dropped [{}]. Request only tools \
915 the role allows, or pick a member whose role carries them.",
916 join(&requested_refs),
917 join(&dropped),
918 ))
919 }
920
921 /// One member, resolved and admitted — but **not yet routed**.
922 ///
923 /// This is the value the caller holds between admission and the Router call.
924 /// Producing it costs nothing: no provider is contacted, so a task that is
925 /// about to be rejected by a gate or blocked on capacity can be resolved
926 /// safely.
927 #[derive(Debug, Clone, PartialEq, Eq)]
928 pub struct ExactMemberBinding {
929 /// Canonical member id from the frozen snapshot.
930 pub member_id: String,
931 /// Semantic role — what gates, handoffs, and records use.
932 pub member_role: String,
933 /// The preflighted, frozen route.
934 pub route: PreflightedRoute,
935 /// Whether this member's reasoning comes from the Router.
936 pub requires_router: bool,
937 /// The clamped authority the child will actually run under.
938 pub authority: ChildAuthority,
939 /// The live session posture this binding was clamped against, kept so the
940 /// launch half can **recompute** the authority instead of trusting the copy
941 /// it was handed. A binding travels across an await point (gates, a
942 /// concurrency slot, a router call); recomputing is what makes a stale or
943 /// tampered authority detectable rather than merely improbable.
944 pub session: PermissionCeiling,
945 /// Source layer captured with the snapshot, never refreshed at spawn.
946 profile_origin: super::roster::ProfileOrigin,
947 task_allowed_tools: Option<Vec<String>>,
948 task_disallowed_tools: Vec<String>,
949 task_worktree_write: bool,
950 }
951
952 impl ExactMemberBinding {
953 /// Task options may narrow the Runtime/parent envelope, never replace the
954 /// frozen identity or grant authority. Preserve the narrowing for the
955 /// independent launch-time recomputation and its durable fingerprint.
956 pub fn narrow_for_task(
957 &mut self,
958 write_authority: Option<&str>,
959 allowed_tools: Option<&[String]>,
960 disallowed_tools: &[String],
961 max_depth: Option<u32>,
962 ) -> Result<(), String> {
963 match write_authority {
964 Some("read_only") => self.session.write = false,
965 Some("workspace_write" | "worktree_write") if !self.authority.ceiling.write => {
966 return Err(format!(
967 "member `{}` is read-only under its Runtime/parent ceiling; a task cannot request write authority via `write_authority`",
968 self.member_id,
969 ));
970 }
971 Some("workspace_write") if self.task_worktree_write => {
972 return Err("a task cannot remove its worktree isolation".to_string());
973 }
974 Some("worktree_write") => self.task_worktree_write = true,
975 Some("workspace_write") | None => {}
976 Some(other) => return Err(format!("invalid task `write_authority` value `{other}`")),
977 }
978 if let Some(depth) = max_depth {
979 self.session.delegation_depth = self.session.delegation_depth.min(depth);
980 }
981 if let Some(tools) = allowed_tools {
982 let mut tools = tools.to_vec();
983 if let Some(previous) = self.task_allowed_tools.as_ref() {
984 tools.retain(|tool| previous.contains(tool));
985 }
986 tools.sort();
987 tools.dedup();
988 self.task_allowed_tools = Some(tools);
989 }
990 self.task_disallowed_tools
991 .extend_from_slice(disallowed_tools);
992 self.task_disallowed_tools.sort();
993 self.task_disallowed_tools.dedup();
994 let authority = self.recompute_authority(&self.member_role);
995 // SHA-6734: narrowing an explicit request against the role ceiling
996 // used to be silent and could start a child with no tools at all.
997 // Every tool the caller asked for by name must survive, or the spawn
998 // is refused with what was asked, allowed, and dropped.
999 if let Some(requested) = allowed_tools {
1000 let ceiling = ChildAuthority::from_runtime_role(&self.member_role, self.session);
1001 refuse_dropped_requested_tools(
1002 &self.member_id,
1003 &self.member_role,
1004 requested,
1005 &ceiling,
1006 &authority,
1007 )?;
1008 }
1009 self.authority = authority;
1010 Ok(())
1011 }
1012
1013 fn recompute_authority(&self, role: &str) -> ChildAuthority {
1014 let mut authority = ChildAuthority::from_runtime_role(role, self.session);
1015 if let Some(tools) = self.task_allowed_tools.as_ref() {
1016 let mut tools = tools.clone();
1017 if let Some(ceiling) = authority.allowed_tools.as_ref() {
1018 tools.retain(|tool| ceiling.contains(tool));
1019 }
1020 authority.allowed_tools = Some(tools);
1021 }
1022 if !self.task_disallowed_tools.is_empty() {
1023 authority
1024 .disallowed_tools
1025 .extend(self.task_disallowed_tools.iter().cloned());
1026 authority.disallowed_tools.sort();
1027 authority.disallowed_tools.dedup();
1028 }
1029 if authority.ceiling.write && self.task_worktree_write {
1030 authority.write_authority = "worktree_write";
1031 }
1032 authority
1033 }
1034
1035 /// Project one preflighted member into the existing profile binder. The
1036 /// saved provider configuration key stays paired with the canonical wire
1037 /// model (including compatibility-migrated provider identities).
1038 pub fn spawn_profile(&self) -> super::profile::AgentProfile {
1039 super::profile::AgentProfile {
1040 native_preset: None,
1041 id: self.member_id.clone(),
1042 display_name: None,
1043 description: None,
1044 requires: Vec::new(),
1045 profile: codewhale_config::FleetProfile {
1046 slot: codewhale_config::FleetSlot::from_name(&self.member_role),
1047 role: codewhale_config::FleetRole {
1048 name: self.member_role.clone(),
1049 ..Default::default()
1050 },
1051 provider: Some(self.route.provider_config_id().to_string()),
1052 model: Some(self.route.wire_model.clone()),
1053 ..Default::default()
1054 },
1055 // Snapshot identity is recorded on the Workflow receipt; profile
1056 // application performs no source-file lookup.
1057 source: std::path::PathBuf::new(),
1058 origin: self.profile_origin,
1059 plugin_authority: None,
1060 }
1061 }
1062 }
1063
1064 /// What a launched exact member resolves to, after routing.
1065 #[derive(Debug, Clone, PartialEq, Eq)]
1066 pub struct ExactMemberLaunch {
1067 /// Canonical member id; also the roster profile id the spawn resolves.
1068 pub member_id: String,
1069 /// Semantic role, preserved for gates/handoffs/records.
1070 pub member_role: String,
1071 /// Frozen provider id.
1072 pub provider: String,
1073 /// Canonical wire model — the same string the receipt records.
1074 pub model: String,
1075 /// Concrete reasoning setting label for the spawn request.
1076 pub thinking: String,
1077 /// The full requested → effective story, for the receipt.
1078 pub reasoning: ResolvedReasoning,
1079 /// The clamped authority the child runs under.
1080 pub authority: ChildAuthority,
1081 /// The durable, visible receipt for this launch.
1082 pub receipt: FleetTaskReceipt,
1083 }
1084
1085 impl ExactFleetWorkflow {
1086 /// Capture a Workflow from a parsed exact Fleet document.
1087 ///
1088 /// Everything that can fail locally fails here, before any worker is
1089 /// dispatched: an unresolvable provider, an unknown model, a missing
1090 /// credential, an unresolvable Reasoning Router profile, or an `auto`
1091 /// member with no usable Router.
1092 pub fn capture(
1093 document: &FleetDocument,
1094 id: QualifiedFleetId,
1095 captured_at: impl Into<String>,
1096 config: Option<&Config>,
1097 search_roots: &[FleetSearchRoot],
1098 accounting_origin: Option<crate::cost_status::NativeUsageOrigin>,
1099 ) -> Result<Self, String> {
1100 let exact = document
1101 .exact()
1102 .ok_or_else(|| "this Fleet is not an exact Fleet".to_string())?;
1103
1104 // Resolve the attached Reasoning Router *reference* into the one
1105 // captured service both forms normalize onto.
1106 let captured_router = match exact.router_ref() {
1107 None => None,
1108 Some(FleetRouterRef::LegacyInline(_)) => captured_legacy_inline_router(exact),
1109 Some(FleetRouterRef::Profile { name }) => {
1110 let (profile, router_id) =
1111 ReasoningRouterProfile::load_by_name(&name, search_roots).map_err(|error| {
1112 format!(
1113 "exact Fleet `{}` references reasoning router `{name}`, which could \
1114 not be loaded: {error}",
1115 id.qualified()
1116 )
1117 })?;
1118 Some(CapturedReasoningRouter::from_profile(
1119 &profile,
1120 router_id.origin,
1121 ))
1122 }
1123 };
1124
1125 // Capture, then immediately verify the hash the receipt will vouch for.
1126 // `capture` computes it, so this can only fail if the value took a
1127 // detour through `Deserialize` — but that is exactly the case a receipt
1128 // must not certify, and checking here means no later caller has to
1129 // remember to.
1130 let snapshot = FleetSnapshot::capture(id, document, captured_at, captured_router.clone())
1131 .and_then(FleetSnapshot::into_verified)
1132 .map_err(|error| error.to_string())?;
1133
1134 // Preflight every worker route before anything else can happen.
1135 let (preflight, router) =
1136 Self::preflight_and_bind(&snapshot, captured_router, config, accounting_origin)?;
1137
1138 let router_unavailable = match (snapshot.router(), &router) {
1139 (Some(_), None) => {
1140 Some("the Fleet's reasoning router could not be bound on this machine".to_string())
1141 }
1142 _ => None,
1143 };
1144
1145 let workflow = Self {
1146 snapshot: Arc::new(snapshot),
1147 preflight: Arc::new(preflight),
1148 router,
1149 router_unavailable,
1150 };
1151 workflow.reject_unusable_auto_members()?;
1152 Ok(workflow)
1153 }
1154
1155 /// Preflight every worker route and bind the Router, or fail the start.
1156 fn preflight_and_bind(
1157 snapshot: &FleetSnapshot,
1158 captured_router: Option<CapturedReasoningRouter>,
1159 config: Option<&Config>,
1160 accounting_origin: Option<crate::cost_status::NativeUsageOrigin>,
1161 ) -> Result<(RoutePreflight, Option<Arc<dyn FleetRouterCaller>>), String> {
1162 let Some(config) = config else {
1163 return Err(format!(
1164 "exact Fleet `{}` cannot start: no session config is available to preflight its \
1165 members' providers and models. An exact Fleet fails closed here rather than \
1166 dispatching a worker onto a route it never verified.",
1167 snapshot.fleet().qualified()
1168 ));
1169 };
1170
1171 let mut workers = Vec::with_capacity(snapshot.members().len());
1172 for member in snapshot.members() {
1173 let route = preflight_route(
1174 &member.id,
1175 &member.route.provider,
1176 &member.route.model,
1177 config,
1178 )
1179 .map_err(|error| {
1180 format!(
1181 "exact Fleet `{}` cannot start: {error}",
1182 snapshot.fleet().qualified()
1183 )
1184 })?;
1185 route.require_ready().map_err(|error| {
1186 format!(
1187 "exact Fleet `{}` cannot start: {error}",
1188 snapshot.fleet().qualified()
1189 )
1190 })?;
1191 workers.push(route);
1192 }
1193
1194 // Every worker client is constructed and validated **before** the
1195 // Router is bound, let alone called. A member whose client cannot be
1196 // built is a start-time failure; discovering it after a Router decision
1197 // means the operator paid for a routing request for a task that could
1198 // never have run.
1199 for route in &workers {
1200 validate_route_client(route, config).map_err(|error| {
1201 format!(
1202 "exact Fleet `{}` cannot start: {error}",
1203 snapshot.fleet().qualified()
1204 )
1205 })?;
1206 }
1207
1208 let mut router: Option<Arc<dyn FleetRouterCaller>> = None;
1209 let mut router_route = None;
1210 if let Some(captured) = &captured_router {
1211 match LiveFleetRouter::bind(captured, config, accounting_origin.clone()) {
1212 Ok(live) => {
1213 router_route = Some(live.route().clone());
1214 router = Some(Arc::new(live));
1215 }
1216 Err(error) => {
1217 // Recorded rather than raised: a Fleet with no `auto`
1218 // member does not need its router to be usable, and
1219 // failing the whole Workflow for an unused service would
1220 // be the wrong trade.
1221 if snapshot.has_auto_member() {
1222 return Err(format!(
1223 "exact Fleet `{}` cannot start: member(s) {} request reasoning \
1224 `auto` but the Fleet's reasoning router is unusable ({}). Fix the \
1225 router profile or pin an explicit reasoning tier — exact Fleets \
1226 never fall back to legacy model routing or a local heuristic.",
1227 snapshot.fleet().qualified(),
1228 snapshot.auto_member_ids().join(", "),
1229 error.reason,
1230 ));
1231 }
1232 }
1233 }
1234 }
1235
1236 Ok((RoutePreflight::new(workers, router_route), router))
1237 }
1238
1239 /// Fail at Workflow start — not at task launch — when a member requests
1240 /// `auto` and the Fleet has no Router it can actually call.
1241 fn reject_unusable_auto_members(&self) -> Result<(), String> {
1242 if !self.snapshot.has_auto_member() || self.router.is_some() {
1243 return Ok(());
1244 }
1245 let reason = self
1246 .router_unavailable
1247 .clone()
1248 .unwrap_or_else(|| "this Fleet references no reasoning router".to_string());
1249 Err(format!(
1250 "exact Fleet `{}` cannot start: member(s) {} request reasoning `auto` but the Fleet's \
1251 reasoning router is unusable ({reason}). Attach a working reasoning router or pin an \
1252 explicit reasoning tier — exact Fleets never fall back to legacy model routing or a \
1253 local heuristic.",
1254 self.snapshot.fleet().qualified(),
1255 self.snapshot.auto_member_ids().join(", "),
1256 ))
1257 }
1258
1259 #[must_use]
1260 pub fn snapshot(&self) -> &Arc<FleetSnapshot> {
1261 &self.snapshot
1262 }
1263
1264 /// Human-readable roster listing for "unknown member" errors.
1265 #[must_use]
1266 pub fn member_names(&self) -> String {
1267 self.snapshot
1268 .members()
1269 .iter()
1270 .map(|member| {
1271 if member.role == member.id {
1272 member.id.clone()
1273 } else {
1274 format!("{} (role {})", member.id, member.role)
1275 }
1276 })
1277 .collect::<Vec<_>>()
1278 .join(", ")
1279 }
1280
1281 /// Resolve a task's `role`/`profile` to one admitted member, **without
1282 /// contacting any provider**.
1283 ///
1284 /// This is deliberately the cheap half of a launch. It runs before gate
1285 /// evaluation and before a concurrency slot is taken, so a task that is
1286 /// about to be rejected or queued costs nothing and discloses nothing.
1287 ///
1288 /// A task that names both a `profile` and a `role` which resolve to
1289 /// different members is **rejected**, not silently resolved by precedence:
1290 /// the two fields would then disagree about who ran, and the receipt could
1291 /// only record one of them.
1292 pub fn bind_member(
1293 &self,
1294 profile: Option<&str>,
1295 role: Option<&str>,
1296 session: PermissionCeiling,
1297 ) -> Result<ExactMemberBinding, String> {
1298 let fleet = self.snapshot.fleet().qualified();
1299 let profile = profile.map(str::trim).filter(|key| !key.is_empty());
1300 let role = role.map(str::trim).filter(|key| !key.is_empty());
1301
1302 let member = match (profile, role) {
1303 (None, None) => {
1304 return Err(format!(
1305 "Fleet `{fleet}` is an exact Fleet: every task must name a member via `role` \
1306 or `profile`. Members: {}",
1307 self.member_names()
1308 ));
1309 }
1310 (Some(profile), None) => self.lookup(profile)?,
1311 (None, Some(role)) => self.lookup(role)?,
1312 (Some(profile), Some(role)) => {
1313 let by_profile = self.lookup(profile)?;
1314 let by_role = self.lookup(role)?;
1315 if by_profile.id != by_role.id {
1316 return Err(format!(
1317 "Fleet `{fleet}`: task names profile `{profile}` (member `{}`) and role \
1318 `{role}` (member `{}`), which are different members. A task must name \
1319 one member; the two fields cannot disagree about who ran.",
1320 by_profile.id, by_role.id
1321 ));
1322 }
1323 by_profile
1324 }
1325 };
1326
1327 let route = self.preflight.worker(&member.id).ok_or_else(|| {
1328 format!(
1329 "Fleet `{fleet}`: member `{}` has no preflighted route",
1330 member.id
1331 )
1332 })?;
1333
1334 Ok(ExactMemberBinding {
1335 member_id: member.id.clone(),
1336 member_role: public_role_label(&member.role),
1337 route: route.clone(),
1338 requires_router: member.requested_reasoning.is_auto(),
1339 authority: ChildAuthority::from_runtime_role(&member.role, session),
1340 session,
1341 profile_origin: match self.snapshot.fleet().origin.as_str() {
1342 "workspace" => super::roster::ProfileOrigin::Workspace,
1343 "codewhale_home" => super::roster::ProfileOrigin::Personal,
1344 _ => super::roster::ProfileOrigin::Config,
1345 },
1346 task_allowed_tools: None,
1347 task_disallowed_tools: Vec::new(),
1348 task_worktree_write: false,
1349 })
1350 }
1351
1352 fn lookup(&self, key: &str) -> Result<&FleetSnapshotMember, String> {
1353 self.snapshot.member_by_id_or_role(key).ok_or_else(|| {
1354 format!(
1355 "unknown exact Fleet member `{key}` in `{}`. Members: {}",
1356 self.snapshot.fleet().qualified(),
1357 self.member_names()
1358 )
1359 })
1360 }
1361
1362 /// Finish an **already admitted** binding: decide only how hard the already
1363 /// frozen model thinks, then build the receipt.
1364 ///
1365 /// This is the half that can cost money. Calling it means the task has
1366 /// already passed its gates and holds a concurrency slot.
1367 pub async fn route_admitted_task(
1368 &self,
1369 binding: &ExactMemberBinding,
1370 task_summary: &str,
1371 ) -> Result<ExactMemberLaunch, String> {
1372 // The receipt built at the end of this function stamps
1373 // `snapshot.content_hash()` as evidence that this launch matched a saved
1374 // definition. Verify the hash actually describes the snapshot *before*
1375 // spending a router call or emitting that claim — an unverified hash is
1376 // not weaker evidence, it is a false receipt.
1377 self.snapshot
1378 .verify_content_hash()
1379 .map_err(|error| error.to_string())?;
1380
1381 let member = self.snapshot.member(&binding.member_id).ok_or_else(|| {
1382 format!(
1383 "Fleet `{}`: member `{}` vanished between admission and launch",
1384 self.snapshot.fleet().qualified(),
1385 binding.member_id
1386 )
1387 })?;
1388
1389 // Recompute authority from Runtime's role policy and the live-parent
1390 // posture this binding was admitted against, and require it to be
1391 // *identical* to the one the binding carries. The snapshot supplies
1392 // identity only; legacy internal `FleetProfilePermissions` input is never
1393 // consulted.
1394 //
1395 // A binding crosses gates, a concurrency wait, and (for `auto` members)
1396 // a router call before it gets here, so "the authority I was handed" and
1397 // "the authority this member actually has" are two different claims. The
1398 // launch below is the value the spawn path consumes, so it must be the
1399 // recomputed one; the equality check is what turns a divergence into a
1400 // refused launch instead of a silently widened child.
1401 let authority = binding.recompute_authority(&member.role);
1402 if authority != binding.authority {
1403 return Err(format!(
1404 "Fleet `{}`: member `{}` resolved a different permission envelope at launch than \
1405 at admission, so the launch is refused. admitted={} launched={}",
1406 self.snapshot.fleet().qualified(),
1407 binding.member_id,
1408 binding.authority.fingerprint(),
1409 authority.fingerprint(),
1410 ));
1411 }
1412
1413 // The route is already frozen and preflighted. Nothing below may move
1414 // it — not a task option, not the Router.
1415 let frozen = binding.route.frozen();
1416 let capability = binding.route.capability;
1417
1418 let availability = self.router_availability();
1419 let mut router_identity = None;
1420 let mut routing_summary: Option<RoutingDisclosure> = None;
1421 let decision = if binding.requires_router {
1422 let router = self.router.as_ref().ok_or_else(|| {
1423 format!(
1424 "member `{}` requests reasoning `auto` but Fleet `{}` has no usable reasoning \
1425 router",
1426 binding.member_id,
1427 self.snapshot.fleet().qualified()
1428 )
1429 })?;
1430 let cross_provider = self.preflight.crosses_providers(&binding.member_id);
1431 let payload = bounded_routing_payload(task_summary).with_cross_provider(cross_provider);
1432 // What actually leaves for the router's provider, recorded so the
1433 // receipt discloses it — counts and hash only, never the text.
1434 routing_summary = Some(payload.disclosure().clone());
1435 router_identity = Some(router.identity());
1436 let input = RouterCallInput {
1437 fleet: self.snapshot.fleet().qualified(),
1438 member_id: binding.member_id.clone(),
1439 frozen: frozen.clone(),
1440 payload,
1441 };
1442 let raw = router.decide(&input).await.map_err(|error| {
1443 format!(
1444 "reasoning router call failed for member `{}`: {error}",
1445 binding.member_id
1446 )
1447 })?;
1448 Some(parse_router_decision(&raw).map_err(|error| {
1449 format!(
1450 "reasoning router returned an unusable decision for member `{}`: {error}",
1451 binding.member_id
1452 )
1453 })?)
1454 } else {
1455 None
1456 };
1457
1458 let reasoning = resolve_exact_member_reasoning(
1459 &binding.member_id,
1460 &frozen,
1461 member.requested_reasoning,
1462 &capability,
1463 &availability,
1464 decision.as_ref(),
1465 router_identity.as_ref(),
1466 )
1467 .map_err(|error| error.to_string())?;
1468
1469 // Every exact launch carries a concrete tier. `auto` is resolved by the
1470 // router above and the literal sentinel never leaves this function.
1471 //
1472 // `NativeAdaptive` is no longer reachable here: removing the bypass
1473 // (so `auto` always asks the router) also removed the one path that
1474 // produced it. It used to be launched as `off`, which mislabelled the
1475 // request — a route choosing its own depth is not a route with thinking
1476 // disabled. Rather than re-introduce that lie, this fails loudly if the
1477 // variant ever comes back.
1478 let thinking = match reasoning.effective() {
1479 EffectiveReasoning::Tier(tier) => effort_of(tier).as_setting().to_string(),
1480 EffectiveReasoning::NativeAdaptive => {
1481 return Err(format!(
1482 "member `{}` resolved to provider-native adaptive reasoning, which an exact \
1483 Fleet launch cannot place on a request. Pin an explicit reasoning tier.",
1484 binding.member_id
1485 ));
1486 }
1487 };
1488
1489 // The durable receipt. Built here, at the one place that knows every
1490 // side of the decision, so no consumer has to re-derive it.
1491 let receipt = FleetTaskReceipt::new(
1492 self.snapshot.fleet().qualified(),
1493 self.snapshot.schema_kind(),
1494 self.snapshot.schema_revision(),
1495 self.snapshot.content_hash(),
1496 binding.member_id.clone(),
1497 binding.member_role.clone(),
1498 &binding.route,
1499 &reasoning,
1500 routing_summary,
1501 binding.authority.ceiling.network_tool,
1502 )
1503 // The fingerprint of the envelope this launch installs, carried on the
1504 // durable receipt so the spawn boundary has something to check against
1505 // rather than a sentinel it can only assume.
1506 .with_authority_fingerprint(authority.fingerprint())
1507 // Semantic role and runtime posture stay two separate facts all the way
1508 // onto the durable receipt: `member_role` is what the operator named
1509 // and what gates key on, `posture_role` is the Runtime baseline role.
1510 // The fingerprint above records the effective parent-narrowed surface.
1511 .with_posture_role(binding.authority.posture_role);
1512
1513 Ok(ExactMemberLaunch {
1514 member_id: binding.member_id.clone(),
1515 member_role: binding.member_role.clone(),
1516 provider: frozen.provider,
1517 model: frozen.model,
1518 thinking,
1519 reasoning,
1520 authority,
1521 receipt,
1522 })
1523 }
1524
1525 fn router_availability(&self) -> RouterAvailability {
1526 match (&self.router, &self.router_unavailable) {
1527 (Some(_), _) => RouterAvailability::Ready,
1528 (None, Some(reason)) => RouterAvailability::Unavailable {
1529 reason: reason.clone(),
1530 },
1531 (None, None) => RouterAvailability::Absent,
1532 }
1533 }
1534 }
1535
1536 // ── Test seams ──────────────────────────────────────────────────────────────
1537
1538 /// A Router that answers with a fixed fixture string, recording what it saw.
1539 ///
1540 /// Test-only: it is how the exact-Fleet reasoning path is exercised end to end
1541 /// without a provider call, and how "the router was never called" is asserted.
1542 #[cfg(any(test, feature = "test-support"))]
1543 #[derive(Debug)]
1544 pub struct StaticFleetRouter {
1545 response: String,
1546 identity: RouterIdentity,
1547 pub seen: std::sync::Mutex<Vec<RouterCallInput>>,
1548 }
1549
1550 #[cfg(any(test, feature = "test-support"))]
1551 impl StaticFleetRouter {
1552 pub fn new(response: impl Into<String>) -> Arc<Self> {
1553 Arc::new(Self {
1554 response: response.into(),
1555 identity: RouterIdentity {
1556 id: "luna-low".to_string(),
1557 origin: "workspace".to_string(),
1558 service_kind: codewhale_workflow::REASONING_ROUTER_SERVICE_KIND.to_string(),
1559 legacy_inline: false,
1560 provider: "openai".to_string(),
1561 model: "gpt-5.6-luna".to_string(),
1562 endpoint: Some(EndpointIdentity::from_base_url("https://api.openai.com/v1")),
1563 call: Some(
1564 router_call_plan(
1565 codewhale_workflow::RouterCallReasoning::Low,
1566 &ReasoningCapability::tiered(),
1567 )
1568 .disclosure,
1569 ),
1570 },
1571 seen: std::sync::Mutex::new(Vec::new()),
1572 })
1573 }
1574
1575 /// How many router calls were made. Zero is the assertion that matters for
1576 /// manual reasoning and for rejected/blocked tasks.
1577 pub fn call_count(&self) -> usize {
1578 self.seen.lock().expect("router log").len()
1579 }
1580 }
1581
1582 #[cfg(any(test, feature = "test-support"))]
1583 #[async_trait]
1584 impl FleetRouterCaller for StaticFleetRouter {
1585 fn identity(&self) -> RouterIdentity {
1586 self.identity.clone()
1587 }
1588
1589 async fn decide(&self, input: &RouterCallInput) -> Result<String, String> {
1590 self.seen.lock().expect("router log").push(input.clone());
1591 Ok(self.response.clone())
1592 }
1593 }
1594
1595 #[cfg(any(test, feature = "test-support"))]
1596 impl ExactFleetWorkflow {
1597 /// Build a Workflow with an injected Router and a supplied capability,
1598 /// skipping provider binding so the reasoning path runs with no network and
1599 /// no configured provider.
1600 /// Takes the concrete fixture type rather than `Option<Arc<dyn ...>>`:
1601 /// `Option` does not coerce its payload, so the unsizing is done once here
1602 /// instead of at every call site.
1603 pub fn for_tests(
1604 document: &FleetDocument,
1605 id: QualifiedFleetId,
1606 router: Option<Arc<StaticFleetRouter>>,
1607 ) -> Self {
1608 Self::for_tests_with_capability(document, id, router, ReasoningCapability::tiered())
1609 }
1610
1611 pub fn for_tests_with_capability(
1612 document: &FleetDocument,
1613 id: QualifiedFleetId,
1614 router: Option<Arc<StaticFleetRouter>>,
1615 capability: ReasoningCapability,
1616 ) -> Self {
1617 let exact = document.exact().expect("exact Fleet");
1618 let captured = captured_legacy_inline_router(exact).or_else(|| {
1619 exact.reasoning_router.as_ref().map(|name| {
1620 CapturedReasoningRouter::from_profile(
1621 &ReasoningRouterProfile::parse(&format!(
1622 "name = \"{name}\"\nschema = \"reasoning_router\"\nprovider = \
1623 \"openai\"\nmodel = \"gpt-5.6-luna\"\ncall_reasoning = \"low\"\n"
1624 ))
1625 .expect("router profile"),
1626 "workspace",
1627 )
1628 })
1629 });
1630 let snapshot =
1631 FleetSnapshot::capture(id, document, "2026-07-26T00:00:00Z", captured.clone())
1632 .expect("valid roster");
1633
1634 let workers = snapshot
1635 .members()
1636 .iter()
1637 .map(|member| {
1638 test_route(
1639 &member.id,
1640 &member.route.provider,
1641 &member.route.model,
1642 capability,
1643 )
1644 })
1645 .collect::<Vec<_>>();
1646 let router_route = captured.as_ref().map(|captured| {
1647 test_route(
1648 "router",
1649 &captured.route.provider,
1650 &captured.route.model,
1651 capability,
1652 )
1653 });
1654 let preflight = RoutePreflight::new(workers, router_route);
1655
1656 Self {
1657 snapshot: Arc::new(snapshot),
1658 preflight: Arc::new(preflight),
1659 router: router.map(|router| {
1660 let router: Arc<dyn FleetRouterCaller> = router;
1661 router
1662 }),
1663 router_unavailable: None,
1664 }
1665 }
1666
1667 /// A Workflow whose Router failed to bind locally — the shape
1668 /// [`Self::capture`] produces when a Router's provider has no credentials
1669 /// configured on this machine. No network is involved either way.
1670 pub fn for_tests_with_unavailable_router(
1671 document: &FleetDocument,
1672 id: QualifiedFleetId,
1673 reason: &str,
1674 ) -> Result<Self, String> {
1675 let mut workflow = Self::for_tests(document, id, None);
1676 workflow.router_unavailable = Some(reason.to_string());
1677 workflow.reject_unusable_auto_members()?;
1678 Ok(workflow)
1679 }
1680 }
1681
1682 #[cfg(any(test, feature = "test-support"))]
1683 fn test_route(
1684 member: &str,
1685 provider: &str,
1686 model: &str,
1687 capability: ReasoningCapability,
1688 ) -> PreflightedRoute {
1689 PreflightedRoute {
1690 member_id: member.to_string(),
1691 provider_id: provider.to_string(),
1692 provider_config_id: None,
1693 provider_kind: provider.to_string(),
1694 declared_model: model.to_string(),
1695 wire_model: model.to_string(),
1696 endpoint: EndpointIdentity::from_base_url("https://api.example.test/v1"),
1697 credential: CredentialReadiness::Configured,
1698 capability,
1699 }
1700 }
1701
1702 #[cfg(test)]
1703 mod shell_ceiling_tests {
1704 use super::*;
1705
1706 fn ceiling(write: bool, shell: ShellCeiling) -> PermissionCeiling {
1707 PermissionCeiling {
1708 write,
1709 network_tool: false,
1710 shell,
1711 delegation_depth: 0,
1712 tools: true,
1713 }
1714 }
1715
1716 fn session() -> PermissionCeiling {
1717 ceiling(true, ShellCeiling::Full)
1718 }
1719
1720 fn denies_raw_shell(authority: &ChildAuthority) -> bool {
1721 authority
1722 .disallowed_tools
1723 .iter()
1724 .any(|rule| rule == RAW_SHELL_SENTINEL)
1725 }
1726
1727 /// The `analyst` preset grants no shell. The envelope reads its shell bit
1728 /// back off the deny list, so the denial has to actually be installed —
1729 /// otherwise a shell-less ceiling reaches dispatch claiming full shell
1730 /// authority and can start a verification process.
1731 #[test]
1732 fn a_shell_less_ceiling_installs_the_raw_shell_denial() {
1733 for shell in [ShellCeiling::None, ShellCeiling::ReadOnly] {
1734 let authority = ChildAuthority::clamp(ceiling(false, shell), session());
1735 assert!(
1736 denies_raw_shell(&authority),
1737 "{shell:?} must deny raw shell"
1738 );
1739 }
1740 }
1741
1742 /// The gap this repair closed: a write-capable member inside a session with
1743 /// no shell authority clamps to `write = true, shell = none`. Keying the
1744 /// denial on `write` alone left that combination with no denial installed —
1745 /// and therefore with an envelope that claimed shell authority the ceiling
1746 /// had refused.
1747 #[test]
1748 fn a_write_capable_member_clamped_to_no_shell_still_loses_raw_shell() {
1749 let authority = ChildAuthority::clamp(
1750 ceiling(true, ShellCeiling::Full),
1751 ceiling(true, ShellCeiling::None),
1752 );
1753
1754 assert_eq!(authority.ceiling.shell, ShellCeiling::None);
1755 assert!(authority.ceiling.write, "the write half is unchanged");
1756 assert!(denies_raw_shell(&authority));
1757 }
1758
1759 /// Prior behavior preserved: a `verifier`/`tester` ceiling
1760 /// (`write = false, shell = "full"`) still loses raw shell, and a fully
1761 /// write-capable member still keeps it.
1762 #[test]
1763 fn the_existing_verifier_and_full_ceilings_are_unchanged() {
1764 let verifier = ChildAuthority::clamp(ceiling(false, ShellCeiling::Full), session());
1765 assert!(denies_raw_shell(&verifier));
1766 assert_eq!(verifier.posture_role, "test");
1767
1768 let full = ChildAuthority::clamp(ceiling(true, ShellCeiling::Full), session());
1769 assert!(!denies_raw_shell(&full));
1770 assert_eq!(full.posture_role, "implement");
1771 }
1772
1773 #[test]
1774 fn bounded_inspection_role_keeps_only_classifier_bounded_bash() {
1775 for role in ["scout", "reviewer", "planner"] {
1776 let authority = ChildAuthority::from_runtime_role(role, session());
1777 assert!(
1778 !authority
1779 .disallowed_tools
1780 .iter()
1781 .any(|name| name.eq_ignore_ascii_case("Bash")),
1782 "{role} keeps canonical Bash for per-input classification"
1783 );
1784 for denied in [
1785 "exec_shell",
1786 "task_shell_start",
1787 "task_shell_wait",
1788 "terminal_*",
1789 "terminal/*",
1790 "write_file",
1791 "apply_patch",
1792 ] {
1793 assert!(
1794 authority.disallowed_tools.iter().any(|name| name == denied),
1795 "{role} must still deny {denied}: {:?}",
1796 authority.disallowed_tools
1797 );
1798 }
1799 }
1800
1801 for role in ["consultant", "verifier"] {
1802 let authority = ChildAuthority::from_runtime_role(role, session());
1803 assert!(
1804 authority
1805 .disallowed_tools
1806 .iter()
1807 .any(|name| name.eq_ignore_ascii_case("Bash")),
1808 "{role} must not gain the read-only inspection exception"
1809 );
1810 }
1811
1812 let parent_shell_off =
1813 ChildAuthority::from_runtime_role("scout", ceiling(true, ShellCeiling::None));
1814 assert!(
1815 parent_shell_off
1816 .disallowed_tools
1817 .iter()
1818 .any(|name| name.eq_ignore_ascii_case("Bash")),
1819 "a named Scout may not turn a parent shell-off ceiling into ReadOnly"
1820 );
1821 let planner_parent_shell_off =
1822 ChildAuthority::from_runtime_role("planner", ceiling(true, ShellCeiling::None));
1823 assert!(
1824 planner_parent_shell_off
1825 .disallowed_tools
1826 .iter()
1827 .any(|name| name.eq_ignore_ascii_case("Bash")),
1828 "a named planner may not turn a parent shell-off ceiling into ReadOnly"
1829 );
1830 assert_eq!(planner_parent_shell_off.posture_role, "planner");
1831 assert_eq!(
1832 session_shell_ceiling(
1833 codewhale_agent_contract::worker_profile::ShellPolicy::Full,
1834 false
1835 ),
1836 ShellCeiling::None
1837 );
1838 }
1839
1840 /// #5426 acceptance 2, made mechanical: delegation moves work, never
1841 /// authority. A read-only scout's own runtime posture is the "session"
1842 /// its children clamp against, so a Runtime `builder` dispatched from a
1843 /// read-only parent lands read-only — raw shell gone and mutating tools
1844 /// denied — while the Runtime posture remains separately identified and delegation stays
1845 /// available (the depth budget is the parent's, not zero). The escape
1846 /// hatch is work capacity, never a wider envelope.
1847 #[test]
1848 fn a_read_only_parents_delegation_never_widens_authority() {
1849 // The scout's live runtime posture, expressed as the session ceiling
1850 // a child clamps against: no writes, read-only shell, network kept,
1851 // one level of delegation budget left.
1852 let scout_runtime = PermissionCeiling {
1853 write: false,
1854 network_tool: true,
1855 shell: ShellCeiling::ReadOnly,
1856 delegation_depth: 1,
1857 tools: true,
1858 };
1859 let authority = ChildAuthority::from_runtime_role("builder", scout_runtime);
1860
1861 // Authority does not widen through delegation: the child is read-only.
1862 assert!(!authority.ceiling.write);
1863 assert_eq!(authority.ceiling.shell, ShellCeiling::ReadOnly);
1864 assert_eq!(authority.write_authority, "read_only");
1865 assert_eq!(authority.posture_role, "implement");
1866 assert!(denies_raw_shell(&authority));
1867 for mutating in ["write_file", "apply_patch"] {
1868 assert!(
1869 authority
1870 .disallowed_tools
1871 .iter()
1872 .any(|rule| rule == mutating),
1873 "{mutating} must stay denied for a scout-delegated builder: {:?}",
1874 authority.disallowed_tools
1875 );
1876 }
1877
1878 // The escape hatch itself stays open: delegation is still possible
1879 // (the parent's budget is intact). But it is useless for shell:
1880 // canonical Bash is denied to a delegated child (it is not a bounded
1881 // inspection role), so a scout can never obtain bash by spawning —
1882 // the scout's own bounded read-only Bash from #5428 is the only shell
1883 // path a read-only parent has.
1884 assert_eq!(authority.max_depth, 1);
1885 assert!(
1886 authority
1887 .disallowed_tools
1888 .iter()
1889 .any(|name| name.eq_ignore_ascii_case("Bash")),
1890 "a scout-delegated child must not gain canonical Bash: {:?}",
1891 authority.disallowed_tools
1892 );
1893 }
1894
1895 /// The deny list feeds the fingerprint, so a ceiling that now denies more
1896 /// must fingerprint differently from one that does not. Two postures that
1897 /// install different surfaces may never share a fingerprint.
1898 #[test]
1899 fn the_shell_denial_is_visible_in_the_fingerprint() {
1900 let no_shell = ChildAuthority::clamp(ceiling(false, ShellCeiling::None), session());
1901 let full = ChildAuthority::clamp(ceiling(true, ShellCeiling::Full), session());
1902
1903 assert_ne!(no_shell.fingerprint(), full.fingerprint());
1904 assert!(no_shell.fingerprint().contains("shell=none"));
1905 }
1906
1907 /// Every rule the shell clamp installs is a *posture* denial, so a
1908 /// grandchild spawned with `inherit_disallowed_tools: false` cannot drop it.
1909 #[test]
1910 fn the_installed_shell_denials_are_posture_denials() {
1911 let authority = ChildAuthority::clamp(ceiling(false, ShellCeiling::None), session());
1912 for rule in &authority.disallowed_tools {
1913 assert!(is_posture_denial(rule), "{rule} must be a posture denial");
1914 }
1915 }
1916 }
1917
1918 #[cfg(test)]
1919 mod tests {
1920 use super::*;
1921 use codewhale_workflow::{
1922 EffectiveReasoningSource, ProviderEffectiveReasoning, RequestedReasoning,
1923 };
1924
1925 /// A Fleet that references a saved, reusable Reasoning Router service.
1926 const GLM_FLEET: &str = r#"
1927 name = "glm-pair"
1928 schema = "exact"
1929 reasoning_router = "luna-low"
1930
1931 [[members]]
1932 id = "implementer"
1933 role = "builder"
1934 provider = "zai"
1935 model = "glm-5"
1936 reasoning = "auto"
1937 permissions = "read_write"
1938
1939 [[members]]
1940 id = "auditor"
1941 role = "reviewer"
1942 provider = "zai"
1943 model = "glm-5"
1944 reasoning = "high"
1945 permissions = "read_only"
1946 "#;
1947
1948 fn id() -> QualifiedFleetId {
1949 QualifiedFleetId {
1950 name: "glm-pair".to_string(),
1951 origin: "workspace".to_string(),
1952 }
1953 }
1954
1955 fn full_session() -> PermissionCeiling {
1956 PermissionCeiling {
1957 write: true,
1958 network_tool: true,
1959 shell: ShellCeiling::Full,
1960 delegation_depth: codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH,
1961 tools: true,
1962 }
1963 }
1964
1965 /// Takes the concrete fixture type: `Option` does not coerce its payload,
1966 /// so the unsizing to `Arc<dyn FleetRouterCaller>` is spelled out here once
1967 /// rather than at every call site.
1968 fn workflow_with(router: Option<Arc<StaticFleetRouter>>, text: &str) -> ExactFleetWorkflow {
1969 let document = FleetDocument::parse(text).expect("parse");
1970 ExactFleetWorkflow::for_tests(&document, id(), router)
1971 }
1972
1973 #[tokio::test]
1974 async fn an_auto_member_takes_a_reasoning_only_router_decision_on_a_frozen_route() {
1975 let router = StaticFleetRouter::new(r#"{"reasoning":"max"}"#);
1976 let workflow = workflow_with(Some(router.clone()), GLM_FLEET);
1977
1978 let binding = workflow
1979 .bind_member(None, Some("builder"), full_session())
1980 .expect("role resolves");
1981 assert_eq!(
1982 router.call_count(),
1983 0,
1984 "binding a member must not cost a router call"
1985 );
1986
1987 let launch = workflow
1988 .route_admitted_task(&binding, "refactor three crates")
1989 .await
1990 .expect("auto resolves through the router");
1991
1992 // The route did not move.
1993 assert_eq!(launch.provider, "zai");
1994 assert_eq!(launch.model, "glm-5");
1995 assert_eq!(launch.thinking, "max");
1996 assert_eq!(launch.member_id, "implementer");
1997 assert_eq!(launch.member_role, "implement");
1998 assert_eq!(launch.reasoning.requested(), RequestedReasoning::Auto);
1999 assert_eq!(
2000 launch.reasoning.source(),
2001 EffectiveReasoningSource::FleetRouter
2002 );
2003
2004 // The router saw the frozen route as context, never as a question, and
2005 // received the bounded payload rather than the raw task.
2006 let seen = router.seen.lock().expect("log");
2007 assert_eq!(seen.len(), 1);
2008 assert_eq!(seen[0].frozen.model, "glm-5");
2009 assert_eq!(seen[0].member_id, "implementer");
2010 assert_eq!(seen[0].payload.text(), "refactor three crates");
2011 }
2012
2013 /// The semantic role must survive onto the launch and the receipt: a gate
2014 /// or handoff keyed on `builder` has to still see `builder` even though the
2015 /// roster resolves the distinct profile id `implementer`.
2016 #[tokio::test]
2017 async fn the_semantic_role_survives_while_the_id_addresses_the_roster() {
2018 let workflow = workflow_with(
2019 Some(StaticFleetRouter::new(r#"{"reasoning":"low"}"#)),
2020 GLM_FLEET,
2021 );
2022
2023 let binding = workflow
2024 .bind_member(None, Some("reviewer"), full_session())
2025 .expect("role lookup");
2026 assert_eq!(binding.member_id, "auditor");
2027 assert_eq!(binding.member_role, "reviewer");
2028
2029 let launch = workflow
2030 .route_admitted_task(&binding, "read the diff")
2031 .await
2032 .expect("launch");
2033 assert_eq!(launch.receipt.member_id, "auditor");
2034 assert_eq!(
2035 launch.receipt.member_role, "reviewer",
2036 "the receipt records the semantic role, not the profile id"
2037 );
2038
2039 // The snapshot is addressed by id; the role is the semantic label.
2040 let member = workflow
2041 .snapshot()
2042 .member("auditor")
2043 .expect("snapshot entry");
2044 assert_eq!(member.role, "reviewer");
2045 }
2046
2047 /// A task that names a profile and a role belonging to different members is
2048 /// rejected — the two fields cannot disagree about who ran.
2049 #[test]
2050 fn a_conflicting_task_role_and_profile_is_rejected() {
2051 let workflow = workflow_with(None, GLM_FLEET);
2052
2053 let err = workflow
2054 .bind_member(Some("implementer"), Some("reviewer"), full_session())
2055 .expect_err("conflicting identity");
2056 assert!(err.contains("different members"), "{err}");
2057 assert!(err.contains("implementer"), "{err}");
2058 assert!(err.contains("auditor"), "{err}");
2059
2060 // Agreeing fields are fine: id plus that member's own role.
2061 let binding = workflow
2062 .bind_member(Some("implementer"), Some("builder"), full_session())
2063 .expect("agreeing identity");
2064 assert_eq!(binding.member_id, "implementer");
2065 }
2066
2067 /// Manual reasoning uses no Router at all — not a call whose answer is
2068 /// discarded, but zero calls.
2069 #[tokio::test]
2070 async fn an_explicit_tier_member_never_calls_the_router() {
2071 let router = StaticFleetRouter::new(r#"{"reasoning":"off"}"#);
2072 let workflow = workflow_with(Some(router.clone()), GLM_FLEET);
2073
2074 let binding = workflow
2075 .bind_member(Some("auditor"), None, full_session())
2076 .expect("bind");
2077 assert!(!binding.requires_router);
2078
2079 let launch = workflow
2080 .route_admitted_task(&binding, "read the diff")
2081 .await
2082 .expect("explicit tier");
2083
2084 assert_eq!(launch.thinking, "high");
2085 assert_eq!(
2086 launch.reasoning.source(),
2087 EffectiveReasoningSource::MemberExplicit
2088 );
2089 assert_eq!(
2090 router.call_count(),
2091 0,
2092 "an explicit tier must not spend a router call"
2093 );
2094 assert!(launch.receipt.router.is_none());
2095 assert!(launch.receipt.routing_summary.is_none());
2096 assert!(!launch.receipt.cross_provider_inference);
2097 }
2098
2099 /// A task that never reaches admission must never reach the Router. This
2100 /// is the shape of a gate rejection or a capacity block: the caller binds,
2101 /// decides not to proceed, and no provider was contacted.
2102 #[test]
2103 fn a_task_that_is_never_admitted_costs_no_router_call() {
2104 let router = StaticFleetRouter::new(r#"{"reasoning":"max"}"#);
2105 let workflow = workflow_with(Some(router.clone()), GLM_FLEET);
2106
2107 // Unknown member: rejected during binding, before any cost.
2108 assert!(
2109 workflow
2110 .bind_member(None, Some("wizard"), full_session())
2111 .is_err()
2112 );
2113 // Conflicting identity: likewise.
2114 assert!(
2115 workflow
2116 .bind_member(Some("implementer"), Some("reviewer"), full_session())
2117 .is_err()
2118 );
2119 // A valid binding that the caller then abandons (gate reject / no slot).
2120 let _binding = workflow
2121 .bind_member(None, Some("builder"), full_session())
2122 .expect("valid binding");
2123
2124 assert_eq!(
2125 router.call_count(),
2126 0,
2127 "no router call may happen before a task is admitted"
2128 );
2129 }
2130
2131 #[tokio::test]
2132 async fn a_router_that_tries_to_move_the_route_fails_the_launch() {
2133 let workflow = workflow_with(
2134 Some(StaticFleetRouter::new(
2135 r#"{"reasoning":"max","model":"glm-4"}"#,
2136 )),
2137 GLM_FLEET,
2138 );
2139 let binding = workflow
2140 .bind_member(None, Some("builder"), full_session())
2141 .expect("bind");
2142
2143 let err = workflow
2144 .route_admitted_task(&binding, "anything")
2145 .await
2146 .expect_err("a route mutation must fail the launch");
2147 assert!(err.contains("frozen"), "{err}");
2148 }
2149
2150 #[tokio::test]
2151 async fn a_duplicate_reasoning_key_fails_the_launch() {
2152 let workflow = workflow_with(
2153 Some(StaticFleetRouter::new(
2154 r#"{"reasoning":"off","reasoning":"max"}"#,
2155 )),
2156 GLM_FLEET,
2157 );
2158 let binding = workflow
2159 .bind_member(None, Some("builder"), full_session())
2160 .expect("bind");
2161
2162 let err = workflow
2163 .route_admitted_task(&binding, "anything")
2164 .await
2165 .expect_err("duplicate key");
2166 assert!(err.contains("more than once"), "{err}");
2167 }
2168
2169 #[test]
2170 fn a_missing_router_fails_before_any_worker_is_dispatched() {
2171 let router_less = GLM_FLEET.replace("reasoning_router = \"luna-low\"\n", "");
2172 let document = FleetDocument::parse(&router_less).expect("parse");
2173 let workflow = ExactFleetWorkflow::for_tests(&document, id(), None);
2174
2175 let err = workflow
2176 .reject_unusable_auto_members()
2177 .expect_err("auto without a router must not start");
2178 assert!(err.contains("implementer"), "{err}");
2179 assert!(err.contains("reasoning router"), "{err}");
2180 assert!(
2181 err.contains("never fall back"),
2182 "the error must rule out legacy fallback: {err}"
2183 );
2184 }
2185
2186 #[test]
2187 fn a_fleet_with_no_auto_member_starts_without_a_router() {
2188 let text = r#"
2189 name = "pinned"
2190 schema = "exact"
2191
2192 [[members]]
2193 id = "auditor"
2194 provider = "zai"
2195 model = "glm-5"
2196 reasoning = "high"
2197 permissions = "read_only"
2198 "#;
2199 let document = FleetDocument::parse(text).expect("parse");
2200 let workflow = ExactFleetWorkflow::for_tests(
2201 &document,
2202 QualifiedFleetId {
2203 name: "pinned".to_string(),
2204 origin: "workspace".to_string(),
2205 },
2206 None,
2207 );
2208 workflow
2209 .reject_unusable_auto_members()
2210 .expect("no auto member means no router requirement");
2211 assert_eq!(workflow.snapshot().members().len(), 1);
2212 }
2213
2214 /// A Router whose credentials are locally absent fails the Workflow before
2215 /// any worker is dispatched — decided from local config, never from a live
2216 /// probe of the provider.
2217 #[test]
2218 fn a_locally_unusable_router_fails_before_any_worker_is_dispatched() {
2219 let document = FleetDocument::parse(GLM_FLEET).expect("parse");
2220 let err = ExactFleetWorkflow::for_tests_with_unavailable_router(
2221 &document,
2222 id(),
2223 "no credential configured for `openai`",
2224 )
2225 .expect_err("an unusable router must not start an auto Fleet");
2226
2227 assert!(err.contains("cannot start"), "{err}");
2228 assert!(err.contains("implementer"), "{err}");
2229 assert!(err.contains("no credential configured"), "{err}");
2230 assert!(err.contains("never fall back"), "{err}");
2231 }
2232
2233 #[test]
2234 fn the_frozen_route_pins_each_members_exact_provider_and_model() {
2235 let workflow = workflow_with(None, GLM_FLEET);
2236 let route = workflow
2237 .preflight
2238 .worker("implementer")
2239 .expect("preflighted worker");
2240
2241 assert_eq!(route.provider_id, "zai");
2242 assert_eq!(route.wire_model, "glm-5");
2243 let member = workflow
2244 .snapshot()
2245 .member("implementer")
2246 .expect("snapshot entry");
2247 assert!(
2248 member.requested_reasoning.is_auto(),
2249 "reasoning is decided per task, not baked into the frozen route"
2250 );
2251 }
2252
2253 /// Binding carries route and Runtime role, but no Fleet-owned authority.
2254 #[test]
2255 fn bound_members_use_runtime_roles_and_neutral_compatibility_fields() {
2256 let workflow = workflow_with(None, GLM_FLEET);
2257 for (id, expected_posture, expected_write) in [
2258 ("auditor", "reviewer", "read_only"),
2259 ("implementer", "implement", "workspace_write"),
2260 ] {
2261 let binding = workflow
2262 .bind_member(Some(id), None, full_session())
2263 .expect("bind");
2264 assert_eq!(
2265 binding.authority.posture_role, expected_posture,
2266 "{id} must resolve through Runtime's closed role policy"
2267 );
2268 assert_eq!(
2269 binding.authority.write_authority, expected_write,
2270 "{id} authority comes from the role posture, never a Fleet permissions block"
2271 );
2272 }
2273 }
2274
2275 /// #5575: a free-form member role keeps its identity and **fails closed**.
2276 ///
2277 /// This test previously asserted the opposite — `posture_role == "custom"`
2278 /// and `write_authority == "workspace_write"` — which is exactly the defect:
2279 /// `audit-lead` is a name nobody declared, and the exact driver answered it
2280 /// with the widest posture there is while the durable driver answered the
2281 /// same class of name with `general`. Identity is still preserved verbatim
2282 /// (`member_role`), but an undeclared label now buys the narrowest useful
2283 /// posture, not write authority.
2284 #[test]
2285 fn a_free_form_member_role_fails_closed_without_losing_identity() {
2286 const AUDIT_FLEET: &str = r#"
2287 name = "audit"
2288 schema = "exact"
2289
2290 [[members]]
2291 id = "auditor-one"
2292 role = "audit-lead"
2293 provider = "zai"
2294 model = "glm-5"
2295 permissions = "read_only"
2296 "#;
2297 let workflow = workflow_with(None, AUDIT_FLEET);
2298 let binding = workflow
2299 .bind_member(Some("auditor-one"), None, full_session())
2300 .expect("bind");
2301
2302 assert_eq!(binding.member_role, "audit-lead");
2303 assert_eq!(binding.authority.posture_role, "explore");
2304 assert_eq!(
2305 binding.authority.write_authority, "read_only",
2306 "an undeclared role name must never grant write authority; an \
2307 operator who wants the parent's posture spells the role `custom`"
2308 );
2309
2310 // The escape hatch is a declared role, not a typo.
2311 assert_eq!(
2312 ChildAuthority::from_runtime_role("custom", full_session()).write_authority,
2313 "workspace_write"
2314 );
2315 }
2316
2317 // ── Permission ceilings, as the child actually experiences them ─────────
2318
2319 /// `tools = false` means zero model tools — an empty allowlist, which the
2320 /// child registry treats as "nothing is visible and nothing is callable".
2321 #[test]
2322 fn spawn_refuses_empty_effective_toolset() {
2323 let authority = ChildAuthority::clamp(PermissionCeiling::ROUTER, full_session());
2324 let err = refuse_dropped_requested_tools(
2325 "router",
2326 "advisor",
2327 &["read_file".to_string(), "grep_files".to_string()],
2328 &authority,
2329 &authority,
2330 )
2331 .expect_err("a child that would start with no tools is refused");
2332 assert!(
2333 err.contains("Agent 'router' (role advisor) would start with no tools"),
2334 "{err}"
2335 );
2336 assert!(err.contains("requested [grep_files, read_file]"), "{err}");
2337 assert!(err.contains("role allows no tools"), "{err}");
2338 // An explicit empty request stays a deliberate tool-free child.
2339 refuse_dropped_requested_tools("router", "advisor", &[], &authority, &authority)
2340 .expect("explicit empty toolset is allowed");
2341 }
2342
2343 #[test]
2344 fn spawn_error_names_dropped_tools() {
2345 let workflow = workflow_with(None, GLM_FLEET);
2346 let mut binding = workflow
2347 .bind_member(None, Some("reviewer"), full_session())
2348 .expect("role lookup");
2349 let err = binding
2350 .narrow_for_task(
2351 None,
2352 Some(&["read_file".to_string(), "exec_shell".to_string()]),
2353 &[],
2354 None,
2355 )
2356 .expect_err("a requested tool the role denies is refused");
2357 assert!(err.contains("would lose requested tools"), "{err}");
2358 assert!(err.contains("dropped [exec_shell]"), "{err}");
2359 assert!(err.contains("requested [exec_shell, read_file]"), "{err}");
2360 assert!(
2361 err.contains("role allows all inherited tools except ["),
2362 "{err}"
2363 );
2364
2365 // Tools the role allows narrow cleanly.
2366 binding
2367 .narrow_for_task(None, Some(&["read_file".to_string()]), &[], None)
2368 .expect("an allowed narrowing succeeds");
2369 assert_eq!(
2370 binding.authority.allowed_tools.as_deref(),
2371 Some(&["read_file".to_string()] as &[String])
2372 );
2373 }
2374
2375 #[test]
2376 fn tools_false_yields_an_empty_tool_surface() {
2377 let authority = ChildAuthority::clamp(PermissionCeiling::ROUTER, full_session());
2378
2379 assert!(!authority.ceiling.tools);
2380 assert_eq!(
2381 authority.allowed_tools.as_deref(),
2382 Some(&[] as &[String]),
2383 "tools = false must be an empty allowlist, not an absent one"
2384 );
2385 assert_eq!(authority.write_authority, "read_only");
2386 assert_eq!(authority.max_depth, 0);
2387 }
2388
2389 /// `network_tool = false` removes every model-visible network, browser,
2390 /// and remote-MCP surface except the `Web` family's two read-only actions
2391 /// — even when `tools = true`. The family *name* must survive the deny
2392 /// list so the child registry's action seam can grant exactly
2393 /// `search`/`fetch`; every other browsing spelling is denied.
2394 #[test]
2395 fn network_disabled_denies_every_network_surface_even_with_tools_enabled() {
2396 let member = PermissionCeiling::preset("read_write").expect("preset");
2397 assert!(member.tools);
2398 assert!(!member.network_tool);
2399
2400 let authority = ChildAuthority::clamp(member, full_session());
2401
2402 assert!(
2403 authority.allowed_tools.is_none(),
2404 "a tool-using member keeps full inheritance, narrowed by the deny list"
2405 );
2406 for expected in [
2407 "web.run",
2408 "web_run",
2409 "web_search",
2410 "fetch_url",
2411 "wait_for_dev_server",
2412 "github",
2413 "mcp*",
2414 ] {
2415 assert!(
2416 authority
2417 .disallowed_tools
2418 .iter()
2419 .any(|name| name == expected),
2420 "{expected} must be denied: {:?}",
2421 authority.disallowed_tools
2422 );
2423 }
2424 // The canonical family name is what the read-only web surface
2425 // dispatches under; only its reaching spellings are denied.
2426 assert!(
2427 !authority.disallowed_tools.iter().any(|name| name == "Web"),
2428 "the Web family name must survive so search/fetch stay reachable: {:?}",
2429 authority.disallowed_tools
2430 );
2431
2432 // A member that IS allowed a network tool gets no such deny list.
2433 let networked = ChildAuthority::clamp(
2434 PermissionCeiling::preset("full").expect("preset"),
2435 full_session(),
2436 );
2437 assert!(networked.ceiling.network_tool);
2438 assert!(networked.disallowed_tools.is_empty());
2439 }
2440
2441 /// The browsing capability is registered under several names, and `web.run`
2442 /// is the one a deny list stopping at the `Web` family name leaves behind.
2443 /// A network-denied member that can still call `web.run` is not
2444 /// network-denied, so every spelling *except* the family name itself —
2445 /// which the action seam bounds to `search`/`fetch` — stays on the list.
2446 #[test]
2447 fn network_disabled_denies_the_canonical_web_run_surface_and_its_aliases() {
2448 let authority = ChildAuthority::clamp(
2449 PermissionCeiling::preset("read_write").expect("preset"),
2450 full_session(),
2451 );
2452
2453 let denied = |name: &str| {
2454 let lowered = name.to_ascii_lowercase();
2455 authority.disallowed_tools.iter().any(|rule| {
2456 let rule = rule.to_ascii_lowercase();
2457 rule.strip_suffix('*')
2458 .map_or(rule == lowered, |prefix| lowered.starts_with(prefix))
2459 })
2460 };
2461
2462 for name in [
2463 "web.run",
2464 "web_run",
2465 "web_search",
2466 "web.fetch",
2467 "web_fetch",
2468 "fetch_url",
2469 "wait_for_dev_server",
2470 "browse",
2471 "browser",
2472 ] {
2473 assert!(
2474 denied(name),
2475 "{name} must be denied: {:?}",
2476 authority.disallowed_tools
2477 );
2478 }
2479 // The family name itself is what the read-only search/fetch surface
2480 // dispatches under; the action seam and the URL-input guard bound it.
2481 assert!(
2482 !denied("Web"),
2483 "the Web family name must survive a network denial: {:?}",
2484 authority.disallowed_tools
2485 );
2486 // The globs must not reach past the browsing family.
2487 for name in ["read_file", "run_tests", "Git", "grep_files"] {
2488 assert!(!denied(name), "{name} is not a network surface");
2489 }
2490 }
2491
2492 /// `rlm` reaches the network without ever naming a network tool: `open`
2493 /// fetches a `url` by calling `FetchUrlTool` in-process, and `eval` runs
2494 /// Python that owns a socket API. Denying `fetch_url` sees neither call, so
2495 /// both actions carry their own deny-list entries.
2496 #[test]
2497 fn network_disabled_denies_the_in_process_rlm_reach() {
2498 let authority = ChildAuthority::clamp(
2499 PermissionCeiling::preset("read_write").expect("preset"),
2500 full_session(),
2501 );
2502
2503 let denied = |name: &str| {
2504 let lowered = name.to_ascii_lowercase();
2505 authority.disallowed_tools.iter().any(|rule| {
2506 let rule = rule.to_ascii_lowercase();
2507 rule.strip_suffix('*')
2508 .map_or(rule == lowered, |prefix| lowered.starts_with(prefix))
2509 })
2510 };
2511
2512 for reaching in ["rlm_open", "rlm_eval"] {
2513 assert!(
2514 denied(reaching),
2515 "{reaching} reaches the network in-process and must be denied: {:?}",
2516 authority.disallowed_tools
2517 );
2518 }
2519 // The fail-closed narrowing is deliberate but *bounded*: the bounded
2520 // local metadata actions survive, and so does the family itself, so the
2521 // per-action seam has something left to permit.
2522 for kept in ["rlm", "rlm_session_objects", "rlm_configure", "rlm_close"] {
2523 assert!(
2524 !denied(kept),
2525 "{kept} is bounded local metadata and must survive a network denial"
2526 );
2527 }
2528 }
2529
2530 /// The deny-list sentinel has to actually be on the deny list, or every
2531 /// posture check derived from it silently reads "network allowed".
2532 #[test]
2533 fn the_network_denial_sentinel_is_installed_by_a_network_denial() {
2534 assert!(
2535 NETWORK_TOOL_DENYLIST.contains(&NETWORK_DENIAL_SENTINEL),
2536 "{NETWORK_DENIAL_SENTINEL} must be an explicit entry, not a glob match"
2537 );
2538 let authority = ChildAuthority::clamp(
2539 PermissionCeiling::preset("read_write").expect("preset"),
2540 full_session(),
2541 );
2542 assert!(
2543 authority
2544 .disallowed_tools
2545 .iter()
2546 .any(|rule| rule == NETWORK_DENIAL_SENTINEL),
2547 "a network denial must install the sentinel verbatim: {:?}",
2548 authority.disallowed_tools
2549 );
2550 // …and a network-*capable* member must not, or the sentinel would read
2551 // as denied for everyone.
2552 let networked = ChildAuthority::clamp(
2553 PermissionCeiling::preset("full").expect("preset"),
2554 full_session(),
2555 );
2556 assert!(
2557 !networked
2558 .disallowed_tools
2559 .iter()
2560 .any(|rule| rule == NETWORK_DENIAL_SENTINEL)
2561 );
2562 }
2563
2564 /// Every network-denied preset — read_only/read-only inspection included — leaves the
2565 /// `Web` family name reachable and seals each of its reaching spellings.
2566 /// This is the deny-list half of the read-only web-search contract; the
2567 /// registry-side half (exactly `search`/`fetch`, with URL-addressed calls
2568 /// refused) is asserted in `subagent/tests.rs`.
2569 #[test]
2570 fn every_network_denial_leaves_web_search_reachable_by_family_name() {
2571 for preset in ["analyst", "read_only", "verifier", "read_write"] {
2572 let authority = ChildAuthority::clamp(
2573 PermissionCeiling::preset(preset).expect("preset"),
2574 full_session(),
2575 );
2576 assert!(
2577 !authority.ceiling.network_tool,
2578 "{preset} is network-denied"
2579 );
2580 assert!(
2581 !authority.disallowed_tools.iter().any(|rule| rule == "Web"),
2582 "{preset} must keep the Web family name: {:?}",
2583 authority.disallowed_tools
2584 );
2585 for sealed in [
2586 "web_*",
2587 "web.*",
2588 "web.run",
2589 "web_run",
2590 "web_search",
2591 "web.fetch",
2592 "web_fetch",
2593 "fetch_url",
2594 "wait_for_dev_server",
2595 "github",
2596 "mcp*",
2597 ] {
2598 assert!(
2599 authority.disallowed_tools.iter().any(|rule| rule == sealed),
2600 "{preset} must deny {sealed}: {:?}",
2601 authority.disallowed_tools
2602 );
2603 }
2604 }
2605 }
2606
2607 /// A member saved as `write = false` must not receive a mutating surface —
2608 /// including the raw shell a `verifier`-shaped ceiling keeps for running
2609 /// checks. `rm -rf` mutates a workspace exactly as well as `write_file`,
2610 /// and a receipt that says `write=false` while the child holds `exec_shell`
2611 /// is not true.
2612 #[test]
2613 fn a_read_only_member_gets_a_truthful_non_mutating_tool_contract() {
2614 let verifier = PermissionCeiling::preset("verifier").expect("preset");
2615 assert!(!verifier.write);
2616 assert_eq!(verifier.shell, ShellCeiling::Full);
2617
2618 let authority = ChildAuthority::clamp(verifier, full_session());
2619 assert_eq!(authority.write_authority, "read_only");
2620
2621 let denied = |name: &str| {
2622 authority.disallowed_tools.iter().any(|rule| {
2623 rule == name || rule.strip_suffix('*').is_some_and(|p| name.starts_with(p))
2624 })
2625 };
2626
2627 // `rlm_eval` belongs on this list for the same reason `exec_shell` does:
2628 // the Python it runs writes files. A tool is a mutation primitive
2629 // because of what it can do, not because of what it is called.
2630 for mutating in [
2631 "write_file",
2632 "edit_file",
2633 "apply_patch",
2634 "fim_edit",
2635 "rlm_eval",
2636 ] {
2637 assert!(
2638 denied(mutating),
2639 "{mutating} must be denied for a read-only member: {:?}",
2640 authority.disallowed_tools
2641 );
2642 }
2643 for raw_shell in [
2644 "Bash",
2645 "exec_shell",
2646 "exec_shell_interact",
2647 "task_shell_start",
2648 "terminal_run",
2649 "terminal/run",
2650 ] {
2651 assert!(
2652 denied(raw_shell),
2653 "{raw_shell} is a general mutation primitive: {:?}",
2654 authority.disallowed_tools
2655 );
2656 }
2657 // What the member is *for* survives: the bounded verification surface.
2658 // (`rlm_open` is absent from this list only because the `verifier`
2659 // preset is also network-denied; the write contract alone keeps it —
2660 // see `a_write_denial_alone_keeps_local_rlm_loading`.)
2661 for kept in [
2662 "Run",
2663 "run_tests",
2664 "run_verifiers",
2665 "read_file",
2666 "grep_files",
2667 "rlm",
2668 ] {
2669 assert!(!denied(kept), "{kept} must stay available to a verifier");
2670 }
2671
2672 // A write-capable member is untouched by this contract.
2673 let builder = ChildAuthority::clamp(
2674 PermissionCeiling::preset("read_write").expect("preset"),
2675 full_session(),
2676 );
2677 assert!(builder.ceiling.write);
2678 for kept in ["write_file", "apply_patch", "exec_shell"] {
2679 assert!(
2680 !builder.disallowed_tools.iter().any(|rule| rule == kept),
2681 "{kept} must stay available to a write-capable member"
2682 );
2683 }
2684 }
2685
2686 /// The two denials are separate contracts and must not bleed into each
2687 /// other. A member that may not *write* can still load a large local file
2688 /// into an RLM kernel and read it — that is analysis, not mutation. Only
2689 /// `eval` goes, because only `eval` runs code.
2690 #[test]
2691 fn a_write_denial_alone_keeps_local_rlm_loading() {
2692 let member = PermissionCeiling {
2693 write: false,
2694 network_tool: true,
2695 shell: ShellCeiling::ReadOnly,
2696 delegation_depth: 0,
2697 tools: true,
2698 };
2699 let authority = ChildAuthority::clamp(member, full_session());
2700 assert!(!authority.ceiling.write);
2701 assert!(authority.ceiling.network_tool);
2702
2703 let denied = |name: &str| authority.disallowed_tools.iter().any(|rule| rule == name);
2704
2705 assert!(denied("rlm_eval"), "eval runs code, so it mutates");
2706 for kept in ["rlm", "rlm_open", "rlm_session_objects", "rlm_close"] {
2707 assert!(
2708 !denied(kept),
2709 "{kept} loads and inspects; it does not mutate: {:?}",
2710 authority.disallowed_tools
2711 );
2712 }
2713 }
2714
2715 /// The parent posture always wins. A saved `full` member inside a
2716 /// read-only, no-network, no-shell session runs at the session's ceiling.
2717 #[test]
2718 fn the_parent_ceiling_wins_over_a_wider_saved_member() {
2719 let session = PermissionCeiling {
2720 write: false,
2721 network_tool: false,
2722 shell: ShellCeiling::ReadOnly,
2723 delegation_depth: 0,
2724 tools: true,
2725 };
2726 let member = PermissionCeiling::preset("full").expect("preset");
2727 assert!(member.write && member.network_tool);
2728
2729 let authority = ChildAuthority::clamp(member, session);
2730
2731 assert!(!authority.ceiling.write, "a Fleet may not grant write");
2732 assert!(
2733 !authority.ceiling.network_tool,
2734 "a Fleet may not grant a network tool"
2735 );
2736 assert_eq!(authority.ceiling.shell, ShellCeiling::ReadOnly);
2737 assert_eq!(authority.ceiling.delegation_depth, 0);
2738 assert_eq!(authority.write_authority, "read_only");
2739 assert_eq!(authority.max_depth, 0);
2740 assert_eq!(authority.posture_role, "explore");
2741 assert!(!authority.disallowed_tools.is_empty());
2742 }
2743
2744 /// A read-only session cannot be widened by a session that *is* permissive
2745 /// either — clamping is symmetric, and takes the narrower side each way.
2746 #[test]
2747 fn clamping_takes_the_narrower_side_of_every_field() {
2748 let narrow_member = PermissionCeiling {
2749 write: false,
2750 network_tool: false,
2751 shell: ShellCeiling::None,
2752 delegation_depth: 0,
2753 tools: true,
2754 };
2755 let authority = ChildAuthority::clamp(narrow_member, full_session());
2756
2757 assert!(!authority.ceiling.write);
2758 assert_eq!(authority.ceiling.shell, ShellCeiling::None);
2759 assert_eq!(authority.ceiling.delegation_depth, 0);
2760 }
2761
2762 // ── Preflight ──────────────────────────────────────────────────────────
2763
2764 /// Z.AI GLM routes express only thinking enabled/disabled, so `high` and
2765 /// `max` must not be reported as two distinct provider-effective tiers.
2766 #[test]
2767 fn glm_routes_report_an_enabled_disabled_provider_control() {
2768 let capability = reasoning_capability_for_route(
2769 ProviderKind::Zai,
2770 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
2771 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
2772 );
2773
2774 assert_eq!(
2775 capability.control,
2776 ProviderReasoningControl::EnabledDisabled,
2777 "Z.AI's request shaping emits only thinking enabled/disabled"
2778 );
2779 assert!(!capability.supports_native_adaptive());
2780 assert_eq!(
2781 capability.provider_effective(ReasoningTier::High),
2782 ProviderEffectiveReasoning::Enabled
2783 );
2784 assert_eq!(
2785 capability.provider_effective(ReasoningTier::Off),
2786 ProviderEffectiveReasoning::Disabled
2787 );
2788 }
2789
2790 /// DeepSeek varies `reasoning_effort` per tier, so its tiers are real.
2791 #[test]
2792 fn a_route_that_varies_its_wire_value_reports_distinct_tiers() {
2793 let capability = reasoning_capability_for_route(
2794 ProviderKind::Deepseek,
2795 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
2796 "deepseek-v4-pro",
2797 );
2798 assert_eq!(capability.control, ProviderReasoningControl::Tiers);
2799 }
2800
2801 /// First-party DeepSeek routes document `reasoning_effort` low/high/max
2802 /// on the wire (no medium), so `low` is a real tier there. The capability
2803 /// must report the tier the route *sends*, not the tier the selector
2804 /// named: low reaches the wire as low, medium rounds up to high because
2805 /// the dialect has no such value (#52).
2806 #[test]
2807 fn a_deepseek_route_reports_low_as_low_and_medium_as_high() {
2808 let capability = reasoning_capability_for_route(
2809 ProviderKind::Deepseek,
2810 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
2811 "deepseek-v4-pro",
2812 );
2813
2814 // Exactly what the request shaping does, read back off the capability.
2815 for (requested, expected) in [
2816 (ReasoningTier::Low, ReasoningTier::Low),
2817 (ReasoningTier::Medium, ReasoningTier::High),
2818 (ReasoningTier::High, ReasoningTier::High),
2819 (ReasoningTier::Max, ReasoningTier::Max),
2820 (ReasoningTier::Off, ReasoningTier::Off),
2821 ] {
2822 assert_eq!(
2823 capability.wire_tier(requested),
2824 expected,
2825 "requested {requested:?} must be reported as what the wire carries"
2826 );
2827 let (effective, normalized) = capability.normalize(requested);
2828 assert_eq!(effective, expected);
2829 assert_eq!(normalized, requested != expected);
2830 }
2831
2832 // And the resolver carries that all the way onto the receipt.
2833 let resolved = codewhale_workflow::resolve_exact_member_reasoning(
2834 "implementer",
2835 &codewhale_workflow::FrozenRoute {
2836 provider: "deepseek".to_string(),
2837 model: "deepseek-v4-pro".to_string(),
2838 },
2839 RequestedReasoning::Low,
2840 &capability,
2841 &RouterAvailability::Absent,
2842 None,
2843 None,
2844 )
2845 .expect("resolve");
2846 assert_eq!(resolved.requested(), RequestedReasoning::Low);
2847 assert_eq!(
2848 resolved.effective(),
2849 codewhale_workflow::EffectiveReasoning::Tier(ReasoningTier::Low)
2850 );
2851 assert!(!resolved.capability_normalized());
2852 }
2853
2854 /// Routes whose dialect has no low tier still collapse low onto high, and
2855 /// the capability must say so instead of reporting a `low` the wire never
2856 /// carried. CodeWhale's normalizer keeps the historic low/medium → high
2857 /// coercion for these DeepSeek-compatible hosted routes because their own
2858 /// wire contracts are not verified.
2859 #[test]
2860 fn a_route_that_collapses_low_onto_high_says_so_instead_of_reporting_low() {
2861 let capability = reasoning_capability_for_route(
2862 ProviderKind::Siliconflow,
2863 codewhale_config::descriptors::defaults::DEFAULT_SILICONFLOW_BASE_URL,
2864 "deepseek-ai/DeepSeek-V4-Pro",
2865 );
2866
2867 for (requested, expected) in [
2868 (ReasoningTier::Low, ReasoningTier::High),
2869 (ReasoningTier::Medium, ReasoningTier::High),
2870 (ReasoningTier::High, ReasoningTier::High),
2871 (ReasoningTier::Max, ReasoningTier::Max),
2872 (ReasoningTier::Off, ReasoningTier::Off),
2873 ] {
2874 assert_eq!(
2875 capability.wire_tier(requested),
2876 expected,
2877 "requested {requested:?} must be reported as what the wire carries"
2878 );
2879 let (effective, normalized) = capability.normalize(requested);
2880 assert_eq!(effective, expected);
2881 assert_eq!(normalized, requested != expected);
2882 }
2883 }
2884
2885 /// Preflight resolves the provider, canonicalizes the model, identifies the
2886 /// endpoint, and decides credential readiness — all from local config.
2887 #[test]
2888 fn preflight_freezes_provider_model_endpoint_and_local_readiness() {
2889 let _env_lock = crate::test_support::lock_test_env();
2890 let _key = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key");
2891 let config = {
2892 let __cw_config_init_0_0 = Some("zai".to_string());
2893 let mut __cw_config_init_0_value: Config = Default::default();
2894 __cw_config_init_0_value.provider = __cw_config_init_0_0;
2895 __cw_config_init_0_value
2896 };
2897
2898 let route = preflight_route(
2899 "implementer",
2900 "zai",
2901 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
2902 &config,
2903 )
2904 .expect("preflight");
2905
2906 assert_eq!(route.member_id, "implementer");
2907 assert_eq!(route.provider_kind, "zai");
2908 assert_eq!(
2909 route.wire_model,
2910 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
2911 );
2912 assert!(!route.endpoint.host.is_empty());
2913 assert!(!route.endpoint.host.contains('/'));
2914 assert_eq!(route.credential, CredentialReadiness::Configured);
2915 route.require_ready().expect("ready");
2916
2917 // The receipt and the child spawn read the same canonical wire model.
2918 assert_eq!(route.frozen().model, route.wire_model);
2919 }
2920
2921 /// A keyless local provider is valid, and is decided without a probe.
2922 #[test]
2923 fn a_keyless_local_provider_preflights_as_ready() {
2924 let _env_lock = crate::test_support::lock_test_env();
2925 let config = {
2926 let __cw_config_init_1_0 = Some("ollama".to_string());
2927 let mut __cw_config_init_1_value: Config = Default::default();
2928 __cw_config_init_1_value.provider = __cw_config_init_1_0;
2929 __cw_config_init_1_value
2930 };
2931
2932 let Ok(route) = preflight_route("worker", "ollama", "qwen3", &config) else {
2933 // A model id this build does not know is a different failure than
2934 // the one under test; skip rather than assert on the catalog.
2935 return;
2936 };
2937 assert_eq!(route.credential, CredentialReadiness::KeylessLocal);
2938 assert!(route.credential.is_ready());
2939 route.require_ready().expect("keyless local is valid");
2940 assert!(route.endpoint.local, "a local runtime is marked local");
2941 }
2942
2943 #[test]
2944 fn ollama_cloud_and_custom_remote_preflight_require_route_scoped_credentials() {
2945 let _env_lock = crate::test_support::lock_test_env();
2946 let temp = tempfile::tempdir().expect("isolated credential home");
2947 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path());
2948 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
2949 let _ollama_cloud_key = crate::test_support::EnvVarGuard::remove("OLLAMA_CLOUD_API_KEY");
2950 let _ollama_key = crate::test_support::EnvVarGuard::remove("OLLAMA_API_KEY");
2951 let _cli_source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE");
2952 let _cli_key = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY");
2953 codewhale_secrets::Secrets::auto_detect()
2954 .set("ollama", "legacy-cloud-key")
2955 .expect("seed released Ollama Cloud slot");
2956
2957 let cloud = {
2958 let __cw_config_init_2_0 = Some("deepseek".to_string());
2959 let __cw_config_init_2_1 = Some(codewhale_runtime::config::ProvidersConfig {
2960 ollama: codewhale_runtime::config::ProviderConfig {
2961 base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()),
2962 ..Default::default()
2963 },
2964 ..Default::default()
2965 });
2966 let mut __cw_config_init_2_value: Config = Default::default();
2967 __cw_config_init_2_value.provider = __cw_config_init_2_0;
2968 __cw_config_init_2_value.providers = __cw_config_init_2_1;
2969 __cw_config_init_2_value
2970 };
2971 let cloud_route = preflight_route(
2972 "cloud-worker",
2973 "ollama",
2974 codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_MODEL,
2975 &cloud,
2976 )
2977 .expect("official Cloud route");
2978 assert_eq!(cloud_route.provider_id, "ollama-cloud");
2979 assert_eq!(cloud_route.provider_config_id.as_deref(), Some("ollama"));
2980 assert_eq!(cloud_route.provider_kind, "ollama-cloud");
2981 assert_eq!(cloud_route.credential, CredentialReadiness::Configured);
2982 assert!(!cloud_route.endpoint.local);
2983 cloud_route.require_ready().expect("Cloud env key is ready");
2984
2985 let custom_remote = {
2986 let __cw_config_init_3_0 = Some("ollama".to_string());
2987 let __cw_config_init_3_1 = Some(codewhale_runtime::config::ProvidersConfig {
2988 ollama: codewhale_runtime::config::ProviderConfig {
2989 base_url: Some("https://ollama-gateway.example.test/v1".to_string()),
2990 ..Default::default()
2991 },
2992 ..Default::default()
2993 });
2994 let mut __cw_config_init_3_value: Config = Default::default();
2995 __cw_config_init_3_value.provider = __cw_config_init_3_0;
2996 __cw_config_init_3_value.providers = __cw_config_init_3_1;
2997 __cw_config_init_3_value
2998 };
2999 let custom_route = preflight_route(
3000 "custom-worker",
3001 "ollama",
3002 codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_MODEL,
3003 &custom_remote,
3004 )
3005 .expect("custom route still resolves structurally");
3006 assert!(matches!(
3007 custom_route.credential,
3008 CredentialReadiness::Missing { .. }
3009 ));
3010 assert!(!custom_route.endpoint.local);
3011 assert!(custom_route.require_ready().is_err());
3012 }
3013
3014 #[tokio::test]
3015 async fn legacy_ollama_cloud_fleet_start_builds_clients_from_the_frozen_source_route() {
3016 let _env_lock = crate::test_support::lock_test_env();
3017 let temp = tempfile::tempdir().expect("isolated credential home");
3018 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path());
3019 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
3020 let _cloud_env = crate::test_support::EnvVarGuard::remove("OLLAMA_CLOUD_API_KEY");
3021 let _official_env = crate::test_support::EnvVarGuard::remove("OLLAMA_API_KEY");
3022 codewhale_secrets::Secrets::auto_detect()
3023 .set("ollama", "legacy-cloud-fleet-key")
3024 .expect("seed released Ollama Cloud slot");
3025
3026 let config = {
3027 let __cw_config_init_4_0 = Some("deepseek".to_string());
3028 let __cw_config_init_4_1 = Some(codewhale_runtime::config::ProvidersConfig {
3029 ollama: codewhale_runtime::config::ProviderConfig {
3030 base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()),
3031 model: Some(
3032 codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_MODEL
3033 .to_string(),
3034 ),
3035 ..Default::default()
3036 },
3037 ..Default::default()
3038 });
3039 let mut __cw_config_init_4_value: Config = Default::default();
3040 __cw_config_init_4_value.provider = __cw_config_init_4_0;
3041 __cw_config_init_4_value.providers = __cw_config_init_4_1;
3042 __cw_config_init_4_value
3043 };
3044 let document = FleetDocument::parse(&format!(
3045 r#"
3046 name = "glm-pair"
3047 schema = "exact"
3048
3049 [[members]]
3050 id = "cloud-worker"
3051 role = "builder"
3052 provider = "ollama"
3053 model = "{}"
3054 reasoning = "medium"
3055 permissions = "read_only"
3056 "#,
3057 codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_MODEL
3058 ))
3059 .expect("legacy Cloud Fleet parses");
3060
3061 // `capture` is the real Workflow-start path: it preflights readiness,
3062 // constructs every worker client, and freezes the snapshot.
3063 let workflow = ExactFleetWorkflow::capture(
3064 &document,
3065 id(),
3066 "2026-08-14T00:00:00Z",
3067 Some(&config),
3068 &[],
3069 None,
3070 )
3071 .expect("legacy Cloud Fleet starts");
3072 let route = workflow
3073 .preflight
3074 .worker("cloud-worker")
3075 .expect("preflighted worker");
3076 assert_eq!(route.provider_id, "ollama-cloud");
3077 assert_eq!(route.provider_config_id.as_deref(), Some("ollama"));
3078
3079 let binding = workflow
3080 .bind_member(Some("cloud-worker"), None, full_session())
3081 .expect("worker binds");
3082 let launch = workflow
3083 .route_admitted_task(&binding, "verify the frozen Cloud route")
3084 .await
3085 .expect("manual-tier launch needs no provider call");
3086 assert_eq!(launch.provider, "ollama-cloud");
3087 assert_eq!(launch.receipt.provider, "ollama-cloud");
3088
3089 let router_profile = ReasoningRouterProfile::parse(&format!(
3090 r#"
3091 name = "legacy-cloud-router"
3092 schema = "reasoning_router"
3093 provider = "ollama"
3094 model = "{}"
3095 call_reasoning = "low"
3096 "#,
3097 codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_MODEL
3098 ))
3099 .expect("legacy Cloud router profile parses");
3100 let captured =
3101 CapturedReasoningRouter::from_profile(&router_profile, "workspace".to_string());
3102 let live = LiveFleetRouter::bind(&captured, &config, None)
3103 .expect("legacy Cloud Router binds its source table and secret");
3104 assert_eq!(live.route.provider_id, "ollama-cloud");
3105 assert_eq!(live.route.provider_config_id.as_deref(), Some("ollama"));
3106 assert_eq!(live.client.api_provider(), ProviderKind::OllamaCloud);
3107 assert_eq!(
3108 live.client.base_url(),
3109 codewhale_config::provider::OLLAMA_CLOUD_BASE_URL
3110 );
3111 }
3112
3113 /// A tier label is a selector concept; what a request may carry is a
3114 /// provider concept. The value placed on a call must come from the route
3115 /// normalizer the client actually uses, or a Codex-routed Router is called
3116 /// at the provider default while its receipt claims a tier.
3117 #[test]
3118 fn a_call_reasoning_value_is_shaped_by_the_configured_route_not_a_tier_label() {
3119 // A tiered non-Codex route spells the tiers the ordinary way, after
3120 // the same route normalization the client performs (first-party
3121 // DeepSeek keeps a real `low`; medium still rounds up to high).
3122 for (tier, expected) in [
3123 (ReasoningTier::Off, "off"),
3124 (ReasoningTier::High, "high"),
3125 (ReasoningTier::Max, "max"),
3126 ] {
3127 assert_eq!(
3128 route_reasoning_setting(
3129 ProviderKind::Deepseek,
3130 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
3131 "deepseek-v4-pro",
3132 tier,
3133 ),
3134 expected,
3135 "{tier:?} on a deepseek route"
3136 );
3137 }
3138
3139 // Codex is the case a bare tier label gets wrong in both directions:
3140 // it has no `off`, and its ladder now spells three separate top rungs
3141 // (`xhigh`, `max`, `ultra`) that the roster publishes per model.
3142 let codex = |tier| {
3143 route_reasoning_setting(
3144 ProviderKind::OpenaiCodex,
3145 "https://chatgpt.com/backend-api/codex",
3146 "gpt-5.6-codex",
3147 tier,
3148 )
3149 };
3150 assert_eq!(codex(ReasoningTier::Max), "max");
3151 assert_eq!(codex(ReasoningTier::Low), "low");
3152 assert_ne!(
3153 codex(ReasoningTier::Off),
3154 "off",
3155 "an always-thinking route cannot be asked for `off`; sending the label \
3156 would take the provider default while the receipt claimed a tier"
3157 );
3158 }
3159
3160 /// An unresolvable provider fails preflight rather than reaching a launch.
3161 #[test]
3162 fn an_unresolvable_provider_fails_preflight() {
3163 let config = Config::default();
3164 let err = preflight_route("implementer", "not-a-provider", "whatever", &config)
3165 .expect_err("unresolvable provider");
3166 assert!(matches!(err, PreflightError::ProviderUnresolved { .. }));
3167 }
3168
3169 // ── Receipts ───────────────────────────────────────────────────────────
3170
3171 /// The receipt is the durable artifact. It must carry every side of the
3172 /// decision — including which service chose the tier and what that call was
3173 /// configured to cost — and must store no task text, path, or key.
3174 #[tokio::test]
3175 async fn a_launch_receipt_names_the_service_route_and_call_cost_without_content() {
3176 let workflow = workflow_with(
3177 Some(StaticFleetRouter::new(r#"{"reasoning":"max"}"#)),
3178 GLM_FLEET,
3179 );
3180 let binding = workflow
3181 .bind_member(None, Some("builder"), full_session())
3182 .expect("bind");
3183
3184 let launch = workflow
3185 .route_admitted_task(&binding, "refactor /Users/hunter/app with ZAI_API_KEY=zzz")
3186 .await
3187 .expect("launch");
3188 let receipt = &launch.receipt;
3189
3190 assert_eq!(receipt.fleet, "workspace/glm-pair");
3191 assert_eq!(receipt.schema_kind, "exact");
3192 assert_eq!(receipt.member_id, "implementer");
3193 assert_eq!(receipt.member_role, "implement");
3194 assert_eq!(receipt.provider, "zai");
3195 assert_eq!(receipt.model, "glm-5");
3196 assert_eq!(receipt.requested_reasoning, "auto");
3197 assert_eq!(receipt.effective_reasoning, "max");
3198 assert_eq!(receipt.selection_source, "fleet_router");
3199 assert!(!receipt.content_hash.is_empty());
3200
3201 // The service is labelled as a service, with its exact route and the
3202 // configured requested → provider-effective call reasoning.
3203 let router = receipt.router.as_ref().expect("router identity");
3204 assert_eq!(router.service_kind, "reasoning_router");
3205 assert_eq!(router.qualified(), "workspace/luna-low");
3206 assert_eq!(router.provider, "openai");
3207 assert_eq!(router.model, "gpt-5.6-luna");
3208 let call = router.call.as_ref().expect("call disclosure");
3209 assert_eq!(call.requested, "low");
3210 assert_eq!(call.effective, "low");
3211 assert_eq!(call.provider_effective, "low");
3212
3213 // Cross-provider inference happened (zai worker, openai router) and is
3214 // disclosed rather than implied away.
3215 assert!(receipt.cross_provider_inference);
3216 assert!(
3217 receipt.transport.contains("different provider"),
3218 "{}",
3219 receipt.transport
3220 );
3221
3222 // Disclosure without content.
3223 let disclosure = receipt.routing_summary.as_ref().expect("disclosure");
3224 assert!(disclosure.transmitted_bytes > 0);
3225 assert!(disclosure.content_hash.starts_with("sha256:"));
3226 assert!(disclosure.redacted);
3227
3228 let json = serde_json::to_string(receipt).expect("serialize");
3229 for forbidden in ["/Users/", "/home/", ".toml", "api_key", "zzz", "refactor"] {
3230 assert!(!json.contains(forbidden), "{forbidden} in {json}");
3231 }
3232
3233 // The visible line names every side and echoes no content.
3234 let line = receipt.line();
3235 for expected in [
3236 "requested=auto",
3237 "effective=max",
3238 "source=fleet_router",
3239 "reasoning_router:workspace/luna-low",
3240 "router_call_requested=low",
3241 ] {
3242 assert!(line.contains(expected), "{expected} missing from {line}");
3243 }
3244 assert!(!line.contains("refactor"), "{line}");
3245 }
3246
3247 /// A member's semantic role and its Runtime posture are separate
3248 /// facts and the receipt keeps both. An operator who named a member
3249 /// `auditor` must see `auditor` on the receipt, while the surface actually
3250 /// selected (`explore`, the fail-closed posture an undeclared role gets
3251 /// since #5575) is disclosed rather than substituted for the name.
3252 #[tokio::test]
3253 async fn a_receipt_records_the_posture_without_renaming_the_members_role() {
3254 const AUDIT_FLEET: &str = r#"
3255 name = "glm-pair"
3256 schema = "exact"
3257
3258 [[members]]
3259 id = "auditor"
3260 role = "auditor"
3261 provider = "zai"
3262 model = "glm-5"
3263 reasoning = "high"
3264 permissions = "read_only"
3265 "#;
3266 let workflow = workflow_with(None, AUDIT_FLEET);
3267 let binding = workflow
3268 .bind_member(None, Some("auditor"), full_session())
3269 .expect("bind");
3270
3271 // Enforcement uses the posture; it is not the operator's role name.
3272 assert_eq!(binding.member_role, "auditor");
3273 assert_eq!(binding.authority.posture_role, "explore");
3274
3275 let launch = workflow
3276 .route_admitted_task(&binding, "review the queue")
3277 .await
3278 .expect("launch");
3279 let receipt = &launch.receipt;
3280
3281 assert_eq!(receipt.member_role, "auditor");
3282 assert_eq!(receipt.posture_role.as_deref(), Some("explore"));
3283 let line = receipt.line();
3284 assert!(line.contains("(role auditor)"), "{line}");
3285 assert!(line.contains("posture=explore"), "{line}");
3286 }
3287
3288 // ── Search roots: where a workspace Fleet lives ────────────────────────
3289
3290 /// The Fleet store saves workspace Fleets under `<workspace>/.codewhale`,
3291 /// so that is the primary `workspace` origin; the workspace root stays a
3292 /// second origin for checked-in `fleets/<name>.toml` rosters.
3293 #[test]
3294 fn workspace_fleets_load_from_dot_codewhale_and_the_legacy_root() {
3295 let _lock = crate::test_support::lock_test_env();
3296 let home = tempfile::tempdir().expect("home");
3297 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
3298 let ws = tempfile::tempdir().expect("workspace");
3299
3300 let saved = ws.path().join(".codewhale").join("fleets");
3301 std::fs::create_dir_all(&saved).expect("saved fleets dir");
3302 std::fs::write(saved.join("glm-pair.toml"), GLM_FLEET).expect("write saved");
3303 let (document, id) =
3304 load_fleet_document("glm-pair", ws.path(), None).expect("saved fleet loads");
3305 assert_eq!(document.name(), "glm-pair");
3306 assert_eq!(id.origin, "workspace");
3307
3308 let checked_in = ws.path().join("fleets");
3309 std::fs::create_dir_all(&checked_in).expect("checked-in fleets dir");
3310 std::fs::write(
3311 checked_in.join("stopship.toml"),
3312 "name = \"stopship\"\n\n[roles]\nscout = \"scout\"\n",
3313 )
3314 .expect("write checked-in");
3315 let (document, id) =
3316 load_fleet_document("stopship", ws.path(), None).expect("checked-in fleet still loads");
3317 assert_eq!(document.name(), "stopship");
3318 assert_eq!(id.origin, "workspace_root");
3319
3320 // An exact Fleet in both workspace origins is ambiguous, and each
3321 // origin can be named explicitly.
3322 std::fs::write(checked_in.join("glm-pair.toml"), GLM_FLEET).expect("write twin");
3323 assert!(matches!(
3324 load_fleet_document("glm-pair", ws.path(), None),
3325 Err(NamedFleetError::AmbiguousFleet { .. })
3326 ));
3327 let (_, id) =
3328 load_fleet_document("workspace_root/glm-pair", ws.path(), None).expect("qualified");
3329 assert_eq!(id.origin, "workspace_root");
3330 }
3331
3332 #[test]
3333 fn fleet_names_that_leave_the_fleets_directory_are_refused() {
3334 let _lock = crate::test_support::lock_test_env();
3335 let home = tempfile::tempdir().expect("home");
3336 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
3337 let outer = tempfile::tempdir().expect("outer");
3338 let ws = outer.path().join("ws");
3339 std::fs::create_dir_all(ws.join("fleets")).expect("fleets dir");
3340 std::fs::write(outer.path().join("outside.toml"), GLM_FLEET).expect("outside");
3341 let absolute = outer.path().join("outside");
3342
3343 for name in [
3344 absolute.to_string_lossy().to_string(),
3345 "workspace_root/../../outside".to_string(),
3346 "codewhale_home/../outside".to_string(),
3347 "user/../outside".to_string(),
3348 ] {
3349 let err = load_fleet_document(&name, &ws, None).expect_err(&name);
3350 assert!(
3351 matches!(err, NamedFleetError::InvalidName),
3352 "{name}: expected InvalidName, got {err:?}"
3353 );
3354 let message = err.to_string();
3355 assert!(
3356 !message.contains(outer.path().to_string_lossy().as_ref()),
3357 "{message}"
3358 );
3359 }
3360 }
3361
3362 /// A Fleet saved through the store at workspace scope is found by the
3363 /// Workflow loader instead of being reported missing. Today the store's
3364 /// `schema = "fleet"` revision-2 document is not a schema the Workflow
3365 /// loader parses, so the load names that exact file and its schema; if a
3366 /// v2 bridge lands, the same call succeeds from the `workspace` origin.
3367 #[test]
3368 fn a_store_saved_workspace_fleet_is_found_by_load_fleet_document() {
3369 use crate::fleet::store::{FleetFile, FleetScope, save_fleet};
3370
3371 let _lock = crate::test_support::lock_test_env();
3372 let home = tempfile::tempdir().expect("home");
3373 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
3374 let ws = tempfile::tempdir().expect("workspace");
3375
3376 let fleet = FleetFile::new("Folder Pair".to_string(), None).expect("fleet");
3377 let path = save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("save");
3378
3379 match load_fleet_document(&fleet.file_slug(), ws.path(), None) {
3380 // A v2 bridge may label the store scope `folder` rather than the
3381 // `workspace` search-root origin; either names this workspace.
3382 Ok((_, id)) => assert!(
3383 matches!(id.origin.as_str(), "workspace" | "folder"),
3384 "{}",
3385 id.origin
3386 ),
3387 Err(err) => {
3388 assert!(
3389 !matches!(err, NamedFleetError::NotFound(_)),
3390 "the saved Fleet must be found, got {err}"
3391 );
3392 let message = err.to_string();
3393 assert!(message.contains(&path.display().to_string()), "{message}");
3394 }
3395 }
3396 }
3397 }
3398
3399 /// `workflow(fleet:)` resolving saved v2 Fleets (store-first lookup, freeze
3400 /// into an exact snapshot, ambiguity against legacy/exact files).
3401 #[cfg(test)]
3402 mod saved_fleet_tests {
3403 use super::*;
3404 use crate::fleet::store::{FleetFile, FleetMember, FleetOperator, FleetScope, save_fleet};
3405 use crate::test_support::{EnvVarGuard, lock_test_env};
3406
3407 fn member(id: &str, pin: Option<(&str, &str)>) -> FleetMember {
3408 FleetMember {
3409 id: id.to_string(),
3410 display_name: None,
3411 shortlist: false,
3412 role: String::new(),
3413 model: pin.map(|(_, model)| model.to_string()),
3414 provider: pin.map(|(provider, _)| provider.to_string()),
3415 reasoning: None,
3416 instructions: None,
3417 requires: Vec::new(),
3418 }
3419 }
3420
3421 fn fleet(name: &str, members: Vec<FleetMember>) -> FleetFile {
3422 let mut fleet = FleetFile::new(name.to_string(), None).expect("fleet");
3423 fleet.members = members;
3424 fleet
3425 }
3426
3427 fn zai_session() -> Config {
3428 {
3429 let __cw_config_init_5_0 = Some("zai".to_string());
3430 let __cw_config_init_5_1 = Some("high".to_string());
3431 let mut __cw_config_init_5_value: Config = Default::default();
3432 __cw_config_init_5_value.provider = __cw_config_init_5_0;
3433 __cw_config_init_5_value.reasoning_effort = __cw_config_init_5_1;
3434 __cw_config_init_5_value
3435 }
3436 }
3437
3438 fn session_ceiling() -> PermissionCeiling {
3439 PermissionCeiling {
3440 write: true,
3441 network_tool: true,
3442 shell: codewhale_protocol::fleet::ShellCeiling::Full,
3443 delegation_depth: codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH,
3444 tools: true,
3445 }
3446 }
3447
3448 #[test]
3449 fn a_personal_saved_fleet_loads_as_a_frozen_exact_document() {
3450 let _lock = lock_test_env();
3451 let home = tempfile::tempdir().expect("home");
3452 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
3453 let ws = tempfile::tempdir().expect("workspace");
3454 let config = zai_session();
3455 let saved = fleet(
3456 "My fleet",
3457 vec![
3458 member(
3459 "builder",
3460 Some((
3461 "zai",
3462 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
3463 )),
3464 ),
3465 member("reviewer", None),
3466 ],
3467 );
3468 let path = save_fleet(&saved, FleetScope::Personal, ws.path()).expect("save");
3469
3470 let (document, id) =
3471 load_fleet_document("My fleet", ws.path(), Some(&config)).expect("v2 loads");
3472
3473 assert_eq!(id.origin, "user");
3474 assert_eq!(id.name, "my-fleet");
3475 assert_eq!(document.source_path(), Some(path.as_path()));
3476 let exact = document.exact().expect("frozen into the exact schema");
3477 let builder = exact.member("builder").expect("builder");
3478 assert_eq!(
3479 (builder.provider.as_str(), builder.model.as_str()),
3480 (
3481 "zai",
3482 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
3483 )
3484 );
3485 // No pin and no operator: the member inherits the live session route
3486 // and tier, resolved now rather than left open.
3487 let reviewer = exact.member("reviewer").expect("reviewer");
3488 assert_eq!(
3489 reviewer.provider,
3490 config.active_provider_identity().unwrap().key.as_str()
3491 );
3492 assert_eq!(reviewer.model, config.default_model());
3493 assert_eq!(reviewer.reasoning.as_str(), "high");
3494
3495 // The slug also resolves, and so does the qualified store scope.
3496 load_fleet_document("my-fleet", ws.path(), Some(&config)).expect("slug loads");
3497 load_fleet_document("user/My fleet", ws.path(), Some(&config)).expect("user/ loads");
3498 }
3499
3500 #[test]
3501 fn a_workspace_saved_fleet_loads_and_members_follow_the_operator_route() {
3502 let _lock = lock_test_env();
3503 let home = tempfile::tempdir().expect("home");
3504 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
3505 let ws = tempfile::tempdir().expect("workspace");
3506 let mut saved = fleet("reviewers", vec![member("auditor", None)]);
3507 saved.operator = Some(FleetOperator {
3508 provider: "zai".to_string(),
3509 model: codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string(),
3510 reasoning: Some("low".to_string()),
3511 });
3512 let path = save_fleet(&saved, FleetScope::Workspace, ws.path()).expect("save");
3513 assert!(path.starts_with(ws.path().join(".codewhale").join("fleets")));
3514
3515 // No session config is needed: nothing inherits the session route.
3516 let (document, id) = load_fleet_document("reviewers", ws.path(), None).expect("loads");
3517 assert_eq!(id.origin, "folder");
3518 let auditor = document.exact().unwrap().member("auditor").unwrap();
3519 assert_eq!(
3520 auditor.model,
3521 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
3522 );
3523 assert_eq!(auditor.reasoning.as_str(), "low");
3524 }
3525
3526 #[test]
3527 fn a_saved_fleet_colliding_with_an_exact_file_is_ambiguous_and_names_both_paths() {
3528 let _lock = lock_test_env();
3529 let home = tempfile::tempdir().expect("home");
3530 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
3531 let ws = tempfile::tempdir().expect("workspace");
3532 let saved_path = save_fleet(
3533 &fleet("glm-pair", vec![member("builder", None)]),
3534 FleetScope::Personal,
3535 ws.path(),
3536 )
3537 .expect("save");
3538 let exact_dir = ws.path().join("fleets");
3539 std::fs::create_dir_all(&exact_dir).unwrap();
3540 let exact_path = exact_dir.join("glm-pair.toml");
3541 std::fs::write(
3542 &exact_path,
3543 "name = \"glm-pair\"\nschema = \"exact\"\n\n[[members]]\nid = \"builder\"\nprovider = \"zai\"\nmodel = \"glm-5\"\n",
3544 )
3545 .unwrap();
3546
3547 let error = load_fleet_document("glm-pair", ws.path(), Some(&zai_session()))
3548 .expect_err("a v2 and an exact Fleet of one name must not shadow each other");
3549 let message = error.to_string();
3550 assert!(
3551 matches!(error, NamedFleetError::AmbiguousFleet { .. }),
3552 "{message}"
3553 );
3554 assert!(
3555 message.contains(&saved_path.display().to_string()),
3556 "{message}"
3557 );
3558 assert!(
3559 message.contains(&exact_path.display().to_string()),
3560 "{message}"
3561 );
3562
3563 // Qualifying either side resolves it.
3564 let (document, _) =
3565 load_fleet_document("user/glm-pair", ws.path(), Some(&zai_session())).expect("v2");
3566 assert_eq!(document.source_path(), Some(saved_path.as_path()));
3567 }
3568
3569 /// Saved Fleets carry session-vocabulary reasoning (an imported agent
3570 /// profile stores `ultra`, `xhigh`, `minimal`); freezing maps it onto an
3571 /// exact tier instead of failing the exact parser, a blank value inherits,
3572 /// and an unknown value is refused with the member named.
3573 #[test]
3574 fn saved_fleet_reasoning_in_session_vocabulary_freezes_to_exact_tiers() {
3575 let _lock = lock_test_env();
3576 let home = tempfile::tempdir().expect("home");
3577 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
3578 let ws = tempfile::tempdir().expect("workspace");
3579 let pin = Some((
3580 "zai",
3581 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
3582 ));
3583 let mut ultra = member("ultra", pin);
3584 ultra.reasoning = Some("ultra".to_string());
3585 let mut minimal = member("minimal", pin);
3586 minimal.reasoning = Some("minimal".to_string());
3587 let mut blank = member("blank", pin);
3588 blank.reasoning = Some(" ".to_string());
3589 let mut saved = fleet("tiers", vec![ultra, minimal, blank]);
3590 saved.operator = Some(FleetOperator {
3591 provider: "zai".to_string(),
3592 model: codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string(),
3593 reasoning: Some("xhigh".to_string()),
3594 });
3595 save_fleet(&saved, FleetScope::Workspace, ws.path()).expect("save");
3596
3597 let (document, _) = load_fleet_document("tiers", ws.path(), None).expect("freezes");
3598 let exact = document.exact().expect("exact");
3599 let tier = |id: &str| exact.member(id).expect(id).reasoning.as_str();
3600 assert_eq!(tier("ultra"), "max");
3601 assert_eq!(tier("minimal"), "low");
3602 // Blank inherits the operator's `xhigh`, which is the `max` tier.
3603 assert_eq!(tier("blank"), "max");
3604
3605 let mut bad = member("bad", pin);
3606 bad.reasoning = Some("turbo".to_string());
3607 save_fleet(
3608 &fleet("bad-tier", vec![bad]),
3609 FleetScope::Workspace,
3610 ws.path(),
3611 )
3612 .expect("save");
3613 let error = load_fleet_document("bad-tier", ws.path(), None).expect_err("refused");
3614 assert!(
3615 error.to_string().contains("member `bad` reasoning"),
3616 "{error}"
3617 );
3618 }
3619
3620 #[test]
3621 fn member_instructions_are_refused_rather_than_silently_dropped() {
3622 let _lock = lock_test_env();
3623 let home = tempfile::tempdir().expect("home");
3624 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
3625 let ws = tempfile::tempdir().expect("workspace");
3626 let mut coach = member(
3627 "coach",
3628 Some((
3629 "zai",
3630 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
3631 )),
3632 );
3633 coach.instructions = Some("Always cite sources.".to_string());
3634 save_fleet(
3635 &fleet("coached", vec![coach]),
3636 FleetScope::Workspace,
3637 ws.path(),
3638 )
3639 .expect("save");
3640
3641 let error = load_fleet_document("coached", ws.path(), None).expect_err("refused");
3642 assert!(
3643 error.to_string().contains("`coach` has instructions"),
3644 "{error}"
3645 );
3646 }
3647
3648 /// The frozen snapshot is what runs: editing the saved file after capture
3649 /// moves nothing, and the inherited member's preflighted route is the same
3650 /// session route the snapshot names.
3651 #[test]
3652 fn frozen_routes_survive_a_mid_run_edit_and_inherit_matches_preflight() {
3653 let _lock = lock_test_env();
3654 let home = tempfile::tempdir().expect("home");
3655 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
3656 let _key = EnvVarGuard::set("ZAI_API_KEY", "zai-key");
3657 let ws = tempfile::tempdir().expect("workspace");
3658 let config = zai_session();
3659 let mut saved = fleet(
3660 "release",
3661 vec![
3662 member(
3663 "builder",
3664 Some((
3665 "zai",
3666 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
3667 )),
3668 ),
3669 member("reviewer", None),
3670 ],
3671 );
3672 save_fleet(&saved, FleetScope::Workspace, ws.path()).expect("save");
3673
3674 let (document, id) =
3675 load_fleet_document("release", ws.path(), Some(&config)).expect("loads");
3676 let roots = fleet_search_roots(ws.path());
3677 let workflow = ExactFleetWorkflow::capture(
3678 &document,
3679 id,
3680 "2026-09-22T00:00:00Z",
3681 Some(&config),
3682 &roots,
3683 None,
3684 )
3685 .expect("capture");
3686
3687 // Edit the saved Fleet mid-run.
3688 saved.members[0].model = Some("glm-4.6".to_string());
3689 save_fleet(&saved, FleetScope::Workspace, ws.path()).expect("re-save");
3690
3691 let builder = workflow
3692 .bind_member(Some("builder"), None, session_ceiling())
3693 .expect("bind builder");
3694 assert_eq!(
3695 builder.route.wire_model,
3696 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
3697 );
3698
3699 let reviewer = workflow
3700 .bind_member(Some("reviewer"), None, session_ceiling())
3701 .expect("bind reviewer");
3702 let frozen = workflow
3703 .snapshot()
3704 .members()
3705 .iter()
3706 .find(|member| member.id == "reviewer")
3707 .expect("reviewer in snapshot");
3708 assert_eq!(frozen.route.model, config.default_model());
3709 assert_eq!(reviewer.route.frozen().model, reviewer.route.wire_model);
3710 assert_eq!(
3711 reviewer.route.wire_model,
3712 codewhale_config::route::resolve_model(
3713 config.active_provider_identity().unwrap().provider,
3714 &config.default_model(),
3715 None,
3716 )
3717 .expect("session model is a known route")
3718 .logical
3719 );
3720 }
3721 }
3722
3722 lines RUST