| 1 | //! The saved named Fleet — the single configuration concept for the whole |
| 2 | //! Fleet surface. Its v2 compatibility storage keeps `schema = "fleet"`. |
| 3 | //! |
| 4 | //! A Fleet is one self-contained TOML file. It owns: |
| 5 | //! |
| 6 | //! - its **operator** route (provider + exact model + reasoning), or the |
| 7 | //! explicit absence of one ("inherit the session route"); |
| 8 | //! - its **roster**: each member's stable id, optional human-facing name, role, |
| 9 | //! exact model pin or inherit policy, provider (pins only — never inferred |
| 10 | //! from a model string), reasoning level, optional instructions, and |
| 11 | //! capability requirements; |
| 12 | //! - its **save scope and source**: personal (`$CODEWHALE_HOME/fleets/`) or |
| 13 | //! workspace (`.codewhale/fleets/`), with the exact file path surfaced. |
| 14 | //! |
| 15 | //! There is exactly one store. The legacy per-role profile files |
| 16 | //! (`~/.codewhale/agents/*.toml`, `.codewhale/agents/*.toml`, |
| 17 | //! `[fleet.profiles]`) and the workflow crate's `exact`/legacy named-fleet |
| 18 | //! files are migration/compat input only — read here, never shadowed, never |
| 19 | //! the runtime winner alongside a v2 Fleet. |
| 20 | //! |
| 21 | //! Selection is a scope-explicit file: `fleets/selected` under the personal |
| 22 | //! root is the user-global default; the same file under the workspace root is |
| 23 | //! an intentional workspace selection. Workspace selection wins; both are |
| 24 | //! labeled in the UI. A workspace selection can never hide or rewrite a |
| 25 | //! personal Fleet. |
| 26 | |
| 27 | use std::collections::BTreeMap; |
| 28 | use std::fs; |
| 29 | use std::path::{Path, PathBuf}; |
| 30 | |
| 31 | use codewhale_config::ProviderKind; |
| 32 | use codewhale_localization::{Locale, MessageId, tr}; |
| 33 | |
| 34 | use serde::{Deserialize, Serialize}; |
| 35 | use thiserror::Error; |
| 36 | |
| 37 | use super::roster::FleetRoster; |
| 38 | |
| 39 | pub const FLEET_SCHEMA_KIND: &str = "fleet"; |
| 40 | pub const FLEET_SCHEMA_REVISION: u32 = 2; |
| 41 | const MAX_MEMBER_DISPLAY_NAME_CHARS: usize = 80; |
| 42 | const MAX_FLEET_NAME_CHARS: usize = 120; |
| 43 | const MAX_MEMBER_ID_CHARS: usize = 64; |
| 44 | const MAX_MEMBER_ROLE_CHARS: usize = 80; |
| 45 | const MAX_ROUTE_FIELD_CHARS: usize = 256; |
| 46 | const MAX_MEMBER_INSTRUCTIONS_CHARS: usize = 32 * 1024; |
| 47 | const MAX_FLEET_DESCRIPTION_CHARS: usize = 32 * 1024; |
| 48 | |
| 49 | /// A value that reaches selectors, receipts, and terminal rendering: printable |
| 50 | /// and bounded. `multiline` admits newlines and tabs (instruction overlays) |
| 51 | /// but no other control characters. |
| 52 | fn validate_text( |
| 53 | what: &str, |
| 54 | value: &str, |
| 55 | max_chars: usize, |
| 56 | multiline: bool, |
| 57 | ) -> Result<(), FleetStoreError> { |
| 58 | let printable = value |
| 59 | .chars() |
| 60 | .all(|ch| !ch.is_control() || (multiline && matches!(ch, '\n' | '\r' | '\t'))); |
| 61 | if !printable || value.chars().count() > max_chars { |
| 62 | return Err(FleetStoreError::Invalid(format!( |
| 63 | "{what} must be printable {} no longer than {max_chars} characters", |
| 64 | if multiline { |
| 65 | "text" |
| 66 | } else { |
| 67 | "single-line text" |
| 68 | } |
| 69 | ))); |
| 70 | } |
| 71 | Ok(()) |
| 72 | } |
| 73 | |
| 74 | /// The directory name used by both roots (next to `agents/` for legacy |
| 75 | /// profiles). Also used by the workflow crate for its own legacy/exact files; |
| 76 | /// v2 files in the same directory are simply a newer schema. |
| 77 | pub const FLEET_DIR: &str = "fleets"; |
| 78 | pub const SELECTED_FILE: &str = "selected"; |
| 79 | |
| 80 | /// Where a Fleet was saved. This is the pin target: personal = user-global, |
| 81 | /// workspace = folder-scoped. |
| 82 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 83 | #[serde(rename_all = "snake_case")] |
| 84 | pub enum FleetScope { |
| 85 | Personal, |
| 86 | Workspace, |
| 87 | } |
| 88 | |
| 89 | impl FleetScope { |
| 90 | /// Short label for UI and receipts: "user" / "folder". |
| 91 | #[must_use] |
| 92 | pub const fn label(self) -> &'static str { |
| 93 | match self { |
| 94 | Self::Personal => "user", |
| 95 | Self::Workspace => "folder", |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | #[must_use] |
| 100 | pub const fn long_label(self) -> &'static str { |
| 101 | match self { |
| 102 | Self::Personal => "user-global", |
| 103 | Self::Workspace => "folder (this workspace)", |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | #[must_use] |
| 108 | pub const fn toggled(self) -> Self { |
| 109 | match self { |
| 110 | Self::Personal => Self::Workspace, |
| 111 | Self::Workspace => Self::Personal, |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// A Fleet's own operator route. Absent = inherit the live session route. |
| 117 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 118 | #[serde(deny_unknown_fields)] |
| 119 | pub struct FleetOperator { |
| 120 | /// Exact provider id (a `[providers.<id>]` key or a built-in id). |
| 121 | pub provider: String, |
| 122 | /// Exact model id on that provider's route. |
| 123 | pub model: String, |
| 124 | /// Reasoning level, only when the resolved route genuinely supports it. |
| 125 | /// Absent = inherit the session tier. |
| 126 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 127 | pub reasoning: Option<String>, |
| 128 | } |
| 129 | |
| 130 | /// Capability requirements a member must satisfy. The vocabulary is closed so |
| 131 | /// an unknown requirement is a specific error, never a silent reinterpretation. |
| 132 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 133 | pub enum MemberCapability { |
| 134 | /// Image input: the member must run on a route that accepts images. |
| 135 | Vision, |
| 136 | } |
| 137 | |
| 138 | impl MemberCapability { |
| 139 | pub const VOCABULARY: [&'static str; 1] = ["vision"]; |
| 140 | |
| 141 | pub fn parse(value: &str) -> Option<Self> { |
| 142 | match value.trim().to_ascii_lowercase().as_str() { |
| 143 | "vision" | "image" | "image-input" => Some(Self::Vision), |
| 144 | _ => None, |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | #[must_use] |
| 149 | pub const fn wire_name(self) -> &'static str { |
| 150 | match self { |
| 151 | Self::Vision => "vision", |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// One roster member of a Fleet. |
| 157 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 158 | #[serde(deny_unknown_fields)] |
| 159 | pub struct FleetMember { |
| 160 | /// Stable member id — the role identity (e.g. `scout`, `builder`). |
| 161 | pub id: String, |
| 162 | /// Optional human-facing name used by roster views and member selectors. |
| 163 | /// |
| 164 | /// `name` is accepted as an authoring alias, while canonical saves use |
| 165 | /// `display_name`. Existing revision-2 files omit this field and continue |
| 166 | /// to deserialize unchanged. |
| 167 | #[serde(default, alias = "name", skip_serializing_if = "Option::is_none")] |
| 168 | pub display_name: Option<String>, |
| 169 | /// A role-less model choice, not an executable roster member. Omitted |
| 170 | /// in legacy files, whose role/id interpretation stays unchanged. |
| 171 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 172 | pub shortlist: bool, |
| 173 | /// Role label; defaults to `id` when absent on a non-shortlist member. |
| 174 | #[serde(default, skip_serializing_if = "String::is_empty")] |
| 175 | pub role: String, |
| 176 | /// Exact model pin. Absent with `provider` absent = inherit the session |
| 177 | /// route (the operator route when the Fleet has one). |
| 178 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 179 | pub model: Option<String>, |
| 180 | /// Exact provider id for `model`. Pins only: a member must never carry |
| 181 | /// `provider` without `model` (rejected at parse), and the provider is |
| 182 | /// never inferred from the model string. |
| 183 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 184 | pub provider: Option<String>, |
| 185 | /// Reasoning level for this member, only when the resolved route |
| 186 | /// supports it. Absent = inherit. |
| 187 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 188 | pub reasoning: Option<String>, |
| 189 | /// Optional instruction overlay for the role. |
| 190 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 191 | pub instructions: Option<String>, |
| 192 | /// Capability requirements, e.g. `["vision"]`. Validated against |
| 193 | /// [`MemberCapability::VOCABULARY`] at parse. |
| 194 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 195 | pub requires: Vec<String>, |
| 196 | } |
| 197 | |
| 198 | impl FleetMember { |
| 199 | /// The role this member fills: `role`, or `id` when the document left |
| 200 | /// the role field off. A shortlisted model has no role. |
| 201 | #[must_use] |
| 202 | pub fn role_label(&self) -> &str { |
| 203 | if self.shortlist { |
| 204 | return ""; |
| 205 | } |
| 206 | let role = self.role.trim(); |
| 207 | if role.is_empty() { |
| 208 | self.id.trim() |
| 209 | } else { |
| 210 | role |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | /// A row that was a model pin promoted to a member: no role, and an id |
| 215 | /// that is just the model's slug. Such rows are not members. |
| 216 | #[must_use] |
| 217 | pub fn is_bare_model_pin(&self) -> bool { |
| 218 | !self.shortlist |
| 219 | && self.role.trim().is_empty() |
| 220 | && self |
| 221 | .model |
| 222 | .as_deref() |
| 223 | .is_some_and(|model| self.id.trim().starts_with(slugify(model).as_str())) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// Provider kinds have documented aliases; named custom routes have exact |
| 228 | /// keys. Treating every provider name as case-insensitive merges distinct |
| 229 | /// endpoints before the configured route binder can resolve them. |
| 230 | pub fn provider_ids_match(saved: &str, requested: &str) -> bool { |
| 231 | saved.trim() == requested.trim() |
| 232 | || ProviderKind::parse(saved) |
| 233 | .filter(|provider| *provider != ProviderKind::Custom) |
| 234 | .is_some_and(|provider| Some(provider) == ProviderKind::parse(requested)) |
| 235 | } |
| 236 | |
| 237 | /// The member pins exactly `provider`/`model`. |
| 238 | pub fn member_pins(member: &FleetMember, provider: &str, model: &str) -> bool { |
| 239 | member |
| 240 | .provider |
| 241 | .as_deref() |
| 242 | .is_some_and(|p| provider_ids_match(p, provider)) |
| 243 | && member.model.as_deref().is_some_and(|id| id == model) |
| 244 | } |
| 245 | |
| 246 | /// The saved named Fleet document (compatibility `schema = "fleet"`, revision 2). |
| 247 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 248 | #[serde(deny_unknown_fields)] |
| 249 | pub struct FleetFile { |
| 250 | pub schema: String, |
| 251 | pub schema_revision: u32, |
| 252 | /// Editable display name. Unique per scope (the file slug is derived |
| 253 | /// from it); the same name may exist in both scopes, distinguished by |
| 254 | /// origin, never silently shadowed. |
| 255 | pub name: String, |
| 256 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 257 | pub description: Option<String>, |
| 258 | /// The Fleet's own operator route. Absent = inherit the session route. |
| 259 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 260 | pub operator: Option<FleetOperator>, |
| 261 | #[serde(default)] |
| 262 | pub members: Vec<FleetMember>, |
| 263 | } |
| 264 | |
| 265 | /// Why a Fleet file could not be used. |
| 266 | #[derive(Debug, Clone, PartialEq, Eq, Error)] |
| 267 | pub enum FleetStoreError { |
| 268 | #[error("invalid fleet: {0}")] |
| 269 | Invalid(String), |
| 270 | #[error( |
| 271 | "fleet `{0}` is defined in both {1} and {2}; name one explicitly as {1}/{0} or {2}/{0}" |
| 272 | )] |
| 273 | Ambiguous(String, String, String), |
| 274 | #[error("fleet file not found: {0}")] |
| 275 | NotFound(String), |
| 276 | #[error("failed to read {path}: {message}")] |
| 277 | Io { path: String, message: String }, |
| 278 | #[error("failed to parse {path}: {message}")] |
| 279 | Parse { path: String, message: String }, |
| 280 | #[error("a fleet named `{name}` already exists at {path}; rename it or choose another name")] |
| 281 | NameTaken { name: String, path: String }, |
| 282 | } |
| 283 | |
| 284 | impl FleetStoreError { |
| 285 | /// The person-facing explanation in `locale`. |
| 286 | #[must_use] |
| 287 | pub fn message(&self, locale: Locale) -> String { |
| 288 | match self { |
| 289 | Self::Invalid(message) => { |
| 290 | tr(locale, MessageId::FleetStoreErrorInvalid).replace("{message}", message) |
| 291 | } |
| 292 | Self::Ambiguous(name, first, second) => tr(locale, MessageId::FleetStoreErrorAmbiguous) |
| 293 | .replace("{name}", name) |
| 294 | .replace("{first}", first) |
| 295 | .replace("{second}", second), |
| 296 | Self::NotFound(name) => { |
| 297 | tr(locale, MessageId::FleetStoreErrorNotFound).replace("{name}", name) |
| 298 | } |
| 299 | Self::Io { path, message } => tr(locale, MessageId::FleetStoreErrorIo) |
| 300 | .replace("{path}", path) |
| 301 | .replace("{message}", message), |
| 302 | Self::Parse { path, message } => tr(locale, MessageId::FleetStoreErrorParse) |
| 303 | .replace("{path}", path) |
| 304 | .replace("{message}", message), |
| 305 | Self::NameTaken { name, path } => tr(locale, MessageId::FleetStoreErrorNameTaken) |
| 306 | .replace("{name}", name) |
| 307 | .replace("{path}", path), |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | impl FleetFile { |
| 313 | /// Create a validated v2 Fleet file. |
| 314 | pub fn new(name: String, description: Option<String>) -> Result<Self, FleetStoreError> { |
| 315 | let fleet = Self { |
| 316 | schema: FLEET_SCHEMA_KIND.to_string(), |
| 317 | schema_revision: FLEET_SCHEMA_REVISION, |
| 318 | name, |
| 319 | description, |
| 320 | operator: None, |
| 321 | members: Vec::new(), |
| 322 | }; |
| 323 | fleet.validate()?; |
| 324 | Ok(fleet) |
| 325 | } |
| 326 | |
| 327 | /// Validate the document: name, member ids, pin symmetry, capability |
| 328 | /// vocabulary. Invalid input is rejected with a specific error — never |
| 329 | /// silently reinterpreted. |
| 330 | pub fn validate(&self) -> Result<(), FleetStoreError> { |
| 331 | if self.schema != FLEET_SCHEMA_KIND { |
| 332 | return Err(FleetStoreError::Invalid(format!( |
| 333 | "unknown schema `{}`; expected `{FLEET_SCHEMA_KIND}`", |
| 334 | self.schema |
| 335 | ))); |
| 336 | } |
| 337 | if self.schema_revision != FLEET_SCHEMA_REVISION { |
| 338 | return Err(FleetStoreError::Invalid(format!( |
| 339 | "unsupported schema revision {}; this build reads revision {FLEET_SCHEMA_REVISION}", |
| 340 | self.schema_revision |
| 341 | ))); |
| 342 | } |
| 343 | let name = self.name.trim(); |
| 344 | if name.is_empty() { |
| 345 | return Err(FleetStoreError::Invalid( |
| 346 | "fleet name must not be empty".to_string(), |
| 347 | )); |
| 348 | } |
| 349 | // The stored name, not its trimmed view: a control character before |
| 350 | // or after the name reaches selectors and terminal rendering too. |
| 351 | validate_text("fleet name", &self.name, MAX_FLEET_NAME_CHARS, false)?; |
| 352 | if let Some(description) = self.description.as_deref() { |
| 353 | validate_text( |
| 354 | "fleet description", |
| 355 | description, |
| 356 | MAX_FLEET_DESCRIPTION_CHARS, |
| 357 | true, |
| 358 | )?; |
| 359 | } |
| 360 | // The operator route flows into every inheriting member's route, so |
| 361 | // it is bounded exactly like a member's pin. |
| 362 | if let Some(operator) = &self.operator { |
| 363 | for (field, value) in [ |
| 364 | ("provider", Some(operator.provider.as_str())), |
| 365 | ("model", Some(operator.model.as_str())), |
| 366 | ("reasoning", operator.reasoning.as_deref()), |
| 367 | ] { |
| 368 | if let Some(value) = value { |
| 369 | validate_text( |
| 370 | &format!("operator {field}"), |
| 371 | value, |
| 372 | MAX_ROUTE_FIELD_CHARS, |
| 373 | false, |
| 374 | )?; |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | let mut seen: BTreeMap<String, String> = BTreeMap::new(); |
| 379 | for member in &self.members { |
| 380 | let member_id = member.id.trim(); |
| 381 | if member_id.is_empty() { |
| 382 | return Err(FleetStoreError::Invalid( |
| 383 | "member id must not be empty".to_string(), |
| 384 | )); |
| 385 | } |
| 386 | // The id is dispatch identity: exact, not merely equal once trimmed. |
| 387 | if member_id != member.id { |
| 388 | return Err(FleetStoreError::Invalid(format!( |
| 389 | "member id {:?} must not carry leading or trailing whitespace", |
| 390 | member.id |
| 391 | ))); |
| 392 | } |
| 393 | validate_text("member id", member_id, MAX_MEMBER_ID_CHARS, false)?; |
| 394 | let fields = [ |
| 395 | ( |
| 396 | "role", |
| 397 | Some(member.role.as_str()), |
| 398 | MAX_MEMBER_ROLE_CHARS, |
| 399 | false, |
| 400 | ), |
| 401 | ( |
| 402 | "provider", |
| 403 | member.provider.as_deref(), |
| 404 | MAX_ROUTE_FIELD_CHARS, |
| 405 | false, |
| 406 | ), |
| 407 | ( |
| 408 | "model", |
| 409 | member.model.as_deref(), |
| 410 | MAX_ROUTE_FIELD_CHARS, |
| 411 | false, |
| 412 | ), |
| 413 | ( |
| 414 | "reasoning", |
| 415 | member.reasoning.as_deref(), |
| 416 | MAX_ROUTE_FIELD_CHARS, |
| 417 | false, |
| 418 | ), |
| 419 | ( |
| 420 | "instructions", |
| 421 | member.instructions.as_deref(), |
| 422 | MAX_MEMBER_INSTRUCTIONS_CHARS, |
| 423 | true, |
| 424 | ), |
| 425 | ]; |
| 426 | for (field, value, max_chars, multiline) in fields { |
| 427 | if let Some(value) = value { |
| 428 | validate_text( |
| 429 | &format!("member `{member_id}` {field}"), |
| 430 | value, |
| 431 | max_chars, |
| 432 | multiline, |
| 433 | )?; |
| 434 | } |
| 435 | } |
| 436 | let member_key = member_id.to_ascii_lowercase(); |
| 437 | if let Some(existing) = seen.insert(member_key, member.id.clone()) { |
| 438 | return Err(FleetStoreError::Invalid(format!( |
| 439 | "duplicate member id `{}` conflicts case-insensitively with `{existing}`", |
| 440 | member.id, |
| 441 | ))); |
| 442 | } |
| 443 | if let Some(display_name) = member.display_name.as_deref() { |
| 444 | let trimmed = display_name.trim(); |
| 445 | if trimmed.is_empty() { |
| 446 | return Err(FleetStoreError::Invalid(format!( |
| 447 | "member `{}` display_name must not be empty", |
| 448 | member.id, |
| 449 | ))); |
| 450 | } |
| 451 | if trimmed != display_name |
| 452 | || display_name.chars().any(char::is_control) |
| 453 | || display_name.chars().count() > MAX_MEMBER_DISPLAY_NAME_CHARS |
| 454 | { |
| 455 | return Err(FleetStoreError::Invalid(format!( |
| 456 | "member `{}` display_name must be one trimmed printable line no longer than {MAX_MEMBER_DISPLAY_NAME_CHARS} characters", |
| 457 | member.id, |
| 458 | ))); |
| 459 | } |
| 460 | } |
| 461 | match (&member.provider, &member.model) { |
| 462 | (Some(_), None) | (None, Some(_)) => { |
| 463 | return Err(FleetStoreError::Invalid(format!( |
| 464 | "member `{}` must pin both provider and model, or neither (inherit); a lone {} is rejected", |
| 465 | member.id, |
| 466 | if member.provider.is_some() { |
| 467 | "provider" |
| 468 | } else { |
| 469 | "model" |
| 470 | } |
| 471 | ))); |
| 472 | } |
| 473 | _ => {} |
| 474 | } |
| 475 | if member.shortlist |
| 476 | && (!member.role.trim().is_empty() |
| 477 | || member |
| 478 | .provider |
| 479 | .as_deref() |
| 480 | .is_none_or(|id| id.trim().is_empty()) |
| 481 | || member |
| 482 | .model |
| 483 | .as_deref() |
| 484 | .is_none_or(|id| id.trim().is_empty())) |
| 485 | { |
| 486 | return Err(FleetStoreError::Invalid(format!( |
| 487 | "shortlisted member `{}` must have no role and pin both provider and model", |
| 488 | member.id, |
| 489 | ))); |
| 490 | } |
| 491 | if member.shortlist |
| 492 | && (member |
| 493 | .reasoning |
| 494 | .as_deref() |
| 495 | .is_some_and(|value| !value.trim().is_empty()) |
| 496 | || member |
| 497 | .instructions |
| 498 | .as_deref() |
| 499 | .is_some_and(|value| !value.trim().is_empty()) |
| 500 | || !member.requires.is_empty()) |
| 501 | { |
| 502 | return Err(FleetStoreError::Invalid(format!( |
| 503 | "shortlisted member `{}` cannot set role reasoning, instructions, or capability requirements", |
| 504 | member.id, |
| 505 | ))); |
| 506 | } |
| 507 | for requirement in &member.requires { |
| 508 | if MemberCapability::parse(requirement).is_none() { |
| 509 | return Err(FleetStoreError::Invalid(format!( |
| 510 | "member `{}` requires unknown capability `{requirement}`; valid values: {}", |
| 511 | member.id, |
| 512 | MemberCapability::VOCABULARY.join(", ") |
| 513 | ))); |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | Ok(()) |
| 518 | } |
| 519 | |
| 520 | /// Render the canonical TOML document. |
| 521 | pub fn render_toml(&self) -> Result<String, FleetStoreError> { |
| 522 | self.validate()?; |
| 523 | let rendered = toml::to_string_pretty(self) |
| 524 | .map_err(|e| FleetStoreError::Invalid(format!("failed to serialize fleet: {e}")))?; |
| 525 | Ok(rendered) |
| 526 | } |
| 527 | |
| 528 | /// Parse a v2 fleet document from TOML text. |
| 529 | pub fn parse(text: &str) -> Result<Self, FleetStoreError> { |
| 530 | let mut fleet: Self = toml::from_str(text) |
| 531 | .map_err(|e| FleetStoreError::Invalid(format!("invalid fleet TOML: {e}")))?; |
| 532 | // Compat (0.9.12): every model the user ever selected was enrolled |
| 533 | // as a role-less member with a slug id. Roles are the members; drop |
| 534 | // those rows on read so the roster reads as roles again. The next |
| 535 | // save writes the clean document. |
| 536 | fleet.members.retain(|member| !member.is_bare_model_pin()); |
| 537 | // #6037: a member pinned to the fleet's own operator route resolves |
| 538 | // to that route either way; the pin only stops it following when the |
| 539 | // operator moves (a vendor retiring the id, an operator switching |
| 540 | // models). Read the redundant pin as the inheritance it always meant. |
| 541 | // Shortlist rows keep their pin — it is their entire content. |
| 542 | if let Some(operator) = &fleet.operator { |
| 543 | for member in &mut fleet.members { |
| 544 | if !member.shortlist && member_pins(member, &operator.provider, &operator.model) { |
| 545 | member.provider = None; |
| 546 | member.model = None; |
| 547 | } |
| 548 | } |
| 549 | } |
| 550 | fleet.validate()?; |
| 551 | Ok(fleet) |
| 552 | } |
| 553 | |
| 554 | /// A stable file slug derived from the display name. Safe across the |
| 555 | /// filesystems Codewhale supports; collisions are detected at save. |
| 556 | #[must_use] |
| 557 | pub fn file_slug(&self) -> String { |
| 558 | slugify(&self.name) |
| 559 | } |
| 560 | |
| 561 | /// Look up an executable member by role id. Shortlisted model ids never |
| 562 | /// select a role, even when they happen to match one. |
| 563 | #[must_use] |
| 564 | pub fn member(&self, id: &str) -> Option<&FleetMember> { |
| 565 | let id = id.trim(); |
| 566 | self.members |
| 567 | .iter() |
| 568 | .find(|member| !member.shortlist && member.id.trim().eq_ignore_ascii_case(id)) |
| 569 | } |
| 570 | |
| 571 | /// Whether the roster contains a scout member (the fast exploratory role). |
| 572 | #[must_use] |
| 573 | pub fn has_scout(&self) -> bool { |
| 574 | self.member("scout").is_some() |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | /// Sanitize a display name into a safe file slug. |
| 579 | pub fn slugify(name: &str) -> String { |
| 580 | let mut slug = String::with_capacity(name.len()); |
| 581 | for ch in name.trim().chars() { |
| 582 | if ch.is_ascii_alphanumeric() { |
| 583 | slug.push(ch.to_ascii_lowercase()); |
| 584 | } else if (ch.is_whitespace() || ch == '-' || ch == '_') && !slug.ends_with('-') { |
| 585 | slug.push('-'); |
| 586 | } |
| 587 | } |
| 588 | while slug.ends_with('-') { |
| 589 | slug.pop(); |
| 590 | } |
| 591 | if slug.is_empty() { |
| 592 | "fleet".to_string() |
| 593 | } else { |
| 594 | slug |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | /// One entry in the Fleet list: name, scope, exact path, and health. |
| 599 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 600 | pub struct FleetEntry { |
| 601 | pub name: String, |
| 602 | pub scope: FleetScope, |
| 603 | /// Exact path of the saved file. |
| 604 | pub path: PathBuf, |
| 605 | /// Parse failure, when the file exists but cannot be read as a v2 Fleet. |
| 606 | pub parse_error: Option<String>, |
| 607 | /// Whether the file is a legacy (pre-v2) named-fleet file (exact or |
| 608 | /// roles map) that is read for compatibility but not editable as v2. |
| 609 | pub legacy: bool, |
| 610 | } |
| 611 | |
| 612 | /// The resolved selection: which Fleet a session should start on, and which |
| 613 | /// scope made the choice. |
| 614 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 615 | pub struct SelectedFleet { |
| 616 | pub name: String, |
| 617 | pub scope: FleetScope, |
| 618 | pub path: PathBuf, |
| 619 | } |
| 620 | |
| 621 | fn personal_fleets_dir() -> Result<PathBuf, FleetStoreError> { |
| 622 | #[cfg(any(test, feature = "test-support"))] |
| 623 | if !crate::test_support::guarded_environment_provides_state_paths() { |
| 624 | return Ok(crate::test_support::unsealed_test_state_root().join(FLEET_DIR)); |
| 625 | } |
| 626 | codewhale_config::codewhale_home() |
| 627 | .map(|home| home.join(FLEET_DIR)) |
| 628 | .map_err(|e| FleetStoreError::Io { |
| 629 | path: "$CODEWHALE_HOME/fleets".to_string(), |
| 630 | message: e.to_string(), |
| 631 | }) |
| 632 | } |
| 633 | |
| 634 | fn workspace_fleets_dir(workspace: &Path) -> PathBuf { |
| 635 | codewhale_util::files::workspace_state_path(workspace, Path::new(FLEET_DIR)).1 |
| 636 | } |
| 637 | |
| 638 | pub fn read_repository_fleet_file(path: &Path) -> std::io::Result<String> { |
| 639 | let root = path |
| 640 | .parent() |
| 641 | .and_then(Path::parent) |
| 642 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; |
| 643 | if root |
| 644 | .file_name() |
| 645 | .is_some_and(|name| name == codewhale_paths::CODEWHALE_APP_DIR) |
| 646 | { |
| 647 | let metadata = fs::symlink_metadata(root)?; |
| 648 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) { |
| 649 | return Err(std::io::Error::new( |
| 650 | std::io::ErrorKind::InvalidInput, |
| 651 | format!("Refusing symlinked path {}", root.display()), |
| 652 | )); |
| 653 | } |
| 654 | } |
| 655 | codewhale_util::fs_confined::read_to_string(root, path) |
| 656 | } |
| 657 | |
| 658 | fn read_store_file(path: &Path) -> std::io::Result<String> { |
| 659 | if personal_fleets_dir() |
| 660 | .ok() |
| 661 | .is_some_and(|personal| path.starts_with(personal)) |
| 662 | { |
| 663 | fs::read_to_string(path) |
| 664 | } else { |
| 665 | read_repository_fleet_file(path) |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | /// The fleet directory for a scope, creating it if needed. |
| 670 | /// |
| 671 | /// Returns the confinement root and the directory. They are one decision: a |
| 672 | /// home workspace keeps its state behind a junction the user made, so the |
| 673 | /// writer must open through the resolved root, or it would refuse the very |
| 674 | /// directory this check just accepted. |
| 675 | fn ensure_fleets_dir( |
| 676 | scope: FleetScope, |
| 677 | workspace: &Path, |
| 678 | ) -> Result<(PathBuf, PathBuf), FleetStoreError> { |
| 679 | let (root, dir) = match scope { |
| 680 | FleetScope::Personal => { |
| 681 | let dir = personal_fleets_dir()?; |
| 682 | (dir.clone(), dir) |
| 683 | } |
| 684 | FleetScope::Workspace => { |
| 685 | codewhale_util::files::workspace_state_path(workspace, Path::new(FLEET_DIR)) |
| 686 | } |
| 687 | }; |
| 688 | reject_linked_workspace_dir(scope, workspace)?; |
| 689 | fs::create_dir_all(&dir).map_err(|e| FleetStoreError::Io { |
| 690 | path: dir.display().to_string(), |
| 691 | message: e.to_string(), |
| 692 | })?; |
| 693 | Ok((root, dir)) |
| 694 | } |
| 695 | |
| 696 | /// A workspace's `.codewhale/fleets` is repository content: refuse it when it, |
| 697 | /// or `.codewhale`, is a link, so saving, selecting or deleting a Fleet cannot |
| 698 | /// reach outside the workspace. The personal directory is the user's own, and |
| 699 | /// so is a home workspace's relocated state directory: the root walk starts at |
| 700 | /// the real directory there, so the user's own junction is not refused. |
| 701 | fn reject_linked_workspace_dir(scope: FleetScope, workspace: &Path) -> Result<(), FleetStoreError> { |
| 702 | if scope != FleetScope::Workspace { |
| 703 | return Ok(()); |
| 704 | } |
| 705 | let (root, dir) = codewhale_util::files::workspace_state_path(workspace, Path::new(FLEET_DIR)); |
| 706 | codewhale_util::files::reject_linked_path(&root, &dir).map_err(|e| FleetStoreError::Io { |
| 707 | path: dir.display().to_string(), |
| 708 | message: e.to_string(), |
| 709 | }) |
| 710 | } |
| 711 | |
| 712 | /// List every named Fleet across both scopes, personal first. A file that is |
| 713 | /// not a v2 Fleet is listed as `legacy` with its parse error, so an old exact |
| 714 | /// fleet is visible — never silently absent — while the user decides whether |
| 715 | /// to migrate it. |
| 716 | pub fn list_fleets(workspace: &Path) -> Vec<FleetEntry> { |
| 717 | let mut entries = Vec::new(); |
| 718 | if let Ok(dir) = personal_fleets_dir() { |
| 719 | collect_entries(&dir, FleetScope::Personal, &mut entries); |
| 720 | } |
| 721 | if reject_linked_workspace_dir(FleetScope::Workspace, workspace).is_ok() { |
| 722 | collect_entries( |
| 723 | &workspace_fleets_dir(workspace), |
| 724 | FleetScope::Workspace, |
| 725 | &mut entries, |
| 726 | ); |
| 727 | } |
| 728 | entries.sort_by(|a, b| { |
| 729 | a.scope |
| 730 | .label() |
| 731 | .cmp(b.scope.label()) |
| 732 | .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) |
| 733 | }); |
| 734 | entries |
| 735 | } |
| 736 | |
| 737 | fn collect_entries(dir: &Path, scope: FleetScope, out: &mut Vec<FleetEntry>) { |
| 738 | let Ok(read) = fs::read_dir(dir) else { |
| 739 | return; |
| 740 | }; |
| 741 | let mut files: Vec<PathBuf> = read |
| 742 | .filter_map(|entry| entry.ok()) |
| 743 | .map(|entry| entry.path()) |
| 744 | .filter(|path| path.extension().is_some_and(|ext| ext == "toml")) |
| 745 | .collect(); |
| 746 | files.sort(); |
| 747 | for path in files { |
| 748 | let stem = path |
| 749 | .file_stem() |
| 750 | .map(|s| s.to_string_lossy().into_owned()) |
| 751 | .unwrap_or_default(); |
| 752 | let read = read_store_file(&path); |
| 753 | let text = read.as_deref().ok(); |
| 754 | let parse_error = match &read { |
| 755 | Ok(text) => FleetFile::parse(text).err().map(|e| e.to_string()), |
| 756 | Err(e) => Some(e.to_string()), |
| 757 | }; |
| 758 | let legacy = parse_error.as_deref().is_some_and(|err| { |
| 759 | err.contains("unknown schema") || err.contains("invalid fleet TOML") |
| 760 | }); |
| 761 | // The row shows the Fleet's own display name, never the file slug — |
| 762 | // a file saved as `Temp Fleet` must not appear as `temp-fleet`. |
| 763 | let name = text |
| 764 | .and_then(|text| toml::from_str::<toml::Value>(text).ok()) |
| 765 | .and_then(|value| { |
| 766 | value |
| 767 | .get("name") |
| 768 | .and_then(|n| n.as_str()) |
| 769 | .map(str::trim) |
| 770 | .filter(|n| !n.is_empty()) |
| 771 | .map(str::to_string) |
| 772 | }) |
| 773 | .unwrap_or(stem); |
| 774 | out.push(FleetEntry { |
| 775 | name, |
| 776 | scope, |
| 777 | path, |
| 778 | parse_error, |
| 779 | legacy, |
| 780 | }); |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | /// Every v2 Fleet file that answers to `name`, personal first. |
| 785 | /// |
| 786 | /// Only files that declare `schema = "fleet"` count. The personal `fleets/` |
| 787 | /// directory is shared with the workflow crate's legacy/exact files, and a |
| 788 | /// file in another schema is a different Fleet form, not a v2 Fleet that |
| 789 | /// failed to parse — the caller that owns that form reports on it. |
| 790 | pub fn v2_fleet_candidates(name: &str, workspace: &Path) -> Vec<(FleetScope, PathBuf)> { |
| 791 | let file_name = format!("{}.toml", slugify(name.trim())); |
| 792 | let mut found = Vec::new(); |
| 793 | let personal = personal_fleets_dir().ok().map(|dir| dir.join(&file_name)); |
| 794 | let workspace = Some(workspace_fleets_dir(workspace).join(&file_name)); |
| 795 | for (scope, path) in [ |
| 796 | (FleetScope::Personal, personal), |
| 797 | (FleetScope::Workspace, workspace), |
| 798 | ] { |
| 799 | if let Some(path) = path |
| 800 | && declares_v2_schema(&path) |
| 801 | { |
| 802 | found.push((scope, path)); |
| 803 | } |
| 804 | } |
| 805 | found |
| 806 | } |
| 807 | |
| 808 | /// The `schema` a Fleet file declares, normalized to lowercase. `None` when |
| 809 | /// the file cannot be read; `Some(None)` when it is readable but declares no |
| 810 | /// schema (or is not valid TOML). |
| 811 | pub fn read_declared_schema(path: &Path) -> Option<Option<String>> { |
| 812 | read_store_file(path) |
| 813 | .ok() |
| 814 | .map(|text| codewhale_workflow::fleet_exact::declared_schema_kind(&text)) |
| 815 | } |
| 816 | |
| 817 | /// Whether a file declares the v2 `schema = "fleet"`. Unreadable or |
| 818 | /// malformed TOML is not a v2 declaration. |
| 819 | pub fn declares_v2_schema(path: &Path) -> bool { |
| 820 | read_declared_schema(path).flatten().as_deref() == Some(FLEET_SCHEMA_KIND) |
| 821 | } |
| 822 | |
| 823 | /// Load a v2 Fleet by name. Ambiguity between the two scopes is an error that |
| 824 | /// names both origins — the caller resolves it by asking for a scope. A file |
| 825 | /// under the same name in another schema (legacy/exact) is not a v2 hit. |
| 826 | /// Used by `workflow(fleet:)` through `fleet::exact::load_fleet_document`. |
| 827 | pub fn load_fleet( |
| 828 | name: &str, |
| 829 | workspace: &Path, |
| 830 | ) -> Result<(FleetFile, FleetScope, PathBuf), FleetStoreError> { |
| 831 | let name = name.trim(); |
| 832 | if name.is_empty() { |
| 833 | return Err(FleetStoreError::NotFound("<empty name>".to_string())); |
| 834 | } |
| 835 | let mut found = v2_fleet_candidates(name, workspace); |
| 836 | if found.len() > 1 { |
| 837 | return Err(FleetStoreError::Ambiguous( |
| 838 | name.to_string(), |
| 839 | FleetScope::Personal.label().to_string(), |
| 840 | FleetScope::Workspace.label().to_string(), |
| 841 | )); |
| 842 | } |
| 843 | let Some((scope, path)) = found.pop() else { |
| 844 | return Err(FleetStoreError::NotFound(name.to_string())); |
| 845 | }; |
| 846 | let text = read_store_file(&path).map_err(|e| FleetStoreError::Io { |
| 847 | path: path.display().to_string(), |
| 848 | message: e.to_string(), |
| 849 | })?; |
| 850 | let fleet = FleetFile::parse(&text).map_err(|e| FleetStoreError::Parse { |
| 851 | path: path.display().to_string(), |
| 852 | message: e.to_string(), |
| 853 | })?; |
| 854 | Ok((fleet, scope, path)) |
| 855 | } |
| 856 | |
| 857 | /// Load a v2 Fleet by name in one explicit scope. Unlike [`load_fleet`], |
| 858 | /// this never resolves ambiguity — the caller already knows where the Fleet |
| 859 | /// lives (e.g. the row the user just picked). |
| 860 | pub fn load_fleet_in_scope( |
| 861 | name: &str, |
| 862 | scope: FleetScope, |
| 863 | workspace: &Path, |
| 864 | ) -> Result<(FleetFile, PathBuf), FleetStoreError> { |
| 865 | let dir = match scope { |
| 866 | FleetScope::Personal => personal_fleets_dir()?, |
| 867 | FleetScope::Workspace => workspace_fleets_dir(workspace), |
| 868 | }; |
| 869 | let path = dir.join(format!("{}.toml", slugify(name))); |
| 870 | let text = match read_store_file(&path) { |
| 871 | Ok(text) => text, |
| 872 | Err(e) |
| 873 | if matches!( |
| 874 | e.kind(), |
| 875 | std::io::ErrorKind::NotFound | std::io::ErrorKind::IsADirectory |
| 876 | ) => |
| 877 | { |
| 878 | return Err(FleetStoreError::NotFound(format!( |
| 879 | "{} ({})", |
| 880 | name, |
| 881 | scope.label() |
| 882 | ))); |
| 883 | } |
| 884 | Err(e) => { |
| 885 | return Err(FleetStoreError::Io { |
| 886 | path: path.display().to_string(), |
| 887 | message: e.to_string(), |
| 888 | }); |
| 889 | } |
| 890 | }; |
| 891 | let fleet = FleetFile::parse(&text).map_err(|e| FleetStoreError::Parse { |
| 892 | path: path.display().to_string(), |
| 893 | message: e.to_string(), |
| 894 | })?; |
| 895 | Ok((fleet, path)) |
| 896 | } |
| 897 | |
| 898 | /// Load a v2 Fleet from a specific path (used by the editor on the currently |
| 899 | /// open entry, so the saved scope is exact). API surface for the path-based |
| 900 | /// editor flows; currently exercised by tests. |
| 901 | pub fn load_fleet_at(path: &Path) -> Result<(FleetFile, FleetScope), FleetStoreError> { |
| 902 | let text = read_store_file(path).map_err(|e| FleetStoreError::Io { |
| 903 | path: path.display().to_string(), |
| 904 | message: e.to_string(), |
| 905 | })?; |
| 906 | let fleet = FleetFile::parse(&text).map_err(|e| FleetStoreError::Parse { |
| 907 | path: path.display().to_string(), |
| 908 | message: e.to_string(), |
| 909 | })?; |
| 910 | let scope = if personal_fleets_dir().is_ok_and(|dir| path.starts_with(dir)) { |
| 911 | FleetScope::Personal |
| 912 | } else { |
| 913 | FleetScope::Workspace |
| 914 | }; |
| 915 | Ok((fleet, scope)) |
| 916 | } |
| 917 | |
| 918 | /// Save a Fleet to a scope with an atomic write. Refuses to clobber a |
| 919 | /// different Fleet of the same slug (the name is the identity). |
| 920 | pub fn save_fleet( |
| 921 | fleet: &FleetFile, |
| 922 | scope: FleetScope, |
| 923 | workspace: &Path, |
| 924 | ) -> Result<PathBuf, FleetStoreError> { |
| 925 | fleet.validate()?; |
| 926 | let (root, dir) = ensure_fleets_dir(scope, workspace)?; |
| 927 | let path = dir.join(format!("{}.toml", fleet.file_slug())); |
| 928 | if path.is_file() { |
| 929 | // Only a readable v2 Fleet of this same name may be replaced. Any |
| 930 | // other non-empty file at this slug (a legacy roster or exact fleet, |
| 931 | // a Fleet from a newer build, a Fleet mid-edit that no longer parses) |
| 932 | // is left unchanged. |
| 933 | let text = read_store_file(&path).map_err(|e| FleetStoreError::Io { |
| 934 | path: path.display().to_string(), |
| 935 | message: e.to_string(), |
| 936 | })?; |
| 937 | if !text.trim().is_empty() { |
| 938 | match FleetFile::parse(&text) { |
| 939 | Ok(existing) if existing.name == fleet.name => {} |
| 940 | Ok(_) => { |
| 941 | return Err(FleetStoreError::NameTaken { |
| 942 | name: fleet.name.clone(), |
| 943 | path: path.display().to_string(), |
| 944 | }); |
| 945 | } |
| 946 | Err(parse_error) => { |
| 947 | let reason = if codewhale_workflow::fleet_exact::declared_schema_kind(&text) |
| 948 | .as_deref() |
| 949 | == Some(FLEET_SCHEMA_KIND) |
| 950 | { |
| 951 | format!("is a Fleet file this build cannot read ({parse_error})") |
| 952 | } else { |
| 953 | "holds another fleet file (a legacy roster or exact fleet)".to_string() |
| 954 | }; |
| 955 | return Err(FleetStoreError::Invalid(format!( |
| 956 | "{} {reason}; it was left unchanged. Fix or move that file, or save `{}` under another name", |
| 957 | path.display(), |
| 958 | fleet.name |
| 959 | ))); |
| 960 | } |
| 961 | } |
| 962 | } |
| 963 | } |
| 964 | let rendered = fleet.render_toml()?; |
| 965 | write_scoped(scope, &root, &path, rendered.as_bytes())?; |
| 966 | Ok(path) |
| 967 | } |
| 968 | |
| 969 | /// Delete a saved Fleet (UI confirms first). Returns the removed path. |
| 970 | pub fn delete_fleet( |
| 971 | name: &str, |
| 972 | scope: FleetScope, |
| 973 | workspace: &Path, |
| 974 | ) -> Result<PathBuf, FleetStoreError> { |
| 975 | let dir = match scope { |
| 976 | FleetScope::Personal => personal_fleets_dir()?, |
| 977 | FleetScope::Workspace => workspace_fleets_dir(workspace), |
| 978 | }; |
| 979 | reject_linked_workspace_dir(scope, workspace)?; |
| 980 | let path = dir.join(format!("{}.toml", slugify(name))); |
| 981 | if !path.is_file() { |
| 982 | return Err(FleetStoreError::NotFound(name.to_string())); |
| 983 | } |
| 984 | fs::remove_file(&path).map_err(|e| FleetStoreError::Io { |
| 985 | path: path.display().to_string(), |
| 986 | message: e.to_string(), |
| 987 | })?; |
| 988 | // A selection that pointed at the deleted Fleet must not linger: it would |
| 989 | // render as a phantom selection. The write is best-effort; a leftover |
| 990 | // selection is reported by the reader as missing, never as valid. |
| 991 | clear_selection_if_matching(scope, workspace, name); |
| 992 | Ok(path) |
| 993 | } |
| 994 | |
| 995 | /// The active selection: workspace selection wins, then the personal |
| 996 | /// user-global default. Each file is scope-explicit; a workspace selection |
| 997 | /// can never hide the personal Fleet — the personal default is only overridden |
| 998 | /// for this folder, visibly. |
| 999 | pub fn resolve_selected_fleet(workspace: &Path) -> Result<Option<SelectedFleet>, FleetStoreError> { |
| 1000 | let ws_dir = workspace_fleets_dir(workspace); |
| 1001 | if let Some(name) = read_selection_result(&ws_dir)? { |
| 1002 | // A workspace selection may name a personal Fleet (selected for this |
| 1003 | // folder only): resolve workspace first, then personal, and report |
| 1004 | // the scope the Fleet actually lives in. |
| 1005 | let ws_path = ws_dir.join(format!("{}.toml", slugify(&name))); |
| 1006 | if ws_path.is_file() { |
| 1007 | return Ok(Some(SelectedFleet { |
| 1008 | name, |
| 1009 | scope: FleetScope::Workspace, |
| 1010 | path: ws_path, |
| 1011 | })); |
| 1012 | } |
| 1013 | if let Ok(dir) = personal_fleets_dir() { |
| 1014 | let personal_path = dir.join(format!("{}.toml", slugify(&name))); |
| 1015 | if personal_path.is_file() { |
| 1016 | return Ok(Some(SelectedFleet { |
| 1017 | name, |
| 1018 | scope: FleetScope::Personal, |
| 1019 | path: personal_path, |
| 1020 | })); |
| 1021 | } |
| 1022 | } |
| 1023 | return Err(FleetStoreError::NotFound(format!( |
| 1024 | "selected fleet `{name}` (folder selection at {})", |
| 1025 | ws_dir.join(SELECTED_FILE).display() |
| 1026 | ))); |
| 1027 | } |
| 1028 | if let Ok(dir) = personal_fleets_dir() |
| 1029 | && let Some(name) = read_selection_result(&dir)? |
| 1030 | { |
| 1031 | let path = dir.join(format!("{}.toml", slugify(&name))); |
| 1032 | if path.is_file() { |
| 1033 | return Ok(Some(SelectedFleet { |
| 1034 | name, |
| 1035 | scope: FleetScope::Personal, |
| 1036 | path, |
| 1037 | })); |
| 1038 | } |
| 1039 | return Err(FleetStoreError::NotFound(format!( |
| 1040 | "selected fleet `{name}` (user selection at {})", |
| 1041 | dir.join(SELECTED_FILE).display() |
| 1042 | ))); |
| 1043 | } |
| 1044 | Ok(None) |
| 1045 | } |
| 1046 | |
| 1047 | /// Compatibility projection for display-only callers. Runtime callers must |
| 1048 | /// use [`resolve_selected_fleet`] so a broken explicit selection cannot be |
| 1049 | /// mistaken for "no selection" and silently fall back to legacy profiles. |
| 1050 | #[must_use] |
| 1051 | pub fn selected_fleet(workspace: &Path) -> Option<SelectedFleet> { |
| 1052 | resolve_selected_fleet(workspace).ok().flatten() |
| 1053 | } |
| 1054 | |
| 1055 | fn read_selection_result(dir: &Path) -> Result<Option<String>, FleetStoreError> { |
| 1056 | let path = dir.join(SELECTED_FILE); |
| 1057 | let text = match read_store_file(&path) { |
| 1058 | Ok(text) => text, |
| 1059 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 1060 | Err(error) => { |
| 1061 | return Err(FleetStoreError::Io { |
| 1062 | path: path.display().to_string(), |
| 1063 | message: error.to_string(), |
| 1064 | }); |
| 1065 | } |
| 1066 | }; |
| 1067 | let name = text.trim(); |
| 1068 | if name.is_empty() { |
| 1069 | Ok(None) |
| 1070 | } else { |
| 1071 | Ok(Some(name.to_string())) |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | fn read_selection(dir: &Path) -> Option<String> { |
| 1076 | read_selection_result(dir).ok().flatten() |
| 1077 | } |
| 1078 | |
| 1079 | /// Write the selection for a scope. Returns the exact file written. |
| 1080 | /// |
| 1081 | /// The selection file lives in the scope's `fleets/` directory, but the |
| 1082 | /// Fleet it names may live in either scope: a workspace selection may point |
| 1083 | /// at a personal Fleet (selecting it for this folder only), and a personal |
| 1084 | /// selection always points at a personal Fleet. The validation only refuses |
| 1085 | /// a name that exists NOWHERE — a phantom selection would be a lie. |
| 1086 | pub fn set_selected( |
| 1087 | name: &str, |
| 1088 | scope: FleetScope, |
| 1089 | workspace: &Path, |
| 1090 | ) -> Result<PathBuf, FleetStoreError> { |
| 1091 | let (root, dir) = ensure_fleets_dir(scope, workspace)?; |
| 1092 | let name = name.trim(); |
| 1093 | let exists_in_scope = |target: FleetScope| { |
| 1094 | let target_dir = match target { |
| 1095 | FleetScope::Personal => personal_fleets_dir().ok(), |
| 1096 | FleetScope::Workspace => Some(workspace_fleets_dir(workspace)), |
| 1097 | }; |
| 1098 | target_dir |
| 1099 | .map(|d| d.join(format!("{}.toml", slugify(name))).is_file()) |
| 1100 | .unwrap_or(false) |
| 1101 | }; |
| 1102 | let exists = exists_in_scope(scope) || exists_in_scope(FleetScope::Personal); |
| 1103 | if !exists { |
| 1104 | return Err(FleetStoreError::NotFound(format!( |
| 1105 | "{} ({})", |
| 1106 | name, |
| 1107 | scope.label() |
| 1108 | ))); |
| 1109 | } |
| 1110 | let selected = dir.join(SELECTED_FILE); |
| 1111 | write_scoped(scope, &root, &selected, name.as_bytes())?; |
| 1112 | Ok(selected) |
| 1113 | } |
| 1114 | |
| 1115 | fn clear_selection_if_matching(scope: FleetScope, workspace: &Path, name: &str) { |
| 1116 | let dir = match scope { |
| 1117 | FleetScope::Personal => personal_fleets_dir().ok(), |
| 1118 | FleetScope::Workspace => Some(workspace_fleets_dir(workspace)), |
| 1119 | }; |
| 1120 | let Some(dir) = dir else { return }; |
| 1121 | if reject_linked_workspace_dir(scope, workspace).is_err() { |
| 1122 | return; |
| 1123 | } |
| 1124 | let selected = dir.join(SELECTED_FILE); |
| 1125 | if read_selection(&dir).as_deref() == Some(name.trim()) { |
| 1126 | let _ = fs::remove_file(selected); |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | /// Write a Fleet or selection file for `scope`. A workspace file goes through |
| 1131 | /// the pinned no-follow writer (parents created without following a link, the |
| 1132 | /// final name replaced, never written through); the personal scope is the |
| 1133 | /// user's own directory and keeps the plain atomic write. |
| 1134 | /// |
| 1135 | /// `root` is the confinement root [`ensure_fleets_dir`] decided, not the raw |
| 1136 | /// workspace: for a home workspace it is the resolved state directory, so the |
| 1137 | /// writer opens the same path the link walk approved. |
| 1138 | fn write_scoped( |
| 1139 | scope: FleetScope, |
| 1140 | root: &Path, |
| 1141 | path: &Path, |
| 1142 | bytes: &[u8], |
| 1143 | ) -> Result<(), FleetStoreError> { |
| 1144 | if scope != FleetScope::Workspace { |
| 1145 | return atomic_write(path, bytes); |
| 1146 | } |
| 1147 | let io_error = |e: std::io::Error| FleetStoreError::Io { |
| 1148 | path: path.display().to_string(), |
| 1149 | message: e.to_string(), |
| 1150 | }; |
| 1151 | let relative = path.strip_prefix(root).map_err(|_| FleetStoreError::Io { |
| 1152 | path: path.display().to_string(), |
| 1153 | message: "a workspace Fleet file must stay within the workspace".to_string(), |
| 1154 | })?; |
| 1155 | codewhale_util::files::WorkspaceFile::open_shared(root, relative, true) |
| 1156 | .and_then(|file| file.replace(bytes)) |
| 1157 | .map_err(io_error) |
| 1158 | } |
| 1159 | |
| 1160 | /// Atomic write: temp file in the same directory, then rename. A failed write |
| 1161 | /// never leaves a half-written Fleet or selection. |
| 1162 | /// Each write gets its own temp file, so two concurrent savers can never |
| 1163 | /// interleave bytes into one shared temp and publish a mixed file. |
| 1164 | fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), FleetStoreError> { |
| 1165 | codewhale_util::utils::write_atomic_workspace(path, bytes).map_err(|e| FleetStoreError::Io { |
| 1166 | path: path.display().to_string(), |
| 1167 | message: e.to_string(), |
| 1168 | }) |
| 1169 | } |
| 1170 | |
| 1171 | /// One row of the migration receipt: how a legacy role profile maps into the |
| 1172 | /// new Fleet. |
| 1173 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1174 | pub struct MigrationRow { |
| 1175 | /// Role id, e.g. `scout`. |
| 1176 | pub id: String, |
| 1177 | /// The pin that will be saved (model + provider, or "inherit"). |
| 1178 | pub pin: Option<(String, String)>, |
| 1179 | /// The winning origin under the legacy precedence. |
| 1180 | pub winner: String, |
| 1181 | /// A lower-precedence copy with identical content — not a conflict. |
| 1182 | pub identical_shadow: Option<String>, |
| 1183 | /// A lower-precedence copy that differed and was NOT carried over. |
| 1184 | pub conflicting_shadow: Option<String>, |
| 1185 | } |
| 1186 | |
| 1187 | /// The result of migrating the legacy per-role roster into a v2 Fleet. |
| 1188 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1189 | pub struct MigrationReceipt { |
| 1190 | /// The Fleet that was (or would be) saved. |
| 1191 | pub fleet: FleetFile, |
| 1192 | /// Per-role mapping, including every conflict that was resolved. |
| 1193 | pub rows: Vec<MigrationRow>, |
| 1194 | /// Path the Fleet was saved to. |
| 1195 | pub saved_to: PathBuf, |
| 1196 | } |
| 1197 | |
| 1198 | /// Build (and optionally save) a v2 Fleet from the legacy per-role roster: |
| 1199 | /// built-ins + `[fleet.profiles]` + personal + workspace profile files. |
| 1200 | /// |
| 1201 | /// Nothing is discarded: every role becomes a member, every pin survives, and |
| 1202 | /// each lower-precedence copy that differed is named in the receipt. The |
| 1203 | /// legacy files themselves are left untouched — they become migration input, |
| 1204 | /// not live config, once a Fleet is selected. |
| 1205 | pub fn migrate_legacy_roster( |
| 1206 | fleet_config: &codewhale_config::FleetConfigToml, |
| 1207 | workspace: &Path, |
| 1208 | save: bool, |
| 1209 | save_scope: FleetScope, |
| 1210 | ) -> Result<MigrationReceipt, FleetStoreError> { |
| 1211 | migrate_legacy_roster_localized(fleet_config, workspace, save, save_scope, Locale::En) |
| 1212 | } |
| 1213 | |
| 1214 | pub fn migrate_legacy_roster_localized( |
| 1215 | fleet_config: &codewhale_config::FleetConfigToml, |
| 1216 | workspace: &Path, |
| 1217 | save: bool, |
| 1218 | save_scope: FleetScope, |
| 1219 | locale: Locale, |
| 1220 | ) -> Result<MigrationReceipt, FleetStoreError> { |
| 1221 | let roster = FleetRoster::load(fleet_config, workspace); |
| 1222 | let mut fleet = FleetFile::new( |
| 1223 | "Default".to_string(), |
| 1224 | Some("Migrated from the legacy per-role profile configuration.".to_string()), |
| 1225 | )?; |
| 1226 | let mut rows = Vec::new(); |
| 1227 | for member in roster.members() { |
| 1228 | let profile = &member.profile; |
| 1229 | let (model, provider) = match (&profile.model, &profile.provider) { |
| 1230 | (Some(model), Some(provider)) => (Some(model.clone()), Some(provider.clone())), |
| 1231 | _ => (None, None), |
| 1232 | }; |
| 1233 | // Legacy profiles carry no capability requirements; a migration |
| 1234 | // never invents one. Requirements start empty in the v2 Fleet. |
| 1235 | let requires: Vec<String> = Vec::new(); |
| 1236 | let row = MigrationRow { |
| 1237 | id: member.id.clone(), |
| 1238 | pin: model |
| 1239 | .as_ref() |
| 1240 | .map(|m| (m.clone(), provider.clone().unwrap_or_default())), |
| 1241 | winner: member.origin.to_string(), |
| 1242 | identical_shadow: None, |
| 1243 | conflicting_shadow: None, |
| 1244 | }; |
| 1245 | // Record shadowed copies (the roster already resolved them; here we |
| 1246 | // name them so the conflict is visible before anyone accepts it). |
| 1247 | let shadows: Vec<String> = roster |
| 1248 | .shadowed() |
| 1249 | .iter() |
| 1250 | .filter(|s| s.id == member.id) |
| 1251 | .map(|s| { |
| 1252 | tr(locale, MessageId::FleetMigrationShadow) |
| 1253 | .replace("{ignored}", &s.shadowed_origin.to_string()) |
| 1254 | .replace("{winner}", &s.winner_origin.to_string()) |
| 1255 | .replace("{path}", &s.shadowed_source.display().to_string()) |
| 1256 | }) |
| 1257 | .collect(); |
| 1258 | let mut row = row; |
| 1259 | if let Some(first) = shadows.first() { |
| 1260 | if shadows.len() == 1 && first.contains("built-in") { |
| 1261 | row.identical_shadow = Some(first.clone()); |
| 1262 | } else { |
| 1263 | row.conflicting_shadow = Some(shadows.join("; ")); |
| 1264 | } |
| 1265 | } |
| 1266 | rows.push(row); |
| 1267 | fleet.members.push(FleetMember { |
| 1268 | id: member.id.clone(), |
| 1269 | display_name: member.display_name.clone(), |
| 1270 | shortlist: false, |
| 1271 | role: profile.role.name.clone(), |
| 1272 | model, |
| 1273 | provider, |
| 1274 | reasoning: profile.reasoning_effort.clone(), |
| 1275 | instructions: profile.role.instructions.clone(), |
| 1276 | requires, |
| 1277 | }); |
| 1278 | } |
| 1279 | fleet.validate()?; |
| 1280 | let saved_to = if save { |
| 1281 | save_fleet(&fleet, save_scope, workspace)? |
| 1282 | } else { |
| 1283 | match save_scope { |
| 1284 | FleetScope::Personal => { |
| 1285 | personal_fleets_dir()?.join(format!("{}.toml", fleet.file_slug())) |
| 1286 | } |
| 1287 | FleetScope::Workspace => { |
| 1288 | workspace_fleets_dir(workspace).join(format!("{}.toml", fleet.file_slug())) |
| 1289 | } |
| 1290 | } |
| 1291 | }; |
| 1292 | Ok(MigrationReceipt { |
| 1293 | fleet, |
| 1294 | rows, |
| 1295 | saved_to, |
| 1296 | }) |
| 1297 | } |
| 1298 | |
| 1299 | #[cfg(test)] |
| 1300 | mod tests { |
| 1301 | use super::*; |
| 1302 | use std::sync::OnceLock; |
| 1303 | |
| 1304 | /// A sealed CODEWHALE_HOME for personal-scope tests, created once per |
| 1305 | /// process. Tests must still hold `lock_test_env` before touching it. |
| 1306 | fn sealed_home() -> &'static Path { |
| 1307 | static HOME: OnceLock<PathBuf> = OnceLock::new(); |
| 1308 | HOME.get_or_init(|| { |
| 1309 | let dir = crate::test_support::test_scratch_dir("codewhale-fleet-sealed-home"); |
| 1310 | std::fs::create_dir_all(dir.join("fleets")).expect("fleets dir"); |
| 1311 | dir |
| 1312 | }) |
| 1313 | } |
| 1314 | |
| 1315 | /// Point CODEWHALE_HOME at a sealed temp dir. Caller must hold |
| 1316 | /// `lock_test_env`. |
| 1317 | fn set_sealed_home() -> crate::test_support::EnvVarGuard { |
| 1318 | crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", sealed_home()) |
| 1319 | } |
| 1320 | |
| 1321 | /// A workspace's `.codewhale/fleets` is repository content. Saving, |
| 1322 | /// selecting and deleting refuse it when it is a link, and a link at the |
| 1323 | /// Fleet's own file name is replaced rather than written through. |
| 1324 | #[cfg(unix)] |
| 1325 | #[test] |
| 1326 | fn workspace_fleet_writes_never_follow_links_out_of_the_workspace() { |
| 1327 | use std::os::unix::fs::symlink; |
| 1328 | let _lock = crate::test_support::lock_test_env(); |
| 1329 | let _home = set_sealed_home(); |
| 1330 | let outside = tempfile::tempdir().unwrap(); |
| 1331 | |
| 1332 | // `.codewhale/fleets` linked: save, select and delete are all refused. |
| 1333 | let linked = tempfile::tempdir().unwrap(); |
| 1334 | std::fs::create_dir_all(linked.path().join(".codewhale")).unwrap(); |
| 1335 | symlink( |
| 1336 | outside.path(), |
| 1337 | linked.path().join(".codewhale").join(FLEET_DIR), |
| 1338 | ) |
| 1339 | .unwrap(); |
| 1340 | let fleet = sample_fleet(); |
| 1341 | assert!(save_fleet(&fleet, FleetScope::Workspace, linked.path()).is_err()); |
| 1342 | assert!(set_selected("DeepSeek Flash", FleetScope::Workspace, linked.path()).is_err()); |
| 1343 | assert!(delete_fleet("DeepSeek Flash", FleetScope::Workspace, linked.path()).is_err()); |
| 1344 | assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0); |
| 1345 | |
| 1346 | // A link at the Fleet's file name is replaced, never written through. |
| 1347 | let plain = tempfile::tempdir().unwrap(); |
| 1348 | let dir = plain.path().join(".codewhale").join(FLEET_DIR); |
| 1349 | std::fs::create_dir_all(&dir).unwrap(); |
| 1350 | let victim = outside.path().join("victim.toml"); |
| 1351 | std::fs::write(&victim, "keep me").unwrap(); |
| 1352 | symlink(&victim, dir.join(format!("{}.toml", fleet.file_slug()))).unwrap(); |
| 1353 | let saved = save_fleet(&fleet, FleetScope::Workspace, plain.path()); |
| 1354 | assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me"); |
| 1355 | if let Ok(path) = saved { |
| 1356 | assert!( |
| 1357 | !std::fs::symlink_metadata(&path) |
| 1358 | .unwrap() |
| 1359 | .file_type() |
| 1360 | .is_symlink() |
| 1361 | ); |
| 1362 | } |
| 1363 | } |
| 1364 | |
| 1365 | #[test] |
| 1366 | fn declared_schema_separates_unreadable_from_undeclared() { |
| 1367 | let dir = tempfile::tempdir().unwrap(); |
| 1368 | let v2 = dir.path().join("v2.toml"); |
| 1369 | std::fs::write(&v2, "name = \"a\"\nschema = \" Fleet \"\n").unwrap(); |
| 1370 | let legacy = dir.path().join("legacy.toml"); |
| 1371 | std::fs::write(&legacy, "name = \"b\"\n[roles]\nscout = \"scout\"\n").unwrap(); |
| 1372 | let malformed = dir.path().join("bad.toml"); |
| 1373 | std::fs::write(&malformed, "schema = [").unwrap(); |
| 1374 | let missing = dir.path().join("missing.toml"); |
| 1375 | |
| 1376 | assert!( |
| 1377 | declares_v2_schema(&v2), |
| 1378 | "case and whitespace are normalized" |
| 1379 | ); |
| 1380 | assert_eq!(read_declared_schema(&legacy), Some(None)); |
| 1381 | assert_eq!(read_declared_schema(&malformed), Some(None)); |
| 1382 | assert_eq!(read_declared_schema(&missing), None); |
| 1383 | assert!(!declares_v2_schema(&legacy)); |
| 1384 | assert!(!declares_v2_schema(&malformed)); |
| 1385 | assert!(!declares_v2_schema(&missing)); |
| 1386 | } |
| 1387 | |
| 1388 | #[test] |
| 1389 | fn unsealed_personal_routes_ignore_ambient_home() { |
| 1390 | const PROBE: &str = "CODEWHALE_TEST_AMBIENT_FLEET_PROBE"; |
| 1391 | if std::env::var_os(PROBE).is_some() { |
| 1392 | let workspace = tempfile::tempdir().unwrap(); |
| 1393 | for hold_env_lock in [false, true] { |
| 1394 | let _lock = hold_env_lock.then(crate::test_support::lock_test_env); |
| 1395 | let root = crate::test_support::unsealed_test_state_root(); |
| 1396 | assert_eq!(personal_fleets_dir().unwrap(), root.join(FLEET_DIR)); |
| 1397 | assert_eq!( |
| 1398 | crate::fleet::profile::personal_agent_profile_dir().unwrap(), |
| 1399 | root.join("agents") |
| 1400 | ); |
| 1401 | assert!(resolve_selected_fleet(workspace.path()).unwrap().is_none()); |
| 1402 | assert!(list_fleets(workspace.path()).is_empty()); |
| 1403 | let roster = crate::fleet::identity::load_effective_roster( |
| 1404 | &Default::default(), |
| 1405 | workspace.path(), |
| 1406 | None, |
| 1407 | ); |
| 1408 | assert!(roster.load_error().is_none()); |
| 1409 | assert!(roster.members().iter().all(|member| { |
| 1410 | member.origin == crate::fleet::roster::ProfileOrigin::BuiltIn |
| 1411 | })); |
| 1412 | } |
| 1413 | return; |
| 1414 | } |
| 1415 | |
| 1416 | // A fresh process inherits populated operator state, without earning |
| 1417 | // the explicit EnvVarGuard seal used by deliberate path fixtures. |
| 1418 | let ambient = tempfile::tempdir().unwrap(); |
| 1419 | let state = ambient.path().join(".codewhale"); |
| 1420 | let fleets = state.join(FLEET_DIR); |
| 1421 | std::fs::create_dir_all(&fleets).unwrap(); |
| 1422 | let fleet = sample_fleet(); |
| 1423 | let fleet_path = fleets.join(format!("{}.toml", fleet.file_slug())); |
| 1424 | let contents = fleet.render_toml().unwrap(); |
| 1425 | std::fs::write(&fleet_path, &contents).unwrap(); |
| 1426 | std::fs::write(fleets.join(SELECTED_FILE), &fleet.name).unwrap(); |
| 1427 | for explicit_override in [false, true] { |
| 1428 | let mut command = std::process::Command::new(std::env::current_exe().unwrap()); |
| 1429 | command |
| 1430 | .args([ |
| 1431 | "--exact", |
| 1432 | "fleet::store::tests::unsealed_personal_routes_ignore_ambient_home", |
| 1433 | "--test-threads=1", |
| 1434 | ]) |
| 1435 | .env(PROBE, "1") |
| 1436 | .env("HOME", ambient.path()) |
| 1437 | .env("USERPROFILE", ambient.path()) |
| 1438 | .env_remove("CODEWHALE_HOME") |
| 1439 | .env_remove("CODEWHALE_CONFIG_PATH") |
| 1440 | .env_remove("DEEPSEEK_CONFIG_PATH"); |
| 1441 | if explicit_override { |
| 1442 | command.env("CODEWHALE_HOME", &state); |
| 1443 | } |
| 1444 | let output = command.output().unwrap(); |
| 1445 | assert!( |
| 1446 | output.status.success(), |
| 1447 | "ambient route probe failed (override={explicit_override})\n{}\n{}", |
| 1448 | String::from_utf8_lossy(&output.stdout), |
| 1449 | String::from_utf8_lossy(&output.stderr) |
| 1450 | ); |
| 1451 | } |
| 1452 | assert_eq!(std::fs::read_to_string(fleet_path).unwrap(), contents); |
| 1453 | assert_eq!( |
| 1454 | std::fs::read_to_string(fleets.join(SELECTED_FILE)).unwrap(), |
| 1455 | fleet.name |
| 1456 | ); |
| 1457 | } |
| 1458 | |
| 1459 | fn sample_fleet() -> FleetFile { |
| 1460 | FleetFile::new("DeepSeek Flash".to_string(), None) |
| 1461 | .expect("valid fleet") |
| 1462 | .with_operator(FleetOperator { |
| 1463 | provider: "deepseek".to_string(), |
| 1464 | model: "deepseek-v4-flash".to_string(), |
| 1465 | reasoning: Some("low".to_string()), |
| 1466 | }) |
| 1467 | .with_member(FleetMember { |
| 1468 | id: "scout".to_string(), |
| 1469 | display_name: Some("Flash Scout".to_string()), |
| 1470 | shortlist: false, |
| 1471 | role: "scout".to_string(), |
| 1472 | provider: None, |
| 1473 | model: None, |
| 1474 | reasoning: None, |
| 1475 | instructions: None, |
| 1476 | requires: Vec::new(), |
| 1477 | }) |
| 1478 | .with_member(FleetMember { |
| 1479 | id: "builder".to_string(), |
| 1480 | display_name: None, |
| 1481 | shortlist: false, |
| 1482 | role: "builder".to_string(), |
| 1483 | provider: Some("deepseek".to_string()), |
| 1484 | model: Some("deepseek-v4-pro".to_string()), |
| 1485 | reasoning: Some("high".to_string()), |
| 1486 | instructions: Some("Implement exactly the task slice.".to_string()), |
| 1487 | requires: vec!["vision".to_string()], |
| 1488 | }) |
| 1489 | } |
| 1490 | |
| 1491 | trait FleetBuilder { |
| 1492 | fn with_operator(self, operator: FleetOperator) -> Self; |
| 1493 | fn with_member(self, member: FleetMember) -> Self; |
| 1494 | } |
| 1495 | |
| 1496 | impl FleetBuilder for FleetFile { |
| 1497 | fn with_operator(mut self, operator: FleetOperator) -> Self { |
| 1498 | self.operator = Some(operator); |
| 1499 | self |
| 1500 | } |
| 1501 | fn with_member(mut self, member: FleetMember) -> Self { |
| 1502 | self.members.push(member); |
| 1503 | self |
| 1504 | } |
| 1505 | } |
| 1506 | |
| 1507 | #[test] |
| 1508 | fn validation_rejects_bad_documents_with_specific_errors() { |
| 1509 | let _lock = crate::test_support::lock_test_env(); |
| 1510 | |
| 1511 | // Empty name. |
| 1512 | let err = FleetFile::new(" ".to_string(), None).unwrap_err(); |
| 1513 | assert!(err.to_string().contains("name must not be empty"), "{err}"); |
| 1514 | |
| 1515 | // Duplicate member ids. |
| 1516 | let mut fleet = sample_fleet(); |
| 1517 | fleet.members.push(fleet.members[0].clone()); |
| 1518 | let err = fleet.validate().unwrap_err(); |
| 1519 | assert!( |
| 1520 | err.to_string().contains("duplicate member id `scout`"), |
| 1521 | "{err}" |
| 1522 | ); |
| 1523 | |
| 1524 | // Dispatch identity is case-insensitive, so validation must reject a |
| 1525 | // pair lookup could not distinguish. |
| 1526 | let mut fleet = sample_fleet(); |
| 1527 | let mut duplicate = fleet.members[0].clone(); |
| 1528 | duplicate.id = "SCOUT".to_string(); |
| 1529 | fleet.members.push(duplicate); |
| 1530 | let err = fleet.validate().unwrap_err(); |
| 1531 | assert!(err.to_string().contains("case-insensitively"), "{err}"); |
| 1532 | |
| 1533 | // Human-facing names stay bounded and single-line before they can |
| 1534 | // enter selectors, roster discovery, or terminal rendering. |
| 1535 | let mut fleet = sample_fleet(); |
| 1536 | fleet.members[0].display_name = Some("x".repeat(MAX_MEMBER_DISPLAY_NAME_CHARS + 1)); |
| 1537 | let err = fleet.validate().unwrap_err(); |
| 1538 | assert!(err.to_string().contains("no longer than 80"), "{err}"); |
| 1539 | let mut fleet = sample_fleet(); |
| 1540 | fleet.members[0].display_name = Some("Flash\nScout".to_string()); |
| 1541 | let err = fleet.validate().unwrap_err(); |
| 1542 | assert!( |
| 1543 | err.to_string().contains("one trimmed printable line"), |
| 1544 | "{err}" |
| 1545 | ); |
| 1546 | |
| 1547 | // Identity and route values are bounded and control-free too; only |
| 1548 | // the instruction overlay may span lines. |
| 1549 | let mut fleet = sample_fleet(); |
| 1550 | fleet.members[0].id = "scout\u{1b}[2J".to_string(); |
| 1551 | let err = fleet.validate().unwrap_err(); |
| 1552 | assert!( |
| 1553 | err.to_string().contains("member id must be printable"), |
| 1554 | "{err}" |
| 1555 | ); |
| 1556 | let mut fleet = sample_fleet(); |
| 1557 | fleet.members[0].id = "x".repeat(MAX_MEMBER_ID_CHARS + 1); |
| 1558 | assert!(fleet.validate().is_err()); |
| 1559 | let mut fleet = sample_fleet(); |
| 1560 | fleet.members[0].id = format!("{} ", fleet.members[0].id); |
| 1561 | assert!( |
| 1562 | fleet.validate().is_err(), |
| 1563 | "an untrimmed id is not its trimmed twin" |
| 1564 | ); |
| 1565 | let mut fleet = sample_fleet(); |
| 1566 | fleet.name = "Team\u{7}".to_string(); |
| 1567 | assert!(fleet.validate().is_err()); |
| 1568 | // F01-04: the rest of the document's free text is bounded too. |
| 1569 | let mut fleet = sample_fleet(); |
| 1570 | fleet.name = "Team\n".to_string(); |
| 1571 | assert!( |
| 1572 | fleet.validate().is_err(), |
| 1573 | "a trailing control is still a control" |
| 1574 | ); |
| 1575 | let mut fleet = sample_fleet(); |
| 1576 | fleet.description = Some("about\u{7}".to_string()); |
| 1577 | assert!(fleet.validate().is_err()); |
| 1578 | fleet.description = Some("line one\nline two".to_string()); |
| 1579 | fleet.validate().expect("a description may span lines"); |
| 1580 | fleet.description = Some("x".repeat(MAX_FLEET_DESCRIPTION_CHARS + 1)); |
| 1581 | assert!(fleet.validate().is_err()); |
| 1582 | let mut fleet = sample_fleet(); |
| 1583 | fleet.operator = Some(FleetOperator { |
| 1584 | provider: "deepseek".to_string(), |
| 1585 | model: "deepseek-v4\u{1b}[2J".to_string(), |
| 1586 | reasoning: None, |
| 1587 | }); |
| 1588 | let err = fleet.validate().unwrap_err(); |
| 1589 | assert!(err.to_string().contains("operator model"), "{err}"); |
| 1590 | let mut fleet = sample_fleet(); |
| 1591 | fleet.members[0].instructions = Some("line one\nline two\ttabbed".to_string()); |
| 1592 | fleet.validate().expect("instructions may span lines"); |
| 1593 | fleet.members[0].instructions = Some("x".repeat(MAX_MEMBER_INSTRUCTIONS_CHARS + 1)); |
| 1594 | assert!(fleet.validate().is_err()); |
| 1595 | |
| 1596 | // Lone provider / lone model: never silently reinterpreted. |
| 1597 | let mut fleet = sample_fleet(); |
| 1598 | fleet.members[0].provider = Some("deepseek".to_string()); |
| 1599 | let err = fleet.validate().unwrap_err(); |
| 1600 | assert!( |
| 1601 | err.to_string().contains("must pin both provider and model"), |
| 1602 | "{err}" |
| 1603 | ); |
| 1604 | let mut fleet = sample_fleet(); |
| 1605 | fleet.members[0].model = Some("deepseek-v4-pro".to_string()); |
| 1606 | let err = fleet.validate().unwrap_err(); |
| 1607 | assert!( |
| 1608 | err.to_string().contains("must pin both provider and model"), |
| 1609 | "{err}" |
| 1610 | ); |
| 1611 | |
| 1612 | // Unknown capability requirement. |
| 1613 | let mut fleet = sample_fleet(); |
| 1614 | fleet.members[0].requires = vec!["telepathy".to_string()]; |
| 1615 | let err = fleet.validate().unwrap_err(); |
| 1616 | assert!( |
| 1617 | err.to_string().contains("unknown capability `telepathy`"), |
| 1618 | "{err}" |
| 1619 | ); |
| 1620 | assert!(err.to_string().contains("vision"), "{err}"); |
| 1621 | } |
| 1622 | |
| 1623 | #[test] |
| 1624 | fn member_pin_matching_the_operator_route_reads_as_inheritance() { |
| 1625 | // #6037: a role member pinned to the fleet's own operator route |
| 1626 | // resolves to that route either way — the pin only stops it |
| 1627 | // following when the operator moves. Parse drops the redundant pin; |
| 1628 | // a different-route pin and a shortlist row keep theirs. |
| 1629 | let fleet = FleetFile::parse( |
| 1630 | r#"schema = "fleet" |
| 1631 | schema_revision = 2 |
| 1632 | name = "Inherit" |
| 1633 | |
| 1634 | [operator] |
| 1635 | provider = "openrouter" |
| 1636 | model = "z-ai/glm-5.3" |
| 1637 | |
| 1638 | [[members]] |
| 1639 | id = "planner" |
| 1640 | role = "planner" |
| 1641 | provider = "openrouter" |
| 1642 | model = "z-ai/glm-5.3" |
| 1643 | |
| 1644 | [[members]] |
| 1645 | id = "builder" |
| 1646 | role = "builder" |
| 1647 | provider = "openrouter" |
| 1648 | model = "z-ai/glm-5.3-pro" |
| 1649 | |
| 1650 | [[members]] |
| 1651 | id = "choice" |
| 1652 | shortlist = true |
| 1653 | provider = "openrouter" |
| 1654 | model = "z-ai/glm-5.3" |
| 1655 | "#, |
| 1656 | ) |
| 1657 | .expect("parse"); |
| 1658 | let planner = fleet.member("planner").expect("planner member"); |
| 1659 | assert_eq!(planner.provider, None); |
| 1660 | assert_eq!(planner.model, None); |
| 1661 | let builder = fleet.member("builder").expect("builder member"); |
| 1662 | assert_eq!(builder.provider.as_deref(), Some("openrouter")); |
| 1663 | assert_eq!(builder.model.as_deref(), Some("z-ai/glm-5.3-pro")); |
| 1664 | let choice = fleet |
| 1665 | .members |
| 1666 | .iter() |
| 1667 | .find(|member| member.shortlist) |
| 1668 | .expect("shortlist row"); |
| 1669 | assert_eq!(choice.provider.as_deref(), Some("openrouter")); |
| 1670 | assert_eq!(choice.model.as_deref(), Some("z-ai/glm-5.3")); |
| 1671 | // The listing still attributes the inherited role to the route it runs. |
| 1672 | let models = crate::fleet::members::models_of(&fleet); |
| 1673 | assert_eq!(models[0].model, "z-ai/glm-5.3"); |
| 1674 | assert_eq!(models[0].roles, ["operator", "planner"]); |
| 1675 | assert_eq!(models[1].roles, ["builder"]); |
| 1676 | // The cleaned document round-trips: inherit stays inherit. |
| 1677 | assert_eq!( |
| 1678 | FleetFile::parse(&fleet.render_toml().expect("render")).expect("reparse"), |
| 1679 | fleet |
| 1680 | ); |
| 1681 | } |
| 1682 | |
| 1683 | #[test] |
| 1684 | fn render_parse_round_trip_preserves_every_field() { |
| 1685 | let fleet = sample_fleet(); |
| 1686 | let text = fleet.render_toml().expect("render"); |
| 1687 | let parsed = FleetFile::parse(&text).expect("parse"); |
| 1688 | assert_eq!(parsed, fleet); |
| 1689 | assert!(text.contains("schema = \"fleet\"")); |
| 1690 | assert!(text.contains("schema_revision = 2")); |
| 1691 | assert!(text.contains("display_name = \"Flash Scout\"")); |
| 1692 | assert!(text.contains("deepseek-v4-flash")); |
| 1693 | assert!( |
| 1694 | !text.contains("shortlist"), |
| 1695 | "legacy members do not gain a marker" |
| 1696 | ); |
| 1697 | } |
| 1698 | |
| 1699 | #[test] |
| 1700 | fn marked_shortlist_round_trips_without_becoming_a_role_or_legacy_bare_pin() { |
| 1701 | let fleet = FleetFile::parse( |
| 1702 | r#"schema = "fleet" |
| 1703 | schema_revision = 2 |
| 1704 | name = "Shortlist" |
| 1705 | |
| 1706 | [[members]] |
| 1707 | id = "scout" |
| 1708 | shortlist = true |
| 1709 | provider = "fixture-provider" |
| 1710 | model = "scout" |
| 1711 | "#, |
| 1712 | ) |
| 1713 | .expect("explicitly marked model survives legacy bare-pin migration"); |
| 1714 | assert_eq!(fleet.members.len(), 1); |
| 1715 | let choice = &fleet.members[0]; |
| 1716 | assert!(choice.shortlist); |
| 1717 | assert_eq!(choice.provider.as_deref(), Some("fixture-provider")); |
| 1718 | assert_eq!(choice.model.as_deref(), Some("scout")); |
| 1719 | assert!(choice.role_label().is_empty()); |
| 1720 | assert!( |
| 1721 | !fleet.has_scout(), |
| 1722 | "a model named scout cannot select the scout role" |
| 1723 | ); |
| 1724 | assert!(fleet.member("scout").is_none()); |
| 1725 | let models = crate::fleet::members::models_of(&fleet); |
| 1726 | assert_eq!(models.len(), 1); |
| 1727 | assert!(models[0].roles.is_empty()); |
| 1728 | let text = fleet.render_toml().expect("serialize marker"); |
| 1729 | assert!(text.contains("shortlist = true")); |
| 1730 | assert!(!text.contains("role =")); |
| 1731 | assert_eq!(FleetFile::parse(&text).expect("reload marker"), fleet); |
| 1732 | } |
| 1733 | |
| 1734 | #[test] |
| 1735 | fn shortlist_marker_rejects_roles_inheritance_and_incomplete_routes() { |
| 1736 | for (role, provider, model) in [ |
| 1737 | ("scout", Some("deepseek"), Some("deepseek-v4-flash")), |
| 1738 | ("", None, None), |
| 1739 | ("", None, Some("deepseek-v4-flash")), |
| 1740 | ("", Some("deepseek"), None), |
| 1741 | ("", Some(" "), Some("deepseek-v4-flash")), |
| 1742 | ("", Some("deepseek"), Some(" ")), |
| 1743 | ] { |
| 1744 | let member: FleetMember = serde_json::from_value(serde_json::json!({ |
| 1745 | "id": "choice", "shortlist": true, "role": role, |
| 1746 | "provider": provider, "model": model, |
| 1747 | })) |
| 1748 | .expect("typed fixture"); |
| 1749 | let mut fleet = FleetFile::new("Malformed shortlist".into(), None).unwrap(); |
| 1750 | fleet.members.push(member); |
| 1751 | assert!( |
| 1752 | fleet.validate().is_err(), |
| 1753 | "accepted invalid marker: {fleet:?}" |
| 1754 | ); |
| 1755 | assert!( |
| 1756 | fleet.render_toml().is_err(), |
| 1757 | "render accepted invalid marker" |
| 1758 | ); |
| 1759 | let text = toml::to_string(&fleet).expect("unchecked fixture serialization"); |
| 1760 | assert!( |
| 1761 | FleetFile::parse(&text).is_err(), |
| 1762 | "parse accepted invalid marker: {text}" |
| 1763 | ); |
| 1764 | } |
| 1765 | |
| 1766 | for metadata in [ |
| 1767 | serde_json::json!({"reasoning": "high"}), |
| 1768 | serde_json::json!({"instructions": "Review the changes."}), |
| 1769 | serde_json::json!({"requires": ["vision"]}), |
| 1770 | ] { |
| 1771 | let mut row = serde_json::json!({ |
| 1772 | "id": "choice", "shortlist": true, |
| 1773 | "provider": "deepseek", "model": "deepseek-v4-flash", |
| 1774 | }); |
| 1775 | row.as_object_mut() |
| 1776 | .unwrap() |
| 1777 | .extend(metadata.as_object().unwrap().clone()); |
| 1778 | let mut fleet = FleetFile::new("Malformed shortlist".into(), None).unwrap(); |
| 1779 | fleet.members.push(serde_json::from_value(row).unwrap()); |
| 1780 | let text = toml::to_string(&fleet).expect("unchecked metadata fixture"); |
| 1781 | for error in [ |
| 1782 | fleet.validate().unwrap_err(), |
| 1783 | fleet.render_toml().unwrap_err(), |
| 1784 | FleetFile::parse(&text).unwrap_err(), |
| 1785 | ] { |
| 1786 | assert!( |
| 1787 | error.to_string().contains("cannot set role reasoning"), |
| 1788 | "metadata was not rejected as role-only: {error}" |
| 1789 | ); |
| 1790 | } |
| 1791 | } |
| 1792 | } |
| 1793 | |
| 1794 | #[test] |
| 1795 | fn member_name_alias_is_accepted_and_old_files_remain_valid() { |
| 1796 | let aliased = FleetFile::parse( |
| 1797 | r#"schema = "fleet" |
| 1798 | schema_revision = 2 |
| 1799 | name = "Named" |
| 1800 | |
| 1801 | [[members]] |
| 1802 | id = "scout" |
| 1803 | name = "Scout One" |
| 1804 | role = "scout" |
| 1805 | "#, |
| 1806 | ) |
| 1807 | .expect("name alias"); |
| 1808 | assert_eq!( |
| 1809 | aliased.members[0].display_name.as_deref(), |
| 1810 | Some("Scout One") |
| 1811 | ); |
| 1812 | let canonical = aliased.render_toml().expect("canonical render"); |
| 1813 | assert!(canonical.contains("display_name = \"Scout One\"")); |
| 1814 | |
| 1815 | let without_name = FleetFile::parse( |
| 1816 | r#"schema = "fleet" |
| 1817 | schema_revision = 2 |
| 1818 | name = "Existing" |
| 1819 | |
| 1820 | [[members]] |
| 1821 | id = "scout" |
| 1822 | role = "scout" |
| 1823 | "#, |
| 1824 | ) |
| 1825 | .expect("pre-display-name revision-2 file"); |
| 1826 | assert!(without_name.members[0].display_name.is_none()); |
| 1827 | } |
| 1828 | |
| 1829 | #[test] |
| 1830 | fn save_load_round_trips_in_workspace_scope() { |
| 1831 | let _lock = crate::test_support::lock_test_env(); |
| 1832 | let ws = tempfile::TempDir::new().unwrap(); |
| 1833 | let fleet = sample_fleet(); |
| 1834 | let path = save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("save"); |
| 1835 | assert!( |
| 1836 | path.ends_with(".codewhale/fleets/deepseek-flash.toml"), |
| 1837 | "{path:?}" |
| 1838 | ); |
| 1839 | |
| 1840 | let (loaded, scope, path) = load_fleet("DeepSeek Flash", ws.path()).expect("load"); |
| 1841 | assert_eq!(loaded, fleet); |
| 1842 | assert_eq!(scope, FleetScope::Workspace); |
| 1843 | assert_eq!(path, load_fleet("DeepSeek Flash", ws.path()).unwrap().2); |
| 1844 | |
| 1845 | // A same-name Fleet in the personal scope makes the bare name |
| 1846 | // ambiguous — the reader names both origins instead of shadowing. |
| 1847 | let _home = set_sealed_home(); |
| 1848 | save_fleet(&fleet, FleetScope::Personal, ws.path()).expect("save personal"); |
| 1849 | let err = load_fleet("DeepSeek Flash", ws.path()).unwrap_err(); |
| 1850 | let msg = err.to_string(); |
| 1851 | assert!(msg.contains("defined in both"), "{msg}"); |
| 1852 | assert!(msg.contains("user") && msg.contains("folder"), "{msg}"); |
| 1853 | } |
| 1854 | |
| 1855 | #[test] |
| 1856 | fn load_fleet_at_returns_workspace_scope_when_home_is_unresolvable() { |
| 1857 | let _lock = crate::test_support::lock_test_env(); |
| 1858 | let ws = tempfile::TempDir::new().unwrap(); |
| 1859 | let fleet = sample_fleet(); |
| 1860 | let path = save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("save workspace"); |
| 1861 | |
| 1862 | let _broken_home = |
| 1863 | crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", "relative/broken-home"); |
| 1864 | let (loaded, scope) = load_fleet_at(&path) |
| 1865 | .expect("workspace fleet must still load when home cannot be resolved"); |
| 1866 | assert_eq!(loaded.name, fleet.name); |
| 1867 | assert_eq!(scope, FleetScope::Workspace); |
| 1868 | } |
| 1869 | |
| 1870 | #[test] |
| 1871 | fn selection_is_scope_explicit_and_workspace_wins() { |
| 1872 | let _lock = crate::test_support::lock_test_env(); |
| 1873 | let _home = set_sealed_home(); |
| 1874 | let ws = tempfile::TempDir::new().unwrap(); |
| 1875 | let fleet = sample_fleet(); |
| 1876 | |
| 1877 | // No selection yet. |
| 1878 | assert!(selected_fleet(ws.path()).is_none()); |
| 1879 | |
| 1880 | // Personal selection: the user-global default. |
| 1881 | save_fleet(&fleet, FleetScope::Personal, ws.path()).unwrap(); |
| 1882 | let selected_file = |
| 1883 | set_selected("DeepSeek Flash", FleetScope::Personal, ws.path()).expect("select"); |
| 1884 | assert!( |
| 1885 | selected_file.ends_with("fleets/selected"), |
| 1886 | "{selected_file:?}" |
| 1887 | ); |
| 1888 | let sel = selected_fleet(ws.path()).expect("selected"); |
| 1889 | assert_eq!(sel.scope, FleetScope::Personal); |
| 1890 | assert_eq!(sel.name, "DeepSeek Flash"); |
| 1891 | |
| 1892 | // A selection naming a missing Fleet is refused — a phantom selection |
| 1893 | // would be a lie. |
| 1894 | let err = set_selected("No Such Fleet", FleetScope::Personal, ws.path()).unwrap_err(); |
| 1895 | assert!(err.to_string().contains("No Such Fleet"), "{err}"); |
| 1896 | |
| 1897 | // Workspace selection overrides for this folder only. |
| 1898 | save_fleet(&fleet, FleetScope::Workspace, ws.path()).unwrap(); |
| 1899 | set_selected("DeepSeek Flash", FleetScope::Workspace, ws.path()).unwrap(); |
| 1900 | let sel = selected_fleet(ws.path()).expect("selected"); |
| 1901 | assert_eq!(sel.scope, FleetScope::Workspace); |
| 1902 | // Deleting the workspace Fleet clears the workspace selection; the |
| 1903 | // personal default reappears rather than a phantom. |
| 1904 | delete_fleet("DeepSeek Flash", FleetScope::Workspace, ws.path()).unwrap(); |
| 1905 | let sel = selected_fleet(ws.path()).expect("personal default returns"); |
| 1906 | assert_eq!(sel.scope, FleetScope::Personal); |
| 1907 | } |
| 1908 | |
| 1909 | #[test] |
| 1910 | fn stale_explicit_selection_is_an_error_not_legacy_fallback() { |
| 1911 | let _lock = crate::test_support::lock_test_env(); |
| 1912 | let _home = set_sealed_home(); |
| 1913 | let ws = tempfile::TempDir::new().unwrap(); |
| 1914 | let dir = workspace_fleets_dir(ws.path()); |
| 1915 | std::fs::create_dir_all(&dir).unwrap(); |
| 1916 | std::fs::write(dir.join(SELECTED_FILE), "Missing Fleet\n").unwrap(); |
| 1917 | |
| 1918 | let error = resolve_selected_fleet(ws.path()).expect_err("stale selection must fail"); |
| 1919 | assert!( |
| 1920 | error.to_string().contains("selected fleet `Missing Fleet`"), |
| 1921 | "{error}" |
| 1922 | ); |
| 1923 | assert!(error.to_string().contains("folder selection"), "{error}"); |
| 1924 | } |
| 1925 | |
| 1926 | #[test] |
| 1927 | fn list_marks_legacy_files_without_hiding_them() { |
| 1928 | let _lock = crate::test_support::lock_test_env(); |
| 1929 | let _home = set_sealed_home(); |
| 1930 | let ws = tempfile::TempDir::new().unwrap(); |
| 1931 | |
| 1932 | save_fleet(&sample_fleet(), FleetScope::Personal, ws.path()).unwrap(); |
| 1933 | // A legacy exact fleet file (workflow schema) in the same directory |
| 1934 | // must be listed as legacy, never silently absent. |
| 1935 | let legacy = r#"schema = "exact" |
| 1936 | schema_revision = 1 |
| 1937 | name = "stopship" |
| 1938 | members = []"#; |
| 1939 | std::fs::write(sealed_home().join("fleets/stopship.toml"), legacy).unwrap(); |
| 1940 | |
| 1941 | let entries = list_fleets(ws.path()); |
| 1942 | assert_eq!(entries.len(), 2, "{entries:?}"); |
| 1943 | let stopship = entries |
| 1944 | .iter() |
| 1945 | .find(|e| e.name == "stopship") |
| 1946 | .expect("legacy fleet listed"); |
| 1947 | assert!(stopship.legacy, "{stopship:?}"); |
| 1948 | assert!(stopship.parse_error.is_some(), "{stopship:?}"); |
| 1949 | let flash = entries.iter().find(|e| e.name == "DeepSeek Flash").unwrap(); |
| 1950 | assert!(!flash.legacy && flash.parse_error.is_none(), "{flash:?}"); |
| 1951 | } |
| 1952 | |
| 1953 | #[test] |
| 1954 | fn save_refuses_to_clobber_a_different_fleet_of_the_same_slug() { |
| 1955 | let _lock = crate::test_support::lock_test_env(); |
| 1956 | let ws = tempfile::TempDir::new().unwrap(); |
| 1957 | let fleet = sample_fleet(); |
| 1958 | save_fleet(&fleet, FleetScope::Workspace, ws.path()).unwrap(); |
| 1959 | |
| 1960 | let mut other = FleetFile::new("DeepSeek Flash!".to_string(), None).unwrap(); |
| 1961 | other.members = fleet.members.clone(); |
| 1962 | let err = save_fleet(&other, FleetScope::Workspace, ws.path()).unwrap_err(); |
| 1963 | assert!(err.to_string().contains("already exists"), "{err}"); |
| 1964 | } |
| 1965 | |
| 1966 | #[test] |
| 1967 | fn save_refuses_to_overwrite_a_legacy_fleet_file_of_the_same_slug() { |
| 1968 | let _lock = crate::test_support::lock_test_env(); |
| 1969 | let ws = tempfile::TempDir::new().unwrap(); |
| 1970 | let dir = ws.path().join(".codewhale/fleets"); |
| 1971 | std::fs::create_dir_all(&dir).unwrap(); |
| 1972 | let legacy_path = dir.join("default.toml"); |
| 1973 | let legacy = "[roles.builder]\nmodel = \"deepseek-v4-flash\"\n"; |
| 1974 | std::fs::write(&legacy_path, legacy).unwrap(); |
| 1975 | |
| 1976 | let fleet = FleetFile::new("Default".to_string(), None).unwrap(); |
| 1977 | let err = save_fleet(&fleet, FleetScope::Workspace, ws.path()).unwrap_err(); |
| 1978 | assert!(err.to_string().contains("left unchanged"), "{err}"); |
| 1979 | assert_eq!(std::fs::read_to_string(&legacy_path).unwrap(), legacy); |
| 1980 | |
| 1981 | // A saved v2 Fleet of the same name is still updated in place. |
| 1982 | std::fs::remove_file(&legacy_path).unwrap(); |
| 1983 | save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("first save"); |
| 1984 | save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("re-save"); |
| 1985 | } |
| 1986 | |
| 1987 | #[test] |
| 1988 | fn save_leaves_an_unreadable_fleet_file_of_the_same_slug_unchanged() { |
| 1989 | let _lock = crate::test_support::lock_test_env(); |
| 1990 | let ws = tempfile::TempDir::new().unwrap(); |
| 1991 | let dir = ws.path().join(".codewhale/fleets"); |
| 1992 | std::fs::create_dir_all(&dir).unwrap(); |
| 1993 | let path = dir.join("default.toml"); |
| 1994 | let fleet = FleetFile::new("Default".to_string(), None).unwrap(); |
| 1995 | |
| 1996 | for existing in [ |
| 1997 | // Written by a newer build. |
| 1998 | "schema = \"fleet\"\nschema_revision = 3\nname = \"Default\"\n", |
| 1999 | // The schema declaration other readers normalize. |
| 2000 | "schema = \"Fleet\"\nschema_revision = 2\nname = \"Default\"\n", |
| 2001 | // A v2 Fleet the user is mid-edit on. |
| 2002 | "schema = \"fleet\"\nschema_revision = 2\nname = \"Default\"\nmembers = [\n", |
| 2003 | ] { |
| 2004 | std::fs::write(&path, existing).unwrap(); |
| 2005 | let err = save_fleet(&fleet, FleetScope::Workspace, ws.path()).unwrap_err(); |
| 2006 | let message = err.to_string(); |
| 2007 | assert!(message.contains("left unchanged"), "{message}"); |
| 2008 | assert!(!message.contains("migrate"), "{message}"); |
| 2009 | assert_eq!(std::fs::read_to_string(&path).unwrap(), existing); |
| 2010 | } |
| 2011 | let declared = "schema = \"fleet\"\nschema_revision = 3\nname = \"Default\"\n"; |
| 2012 | std::fs::write(&path, declared).unwrap(); |
| 2013 | let message = save_fleet(&fleet, FleetScope::Workspace, ws.path()) |
| 2014 | .unwrap_err() |
| 2015 | .to_string(); |
| 2016 | assert!(message.contains("cannot read"), "{message}"); |
| 2017 | |
| 2018 | // An empty placeholder is not a Fleet worth keeping. |
| 2019 | std::fs::write(&path, "").unwrap(); |
| 2020 | save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("replace empty file"); |
| 2021 | assert!( |
| 2022 | load_fleet_at(&path).is_ok(), |
| 2023 | "the saved Fleet must read back" |
| 2024 | ); |
| 2025 | } |
| 2026 | |
| 2027 | #[test] |
| 2028 | fn migration_preserves_pins_and_names_shadowing() { |
| 2029 | let _lock = crate::test_support::lock_test_env(); |
| 2030 | let ws = tempfile::TempDir::new().unwrap(); |
| 2031 | |
| 2032 | // A workspace legacy profile file with a pin. |
| 2033 | let agents_dir = ws.path().join(".codewhale/agents"); |
| 2034 | std::fs::create_dir_all(&agents_dir).unwrap(); |
| 2035 | std::fs::write( |
| 2036 | agents_dir.join("scout.toml"), |
| 2037 | r#"id = "scout" |
| 2038 | display_name = "Scout One" |
| 2039 | role_hint = "scout" |
| 2040 | model = "deepseek-v4-flash" |
| 2041 | provider = "deepseek" |
| 2042 | "#, |
| 2043 | ) |
| 2044 | .unwrap(); |
| 2045 | |
| 2046 | let receipt = migrate_legacy_roster( |
| 2047 | &codewhale_config::FleetConfigToml::default(), |
| 2048 | ws.path(), |
| 2049 | true, |
| 2050 | FleetScope::Workspace, |
| 2051 | ) |
| 2052 | .expect("migration"); |
| 2053 | |
| 2054 | assert_eq!(receipt.fleet.name, "Default"); |
| 2055 | let scout = receipt.fleet.member("scout").expect("scout member"); |
| 2056 | assert_eq!(scout.display_name.as_deref(), Some("Scout One")); |
| 2057 | assert_eq!(scout.model.as_deref(), Some("deepseek-v4-flash")); |
| 2058 | assert_eq!(scout.provider.as_deref(), Some("deepseek")); |
| 2059 | assert!(receipt.saved_to.ends_with("fleets/default.toml")); |
| 2060 | // The legacy profile file itself is untouched. |
| 2061 | assert!( |
| 2062 | std::fs::read_to_string(agents_dir.join("scout.toml")) |
| 2063 | .unwrap() |
| 2064 | .contains("model = \"deepseek-v4-flash\"") |
| 2065 | ); |
| 2066 | } |
| 2067 | } |
| 2068 |