| 1 | //! Typed Workflow IR and validation for CodeWhale. |
| 2 | //! |
| 3 | //! This crate deliberately stops at the Rust-owned IR boundary. Runtime tool |
| 4 | //! exposure, worktree application, replay, and model execution are layered on |
| 5 | //! top only after their cancellation and evidence semantics are proven. |
| 6 | |
| 7 | pub mod elevation; |
| 8 | /// Setup-time Fleet composition: a suggestion schema with no runtime authority. |
| 9 | /// |
| 10 | /// Deliberately **not** re-exported from the crate root. The setup wizard uses |
| 11 | /// it by its explicit module path |
| 12 | /// (`codewhale_workflow::fleet_composition::…`), keeping the advisory boundary |
| 13 | /// visible instead of making the schema look like runtime Fleet authority. |
| 14 | pub mod fleet_composition; |
| 15 | pub mod fleet_exact; |
| 16 | pub mod fleet_preflight; |
| 17 | pub mod fleet_reasoning; |
| 18 | pub mod fleet_snapshot; |
| 19 | mod gates; |
| 20 | mod js_authoring; |
| 21 | mod named_fleet; |
| 22 | pub mod reasoning_router; |
| 23 | pub mod redaction; |
| 24 | mod role_resolve; |
| 25 | |
| 26 | use std::collections::BTreeSet; |
| 27 | |
| 28 | use serde::{Deserialize, Serialize}; |
| 29 | use thiserror::Error; |
| 30 | |
| 31 | pub use elevation::{ |
| 32 | ElevationOptions, PlanRiskHint, ToolAuthority, WorkflowPlanElevation, assess_plan_risk_string, |
| 33 | assess_workflow_elevation, is_shell_tool, is_write_tool, tool_name_authority, |
| 34 | }; |
| 35 | pub use fleet_exact::{ |
| 36 | EXACT_FLEET_SCHEMA_KIND, EXACT_FLEET_SCHEMA_REVISION, ExactFleet, ExactFleetError, ExactMember, |
| 37 | FrozenRoute, LEGACY_FLEET_SCHEMA_KIND, ROLE_ALIASES, ROUTER_PUBLIC_ID, ROUTER_PUBLIC_ROLE, |
| 38 | ReasoningTier, RequestedReasoning, RouterMember, canonical_member_key, canonical_role_key, |
| 39 | }; |
| 40 | pub use fleet_preflight::{ |
| 41 | CredentialReadiness, EndpointIdentity, PreflightError, PreflightedRoute, RoutePreflight, |
| 42 | }; |
| 43 | pub use fleet_reasoning::{ |
| 44 | EffectiveReasoning, EffectiveReasoningSource, FAITHFUL_WIRE_TIERS, FleetTaskReceipt, |
| 45 | ProviderEffectiveReasoning, ProviderReasoningControl, ROUTER_CALL_REASONING, |
| 46 | ROUTER_MAX_OUTPUT_TOKENS, ROUTER_REASONING_FIELD, ROUTER_SUMMARY_MAX_CHARS, ROUTING_SCOPE, |
| 47 | ReasoningCapability, ReasoningResolveError, ResolvedReasoning, RouterAvailability, |
| 48 | RouterCallDisclosure, RouterCallInput, RouterCallPlan, RouterDecision, RouterDecisionError, |
| 49 | RouterIdentity, RoutingDisclosure, RoutingPayload, TaskShape, bounded_routing_payload, |
| 50 | parse_router_decision, resolve_exact_member_reasoning, resolve_legacy_reasoning, |
| 51 | router_call_plan, router_system_prompt, router_user_message, transport_disclosure, |
| 52 | }; |
| 53 | pub use fleet_snapshot::{ |
| 54 | FleetSnapshot, FleetSnapshotLegacyRole, FleetSnapshotMember, FleetSnapshotRouter, |
| 55 | QualifiedFleetId, captured_legacy_inline_router, verify_snapshot_content_hash, |
| 56 | }; |
| 57 | pub use gates::{ |
| 58 | GateError, GateKind, GateOn, GateOnFail, GateOutcome, GateSpec, GateState, GateStatusLine, |
| 59 | HandoffArtifact, LaneGateBoard, stopship_gate_pipeline, |
| 60 | }; |
| 61 | pub use js_authoring::{ |
| 62 | JavascriptWorkflowError, JavascriptWorkflowResult, compile_javascript_workflow, |
| 63 | compile_typescript_workflow, |
| 64 | }; |
| 65 | pub use named_fleet::{ |
| 66 | FleetDocument, FleetFileReader, FleetSchema, FleetSearchRoot, NamedFleet, NamedFleetError, |
| 67 | STOPSHIP_REQUIRED_ROLES, exact_schema_revision, load_named_fleet, load_named_fleet_file, |
| 68 | parse_named_fleet, split_qualified_fleet_name, validate_fleet_file_stem, |
| 69 | }; |
| 70 | pub use reasoning_router::{ |
| 71 | CapturedReasoningRouter, FleetRouterRef, LEGACY_INLINE_ROUTER_ORIGIN, QualifiedRouterId, |
| 72 | REASONING_ROUTER_DIR, REASONING_ROUTER_SCHEMA_KIND, REASONING_ROUTER_SERVICE_KIND, |
| 73 | ReasoningRouterError, ReasoningRouterProfile, RouterCallReasoning, |
| 74 | }; |
| 75 | pub use redaction::{ |
| 76 | REDACTION_ABSOLUTE_PATH, REDACTION_RELATIVE_PATH, REDACTION_SECRET, Redaction, |
| 77 | redact_for_disclosure, |
| 78 | }; |
| 79 | pub use role_resolve::{ |
| 80 | FleetRoleMap, FleetRoleResolveError, ResolvedWorkflowAgent, normalize_token, |
| 81 | resolve_workflow_agent, validate_role_token, |
| 82 | }; |
| 83 | |
| 84 | /// Default hard ceiling on total agents a Fleet-shaped Workflow plan may launch. |
| 85 | /// Zero leaves the total number of agents uncapped. |
| 86 | pub const DEFAULT_FLEET_WORKFLOW_MAX_AGENTS: usize = 0; |
| 87 | pub const DEFAULT_FLEET_WORKFLOW_MAX_DEPTH: usize = 0; |
| 88 | |
| 89 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 90 | pub struct WorkflowSpec { |
| 91 | #[serde(default)] |
| 92 | pub id: Option<String>, |
| 93 | pub goal: String, |
| 94 | #[serde(default)] |
| 95 | pub description: Option<String>, |
| 96 | #[serde(default)] |
| 97 | pub budget: BudgetSpec, |
| 98 | #[serde(default)] |
| 99 | pub permissions: PermissionSpec, |
| 100 | #[serde(default)] |
| 101 | pub model_policy: ModelPolicy, |
| 102 | /// Workflow-owned role gates and handoffs (#4179). Fleet supplies roles; |
| 103 | /// gate semantics stay attached to the Workflow definition. |
| 104 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 105 | pub gates: Vec<GateSpec>, |
| 106 | #[serde(default)] |
| 107 | pub nodes: Vec<WorkflowNode>, |
| 108 | } |
| 109 | |
| 110 | impl WorkflowSpec { |
| 111 | pub fn validate_for_fleet(&self) -> Result<WorkflowFleetShape, WorkflowFleetLimitError> { |
| 112 | self.validate_for_fleet_with_limits(WorkflowFleetLimits::default()) |
| 113 | } |
| 114 | |
| 115 | pub fn validate_for_fleet_with_limits( |
| 116 | &self, |
| 117 | limits: WorkflowFleetLimits, |
| 118 | ) -> Result<WorkflowFleetShape, WorkflowFleetLimitError> { |
| 119 | let shape = estimate_fleet_shape(&self.nodes, limits)?; |
| 120 | validate_workflow_nodes(&self.nodes) |
| 121 | .map_err(|source| WorkflowFleetLimitError::InvalidWorkflow { source })?; |
| 122 | if limits.max_total_agents > 0 && shape.total_agents > limits.max_total_agents { |
| 123 | return Err(WorkflowFleetLimitError::TooManyAgents { |
| 124 | total_agents: shape.total_agents, |
| 125 | max_total_agents: limits.max_total_agents, |
| 126 | }); |
| 127 | } |
| 128 | Ok(shape) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 133 | #[serde(tag = "kind", content = "spec", rename_all = "snake_case")] |
| 134 | pub enum WorkflowNode { |
| 135 | BranchSet(BranchSpec), |
| 136 | Leaf(LeafSpec), |
| 137 | Sequence(SequenceSpec), |
| 138 | Reduce(ReduceSpec), |
| 139 | } |
| 140 | |
| 141 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 142 | pub struct BranchSpec { |
| 143 | pub id: String, |
| 144 | #[serde(default)] |
| 145 | pub description: Option<String>, |
| 146 | #[serde(default)] |
| 147 | pub parallel: bool, |
| 148 | #[serde(default)] |
| 149 | pub budget: BudgetSpec, |
| 150 | #[serde(default)] |
| 151 | pub permissions: PermissionSpec, |
| 152 | #[serde(default)] |
| 153 | pub model_policy: ModelPolicy, |
| 154 | #[serde(default)] |
| 155 | pub children: Vec<WorkflowNode>, |
| 156 | } |
| 157 | |
| 158 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 159 | pub struct LeafSpec { |
| 160 | pub id: String, |
| 161 | pub prompt: String, |
| 162 | #[serde(default)] |
| 163 | pub agent_type: AgentType, |
| 164 | /// Fleet role this step should run as (e.g. `scout`, `implementer`). |
| 165 | /// Resolved via the fleet roster at dispatch time (#4177). Preferred |
| 166 | /// identity field for workflow steps; `profile` remains an explicit |
| 167 | /// AgentProfile override. Provider/model live on [`ModelPolicy`] as |
| 168 | /// optional overrides — they are **not** required identity fields. |
| 169 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 170 | pub role: Option<String>, |
| 171 | /// Named Fleet roster profile this agent should run as. Resolved against |
| 172 | /// the saved Fleet roster at dispatch time; unknown names fail validation |
| 173 | /// before any spawn. When set, role/model/loadout defaults come from the |
| 174 | /// roster member; explicit fields on this spec override the profile. |
| 175 | /// Precedence over `role` when both are set (#4177 / #4111). |
| 176 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 177 | pub profile: Option<String>, |
| 178 | #[serde(default)] |
| 179 | pub mode: TaskMode, |
| 180 | #[serde(default)] |
| 181 | pub isolation: IsolationMode, |
| 182 | #[serde(default)] |
| 183 | pub file_scope: Vec<String>, |
| 184 | /// Optional child working directory, repository-relative like |
| 185 | /// `task({cwd})`. Disambiguates multi-repo workspaces (#6232). |
| 186 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 187 | pub cwd: Option<String>, |
| 188 | #[serde(default)] |
| 189 | pub depends_on_results: Vec<String>, |
| 190 | #[serde(default)] |
| 191 | pub budget: BudgetSpec, |
| 192 | #[serde(default)] |
| 193 | pub permissions: PermissionSpec, |
| 194 | #[serde(default)] |
| 195 | pub model_policy: ModelPolicy, |
| 196 | } |
| 197 | |
| 198 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 199 | pub struct SequenceSpec { |
| 200 | pub id: String, |
| 201 | #[serde(default)] |
| 202 | pub children: Vec<WorkflowNode>, |
| 203 | } |
| 204 | |
| 205 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 206 | pub struct ReduceSpec { |
| 207 | pub id: String, |
| 208 | #[serde(default)] |
| 209 | pub inputs: Vec<String>, |
| 210 | pub prompt: String, |
| 211 | #[serde(default)] |
| 212 | pub model_policy: ModelPolicy, |
| 213 | } |
| 214 | |
| 215 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 216 | pub struct BudgetSpec { |
| 217 | #[serde(default)] |
| 218 | pub max_steps: Option<u32>, |
| 219 | #[serde(default)] |
| 220 | pub timeout_secs: Option<u64>, |
| 221 | #[serde(default)] |
| 222 | pub max_parallel: Option<u8>, |
| 223 | #[serde(default)] |
| 224 | pub max_tokens: Option<u64>, |
| 225 | } |
| 226 | |
| 227 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 228 | pub struct PermissionSpec { |
| 229 | #[serde(default)] |
| 230 | pub allow_write: bool, |
| 231 | #[serde(default)] |
| 232 | pub allow_network: bool, |
| 233 | /// Expose no tools to the child. This is distinct from an empty |
| 234 | /// `allowed_tools` list, which preserves the role's default tool surface. |
| 235 | #[serde(default)] |
| 236 | pub deny_all_tools: bool, |
| 237 | #[serde(default)] |
| 238 | pub allowed_tools: Vec<String>, |
| 239 | #[serde(default)] |
| 240 | pub file_scope: Vec<String>, |
| 241 | } |
| 242 | |
| 243 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 244 | pub struct ModelPolicy { |
| 245 | #[serde(default)] |
| 246 | pub provider: Option<String>, |
| 247 | #[serde(default)] |
| 248 | pub model: Option<String>, |
| 249 | #[serde(default)] |
| 250 | pub fallback_models: Vec<String>, |
| 251 | } |
| 252 | |
| 253 | /// The workflow wire's agent type. The serialized spellings are the canonical |
| 254 | /// Codewhale role vocabulary (founder, 2026-09-02); the pre-rename JS |
| 255 | /// spellings stay accepted as aliases so checked-in and saved workflows keep |
| 256 | /// compiling. |
| 257 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 258 | #[serde(rename_all = "snake_case")] |
| 259 | pub enum AgentType { |
| 260 | #[default] |
| 261 | General, |
| 262 | #[serde(alias = "scout")] |
| 263 | Explore, |
| 264 | #[serde(rename = "planner", alias = "plan", alias = "awaiter")] |
| 265 | Plan, |
| 266 | #[serde( |
| 267 | alias = "review", |
| 268 | alias = "reviewer", |
| 269 | alias = "consultant", |
| 270 | alias = "oracle" |
| 271 | )] |
| 272 | Review, |
| 273 | #[serde(rename = "implement", alias = "implementer", alias = "builder")] |
| 274 | Implementer, |
| 275 | #[serde(rename = "test", alias = "verifier", alias = "verify")] |
| 276 | Verifier, |
| 277 | } |
| 278 | |
| 279 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 280 | #[serde(rename_all = "snake_case")] |
| 281 | pub enum TaskMode { |
| 282 | #[default] |
| 283 | ReadOnly, |
| 284 | ReadWrite, |
| 285 | } |
| 286 | |
| 287 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 288 | #[serde(rename_all = "snake_case")] |
| 289 | pub enum IsolationMode { |
| 290 | /// Runtime chooses isolation. |
| 291 | /// |
| 292 | /// Parallel write-capable children resolve to [`IsolationMode::Worktree`] |
| 293 | /// so concurrent writers do not collide in the parent checkout. Explicit |
| 294 | /// [`IsolationMode::Shared`] is the plan-level same-worktree override. |
| 295 | #[default] |
| 296 | Auto, |
| 297 | /// Share the parent checkout (same-worktree). |
| 298 | Shared, |
| 299 | /// Dedicated git worktree / branch. |
| 300 | Worktree, |
| 301 | } |
| 302 | |
| 303 | impl IsolationMode { |
| 304 | /// Resolve [`IsolationMode::Auto`] for a leaf. |
| 305 | /// |
| 306 | /// When `parallel_write` is true (leaf is write-capable inside a parallel |
| 307 | /// branch), Auto becomes Worktree. Otherwise Auto becomes Shared. |
| 308 | #[must_use] |
| 309 | pub fn resolve(self, parallel_write: bool) -> Self { |
| 310 | match self { |
| 311 | Self::Auto if parallel_write => Self::Worktree, |
| 312 | Self::Auto => Self::Shared, |
| 313 | other => other, |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | /// Whether the resolved mode provisions a dedicated worktree. |
| 318 | #[must_use] |
| 319 | pub fn wants_worktree(self, parallel_write: bool) -> bool { |
| 320 | matches!(self.resolve(parallel_write), Self::Worktree) |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | /// A leaf is write-capable when it can mutate the workspace. |
| 325 | /// |
| 326 | /// Authority comes from the declared mode and permissions, not the agent's |
| 327 | /// role identity. In particular, an implementer may be deliberately confined |
| 328 | /// to a read-only verification task. Used by workflow lowering to decide the |
| 329 | /// default isolation for parallel children (#4120). |
| 330 | #[must_use] |
| 331 | pub fn leaf_is_write_capable(spec: &LeafSpec) -> bool { |
| 332 | spec.mode == TaskMode::ReadWrite || spec.permissions.allow_write |
| 333 | } |
| 334 | |
| 335 | /// Effective worktree flag for a leaf given whether it is being lowered inside |
| 336 | /// a parallel branch. |
| 337 | #[must_use] |
| 338 | pub fn leaf_wants_worktree(spec: &LeafSpec, parallel: bool) -> bool { |
| 339 | let parallel_write = parallel && leaf_is_write_capable(spec); |
| 340 | spec.isolation.wants_worktree(parallel_write) |
| 341 | } |
| 342 | |
| 343 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 344 | pub struct BranchResult { |
| 345 | pub branch_id: String, |
| 346 | pub task_id: String, |
| 347 | pub status: WorkflowRunStatus, |
| 348 | #[serde(default)] |
| 349 | pub usage: WorkflowUsage, |
| 350 | #[serde(default)] |
| 351 | pub artifacts: Vec<String>, |
| 352 | #[serde(default)] |
| 353 | pub notes: Option<String>, |
| 354 | } |
| 355 | |
| 356 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 357 | pub struct LeafResult { |
| 358 | pub leaf_id: String, |
| 359 | pub task_id: String, |
| 360 | /// Fleet role the leaf was declared to run as, if any (#4177). |
| 361 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 362 | pub role: Option<String>, |
| 363 | /// Fleet roster profile the leaf was declared to run as, if any. |
| 364 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 365 | pub profile: Option<String>, |
| 366 | pub status: WorkflowRunStatus, |
| 367 | #[serde(default)] |
| 368 | pub usage: WorkflowUsage, |
| 369 | #[serde(default)] |
| 370 | pub output: Option<String>, |
| 371 | #[serde(default)] |
| 372 | pub artifacts: Vec<String>, |
| 373 | /// Post-hoc validation failure for the leaf's structured response. |
| 374 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 375 | pub schema_error: Option<String>, |
| 376 | } |
| 377 | |
| 378 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 379 | pub struct WorkflowUsage { |
| 380 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 381 | pub input_tokens: Option<u64>, |
| 382 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 383 | pub output_tokens: Option<u64>, |
| 384 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 385 | pub cost_microusd: Option<u64>, |
| 386 | } |
| 387 | |
| 388 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 389 | pub struct ControlNodeResult { |
| 390 | pub node_id: String, |
| 391 | pub kind: ControlNodeKind, |
| 392 | pub status: WorkflowRunStatus, |
| 393 | #[serde(default)] |
| 394 | pub selected_children: Vec<String>, |
| 395 | #[serde(default)] |
| 396 | pub summary: Option<String>, |
| 397 | } |
| 398 | |
| 399 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 400 | #[serde(rename_all = "snake_case")] |
| 401 | pub enum WorkflowRunStatus { |
| 402 | #[default] |
| 403 | Pending, |
| 404 | Running, |
| 405 | Succeeded, |
| 406 | Failed, |
| 407 | Cancelled, |
| 408 | BudgetExceeded, |
| 409 | } |
| 410 | |
| 411 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] |
| 412 | #[serde(rename_all = "snake_case")] |
| 413 | pub enum ControlNodeKind { |
| 414 | BranchSet, |
| 415 | Leaf, |
| 416 | Sequence, |
| 417 | Reduce, |
| 418 | } |
| 419 | |
| 420 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 421 | pub struct WorkflowExecution { |
| 422 | pub status: WorkflowRunStatus, |
| 423 | #[serde(default)] |
| 424 | pub usage: WorkflowUsage, |
| 425 | #[serde(default)] |
| 426 | pub leaf_results: Vec<LeafResult>, |
| 427 | #[serde(default)] |
| 428 | pub branch_results: Vec<BranchResult>, |
| 429 | #[serde(default)] |
| 430 | pub control_node_results: Vec<ControlNodeResult>, |
| 431 | } |
| 432 | |
| 433 | impl Default for WorkflowExecution { |
| 434 | fn default() -> Self { |
| 435 | Self { |
| 436 | status: WorkflowRunStatus::Succeeded, |
| 437 | usage: WorkflowUsage::default(), |
| 438 | leaf_results: Vec::new(), |
| 439 | branch_results: Vec::new(), |
| 440 | control_node_results: Vec::new(), |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | impl WorkflowExecution { |
| 446 | pub fn mark_failed(&mut self) { |
| 447 | self.status = WorkflowRunStatus::Failed; |
| 448 | } |
| 449 | |
| 450 | pub fn mark_cancelled(&mut self) { |
| 451 | self.status = WorkflowRunStatus::Cancelled; |
| 452 | } |
| 453 | |
| 454 | pub fn mark_budget_exceeded(&mut self) { |
| 455 | self.status = WorkflowRunStatus::BudgetExceeded; |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | #[derive(Debug, Clone, PartialEq, Eq, Error)] |
| 460 | pub enum WorkflowExecutionError { |
| 461 | #[error("workflow must contain at least one node")] |
| 462 | EmptyWorkflow, |
| 463 | #[error("{kind} node id must not be empty")] |
| 464 | EmptyNodeId { kind: &'static str }, |
| 465 | #[error("leaf `{leaf}` prompt must not be empty")] |
| 466 | EmptyLeafPrompt { leaf: String }, |
| 467 | #[error( |
| 468 | "leaf `{leaf}` profile `{profile}` must be a non-empty token without whitespace, quotes, or `=`" |
| 469 | )] |
| 470 | InvalidLeafProfile { leaf: String, profile: String }, |
| 471 | #[error( |
| 472 | "leaf `{leaf}` role `{role}` must be a non-empty token without whitespace, quotes, or `=`" |
| 473 | )] |
| 474 | InvalidLeafRole { leaf: String, role: String }, |
| 475 | #[error("duplicate workflow node `{node}`")] |
| 476 | DuplicateNodeId { node: String }, |
| 477 | #[error("workflow node `{node}` has unknown {field} reference `{reference}`")] |
| 478 | UnknownNodeReference { |
| 479 | node: String, |
| 480 | field: &'static str, |
| 481 | reference: String, |
| 482 | }, |
| 483 | #[error("workflow node `{node}` reads {field} `{reference}` before its result is available")] |
| 484 | UnavailableNodeReference { |
| 485 | node: String, |
| 486 | field: &'static str, |
| 487 | reference: String, |
| 488 | }, |
| 489 | } |
| 490 | |
| 491 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 492 | pub struct WorkflowFleetLimits { |
| 493 | pub max_total_agents: usize, |
| 494 | pub max_depth: usize, |
| 495 | } |
| 496 | |
| 497 | impl Default for WorkflowFleetLimits { |
| 498 | fn default() -> Self { |
| 499 | Self { |
| 500 | max_total_agents: DEFAULT_FLEET_WORKFLOW_MAX_AGENTS, |
| 501 | max_depth: DEFAULT_FLEET_WORKFLOW_MAX_DEPTH, |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 507 | pub struct WorkflowFleetShape { |
| 508 | pub total_agents: usize, |
| 509 | pub max_depth: usize, |
| 510 | } |
| 511 | |
| 512 | impl WorkflowFleetShape { |
| 513 | fn add(self, other: Self) -> Self { |
| 514 | Self { |
| 515 | total_agents: self.total_agents.saturating_add(other.total_agents), |
| 516 | max_depth: self.max_depth.max(other.max_depth), |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | #[derive(Debug, Clone, PartialEq, Eq, Error)] |
| 522 | pub enum WorkflowFleetLimitError { |
| 523 | #[error("workflow IR is invalid for Fleet: {source}")] |
| 524 | InvalidWorkflow { |
| 525 | #[from] |
| 526 | source: WorkflowExecutionError, |
| 527 | }, |
| 528 | #[error( |
| 529 | "workflow would launch {total_agents} agents; Fleet Workflow limit is {max_total_agents}" |
| 530 | )] |
| 531 | TooManyAgents { |
| 532 | total_agents: usize, |
| 533 | max_total_agents: usize, |
| 534 | }, |
| 535 | #[error("workflow reaches recursion depth {depth}; Fleet Workflow limit is {max_depth}")] |
| 536 | RecursionTooDeep { depth: usize, max_depth: usize }, |
| 537 | } |
| 538 | |
| 539 | fn estimate_fleet_shape( |
| 540 | nodes: &[WorkflowNode], |
| 541 | limits: WorkflowFleetLimits, |
| 542 | ) -> Result<WorkflowFleetShape, WorkflowFleetLimitError> { |
| 543 | estimate_fleet_shape_at_depth(nodes, 1, limits) |
| 544 | } |
| 545 | |
| 546 | fn estimate_fleet_shape_at_depth( |
| 547 | nodes: &[WorkflowNode], |
| 548 | depth: usize, |
| 549 | limits: WorkflowFleetLimits, |
| 550 | ) -> Result<WorkflowFleetShape, WorkflowFleetLimitError> { |
| 551 | if limits.max_depth > 0 && depth > limits.max_depth { |
| 552 | return Err(WorkflowFleetLimitError::RecursionTooDeep { |
| 553 | depth, |
| 554 | max_depth: limits.max_depth, |
| 555 | }); |
| 556 | } |
| 557 | nodes |
| 558 | .iter() |
| 559 | .try_fold(WorkflowFleetShape::default(), |shape, node| { |
| 560 | Ok(shape.add(estimate_node_fleet_shape(node, depth, limits)?)) |
| 561 | }) |
| 562 | } |
| 563 | |
| 564 | fn estimate_node_fleet_shape( |
| 565 | node: &WorkflowNode, |
| 566 | depth: usize, |
| 567 | limits: WorkflowFleetLimits, |
| 568 | ) -> Result<WorkflowFleetShape, WorkflowFleetLimitError> { |
| 569 | match node { |
| 570 | WorkflowNode::Leaf(_) => Ok(WorkflowFleetShape { |
| 571 | total_agents: 1, |
| 572 | max_depth: depth, |
| 573 | }), |
| 574 | WorkflowNode::BranchSet(spec) => { |
| 575 | estimate_fleet_shape_at_depth(&spec.children, depth + 1, limits) |
| 576 | } |
| 577 | WorkflowNode::Sequence(spec) => { |
| 578 | estimate_fleet_shape_at_depth(&spec.children, depth, limits) |
| 579 | } |
| 580 | WorkflowNode::Reduce(_) => Ok(WorkflowFleetShape { |
| 581 | total_agents: 1, |
| 582 | max_depth: depth, |
| 583 | }), |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | fn node_id(node: &WorkflowNode) -> String { |
| 588 | match node { |
| 589 | WorkflowNode::BranchSet(spec) => spec.id.clone(), |
| 590 | WorkflowNode::Leaf(spec) => spec.id.clone(), |
| 591 | WorkflowNode::Sequence(spec) => spec.id.clone(), |
| 592 | WorkflowNode::Reduce(spec) => spec.id.clone(), |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | pub(crate) fn validate_workflow_nodes( |
| 597 | nodes: &[WorkflowNode], |
| 598 | ) -> Result<BTreeSet<String>, WorkflowExecutionError> { |
| 599 | if nodes.is_empty() { |
| 600 | return Err(WorkflowExecutionError::EmptyWorkflow); |
| 601 | } |
| 602 | let mut seen = BTreeSet::new(); |
| 603 | validate_workflow_nodes_inner(nodes, &mut seen)?; |
| 604 | validate_workflow_references(nodes, &seen)?; |
| 605 | validate_reference_order(nodes, &mut BTreeSet::new())?; |
| 606 | Ok(seen) |
| 607 | } |
| 608 | |
| 609 | fn validate_workflow_nodes_inner( |
| 610 | nodes: &[WorkflowNode], |
| 611 | seen: &mut BTreeSet<String>, |
| 612 | ) -> Result<(), WorkflowExecutionError> { |
| 613 | for node in nodes { |
| 614 | let id = node_id(node); |
| 615 | let kind = control_kind_name(node); |
| 616 | if id.trim().is_empty() { |
| 617 | return Err(WorkflowExecutionError::EmptyNodeId { kind }); |
| 618 | } |
| 619 | if !seen.insert(id.clone()) { |
| 620 | return Err(WorkflowExecutionError::DuplicateNodeId { node: id }); |
| 621 | } |
| 622 | match node { |
| 623 | WorkflowNode::BranchSet(spec) => validate_workflow_nodes_inner(&spec.children, seen)?, |
| 624 | WorkflowNode::Leaf(spec) => { |
| 625 | if spec.prompt.trim().is_empty() { |
| 626 | return Err(WorkflowExecutionError::EmptyLeafPrompt { |
| 627 | leaf: spec.id.clone(), |
| 628 | }); |
| 629 | } |
| 630 | if let Some(role) = spec.role.as_deref() { |
| 631 | validate_leaf_role(&spec.id, role)?; |
| 632 | } |
| 633 | if let Some(profile) = spec.profile.as_deref() { |
| 634 | validate_leaf_profile(&spec.id, profile)?; |
| 635 | } |
| 636 | } |
| 637 | WorkflowNode::Sequence(spec) => validate_workflow_nodes_inner(&spec.children, seen)?, |
| 638 | WorkflowNode::Reduce(_) => {} |
| 639 | } |
| 640 | } |
| 641 | Ok(()) |
| 642 | } |
| 643 | |
| 644 | fn validate_workflow_references( |
| 645 | nodes: &[WorkflowNode], |
| 646 | known_ids: &BTreeSet<String>, |
| 647 | ) -> Result<(), WorkflowExecutionError> { |
| 648 | for node in nodes { |
| 649 | match node { |
| 650 | WorkflowNode::BranchSet(spec) => { |
| 651 | validate_workflow_references(&spec.children, known_ids)?; |
| 652 | } |
| 653 | WorkflowNode::Leaf(spec) => { |
| 654 | validate_known_references( |
| 655 | spec.id.as_str(), |
| 656 | "depends_on_results", |
| 657 | &spec.depends_on_results, |
| 658 | known_ids, |
| 659 | )?; |
| 660 | } |
| 661 | WorkflowNode::Sequence(spec) => { |
| 662 | validate_workflow_references(&spec.children, known_ids)?; |
| 663 | } |
| 664 | WorkflowNode::Reduce(spec) => { |
| 665 | validate_known_references(spec.id.as_str(), "inputs", &spec.inputs, known_ids)?; |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | Ok(()) |
| 670 | } |
| 671 | |
| 672 | // Token rule only. Roster membership is resolved by the dispatcher (tui crate) |
| 673 | // at spawn time; this crate never sees the saved Fleet roster. |
| 674 | fn validate_leaf_profile(leaf: &str, profile: &str) -> Result<(), WorkflowExecutionError> { |
| 675 | let invalid = profile.is_empty() |
| 676 | || profile |
| 677 | .chars() |
| 678 | .any(|ch| ch.is_whitespace() || matches!(ch, '"' | '\'' | '`' | '=')); |
| 679 | if invalid { |
| 680 | return Err(WorkflowExecutionError::InvalidLeafProfile { |
| 681 | leaf: leaf.to_string(), |
| 682 | profile: profile.to_string(), |
| 683 | }); |
| 684 | } |
| 685 | Ok(()) |
| 686 | } |
| 687 | |
| 688 | fn validate_leaf_role(leaf: &str, role: &str) -> Result<(), WorkflowExecutionError> { |
| 689 | if validate_role_token(role).is_err() { |
| 690 | return Err(WorkflowExecutionError::InvalidLeafRole { |
| 691 | leaf: leaf.to_string(), |
| 692 | role: role.to_string(), |
| 693 | }); |
| 694 | } |
| 695 | Ok(()) |
| 696 | } |
| 697 | |
| 698 | fn validate_reference_order( |
| 699 | nodes: &[WorkflowNode], |
| 700 | finished: &mut BTreeSet<String>, |
| 701 | ) -> Result<(), WorkflowExecutionError> { |
| 702 | for node in nodes { |
| 703 | let (field, references): (&'static str, &[String]) = match node { |
| 704 | WorkflowNode::Leaf(spec) => ("depends_on_results", &spec.depends_on_results), |
| 705 | WorkflowNode::Reduce(spec) => ("inputs", &spec.inputs), |
| 706 | _ => ("", &[]), |
| 707 | }; |
| 708 | let id = node_id(node); |
| 709 | if let Some(reference) = references |
| 710 | .iter() |
| 711 | .find(|reference| !finished.contains(*reference)) |
| 712 | { |
| 713 | return Err(WorkflowExecutionError::UnavailableNodeReference { |
| 714 | node: id, |
| 715 | field, |
| 716 | reference: reference.clone(), |
| 717 | }); |
| 718 | } |
| 719 | match node { |
| 720 | WorkflowNode::BranchSet(spec) if spec.parallel => { |
| 721 | let before = finished.clone(); |
| 722 | for child in &spec.children { |
| 723 | let mut branch = before.clone(); |
| 724 | validate_reference_order(std::slice::from_ref(child), &mut branch)?; |
| 725 | finished.extend(branch); |
| 726 | } |
| 727 | } |
| 728 | WorkflowNode::BranchSet(spec) => validate_reference_order(&spec.children, finished)?, |
| 729 | WorkflowNode::Sequence(spec) => validate_reference_order(&spec.children, finished)?, |
| 730 | WorkflowNode::Leaf(_) | WorkflowNode::Reduce(_) => {} |
| 731 | } |
| 732 | finished.insert(id); |
| 733 | } |
| 734 | Ok(()) |
| 735 | } |
| 736 | |
| 737 | fn validate_known_references( |
| 738 | node: &str, |
| 739 | field: &'static str, |
| 740 | references: &[String], |
| 741 | known_ids: &BTreeSet<String>, |
| 742 | ) -> Result<(), WorkflowExecutionError> { |
| 743 | for reference in references { |
| 744 | if !known_ids.contains(reference) { |
| 745 | return Err(WorkflowExecutionError::UnknownNodeReference { |
| 746 | node: node.to_string(), |
| 747 | field, |
| 748 | reference: reference.clone(), |
| 749 | }); |
| 750 | } |
| 751 | } |
| 752 | Ok(()) |
| 753 | } |
| 754 | |
| 755 | fn control_kind_name(node: &WorkflowNode) -> &'static str { |
| 756 | match node { |
| 757 | WorkflowNode::BranchSet(_) => "branch_set", |
| 758 | WorkflowNode::Leaf(_) => "leaf", |
| 759 | WorkflowNode::Sequence(_) => "sequence", |
| 760 | WorkflowNode::Reduce(_) => "reduce", |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | /// Normalize the suffix-glob spelling accepted by declarative workflow |
| 765 | /// `file_scope` into the concrete directory root enforced at runtime. |
| 766 | #[must_use] |
| 767 | pub fn normalize_file_scope_root(scope: &str) -> String { |
| 768 | let trimmed = scope.trim().trim_start_matches("./").trim_end_matches('/'); |
| 769 | trimmed |
| 770 | .strip_suffix("/**") |
| 771 | .or_else(|| trimmed.strip_suffix("/*")) |
| 772 | .unwrap_or(trimmed) |
| 773 | .to_string() |
| 774 | } |
| 775 | |
| 776 | #[cfg(test)] |
| 777 | mod tests { |
| 778 | use super::*; |
| 779 | |
| 780 | fn leaf_node(id: &str) -> WorkflowNode { |
| 781 | WorkflowNode::Leaf(LeafSpec { |
| 782 | id: id.to_string(), |
| 783 | prompt: format!("run {id}"), |
| 784 | agent_type: AgentType::General, |
| 785 | role: None, |
| 786 | profile: None, |
| 787 | mode: TaskMode::ReadOnly, |
| 788 | isolation: IsolationMode::Shared, |
| 789 | file_scope: Vec::new(), |
| 790 | cwd: None, |
| 791 | depends_on_results: Vec::new(), |
| 792 | budget: BudgetSpec::default(), |
| 793 | permissions: PermissionSpec::default(), |
| 794 | model_policy: ModelPolicy::default(), |
| 795 | }) |
| 796 | } |
| 797 | |
| 798 | fn workflow_spec(nodes: Vec<WorkflowNode>) -> WorkflowSpec { |
| 799 | WorkflowSpec { |
| 800 | id: Some("test-workflow".to_string()), |
| 801 | goal: "prove workflow validation".to_string(), |
| 802 | description: None, |
| 803 | budget: BudgetSpec::default(), |
| 804 | permissions: PermissionSpec::default(), |
| 805 | model_policy: ModelPolicy::default(), |
| 806 | gates: Vec::new(), |
| 807 | nodes, |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | #[test] |
| 812 | fn json_accepts_pre_rename_agent_type_spellings_as_aliases() { |
| 813 | for (legacy, expected) in [ |
| 814 | ("implementer", AgentType::Implementer), |
| 815 | ("builder", AgentType::Implementer), |
| 816 | ("verifier", AgentType::Verifier), |
| 817 | ("verify", AgentType::Verifier), |
| 818 | ("scout", AgentType::Explore), |
| 819 | ("review", AgentType::Review), |
| 820 | ] { |
| 821 | let parsed: AgentType = |
| 822 | serde_json::from_value(serde_json::json!(legacy)).expect("legacy alias must parse"); |
| 823 | assert_eq!(parsed, expected, "alias {legacy}"); |
| 824 | } |
| 825 | // Canonical spellings parse and round-trip back as themselves. |
| 826 | for (canonical, expected) in [ |
| 827 | ("implement", AgentType::Implementer), |
| 828 | ("test", AgentType::Verifier), |
| 829 | ("explore", AgentType::Explore), |
| 830 | ("general", AgentType::General), |
| 831 | ] { |
| 832 | let parsed: AgentType = |
| 833 | serde_json::from_value(serde_json::json!(canonical)).expect("canonical parses"); |
| 834 | assert_eq!(parsed, expected); |
| 835 | assert_eq!( |
| 836 | serde_json::to_value(parsed).expect("serialize"), |
| 837 | serde_json::json!(canonical), |
| 838 | "canonical spelling must serialize as itself" |
| 839 | ); |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn isolation_auto_defaults_parallel_write_to_worktree() { |
| 845 | assert_eq!(IsolationMode::default(), IsolationMode::Auto); |
| 846 | assert_eq!( |
| 847 | IsolationMode::Auto.resolve(/* parallel_write */ true), |
| 848 | IsolationMode::Worktree |
| 849 | ); |
| 850 | assert_eq!( |
| 851 | IsolationMode::Auto.resolve(/* parallel_write */ false), |
| 852 | IsolationMode::Shared |
| 853 | ); |
| 854 | // Explicit shared is the approved same-worktree override. |
| 855 | assert_eq!( |
| 856 | IsolationMode::Shared.resolve(/* parallel_write */ true), |
| 857 | IsolationMode::Shared |
| 858 | ); |
| 859 | assert!(IsolationMode::Worktree.wants_worktree(false)); |
| 860 | assert!(!IsolationMode::Shared.wants_worktree(true)); |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn leaf_write_capable_and_worktree_defaults() { |
| 865 | let read_only = LeafSpec { |
| 866 | id: "ro".to_string(), |
| 867 | prompt: "inspect".to_string(), |
| 868 | agent_type: AgentType::Explore, |
| 869 | role: None, |
| 870 | profile: None, |
| 871 | mode: TaskMode::ReadOnly, |
| 872 | isolation: IsolationMode::Auto, |
| 873 | file_scope: Vec::new(), |
| 874 | cwd: None, |
| 875 | depends_on_results: Vec::new(), |
| 876 | budget: BudgetSpec::default(), |
| 877 | permissions: PermissionSpec::default(), |
| 878 | model_policy: ModelPolicy::default(), |
| 879 | }; |
| 880 | assert!(!leaf_is_write_capable(&read_only)); |
| 881 | assert!(!leaf_wants_worktree(&read_only, true)); |
| 882 | |
| 883 | let mut read_only_implementer = read_only.clone(); |
| 884 | read_only_implementer.id = "ro-implementer".to_string(); |
| 885 | read_only_implementer.agent_type = AgentType::Implementer; |
| 886 | assert!( |
| 887 | !leaf_is_write_capable(&read_only_implementer), |
| 888 | "role identity must not grant write authority" |
| 889 | ); |
| 890 | assert!( |
| 891 | !leaf_wants_worktree(&read_only_implementer, true), |
| 892 | "parallel read-only implementers stay shared under auto isolation" |
| 893 | ); |
| 894 | |
| 895 | let mut write = read_only.clone(); |
| 896 | write.id = "rw".to_string(); |
| 897 | write.mode = TaskMode::ReadWrite; |
| 898 | write.agent_type = AgentType::Implementer; |
| 899 | assert!(leaf_is_write_capable(&write)); |
| 900 | // Parallel write-capable + Auto → worktree by default. |
| 901 | assert!(leaf_wants_worktree(&write, true)); |
| 902 | // Sequential write-capable stays shared unless isolation is worktree. |
| 903 | assert!(!leaf_wants_worktree(&write, false)); |
| 904 | |
| 905 | write.isolation = IsolationMode::Shared; |
| 906 | assert!( |
| 907 | !leaf_wants_worktree(&write, true), |
| 908 | "explicit shared is the same-worktree override" |
| 909 | ); |
| 910 | |
| 911 | write.isolation = IsolationMode::Worktree; |
| 912 | assert!(leaf_wants_worktree(&write, true)); |
| 913 | assert!(leaf_wants_worktree(&write, false)); |
| 914 | } |
| 915 | |
| 916 | #[test] |
| 917 | fn workflow_ir_roundtrip() { |
| 918 | let discover_leaf = LeafSpec { |
| 919 | id: "scan-readme".to_string(), |
| 920 | prompt: "Inspect README setup gaps".to_string(), |
| 921 | agent_type: AgentType::Explore, |
| 922 | role: None, |
| 923 | profile: Some("scout".to_string()), |
| 924 | mode: TaskMode::ReadOnly, |
| 925 | isolation: IsolationMode::Shared, |
| 926 | file_scope: vec!["README.md".to_string()], |
| 927 | cwd: None, |
| 928 | depends_on_results: Vec::new(), |
| 929 | budget: BudgetSpec { |
| 930 | max_steps: Some(8), |
| 931 | timeout_secs: Some(300), |
| 932 | max_parallel: None, |
| 933 | max_tokens: None, |
| 934 | }, |
| 935 | permissions: PermissionSpec::default(), |
| 936 | model_policy: ModelPolicy { |
| 937 | provider: Some("openai".to_string()), |
| 938 | model: Some("gpt-5.4".to_string()), |
| 939 | fallback_models: Vec::new(), |
| 940 | }, |
| 941 | }; |
| 942 | let workflow = WorkflowSpec { |
| 943 | id: Some("v090-readme-check".to_string()), |
| 944 | goal: "tighten setup docs".to_string(), |
| 945 | description: Some("metadata-only typed Workflow IR".to_string()), |
| 946 | budget: BudgetSpec { |
| 947 | max_steps: Some(30), |
| 948 | timeout_secs: Some(1_800), |
| 949 | max_parallel: Some(2), |
| 950 | max_tokens: None, |
| 951 | }, |
| 952 | permissions: PermissionSpec { |
| 953 | allow_write: false, |
| 954 | allow_network: false, |
| 955 | deny_all_tools: false, |
| 956 | allowed_tools: vec!["rg".to_string()], |
| 957 | file_scope: vec!["README.md".to_string()], |
| 958 | }, |
| 959 | model_policy: ModelPolicy { |
| 960 | provider: Some("openai".to_string()), |
| 961 | model: Some("gpt-5.4".to_string()), |
| 962 | fallback_models: vec!["gpt-5.4-mini".to_string()], |
| 963 | }, |
| 964 | gates: Vec::new(), |
| 965 | nodes: vec![ |
| 966 | WorkflowNode::BranchSet(BranchSpec { |
| 967 | id: "discover".to_string(), |
| 968 | description: Some("parallel doc inspection".to_string()), |
| 969 | parallel: true, |
| 970 | budget: BudgetSpec { |
| 971 | max_steps: Some(12), |
| 972 | timeout_secs: Some(600), |
| 973 | max_parallel: Some(2), |
| 974 | max_tokens: None, |
| 975 | }, |
| 976 | permissions: PermissionSpec::default(), |
| 977 | model_policy: ModelPolicy::default(), |
| 978 | children: vec![WorkflowNode::Leaf(discover_leaf)], |
| 979 | }), |
| 980 | WorkflowNode::Sequence(SequenceSpec { |
| 981 | id: "reduce".to_string(), |
| 982 | children: vec![WorkflowNode::Reduce(ReduceSpec { |
| 983 | id: "summarize".to_string(), |
| 984 | inputs: vec!["scan-readme".to_string()], |
| 985 | prompt: "Summarize the smallest safe patch".to_string(), |
| 986 | model_policy: ModelPolicy::default(), |
| 987 | })], |
| 988 | }), |
| 989 | ], |
| 990 | }; |
| 991 | |
| 992 | let json = serde_json::to_string_pretty(&workflow).expect("serialize workflow ir"); |
| 993 | |
| 994 | assert!(json.contains("\"kind\": \"branch_set\"")); |
| 995 | assert!(json.contains("\"profile\": \"scout\"")); |
| 996 | let parsed: WorkflowSpec = serde_json::from_str(&json).expect("parse workflow ir"); |
| 997 | assert_eq!(parsed, workflow); |
| 998 | |
| 999 | let minimal: WorkflowSpec = serde_json::from_str(r#"{"goal":"ship v0.9","nodes":[]}"#) |
| 1000 | .expect("parse minimal workflow ir"); |
| 1001 | assert_eq!(minimal.budget, BudgetSpec::default()); |
| 1002 | assert_eq!(minimal.permissions, PermissionSpec::default()); |
| 1003 | assert_eq!(minimal.model_policy, ModelPolicy::default()); |
| 1004 | |
| 1005 | // Pre-profile leaf IR stays parseable and profile-less leaves omit the key. |
| 1006 | let legacy_leaf: LeafSpec = serde_json::from_str(r#"{"id":"scan","prompt":"scan safely"}"#) |
| 1007 | .expect("parse pre-profile leaf ir"); |
| 1008 | assert_eq!(legacy_leaf.profile, None); |
| 1009 | let legacy_json = serde_json::to_string(&legacy_leaf).expect("serialize legacy leaf"); |
| 1010 | assert!(!legacy_json.contains("profile")); |
| 1011 | } |
| 1012 | |
| 1013 | #[test] |
| 1014 | fn fleet_validation_accepts_one_thousand_agents_and_variable_models() { |
| 1015 | let nodes = (0..1001) |
| 1016 | .map(|index| { |
| 1017 | let mut leaf = match leaf_node(&format!("agent-{index}")) { |
| 1018 | WorkflowNode::Leaf(leaf) => leaf, |
| 1019 | _ => unreachable!("leaf helper returns a leaf"), |
| 1020 | }; |
| 1021 | leaf.model_policy = if index == 0 { |
| 1022 | ModelPolicy { |
| 1023 | provider: Some("deepseek".to_string()), |
| 1024 | model: Some("deepseek-v4-pro".to_string()), |
| 1025 | fallback_models: Vec::new(), |
| 1026 | } |
| 1027 | } else { |
| 1028 | ModelPolicy { |
| 1029 | provider: Some("deepseek".to_string()), |
| 1030 | model: Some("deepseek-v4-flash".to_string()), |
| 1031 | fallback_models: Vec::new(), |
| 1032 | } |
| 1033 | }; |
| 1034 | WorkflowNode::Leaf(leaf) |
| 1035 | }) |
| 1036 | .collect(); |
| 1037 | let workflow = workflow_spec(nodes); |
| 1038 | |
| 1039 | let shape = workflow |
| 1040 | .validate_for_fleet() |
| 1041 | .expect("total work is uncapped by default"); |
| 1042 | |
| 1043 | assert_eq!(shape.total_agents, 1001); |
| 1044 | assert_eq!(shape.max_depth, 1); |
| 1045 | } |
| 1046 | |
| 1047 | #[test] |
| 1048 | fn fleet_validation_honors_an_explicit_total_agent_limit() { |
| 1049 | let nodes = (0..=1000) |
| 1050 | .map(|index| leaf_node(&format!("agent-{index}"))) |
| 1051 | .collect(); |
| 1052 | let workflow = workflow_spec(nodes); |
| 1053 | |
| 1054 | let err = workflow |
| 1055 | .validate_for_fleet_with_limits(WorkflowFleetLimits { |
| 1056 | max_total_agents: 1000, |
| 1057 | ..Default::default() |
| 1058 | }) |
| 1059 | .expect_err("agent population should be bounded before Fleet launch"); |
| 1060 | |
| 1061 | assert_eq!( |
| 1062 | err, |
| 1063 | WorkflowFleetLimitError::TooManyAgents { |
| 1064 | total_agents: 1001, |
| 1065 | max_total_agents: 1000, |
| 1066 | } |
| 1067 | ); |
| 1068 | } |
| 1069 | |
| 1070 | #[test] |
| 1071 | fn fleet_validation_honors_only_explicit_depth_limits() { |
| 1072 | let mut node = leaf_node("deep-leaf"); |
| 1073 | for depth in (0..8).rev() { |
| 1074 | node = WorkflowNode::BranchSet(BranchSpec { |
| 1075 | id: format!("ring-{depth}"), |
| 1076 | description: None, |
| 1077 | parallel: true, |
| 1078 | budget: BudgetSpec::default(), |
| 1079 | permissions: PermissionSpec::default(), |
| 1080 | model_policy: ModelPolicy::default(), |
| 1081 | children: vec![node], |
| 1082 | }); |
| 1083 | } |
| 1084 | let workflow = workflow_spec(vec![node]); |
| 1085 | |
| 1086 | assert_eq!(workflow.validate_for_fleet().unwrap().max_depth, 9); |
| 1087 | let err = workflow |
| 1088 | .validate_for_fleet_with_limits(WorkflowFleetLimits { |
| 1089 | max_depth: 8, |
| 1090 | ..Default::default() |
| 1091 | }) |
| 1092 | .expect_err("the explicit owner depth should be enforced"); |
| 1093 | |
| 1094 | assert_eq!( |
| 1095 | err, |
| 1096 | WorkflowFleetLimitError::RecursionTooDeep { |
| 1097 | depth: 9, |
| 1098 | max_depth: 8, |
| 1099 | } |
| 1100 | ); |
| 1101 | |
| 1102 | let mut deeper = leaf_node("deeper-leaf"); |
| 1103 | for depth in (0..64).rev() { |
| 1104 | deeper = WorkflowNode::BranchSet(BranchSpec { |
| 1105 | id: format!("deep-ring-{depth}"), |
| 1106 | description: None, |
| 1107 | parallel: true, |
| 1108 | budget: BudgetSpec::default(), |
| 1109 | permissions: PermissionSpec::default(), |
| 1110 | model_policy: ModelPolicy::default(), |
| 1111 | children: vec![deeper], |
| 1112 | }); |
| 1113 | } |
| 1114 | let deeper = workflow_spec(vec![deeper]); |
| 1115 | let err = deeper |
| 1116 | .validate_for_fleet_with_limits(WorkflowFleetLimits { |
| 1117 | max_depth: 8, |
| 1118 | ..Default::default() |
| 1119 | }) |
| 1120 | .expect_err("depth must be rejected before the whole tree is descended"); |
| 1121 | assert_eq!( |
| 1122 | err, |
| 1123 | WorkflowFleetLimitError::RecursionTooDeep { |
| 1124 | depth: 9, |
| 1125 | max_depth: 8, |
| 1126 | } |
| 1127 | ); |
| 1128 | } |
| 1129 | |
| 1130 | #[test] |
| 1131 | fn branch_result_serialization() { |
| 1132 | let result = BranchResult { |
| 1133 | branch_id: "discover".to_string(), |
| 1134 | task_id: "scan".to_string(), |
| 1135 | status: WorkflowRunStatus::Succeeded, |
| 1136 | usage: WorkflowUsage { |
| 1137 | input_tokens: Some(100), |
| 1138 | output_tokens: Some(25), |
| 1139 | cost_microusd: Some(42), |
| 1140 | }, |
| 1141 | artifacts: vec!["trace://branches/discover".to_string()], |
| 1142 | notes: Some("validated prompt surfaces".to_string()), |
| 1143 | }; |
| 1144 | |
| 1145 | let json = serde_json::to_string(&result).expect("serialize branch result"); |
| 1146 | |
| 1147 | assert!(json.contains("\"status\":\"succeeded\"")); |
| 1148 | assert!(json.contains("\"cost_microusd\":42")); |
| 1149 | let parsed: BranchResult = serde_json::from_str(&json).expect("parse branch result"); |
| 1150 | assert_eq!(parsed, result); |
| 1151 | |
| 1152 | let minimal: BranchResult = |
| 1153 | serde_json::from_str(r#"{"branch_id":"discover","task_id":"scan","status":"pending"}"#) |
| 1154 | .expect("parse minimal branch result"); |
| 1155 | assert_eq!(minimal.usage, WorkflowUsage::default()); |
| 1156 | assert!(minimal.artifacts.is_empty()); |
| 1157 | assert_eq!(minimal.notes, None); |
| 1158 | } |
| 1159 | |
| 1160 | #[test] |
| 1161 | fn workflow_usage_serialization_distinguishes_unknown_from_reported_zero() { |
| 1162 | let unknown = serde_json::to_value(WorkflowUsage::default()).expect("unknown usage JSON"); |
| 1163 | assert_eq!(unknown, serde_json::json!({})); |
| 1164 | |
| 1165 | let reported_zero = serde_json::to_value(WorkflowUsage { |
| 1166 | input_tokens: Some(0), |
| 1167 | output_tokens: Some(0), |
| 1168 | cost_microusd: Some(0), |
| 1169 | }) |
| 1170 | .expect("reported zero usage JSON"); |
| 1171 | assert_eq!( |
| 1172 | reported_zero, |
| 1173 | serde_json::json!({ |
| 1174 | "input_tokens": 0, |
| 1175 | "output_tokens": 0, |
| 1176 | "cost_microusd": 0, |
| 1177 | }) |
| 1178 | ); |
| 1179 | } |
| 1180 | |
| 1181 | #[test] |
| 1182 | fn leaf_result_serialization() { |
| 1183 | let result = LeafResult { |
| 1184 | leaf_id: "scan-readme".to_string(), |
| 1185 | task_id: "scan".to_string(), |
| 1186 | role: None, |
| 1187 | profile: Some("reviewer".to_string()), |
| 1188 | status: WorkflowRunStatus::Failed, |
| 1189 | usage: WorkflowUsage { |
| 1190 | input_tokens: Some(11), |
| 1191 | output_tokens: Some(7), |
| 1192 | cost_microusd: Some(3), |
| 1193 | }, |
| 1194 | output: Some("README needs clearer setup steps".to_string()), |
| 1195 | artifacts: vec!["trace://leaves/scan-readme".to_string()], |
| 1196 | schema_error: None, |
| 1197 | }; |
| 1198 | |
| 1199 | let json = serde_json::to_string(&result).expect("serialize leaf result"); |
| 1200 | |
| 1201 | assert!(json.contains("\"status\":\"failed\"")); |
| 1202 | assert!(json.contains("\"input_tokens\":11")); |
| 1203 | assert!(json.contains("\"profile\":\"reviewer\"")); |
| 1204 | let parsed: LeafResult = serde_json::from_str(&json).expect("parse leaf result"); |
| 1205 | assert_eq!(parsed, result); |
| 1206 | |
| 1207 | let minimal: LeafResult = serde_json::from_str( |
| 1208 | r#"{"leaf_id":"scan-readme","task_id":"scan","status":"pending","memo_usage":{"armh_hits":1}}"#, |
| 1209 | ) |
| 1210 | .expect("parse minimal leaf result with a pre-removal memo_usage field"); |
| 1211 | assert_eq!(minimal.profile, None); |
| 1212 | assert_eq!(minimal.usage, WorkflowUsage::default()); |
| 1213 | assert_eq!(minimal.output, None); |
| 1214 | assert!(minimal.artifacts.is_empty()); |
| 1215 | } |
| 1216 | |
| 1217 | #[test] |
| 1218 | fn control_node_result_serialization() { |
| 1219 | let result = ControlNodeResult { |
| 1220 | node_id: "select-fix".to_string(), |
| 1221 | kind: ControlNodeKind::Reduce, |
| 1222 | status: WorkflowRunStatus::Running, |
| 1223 | selected_children: vec!["branch-a".to_string(), "branch-c".to_string()], |
| 1224 | summary: Some("reduce is waiting on branch results".to_string()), |
| 1225 | }; |
| 1226 | |
| 1227 | let json = serde_json::to_string(&result).expect("serialize control node result"); |
| 1228 | |
| 1229 | assert!(json.contains("\"kind\":\"reduce\"")); |
| 1230 | assert!(json.contains("\"status\":\"running\"")); |
| 1231 | let parsed: ControlNodeResult = |
| 1232 | serde_json::from_str(&json).expect("parse control node result"); |
| 1233 | assert_eq!(parsed, result); |
| 1234 | |
| 1235 | let minimal: ControlNodeResult = serde_json::from_str( |
| 1236 | r#"{"node_id":"select-fix","kind":"branch_set","status":"pending"}"#, |
| 1237 | ) |
| 1238 | .expect("parse minimal control node result"); |
| 1239 | assert!(minimal.selected_children.is_empty()); |
| 1240 | assert_eq!(minimal.summary, None); |
| 1241 | } |
| 1242 | |
| 1243 | #[test] |
| 1244 | fn leaf_role_token_rule_rejects_invalid_names() { |
| 1245 | for bad in ["", "has space", "role=scout"] { |
| 1246 | let mut leaf = match leaf_node("scan") { |
| 1247 | WorkflowNode::Leaf(leaf) => leaf, |
| 1248 | _ => unreachable!("leaf helper returns a leaf"), |
| 1249 | }; |
| 1250 | leaf.role = Some(bad.to_string()); |
| 1251 | let workflow = workflow_spec(vec![WorkflowNode::Leaf(leaf)]); |
| 1252 | |
| 1253 | let err = validate_workflow_nodes(&workflow.nodes) |
| 1254 | .expect_err("invalid role token should fail validation"); |
| 1255 | |
| 1256 | assert!( |
| 1257 | matches!(&err, WorkflowExecutionError::InvalidLeafRole { role, .. } if role == bad), |
| 1258 | "role `{bad}` should be rejected, got {err:?}" |
| 1259 | ); |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | #[test] |
| 1264 | fn leaf_role_roundtrips_without_required_provider_model() { |
| 1265 | let leaf = LeafSpec { |
| 1266 | id: "scout-1".to_string(), |
| 1267 | prompt: "Investigate #4090. Read-only.".to_string(), |
| 1268 | agent_type: AgentType::Explore, |
| 1269 | role: Some("scout".to_string()), |
| 1270 | profile: None, |
| 1271 | mode: TaskMode::ReadOnly, |
| 1272 | isolation: IsolationMode::Shared, |
| 1273 | file_scope: Vec::new(), |
| 1274 | cwd: None, |
| 1275 | depends_on_results: Vec::new(), |
| 1276 | budget: BudgetSpec::default(), |
| 1277 | permissions: PermissionSpec::default(), |
| 1278 | model_policy: ModelPolicy::default(), |
| 1279 | }; |
| 1280 | let json = serde_json::to_string(&leaf).expect("serialize"); |
| 1281 | assert!(json.contains("\"role\":\"scout\"")); |
| 1282 | let parsed: LeafSpec = serde_json::from_str(&json).expect("parse"); |
| 1283 | assert_eq!(parsed.role.as_deref(), Some("scout")); |
| 1284 | // Provider/model are optional overrides, not required identity fields. |
| 1285 | assert_eq!(parsed.model_policy.provider, None); |
| 1286 | assert_eq!(parsed.model_policy.model, None); |
| 1287 | assert_eq!(parsed.model_policy, ModelPolicy::default()); |
| 1288 | } |
| 1289 | |
| 1290 | #[test] |
| 1291 | fn leaf_profile_token_rule_rejects_invalid_names() { |
| 1292 | for bad in ["", "has space", "quote\"y", "role=reviewer", "back`tick"] { |
| 1293 | let mut leaf = match leaf_node("scan") { |
| 1294 | WorkflowNode::Leaf(leaf) => leaf, |
| 1295 | _ => unreachable!("leaf helper returns a leaf"), |
| 1296 | }; |
| 1297 | leaf.profile = Some(bad.to_string()); |
| 1298 | let workflow = workflow_spec(vec![WorkflowNode::Leaf(leaf)]); |
| 1299 | |
| 1300 | let err = validate_workflow_nodes(&workflow.nodes) |
| 1301 | .expect_err("invalid profile token should fail validation"); |
| 1302 | |
| 1303 | assert!( |
| 1304 | matches!(&err, WorkflowExecutionError::InvalidLeafProfile { profile, .. } if profile == bad), |
| 1305 | "profile `{bad}` should be rejected, got {err:?}" |
| 1306 | ); |
| 1307 | } |
| 1308 | |
| 1309 | let mut leaf = match leaf_node("scan") { |
| 1310 | WorkflowNode::Leaf(leaf) => leaf, |
| 1311 | _ => unreachable!("leaf helper returns a leaf"), |
| 1312 | }; |
| 1313 | leaf.profile = Some("reviewer".to_string()); |
| 1314 | let workflow = workflow_spec(vec![WorkflowNode::Leaf(leaf)]); |
| 1315 | validate_workflow_nodes(&workflow.nodes) |
| 1316 | .expect("valid profile token should pass validation"); |
| 1317 | } |
| 1318 | |
| 1319 | #[test] |
| 1320 | fn budget_spec_serializes_max_tokens() { |
| 1321 | let budget = BudgetSpec { |
| 1322 | max_steps: Some(10), |
| 1323 | timeout_secs: Some(600), |
| 1324 | max_parallel: Some(4), |
| 1325 | max_tokens: Some(50_000), |
| 1326 | }; |
| 1327 | let json = serde_json::to_string(&budget).expect("serialize budget"); |
| 1328 | let parsed: BudgetSpec = serde_json::from_str(&json).expect("parse budget"); |
| 1329 | assert_eq!(parsed, budget); |
| 1330 | assert!(json.contains("\"max_tokens\":50000")); |
| 1331 | |
| 1332 | // Default (all None) round-trips without the field present. |
| 1333 | let default_json = |
| 1334 | serde_json::to_string(&BudgetSpec::default()).expect("serialize default"); |
| 1335 | let parsed_default: BudgetSpec = |
| 1336 | serde_json::from_str(&default_json).expect("parse default budget"); |
| 1337 | assert_eq!(parsed_default, BudgetSpec::default()); |
| 1338 | assert!(parsed_default.max_tokens.is_none()); |
| 1339 | } |
| 1340 | |
| 1341 | #[test] |
| 1342 | fn workflow_spec_rejects_unknown_leaf_dependency() { |
| 1343 | let mut summarize = leaf_node("summarize"); |
| 1344 | let WorkflowNode::Leaf(spec) = &mut summarize else { |
| 1345 | panic!("expected leaf"); |
| 1346 | }; |
| 1347 | spec.depends_on_results = vec!["missing-scan".to_string()]; |
| 1348 | let workflow = workflow_spec(vec![summarize]); |
| 1349 | |
| 1350 | let err = validate_workflow_nodes(&workflow.nodes) |
| 1351 | .expect_err("unknown leaf dependency should fail before execution"); |
| 1352 | |
| 1353 | assert_eq!( |
| 1354 | err, |
| 1355 | WorkflowExecutionError::UnknownNodeReference { |
| 1356 | node: "summarize".to_string(), |
| 1357 | field: "depends_on_results", |
| 1358 | reference: "missing-scan".to_string(), |
| 1359 | } |
| 1360 | ); |
| 1361 | } |
| 1362 | |
| 1363 | #[test] |
| 1364 | fn workflow_spec_rejects_unavailable_result_references() { |
| 1365 | let reduce = |id: &str, inputs: &[&str]| { |
| 1366 | WorkflowNode::Reduce(ReduceSpec { |
| 1367 | id: id.to_string(), |
| 1368 | inputs: inputs.iter().map(|input| input.to_string()).collect(), |
| 1369 | prompt: "combine".to_string(), |
| 1370 | model_policy: ModelPolicy::default(), |
| 1371 | }) |
| 1372 | }; |
| 1373 | let parallel = |children: Vec<WorkflowNode>| { |
| 1374 | WorkflowNode::BranchSet(BranchSpec { |
| 1375 | id: "fan".to_string(), |
| 1376 | description: None, |
| 1377 | parallel: true, |
| 1378 | budget: BudgetSpec::default(), |
| 1379 | permissions: PermissionSpec::default(), |
| 1380 | model_policy: ModelPolicy::default(), |
| 1381 | children, |
| 1382 | }) |
| 1383 | }; |
| 1384 | for (nodes, reference) in [ |
| 1385 | (vec![reduce("sum", &["later"]), leaf_node("later")], "later"), |
| 1386 | (vec![reduce("sum", &["sum"])], "sum"), |
| 1387 | ( |
| 1388 | vec![parallel(vec![leaf_node("a"), reduce("sum", &["a"])])], |
| 1389 | "a", |
| 1390 | ), |
| 1391 | (vec![parallel(vec![reduce("sum", &["fan"])])], "fan"), |
| 1392 | ] { |
| 1393 | assert!( |
| 1394 | matches!( |
| 1395 | workflow_spec(nodes).validate_for_fleet(), |
| 1396 | Err(WorkflowFleetLimitError::InvalidWorkflow { |
| 1397 | source: WorkflowExecutionError::UnavailableNodeReference { reference: found, .. } |
| 1398 | }) if found == reference |
| 1399 | ), |
| 1400 | "{reference} must already have completed" |
| 1401 | ); |
| 1402 | } |
| 1403 | let shape = workflow_spec(vec![ |
| 1404 | parallel(vec![leaf_node("a"), leaf_node("b")]), |
| 1405 | reduce("sum", &["a", "b", "fan"]), |
| 1406 | reduce("after_sum", &["sum"]), |
| 1407 | ]) |
| 1408 | .validate_for_fleet() |
| 1409 | .expect("completed results remain available"); |
| 1410 | assert_eq!(shape.total_agents, 4); |
| 1411 | } |
| 1412 | |
| 1413 | #[test] |
| 1414 | fn workflow_spec_rejects_unknown_reduce_input() { |
| 1415 | let workflow = workflow_spec(vec![ |
| 1416 | leaf_node("scan"), |
| 1417 | WorkflowNode::Reduce(ReduceSpec { |
| 1418 | id: "summarize".to_string(), |
| 1419 | inputs: vec!["scan".to_string(), "missing-review".to_string()], |
| 1420 | prompt: "Summarize safe fixes".to_string(), |
| 1421 | model_policy: ModelPolicy::default(), |
| 1422 | }), |
| 1423 | ]); |
| 1424 | |
| 1425 | let err = validate_workflow_nodes(&workflow.nodes) |
| 1426 | .expect_err("unknown reduce input should fail before execution"); |
| 1427 | |
| 1428 | assert_eq!( |
| 1429 | err, |
| 1430 | WorkflowExecutionError::UnknownNodeReference { |
| 1431 | node: "summarize".to_string(), |
| 1432 | field: "inputs", |
| 1433 | reference: "missing-review".to_string(), |
| 1434 | } |
| 1435 | ); |
| 1436 | } |
| 1437 | } |
| 1438 |