| 1 | //! Typed task-spec loading, artifact refs, deterministic scorers, and receipts. |
| 2 | |
| 3 | use std::collections::{BTreeMap, BTreeSet}; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | |
| 6 | use anyhow::{Context, Result, bail, ensure}; |
| 7 | use chrono::{SecondsFormat, Utc}; |
| 8 | use codewhale_protocol::fleet::*; |
| 9 | use regex::Regex; |
| 10 | use serde::{Deserialize, Serialize}; |
| 11 | use serde_json::{Value, json}; |
| 12 | |
| 13 | #[cfg(any(test, feature = "test-support"))] |
| 14 | use super::ledger::FleetLedger; |
| 15 | |
| 16 | const MAX_SCORER_READ_BYTES: u64 = 1_000_000; |
| 17 | const MAX_FLEET_ID_BYTES: usize = 128; |
| 18 | const MAX_FLEET_NAME_BYTES: usize = 256; |
| 19 | |
| 20 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 21 | pub struct FleetTaskSpecDocument { |
| 22 | #[serde(default)] |
| 23 | pub name: Option<String>, |
| 24 | #[serde(default)] |
| 25 | pub labels: BTreeMap<String, String>, |
| 26 | #[serde(default)] |
| 27 | #[serde(skip_serializing_if = "Option::is_none")] |
| 28 | /// Legacy replay/input compatibility only. New run validation rejects it; |
| 29 | /// Runtime policy owns execution authority. |
| 30 | pub security_policy: Option<FleetSecurityPolicy>, |
| 31 | #[serde(default, alias = "worker_specs")] |
| 32 | pub workers: Vec<FleetWorkerSpec>, |
| 33 | #[serde(default)] |
| 34 | pub tasks: Vec<FleetTaskSpec>, |
| 35 | /// Optional run-wide usage ceiling (R6, #5567), e.g. |
| 36 | /// `usage_ceiling = { max_total_tokens = 2_000_000 }`. |
| 37 | #[serde(default)] |
| 38 | #[serde(skip_serializing_if = "Option::is_none")] |
| 39 | pub usage_ceiling: Option<codewhale_protocol::fleet::FleetUsageCeiling>, |
| 40 | } |
| 41 | |
| 42 | /// A parsed spec file in one of its three accepted shapes. The shape is |
| 43 | /// chosen from the file's structure first ([`FleetTaskSpecShape::detect`]) and |
| 44 | /// only then deserialized into the matching type, so a malformed spec reports |
| 45 | /// the real field error instead of serde's opaque "did not match any variant |
| 46 | /// of untagged enum". |
| 47 | #[derive(Debug, Clone)] |
| 48 | enum FleetTaskSpecFile { |
| 49 | Document(FleetTaskSpecDocument), |
| 50 | Tasks(Vec<FleetTaskSpec>), |
| 51 | Single(Box<FleetTaskSpec>), |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 55 | enum FleetTaskSpecShape { |
| 56 | /// `{ name?, labels?, workers?, tasks = [...] }` |
| 57 | Document, |
| 58 | /// A bare JSON array of task objects. |
| 59 | Tasks, |
| 60 | /// A single task object (`{ id, name, instructions, ... }`). |
| 61 | Single, |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 65 | enum FleetTaskSpecFormat { |
| 66 | Json, |
| 67 | Toml, |
| 68 | } |
| 69 | |
| 70 | impl FleetTaskSpecFormat { |
| 71 | fn label(self) -> &'static str { |
| 72 | match self { |
| 73 | Self::Json => "JSON", |
| 74 | Self::Toml => "TOML", |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Top-level keys that only a spec document carries. |
| 80 | const DOCUMENT_KEYS: &[&str] = &["tasks", "workers", "worker_specs"]; |
| 81 | /// Top-level keys that mark a bare single-task file. |
| 82 | const SINGLE_TASK_KEYS: &[&str] = &["id", "instructions"]; |
| 83 | |
| 84 | impl FleetTaskSpecShape { |
| 85 | fn detect(value: &Value) -> Result<Self> { |
| 86 | match value { |
| 87 | Value::Array(_) => Ok(Self::Tasks), |
| 88 | Value::Object(map) => { |
| 89 | if DOCUMENT_KEYS.iter().any(|key| map.contains_key(*key)) { |
| 90 | Ok(Self::Document) |
| 91 | } else if SINGLE_TASK_KEYS.iter().any(|key| map.contains_key(*key)) { |
| 92 | Ok(Self::Single) |
| 93 | } else { |
| 94 | // Name/labels-only (or empty) objects are documents; the |
| 95 | // validator then reports the missing `tasks`. |
| 96 | Ok(Self::Document) |
| 97 | } |
| 98 | } |
| 99 | other => bail!( |
| 100 | "a fleet task spec must be a document object with `tasks`, an array of task objects, or a single task object; found {}", |
| 101 | json_kind(other) |
| 102 | ), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | fn label(self) -> &'static str { |
| 107 | match self { |
| 108 | Self::Document => "spec document", |
| 109 | Self::Tasks => "task array", |
| 110 | Self::Single => "single task", |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn json_kind(value: &Value) -> &'static str { |
| 116 | match value { |
| 117 | Value::Null => "null", |
| 118 | Value::Bool(_) => "a boolean", |
| 119 | Value::Number(_) => "a number", |
| 120 | Value::String(_) => "a string", |
| 121 | Value::Array(_) => "an array", |
| 122 | Value::Object(_) => "an object", |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | fn parse_task_spec_file(raw: &str, format: FleetTaskSpecFormat) -> Result<FleetTaskSpecFile> { |
| 127 | // Pass 1: syntax only, to learn the shape. |
| 128 | let value = match format { |
| 129 | FleetTaskSpecFormat::Json => serde_json::from_str::<Value>(raw) |
| 130 | .map_err(|err| anyhow::anyhow!("invalid JSON: {err}"))?, |
| 131 | FleetTaskSpecFormat::Toml => { |
| 132 | let table = toml::from_str::<toml::Table>(raw) |
| 133 | .map_err(|err| anyhow::anyhow!("invalid TOML: {err}"))?; |
| 134 | serde_json::to_value(table).context("converting TOML fleet task spec")? |
| 135 | } |
| 136 | }; |
| 137 | let shape = FleetTaskSpecShape::detect(&value)?; |
| 138 | |
| 139 | // Pass 2: typed deserialize of exactly that shape, from the raw text so |
| 140 | // the error keeps its line/column. |
| 141 | fn typed<T: serde::de::DeserializeOwned>( |
| 142 | raw: &str, |
| 143 | format: FleetTaskSpecFormat, |
| 144 | ) -> std::result::Result<T, String> { |
| 145 | match format { |
| 146 | FleetTaskSpecFormat::Json => serde_json::from_str::<T>(raw).map_err(|e| e.to_string()), |
| 147 | FleetTaskSpecFormat::Toml => toml::from_str::<T>(raw).map_err(|e| e.to_string()), |
| 148 | } |
| 149 | } |
| 150 | let parsed = match shape { |
| 151 | FleetTaskSpecShape::Document => { |
| 152 | typed::<FleetTaskSpecDocument>(raw, format).map(FleetTaskSpecFile::Document) |
| 153 | } |
| 154 | FleetTaskSpecShape::Tasks => { |
| 155 | typed::<Vec<FleetTaskSpec>>(raw, format).map(FleetTaskSpecFile::Tasks) |
| 156 | } |
| 157 | FleetTaskSpecShape::Single => typed::<FleetTaskSpec>(raw, format) |
| 158 | .map(|task| FleetTaskSpecFile::Single(Box::new(task))), |
| 159 | }; |
| 160 | parsed.map_err(|err| { |
| 161 | let location = locate_spec_error(shape, &value) |
| 162 | .map(|loc| format!(" at {loc}")) |
| 163 | .unwrap_or_default(); |
| 164 | anyhow::anyhow!( |
| 165 | "{} {}{location}: {}", |
| 166 | format.label(), |
| 167 | shape.label(), |
| 168 | err.trim() |
| 169 | ) |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | /// Name the first task (or worker) entry that fails to deserialize on its |
| 174 | /// own, e.g. `tasks[1] (id "review")`, so a long spec's error points at the |
| 175 | /// entry and not only at a line number. |
| 176 | fn locate_spec_error(shape: FleetTaskSpecShape, value: &Value) -> Option<String> { |
| 177 | fn first_bad<T: serde::de::DeserializeOwned>(prefix: &str, items: &[Value]) -> Option<String> { |
| 178 | items.iter().enumerate().find_map(|(index, item)| { |
| 179 | serde_json::from_value::<T>(item.clone()).err().map(|_| { |
| 180 | match item.get("id").and_then(Value::as_str) { |
| 181 | Some(id) => format!("{prefix}[{index}] (id {id:?})"), |
| 182 | None => format!("{prefix}[{index}]"), |
| 183 | } |
| 184 | }) |
| 185 | }) |
| 186 | } |
| 187 | match shape { |
| 188 | FleetTaskSpecShape::Document => { |
| 189 | if let Some(tasks) = value.get("tasks").and_then(Value::as_array) |
| 190 | && let Some(loc) = first_bad::<FleetTaskSpec>("tasks", tasks) |
| 191 | { |
| 192 | return Some(loc); |
| 193 | } |
| 194 | let workers = value |
| 195 | .get("workers") |
| 196 | .or_else(|| value.get("worker_specs")) |
| 197 | .and_then(Value::as_array)?; |
| 198 | first_bad::<FleetWorkerSpec>("workers", workers) |
| 199 | } |
| 200 | FleetTaskSpecShape::Tasks => first_bad::<FleetTaskSpec>("", value.as_array()?), |
| 201 | FleetTaskSpecShape::Single => None, |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | impl FleetTaskSpecFile { |
| 206 | fn into_document(self, fallback_name: String) -> FleetTaskSpecDocument { |
| 207 | match self { |
| 208 | Self::Document(mut doc) => { |
| 209 | if doc.name.as_deref().is_none_or(str::is_empty) { |
| 210 | doc.name = Some(fallback_name); |
| 211 | } |
| 212 | doc |
| 213 | } |
| 214 | Self::Tasks(tasks) => FleetTaskSpecDocument { |
| 215 | name: Some(fallback_name), |
| 216 | labels: BTreeMap::new(), |
| 217 | security_policy: None, |
| 218 | workers: Vec::new(), |
| 219 | tasks, |
| 220 | usage_ceiling: None, |
| 221 | }, |
| 222 | Self::Single(task) => FleetTaskSpecDocument { |
| 223 | name: Some(fallback_name), |
| 224 | labels: BTreeMap::new(), |
| 225 | security_policy: None, |
| 226 | workers: Vec::new(), |
| 227 | tasks: vec![*task], |
| 228 | usage_ceiling: None, |
| 229 | }, |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | /// The worker's visible final answer as carried by the terminal exec |
| 235 | /// `metadata` receipt: `excerpt` is already bounded and secret-redacted by the |
| 236 | /// emitter (`visible_final_answer_excerpt`), `chars` is the real |
| 237 | /// pre-truncation length (`visible_final_answer_chars`). |
| 238 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 239 | pub struct FleetWorkerFinalAnswer { |
| 240 | pub excerpt: String, |
| 241 | pub chars: usize, |
| 242 | } |
| 243 | |
| 244 | impl FleetWorkerFinalAnswer { |
| 245 | /// The receipt note for a task whose only deliverable is its answer text. |
| 246 | /// The excerpt is used verbatim: it was bounded and redacted once at the |
| 247 | /// emitter, and the ledger redacts receipt notes again on write. |
| 248 | pub fn receipt_note(&self) -> String { |
| 249 | format!( |
| 250 | "worker produced {} characters of deliverable: {}", |
| 251 | self.chars, self.excerpt |
| 252 | ) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | #[derive(Debug, Clone)] |
| 257 | pub struct FleetTaskVerificationInput { |
| 258 | pub run_id: FleetRunId, |
| 259 | pub task_id: String, |
| 260 | pub worker_id: String, |
| 261 | /// Durable lease generation whose result is being verified. |
| 262 | pub attempt: u32, |
| 263 | pub exit_code: Option<i32>, |
| 264 | pub artifacts: Vec<FleetArtifactRef>, |
| 265 | /// The worker's visible final answer, as reported by its terminal exec |
| 266 | /// receipt. Report/summary tasks with no scorer and no file artifact |
| 267 | /// surface this as their deliverable instead of "no verifiable output". |
| 268 | pub final_answer: Option<FleetWorkerFinalAnswer>, |
| 269 | /// Saved exec session id holding the worker's full transcript, when the |
| 270 | /// worker persisted one on completion. |
| 271 | pub saved_session_id: Option<String>, |
| 272 | /// Resolved-route snapshot to persist on the receipt (#3154). |
| 273 | pub resolved_route: Option<FleetResolvedRoute>, |
| 274 | /// Effective worker authority snapshot to persist on the receipt (#3211). |
| 275 | pub effective_permissions: Option<FleetEffectivePermissions>, |
| 276 | } |
| 277 | |
| 278 | #[derive(Debug, Clone)] |
| 279 | pub struct FleetTaskVerification { |
| 280 | pub result: FleetTaskResult, |
| 281 | pub failure_kind: Option<FleetTaskFailureKind>, |
| 282 | pub score: FleetScore, |
| 283 | pub evidence: Vec<String>, |
| 284 | } |
| 285 | |
| 286 | pub fn load_task_spec_document(path: &Path) -> Result<FleetTaskSpecDocument> { |
| 287 | let raw = std::fs::read_to_string(path) |
| 288 | .with_context(|| format!("reading fleet task spec {}", path.display()))?; |
| 289 | let fallback_name = path |
| 290 | .file_stem() |
| 291 | .and_then(|s| s.to_str()) |
| 292 | .filter(|s| !s.is_empty()) |
| 293 | .unwrap_or("fleet-run") |
| 294 | .to_string(); |
| 295 | let format = match path.extension().and_then(|s| s.to_str()) { |
| 296 | Some("toml") => FleetTaskSpecFormat::Toml, |
| 297 | _ => FleetTaskSpecFormat::Json, |
| 298 | }; |
| 299 | let parsed = parse_task_spec_file(&raw, format).with_context(|| { |
| 300 | format!( |
| 301 | "parsing {} fleet task spec {}", |
| 302 | format.label(), |
| 303 | path.display() |
| 304 | ) |
| 305 | })?; |
| 306 | let doc = parsed.into_document(fallback_name); |
| 307 | validate_task_spec_document(&doc)?; |
| 308 | Ok(doc) |
| 309 | } |
| 310 | |
| 311 | pub fn validate_task_spec_document(doc: &FleetTaskSpecDocument) -> Result<()> { |
| 312 | if doc.security_policy.is_some() { |
| 313 | bail!( |
| 314 | "fleet task spec security_policy is a legacy compatibility field, not executable Fleet identity; configure trust, secrets, approvals, sandboxing, and tool authority through Runtime policy" |
| 315 | ); |
| 316 | } |
| 317 | if doc.tasks.is_empty() { |
| 318 | bail!("fleet task spec must include at least one task"); |
| 319 | } |
| 320 | ensure!( |
| 321 | doc.tasks.len() <= 64, |
| 322 | "fleet task spec cannot declare more than 64 tasks" |
| 323 | ); |
| 324 | let mut ids = BTreeSet::new(); |
| 325 | for task in &doc.tasks { |
| 326 | validate_fleet_identity("task id", &task.id)?; |
| 327 | if !ids.insert(task.id.clone()) { |
| 328 | bail!("duplicate fleet task id {}", task.id); |
| 329 | } |
| 330 | validate_fleet_name(&format!("task {} name", task.id), &task.name)?; |
| 331 | if task.instructions.trim().is_empty() { |
| 332 | bail!("fleet task {} instructions cannot be empty", task.id); |
| 333 | } |
| 334 | if let Some(objective) = &task.objective |
| 335 | && objective.trim().is_empty() |
| 336 | { |
| 337 | bail!("fleet task {} objective cannot be empty", task.id); |
| 338 | } |
| 339 | validate_worker_profile(&task.id, task.worker.as_ref())?; |
| 340 | if task |
| 341 | .metadata |
| 342 | .contains_key(super::worker_runtime::FROZEN_FLEET_MEMBER_METADATA_KEY) |
| 343 | { |
| 344 | bail!( |
| 345 | "fleet task {} metadata key {} is reserved for the durable Runtime selection receipt", |
| 346 | task.id, |
| 347 | super::worker_runtime::FROZEN_FLEET_MEMBER_METADATA_KEY |
| 348 | ); |
| 349 | } |
| 350 | validate_tags(&task.id, &task.tags)?; |
| 351 | validate_workspace_requirements(task)?; |
| 352 | super::placement::validate(task)?; |
| 353 | } |
| 354 | ensure!( |
| 355 | doc.workers.len() <= 128, |
| 356 | "Fleet cannot declare more than 128 workers" |
| 357 | ); |
| 358 | let mut worker_ids = BTreeSet::new(); |
| 359 | let mut environment_hosts = BTreeMap::new(); |
| 360 | for worker in &doc.workers { |
| 361 | validate_fleet_identity("worker id", &worker.id)?; |
| 362 | super::placement::validate_worker(worker)?; |
| 363 | if let Some(environment) = &worker.environment |
| 364 | && let Some(previous_host) = environment_hosts.insert(&environment.id, &worker.host) |
| 365 | { |
| 366 | ensure!( |
| 367 | previous_host == &worker.host, |
| 368 | "Environment {} names more than one execution host", |
| 369 | environment.id |
| 370 | ); |
| 371 | } |
| 372 | if !worker_ids.insert(worker.id.clone()) { |
| 373 | bail!("duplicate fleet worker id {}", worker.id); |
| 374 | } |
| 375 | validate_fleet_name(&format!("worker {} name", worker.id), &worker.name)?; |
| 376 | if worker.trust_level.is_some() { |
| 377 | bail!( |
| 378 | "fleet worker {} trust_level is a legacy compatibility field, not Fleet identity; configure execution authority through Runtime policy", |
| 379 | worker.id |
| 380 | ); |
| 381 | } |
| 382 | } |
| 383 | Ok(()) |
| 384 | } |
| 385 | |
| 386 | fn validate_fleet_identity(field: &str, value: &str) -> Result<()> { |
| 387 | if value.is_empty() { |
| 388 | bail!("fleet {field} cannot be empty"); |
| 389 | } |
| 390 | if value.len() > MAX_FLEET_ID_BYTES || !value.chars().all(is_worker_token_char) { |
| 391 | bail!( |
| 392 | "fleet {field} must be a simple ASCII token no longer than {MAX_FLEET_ID_BYTES} bytes" |
| 393 | ); |
| 394 | } |
| 395 | Ok(()) |
| 396 | } |
| 397 | |
| 398 | fn validate_fleet_name(field: &str, value: &str) -> Result<()> { |
| 399 | if value.trim().is_empty() { |
| 400 | bail!("fleet {field} cannot be empty"); |
| 401 | } |
| 402 | if value.len() > MAX_FLEET_NAME_BYTES || value.chars().any(char::is_control) { |
| 403 | bail!( |
| 404 | "fleet {field} must be one printable line no longer than {MAX_FLEET_NAME_BYTES} bytes" |
| 405 | ); |
| 406 | } |
| 407 | Ok(()) |
| 408 | } |
| 409 | |
| 410 | fn validate_worker_profile(task_id: &str, worker: Option<&FleetTaskWorkerProfile>) -> Result<()> { |
| 411 | let Some(worker) = worker else { |
| 412 | return Ok(()); |
| 413 | }; |
| 414 | validate_worker_selector( |
| 415 | task_id, |
| 416 | "worker.agent_profile", |
| 417 | worker.agent_profile.as_deref(), |
| 418 | )?; |
| 419 | validate_worker_token(task_id, "worker.loadout", worker.loadout.as_deref())?; |
| 420 | validate_worker_token(task_id, "worker.model_class", worker.model_class.as_deref())?; |
| 421 | validate_worker_model(task_id, worker.model.as_deref())?; |
| 422 | validate_worker_token(task_id, "worker.provider", worker.provider.as_deref())?; |
| 423 | if worker.provider.is_some() { |
| 424 | anyhow::ensure!( |
| 425 | worker |
| 426 | .model |
| 427 | .as_deref() |
| 428 | .is_some_and(|model| !model.eq_ignore_ascii_case("auto")), |
| 429 | "fleet task {task_id} worker.provider requires a concrete worker.model" |
| 430 | ); |
| 431 | anyhow::ensure!( |
| 432 | worker.external_agent.is_none(), |
| 433 | "fleet task {task_id} worker.provider cannot select an external agent" |
| 434 | ); |
| 435 | } |
| 436 | Ok(()) |
| 437 | } |
| 438 | |
| 439 | fn validate_worker_selector(task_id: &str, field: &str, value: Option<&str>) -> Result<()> { |
| 440 | let Some(value) = value else { |
| 441 | return Ok(()); |
| 442 | }; |
| 443 | let trimmed = value.trim(); |
| 444 | if trimmed.is_empty() { |
| 445 | bail!("fleet task {task_id} {field} cannot be empty"); |
| 446 | } |
| 447 | if trimmed != value || value.len() > MAX_FLEET_NAME_BYTES || value.chars().any(char::is_control) |
| 448 | { |
| 449 | bail!( |
| 450 | "fleet task {task_id} {field} must be one printable selector no longer than {MAX_FLEET_NAME_BYTES} bytes" |
| 451 | ); |
| 452 | } |
| 453 | Ok(()) |
| 454 | } |
| 455 | |
| 456 | fn validate_worker_token(task_id: &str, field: &str, value: Option<&str>) -> Result<()> { |
| 457 | let Some(value) = value else { |
| 458 | return Ok(()); |
| 459 | }; |
| 460 | let trimmed = value.trim(); |
| 461 | if trimmed.is_empty() { |
| 462 | bail!("fleet task {task_id} {field} cannot be empty"); |
| 463 | } |
| 464 | if trimmed != value || !trimmed.chars().all(is_worker_token_char) { |
| 465 | bail!( |
| 466 | "fleet task {task_id} {field} must be a simple token, not a path or provider/model id" |
| 467 | ); |
| 468 | } |
| 469 | Ok(()) |
| 470 | } |
| 471 | |
| 472 | fn is_worker_token_char(ch: char) -> bool { |
| 473 | ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') |
| 474 | } |
| 475 | |
| 476 | fn validate_worker_model(task_id: &str, value: Option<&str>) -> Result<()> { |
| 477 | let Some(value) = value else { |
| 478 | return Ok(()); |
| 479 | }; |
| 480 | let trimmed = value.trim(); |
| 481 | if trimmed.is_empty() { |
| 482 | bail!("fleet task {task_id} worker.model cannot be empty"); |
| 483 | } |
| 484 | if trimmed != value |
| 485 | || !trimmed |
| 486 | .chars() |
| 487 | .all(|ch| ch.is_ascii_graphic() && !matches!(ch, '=' | '\'' | '"')) |
| 488 | { |
| 489 | bail!( |
| 490 | "fleet task {task_id} worker.model must be a visible model id without whitespace or secrets" |
| 491 | ); |
| 492 | } |
| 493 | Ok(()) |
| 494 | } |
| 495 | |
| 496 | #[allow(clippy::too_many_arguments)] |
| 497 | pub fn write_fleet_artifact_ref( |
| 498 | workspace: &Path, |
| 499 | run_id: &FleetRunId, |
| 500 | task_id: &str, |
| 501 | worker_id: &str, |
| 502 | kind: FleetArtifactKind, |
| 503 | filename: &str, |
| 504 | contents: &[u8], |
| 505 | mime_type: Option<&str>, |
| 506 | ) -> Result<FleetArtifactRef> { |
| 507 | let rel_path = PathBuf::from(".codewhale") |
| 508 | .join("fleet") |
| 509 | .join(safe_path_segment(&run_id.0)) |
| 510 | .join(safe_path_segment(task_id)) |
| 511 | .join(safe_path_segment(worker_id)) |
| 512 | .join(safe_path_segment(filename)); |
| 513 | super::artifacts::write(workspace, &rel_path, contents)?; |
| 514 | Ok(FleetArtifactRef { |
| 515 | kind, |
| 516 | path: rel_path, |
| 517 | checksum: Some(format!( |
| 518 | "sha256:{}", |
| 519 | codewhale_runtime::hashing::sha256_hex(contents) |
| 520 | )), |
| 521 | mime_type: mime_type.map(str::to_string), |
| 522 | size_bytes: Some(contents.len() as u64), |
| 523 | }) |
| 524 | } |
| 525 | |
| 526 | pub fn verify_task_result( |
| 527 | workspace: &Path, |
| 528 | task: &FleetTaskSpec, |
| 529 | input: &FleetTaskVerificationInput, |
| 530 | ) -> FleetTaskVerification { |
| 531 | match &task.scorer { |
| 532 | Some(FleetScorerSpec::ExitCode) => verify_exit_code(input.exit_code), |
| 533 | Some(FleetScorerSpec::FileExists { path }) => verify_file_exists(workspace, path), |
| 534 | Some(FleetScorerSpec::RegexMatch { path, pattern }) => { |
| 535 | verify_regex_match(workspace, path, pattern) |
| 536 | } |
| 537 | Some(FleetScorerSpec::JsonPath { path, expression }) => { |
| 538 | verify_json_path(workspace, path, expression) |
| 539 | } |
| 540 | Some(FleetScorerSpec::Command { command, .. }) => partial( |
| 541 | format!("external scorer command configured: {command}"), |
| 542 | "run the configured scorer command to finalize this receipt", |
| 543 | ), |
| 544 | Some(FleetScorerSpec::CodeWhaleVerifierPrompt { .. }) => partial( |
| 545 | "Codewhale verifier prompt configured", |
| 546 | "run a verifier prompt pass to finalize this receipt", |
| 547 | ), |
| 548 | Some(FleetScorerSpec::Manual) => partial( |
| 549 | "manual scorer configured", |
| 550 | "manual verification is required to finalize this receipt", |
| 551 | ), |
| 552 | None if !has_verifiable_artifact(input) => match input |
| 553 | .final_answer |
| 554 | .as_ref() |
| 555 | .filter(|answer| !answer.excerpt.trim().is_empty()) |
| 556 | { |
| 557 | Some(answer) => partial( |
| 558 | "no scorer configured; worker produced a summary deliverable", |
| 559 | answer.receipt_note(), |
| 560 | ), |
| 561 | None => partial( |
| 562 | "no scorer configured and no verifiable artifacts recorded", |
| 563 | "worker exited successfully but produced no verifiable output", |
| 564 | ), |
| 565 | }, |
| 566 | None => partial( |
| 567 | "no scorer configured", |
| 568 | "task has artifacts but no deterministic scorer", |
| 569 | ), |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | pub fn prepare_verification_receipt( |
| 574 | workspace: &Path, |
| 575 | input: &FleetTaskVerificationInput, |
| 576 | verification: FleetTaskVerification, |
| 577 | ) -> Result<FleetReceipt> { |
| 578 | let evidence = json!({ |
| 579 | "run_id": input.run_id.0.clone(), |
| 580 | "task_id": input.task_id.clone(), |
| 581 | "worker_id": input.worker_id.clone(), |
| 582 | "attempt": input.attempt, |
| 583 | "result": verification.result.clone(), |
| 584 | "failure_kind": verification.failure_kind.clone(), |
| 585 | "score": verification.score.clone(), |
| 586 | "evidence": verification.evidence.clone(), |
| 587 | "artifacts": input.artifacts.clone(), |
| 588 | }); |
| 589 | let bytes = |
| 590 | serde_json::to_vec_pretty(&evidence).context("serializing fleet receipt evidence")?; |
| 591 | // Content-address the evidence as well as namespacing it by attempt. A |
| 592 | // stale verifier may finish after a retry has started; it is allowed to |
| 593 | // leave an orphaned evidence file, but it must never overwrite the file a |
| 594 | // winning attempt's durable receipt references. |
| 595 | let evidence_hash = codewhale_runtime::hashing::sha256_hex(&bytes); |
| 596 | let filename = format!( |
| 597 | "verification-receipt-attempt-{:010}-{}.json", |
| 598 | input.attempt, evidence_hash |
| 599 | ); |
| 600 | let receipt_artifact = write_fleet_artifact_ref( |
| 601 | workspace, |
| 602 | &input.run_id, |
| 603 | &input.task_id, |
| 604 | &input.worker_id, |
| 605 | FleetArtifactKind::Receipt, |
| 606 | &filename, |
| 607 | &bytes, |
| 608 | Some("application/json"), |
| 609 | )?; |
| 610 | let mut artifacts = input.artifacts.clone(); |
| 611 | artifacts.push(receipt_artifact); |
| 612 | let receipt = FleetReceipt { |
| 613 | run_id: input.run_id.clone(), |
| 614 | task_id: input.task_id.clone(), |
| 615 | worker_id: input.worker_id.clone(), |
| 616 | attempt: Some(input.attempt), |
| 617 | terminal_seq: None, |
| 618 | completed_at: timestamp(), |
| 619 | result: verification.result, |
| 620 | failure_kind: verification.failure_kind, |
| 621 | artifacts, |
| 622 | score: Some(verification.score), |
| 623 | resolved_route: input.resolved_route.clone(), |
| 624 | saved_session_id: input.saved_session_id.clone(), |
| 625 | effective_permissions: input.effective_permissions.clone(), |
| 626 | }; |
| 627 | Ok(receipt) |
| 628 | } |
| 629 | |
| 630 | #[cfg(any(test, feature = "test-support"))] |
| 631 | pub fn record_verification_receipt( |
| 632 | ledger: &FleetLedger, |
| 633 | workspace: &Path, |
| 634 | input: &FleetTaskVerificationInput, |
| 635 | verification: FleetTaskVerification, |
| 636 | ) -> Result<FleetReceipt> { |
| 637 | let receipt = prepare_verification_receipt(workspace, input, verification)?; |
| 638 | ledger.record_receipt(receipt.clone())?; |
| 639 | Ok(receipt) |
| 640 | } |
| 641 | |
| 642 | fn validate_tags(task_id: &str, tags: &[String]) -> Result<()> { |
| 643 | let mut seen = BTreeSet::new(); |
| 644 | for tag in tags { |
| 645 | if tag.trim().is_empty() { |
| 646 | bail!("fleet task {task_id} tag cannot be empty"); |
| 647 | } |
| 648 | if !seen.insert(tag) { |
| 649 | bail!("fleet task {task_id} has duplicate tag {tag}"); |
| 650 | } |
| 651 | } |
| 652 | Ok(()) |
| 653 | } |
| 654 | |
| 655 | fn validate_workspace_requirements(task: &FleetTaskSpec) -> Result<()> { |
| 656 | let Some(workspace) = &task.workspace else { |
| 657 | return Ok(()); |
| 658 | }; |
| 659 | let env = workspace.environment.as_ref(); |
| 660 | for name in env |
| 661 | .into_iter() |
| 662 | .flat_map(|env| env.required.iter().chain(env.allowlist.iter())) |
| 663 | { |
| 664 | if name.trim().is_empty() { |
| 665 | bail!( |
| 666 | "fleet task {} environment variable name cannot be empty", |
| 667 | task.id |
| 668 | ); |
| 669 | } |
| 670 | } |
| 671 | Ok(()) |
| 672 | } |
| 673 | |
| 674 | fn verify_exit_code(exit_code: Option<i32>) -> FleetTaskVerification { |
| 675 | match exit_code { |
| 676 | Some(0) => pass("exit_code=0"), |
| 677 | Some(code) => fail( |
| 678 | FleetTaskFailureKind::Task, |
| 679 | 0.0, |
| 680 | format!("exit_code={code}"), |
| 681 | "worker task exited unsuccessfully", |
| 682 | ), |
| 683 | None => fail( |
| 684 | FleetTaskFailureKind::Transport, |
| 685 | 0.0, |
| 686 | "missing exit code", |
| 687 | "worker transport did not report a process result", |
| 688 | ), |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | fn verify_file_exists(workspace: &Path, path: &Path) -> FleetTaskVerification { |
| 693 | let abs_path = resolve_workspace_path(workspace, path); |
| 694 | if abs_path.is_file() { |
| 695 | pass(format!("file exists: {}", path.display())) |
| 696 | } else { |
| 697 | fail( |
| 698 | FleetTaskFailureKind::Task, |
| 699 | 0.0, |
| 700 | format!("missing file: {}", path.display()), |
| 701 | "expected artifact file was not produced", |
| 702 | ) |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | fn verify_regex_match(workspace: &Path, path: &Path, pattern: &str) -> FleetTaskVerification { |
| 707 | let regex = match Regex::new(pattern) { |
| 708 | Ok(regex) => regex, |
| 709 | Err(err) => { |
| 710 | return fail( |
| 711 | FleetTaskFailureKind::Verifier, |
| 712 | 0.0, |
| 713 | format!("invalid regex: {err}"), |
| 714 | "regex scorer could not be compiled", |
| 715 | ); |
| 716 | } |
| 717 | }; |
| 718 | let contents = match read_bounded_to_string(workspace, path) { |
| 719 | Ok(contents) => contents, |
| 720 | Err(err) => { |
| 721 | return fail( |
| 722 | err.failure_kind, |
| 723 | 0.0, |
| 724 | err.evidence, |
| 725 | "regex scorer could not read bounded evidence", |
| 726 | ); |
| 727 | } |
| 728 | }; |
| 729 | if regex.is_match(&contents) { |
| 730 | pass(format!("regex matched {}: {pattern}", path.display())) |
| 731 | } else { |
| 732 | fail( |
| 733 | FleetTaskFailureKind::Task, |
| 734 | 0.0, |
| 735 | format!("regex did not match {}: {pattern}", path.display()), |
| 736 | "worker output did not satisfy the regex scorer", |
| 737 | ) |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | fn verify_json_path(workspace: &Path, path: &Path, expression: &str) -> FleetTaskVerification { |
| 742 | let Some(segments) = json_path_segments(expression) else { |
| 743 | return fail( |
| 744 | FleetTaskFailureKind::Verifier, |
| 745 | 0.0, |
| 746 | format!("unsupported JSON path expression: {expression}"), |
| 747 | "json_path scorer supports $.field or .field paths", |
| 748 | ); |
| 749 | }; |
| 750 | let contents = match read_bounded_to_string(workspace, path) { |
| 751 | Ok(contents) => contents, |
| 752 | Err(err) => { |
| 753 | return fail( |
| 754 | err.failure_kind, |
| 755 | 0.0, |
| 756 | err.evidence, |
| 757 | "json_path scorer could not read bounded evidence", |
| 758 | ); |
| 759 | } |
| 760 | }; |
| 761 | let value: Value = match serde_json::from_str(&contents) { |
| 762 | Ok(value) => value, |
| 763 | Err(err) => { |
| 764 | return fail( |
| 765 | FleetTaskFailureKind::Task, |
| 766 | 0.0, |
| 767 | format!("invalid JSON in {}: {err}", path.display()), |
| 768 | "worker artifact was not valid JSON", |
| 769 | ); |
| 770 | } |
| 771 | }; |
| 772 | match json_path_lookup(&value, &segments) { |
| 773 | Some(found) if json_truthy(found) => pass(format!( |
| 774 | "json_path matched {}: {expression}", |
| 775 | path.display() |
| 776 | )), |
| 777 | _ => fail( |
| 778 | FleetTaskFailureKind::Task, |
| 779 | 0.0, |
| 780 | format!( |
| 781 | "json_path missing or false in {}: {expression}", |
| 782 | path.display() |
| 783 | ), |
| 784 | "worker JSON artifact did not satisfy the scorer", |
| 785 | ), |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | fn pass(evidence: impl Into<String>) -> FleetTaskVerification { |
| 790 | let evidence = evidence.into(); |
| 791 | FleetTaskVerification { |
| 792 | result: FleetTaskResult::Pass, |
| 793 | failure_kind: None, |
| 794 | score: FleetScore { |
| 795 | value: 1.0, |
| 796 | max: Some(1.0), |
| 797 | notes: Some(evidence.clone()), |
| 798 | }, |
| 799 | evidence: vec![evidence], |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | fn partial(evidence: impl Into<String>, notes: impl Into<String>) -> FleetTaskVerification { |
| 804 | let evidence = evidence.into(); |
| 805 | let notes = notes.into(); |
| 806 | FleetTaskVerification { |
| 807 | result: FleetTaskResult::Partial, |
| 808 | failure_kind: None, |
| 809 | score: FleetScore { |
| 810 | value: 0.5, |
| 811 | max: Some(1.0), |
| 812 | notes: Some(notes), |
| 813 | }, |
| 814 | evidence: vec![evidence], |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | fn fail( |
| 819 | failure_kind: FleetTaskFailureKind, |
| 820 | value: f64, |
| 821 | evidence: impl Into<String>, |
| 822 | notes: impl Into<String>, |
| 823 | ) -> FleetTaskVerification { |
| 824 | let evidence = evidence.into(); |
| 825 | FleetTaskVerification { |
| 826 | result: FleetTaskResult::Fail, |
| 827 | failure_kind: Some(failure_kind), |
| 828 | score: FleetScore { |
| 829 | value, |
| 830 | max: Some(1.0), |
| 831 | notes: Some(notes.into()), |
| 832 | }, |
| 833 | evidence: vec![evidence], |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | fn has_verifiable_artifact(input: &FleetTaskVerificationInput) -> bool { |
| 838 | input.artifacts.iter().any(|artifact| { |
| 839 | !matches!( |
| 840 | artifact.kind, |
| 841 | FleetArtifactKind::Log | FleetArtifactKind::Receipt |
| 842 | ) |
| 843 | }) |
| 844 | } |
| 845 | |
| 846 | #[derive(Debug)] |
| 847 | struct EvidenceReadError { |
| 848 | failure_kind: FleetTaskFailureKind, |
| 849 | evidence: String, |
| 850 | } |
| 851 | |
| 852 | fn read_bounded_to_string( |
| 853 | workspace: &Path, |
| 854 | path: &Path, |
| 855 | ) -> std::result::Result<String, EvidenceReadError> { |
| 856 | let abs_path = resolve_workspace_path(workspace, path); |
| 857 | let metadata = std::fs::metadata(&abs_path).map_err(|err| EvidenceReadError { |
| 858 | failure_kind: if err.kind() == std::io::ErrorKind::NotFound { |
| 859 | FleetTaskFailureKind::Task |
| 860 | } else { |
| 861 | FleetTaskFailureKind::Verifier |
| 862 | }, |
| 863 | evidence: format!("cannot read {}: {err}", path.display()), |
| 864 | })?; |
| 865 | if metadata.len() > MAX_SCORER_READ_BYTES { |
| 866 | return Err(EvidenceReadError { |
| 867 | failure_kind: FleetTaskFailureKind::Verifier, |
| 868 | evidence: format!( |
| 869 | "refusing to read oversized evidence {}: {} bytes", |
| 870 | path.display(), |
| 871 | metadata.len() |
| 872 | ), |
| 873 | }); |
| 874 | } |
| 875 | std::fs::read_to_string(&abs_path).map_err(|err| EvidenceReadError { |
| 876 | failure_kind: FleetTaskFailureKind::Verifier, |
| 877 | evidence: format!("cannot decode {} as UTF-8: {err}", path.display()), |
| 878 | }) |
| 879 | } |
| 880 | |
| 881 | fn resolve_workspace_path(workspace: &Path, path: &Path) -> PathBuf { |
| 882 | if path.is_absolute() { |
| 883 | path.to_path_buf() |
| 884 | } else { |
| 885 | workspace.join(path) |
| 886 | } |
| 887 | } |
| 888 | |
| 889 | fn json_path_segments(expression: &str) -> Option<Vec<&str>> { |
| 890 | let trimmed = expression.trim(); |
| 891 | let path = trimmed |
| 892 | .strip_prefix("$.") |
| 893 | .or_else(|| trimmed.strip_prefix('.'))?; |
| 894 | if path.is_empty() { |
| 895 | return None; |
| 896 | } |
| 897 | let segments: Vec<_> = path.split('.').collect(); |
| 898 | if segments.iter().any(|segment| segment.is_empty()) { |
| 899 | return None; |
| 900 | } |
| 901 | Some(segments) |
| 902 | } |
| 903 | |
| 904 | fn json_path_lookup<'a>(value: &'a Value, segments: &[&str]) -> Option<&'a Value> { |
| 905 | let mut current = value; |
| 906 | for segment in segments { |
| 907 | current = current.as_object()?.get(*segment)?; |
| 908 | } |
| 909 | Some(current) |
| 910 | } |
| 911 | |
| 912 | fn json_truthy(value: &Value) -> bool { |
| 913 | !matches!(value, Value::Null | Value::Bool(false)) |
| 914 | } |
| 915 | |
| 916 | fn timestamp() -> String { |
| 917 | Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true) |
| 918 | } |
| 919 | |
| 920 | fn safe_path_segment(value: &str) -> String { |
| 921 | value |
| 922 | .chars() |
| 923 | .map(|ch| { |
| 924 | if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') { |
| 925 | ch |
| 926 | } else { |
| 927 | '_' |
| 928 | } |
| 929 | }) |
| 930 | .collect() |
| 931 | } |
| 932 | |
| 933 | #[cfg(test)] |
| 934 | mod tests { |
| 935 | use super::*; |
| 936 | use serde_json::json; |
| 937 | use tempfile::TempDir; |
| 938 | |
| 939 | fn task(id: &str, scorer: Option<FleetScorerSpec>) -> FleetTaskSpec { |
| 940 | FleetTaskSpec { |
| 941 | id: id.to_string(), |
| 942 | name: id.to_string(), |
| 943 | description: None, |
| 944 | objective: Some(format!("Verify {id}")), |
| 945 | instructions: format!("do {id}"), |
| 946 | worker: Some(FleetTaskWorkerProfile { |
| 947 | provider: None, |
| 948 | agent_profile: None, |
| 949 | role: Some("reviewer".to_string()), |
| 950 | loadout: None, |
| 951 | model_class: None, |
| 952 | model: None, |
| 953 | external_agent: None, |
| 954 | external_agent_transport: None, |
| 955 | tool_profile: Some("read-only".to_string()), |
| 956 | tools: vec!["git".to_string()], |
| 957 | capabilities: vec!["rust".to_string()], |
| 958 | }), |
| 959 | workspace: Some(FleetWorkspaceRequirements { |
| 960 | placement: None, |
| 961 | root: Some(PathBuf::from(".")), |
| 962 | required_files: vec![PathBuf::from("Cargo.toml")], |
| 963 | writable_paths: vec![PathBuf::from(".codewhale/fleet")], |
| 964 | environment: Some(FleetEnvironmentRequirements { |
| 965 | required: vec!["PATH".to_string()], |
| 966 | allowlist: vec!["RUST_LOG".to_string()], |
| 967 | }), |
| 968 | }), |
| 969 | input_files: vec![PathBuf::from("Cargo.toml")], |
| 970 | context: vec!["fleet verifier test".to_string()], |
| 971 | budget: Some(FleetTaskBudget { |
| 972 | max_tokens: Some(4000), |
| 973 | max_steps: None, |
| 974 | max_tool_calls: Some(12), |
| 975 | max_seconds: Some(120), |
| 976 | }), |
| 977 | expected_artifacts: vec![FleetArtifactKind::Log, FleetArtifactKind::Receipt], |
| 978 | scorer, |
| 979 | retry_policy: Some(FleetRetryPolicy::default()), |
| 980 | alert_policy: None, |
| 981 | timeout_seconds: Some(120), |
| 982 | tags: vec!["review".to_string()], |
| 983 | metadata: BTreeMap::new(), |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | #[test] |
| 988 | fn fleet_task_spec_document_parses_multi_task_verified_shape() { |
| 989 | let tmp = TempDir::new().unwrap(); |
| 990 | let path = tmp.path().join("fleet-tasks.json"); |
| 991 | let doc = json!({ |
| 992 | "name": "release triage", |
| 993 | "labels": {"milestone": "v0.8.60"}, |
| 994 | "tasks": [ |
| 995 | task("release-notes", Some(FleetScorerSpec::ExitCode)), |
| 996 | task("risk-review", Some(FleetScorerSpec::Manual)) |
| 997 | ] |
| 998 | }); |
| 999 | std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).unwrap(); |
| 1000 | |
| 1001 | let parsed = load_task_spec_document(&path).unwrap(); |
| 1002 | |
| 1003 | assert_eq!(parsed.name.as_deref(), Some("release triage")); |
| 1004 | assert_eq!(parsed.tasks.len(), 2); |
| 1005 | assert_eq!( |
| 1006 | parsed.tasks[0].objective.as_deref(), |
| 1007 | Some("Verify release-notes") |
| 1008 | ); |
| 1009 | assert_eq!( |
| 1010 | parsed.tasks[0].worker.as_ref().unwrap().role.as_deref(), |
| 1011 | Some("reviewer") |
| 1012 | ); |
| 1013 | assert_eq!(parsed.tasks[1].tags, vec!["review"]); |
| 1014 | } |
| 1015 | |
| 1016 | #[test] |
| 1017 | fn fleet_task_spec_document_parses_worker_profile_loadout_intent() { |
| 1018 | let tmp = TempDir::new().unwrap(); |
| 1019 | let path = tmp.path().join("fleet-profile-task.json"); |
| 1020 | let doc = json!({ |
| 1021 | "name": "profile loadout smoke", |
| 1022 | "tasks": [{ |
| 1023 | "id": "review", |
| 1024 | "name": "review", |
| 1025 | "instructions": "review the patch", |
| 1026 | "worker": { |
| 1027 | "profile": "DeepSeek V4 Flash", |
| 1028 | "role": "reviewer", |
| 1029 | "loadout": "auto", |
| 1030 | "model_class": "balanced", |
| 1031 | "model": "deepseek-v4-pro", |
| 1032 | "tool_profile": "read-only", |
| 1033 | "tools": ["read_file", "grep_files"], |
| 1034 | "capabilities": ["rust"] |
| 1035 | } |
| 1036 | }] |
| 1037 | }); |
| 1038 | std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).unwrap(); |
| 1039 | |
| 1040 | let parsed = load_task_spec_document(&path).unwrap(); |
| 1041 | let worker = parsed.tasks[0].worker.as_ref().unwrap(); |
| 1042 | |
| 1043 | assert_eq!(worker.agent_profile.as_deref(), Some("DeepSeek V4 Flash")); |
| 1044 | assert_eq!(worker.role.as_deref(), Some("reviewer")); |
| 1045 | assert_eq!(worker.loadout.as_deref(), Some("auto")); |
| 1046 | assert_eq!(worker.model_class.as_deref(), Some("balanced")); |
| 1047 | assert_eq!(worker.model.as_deref(), Some("deepseek-v4-pro")); |
| 1048 | assert_eq!(worker.tool_profile.as_deref(), Some("read-only")); |
| 1049 | } |
| 1050 | |
| 1051 | #[test] |
| 1052 | fn fleet_task_spec_rejects_unsafe_worker_profile_intent_tokens() { |
| 1053 | let tmp = TempDir::new().unwrap(); |
| 1054 | let path = tmp.path().join("unsafe-profile-task.json"); |
| 1055 | let doc = json!({ |
| 1056 | "tasks": [{ |
| 1057 | "id": "review", |
| 1058 | "name": "review", |
| 1059 | "instructions": "review the patch", |
| 1060 | "worker": { |
| 1061 | "profile": "reviewer\n../../secrets", |
| 1062 | "loadout": "openrouter/deepseek", |
| 1063 | "model_class": "", |
| 1064 | "model": "deepseek/deepseek-v4-pro" |
| 1065 | } |
| 1066 | }] |
| 1067 | }); |
| 1068 | std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).unwrap(); |
| 1069 | |
| 1070 | let err = load_task_spec_document(&path).unwrap_err().to_string(); |
| 1071 | |
| 1072 | assert!( |
| 1073 | err.contains("worker.agent_profile must be one printable selector"), |
| 1074 | "unexpected error: {err}" |
| 1075 | ); |
| 1076 | } |
| 1077 | |
| 1078 | #[test] |
| 1079 | fn fleet_task_spec_rejects_secret_like_worker_model() { |
| 1080 | let tmp = TempDir::new().unwrap(); |
| 1081 | let path = tmp.path().join("unsafe-worker-model.json"); |
| 1082 | let doc = json!({ |
| 1083 | "tasks": [{ |
| 1084 | "id": "review", |
| 1085 | "name": "review", |
| 1086 | "instructions": "review the patch", |
| 1087 | "worker": { |
| 1088 | "model": "deepseek-v4-pro api_key=secret" |
| 1089 | } |
| 1090 | }] |
| 1091 | }); |
| 1092 | std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).unwrap(); |
| 1093 | |
| 1094 | let err = load_task_spec_document(&path).unwrap_err().to_string(); |
| 1095 | |
| 1096 | assert!( |
| 1097 | err.contains("worker.model must be a visible model id"), |
| 1098 | "unexpected error: {err}" |
| 1099 | ); |
| 1100 | } |
| 1101 | |
| 1102 | #[test] |
| 1103 | fn fleet_task_spec_rejects_unbounded_or_multiline_task_and_worker_identities() { |
| 1104 | let tmp = TempDir::new().unwrap(); |
| 1105 | let path = tmp.path().join("unsafe-identities.json"); |
| 1106 | let doc = json!({ |
| 1107 | "workers": [{ |
| 1108 | "id": "worker\r\nforged", |
| 1109 | "name": "forged worker", |
| 1110 | "host": {"kind": "local"} |
| 1111 | }], |
| 1112 | "tasks": [{ |
| 1113 | "id": "review", |
| 1114 | "name": "review", |
| 1115 | "instructions": "review the patch" |
| 1116 | }] |
| 1117 | }); |
| 1118 | std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).unwrap(); |
| 1119 | |
| 1120 | let err = load_task_spec_document(&path).unwrap_err().to_string(); |
| 1121 | assert!( |
| 1122 | err.contains("worker id must be a simple ASCII token"), |
| 1123 | "unexpected error: {err}" |
| 1124 | ); |
| 1125 | |
| 1126 | let mut doc = task("review", None); |
| 1127 | doc.id = "a".repeat(MAX_FLEET_ID_BYTES + 1); |
| 1128 | let err = validate_task_spec_document(&FleetTaskSpecDocument { |
| 1129 | name: None, |
| 1130 | labels: BTreeMap::new(), |
| 1131 | security_policy: None, |
| 1132 | workers: Vec::new(), |
| 1133 | tasks: vec![doc], |
| 1134 | usage_ceiling: None, |
| 1135 | }) |
| 1136 | .unwrap_err() |
| 1137 | .to_string(); |
| 1138 | assert!( |
| 1139 | err.contains("task id must be a simple ASCII token"), |
| 1140 | "unexpected error: {err}" |
| 1141 | ); |
| 1142 | } |
| 1143 | |
| 1144 | #[test] |
| 1145 | fn fleet_task_spec_rejects_runtime_authority_fields_for_new_runs() { |
| 1146 | let mut security_doc = FleetTaskSpecDocument { |
| 1147 | name: None, |
| 1148 | labels: BTreeMap::new(), |
| 1149 | security_policy: Some(FleetSecurityPolicy::default()), |
| 1150 | workers: Vec::new(), |
| 1151 | tasks: vec![task("review", None)], |
| 1152 | usage_ceiling: None, |
| 1153 | }; |
| 1154 | let error = validate_task_spec_document(&security_doc) |
| 1155 | .unwrap_err() |
| 1156 | .to_string(); |
| 1157 | assert!( |
| 1158 | error.contains("security_policy is a legacy compatibility field"), |
| 1159 | "unexpected error: {error}" |
| 1160 | ); |
| 1161 | |
| 1162 | security_doc.security_policy = None; |
| 1163 | security_doc.workers.push(FleetWorkerSpec { |
| 1164 | environment: None, |
| 1165 | id: "worker-1".to_string(), |
| 1166 | name: "Worker 1".to_string(), |
| 1167 | host: FleetHostSpec::Local, |
| 1168 | trust_level: Some(FleetTrustLevel::Local), |
| 1169 | labels: BTreeMap::new(), |
| 1170 | capabilities: vec!["local".to_string()], |
| 1171 | max_concurrent_tasks: Some(1), |
| 1172 | }); |
| 1173 | let error = validate_task_spec_document(&security_doc) |
| 1174 | .unwrap_err() |
| 1175 | .to_string(); |
| 1176 | assert!( |
| 1177 | error.contains("trust_level is a legacy compatibility field"), |
| 1178 | "unexpected error: {error}" |
| 1179 | ); |
| 1180 | } |
| 1181 | |
| 1182 | #[cfg(unix)] |
| 1183 | #[test] |
| 1184 | fn fleet_artifact_publication_rejects_symlinked_workspace_paths() { |
| 1185 | use std::os::unix::fs::symlink; |
| 1186 | let workspace = TempDir::new().unwrap(); |
| 1187 | let outside = TempDir::new().unwrap(); |
| 1188 | std::fs::create_dir_all(workspace.path().join(".codewhale")).unwrap(); |
| 1189 | symlink(outside.path(), workspace.path().join(".codewhale/fleet")).unwrap(); |
| 1190 | let result = write_fleet_artifact_ref( |
| 1191 | workspace.path(), |
| 1192 | &FleetRunId::from("run-1"), |
| 1193 | "task-a", |
| 1194 | "worker-1", |
| 1195 | FleetArtifactKind::Receipt, |
| 1196 | "receipt.json", |
| 1197 | b"synthetic receipt", |
| 1198 | Some("application/json"), |
| 1199 | ); |
| 1200 | assert!( |
| 1201 | result.is_err(), |
| 1202 | "publication must reject a symlinked parent" |
| 1203 | ); |
| 1204 | assert!(!outside.path().join("run-1").exists()); |
| 1205 | } |
| 1206 | |
| 1207 | #[test] |
| 1208 | fn fleet_task_spec_artifact_refs_are_bounded_paths() { |
| 1209 | let tmp = TempDir::new().unwrap(); |
| 1210 | let artifact = write_fleet_artifact_ref( |
| 1211 | tmp.path(), |
| 1212 | &FleetRunId::from("run-1"), |
| 1213 | "task-a", |
| 1214 | "worker-1", |
| 1215 | FleetArtifactKind::Log, |
| 1216 | "worker.log", |
| 1217 | b"this is artifact content", |
| 1218 | Some("text/plain"), |
| 1219 | ) |
| 1220 | .unwrap(); |
| 1221 | |
| 1222 | let json = serde_json::to_string(&artifact).unwrap(); |
| 1223 | assert!(!json.contains("this is artifact content")); |
| 1224 | assert!(json.contains("worker.log")); |
| 1225 | assert_eq!(artifact.size_bytes, Some(24)); |
| 1226 | assert!(artifact.checksum.as_deref().unwrap().starts_with("sha256:")); |
| 1227 | assert!(tmp.path().join(&artifact.path).exists()); |
| 1228 | } |
| 1229 | |
| 1230 | #[test] |
| 1231 | fn fleet_task_spec_scorers_record_pass_fail_partial_evidence() { |
| 1232 | let tmp = TempDir::new().unwrap(); |
| 1233 | std::fs::write(tmp.path().join("result.txt"), "status=ok\n").unwrap(); |
| 1234 | std::fs::write(tmp.path().join("result.json"), r#"{"status":"ok"}"#).unwrap(); |
| 1235 | let input = FleetTaskVerificationInput { |
| 1236 | run_id: FleetRunId::from("run-1"), |
| 1237 | task_id: "task-a".to_string(), |
| 1238 | worker_id: "worker-1".to_string(), |
| 1239 | attempt: 1, |
| 1240 | exit_code: Some(0), |
| 1241 | artifacts: vec![], |
| 1242 | final_answer: None, |
| 1243 | saved_session_id: None, |
| 1244 | resolved_route: None, |
| 1245 | effective_permissions: None, |
| 1246 | }; |
| 1247 | |
| 1248 | let pass = verify_task_result( |
| 1249 | tmp.path(), |
| 1250 | &task("exit", Some(FleetScorerSpec::ExitCode)), |
| 1251 | &input, |
| 1252 | ); |
| 1253 | assert_eq!(pass.result, FleetTaskResult::Pass); |
| 1254 | assert_eq!(pass.failure_kind, None); |
| 1255 | |
| 1256 | let regex = verify_task_result( |
| 1257 | tmp.path(), |
| 1258 | &task( |
| 1259 | "regex", |
| 1260 | Some(FleetScorerSpec::RegexMatch { |
| 1261 | path: PathBuf::from("result.txt"), |
| 1262 | pattern: "status=ok".to_string(), |
| 1263 | }), |
| 1264 | ), |
| 1265 | &input, |
| 1266 | ); |
| 1267 | assert_eq!(regex.result, FleetTaskResult::Pass); |
| 1268 | |
| 1269 | let json_path = verify_task_result( |
| 1270 | tmp.path(), |
| 1271 | &task( |
| 1272 | "json", |
| 1273 | Some(FleetScorerSpec::JsonPath { |
| 1274 | path: PathBuf::from("result.json"), |
| 1275 | expression: "$.status".to_string(), |
| 1276 | }), |
| 1277 | ), |
| 1278 | &input, |
| 1279 | ); |
| 1280 | assert_eq!(json_path.result, FleetTaskResult::Pass); |
| 1281 | |
| 1282 | let manual = verify_task_result( |
| 1283 | tmp.path(), |
| 1284 | &task("manual", Some(FleetScorerSpec::Manual)), |
| 1285 | &input, |
| 1286 | ); |
| 1287 | assert_eq!(manual.result, FleetTaskResult::Partial); |
| 1288 | |
| 1289 | let no_scorer_empty = verify_task_result(tmp.path(), &task("unscored", None), &input); |
| 1290 | assert_eq!(no_scorer_empty.result, FleetTaskResult::Partial); |
| 1291 | assert!( |
| 1292 | no_scorer_empty |
| 1293 | .score |
| 1294 | .notes |
| 1295 | .as_deref() |
| 1296 | .unwrap_or_default() |
| 1297 | .contains("no verifiable output") |
| 1298 | ); |
| 1299 | |
| 1300 | let failed = verify_task_result( |
| 1301 | tmp.path(), |
| 1302 | &task( |
| 1303 | "missing", |
| 1304 | Some(FleetScorerSpec::FileExists { |
| 1305 | path: PathBuf::from("missing.txt"), |
| 1306 | }), |
| 1307 | ), |
| 1308 | &input, |
| 1309 | ); |
| 1310 | assert_eq!(failed.result, FleetTaskResult::Fail); |
| 1311 | assert_eq!(failed.failure_kind, Some(FleetTaskFailureKind::Task)); |
| 1312 | |
| 1313 | let verifier_failed = verify_task_result( |
| 1314 | tmp.path(), |
| 1315 | &task( |
| 1316 | "bad-regex", |
| 1317 | Some(FleetScorerSpec::RegexMatch { |
| 1318 | path: PathBuf::from("result.txt"), |
| 1319 | pattern: "[".to_string(), |
| 1320 | }), |
| 1321 | ), |
| 1322 | &input, |
| 1323 | ); |
| 1324 | assert_eq!(verifier_failed.result, FleetTaskResult::Fail); |
| 1325 | assert_eq!( |
| 1326 | verifier_failed.failure_kind, |
| 1327 | Some(FleetTaskFailureKind::Verifier) |
| 1328 | ); |
| 1329 | } |
| 1330 | |
| 1331 | #[test] |
| 1332 | fn unscored_worker_surfaces_summary_deliverable_instead_of_no_output() { |
| 1333 | let tmp = TempDir::new().unwrap(); |
| 1334 | let input = FleetTaskVerificationInput { |
| 1335 | run_id: FleetRunId::from("run-1"), |
| 1336 | task_id: "task-a".to_string(), |
| 1337 | worker_id: "worker-1".to_string(), |
| 1338 | attempt: 1, |
| 1339 | exit_code: Some(0), |
| 1340 | artifacts: vec![], |
| 1341 | final_answer: Some(FleetWorkerFinalAnswer { |
| 1342 | excerpt: "The Changelog review is complete".to_string(), |
| 1343 | chars: 32, |
| 1344 | }), |
| 1345 | saved_session_id: None, |
| 1346 | resolved_route: None, |
| 1347 | effective_permissions: None, |
| 1348 | }; |
| 1349 | let verification = verify_task_result(tmp.path(), &task("unscored", None), &input); |
| 1350 | assert_eq!(verification.result, FleetTaskResult::Partial); |
| 1351 | let notes = verification |
| 1352 | .score |
| 1353 | .notes |
| 1354 | .as_deref() |
| 1355 | .unwrap_or_default() |
| 1356 | .to_string(); |
| 1357 | assert!( |
| 1358 | notes.contains("worker produced 32 characters of deliverable"), |
| 1359 | "unexpected notes: {notes}" |
| 1360 | ); |
| 1361 | assert!(notes.contains("Changelog review is complete")); |
| 1362 | assert!(!notes.contains("no verifiable output")); |
| 1363 | } |
| 1364 | |
| 1365 | #[test] |
| 1366 | fn fleet_task_spec_receipt_records_artifacts_scores_and_failure_kind() { |
| 1367 | let tmp = TempDir::new().unwrap(); |
| 1368 | let ledger = FleetLedger::open(tmp.path()).unwrap(); |
| 1369 | let log = write_fleet_artifact_ref( |
| 1370 | tmp.path(), |
| 1371 | &FleetRunId::from("run-1"), |
| 1372 | "task-a", |
| 1373 | "worker-1", |
| 1374 | FleetArtifactKind::Log, |
| 1375 | "worker.log", |
| 1376 | b"exit_code=1", |
| 1377 | Some("text/plain"), |
| 1378 | ) |
| 1379 | .unwrap(); |
| 1380 | let input = FleetTaskVerificationInput { |
| 1381 | run_id: FleetRunId::from("run-1"), |
| 1382 | task_id: "task-a".to_string(), |
| 1383 | worker_id: "worker-1".to_string(), |
| 1384 | attempt: 3, |
| 1385 | exit_code: Some(1), |
| 1386 | artifacts: vec![log], |
| 1387 | final_answer: None, |
| 1388 | saved_session_id: None, |
| 1389 | resolved_route: None, |
| 1390 | effective_permissions: Some(FleetEffectivePermissions { |
| 1391 | write: false, |
| 1392 | network: false, |
| 1393 | shell: "read_only".to_string(), |
| 1394 | tool_scope: "explicit".to_string(), |
| 1395 | tools: vec!["read_file".to_string()], |
| 1396 | background: true, |
| 1397 | max_spawn_depth: 0, |
| 1398 | profile_id: None, |
| 1399 | profile_origin: None, |
| 1400 | source: "worker_runtime_profile".to_string(), |
| 1401 | }), |
| 1402 | }; |
| 1403 | let verification = verify_task_result( |
| 1404 | tmp.path(), |
| 1405 | &task("task-a", Some(FleetScorerSpec::ExitCode)), |
| 1406 | &input, |
| 1407 | ); |
| 1408 | |
| 1409 | let receipt = |
| 1410 | record_verification_receipt(&ledger, tmp.path(), &input, verification).unwrap(); |
| 1411 | |
| 1412 | assert_eq!(receipt.result, FleetTaskResult::Fail); |
| 1413 | assert_eq!(receipt.failure_kind, Some(FleetTaskFailureKind::Task)); |
| 1414 | assert_eq!(receipt.attempt, Some(3)); |
| 1415 | assert_eq!(receipt.terminal_seq, None); |
| 1416 | assert_eq!(receipt.effective_permissions, input.effective_permissions); |
| 1417 | assert_eq!(receipt.artifacts.len(), 2); |
| 1418 | assert!(matches!( |
| 1419 | receipt.artifacts.last().unwrap().kind, |
| 1420 | FleetArtifactKind::Receipt |
| 1421 | )); |
| 1422 | assert!( |
| 1423 | receipt |
| 1424 | .artifacts |
| 1425 | .last() |
| 1426 | .unwrap() |
| 1427 | .path |
| 1428 | .to_string_lossy() |
| 1429 | .contains("verification-receipt-attempt-0000000003-") |
| 1430 | ); |
| 1431 | let state = ledger.rebuild_state().unwrap(); |
| 1432 | assert_eq!( |
| 1433 | state.receipts["run-1:task-a"].failure_kind, |
| 1434 | Some(FleetTaskFailureKind::Task) |
| 1435 | ); |
| 1436 | } |
| 1437 | |
| 1438 | #[test] |
| 1439 | fn verification_evidence_is_attempt_and_content_addressed() { |
| 1440 | let tmp = TempDir::new().unwrap(); |
| 1441 | let mut input = FleetTaskVerificationInput { |
| 1442 | run_id: FleetRunId::from("run-1"), |
| 1443 | task_id: "task-a".to_string(), |
| 1444 | worker_id: "worker-1".to_string(), |
| 1445 | attempt: 1, |
| 1446 | exit_code: Some(1), |
| 1447 | artifacts: Vec::new(), |
| 1448 | final_answer: None, |
| 1449 | saved_session_id: None, |
| 1450 | resolved_route: None, |
| 1451 | effective_permissions: None, |
| 1452 | }; |
| 1453 | let scorer = task("task-a", Some(FleetScorerSpec::ExitCode)); |
| 1454 | let stale_verification = verify_task_result(tmp.path(), &scorer, &input); |
| 1455 | let stale = prepare_verification_receipt(tmp.path(), &input, stale_verification).unwrap(); |
| 1456 | |
| 1457 | input.attempt = 2; |
| 1458 | input.exit_code = Some(0); |
| 1459 | let winning_verification = verify_task_result(tmp.path(), &scorer, &input); |
| 1460 | let winning = |
| 1461 | prepare_verification_receipt(tmp.path(), &input, winning_verification).unwrap(); |
| 1462 | |
| 1463 | let stale_path = &stale.artifacts.last().unwrap().path; |
| 1464 | let winning_path = &winning.artifacts.last().unwrap().path; |
| 1465 | assert_ne!(stale_path, winning_path); |
| 1466 | assert!(stale_path.to_string_lossy().contains("attempt-0000000001-")); |
| 1467 | assert!( |
| 1468 | winning_path |
| 1469 | .to_string_lossy() |
| 1470 | .contains("attempt-0000000002-") |
| 1471 | ); |
| 1472 | assert!(tmp.path().join(stale_path).is_file()); |
| 1473 | assert!(tmp.path().join(winning_path).is_file()); |
| 1474 | assert_eq!(stale.result, FleetTaskResult::Fail); |
| 1475 | assert_eq!(winning.result, FleetTaskResult::Pass); |
| 1476 | } |
| 1477 | |
| 1478 | fn load_error(file_name: &str, body: &str) -> String { |
| 1479 | let tmp = TempDir::new().unwrap(); |
| 1480 | let path = tmp.path().join(file_name); |
| 1481 | std::fs::write(&path, body).unwrap(); |
| 1482 | let err = load_task_spec_document(&path).expect_err("spec should be rejected"); |
| 1483 | format!("{err:#}") |
| 1484 | } |
| 1485 | |
| 1486 | #[test] |
| 1487 | fn fleet_task_spec_document_shape_error_names_missing_field_and_task() { |
| 1488 | let err = load_error( |
| 1489 | "doc.json", |
| 1490 | r#"{"name": "n", "tasks": [ |
| 1491 | {"id": "ok", "name": "ok", "instructions": "do it"}, |
| 1492 | {"id": "review", "name": "review"} |
| 1493 | ]}"#, |
| 1494 | ); |
| 1495 | assert!(!err.contains("untagged enum"), "{err}"); |
| 1496 | assert!(err.contains("JSON spec document"), "{err}"); |
| 1497 | assert!(err.contains("missing field `instructions`"), "{err}"); |
| 1498 | assert!(err.contains(r#"tasks[1] (id "review")"#), "{err}"); |
| 1499 | } |
| 1500 | |
| 1501 | #[test] |
| 1502 | fn fleet_task_spec_task_array_shape_error_names_missing_field() { |
| 1503 | let err = load_error("tasks.json", r#"[{"id": "a", "instructions": "do it"}]"#); |
| 1504 | assert!(!err.contains("untagged enum"), "{err}"); |
| 1505 | assert!(err.contains("JSON task array"), "{err}"); |
| 1506 | assert!(err.contains("missing field `name`"), "{err}"); |
| 1507 | assert!(err.contains(r#"[0] (id "a")"#), "{err}"); |
| 1508 | } |
| 1509 | |
| 1510 | #[test] |
| 1511 | fn fleet_task_spec_single_task_shape_error_names_missing_field() { |
| 1512 | let err = load_error("one.json", r#"{"id": "a", "name": "a"}"#); |
| 1513 | assert!(!err.contains("untagged enum"), "{err}"); |
| 1514 | assert!(err.contains("JSON single task"), "{err}"); |
| 1515 | assert!(err.contains("missing field `instructions`"), "{err}"); |
| 1516 | } |
| 1517 | |
| 1518 | #[test] |
| 1519 | fn fleet_task_spec_toml_document_error_names_missing_field() { |
| 1520 | let err = load_error( |
| 1521 | "doc.toml", |
| 1522 | "name = \"n\"\n\n[[tasks]]\nid = \"a\"\ninstructions = \"do it\"\n", |
| 1523 | ); |
| 1524 | assert!(!err.contains("untagged enum"), "{err}"); |
| 1525 | assert!(err.contains("TOML spec document"), "{err}"); |
| 1526 | assert!(err.contains("missing field `name`"), "{err}"); |
| 1527 | assert!(err.contains(r#"tasks[0] (id "a")"#), "{err}"); |
| 1528 | } |
| 1529 | |
| 1530 | #[test] |
| 1531 | fn fleet_task_spec_rejects_scalar_top_level_with_shape_hint() { |
| 1532 | let err = load_error("scalar.json", "\"just a string\""); |
| 1533 | assert!(err.contains("found a string"), "{err}"); |
| 1534 | assert!(err.contains("array of task objects"), "{err}"); |
| 1535 | } |
| 1536 | |
| 1537 | #[test] |
| 1538 | fn fleet_task_spec_single_and_array_shapes_load_with_fallback_name() { |
| 1539 | let tmp = TempDir::new().unwrap(); |
| 1540 | let single = tmp.path().join("solo.json"); |
| 1541 | std::fs::write( |
| 1542 | &single, |
| 1543 | r#"{"id": "a", "name": "a", "instructions": "do it"}"#, |
| 1544 | ) |
| 1545 | .unwrap(); |
| 1546 | let doc = load_task_spec_document(&single).unwrap(); |
| 1547 | assert_eq!(doc.name.as_deref(), Some("solo")); |
| 1548 | assert_eq!(doc.tasks.len(), 1); |
| 1549 | |
| 1550 | let array = tmp.path().join("pair.json"); |
| 1551 | std::fs::write( |
| 1552 | &array, |
| 1553 | r#"[{"id": "a", "name": "a", "instructions": "x"}, |
| 1554 | {"id": "b", "name": "b", "instructions": "y"}]"#, |
| 1555 | ) |
| 1556 | .unwrap(); |
| 1557 | let doc = load_task_spec_document(&array).unwrap(); |
| 1558 | assert_eq!(doc.name.as_deref(), Some("pair")); |
| 1559 | assert_eq!(doc.tasks.len(), 2); |
| 1560 | } |
| 1561 | |
| 1562 | #[test] |
| 1563 | fn fleet_task_spec_toml_single_task_loads_with_fallback_name() { |
| 1564 | let tmp = TempDir::new().unwrap(); |
| 1565 | let path = tmp.path().join("solo.toml"); |
| 1566 | std::fs::write( |
| 1567 | &path, |
| 1568 | "id = \"a\"\nname = \"a\"\ninstructions = \"do it\"\n", |
| 1569 | ) |
| 1570 | .unwrap(); |
| 1571 | let doc = load_task_spec_document(&path).unwrap(); |
| 1572 | assert_eq!(doc.name.as_deref(), Some("solo")); |
| 1573 | assert_eq!(doc.tasks.len(), 1); |
| 1574 | } |
| 1575 | |
| 1576 | fn repo_doc(relative: &str) -> PathBuf { |
| 1577 | Path::new(env!("CARGO_MANIFEST_DIR")) |
| 1578 | .join("../..") |
| 1579 | .join(relative) |
| 1580 | } |
| 1581 | |
| 1582 | #[test] |
| 1583 | fn fleet_dogfood_example_spec_parses_and_validates() { |
| 1584 | let doc = load_task_spec_document(&repo_doc("docs/examples/fleet-dogfood.toml")) |
| 1585 | .expect("docs/examples/fleet-dogfood.toml must stay a valid fleet spec"); |
| 1586 | assert_eq!(doc.name.as_deref(), Some("dogfood smoke")); |
| 1587 | let ids: Vec<_> = doc.tasks.iter().map(|task| task.id.as_str()).collect(); |
| 1588 | assert_eq!(ids, ["cargo-check", "protocol-review"]); |
| 1589 | } |
| 1590 | |
| 1591 | #[test] |
| 1592 | fn fleet_workflow_tutorial_json_spec_parses_and_validates() { |
| 1593 | let tutorial = std::fs::read_to_string(repo_doc("docs/FLEET_WORKFLOW_TUTORIAL.md")) |
| 1594 | .expect("read fleet tutorial"); |
| 1595 | let start = tutorial |
| 1596 | .find("```json\n") |
| 1597 | .expect("tutorial should carry a JSON task spec") |
| 1598 | + "```json\n".len(); |
| 1599 | let end = start + tutorial[start..].find("```").expect("closed JSON fence"); |
| 1600 | let tmp = TempDir::new().unwrap(); |
| 1601 | let path = tmp.path().join("tasks.json"); |
| 1602 | std::fs::write(&path, &tutorial[start..end]).unwrap(); |
| 1603 | let doc = load_task_spec_document(&path) |
| 1604 | .expect("the tutorial's tasks.json must stay a valid fleet spec"); |
| 1605 | assert_eq!(doc.name.as_deref(), Some("docs readiness check")); |
| 1606 | assert_eq!(doc.tasks.len(), 2); |
| 1607 | } |
| 1608 | } |
| 1609 |