返回 CodeWhale
fleet_exact.rs
根目录 / crates / workflow / src / fleet_exact.rs
1 //! Exact named-Fleet schema — fully resolved members, no late model choice.
2 //!
3 //! A named Fleet is a saved, reusable team. Two forms of `fleets/<name>.toml`
4 //! exist and both keep working:
5 //!
6 //! - **Legacy** (`[roles]` role → AgentProfile id). See [`crate::NamedFleet`].
7 //! Legacy files declare no `schema` key, which is what makes the legacy form
8 //! *explicitly detectable* rather than inferred from a missing table.
9 //! - **Exact** (`schema = "exact"`). Every member owns a stable member id/role,
10 //! an exact configured provider id, an exact model id, a requested reasoning
11 //! policy. Authority is deliberately absent: Runtime derives the effective
12 //! child posture from the selected member's Runtime role and the live parent.
13 //!
14 //! The exact form deliberately has **no** late-binding selectors. `inherit`,
15 //! `faster`/fast siblings, model-strength classes, and `model = "auto"` are
16 //! rejected at parse time, not silently resolved later — a Fleet the operator
17 //! saved is the Fleet that runs. Users switch Fleets; models never switch
18 //! themselves.
19 //!
20 //! The **Adaptive Reasoning Router is not a Fleet member.** A Fleet says *who*
21 //! runs; a Router is a separate, optional, reusable service that decides only
22 //! *how hard an already frozen route thinks*. An exact Fleet points at one by
23 //! name — `reasoning_router = "luna-low"` — and the same saved profile may be
24 //! referenced by any number of Fleets. See [`crate::reasoning_router`].
25 //!
26 //! The prototype form (`[[members]]` with `kind = "router"`) still parses, is
27 //! labelled **legacy inline**, and normalizes into the same captured service.
28 //! It is retained for compatibility only; it is not a second runtime concept.
29
30 use std::collections::BTreeMap;
31
32 use codewhale_protocol::fleet::PermissionCeiling;
33 #[cfg(test)]
34 use codewhale_protocol::fleet::ShellCeiling;
35 use serde::{Deserialize, Serialize};
36 use thiserror::Error;
37
38 use crate::reasoning_router::{FleetRouterRef, ReasoningRouterError, RouterCallReasoning};
39
40 /// Wire value of the `schema` key that selects the exact form.
41 pub const EXACT_FLEET_SCHEMA_KIND: &str = "exact";
42 /// Wire value recorded for files in the pre-exact role→profile form.
43 pub const LEGACY_FLEET_SCHEMA_KIND: &str = "legacy";
44 /// Current revision of the exact schema.
45 pub const EXACT_FLEET_SCHEMA_REVISION: u32 = 1;
46
47 /// Member kind that selects the Fleet Router.
48 pub const ROUTER_MEMBER_KIND: &str = "router";
49 /// Member kind for an ordinary dispatchable worker.
50 pub const WORKER_MEMBER_KIND: &str = "worker";
51
52 /// The Router's public id. A Router is addressed by this literal everywhere a
53 /// receipt, decision, or error names it, whatever the file called the member.
54 /// No worker may claim it — see [`ExactFleetError::ReservedRouterIdentity`].
55 pub const ROUTER_PUBLIC_ID: &str = "router";
56 /// The Router's public role. Identical to [`ROUTER_PUBLIC_ID`]: a Router has
57 /// exactly one identity and it is not a dispatchable role.
58 pub const ROUTER_PUBLIC_ROLE: &str = "router";
59
60 /// Public role names that were renamed, and what they are now called.
61 ///
62 /// A saved Fleet, a gate, a handoff record, and a task option are four
63 /// different places the *same* role name is written down, and they are written
64 /// at different times: a Fleet file saved a year ago says `oracle`, a workflow
65 /// script written today says `consultant`. Canonicalizing in only one of those
66 /// places is what turns a rename into a lookup failure, so every boundary that
67 /// compares a role goes through [`canonical_role_key`].
68 ///
69 /// New schemas and receipts always record the canonical name — the alias is an
70 /// input spelling, never an output one.
71 pub const ROLE_ALIASES: &[(&str, &str)] = &[("oracle", "consultant"), ("advisor", "consultant")];
72
73 /// The canonical, case-folded key a role compares under.
74 ///
75 /// Trims, lowercases, and resolves a renamed public role to its current name.
76 /// This is the *only* way roles are compared anywhere in the exact-Fleet path:
77 /// parse writes the canonical name into the roster, `validate` detects
78 /// duplicates under it, and every lookup resolves the caller's spelling through
79 /// it. A member saved as `oracle` and a task naming `consultant` therefore meet,
80 /// and so do the reverse.
81 #[must_use]
82 pub fn canonical_role_key(value: &str) -> String {
83 let key = value.trim().to_ascii_lowercase();
84 ROLE_ALIASES
85 .iter()
86 .find(|(alias, _)| *alias == key)
87 .map_or(key, |(_, canonical)| (*canonical).to_string())
88 }
89
90 /// The case-folded key a member **id** compares under.
91 ///
92 /// Ids are identities, not names, so they get no alias table — but they do get
93 /// case folding, because `ExactFleet` is `Deserialize` and a roster can reach a
94 /// lookup without having passed the parser that lowercased it.
95 #[must_use]
96 pub fn canonical_member_key(value: &str) -> String {
97 value.trim().to_ascii_lowercase()
98 }
99
100 /// Selector tokens that are legal elsewhere in CodeWhale but are exactly what
101 /// the exact schema exists to forbid. Rejecting them by value (in addition to
102 /// `deny_unknown_fields` rejecting `model_strength`/`loadout`/`model_class` as
103 /// keys) is what keeps "exact" honest.
104 const FORBIDDEN_ROUTE_SELECTORS: &[&str] = &[
105 "auto", "inherit", "parent", "same", "faster", "fast", "cheap", "strong", "balanced", "default",
106 ];
107
108 /// A concrete reasoning tier. Unlike [`RequestedReasoning`] this has no `auto`
109 /// — it is what a request actually runs at.
110 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
111 #[serde(rename_all = "snake_case")]
112 pub enum ReasoningTier {
113 Off,
114 Low,
115 Medium,
116 High,
117 Max,
118 }
119
120 impl ReasoningTier {
121 #[must_use]
122 pub const fn as_str(self) -> &'static str {
123 match self {
124 Self::Off => "off",
125 Self::Low => "low",
126 Self::Medium => "medium",
127 Self::High => "high",
128 Self::Max => "max",
129 }
130 }
131
132 /// Parse a concrete tier. `auto` is intentionally NOT accepted here.
133 pub fn parse(value: &str) -> Option<Self> {
134 match value.trim().to_ascii_lowercase().as_str() {
135 "off" | "none" | "disabled" => Some(Self::Off),
136 "low" | "minimal" => Some(Self::Low),
137 "medium" | "mid" => Some(Self::Medium),
138 "high" => Some(Self::High),
139 "max" | "maximum" | "xhigh" => Some(Self::Max),
140 _ => None,
141 }
142 }
143 }
144
145 /// The reasoning policy a member *requests*. `Auto` is an explicit per-member
146 /// opt-in, never a global mode.
147 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
148 #[serde(rename_all = "snake_case")]
149 pub enum RequestedReasoning {
150 Off,
151 Low,
152 Medium,
153 High,
154 Max,
155 Auto,
156 }
157
158 impl RequestedReasoning {
159 #[must_use]
160 pub const fn as_str(self) -> &'static str {
161 match self {
162 Self::Off => "off",
163 Self::Low => "low",
164 Self::Medium => "medium",
165 Self::High => "high",
166 Self::Max => "max",
167 Self::Auto => "auto",
168 }
169 }
170
171 #[must_use]
172 pub const fn is_auto(self) -> bool {
173 matches!(self, Self::Auto)
174 }
175
176 /// The concrete tier this request names, or `None` for `auto`.
177 #[must_use]
178 pub const fn tier(self) -> Option<ReasoningTier> {
179 match self {
180 Self::Off => Some(ReasoningTier::Off),
181 Self::Low => Some(ReasoningTier::Low),
182 Self::Medium => Some(ReasoningTier::Medium),
183 Self::High => Some(ReasoningTier::High),
184 Self::Max => Some(ReasoningTier::Max),
185 Self::Auto => None,
186 }
187 }
188
189 pub fn parse(value: &str) -> Option<Self> {
190 if matches!(value.trim().to_ascii_lowercase().as_str(), "auto") {
191 return Some(Self::Auto);
192 }
193 ReasoningTier::parse(value).map(|tier| match tier {
194 ReasoningTier::Off => Self::Off,
195 ReasoningTier::Low => Self::Low,
196 ReasoningTier::Medium => Self::Medium,
197 ReasoningTier::High => Self::High,
198 ReasoningTier::Max => Self::Max,
199 })
200 }
201 }
202
203 /// The exact provider/model a member is frozen to before any reasoning
204 /// resolution runs. Nothing downstream may change these two strings.
205 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
206 pub struct FrozenRoute {
207 pub provider: String,
208 pub model: String,
209 }
210
211 /// A dispatchable exact Fleet member.
212 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213 pub struct ExactMember {
214 /// Stable member id — the identity a run refers to.
215 pub id: String,
216 /// Role name; defaults to the member id.
217 pub role: String,
218 /// Exact configured provider id (a `[providers.<id>]` key or a built-in id).
219 pub provider: String,
220 /// Exact model id.
221 pub model: String,
222 /// Requested reasoning policy for this member.
223 pub reasoning: RequestedReasoning,
224 }
225
226 impl ExactMember {
227 /// The provider/model pair, frozen. Callers resolve reasoning *after* this.
228 #[must_use]
229 pub fn frozen_route(&self) -> FrozenRoute {
230 FrozenRoute {
231 provider: self.provider.clone(),
232 model: self.model.clone(),
233 }
234 }
235
236 #[must_use]
237 pub const fn is_dispatchable(&self) -> bool {
238 true
239 }
240 }
241
242 /// The **legacy inline** Router form: a `[[members]]` entry with
243 /// `kind = "router"`.
244 ///
245 /// Retained for compatibility with Fleet files written against the prototype.
246 /// It is normalized into [`crate::reasoning_router::CapturedReasoningRouter`]
247 /// at capture, so nothing downstream sees two kinds of Router. New Fleets
248 /// should use `reasoning_router = "<name>"` and a saved profile, which is what
249 /// lets several Fleets share one Router configuration.
250 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251 pub struct RouterMember {
252 pub id: String,
253 pub provider: String,
254 pub model: String,
255 /// What the Router's own call runs at — `off` or `low` only, exactly as for
256 /// a saved profile. Defaults to `off`; `auto` is rejected (a router cannot
257 /// ask a router what to think) and `medium`/`high`/`max` are rejected
258 /// rather than clamped.
259 #[serde(default, alias = "reasoning")]
260 pub call_reasoning: RouterCallReasoning,
261 }
262
263 impl RouterMember {
264 /// The Router's public id — always the literal `router`, regardless of the
265 /// member id the file used. Receipts and errors name this, so a Fleet
266 /// cannot disguise its Router behind a friendly label.
267 #[must_use]
268 pub const fn public_id(&self) -> &'static str {
269 ROUTER_PUBLIC_ID
270 }
271
272 /// The Router's public role — always the literal `router`.
273 #[must_use]
274 pub const fn public_role(&self) -> &'static str {
275 ROUTER_PUBLIC_ROLE
276 }
277
278 /// A Router is never a worker. This is a constant, not a policy lookup.
279 #[must_use]
280 pub const fn is_dispatchable(&self) -> bool {
281 false
282 }
283
284 /// The Router's tool surface is empty, always.
285 #[must_use]
286 pub const fn tool_surface(&self) -> &'static [&'static str] {
287 &[]
288 }
289
290 /// The Router's fixed permission ceiling.
291 #[must_use]
292 pub const fn permissions(&self) -> PermissionCeiling {
293 PermissionCeiling::ROUTER
294 }
295
296 #[must_use]
297 pub fn frozen_route(&self) -> FrozenRoute {
298 FrozenRoute {
299 provider: self.provider.clone(),
300 model: self.model.clone(),
301 }
302 }
303 }
304
305 /// A parsed exact Fleet.
306 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307 pub struct ExactFleet {
308 pub name: String,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub description: Option<String>,
311 pub schema_revision: u32,
312 pub members: Vec<ExactMember>,
313 /// Name of the saved Reasoning Router profile this Fleet references. The
314 /// profile is a separate, reusable service — several Fleets may name the
315 /// same one. Accepts a qualified `origin/name`.
316 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub reasoning_router: Option<String>,
318 /// The legacy inline Router, if the file used the prototype form.
319 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub router: Option<RouterMember>,
321 }
322
323 impl ExactFleet {
324 /// Look up a dispatchable member by its **member id only**.
325 ///
326 /// Roles are semantic labels used by gates, handoffs, and records; ids are
327 /// what addresses a roster entry. Keeping the two lookups separate is what
328 /// lets a task carry a meaningful role (`builder`) while the runtime
329 /// resolves a distinct profile id (`implementer`) — see
330 /// [`Self::member_by_role`].
331 #[must_use]
332 pub fn member(&self, id: &str) -> Option<&ExactMember> {
333 let key = canonical_member_key(id);
334 self.members
335 .iter()
336 .find(|member| canonical_member_key(&member.id) == key)
337 }
338
339 /// Look up a dispatchable member by its semantic role.
340 ///
341 /// Both sides resolve through [`canonical_role_key`], so a member saved
342 /// under a renamed role (`oracle`) is found by a task, gate, or handoff that
343 /// names either spelling.
344 #[must_use]
345 pub fn member_by_role(&self, role: &str) -> Option<&ExactMember> {
346 let key = canonical_role_key(role);
347 self.members
348 .iter()
349 .find(|member| canonical_role_key(&member.role) == key)
350 }
351
352 /// Look up a member by id first, then by role. Roster invariants forbid an
353 /// id/role collision, so this can never be order-dependent.
354 #[must_use]
355 pub fn member_by_id_or_role(&self, id_or_role: &str) -> Option<&ExactMember> {
356 self.member(id_or_role)
357 .or_else(|| self.member_by_role(id_or_role))
358 }
359
360 /// How this Fleet points at its Router, if it does at all.
361 #[must_use]
362 pub fn router_ref(&self) -> Option<FleetRouterRef> {
363 if let Some(name) = &self.reasoning_router {
364 return Some(FleetRouterRef::Profile { name: name.clone() });
365 }
366 self.router
367 .as_ref()
368 .map(|member| FleetRouterRef::LegacyInline(Box::new(member.clone())))
369 }
370
371 /// The legacy inline Router member, if the file used the prototype form.
372 #[must_use]
373 pub fn legacy_inline_router(&self) -> Option<&RouterMember> {
374 self.router.as_ref()
375 }
376
377 /// Whether any member explicitly requested `reasoning = "auto"`.
378 #[must_use]
379 pub fn has_auto_member(&self) -> bool {
380 self.members.iter().any(|member| member.reasoning.is_auto())
381 }
382
383 /// Re-check every roster invariant that [`Self::parse`] enforces.
384 ///
385 /// `ExactFleet` is `pub` and `Deserialize`, so a value can reach a snapshot
386 /// without ever passing through the TOML parser. Capture calls this so a
387 /// hand-built or round-tripped roster cannot smuggle in a duplicate role, an
388 /// id/role collision, or a worker claiming the Router's identity.
389 pub fn validate(&self) -> Result<(), ExactFleetError> {
390 if self.members.is_empty() {
391 return Err(ExactFleetError::NoMembers {
392 fleet: self.name.clone(),
393 });
394 }
395
396 let mut ids: BTreeMap<String, ()> = BTreeMap::new();
397 let mut roles: BTreeMap<String, ()> = BTreeMap::new();
398
399 for member in &self.members {
400 let id = canonical_member_key(&member.id);
401 // Duplicate detection runs on the canonical role key, so a roster
402 // carrying both `oracle` and `consultant` is caught as the collision
403 // it is rather than resolving by list order at lookup time.
404 let role = canonical_role_key(&member.role);
405 if id.is_empty() {
406 return Err(ExactFleetError::InvalidToken {
407 field: "member id".to_string(),
408 value: member.id.clone(),
409 });
410 }
411 if role.is_empty() {
412 return Err(ExactFleetError::InvalidToken {
413 field: "member role".to_string(),
414 value: member.role.clone(),
415 });
416 }
417 // A worker may never be called `router`, by id or by role: the
418 // Router's public identity is that literal, and a worker wearing it
419 // would make a receipt ambiguous about who decided the reasoning.
420 for (field, value) in [("id", &id), ("role", &role)] {
421 if value.as_str() == ROUTER_PUBLIC_ID {
422 return Err(ExactFleetError::ReservedRouterIdentity {
423 id: member.id.clone(),
424 field: field.to_string(),
425 });
426 }
427 }
428 if ids.insert(id.clone(), ()).is_some() {
429 return Err(ExactFleetError::DuplicateMember { id });
430 }
431 if roles.insert(role.clone(), ()).is_some() {
432 return Err(ExactFleetError::DuplicateRole { role });
433 }
434 }
435
436 // An id belonging to one member and a role belonging to a *different*
437 // member would make `member()` lookup order-dependent, so it is a
438 // collision even though neither set has an internal duplicate.
439 for member in &self.members {
440 let id = canonical_member_key(&member.id);
441 if let Some(other) = self
442 .members
443 .iter()
444 .find(|other| other.id != member.id && canonical_role_key(&other.role) == id)
445 {
446 return Err(ExactFleetError::IdRoleCollision {
447 id: member.id.clone(),
448 other: other.id.clone(),
449 });
450 }
451 }
452
453 Ok(())
454 }
455
456 /// Parse an exact Fleet from TOML text.
457 pub fn parse(text: &str) -> Result<Self, ExactFleetError> {
458 let doc: ExactFleetToml =
459 toml::from_str(text).map_err(|error| ExactFleetError::Parse(error.to_string()))?;
460 Self::from_toml(doc)
461 }
462
463 fn from_toml(doc: ExactFleetToml) -> Result<Self, ExactFleetError> {
464 if !doc
465 .schema
466 .trim()
467 .eq_ignore_ascii_case(EXACT_FLEET_SCHEMA_KIND)
468 {
469 return Err(ExactFleetError::UnknownSchema {
470 schema: doc.schema.trim().to_string(),
471 });
472 }
473 if doc.schema_revision != EXACT_FLEET_SCHEMA_REVISION {
474 return Err(ExactFleetError::UnsupportedRevision {
475 revision: doc.schema_revision,
476 supported: EXACT_FLEET_SCHEMA_REVISION,
477 });
478 }
479 let name = require_token(&doc.name, "name")?;
480
481 let mut members = Vec::new();
482 let mut router: Option<RouterMember> = None;
483 let mut seen: BTreeMap<String, ()> = BTreeMap::new();
484
485 for raw in doc.members {
486 let id = require_token(&raw.id, "member id")?;
487 if seen.insert(id.clone(), ()).is_some() {
488 return Err(ExactFleetError::DuplicateMember { id });
489 }
490 let provider = require_exact_route_token(&raw.provider, &id, "provider")?;
491 let model = require_exact_route_token(&raw.model, &id, "model")?;
492 let kind = raw
493 .kind
494 .as_deref()
495 .map(str::trim)
496 .filter(|kind| !kind.is_empty())
497 .unwrap_or(WORKER_MEMBER_KIND)
498 .to_ascii_lowercase();
499
500 match kind.as_str() {
501 ROUTER_MEMBER_KIND => {
502 if router.is_some() {
503 return Err(ExactFleetError::MultipleRouters);
504 }
505 if raw.role.is_some() {
506 return Err(ExactFleetError::RouterRoleDeclared { id });
507 }
508 let call_reasoning = match raw.reasoning.as_deref() {
509 None => RouterCallReasoning::default(),
510 Some(value) if value.trim().eq_ignore_ascii_case("auto") => {
511 return Err(ExactFleetError::RouterAutoReasoning { id });
512 }
513 // The cheap ceiling is a property of the *service*, not
514 // of how it was written down, so the legacy inline form
515 // gets the identical rejection a saved profile gets.
516 Some(value) => RouterCallReasoning::parse(value, &id)
517 .map_err(|source| ExactFleetError::Router { source })?,
518 };
519 router = Some(RouterMember {
520 id,
521 provider,
522 model,
523 call_reasoning,
524 });
525 }
526 WORKER_MEMBER_KIND => {
527 let role = match raw.role.as_deref() {
528 Some(role) => require_member_role(role)?,
529 None => id.clone(),
530 };
531 let reasoning = match raw.reasoning.as_deref() {
532 None => RequestedReasoning::Off,
533 Some(value) => RequestedReasoning::parse(value).ok_or_else(|| {
534 ExactFleetError::InvalidReasoning {
535 id: id.clone(),
536 value: value.trim().to_string(),
537 }
538 })?,
539 };
540 members.push(ExactMember {
541 id,
542 role,
543 provider,
544 model,
545 reasoning,
546 });
547 }
548 other => {
549 return Err(ExactFleetError::UnknownMemberKind {
550 id,
551 kind: other.to_string(),
552 });
553 }
554 }
555 }
556
557 if members.is_empty() {
558 return Err(ExactFleetError::NoMembers { fleet: name });
559 }
560
561 // One Router per Fleet, named exactly one way. Declaring both forms is
562 // an error rather than a precedence rule: a silent winner here would
563 // decide which provider sees every routing summary.
564 let reasoning_router = match doc.reasoning_router.as_deref().map(str::trim) {
565 Some(value) if !value.is_empty() => {
566 if router.is_some() {
567 return Err(ExactFleetError::ConflictingRouterDeclarations { fleet: name });
568 }
569 Some(value.to_string())
570 }
571 _ => None,
572 };
573
574 let fleet = Self {
575 name,
576 description: doc.description,
577 schema_revision: doc.schema_revision,
578 members,
579 reasoning_router,
580 router,
581 };
582 // One authority for the roster invariants, shared with capture-time
583 // revalidation so the two can never drift.
584 fleet.validate()?;
585 Ok(fleet)
586 }
587 }
588
589 /// Peek at a fleet document's `schema` key without committing to a form.
590 ///
591 /// Returns `None` for legacy files, which declare no `schema` key at all.
592 /// A malformed document returns `None` too; the legacy parser then owns the
593 /// error, keeping old files on the old diagnostics.
594 #[must_use]
595 pub fn declared_schema_kind(text: &str) -> Option<String> {
596 #[derive(Deserialize)]
597 struct SchemaProbe {
598 #[serde(default)]
599 schema: Option<String>,
600 }
601
602 let probe: SchemaProbe = toml::from_str(text).ok()?;
603 probe
604 .schema
605 .map(|schema| schema.trim().to_ascii_lowercase())
606 .filter(|schema| !schema.is_empty())
607 }
608
609 #[derive(Debug, Deserialize)]
610 #[serde(deny_unknown_fields)]
611 struct ExactFleetToml {
612 name: String,
613 #[serde(default)]
614 description: Option<String>,
615 schema: String,
616 #[serde(default = "default_schema_revision")]
617 schema_revision: u32,
618 /// Reference to a saved Reasoning Router profile. Optional: a Fleet whose
619 /// members all pin explicit tiers needs no Router at all.
620 #[serde(default)]
621 reasoning_router: Option<String>,
622 #[serde(default)]
623 members: Vec<ExactMemberToml>,
624 }
625
626 /// `deny_unknown_fields` is load-bearing here: it is what rejects
627 /// `model_strength`, `loadout`, `model_class`, and any other late-binding
628 /// selector someone tries to smuggle into an exact member.
629 #[derive(Debug, Deserialize)]
630 #[serde(deny_unknown_fields)]
631 struct ExactMemberToml {
632 id: String,
633 #[serde(default)]
634 kind: Option<String>,
635 #[serde(default)]
636 role: Option<String>,
637 provider: String,
638 model: String,
639 #[serde(default)]
640 reasoning: Option<String>,
641 /// Compatibility-only input from the prototype exact-Fleet schema.
642 ///
643 /// It is intentionally a generic TOML value and intentionally unread:
644 /// old files and replays remain loadable, while no spelling can influence
645 /// active identity, snapshots, selection, or Runtime authority.
646 #[serde(default, rename = "permissions")]
647 _legacy_permissions: Option<toml::Value>,
648 }
649
650 const fn default_schema_revision() -> u32 {
651 EXACT_FLEET_SCHEMA_REVISION
652 }
653
654 fn require_token(value: &str, field: &str) -> Result<String, ExactFleetError> {
655 crate::role_resolve::normalize_token(value).ok_or_else(|| ExactFleetError::InvalidToken {
656 field: field.to_string(),
657 value: value.trim().to_string(),
658 })
659 }
660
661 /// Canonicalize the renamed public roles at the saved-Fleet boundary, so a new
662 /// schema and every receipt it produces record only the current name.
663 ///
664 /// Exact Fleets otherwise permit domain-specific semantic roles (for example
665 /// `auditor`), so this is intentionally not a closed-role parser. The alias
666 /// table is shared with [`canonical_role_key`], which is what makes an *old*
667 /// file — parsed before this canonicalization existed, or reaching the roster
668 /// through `Deserialize` — still resolvable by either spelling at lookup time.
669 fn require_member_role(value: &str) -> Result<String, ExactFleetError> {
670 let role = require_token(value, "member role")?;
671 Ok(canonical_role_key(&role))
672 }
673
674 /// Provider/model ids keep their configured casing (a model id is
675 /// case-sensitive on the wire) but must be non-empty, whitespace-free, and must
676 /// not be a late-binding selector.
677 fn require_exact_route_token(
678 value: &str,
679 member: &str,
680 field: &str,
681 ) -> Result<String, ExactFleetError> {
682 let trimmed = value.trim();
683 if trimmed.is_empty()
684 || trimmed
685 .chars()
686 .any(|ch| ch.is_whitespace() || matches!(ch, '"' | '\'' | '`' | '='))
687 {
688 return Err(ExactFleetError::InvalidToken {
689 field: format!("{member}.{field}"),
690 value: trimmed.to_string(),
691 });
692 }
693 if FORBIDDEN_ROUTE_SELECTORS
694 .iter()
695 .any(|selector| trimmed.eq_ignore_ascii_case(selector))
696 {
697 return Err(ExactFleetError::LateBindingSelector {
698 id: member.to_string(),
699 field: field.to_string(),
700 value: trimmed.to_string(),
701 });
702 }
703 Ok(trimmed.to_string())
704 }
705
706 #[derive(Debug, Clone, PartialEq, Eq, Error)]
707 pub enum ExactFleetError {
708 #[error("failed to parse exact fleet file: {0}")]
709 Parse(String),
710 #[error("unknown fleet schema `{schema}`; expected `exact`")]
711 UnknownSchema { schema: String },
712 #[error(
713 "exact fleet schema revision {revision} is not supported (this build reads {supported})"
714 )]
715 UnsupportedRevision { revision: u32, supported: u32 },
716 #[error("{field} must be a non-empty token without whitespace, quotes, or `=` (got `{value}`)")]
717 InvalidToken { field: String, value: String },
718 #[error("duplicate fleet member id `{id}`")]
719 DuplicateMember { id: String },
720 #[error(
721 "duplicate fleet member role `{role}`; two members cannot answer to the same role or a \
722 task naming it would resolve to whichever one happened to be listed first"
723 )]
724 DuplicateRole { role: String },
725 #[error(
726 "member `{id}` collides with member `{other}`: one member's id is another member's role, \
727 so a task naming it would resolve by list order rather than by identity"
728 )]
729 IdRoleCollision { id: String, other: String },
730 #[error(
731 "member `{id}` claims the reserved {field} `router`; that identity belongs to the fleet \
732 router, which is declared with `kind = \"router\"` and is never dispatchable"
733 )]
734 ReservedRouterIdentity { id: String, field: String },
735 #[error(
736 "fleet `{fleet}` snapshot content hash does not describe its own contents (recorded \
737 `{recorded}`, recomputed `{recomputed}`). The snapshot was edited or migrated after \
738 capture, so its hash cannot be used as evidence that a run matched a saved definition. \
739 Re-capture the fleet."
740 )]
741 ContentHashMismatch {
742 fleet: String,
743 recorded: String,
744 recomputed: String,
745 },
746 #[error("fleet `{fleet}` declares no dispatchable members")]
747 NoMembers { fleet: String },
748 #[error("member `{id}` has unknown kind `{kind}`; expected `worker` or `router`")]
749 UnknownMemberKind { id: String, kind: String },
750 #[error("a fleet may declare at most one router member")]
751 MultipleRouters,
752 #[error(
753 "member `{id}`.{field} is `{value}`, but exact fleets forbid late-binding route selectors \
754 (inherit, fast siblings, model strength, or model=auto). Name the exact provider/model."
755 )]
756 LateBindingSelector {
757 id: String,
758 field: String,
759 value: String,
760 },
761 #[error(
762 "member `{id}` has invalid reasoning `{value}`; expected off, low, medium, high, max, or auto"
763 )]
764 InvalidReasoning { id: String, value: String },
765 #[error(
766 "router member `{id}` may not declare a role; a router is never dispatched as a worker"
767 )]
768 RouterRoleDeclared { id: String },
769 #[error(
770 "router member `{id}` may not request reasoning `auto`; a router's own thinking is a fixed tier (default off)"
771 )]
772 RouterAutoReasoning { id: String },
773 #[error(
774 "fleet `{fleet}` declares both `reasoning_router = \"...\"` and an inline \
775 `kind = \"router\"` member. A fleet references exactly one reasoning router service; \
776 pick the saved profile (preferred, and shareable across fleets) or the legacy inline \
777 form, not both."
778 )]
779 ConflictingRouterDeclarations { fleet: String },
780 #[error(transparent)]
781 Router {
782 #[from]
783 source: ReasoningRouterError,
784 },
785 }
786
787 #[cfg(test)]
788 mod role_alias_tests {
789 use super::*;
790
791 /// A Fleet saved before the rename. The file spells the advisory role
792 /// `oracle`; everything downstream must call it `consultant`.
793 const RENAMED_ROLE_FLEET: &str = r#"
794 name = "counsel"
795 schema = "exact"
796
797 [[members]]
798 id = "advisor-one"
799 role = "oracle"
800 provider = "zai"
801 model = "glm-5"
802 permissions = "analyst"
803 "#;
804
805 /// Parse canonicalizes on the way in, so the roster — and therefore every
806 /// receipt built from it — records only the current name.
807 #[test]
808 fn parsing_a_renamed_role_stores_the_canonical_name() {
809 let fleet = ExactFleet::parse(RENAMED_ROLE_FLEET).expect("parse");
810 assert_eq!(fleet.members[0].role, "consultant");
811 }
812
813 /// The compatibility half: a saved task, gate, or handoff that still spells
814 /// the role the old way resolves to the same member. This is the lookup that
815 /// used to fail, because parse canonicalized and the lookup did not.
816 #[test]
817 fn every_alias_spelling_resolves_to_the_same_member() {
818 let fleet = ExactFleet::parse(RENAMED_ROLE_FLEET).expect("parse");
819
820 for spelling in ["consultant", "oracle", "advisor", "Oracle", " ADVISOR "] {
821 let member = fleet
822 .member_by_role(spelling)
823 .unwrap_or_else(|| panic!("`{spelling}` must resolve"));
824 assert_eq!(member.id, "advisor-one");
825 assert_eq!(member.role, "consultant", "receipts stay canonical");
826 }
827
828 // `member_by_id_or_role` is what the runtime actually calls.
829 assert_eq!(
830 fleet
831 .member_by_id_or_role("oracle")
832 .expect("alias resolves through the combined lookup")
833 .id,
834 "advisor-one"
835 );
836 }
837
838 /// A Fleet written against the *new* name keeps working, and is equally
839 /// reachable by the old one — the rename is bidirectional at the lookup.
840 #[test]
841 fn a_canonical_role_is_reachable_by_its_alias() {
842 let text = RENAMED_ROLE_FLEET.replace(r#"role = "oracle""#, r#"role = "consultant""#);
843 let fleet = ExactFleet::parse(&text).expect("parse");
844
845 assert_eq!(fleet.members[0].role, "consultant");
846 assert!(fleet.member_by_role("oracle").is_some());
847 assert!(fleet.member_by_role("advisor").is_some());
848 }
849
850 /// A roster that reaches `validate` through `Deserialize` — never having
851 /// passed the parser — is still judged on canonical keys. `oracle` and
852 /// `consultant` are one role, so declaring both is the collision it looks
853 /// like, not a pair that resolves by list order.
854 #[test]
855 fn an_alias_and_its_canonical_name_collide_on_reload() {
856 let member = |id: &str, role: &str| ExactMember {
857 id: id.to_string(),
858 role: role.to_string(),
859 provider: "zai".to_string(),
860 model: "glm-5".to_string(),
861 reasoning: RequestedReasoning::Off,
862 };
863 let fleet = ExactFleet {
864 name: "counsel".to_string(),
865 description: None,
866 schema_revision: EXACT_FLEET_SCHEMA_REVISION,
867 members: vec![member("a", "oracle"), member("b", "consultant")],
868 reasoning_router: None,
869 router: None,
870 };
871
872 assert!(matches!(
873 fleet.validate(),
874 Err(ExactFleetError::DuplicateRole { role }) if role == "consultant"
875 ));
876 }
877
878 /// Ids are identities, not names: no alias table, but case folding, because
879 /// a deserialized roster never passed the parser that lowercased it.
880 #[test]
881 fn member_ids_resolve_case_insensitively_without_aliasing() {
882 let fleet = ExactFleet {
883 name: "counsel".to_string(),
884 description: None,
885 schema_revision: EXACT_FLEET_SCHEMA_REVISION,
886 members: vec![ExactMember {
887 id: "Builder".to_string(),
888 role: "auditor".to_string(),
889 provider: "zai".to_string(),
890 model: "glm-5".to_string(),
891 reasoning: RequestedReasoning::Off,
892 }],
893 reasoning_router: None,
894 router: None,
895 };
896
897 assert!(fleet.member("builder").is_some());
898 assert!(fleet.member("Builder").is_some());
899 // `oracle` is a role alias, never an id alias.
900 assert!(fleet.member("oracle").is_none());
901 }
902
903 #[test]
904 fn canonical_role_key_maps_only_the_declared_aliases() {
905 assert_eq!(canonical_role_key(" Oracle "), "consultant");
906 assert_eq!(canonical_role_key("ADVISOR"), "consultant");
907 assert_eq!(canonical_role_key("consultant"), "consultant");
908 // Unrelated semantic roles pass through untouched, case-folded only.
909 assert_eq!(canonical_role_key("Auditor"), "auditor");
910 assert_eq!(canonical_role_key("router"), "router");
911 }
912 }
913
914 #[cfg(test)]
915 mod tests {
916 use super::*;
917
918 const GLM_FLEET: &str = r#"
919 name = "glm-pair"
920 description = "GLM worker with a GLM Turbo router"
921 schema = "exact"
922 schema_revision = 1
923
924 [[members]]
925 id = "implementer"
926 role = "builder"
927 provider = "zai"
928 model = "glm-5"
929 reasoning = "auto"
930 permissions = "read_write"
931
932 [[members]]
933 id = "router"
934 kind = "router"
935 provider = "zai"
936 model = "glm-5-turbo"
937 "#;
938
939 /// A Fleet that references a saved, reusable Router service by name — the
940 /// form new Fleets use.
941 const NAMED_ROUTER_FLEET: &str = r#"
942 name = "glm-pair"
943 schema = "exact"
944 reasoning_router = "luna-low"
945
946 [[members]]
947 id = "implementer"
948 role = "builder"
949 provider = "zai"
950 model = "glm-5"
951 reasoning = "auto"
952 "#;
953
954 #[test]
955 fn exact_fleet_parses_members_and_a_legacy_inline_router() {
956 let fleet = ExactFleet::parse(GLM_FLEET).expect("parse");
957 assert_eq!(fleet.name, "glm-pair");
958 assert_eq!(fleet.schema_revision, EXACT_FLEET_SCHEMA_REVISION);
959 assert_eq!(fleet.members.len(), 1);
960
961 // Id and role are separate lookups: a role is a semantic label, an id
962 // addresses a roster entry.
963 let member = fleet.member_by_role("builder").expect("role lookup");
964 assert_eq!(member.id, "implementer");
965 assert_eq!(
966 fleet.member("implementer").expect("id lookup").id,
967 "implementer"
968 );
969 assert!(
970 fleet.member("builder").is_none(),
971 "an id lookup must not answer to a role"
972 );
973 assert_eq!(member.provider, "zai");
974 assert_eq!(member.model, "glm-5");
975 assert_eq!(member.reasoning, RequestedReasoning::Auto);
976 let serialized = serde_json::to_value(member).expect("serialize member");
977 assert!(
978 serialized.get("permissions").is_none(),
979 "exact member identity must not carry authority: {serialized}"
980 );
981
982 let router = fleet.legacy_inline_router().expect("inline router");
983 assert_eq!(router.provider, "zai");
984 assert_eq!(router.model, "glm-5-turbo");
985 // The call tier defaults to off when the file says nothing.
986 assert_eq!(router.call_reasoning, RouterCallReasoning::Off);
987 assert!(matches!(
988 fleet.router_ref(),
989 Some(FleetRouterRef::LegacyInline(_))
990 ));
991 }
992
993 #[test]
994 fn legacy_advisory_role_names_canonicalize_to_consultant() {
995 for legacy in ["oracle", "advisor"] {
996 let text = GLM_FLEET.replace("role = \"builder\"", &format!("role = \"{legacy}\""));
997 let fleet = ExactFleet::parse(&text).expect("legacy role parses");
998 assert_eq!(fleet.members[0].role, "consultant");
999 assert!(fleet.member_by_role("consultant").is_some());
1000 // The rename resolves in both directions: the roster stores the
1001 // canonical name, and a caller still spelling the legacy one lands
1002 // on the same member rather than on nothing.
1003 assert_eq!(
1004 fleet
1005 .member_by_role(legacy)
1006 .map(|member| member.id.as_str()),
1007 fleet
1008 .member_by_role("consultant")
1009 .map(|member| member.id.as_str()),
1010 );
1011 }
1012 }
1013
1014 /// The preferred form: the Router is a *reference* to a saved service, so
1015 /// several Fleets can point at one configuration.
1016 #[test]
1017 fn a_fleet_references_a_named_reasoning_router_service() {
1018 let fleet = ExactFleet::parse(NAMED_ROUTER_FLEET).expect("parse");
1019
1020 assert_eq!(fleet.reasoning_router.as_deref(), Some("luna-low"));
1021 assert!(fleet.legacy_inline_router().is_none());
1022 assert!(matches!(
1023 fleet.router_ref(),
1024 Some(FleetRouterRef::Profile { ref name }) if name == "luna-low"
1025 ));
1026 assert!(fleet.has_auto_member());
1027
1028 // A qualified origin is accepted verbatim; resolution happens in the
1029 // host that owns the search roots.
1030 let qualified = NAMED_ROUTER_FLEET.replace("\"luna-low\"", "\"codewhale_home/luna-low\"");
1031 assert!(matches!(
1032 ExactFleet::parse(&qualified).expect("parse").router_ref(),
1033 Some(FleetRouterRef::Profile { ref name }) if name == "codewhale_home/luna-low"
1034 ));
1035 }
1036
1037 /// Both forms at once would make a silent winner decide which provider sees
1038 /// every routing summary, so it is an error instead.
1039 #[test]
1040 fn declaring_both_router_forms_is_rejected() {
1041 let both = GLM_FLEET.replace(
1042 "schema_revision = 1",
1043 "schema_revision = 1\nreasoning_router = \"luna-low\"",
1044 );
1045 let err = ExactFleet::parse(&both).expect_err("two router declarations");
1046 assert!(
1047 matches!(err, ExactFleetError::ConflictingRouterDeclarations { .. }),
1048 "{err:?}"
1049 );
1050 assert!(err.to_string().contains("exactly one"), "{err}");
1051 }
1052
1053 /// The cheap call ceiling belongs to the service, not to how it was written
1054 /// down: the inline form gets the identical rejection a saved profile does.
1055 #[test]
1056 fn a_legacy_inline_router_may_not_request_an_expensive_call_tier() {
1057 for value in ["medium", "high", "max"] {
1058 let text = format!("{GLM_FLEET}reasoning = \"{value}\"\n");
1059 let err = ExactFleet::parse(&text).expect_err("expensive router tier");
1060 assert!(
1061 matches!(
1062 err,
1063 ExactFleetError::Router {
1064 source: ReasoningRouterError::CallReasoningTooExpensive { .. }
1065 }
1066 ),
1067 "value={value} err={err:?}"
1068 );
1069 }
1070
1071 let low = format!("{GLM_FLEET}reasoning = \"low\"\n");
1072 assert_eq!(
1073 ExactFleet::parse(&low)
1074 .expect("low is allowed")
1075 .legacy_inline_router()
1076 .expect("router")
1077 .call_reasoning,
1078 RouterCallReasoning::Low
1079 );
1080 }
1081
1082 #[test]
1083 fn a_router_is_not_dispatchable_and_holds_no_authority() {
1084 let fleet = ExactFleet::parse(GLM_FLEET).expect("parse");
1085 let router = fleet.legacy_inline_router().expect("router");
1086
1087 assert!(!router.is_dispatchable());
1088 assert!(router.tool_surface().is_empty());
1089 let permissions = router.permissions();
1090 assert!(!permissions.tools);
1091 assert!(!permissions.write);
1092 assert!(!permissions.network_tool);
1093 assert_eq!(permissions.shell, ShellCeiling::None);
1094 assert_eq!(permissions.delegation_depth, 0);
1095
1096 // The router is not reachable through worker lookup either.
1097 assert!(fleet.member_by_id_or_role("router").is_none());
1098 assert!(fleet.members.iter().all(ExactMember::is_dispatchable));
1099 }
1100
1101 #[test]
1102 fn late_binding_selectors_are_rejected() {
1103 for (field, value) in [
1104 ("model", "auto"),
1105 ("model", "inherit"),
1106 ("model", "faster"),
1107 ("model", "strong"),
1108 ("provider", "inherit"),
1109 ] {
1110 let text = format!(
1111 r#"
1112 name = "f"
1113 schema = "exact"
1114
1115 [[members]]
1116 id = "w"
1117 provider = "{provider}"
1118 model = "{model}"
1119 "#,
1120 provider = if field == "provider" { value } else { "zai" },
1121 model = if field == "model" { value } else { "glm-5" },
1122 );
1123 let err = ExactFleet::parse(&text).expect_err("selector must be rejected");
1124 assert!(
1125 matches!(err, ExactFleetError::LateBindingSelector { .. }),
1126 "field={field} value={value} err={err:?}"
1127 );
1128 }
1129 }
1130
1131 #[test]
1132 fn model_strength_and_loadout_keys_are_rejected() {
1133 for key in ["model_strength", "loadout", "model_class", "model_hint"] {
1134 let text = format!(
1135 r#"
1136 name = "f"
1137 schema = "exact"
1138
1139 [[members]]
1140 id = "w"
1141 provider = "zai"
1142 model = "glm-5"
1143 {key} = "strong"
1144 "#
1145 );
1146 let err = ExactFleet::parse(&text).expect_err("unknown key must be rejected");
1147 assert!(
1148 matches!(err, ExactFleetError::Parse(_)),
1149 "key={key} err={err:?}"
1150 );
1151 }
1152 }
1153
1154 #[test]
1155 fn legacy_permissions_are_accepted_as_ignored_input_only() {
1156 let text = r#"
1157 name = "f"
1158 schema = "exact"
1159
1160 [[members]]
1161 id = "w"
1162 role = "builder"
1163 provider = "zai"
1164 model = "glm-5"
1165 permissions = "a-value-no-current-preset-recognizes"
1166 "#;
1167 let fleet = ExactFleet::parse(text).expect("legacy permissions must remain loadable");
1168 let member = fleet.member("w").expect("member");
1169 let encoded = serde_json::to_value(member).expect("serialize current member identity");
1170
1171 assert!(encoded.get("permissions").is_none(), "{encoded}");
1172 assert_eq!(member.role, "builder");
1173 assert_eq!(member.frozen_route().model, "glm-5");
1174 }
1175
1176 #[test]
1177 fn router_ignores_legacy_permissions_but_rejects_role_and_auto_reasoning() {
1178 let base = r#"
1179 name = "f"
1180 schema = "exact"
1181
1182 [[members]]
1183 id = "w"
1184 provider = "zai"
1185 model = "glm-5"
1186
1187 [[members]]
1188 id = "router"
1189 kind = "router"
1190 provider = "zai"
1191 model = "glm-5-turbo"
1192 "#;
1193 let permissions = format!("{base}permissions = \"full\"\n");
1194 let parsed = ExactFleet::parse(&permissions).expect("legacy permissions are ignored");
1195 assert!(parsed.legacy_inline_router().is_some());
1196
1197 let role = format!("{base}role = \"builder\"\n");
1198 assert!(matches!(
1199 ExactFleet::parse(&role).expect_err("role rejected"),
1200 ExactFleetError::RouterRoleDeclared { .. }
1201 ));
1202
1203 let auto = format!("{base}reasoning = \"auto\"\n");
1204 assert!(matches!(
1205 ExactFleet::parse(&auto).expect_err("auto rejected"),
1206 ExactFleetError::RouterAutoReasoning { .. }
1207 ));
1208 }
1209
1210 #[test]
1211 fn duplicate_members_and_multiple_routers_fail() {
1212 let duplicate = r#"
1213 name = "f"
1214 schema = "exact"
1215
1216 [[members]]
1217 id = "w"
1218 provider = "zai"
1219 model = "glm-5"
1220
1221 [[members]]
1222 id = "w"
1223 provider = "zai"
1224 model = "glm-5"
1225 "#;
1226 assert!(matches!(
1227 ExactFleet::parse(duplicate).expect_err("duplicate"),
1228 ExactFleetError::DuplicateMember { .. }
1229 ));
1230
1231 let two_routers = r#"
1232 name = "f"
1233 schema = "exact"
1234
1235 [[members]]
1236 id = "w"
1237 provider = "zai"
1238 model = "glm-5"
1239
1240 [[members]]
1241 id = "r1"
1242 kind = "router"
1243 provider = "zai"
1244 model = "glm-5-turbo"
1245
1246 [[members]]
1247 id = "r2"
1248 kind = "router"
1249 provider = "zai"
1250 model = "glm-5-turbo"
1251 "#;
1252 assert!(matches!(
1253 ExactFleet::parse(two_routers).expect_err("two routers"),
1254 ExactFleetError::MultipleRouters
1255 ));
1256 }
1257
1258 /// Two members answering to one role, or one member's id being another's
1259 /// role, would make `member()` resolve by list order instead of identity.
1260 #[test]
1261 fn duplicate_roles_and_id_role_collisions_are_rejected() {
1262 let duplicate_role = r#"
1263 name = "f"
1264 schema = "exact"
1265
1266 [[members]]
1267 id = "a"
1268 role = "builder"
1269 provider = "zai"
1270 model = "glm-5"
1271
1272 [[members]]
1273 id = "b"
1274 role = "builder"
1275 provider = "zai"
1276 model = "glm-5"
1277 "#;
1278 assert!(matches!(
1279 ExactFleet::parse(duplicate_role).expect_err("duplicate role"),
1280 ExactFleetError::DuplicateRole { .. }
1281 ));
1282
1283 // `b`'s role is `a`'s id: naming "a" would be ambiguous.
1284 let collision = r#"
1285 name = "f"
1286 schema = "exact"
1287
1288 [[members]]
1289 id = "a"
1290 role = "builder"
1291 provider = "zai"
1292 model = "glm-5"
1293
1294 [[members]]
1295 id = "b"
1296 role = "a"
1297 provider = "zai"
1298 model = "glm-5"
1299 "#;
1300 assert!(matches!(
1301 ExactFleet::parse(collision).expect_err("id/role collision"),
1302 ExactFleetError::IdRoleCollision { .. }
1303 ));
1304 }
1305
1306 /// `router` is the Router's public identity. A worker may not wear it by
1307 /// either id or role.
1308 #[test]
1309 fn a_worker_may_not_claim_the_router_identity() {
1310 for (id, role) in [("router", None), ("helper", Some("router"))] {
1311 let role_line = role.map_or(String::new(), |role| format!("role = \"{role}\"\n"));
1312 let text = format!(
1313 r#"
1314 name = "f"
1315 schema = "exact"
1316
1317 [[members]]
1318 id = "{id}"
1319 {role_line}provider = "zai"
1320 model = "glm-5"
1321 "#
1322 );
1323 let err = ExactFleet::parse(&text).expect_err("reserved router identity");
1324 assert!(
1325 matches!(err, ExactFleetError::ReservedRouterIdentity { .. }),
1326 "id={id} role={role:?} err={err:?}"
1327 );
1328 }
1329 }
1330
1331 /// `ExactFleet` is `pub` and `Deserialize`, so the invariants must be
1332 /// re-checkable on a value that never went through the TOML parser.
1333 #[test]
1334 fn capture_time_revalidation_catches_a_hand_built_roster() {
1335 let member = |id: &str, role: &str| ExactMember {
1336 id: id.to_string(),
1337 role: role.to_string(),
1338 provider: "zai".to_string(),
1339 model: "glm-5".to_string(),
1340 reasoning: RequestedReasoning::Off,
1341 };
1342
1343 let valid = ExactFleet {
1344 name: "f".to_string(),
1345 description: None,
1346 schema_revision: EXACT_FLEET_SCHEMA_REVISION,
1347 members: vec![member("a", "scout"), member("b", "builder")],
1348 reasoning_router: None,
1349 router: None,
1350 };
1351 valid.validate().expect("a clean roster validates");
1352
1353 for (fleet, label) in [
1354 (
1355 ExactFleet {
1356 members: vec![member("a", "scout"), member("a", "builder")],
1357 ..valid.clone()
1358 },
1359 "duplicate id",
1360 ),
1361 (
1362 ExactFleet {
1363 members: vec![member("a", "scout"), member("b", "scout")],
1364 ..valid.clone()
1365 },
1366 "duplicate role",
1367 ),
1368 (
1369 ExactFleet {
1370 members: vec![member("router", "scout")],
1371 ..valid.clone()
1372 },
1373 "reserved router id",
1374 ),
1375 (
1376 ExactFleet {
1377 members: vec![member("a", "scout"), member("b", "a")],
1378 ..valid.clone()
1379 },
1380 "id/role collision",
1381 ),
1382 ] {
1383 assert!(
1384 fleet.validate().is_err(),
1385 "{label} must not survive revalidation"
1386 );
1387 }
1388
1389 // A serde round-trip is exactly how such a value reaches a snapshot.
1390 let smuggled: ExactFleet = serde_json::from_str(
1391 &serde_json::to_string(&ExactFleet {
1392 members: vec![member("a", "scout"), member("b", "scout")],
1393 ..valid
1394 })
1395 .expect("serialize"),
1396 )
1397 .expect("deserialize");
1398 assert!(matches!(
1399 smuggled
1400 .validate()
1401 .expect_err("round-trip must not launder it"),
1402 ExactFleetError::DuplicateRole { .. }
1403 ));
1404 }
1405
1406 #[test]
1407 fn a_router_only_fleet_has_no_dispatchable_members() {
1408 let text = r#"
1409 name = "f"
1410 schema = "exact"
1411
1412 [[members]]
1413 id = "router"
1414 kind = "router"
1415 provider = "zai"
1416 model = "glm-5-turbo"
1417 "#;
1418 assert!(matches!(
1419 ExactFleet::parse(text).expect_err("router alone is not a fleet"),
1420 ExactFleetError::NoMembers { .. }
1421 ));
1422 }
1423
1424 #[test]
1425 fn permission_ceiling_can_only_narrow_the_session_posture() {
1426 let session = PermissionCeiling {
1427 write: false,
1428 network_tool: false,
1429 shell: ShellCeiling::ReadOnly,
1430 delegation_depth: 0,
1431 tools: true,
1432 };
1433 let member = PermissionCeiling::preset("full").expect("preset");
1434
1435 let clamped = member.clamp_to(session);
1436
1437 assert!(
1438 !clamped.write,
1439 "member must not gain write over a read-only session"
1440 );
1441 assert!(!clamped.network_tool);
1442 assert_eq!(clamped.shell, ShellCeiling::ReadOnly);
1443 assert_eq!(clamped.delegation_depth, 0);
1444 }
1445
1446 #[test]
1447 fn declared_schema_kind_distinguishes_the_two_forms() {
1448 assert_eq!(declared_schema_kind(GLM_FLEET).as_deref(), Some("exact"));
1449 assert_eq!(
1450 declared_schema_kind("name = \"stopship\"\n\n[roles]\nscout = \"scout\"\n"),
1451 None
1452 );
1453 }
1454
1455 #[test]
1456 fn unsupported_revision_fails_closed() {
1457 let text = r#"
1458 name = "f"
1459 schema = "exact"
1460 schema_revision = 99
1461
1462 [[members]]
1463 id = "w"
1464 provider = "zai"
1465 model = "glm-5"
1466 "#;
1467 assert!(matches!(
1468 ExactFleet::parse(text).expect_err("future revision"),
1469 ExactFleetError::UnsupportedRevision { revision: 99, .. }
1470 ));
1471 }
1472 }
1473
1473 lines RUST