返回 CodeWhale
named_fleet.rs
根目录 / crates / workflow / src / named_fleet.rs
1 //! Named fleet roster files for dogfood lanes (#4178).
2 //!
3 //! Format: TOML at `fleets/<name>.toml` (workspace) or
4 //! `$CODEWHALE_HOME/fleets/<name>.toml`.
5 //!
6 //! Two forms share this one store — there is no parallel fleet directory:
7 //!
8 //! - **Legacy**: `[roles]` maps role → AgentProfile id. Fleet resolves roles →
9 //! profile ids only; Runtime owns tmux/worktrees. Legacy files declare no
10 //! `schema` key, which is what makes the form explicitly detectable rather
11 //! than guessed from a missing table.
12 //! - **Exact**: `schema = "exact"` with fully resolved `[[members]]`. See
13 //! [`crate::fleet_exact`].
14 //!
15 //! [`FleetDocument`] is the form-agnostic entry point: it reports which form a
16 //! file is in and carries the content hash a Workflow snapshot records.
17
18 use std::collections::BTreeMap;
19 use std::path::{Path, PathBuf};
20
21 use serde::{Deserialize, Serialize};
22 use sha2::{Digest, Sha256};
23 use thiserror::Error;
24
25 use crate::fleet_exact::{
26 EXACT_FLEET_SCHEMA_KIND, EXACT_FLEET_SCHEMA_REVISION, ExactFleet, ExactFleetError,
27 LEGACY_FLEET_SCHEMA_KIND, declared_schema_kind,
28 };
29 use crate::fleet_snapshot::QualifiedFleetId;
30
31 pub type FleetFileReader = fn(&Path) -> std::io::Result<String>;
32
33 fn read_followed(path: &Path) -> std::io::Result<String> {
34 std::fs::read_to_string(path)
35 }
36
37 /// One labelled place fleet files are looked up.
38 ///
39 /// The label is what makes a Fleet identity *qualified*: `workspace/glm-pair`
40 /// and `codewhale_home/glm-pair` are different Fleets, and the loader refuses
41 /// to guess between them for exact definitions.
42 #[derive(Debug, Clone)]
43 pub struct FleetSearchRoot {
44 /// Non-secret origin label, e.g. `workspace` or `codewhale_home`.
45 pub origin: String,
46 /// Directory that contains a `fleets/` subdirectory.
47 pub root: PathBuf,
48 reader: FleetFileReader,
49 }
50
51 impl PartialEq for FleetSearchRoot {
52 fn eq(&self, other: &Self) -> bool {
53 self.origin == other.origin && self.root == other.root
54 }
55 }
56
57 impl Eq for FleetSearchRoot {}
58
59 impl FleetSearchRoot {
60 pub fn new(origin: impl Into<String>, root: impl Into<PathBuf>) -> Self {
61 Self {
62 origin: origin.into(),
63 root: root.into(),
64 reader: read_followed,
65 }
66 }
67
68 #[must_use]
69 pub fn with_reader(mut self, reader: FleetFileReader) -> Self {
70 self.reader = reader;
71 self
72 }
73
74 pub(crate) fn read_candidate(&self, path: &Path) -> std::io::Result<Option<String>> {
75 match (self.reader)(path) {
76 Ok(text) => Ok(Some(text)),
77 Err(error)
78 if matches!(
79 error.kind(),
80 std::io::ErrorKind::NotFound | std::io::ErrorKind::IsADirectory
81 ) =>
82 {
83 Ok(None)
84 }
85 Err(error) => Err(error),
86 }
87 }
88 }
89
90 /// Split `origin/name` into its parts. A bare name yields `(None, name)`.
91 ///
92 /// The bare part becomes a `<name>.toml` file name, so it is validated here
93 /// with [`validate_fleet_file_stem`] before any caller touches the disk.
94 pub fn split_qualified_fleet_name(name: &str) -> Result<(Option<&str>, &str), NamedFleetError> {
95 let trimmed = name.trim();
96 let (origin, bare) = match trimmed.split_once('/') {
97 Some((origin, bare)) if !origin.trim().is_empty() && !bare.trim().is_empty() => {
98 (Some(origin.trim()), bare.trim())
99 }
100 _ => (None, trimmed),
101 };
102 validate_fleet_file_stem(bare)?;
103 Ok((origin, bare))
104 }
105
106 /// A fleet or router name is one file name inside a `fleets/`-style
107 /// directory: non-empty, a single normal path component, and free of path
108 /// separators, drive prefixes and NUL. Anything else is refused before a
109 /// path is built from it.
110 pub fn validate_fleet_file_stem(stem: &str) -> Result<(), NamedFleetError> {
111 let single_component = matches!(
112 Path::new(stem).components().collect::<Vec<_>>().as_slice(),
113 [std::path::Component::Normal(_)]
114 );
115 if stem.is_empty()
116 || stem == "."
117 || stem == ".."
118 || stem.contains(['/', '\\', ':', '\0'])
119 || !single_component
120 {
121 return Err(NamedFleetError::InvalidName);
122 }
123 Ok(())
124 }
125
126 /// Parsed named fleet file.
127 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128 pub struct NamedFleet {
129 pub name: String,
130 #[serde(default)]
131 pub description: Option<String>,
132 /// role name → AgentProfile id
133 pub roles: BTreeMap<String, String>,
134 }
135
136 #[derive(Debug, Clone, PartialEq, Eq, Error)]
137 pub enum NamedFleetError {
138 #[error("fleet file not found: {0}")]
139 NotFound(String),
140 /// Carries no text from the rejected name, so the refusal cannot echo a
141 /// path back.
142 #[error(
143 "invalid fleet name: use a plain name (optionally `origin/name`) without path \
144 separators or `..`"
145 )]
146 InvalidName,
147 #[error("failed to read fleet file {path}: {message}")]
148 Io { path: String, message: String },
149 #[error("failed to parse fleet file {path}: {message}")]
150 Parse { path: String, message: String },
151 #[error("fleet `{fleet}` is missing required role `{role}`")]
152 MissingRole { fleet: String, role: String },
153 #[error("fleet name mismatch: file declares `{declared}`, expected `{expected}`")]
154 NameMismatch { declared: String, expected: String },
155 #[error(
156 "fleet `{name}` is defined in more than one place ({}); an exact fleet must not be \
157 resolved by shadowing. Name one explicitly as `origin/{name}`.",
158 origins.join(", ")
159 )]
160 AmbiguousFleet { name: String, origins: Vec<String> },
161 #[error("exact fleet `{fleet}`: {source}")]
162 Exact {
163 fleet: String,
164 #[source]
165 source: ExactFleetError,
166 },
167 }
168
169 /// Which form a `fleets/<name>.toml` file is in.
170 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171 #[serde(rename_all = "snake_case", tag = "kind")]
172 pub enum FleetSchema {
173 /// Pre-exact role → AgentProfile id map.
174 Legacy(NamedFleet),
175 /// Fully resolved exact members.
176 Exact(ExactFleet),
177 }
178
179 /// A parsed fleet file plus the provenance a Workflow snapshot needs.
180 #[derive(Debug, Clone, PartialEq, Eq)]
181 pub struct FleetDocument {
182 schema: FleetSchema,
183 source: Option<PathBuf>,
184 source_hash: String,
185 }
186
187 impl FleetDocument {
188 /// Parse either form. The exact form is selected by an explicit
189 /// `schema = "exact"`; everything else is the legacy form.
190 pub fn parse(text: &str) -> Result<Self, NamedFleetError> {
191 let schema = match declared_schema_kind(text).as_deref() {
192 Some(EXACT_FLEET_SCHEMA_KIND) => {
193 let exact = ExactFleet::parse(text).map_err(|source| NamedFleetError::Exact {
194 fleet: "<memory>".to_string(),
195 source,
196 })?;
197 FleetSchema::Exact(exact)
198 }
199 Some(other) => {
200 return Err(NamedFleetError::Parse {
201 path: "<memory>".into(),
202 message: format!(
203 "unknown fleet schema `{other}`; expected `exact` or a saved Fleet \
204 (`schema = \"fleet\"`, loaded from `.codewhale/fleets/` or \
205 `$CODEWHALE_HOME/fleets/`)"
206 ),
207 });
208 }
209 None => FleetSchema::Legacy(parse_named_fleet(text)?),
210 };
211 Ok(Self {
212 schema,
213 source: None,
214 source_hash: content_hash(text),
215 })
216 }
217
218 pub fn load(path: &Path, expect_name: Option<&str>) -> Result<Self, NamedFleetError> {
219 let text = std::fs::read_to_string(path).map_err(|e| NamedFleetError::Io {
220 path: path.display().to_string(),
221 message: e.to_string(),
222 })?;
223 Self::from_source(path, &text, expect_name)
224 }
225
226 fn from_source(
227 path: &Path,
228 text: &str,
229 expect_name: Option<&str>,
230 ) -> Result<Self, NamedFleetError> {
231 let mut document = Self::parse(text).map_err(|e| match e {
232 NamedFleetError::Parse { message, .. } => NamedFleetError::Parse {
233 path: path.display().to_string(),
234 message,
235 },
236 NamedFleetError::Exact { source, .. } => NamedFleetError::Exact {
237 fleet: path.display().to_string(),
238 source,
239 },
240 other => other,
241 })?;
242 if let Some(expected) = expect_name
243 && document.name() != expected
244 {
245 return Err(NamedFleetError::NameMismatch {
246 declared: document.name().to_string(),
247 expected: expected.to_string(),
248 });
249 }
250 document.source = Some(path.to_path_buf());
251 Ok(document)
252 }
253
254 /// Load a fleet document by name from labelled search roots.
255 ///
256 /// A bare `name` that exists under more than one origin is **ambiguous**
257 /// once any candidate is an exact fleet: a personal `~/.codewhale` Fleet
258 /// silently shadowing (or being shadowed by) a project Fleet would change
259 /// which exact provider/model actually runs, so the caller is asked for a
260 /// qualified `origin/name` instead. Purely legacy collisions keep the
261 /// historic first-hit-wins behavior, because a role→profile map resolves
262 /// through the same profile store either way.
263 ///
264 /// Ambiguity is decided from a `schema`-key probe, not from a full parse of
265 /// every candidate: a malformed file in a *shadowed* origin must not break a
266 /// legacy load that has always worked. A file whose TOML does not even
267 /// parse therefore counts as legacy for this decision, and the first hit
268 /// still wins — the same outcome the pre-exact loader gave.
269 ///
270 /// Accepts `origin/name` to name one origin explicitly.
271 pub fn load_by_name(
272 name: &str,
273 search_roots: &[FleetSearchRoot],
274 ) -> Result<(Self, QualifiedFleetId), NamedFleetError> {
275 let (requested_origin, bare_name) = split_qualified_fleet_name(name)?;
276 let file_name = format!("{bare_name}.toml");
277
278 let mut candidates: Vec<(&FleetSearchRoot, PathBuf, String)> = Vec::new();
279 for root in search_roots {
280 if let Some(origin) = requested_origin
281 && !root.origin.eq_ignore_ascii_case(origin)
282 {
283 continue;
284 }
285 let path = root.root.join("fleets").join(&file_name);
286 let text = root
287 .read_candidate(&path)
288 .map_err(|e| NamedFleetError::Io {
289 path: path.display().to_string(),
290 message: e.to_string(),
291 })?;
292 if let Some(text) = text {
293 candidates.push((root, path, text));
294 }
295 }
296
297 let Some((first_root, first_path, first_text)) = candidates.first() else {
298 return Err(NamedFleetError::NotFound(name.to_string()));
299 };
300
301 if candidates.len() > 1 {
302 // Decide ambiguity from the `schema` key alone — a cheap probe that
303 // does not parse the rest of the file. Fully parsing every sibling
304 // would mean a malformed *shadowed* file could fail a load that
305 // legacy first-hit-wins has always satisfied, which is a regression
306 // in a path the exact schema was never meant to touch. The
307 // ambiguity that actually matters is "one of these is exact", and
308 // the probe answers exactly that.
309 let any_exact = candidates
310 .iter()
311 .any(|(_, _, text)| declared_schema_kind(text).is_some());
312 if any_exact {
313 return Err(NamedFleetError::AmbiguousFleet {
314 name: bare_name.to_string(),
315 origins: candidates
316 .iter()
317 .map(|(root, path, _)| {
318 format!("{}/{bare_name} ({})", root.origin, path.display())
319 })
320 .collect(),
321 });
322 }
323 // Purely legacy collision: first hit wins, and only the first hit
324 // is parsed.
325 }
326
327 let document = Self::from_source(first_path, first_text, Some(bare_name))?;
328 Ok((
329 document,
330 QualifiedFleetId {
331 name: bare_name.to_string(),
332 origin: first_root.origin.clone(),
333 },
334 ))
335 }
336
337 #[must_use]
338 pub fn name(&self) -> &str {
339 match &self.schema {
340 FleetSchema::Legacy(fleet) => &fleet.name,
341 FleetSchema::Exact(fleet) => &fleet.name,
342 }
343 }
344
345 #[must_use]
346 pub fn description(&self) -> Option<&str> {
347 match &self.schema {
348 FleetSchema::Legacy(fleet) => fleet.description.as_deref(),
349 FleetSchema::Exact(fleet) => fleet.description.as_deref(),
350 }
351 }
352
353 #[must_use]
354 pub fn schema(&self) -> &FleetSchema {
355 &self.schema
356 }
357
358 /// Explicit legacy detection — never inferred from a missing table.
359 #[must_use]
360 pub const fn is_legacy(&self) -> bool {
361 matches!(self.schema, FleetSchema::Legacy(_))
362 }
363
364 #[must_use]
365 pub fn legacy(&self) -> Option<&NamedFleet> {
366 match &self.schema {
367 FleetSchema::Legacy(fleet) => Some(fleet),
368 FleetSchema::Exact(_) => None,
369 }
370 }
371
372 #[must_use]
373 pub fn exact(&self) -> Option<&ExactFleet> {
374 match &self.schema {
375 FleetSchema::Exact(fleet) => Some(fleet),
376 FleetSchema::Legacy(_) => None,
377 }
378 }
379
380 #[must_use]
381 pub fn schema_kind(&self) -> &'static str {
382 match self.schema {
383 FleetSchema::Legacy(_) => LEGACY_FLEET_SCHEMA_KIND,
384 FleetSchema::Exact(_) => EXACT_FLEET_SCHEMA_KIND,
385 }
386 }
387
388 #[must_use]
389 pub fn schema_revision(&self) -> u32 {
390 match &self.schema {
391 // Legacy files carry no revision; report 0 so a snapshot can tell
392 // "pre-versioned" from exact revision 1.
393 FleetSchema::Legacy(_) => 0,
394 FleetSchema::Exact(fleet) => fleet.schema_revision,
395 }
396 }
397
398 /// SHA-256 of the exact file bytes this document was parsed from.
399 #[must_use]
400 pub fn source_hash(&self) -> &str {
401 &self.source_hash
402 }
403
404 #[must_use]
405 pub fn source_path(&self) -> Option<&Path> {
406 self.source.as_deref()
407 }
408
409 /// An exact document frozen from a saved v2 Fleet at Workflow start.
410 ///
411 /// `frozen_text` is the exact-schema rendering of the saved Fleet with every
412 /// route and reasoning request resolved; it goes through the same exact
413 /// parser as a hand-written file, and [`Self::source_hash`] covers those
414 /// frozen bytes — what actually runs — while [`Self::source_path`] names the
415 /// saved Fleet file it came from.
416 pub fn from_frozen_saved_fleet(
417 frozen_text: &str,
418 source: &Path,
419 ) -> Result<Self, NamedFleetError> {
420 if declared_schema_kind(frozen_text).as_deref() != Some(EXACT_FLEET_SCHEMA_KIND) {
421 return Err(NamedFleetError::Parse {
422 path: source.display().to_string(),
423 message: "a frozen saved Fleet must be in the exact schema".to_string(),
424 });
425 }
426 let mut document = Self::parse(frozen_text).map_err(|error| match error {
427 NamedFleetError::Exact { source: inner, .. } => NamedFleetError::Exact {
428 fleet: source.display().to_string(),
429 source: inner,
430 },
431 other => other,
432 })?;
433 document.source = Some(source.to_path_buf());
434 Ok(document)
435 }
436
437 /// Build a document around an already-constructed exact roster.
438 ///
439 /// Test-only, and deliberately so: it is how a roster that never passed
440 /// through the TOML parser reaches [`crate::FleetSnapshot::capture`], which
441 /// is exactly the bypass capture-time revalidation exists to close.
442 #[cfg(test)]
443 #[must_use]
444 pub(crate) fn from_exact_for_tests(exact: ExactFleet) -> Self {
445 Self {
446 schema: FleetSchema::Exact(exact),
447 source: None,
448 source_hash: content_hash("<constructed>"),
449 }
450 }
451 }
452
453 /// The schema revision an exact document is expected to declare.
454 #[must_use]
455 pub const fn exact_schema_revision() -> u32 {
456 EXACT_FLEET_SCHEMA_REVISION
457 }
458
459 pub(crate) fn content_hash(text: &str) -> String {
460 sha256_label(text.as_bytes())
461 }
462
463 /// `sha256:<hex>` over arbitrary bytes, written out by hand rather than
464 /// relying on a digest `LowerHex` impl.
465 pub(crate) fn sha256_label(bytes: &[u8]) -> String {
466 use std::fmt::Write as _;
467
468 let digest = Sha256::digest(bytes);
469 let mut out = String::with_capacity(7 + digest.len() * 2);
470 out.push_str("sha256:");
471 for byte in digest.iter() {
472 let _ = write!(&mut out, "{byte:02x}");
473 }
474 out
475 }
476
477 /// Required roles for the stopship dogfood fleet (#4178).
478 pub const STOPSHIP_REQUIRED_ROLES: &[&str] =
479 &["explore", "implement", "reviewer", "test", "release_lead"];
480
481 /// Parse a fleet TOML document.
482 pub fn parse_named_fleet(toml_text: &str) -> Result<NamedFleet, NamedFleetError> {
483 // Minimal TOML subset without adding a toml dep to workflow:
484 // accept JSON as well for tests; for TOML use a tiny hand parser for
485 // the documented shape, or serde via json for unit tests.
486 // Prefer JSON if the text looks like JSON; otherwise use line-oriented TOML.
487 let trimmed = toml_text.trim();
488 if trimmed.starts_with('{') {
489 return serde_json::from_str(trimmed).map_err(|e| NamedFleetError::Parse {
490 path: "<memory>".into(),
491 message: e.to_string(),
492 });
493 }
494 parse_fleet_toml_minimal(trimmed)
495 }
496
497 /// Strip comments from the single-line basic and literal strings supported by
498 /// the minimal fleet parser.
499 fn strip_toml_comment(line: &str) -> &str {
500 let mut quote = None;
501 let mut escaped = false;
502
503 for (index, character) in line.char_indices() {
504 match quote {
505 Some('"') => {
506 if escaped {
507 escaped = false;
508 } else {
509 match character {
510 '\\' => escaped = true,
511 '"' => quote = None,
512 _ => {}
513 }
514 }
515 }
516 Some('\'') => {
517 if character == '\'' {
518 quote = None;
519 }
520 }
521 Some(_) => unreachable!("only TOML string delimiters are tracked"),
522 None => match character {
523 '"' | '\'' => quote = Some(character),
524 '#' => return &line[..index],
525 _ => {}
526 },
527 }
528 }
529
530 line
531 }
532
533 fn toml_string_value(value: &str) -> String {
534 if let Some(literal) = value
535 .strip_prefix('\'')
536 .and_then(|rest| rest.strip_suffix('\''))
537 {
538 return literal.to_string();
539 }
540 if value.starts_with('"')
541 && let Ok(basic) = serde_json::from_str::<String>(value)
542 {
543 return basic;
544 }
545 value.trim_matches('"').to_string()
546 }
547
548 fn parse_fleet_toml_minimal(text: &str) -> Result<NamedFleet, NamedFleetError> {
549 let mut name = None;
550 let mut description = None;
551 let mut roles = BTreeMap::new();
552 let mut section = "";
553 for raw in text.lines() {
554 let line = strip_toml_comment(raw).trim();
555 if line.is_empty() {
556 continue;
557 }
558 if line.starts_with('[') && line.ends_with(']') {
559 section = &line[1..line.len() - 1];
560 continue;
561 }
562 let Some((key, value)) = line.split_once('=') else {
563 continue;
564 };
565 let key = key.trim();
566 let value = toml_string_value(value.trim());
567 match section {
568 "" => match key {
569 "name" => name = Some(value),
570 "description" => description = Some(value),
571 _ => {}
572 },
573 "roles" => {
574 roles.insert(key.to_string(), value);
575 }
576 _ => {}
577 }
578 }
579 let name = name.ok_or_else(|| NamedFleetError::Parse {
580 path: "<memory>".into(),
581 message: "missing name".into(),
582 })?;
583 Ok(NamedFleet {
584 name,
585 description,
586 roles,
587 })
588 }
589
590 /// Load fleet by name from search paths (first hit wins).
591 pub fn load_named_fleet(
592 name: &str,
593 search_roots: &[FleetSearchRoot],
594 ) -> Result<NamedFleet, NamedFleetError> {
595 validate_fleet_file_stem(name)?;
596 let file_name = format!("{name}.toml");
597 for root in search_roots {
598 let path = root.root.join("fleets").join(&file_name);
599 let Some(text) = root
600 .read_candidate(&path)
601 .map_err(|e| NamedFleetError::Io {
602 path: path.display().to_string(),
603 message: e.to_string(),
604 })?
605 else {
606 continue;
607 };
608 let fleet = parse_named_fleet(&text).map_err(|e| match e {
609 NamedFleetError::Parse { message, .. } => NamedFleetError::Parse {
610 path: path.display().to_string(),
611 message,
612 },
613 other => other,
614 })?;
615 if fleet.name != name {
616 return Err(NamedFleetError::NameMismatch {
617 declared: fleet.name,
618 expected: name.to_string(),
619 });
620 }
621 return Ok(fleet);
622 }
623 Err(NamedFleetError::NotFound(name.to_string()))
624 }
625
626 pub fn load_named_fleet_file(
627 path: &Path,
628 expect_name: Option<&str>,
629 ) -> Result<NamedFleet, NamedFleetError> {
630 let text = std::fs::read_to_string(path).map_err(|e| NamedFleetError::Io {
631 path: path.display().to_string(),
632 message: e.to_string(),
633 })?;
634 let fleet = parse_named_fleet(&text).map_err(|e| match e {
635 NamedFleetError::Parse { message, .. } => NamedFleetError::Parse {
636 path: path.display().to_string(),
637 message,
638 },
639 other => other,
640 })?;
641 if let Some(expected) = expect_name
642 && fleet.name != expected
643 {
644 return Err(NamedFleetError::NameMismatch {
645 declared: fleet.name,
646 expected: expected.to_string(),
647 });
648 }
649 Ok(fleet)
650 }
651
652 impl NamedFleet {
653 /// Resolve a role name to a profile id.
654 pub fn resolve(&self, role: &str) -> Result<&str, NamedFleetError> {
655 let key = role.trim().to_ascii_lowercase();
656 self.roles
657 .get(&key)
658 .or_else(|| {
659 self.roles
660 .iter()
661 .find(|(k, _)| k.eq_ignore_ascii_case(role))
662 .map(|(_, v)| v)
663 })
664 .map(String::as_str)
665 .ok_or_else(|| NamedFleetError::MissingRole {
666 fleet: self.name.clone(),
667 role: role.to_string(),
668 })
669 }
670
671 /// Ensure all required stopship roles are present.
672 pub fn validate_stopship_roles(&self) -> Result<(), NamedFleetError> {
673 for role in STOPSHIP_REQUIRED_ROLES {
674 self.resolve(role)?;
675 }
676 Ok(())
677 }
678 }
679
680 #[cfg(test)]
681 mod tests {
682 use super::*;
683
684 const STOPSHIP_TOML: &str = r#"
685 name = "stopship"
686 description = "Stopship dogfood fleet"
687
688 [roles]
689 explore = "scout"
690 implement = "builder"
691 reviewer = "reviewer"
692 test = "verifier"
693 release_lead = "manager"
694 "#;
695
696 #[test]
697 fn stopship_fleet_resolves_all_five_roles() {
698 let fleet = parse_named_fleet(STOPSHIP_TOML).expect("parse");
699 assert_eq!(fleet.name, "stopship");
700 fleet.validate_stopship_roles().expect("all roles");
701 assert_eq!(fleet.resolve("explore").unwrap(), "scout");
702 assert_eq!(fleet.resolve("implement").unwrap(), "builder");
703 assert_eq!(fleet.resolve("reviewer").unwrap(), "reviewer");
704 assert_eq!(fleet.resolve("test").unwrap(), "verifier");
705 assert_eq!(fleet.resolve("release_lead").unwrap(), "manager");
706 }
707
708 #[test]
709 fn literal_and_escaped_toml_strings_lose_their_quotes() {
710 let fleet = parse_named_fleet(
711 "name = 'stopship' # literal\ndescription = \"a \\\"quoted\\\" fleet\"\n[roles]\nexplore = 'scout'\n",
712 )
713 .expect("parse");
714 assert_eq!(fleet.name, "stopship");
715 assert_eq!(fleet.description.as_deref(), Some("a \"quoted\" fleet"));
716 assert_eq!(fleet.resolve("explore").unwrap(), "scout");
717 }
718
719 #[test]
720 fn fleet_names_cannot_leave_the_fleets_directory() {
721 let tmp = tempfile::tempdir().expect("tempdir");
722 let ws = tmp.path().join("ws");
723 std::fs::create_dir_all(ws.join("fleets")).expect("fleets dir");
724 let planted = STOPSHIP_TOML.replace("\"stopship\"", "\"outside\"");
725 // Reachable by `workspace/../../outside` and by an absolute name.
726 std::fs::write(tmp.path().join("outside.toml"), &planted).expect("outside");
727 // Reachable by a bare `../outside` from `ws/fleets`.
728 std::fs::write(ws.join("outside.toml"), &planted).expect("sibling");
729 let roots = vec![FleetSearchRoot::new("workspace", &ws)];
730 let absolute = tmp.path().join("outside");
731 let absolute = absolute.to_string_lossy();
732
733 for name in [
734 "workspace/../../outside",
735 "workspace/../outside",
736 absolute.as_ref(),
737 "workspace/sub/outside",
738 "..",
739 "",
740 ] {
741 let err = FleetDocument::load_by_name(name, &roots).expect_err(name);
742 assert!(
743 matches!(err, NamedFleetError::InvalidName),
744 "{name}: expected InvalidName, got {err:?}"
745 );
746 assert!(
747 !err.to_string()
748 .contains(tmp.path().to_string_lossy().as_ref())
749 );
750 }
751 let root_ref = FleetSearchRoot::new("workspace", &ws);
752 let err =
753 load_named_fleet("../outside", std::slice::from_ref(&root_ref)).expect_err("legacy");
754 assert!(matches!(err, NamedFleetError::InvalidName), "{err:?}");
755
756 // A plain name still loads.
757 std::fs::write(ws.join("fleets").join("stopship.toml"), STOPSHIP_TOML).expect("fleet");
758 FleetDocument::load_by_name("stopship", &roots).expect("plain name");
759 FleetDocument::load_by_name("workspace/stopship", &roots).expect("qualified name");
760 load_named_fleet("stopship", std::slice::from_ref(&root_ref)).expect("legacy plain name");
761 }
762
763 #[test]
764 fn a_search_root_reader_decides_what_a_candidate_may_read() {
765 fn refuse(_: &Path) -> std::io::Result<String> {
766 Err(std::io::Error::new(
767 std::io::ErrorKind::InvalidInput,
768 "refused",
769 ))
770 }
771 fn missing(_: &Path) -> std::io::Result<String> {
772 Err(std::io::Error::from(std::io::ErrorKind::NotFound))
773 }
774 let tmp = tempfile::tempdir().expect("tmp");
775 let refusing = [FleetSearchRoot::new("workspace", tmp.path()).with_reader(refuse)];
776 assert!(matches!(
777 FleetDocument::load_by_name("stopship", &refusing),
778 Err(NamedFleetError::Io { .. })
779 ));
780 assert!(matches!(
781 load_named_fleet("stopship", &refusing),
782 Err(NamedFleetError::Io { .. })
783 ));
784 let absent = [FleetSearchRoot::new("workspace", tmp.path()).with_reader(missing)];
785 assert!(matches!(
786 FleetDocument::load_by_name("stopship", &absent),
787 Err(NamedFleetError::NotFound(_))
788 ));
789 assert!(matches!(
790 load_named_fleet("stopship", &absent),
791 Err(NamedFleetError::NotFound(_))
792 ));
793 }
794
795 #[cfg(unix)]
796 #[test]
797 fn load_named_fleet_refuses_symlinked_file_when_reader_rejects_links() {
798 fn refuse_symlink(path: &Path) -> std::io::Result<String> {
799 if std::fs::symlink_metadata(path)?.file_type().is_symlink() {
800 return Err(std::io::Error::new(
801 std::io::ErrorKind::InvalidInput,
802 format!("Refusing symlinked file {}", path.display()),
803 ));
804 }
805 std::fs::read_to_string(path)
806 }
807 let ws = tempfile::tempdir().expect("ws");
808 let outside = tempfile::tempdir().expect("outside");
809 std::fs::create_dir_all(ws.path().join("fleets")).expect("fleets dir");
810 std::fs::write(outside.path().join("x.toml"), "name = \"OUTSIDE\"\n").expect("outside");
811 std::os::unix::fs::symlink(
812 outside.path().join("x.toml"),
813 ws.path().join("fleets").join("x.toml"),
814 )
815 .expect("symlink");
816 let roots = [FleetSearchRoot::new("workspace", ws.path()).with_reader(refuse_symlink)];
817 assert!(matches!(
818 load_named_fleet("x", &roots),
819 Err(NamedFleetError::Io { .. })
820 ));
821 }
822
823 #[test]
824 fn unknown_role_fails_clearly() {
825 let fleet = parse_named_fleet(STOPSHIP_TOML).unwrap();
826 let err = fleet.resolve("wizard").unwrap_err();
827 assert!(matches!(err, NamedFleetError::MissingRole { .. }));
828 }
829
830 #[test]
831 fn quoted_hashes_are_not_treated_as_comments() {
832 let fleet = parse_named_fleet(
833 r#"
834 name = "issue-references"
835 description = "Tracks #4178 dogfood" # real comment
836
837 [roles]
838 scout = "scout#stable"
839 "#,
840 )
841 .expect("parse");
842
843 assert_eq!(fleet.description.as_deref(), Some("Tracks #4178 dogfood"));
844 assert_eq!(fleet.resolve("scout").unwrap(), "scout#stable");
845 }
846
847 #[test]
848 fn comment_stripping_tracks_toml_quotes_and_escapes() {
849 assert_eq!(
850 strip_toml_comment(r##"description = "say \"#still-value\"" # comment"##).trim_end(),
851 r##"description = "say \"#still-value\"""##
852 );
853 assert_eq!(
854 strip_toml_comment("description = 'tracks #4178' # comment").trim_end(),
855 "description = 'tracks #4178'"
856 );
857 assert_eq!(
858 strip_toml_comment(r#"name = "stopship" # comment"#).trim_end(),
859 r#"name = "stopship""#
860 );
861 }
862
863 #[test]
864 fn legacy_fleet_files_still_deserialize_and_resolve_through_the_document_api() {
865 let document = FleetDocument::parse(STOPSHIP_TOML).expect("legacy parse");
866
867 // Legacy is explicitly detectable, not inferred.
868 assert!(document.is_legacy());
869 assert_eq!(document.schema_kind(), "legacy");
870 assert_eq!(document.schema_revision(), 0);
871 assert!(document.exact().is_none());
872
873 let legacy = document.legacy().expect("legacy body");
874 legacy.validate_stopship_roles().expect("all roles");
875 assert_eq!(legacy.resolve("implement").unwrap(), "builder");
876 assert_eq!(document.name(), "stopship");
877 assert!(document.source_hash().starts_with("sha256:"));
878 }
879
880 #[test]
881 fn exact_fleet_files_are_selected_by_an_explicit_schema_key() {
882 let document = FleetDocument::parse(
883 r#"
884 name = "glm-pair"
885 schema = "exact"
886
887 [[members]]
888 id = "implementer"
889 provider = "zai"
890 model = "glm-5"
891 reasoning = "auto"
892
893 [[members]]
894 id = "router"
895 kind = "router"
896 provider = "zai"
897 model = "glm-5-turbo"
898 "#,
899 )
900 .expect("exact parse");
901
902 assert!(!document.is_legacy());
903 assert_eq!(document.schema_kind(), "exact");
904 assert_eq!(document.schema_revision(), exact_schema_revision());
905 assert!(document.legacy().is_none());
906 let exact = document.exact().expect("exact body");
907 assert!(exact.has_auto_member());
908 // The prototype inline form still parses, and is reported as the legacy
909 // inline router rather than as a second runtime concept.
910 assert!(exact.legacy_inline_router().is_some());
911 assert!(exact.router_ref().is_some());
912 }
913
914 #[test]
915 fn an_unknown_schema_key_fails_instead_of_falling_back_to_legacy() {
916 let err = FleetDocument::parse("name = \"f\"\nschema = \"experimental\"\n")
917 .expect_err("unknown schema must not silently parse as legacy");
918 assert!(matches!(err, NamedFleetError::Parse { .. }), "{err:?}");
919 }
920
921 #[test]
922 fn document_hash_follows_the_file_bytes() {
923 let a = FleetDocument::parse(STOPSHIP_TOML).expect("parse");
924 let b = FleetDocument::parse(STOPSHIP_TOML).expect("parse");
925 let c = FleetDocument::parse(&STOPSHIP_TOML.replace("builder", "implementer_profile"))
926 .expect("parse");
927
928 assert_eq!(a.source_hash(), b.source_hash());
929 assert_ne!(a.source_hash(), c.source_hash());
930 }
931
932 #[test]
933 fn loads_workspace_fleet_file() {
934 // Relative to crate CARGO_MANIFEST_DIR → repo .codewhale/fleets/
935 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
936 .join("..")
937 .join("..")
938 .join(".codewhale");
939 let search_root = FleetSearchRoot::new("workspace", &root);
940 let fleet = load_named_fleet("stopship", &[search_root]).expect("load workspace fleet");
941 fleet.validate_stopship_roles().unwrap();
942 }
943
944 #[test]
945 fn a_frozen_saved_fleet_is_exact_and_names_its_source_file() {
946 let source = Path::new("/saved/.codewhale/fleets/release.toml");
947 let frozen = "schema = \"exact\"\nschema_revision = 1\nname = \"release\"\n\n\
948 [[members]]\nid = \"builder\"\nrole = \"implement\"\n\
949 provider = \"zai\"\nmodel = \"glm-5\"\nreasoning = \"high\"\n";
950 let document = FleetDocument::from_frozen_saved_fleet(frozen, source).expect("frozen");
951 assert!(document.exact().is_some());
952 assert_eq!(document.source_path(), Some(source));
953 assert_eq!(document.source_hash(), content_hash(frozen));
954
955 // Anything that is not the exact schema is refused, never parsed as a
956 // legacy role map.
957 let error = FleetDocument::from_frozen_saved_fleet(
958 "name = \"release\"\n[roles]\nimplement = \"builder\"\n",
959 source,
960 )
961 .expect_err("legacy text is not a frozen snapshot");
962 assert!(error.to_string().contains("exact schema"), "{error}");
963 }
964
965 #[test]
966 fn a_saved_fleet_schema_is_named_in_the_unknown_schema_error() {
967 let error = FleetDocument::parse("schema = \"fleet\"\nname = \"x\"\n").unwrap_err();
968 let message = error.to_string();
969 assert!(
970 message.contains("expected `exact` or a saved Fleet"),
971 "{message}"
972 );
973 assert!(message.contains(".codewhale/fleets/"), "{message}");
974 }
975 }
976
976 lines RUST