返回 CodeWhale
fleet_snapshot.rs
根目录 / crates / workflow / src / fleet_snapshot.rs
1 //! Immutable Fleet snapshot taken at Workflow start.
2 //!
3 //! A saved Fleet is editable; a *running* Workflow is not. At start we capture
4 //! a secret-free, durable value containing the qualified Fleet identity, the
5 //! schema kind/revision/hash, the exact members, the exact routes, the
6 //! reasoning policies. Authority is absent by design: Runtime derives it from
7 //! the selected member's Runtime role and the live parent. Editing the saved file
8 //! afterwards changes only future runs — the snapshot in flight is unaffected,
9 //! because it owns copies and exposes no mutators.
10 //!
11 //! **No-secrets invariant**: every field here is a non-sensitive id, model
12 //! string, tier label, or boolean. There is deliberately no field that could
13 //! hold a credential, token, or base URL.
14
15 use serde::{Deserialize, Serialize};
16
17 use crate::fleet_exact::{
18 ExactFleet, ExactFleetError, FrozenRoute, RequestedReasoning, canonical_member_key,
19 canonical_role_key,
20 };
21 use crate::named_fleet::{FleetDocument, FleetSchema};
22 use crate::reasoning_router::CapturedReasoningRouter;
23 use codewhale_protocol::fleet::PermissionCeiling;
24
25 /// A Fleet identity qualified by where the definition came from.
26 ///
27 /// Deliberately **path-free**. An absolute filesystem path in a durable receipt
28 /// leaks the operator's home directory, username, and machine layout into
29 /// journals and events that travel further than the machine that wrote them.
30 /// `origin/name` plus the schema/content hashes identify a definition precisely
31 /// enough to compare two runs, without any of that. Local diagnostic errors
32 /// (fleet not found, ambiguous fleet) still name paths — those are read on the
33 /// machine that produced them and never persisted onto a receipt.
34 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35 pub struct QualifiedFleetId {
36 /// Fleet name as declared in the file.
37 pub name: String,
38 /// Non-secret origin label, e.g. `workspace` or `codewhale_home`.
39 pub origin: String,
40 }
41
42 impl QualifiedFleetId {
43 /// `origin/name` — the stable display form.
44 #[must_use]
45 pub fn qualified(&self) -> String {
46 format!("{}/{}", self.origin, self.name)
47 }
48 }
49
50 /// One member as frozen into the snapshot.
51 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52 pub struct FleetSnapshotMember {
53 pub id: String,
54 pub role: String,
55 /// The exact route, frozen before any reasoning resolution.
56 pub route: FrozenRoute,
57 /// The reasoning policy the member requested (not the effective tier —
58 /// that is resolved per run and recorded on the receipt).
59 pub requested_reasoning: RequestedReasoning,
60 /// Prototype snapshot compatibility only.
61 ///
62 /// New captures leave this absent. Old replay snapshots need the historic
63 /// value solely to verify their original content hash; selection and
64 /// Runtime authority never read it. Re-serializing a verified old snapshot
65 /// preserves the field so its evidence remains round-trippable, while a
66 /// fresh recapture emits the canonical authority-free shape.
67 #[serde(
68 default,
69 rename = "permissions",
70 skip_serializing_if = "Option::is_none"
71 )]
72 legacy_permissions: Option<PermissionCeiling>,
73 }
74
75 /// The Reasoning Router service a snapshot is attached to.
76 ///
77 /// This is [`CapturedReasoningRouter`] under its historic name — the Router is
78 /// no longer a Fleet member, so the alias exists only to keep older call sites
79 /// and serialized shapes readable.
80 pub type FleetSnapshotRouter = CapturedReasoningRouter;
81
82 /// A legacy fleet's role → profile binding, recorded for provenance.
83 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84 pub struct FleetSnapshotLegacyRole {
85 pub role: String,
86 pub profile: String,
87 }
88
89 /// The immutable value captured at Workflow start.
90 ///
91 /// Fields are private and there are no setters: once captured, the only way to
92 /// change a snapshot is to take a new one.
93 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94 pub struct FleetSnapshot {
95 fleet: QualifiedFleetId,
96 schema_kind: String,
97 schema_revision: u32,
98 /// SHA-256 of the fleet definition bytes.
99 schema_hash: String,
100 /// SHA-256 over the captured members/routes/policies themselves, so two
101 /// snapshots can be compared without re-reading the source file.
102 content_hash: String,
103 members: Vec<FleetSnapshotMember>,
104 /// The attached Reasoning Router service, if this Fleet references one.
105 /// Resolved by the host (which owns the search roots) and handed in, so a
106 /// snapshot stays a pure value with no loader inside it.
107 router: Option<FleetSnapshotRouter>,
108 legacy_roles: Vec<FleetSnapshotLegacyRole>,
109 /// Caller-supplied timestamp; this crate has no clock.
110 captured_at: String,
111 }
112
113 impl FleetSnapshot {
114 /// Capture a snapshot from a parsed fleet document and an already-resolved
115 /// Reasoning Router service.
116 ///
117 /// Exact rosters are **revalidated here**, not trusted. `ExactFleet` is
118 /// public and `Deserialize`, so a document can reach this point without
119 /// having passed the TOML parser's invariant checks; capture is the last
120 /// place to catch a duplicate role, an id/role collision, or a worker
121 /// claiming the Router's identity before those become a running Workflow.
122 ///
123 /// `router` is the captured service, whether it came from a saved reusable
124 /// profile or was normalized out of the legacy inline form. Resolution
125 /// happens in the host because it needs the fleet search roots; capture
126 /// only records the result.
127 pub fn capture(
128 fleet: QualifiedFleetId,
129 document: &FleetDocument,
130 captured_at: impl Into<String>,
131 router: Option<CapturedReasoningRouter>,
132 ) -> Result<Self, ExactFleetError> {
133 let (members, legacy_roles) = match document.schema() {
134 FleetSchema::Exact(exact) => {
135 exact.validate()?;
136 (exact_members(exact), Vec::new())
137 }
138 FleetSchema::Legacy(legacy) => (
139 Vec::new(),
140 legacy
141 .roles
142 .iter()
143 .map(|(role, profile)| FleetSnapshotLegacyRole {
144 role: role.clone(),
145 profile: profile.clone(),
146 })
147 .collect(),
148 ),
149 };
150
151 let mut snapshot = Self {
152 fleet,
153 schema_kind: document.schema_kind().to_string(),
154 schema_revision: document.schema_revision(),
155 schema_hash: document.source_hash().to_string(),
156 content_hash: String::new(),
157 members,
158 router,
159 legacy_roles,
160 captured_at: captured_at.into(),
161 };
162 snapshot.content_hash = snapshot.compute_content_hash();
163 Ok(snapshot)
164 }
165
166 /// Recompute the canonical content hash and reject a snapshot whose
167 /// recorded hash does not describe its own contents.
168 ///
169 /// `FleetSnapshot` is `Deserialize` and its `content_hash` is an ordinary
170 /// field, so a snapshot can reach a launch without ever having passed
171 /// [`Self::capture`] — through a replay file, a cache, or an IPC hop. That
172 /// hash is then stamped onto the durable receipt as the evidence that a run
173 /// matched a saved definition, so an unverified one is not weak evidence but
174 /// *false* evidence: it asserts a definition the members may not describe.
175 ///
176 /// Call this before anything durable or costly happens. It is cheap (one
177 /// canonical serialization plus a SHA-256) and it is the only thing standing
178 /// between a tampered or migrated snapshot and a receipt that vouches for
179 /// it.
180 pub fn verify_content_hash(&self) -> Result<(), ExactFleetError> {
181 let recomputed = if self
182 .members
183 .iter()
184 .any(|member| member.legacy_permissions.is_some())
185 {
186 // Once an old authority-bearing field is present, it must be
187 // covered by the historic hash. Accepting the new canonical hash
188 // here would let arbitrary compatibility bytes hitchhike on an
189 // otherwise valid snapshot without verification.
190 self.compute_legacy_content_hash().ok_or_else(|| {
191 ExactFleetError::ContentHashMismatch {
192 fleet: self.fleet.qualified(),
193 recorded: self.content_hash.clone(),
194 recomputed: "unverifiable mixed legacy-permissions shape".to_string(),
195 }
196 })?
197 } else {
198 self.compute_content_hash()
199 };
200 if recomputed == self.content_hash {
201 return Ok(());
202 }
203 Err(ExactFleetError::ContentHashMismatch {
204 fleet: self.fleet.qualified(),
205 recorded: self.content_hash.clone(),
206 recomputed,
207 })
208 }
209
210 /// [`Self::verify_content_hash`], as a guard that yields the snapshot.
211 ///
212 /// Exists so a load path cannot verify and then accidentally go on to use a
213 /// *different* value: the only thing this returns is the snapshot it just
214 /// checked.
215 pub fn into_verified(self) -> Result<Self, ExactFleetError> {
216 self.verify_content_hash()?;
217 Ok(self)
218 }
219
220 fn compute_content_hash(&self) -> String {
221 // Hash only the captured shape, not the timestamp: two Workflows
222 // started from the same saved Fleet must agree.
223 #[derive(Serialize)]
224 struct CanonicalMember<'a> {
225 id: &'a str,
226 role: &'a str,
227 route: &'a FrozenRoute,
228 requested_reasoning: RequestedReasoning,
229 }
230 #[derive(Serialize)]
231 struct Shape<'a> {
232 fleet: &'a QualifiedFleetId,
233 schema_kind: &'a str,
234 schema_revision: u32,
235 schema_hash: &'a str,
236 members: Vec<CanonicalMember<'a>>,
237 router: &'a Option<FleetSnapshotRouter>,
238 legacy_roles: &'a [FleetSnapshotLegacyRole],
239 }
240
241 let shape = Shape {
242 fleet: &self.fleet,
243 schema_kind: &self.schema_kind,
244 schema_revision: self.schema_revision,
245 schema_hash: &self.schema_hash,
246 members: self
247 .members
248 .iter()
249 .map(|member| CanonicalMember {
250 id: &member.id,
251 role: &member.role,
252 route: &member.route,
253 requested_reasoning: member.requested_reasoning,
254 })
255 .collect(),
256 router: &self.router,
257 legacy_roles: &self.legacy_roles,
258 };
259 let encoded = serde_json::to_vec(&shape).expect("snapshot shape is serializable");
260 crate::named_fleet::sha256_label(&encoded)
261 }
262
263 /// Recompute the prototype content hash when (and only when) every exact
264 /// member carried its historic permission field. This validates old
265 /// evidence without projecting that field into current authority.
266 fn compute_legacy_content_hash(&self) -> Option<String> {
267 #[derive(Serialize)]
268 struct LegacyMember<'a> {
269 id: &'a str,
270 role: &'a str,
271 route: &'a FrozenRoute,
272 requested_reasoning: RequestedReasoning,
273 permissions: PermissionCeiling,
274 }
275 #[derive(Serialize)]
276 struct Shape<'a> {
277 fleet: &'a QualifiedFleetId,
278 schema_kind: &'a str,
279 schema_revision: u32,
280 schema_hash: &'a str,
281 members: Vec<LegacyMember<'a>>,
282 router: &'a Option<FleetSnapshotRouter>,
283 legacy_roles: &'a [FleetSnapshotLegacyRole],
284 }
285
286 if self.members.is_empty()
287 || self
288 .members
289 .iter()
290 .any(|member| member.legacy_permissions.is_none())
291 {
292 return None;
293 }
294 let shape = Shape {
295 fleet: &self.fleet,
296 schema_kind: &self.schema_kind,
297 schema_revision: self.schema_revision,
298 schema_hash: &self.schema_hash,
299 members: self
300 .members
301 .iter()
302 .map(|member| LegacyMember {
303 id: &member.id,
304 role: &member.role,
305 route: &member.route,
306 requested_reasoning: member.requested_reasoning,
307 permissions: member
308 .legacy_permissions
309 .expect("checked every legacy permission above"),
310 })
311 .collect(),
312 router: &self.router,
313 legacy_roles: &self.legacy_roles,
314 };
315 let encoded = serde_json::to_vec(&shape).expect("legacy snapshot shape is serializable");
316 Some(crate::named_fleet::sha256_label(&encoded))
317 }
318
319 #[must_use]
320 pub fn fleet(&self) -> &QualifiedFleetId {
321 &self.fleet
322 }
323
324 #[must_use]
325 pub fn schema_kind(&self) -> &str {
326 &self.schema_kind
327 }
328
329 #[must_use]
330 pub const fn schema_revision(&self) -> u32 {
331 self.schema_revision
332 }
333
334 #[must_use]
335 pub fn schema_hash(&self) -> &str {
336 &self.schema_hash
337 }
338
339 #[must_use]
340 pub fn content_hash(&self) -> &str {
341 &self.content_hash
342 }
343
344 #[must_use]
345 pub fn members(&self) -> &[FleetSnapshotMember] {
346 &self.members
347 }
348
349 #[must_use]
350 pub fn router(&self) -> Option<&FleetSnapshotRouter> {
351 self.router.as_ref()
352 }
353
354 #[must_use]
355 pub fn legacy_roles(&self) -> &[FleetSnapshotLegacyRole] {
356 &self.legacy_roles
357 }
358
359 #[must_use]
360 pub fn captured_at(&self) -> &str {
361 &self.captured_at
362 }
363
364 /// Look up a member by its **member id** — what addresses a roster entry.
365 #[must_use]
366 pub fn member(&self, id: &str) -> Option<&FleetSnapshotMember> {
367 let key = canonical_member_key(id);
368 self.members
369 .iter()
370 .find(|member| canonical_member_key(&member.id) == key)
371 }
372
373 /// Look up a member by its **semantic role** — what gates, handoffs, and
374 /// records use. Kept separate from id lookup so a task can carry a
375 /// meaningful role while the runtime resolves a distinct profile id.
376 ///
377 /// Both sides resolve through [`canonical_role_key`], so a snapshot frozen
378 /// from a Fleet saved under a renamed role is still addressable by a gate or
379 /// handoff that spells the role the old way.
380 #[must_use]
381 pub fn member_by_role(&self, role: &str) -> Option<&FleetSnapshotMember> {
382 let key = canonical_role_key(role);
383 self.members
384 .iter()
385 .find(|member| canonical_role_key(&member.role) == key)
386 }
387
388 /// Look up by id first, then by role. Roster invariants forbid an id/role
389 /// collision, so this can never be order-dependent.
390 #[must_use]
391 pub fn member_by_id_or_role(&self, id_or_role: &str) -> Option<&FleetSnapshotMember> {
392 self.member(id_or_role)
393 .or_else(|| self.member_by_role(id_or_role))
394 }
395
396 /// Whether any frozen member requested `auto` reasoning — i.e. whether this
397 /// Workflow needs a working Reasoning Router at all.
398 #[must_use]
399 pub fn has_auto_member(&self) -> bool {
400 self.members
401 .iter()
402 .any(|member| member.requested_reasoning.is_auto())
403 }
404
405 /// Ids of the members that requested `auto`, for a startup error that names
406 /// who actually needs the Router.
407 #[must_use]
408 pub fn auto_member_ids(&self) -> Vec<String> {
409 self.members
410 .iter()
411 .filter(|member| member.requested_reasoning.is_auto())
412 .map(|member| member.id.clone())
413 .collect()
414 }
415 }
416
417 fn exact_members(exact: &ExactFleet) -> Vec<FleetSnapshotMember> {
418 exact
419 .members
420 .iter()
421 .map(|member| FleetSnapshotMember {
422 id: canonical_member_key(&member.id),
423 // The snapshot is what every receipt is built from, so it records
424 // the *canonical* role even when the saved file used a renamed one.
425 // Old files keep working (lookup resolves either spelling); new
426 // receipts never print a name the current schema does not use.
427 role: canonical_role_key(&member.role),
428 route: member.frozen_route(),
429 requested_reasoning: member.reasoning,
430 legacy_permissions: None,
431 })
432 .collect()
433 }
434
435 /// Verify a snapshot that arrived from anywhere other than [`FleetSnapshot::capture`].
436 ///
437 /// The free function exists for load/deserialize seams that hold a snapshot by
438 /// reference and only need the yes/no answer — a durable-write guard, a replay
439 /// loader, a cache read. It is the same check as
440 /// [`FleetSnapshot::verify_content_hash`]; having a named entry point is what
441 /// lets those call sites read as "verify before use" rather than as an
442 /// incidental method call.
443 pub fn verify_snapshot_content_hash(snapshot: &FleetSnapshot) -> Result<(), ExactFleetError> {
444 snapshot.verify_content_hash()
445 }
446
447 /// Normalize an exact Fleet's **legacy inline** Router into the captured
448 /// service, if it used the prototype form.
449 ///
450 /// A Fleet that references a saved profile resolves through
451 /// [`crate::ReasoningRouterProfile::load_by_name`] instead, in the host that
452 /// owns the search roots. Both paths land on the same value, which is the whole
453 /// point of keeping only one runtime representation.
454 #[must_use]
455 pub fn captured_legacy_inline_router(exact: &ExactFleet) -> Option<CapturedReasoningRouter> {
456 exact
457 .legacy_inline_router()
458 .map(CapturedReasoningRouter::from_legacy_inline)
459 }
460
461 #[cfg(test)]
462 mod content_hash_tests {
463 use super::*;
464
465 const EXACT_FLEET: &str = r#"
466 name = "glm-pair"
467 schema = "exact"
468
469 [[members]]
470 id = "implementer"
471 role = "builder"
472 provider = "zai"
473 model = "glm-5"
474 reasoning = "high"
475 permissions = "read_write"
476
477 [[members]]
478 id = "advisor-one"
479 role = "oracle"
480 provider = "zai"
481 model = "glm-5"
482 reasoning = "low"
483 permissions = "analyst"
484 "#;
485
486 fn captured() -> FleetSnapshot {
487 let document = FleetDocument::parse(EXACT_FLEET).expect("parse fleet document");
488 FleetSnapshot::capture(
489 QualifiedFleetId {
490 name: "glm-pair".to_string(),
491 origin: "workspace".to_string(),
492 },
493 &document,
494 "2026-07-26T00:00:00Z",
495 None,
496 )
497 .expect("capture")
498 }
499
500 #[test]
501 fn a_freshly_captured_snapshot_verifies() {
502 let snapshot = captured();
503 assert!(snapshot.verify_content_hash().is_ok());
504 assert!(verify_snapshot_content_hash(&snapshot).is_ok());
505 assert!(snapshot.into_verified().is_ok());
506 }
507
508 /// The round trip a replay file, a cache read, or an IPC hop performs. An
509 /// untouched snapshot must survive it — otherwise the guard below would be
510 /// unusable at exactly the seams it exists for.
511 #[test]
512 fn an_untouched_round_trip_still_verifies() {
513 let snapshot = captured();
514 let encoded = serde_json::to_string(&snapshot).expect("serialize");
515 let decoded: FleetSnapshot = serde_json::from_str(&encoded).expect("deserialize");
516
517 assert_eq!(decoded, snapshot);
518 assert!(decoded.verify_content_hash().is_ok());
519 }
520
521 /// The tamper case. A snapshot whose members were edited after capture
522 /// keeps its old hash, and that hash is what a receipt would vouch for.
523 /// Verification must reject it *before* any launch or durable write.
524 #[test]
525 fn an_edited_member_is_rejected_while_the_hash_still_claims_the_original() {
526 let snapshot = captured();
527 let original_hash = snapshot.content_hash().to_string();
528
529 let mut value = serde_json::to_value(&snapshot).expect("serialize");
530 // Widen a member's route — the single most consequential edit, and the
531 // one a stale hash would silently certify.
532 value["members"][0]["route"]["model"] = serde_json::json!("glm-5-max");
533 let tampered: FleetSnapshot = serde_json::from_value(value).expect("deserialize");
534
535 assert_eq!(
536 tampered.content_hash(),
537 original_hash,
538 "the tamper does not touch the recorded hash — that is the point"
539 );
540 let error = tampered
541 .verify_content_hash()
542 .expect_err("a tampered snapshot must not verify");
543 assert!(matches!(
544 error,
545 ExactFleetError::ContentHashMismatch { ref recorded, .. } if *recorded == original_hash
546 ));
547 assert!(tampered.into_verified().is_err());
548 }
549
550 /// Prototype snapshots carried member `permissions`. A valid old content
551 /// hash remains verifiable for replay, but the field is compatibility
552 /// evidence only and a fresh capture emits the authority-free shape.
553 #[test]
554 fn a_valid_legacy_permission_snapshot_verifies_and_round_trips() {
555 let snapshot = captured();
556 let mut value = serde_json::to_value(&snapshot).expect("serialize");
557 for index in 0..2 {
558 value["members"][index]["permissions"] = serde_json::json!({
559 "write": index == 0,
560 "network_tool": false,
561 "shell": "read_only",
562 "delegation_depth": 0,
563 "tools": true
564 });
565 }
566 let mut replay: FleetSnapshot = serde_json::from_value(value).expect("legacy replay loads");
567 replay.content_hash = replay
568 .compute_legacy_content_hash()
569 .expect("old shape has a legacy hash");
570
571 assert_ne!(replay.compute_content_hash(), replay.content_hash);
572 assert!(replay.verify_content_hash().is_ok());
573 let encoded = serde_json::to_string(&replay).expect("legacy replay remains durable");
574 assert!(encoded.contains("\"permissions\""), "{encoded}");
575 let decoded: FleetSnapshot = serde_json::from_str(&encoded).expect("round trip");
576 assert!(decoded.verify_content_hash().is_ok());
577 }
578
579 #[test]
580 fn a_tampered_legacy_permission_snapshot_fails_closed() {
581 let snapshot = captured();
582 let mut value = serde_json::to_value(&snapshot).expect("serialize");
583 for index in 0..2 {
584 value["members"][index]["permissions"] = serde_json::json!({
585 "write": false,
586 "network_tool": false,
587 "shell": "read_only",
588 "delegation_depth": 0,
589 "tools": true
590 });
591 }
592 let mut replay: FleetSnapshot = serde_json::from_value(value).expect("legacy replay loads");
593 replay.content_hash = replay
594 .compute_legacy_content_hash()
595 .expect("old shape has a legacy hash");
596 let recorded = replay.content_hash.clone();
597
598 let mut tampered = serde_json::to_value(&replay).expect("serialize old replay");
599 tampered["members"][0]["permissions"]["write"] = serde_json::json!(true);
600 let tampered: FleetSnapshot = serde_json::from_value(tampered).expect("deserialize");
601 assert_eq!(tampered.content_hash(), recorded);
602 assert!(tampered.verify_content_hash().is_err());
603 }
604
605 #[test]
606 fn legacy_permission_bytes_must_be_covered_by_the_legacy_hash() {
607 let snapshot = captured();
608 let canonical_hash = snapshot.content_hash().to_string();
609 let mut value = serde_json::to_value(&snapshot).expect("serialize");
610 for index in 0..2 {
611 value["members"][index]["permissions"] = serde_json::json!({
612 "write": false,
613 "network_tool": false,
614 "shell": "read_only",
615 "delegation_depth": 0,
616 "tools": true
617 });
618 }
619 let replay: FleetSnapshot = serde_json::from_value(value).expect("legacy shape loads");
620
621 assert_eq!(replay.content_hash(), canonical_hash);
622 assert!(
623 replay.verify_content_hash().is_err(),
624 "legacy bytes may not hitchhike on the authority-free canonical hash"
625 );
626 }
627
628 /// A forged hash fails the same way an edited body does: the check is a
629 /// recomputation, not a presence test, so neither side can be trusted alone.
630 #[test]
631 fn a_forged_hash_is_rejected() {
632 let snapshot = captured();
633 let mut value = serde_json::to_value(&snapshot).expect("serialize");
634 value["content_hash"] = serde_json::json!("0".repeat(64));
635 let forged: FleetSnapshot = serde_json::from_value(value).expect("deserialize");
636
637 assert!(forged.verify_content_hash().is_err());
638 }
639
640 /// The migration case: a snapshot written by an older build that recorded a
641 /// renamed role verbatim. Capture now canonicalizes, so the *stored* role is
642 /// `consultant` and the hash covers that — an old snapshot carrying
643 /// `oracle` cannot pass verification and must be re-captured rather than
644 /// quietly relabelled at read time.
645 #[test]
646 fn a_pre_rename_snapshot_is_rejected_rather_than_silently_relabelled() {
647 let snapshot = captured();
648 assert_eq!(
649 snapshot.members()[1].role,
650 "consultant",
651 "capture records the canonical role"
652 );
653
654 let mut value = serde_json::to_value(&snapshot).expect("serialize");
655 value["members"][1]["role"] = serde_json::json!("oracle");
656 let migrated: FleetSnapshot = serde_json::from_value(value).expect("deserialize");
657
658 assert!(migrated.verify_content_hash().is_err());
659 // The alias still *resolves* — compatibility is a lookup property, not a
660 // licence to accept an unverified hash.
661 assert!(migrated.member_by_role("consultant").is_some());
662 }
663
664 /// Lookup canonicalization survives capture: a snapshot frozen from a Fleet
665 /// saved under the old name answers to either spelling.
666 #[test]
667 fn snapshot_role_lookup_accepts_both_spellings() {
668 let snapshot = captured();
669
670 for spelling in ["consultant", "oracle", "advisor", "ORACLE"] {
671 assert_eq!(
672 snapshot
673 .member_by_role(spelling)
674 .unwrap_or_else(|| panic!("`{spelling}` must resolve"))
675 .id,
676 "advisor-one"
677 );
678 }
679 assert!(snapshot.member_by_id_or_role("oracle").is_some());
680 }
681 }
682
683 #[cfg(test)]
684 mod tests {
685 use super::*;
686 use crate::reasoning_router::{
687 LEGACY_INLINE_ROUTER_ORIGIN, REASONING_ROUTER_SERVICE_KIND, ReasoningRouterProfile,
688 RouterCallReasoning,
689 };
690 use codewhale_protocol::fleet::ShellCeiling;
691
692 /// A Fleet that references a saved, reusable Router profile — the shape new
693 /// Fleets use.
694 const EXACT: &str = r#"
695 name = "glm-pair"
696 schema = "exact"
697 reasoning_router = "luna-low"
698
699 [[members]]
700 id = "implementer"
701 role = "builder"
702 provider = "zai"
703 model = "glm-5"
704 reasoning = "auto"
705 permissions = "read_write"
706
707 [[members]]
708 id = "auditor"
709 provider = "zai"
710 model = "glm-5"
711 reasoning = "high"
712 permissions = "read_only"
713 "#;
714
715 /// The prototype form, retained for compatibility.
716 const LEGACY_INLINE: &str = r#"
717 name = "glm-pair"
718 schema = "exact"
719
720 [[members]]
721 id = "implementer"
722 role = "builder"
723 provider = "zai"
724 model = "glm-5"
725 reasoning = "auto"
726 permissions = "read_write"
727
728 [[members]]
729 id = "router"
730 kind = "router"
731 provider = "zai"
732 model = "glm-5-turbo"
733 "#;
734
735 const LEGACY_ROLE_MAP: &str = r#"
736 name = "stopship"
737 description = "legacy roster"
738
739 [roles]
740 scout = "scout"
741 implementer = "builder"
742 "#;
743
744 const LUNA: &str = r#"
745 name = "luna-low"
746 schema = "reasoning_router"
747 provider = "openai"
748 model = "gpt-5.6-luna"
749 call_reasoning = "low"
750 "#;
751
752 fn id() -> QualifiedFleetId {
753 QualifiedFleetId {
754 name: "glm-pair".to_string(),
755 origin: "workspace".to_string(),
756 }
757 }
758
759 fn luna() -> CapturedReasoningRouter {
760 let profile = ReasoningRouterProfile::parse(LUNA).expect("router profile");
761 CapturedReasoningRouter::from_profile(&profile, "workspace")
762 }
763
764 fn capture(text: &str, router: Option<CapturedReasoningRouter>) -> FleetSnapshot {
765 let document = FleetDocument::parse(text).expect("parse");
766 FleetSnapshot::capture(id(), &document, "2026-07-26T00:00:00Z", router).expect("capture")
767 }
768
769 #[test]
770 fn snapshot_captures_identity_schema_routes_and_reasoning() {
771 let snapshot = capture(EXACT, Some(luna()));
772
773 assert_eq!(snapshot.fleet().qualified(), "workspace/glm-pair");
774 assert_eq!(snapshot.schema_kind(), "exact");
775 assert_eq!(snapshot.schema_revision(), 1);
776 assert!(snapshot.schema_hash().starts_with("sha256:"));
777 assert!(snapshot.content_hash().starts_with("sha256:"));
778
779 // Roles and ids are separate lookups, and both find the same member.
780 let by_role = snapshot.member_by_role("builder").expect("role lookup");
781 let by_id = snapshot.member("implementer").expect("id lookup");
782 assert_eq!(by_role.id, by_id.id);
783 assert_eq!(by_id.route.provider, "zai");
784 assert_eq!(by_id.route.model, "glm-5");
785 assert_eq!(by_id.requested_reasoning, RequestedReasoning::Auto);
786 let member_json = serde_json::to_value(by_id).expect("serialize member");
787 assert!(member_json.get("permissions").is_none(), "{member_json}");
788
789 // An id lookup must not answer to a role, or a task naming one would
790 // silently resolve the other.
791 assert!(snapshot.member("builder").is_none());
792 assert!(snapshot.member_by_role("implementer").is_none());
793
794 assert!(snapshot.has_auto_member());
795 assert_eq!(snapshot.auto_member_ids(), vec!["implementer".to_string()]);
796 }
797
798 /// The Router is a referenced service, not a Fleet member: it holds no
799 /// authority, is never dispatchable, and is not in the roster.
800 #[test]
801 fn the_attached_router_is_a_service_and_not_a_roster_member() {
802 let snapshot = capture(EXACT, Some(luna()));
803 let router = snapshot.router().expect("router service");
804
805 assert_eq!(router.service_kind, REASONING_ROUTER_SERVICE_KIND);
806 assert_eq!(router.qualified(), "workspace/luna-low");
807 assert!(!router.legacy_inline);
808 assert!(!router.is_dispatchable());
809 assert!(!router.dispatchable);
810 assert!(router.tool_surface().is_empty());
811 assert_eq!(router.route.provider, "openai");
812 assert_eq!(router.route.model, "gpt-5.6-luna");
813 assert_eq!(router.requested_call_reasoning, RouterCallReasoning::Low);
814 assert_eq!(router.permissions.shell, ShellCeiling::None);
815 assert!(!router.permissions.tools);
816 assert_eq!(router.permissions.delegation_depth, 0);
817
818 // Not reachable through worker lookup by either id or role.
819 assert!(snapshot.member("luna-low").is_none());
820 assert!(snapshot.member_by_role("luna-low").is_none());
821 assert!(snapshot.member_by_id_or_role("router").is_none());
822 }
823
824 /// One saved profile, two different Fleets. The service is referenced, not
825 /// owned, so both snapshots capture the identical value.
826 #[test]
827 fn one_router_profile_serves_two_fleets() {
828 let first = capture(EXACT, Some(luna()));
829 let second_text = EXACT.replace("name = \"glm-pair\"", "name = \"other-pair\"");
830 let document = FleetDocument::parse(&second_text).expect("parse");
831 let second = FleetSnapshot::capture(
832 QualifiedFleetId {
833 name: "other-pair".to_string(),
834 origin: "workspace".to_string(),
835 },
836 &document,
837 "2026-07-26T00:00:00Z",
838 Some(luna()),
839 )
840 .expect("capture");
841
842 assert_eq!(first.router(), second.router());
843 assert_ne!(first.fleet(), second.fleet());
844 assert_ne!(
845 first.content_hash(),
846 second.content_hash(),
847 "different fleets are still different snapshots"
848 );
849 }
850
851 /// The prototype inline form normalizes into the same captured service, so
852 /// nothing downstream has to know which way the operator wrote it.
853 #[test]
854 fn a_legacy_inline_router_normalizes_into_the_same_captured_service() {
855 let document = FleetDocument::parse(LEGACY_INLINE).expect("parse");
856 let exact = document.exact().expect("exact");
857 let captured = captured_legacy_inline_router(exact).expect("inline router");
858
859 assert!(captured.legacy_inline);
860 assert_eq!(captured.origin, LEGACY_INLINE_ROUTER_ORIGIN);
861 assert_eq!(captured.service_kind, REASONING_ROUTER_SERVICE_KIND);
862 assert_eq!(captured.route.model, "glm-5-turbo");
863 assert_eq!(captured.requested_call_reasoning, RouterCallReasoning::Off);
864 assert!(!captured.is_dispatchable());
865 assert!(!captured.permissions.tools);
866
867 let snapshot = FleetSnapshot::capture(
868 id(),
869 &document,
870 "2026-07-26T00:00:00Z",
871 Some(captured.clone()),
872 )
873 .expect("capture");
874 assert_eq!(snapshot.router(), Some(&captured));
875 // The inline member is not in the roster.
876 assert!(snapshot.member("router").is_none());
877 assert_eq!(snapshot.members().len(), 1);
878 }
879
880 #[test]
881 fn editing_the_saved_fleet_does_not_touch_a_running_snapshot() {
882 let snapshot = capture(EXACT, Some(luna()));
883
884 // The operator edits the saved file mid-run: different model and
885 // reasoning. (The historic permissions key remains ignored input.)
886 let edited = EXACT
887 .replace(
888 "model = \"glm-5\"\nreasoning = \"auto\"",
889 "model = \"glm-4\"\nreasoning = \"off\"",
890 )
891 .replace("permissions = \"read_write\"", "permissions = \"full\"");
892 let next = capture(&edited, Some(luna()));
893
894 // The in-flight snapshot is untouched.
895 let member = snapshot.member("implementer").expect("member");
896 assert_eq!(member.route.model, "glm-5");
897 assert_eq!(member.requested_reasoning, RequestedReasoning::Auto);
898
899 // The next run sees the edit, and the hashes prove they differ.
900 assert_eq!(next.member("implementer").unwrap().route.model, "glm-4");
901 assert_ne!(snapshot.schema_hash(), next.schema_hash());
902 assert_ne!(snapshot.content_hash(), next.content_hash());
903 }
904
905 #[test]
906 fn identical_definitions_produce_an_identical_content_hash() {
907 let document = FleetDocument::parse(EXACT).expect("parse");
908 let a = FleetSnapshot::capture(id(), &document, "2026-07-26T00:00:00Z", Some(luna()))
909 .expect("capture");
910 // Different capture time, same fleet: the content hash must not move.
911 let b = FleetSnapshot::capture(id(), &document, "2026-07-27T09:30:00Z", Some(luna()))
912 .expect("capture");
913
914 assert_eq!(a.content_hash(), b.content_hash());
915 assert_ne!(a.captured_at(), b.captured_at());
916 }
917
918 /// Swapping the attached Router is a real change to what will run, so it
919 /// must move the content hash.
920 #[test]
921 fn changing_the_attached_router_changes_the_content_hash() {
922 let with_luna = capture(EXACT, Some(luna()));
923 let without = capture(EXACT, None);
924 assert_ne!(with_luna.content_hash(), without.content_hash());
925 }
926
927 #[test]
928 fn legacy_role_map_fleets_snapshot_as_legacy() {
929 let document = FleetDocument::parse(LEGACY_ROLE_MAP).expect("parse legacy");
930 let snapshot = FleetSnapshot::capture(
931 QualifiedFleetId {
932 name: "stopship".to_string(),
933 origin: "workspace".to_string(),
934 },
935 &document,
936 "2026-07-26T00:00:00Z",
937 None,
938 )
939 .expect("capture");
940
941 assert_eq!(snapshot.schema_kind(), "legacy");
942 assert_eq!(snapshot.schema_revision(), 0);
943 assert!(snapshot.members().is_empty());
944 assert!(snapshot.router().is_none());
945 assert!(!snapshot.has_auto_member());
946 assert_eq!(snapshot.legacy_roles().len(), 2);
947 assert!(
948 snapshot
949 .legacy_roles()
950 .iter()
951 .any(|role| role.role == "implementer" && role.profile == "builder")
952 );
953 }
954
955 #[test]
956 fn snapshot_serialization_carries_no_secret_shaped_fields() {
957 let snapshot = capture(EXACT, Some(luna()));
958 let json = serde_json::to_string(&snapshot).expect("serialize");
959 let lowered = json.to_ascii_lowercase();
960
961 for forbidden in [
962 "api_key",
963 "apikey",
964 "secret",
965 "token",
966 "bearer",
967 "password",
968 "base_url",
969 "credential",
970 "authorization",
971 ] {
972 assert!(
973 !lowered.contains(forbidden),
974 "snapshot must not carry `{forbidden}`: {json}"
975 );
976 }
977
978 // Round-trips as a durable value.
979 let back: FleetSnapshot = serde_json::from_str(&json).expect("deserialize");
980 assert_eq!(back, snapshot);
981 }
982
983 /// A durable snapshot identifies its definition by qualified origin/name
984 /// and by hash — never by a filesystem path, which would leak the
985 /// operator's home directory and username into anything that stores it.
986 #[test]
987 fn a_snapshot_carries_no_filesystem_path() {
988 let tmp = tempfile::tempdir().expect("tmp");
989 std::fs::create_dir_all(tmp.path().join("fleets")).expect("dirs");
990 let path = tmp.path().join("fleets/glm-pair.toml");
991 std::fs::write(&path, EXACT).expect("write");
992 let document = FleetDocument::load(&path, Some("glm-pair")).expect("load from disk");
993 // The document still knows where it came from, for local diagnostics.
994 assert!(document.source_path().is_some());
995
996 let snapshot =
997 FleetSnapshot::capture(id(), &document, "2026-07-26T00:00:00Z", Some(luna()))
998 .expect("capture");
999 let json = serde_json::to_string(&snapshot).expect("serialize");
1000
1001 assert!(!json.contains(&tmp.path().display().to_string()), "{json}");
1002 for fragment in ["/Users/", "/home/", "/private/", ".toml", "\\Users\\"] {
1003 assert!(
1004 !json.contains(fragment),
1005 "snapshot must not carry `{fragment}`: {json}"
1006 );
1007 }
1008 assert_eq!(snapshot.fleet().qualified(), "workspace/glm-pair");
1009 assert!(snapshot.content_hash().starts_with("sha256:"));
1010 }
1011
1012 /// Capture is the last gate before a roster becomes a running Workflow, so
1013 /// a value that never saw the TOML parser must still be rejected here.
1014 #[test]
1015 fn capture_revalidates_a_roster_that_bypassed_the_parser() {
1016 use crate::fleet_exact::ExactMember;
1017
1018 let member = |id: &str, role: &str| ExactMember {
1019 id: id.to_string(),
1020 role: role.to_string(),
1021 provider: "zai".to_string(),
1022 model: "glm-5".to_string(),
1023 reasoning: RequestedReasoning::Off,
1024 };
1025 let smuggled = ExactFleet {
1026 name: "f".to_string(),
1027 description: None,
1028 schema_revision: 1,
1029 reasoning_router: None,
1030 // Two members, one role: role lookup would resolve by list order.
1031 members: vec![member("a", "builder"), member("b", "builder")],
1032 router: None,
1033 };
1034
1035 let document = FleetDocument::from_exact_for_tests(smuggled);
1036 let err = FleetSnapshot::capture(id(), &document, "2026-07-26T00:00:00Z", None)
1037 .expect_err("capture must revalidate");
1038 assert!(
1039 matches!(err, ExactFleetError::DuplicateRole { .. }),
1040 "{err:?}"
1041 );
1042 }
1043 }
1044
1044 lines RUST