| 1 | //! Elevated Workflow plan approval analysis (#4126). |
| 2 | //! |
| 3 | //! Builds the approval-card summary (goal, children, writes/shell/network/budget) |
| 4 | //! and decides whether a launch is elevated enough to require operator approval |
| 5 | //! beyond read-only auto-start. |
| 6 | |
| 7 | use codewhale_config::WorkflowConfigToml; |
| 8 | use codewhale_workflow::{ |
| 9 | ElevationOptions, WorkflowPlanElevation, WorkflowSpec, assess_workflow_elevation, |
| 10 | elevation::{ToolAuthority, tool_name_authority}, |
| 11 | }; |
| 12 | use serde::{Deserialize, Serialize}; |
| 13 | use serde_json::Value; |
| 14 | |
| 15 | use crate::tools::spec::ApprovalRequirement; |
| 16 | |
| 17 | /// Capability / budget summary shown on the Workflow approval card. |
| 18 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 19 | pub struct WorkflowPlanApprovalSummary { |
| 20 | pub goal: String, |
| 21 | pub risk: Option<String>, |
| 22 | pub child_count: usize, |
| 23 | pub child_labels: Vec<String>, |
| 24 | pub child_summary: String, |
| 25 | pub phase_count: usize, |
| 26 | pub writes: bool, |
| 27 | pub shell: bool, |
| 28 | pub network: bool, |
| 29 | pub secrets: bool, |
| 30 | pub worktree: bool, |
| 31 | pub broader_authority: bool, |
| 32 | pub token_budget: Option<u64>, |
| 33 | pub budget_label: String, |
| 34 | pub elevated: bool, |
| 35 | pub reasons: Vec<String>, |
| 36 | } |
| 37 | |
| 38 | impl WorkflowPlanApprovalSummary { |
| 39 | /// Card field pairs: Goal, Children, Writes, Shell, Network, Budget. |
| 40 | #[must_use] |
| 41 | pub fn card_fields(&self) -> Vec<(&'static str, String)> { |
| 42 | vec![ |
| 43 | ("Goal", self.goal.clone()), |
| 44 | ("Children", self.child_summary.clone()), |
| 45 | ("Writes", yn(self.writes).to_string()), |
| 46 | ("Shell", yn(self.shell).to_string()), |
| 47 | ("Network", yn(self.network).to_string()), |
| 48 | ("Budget", self.budget_label.clone()), |
| 49 | ] |
| 50 | } |
| 51 | |
| 52 | /// One-line impacts for the shared ApprovalView card. |
| 53 | #[must_use] |
| 54 | pub fn approval_impacts(&self) -> Vec<String> { |
| 55 | let mut impacts = Vec::new(); |
| 56 | if !self.goal.is_empty() { |
| 57 | impacts.push(format!("Goal: {}", truncate(&self.goal, 96))); |
| 58 | } |
| 59 | if let Some(risk) = &self.risk { |
| 60 | impacts.push(format!("Risk: {risk}")); |
| 61 | } |
| 62 | impacts.push(format!("Children: {}", self.child_summary)); |
| 63 | if self.phase_count > 0 { |
| 64 | impacts.push(format!("Phases: {}", self.phase_count)); |
| 65 | } |
| 66 | impacts.push(format!("Writes: {}", yn(self.writes))); |
| 67 | impacts.push(format!("Shell: {}", yn(self.shell))); |
| 68 | impacts.push(format!("Network: {}", yn(self.network))); |
| 69 | if self.secrets { |
| 70 | impacts.push(format!("Secrets: {}", yn(self.secrets))); |
| 71 | } |
| 72 | if self.worktree { |
| 73 | impacts.push(format!("Worktree: {}", yn(self.worktree))); |
| 74 | } |
| 75 | impacts.push(format!("Budget: {}", self.budget_label)); |
| 76 | if self.broader_authority { |
| 77 | impacts.push("Broader authority than parent mode".into()); |
| 78 | } |
| 79 | if self.elevated { |
| 80 | impacts.push( |
| 81 | "Elevated plan — Approve to launch, Edit plan to revise, Cancel to abort.".into(), |
| 82 | ); |
| 83 | } else { |
| 84 | impacts.push("Read-only plan.".into()); |
| 85 | } |
| 86 | impacts |
| 87 | } |
| 88 | |
| 89 | /// Durable receipt fragment for audit after approval/launch. |
| 90 | #[must_use] |
| 91 | pub fn to_receipt(&self, decision: &str, approved_at_ms: u64) -> WorkflowPlanApprovalReceipt { |
| 92 | WorkflowPlanApprovalReceipt { |
| 93 | decision: decision.to_string(), |
| 94 | approved_at_ms, |
| 95 | goal: self.goal.clone(), |
| 96 | child_summary: self.child_summary.clone(), |
| 97 | writes: self.writes, |
| 98 | shell: self.shell, |
| 99 | network: self.network, |
| 100 | secrets: self.secrets, |
| 101 | worktree: self.worktree, |
| 102 | broader_authority: self.broader_authority, |
| 103 | budget_label: self.budget_label.clone(), |
| 104 | reasons: self.reasons.clone(), |
| 105 | elevated: self.elevated, |
| 106 | token_budget: self.token_budget, |
| 107 | risk: self.risk.clone(), |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #[must_use] |
| 112 | pub fn is_read_only_envelope(&self) -> bool { |
| 113 | !self.elevated |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// Durable snapshot of an approved (or auto-started) plan for audit (#4126). |
| 118 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 119 | pub struct WorkflowPlanApprovalReceipt { |
| 120 | pub decision: String, |
| 121 | pub approved_at_ms: u64, |
| 122 | pub goal: String, |
| 123 | pub child_summary: String, |
| 124 | pub writes: bool, |
| 125 | pub shell: bool, |
| 126 | pub network: bool, |
| 127 | pub secrets: bool, |
| 128 | pub worktree: bool, |
| 129 | pub broader_authority: bool, |
| 130 | pub budget_label: String, |
| 131 | pub reasons: Vec<String>, |
| 132 | pub elevated: bool, |
| 133 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 134 | pub token_budget: Option<u64>, |
| 135 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 136 | pub risk: Option<String>, |
| 137 | } |
| 138 | |
| 139 | /// Analyze a `workflow` tool input for approval elevation (#4126). |
| 140 | #[must_use] |
| 141 | pub fn analyze_workflow_plan_approval(input: &Value) -> WorkflowPlanApprovalSummary { |
| 142 | let action = input |
| 143 | .get("action") |
| 144 | .and_then(Value::as_str) |
| 145 | .unwrap_or("start"); |
| 146 | if matches!(action, "status" | "cancel") { |
| 147 | return empty_summary(format!("workflow {action}"), None); |
| 148 | } |
| 149 | |
| 150 | let mut summary = analyze_workflow_launch(input); |
| 151 | // `verify: true` runs the workspace's detected gates (package scripts, |
| 152 | // `cargo check` build scripts, ...) when the run completes. That is shell |
| 153 | // execution of workspace code, so it leaves the read-only envelope. |
| 154 | if input.get("verify").and_then(Value::as_bool) == Some(true) { |
| 155 | summary.shell = true; |
| 156 | summary.elevated = true; |
| 157 | if !summary.reasons.iter().any(|r| r == "verify_gates") { |
| 158 | summary.reasons.push("verify_gates".into()); |
| 159 | } |
| 160 | } |
| 161 | summary |
| 162 | } |
| 163 | |
| 164 | fn analyze_workflow_launch(input: &Value) -> WorkflowPlanApprovalSummary { |
| 165 | if let Some(plan) = input.get("plan").filter(|v| v.is_object()) { |
| 166 | if plan.get("nodes").is_none() { |
| 167 | return analyze_plan_object(plan); |
| 168 | } |
| 169 | if let Ok(spec) = crate::tools::workflow::structured_plan_to_workflow_spec(plan) { |
| 170 | return analyze_workflow_spec(&spec); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // script / source_path — conservative elevated unless clearly status-only. |
| 175 | let goal = input |
| 176 | .get("source_path") |
| 177 | .and_then(Value::as_str) |
| 178 | .map(|p| format!("source_path: {p}")) |
| 179 | .or_else(|| { |
| 180 | input |
| 181 | .get("script") |
| 182 | .and_then(Value::as_str) |
| 183 | .map(|s| truncate(s.lines().next().unwrap_or("inline script"), 80)) |
| 184 | }) |
| 185 | .unwrap_or_else(|| "workflow launch".into()); |
| 186 | |
| 187 | let script = input |
| 188 | .get("script") |
| 189 | .and_then(Value::as_str) |
| 190 | .unwrap_or_default(); |
| 191 | let writes = script_suggests_writes(script); |
| 192 | let shell = script_suggests_shell(script); |
| 193 | let network = script_suggests_network(script); |
| 194 | let worktree = script.contains("worktree") || script.contains("isolation"); |
| 195 | // Unknown script authority: always elevated so the card is required. |
| 196 | let elevated = true; |
| 197 | let mut reasons = vec!["script_or_source".to_string()]; |
| 198 | if writes { |
| 199 | reasons.push("writes".into()); |
| 200 | } |
| 201 | if shell { |
| 202 | reasons.push("shell".into()); |
| 203 | } |
| 204 | if network { |
| 205 | reasons.push("network".into()); |
| 206 | } |
| 207 | if worktree { |
| 208 | reasons.push("worktree".into()); |
| 209 | } |
| 210 | let child_count = count_script_tasks(script); |
| 211 | let child_summary = if child_count == 0 { |
| 212 | "script/source (authority unknown until run)".into() |
| 213 | } else { |
| 214 | format!("{child_count} task() calls") |
| 215 | }; |
| 216 | WorkflowPlanApprovalSummary { |
| 217 | goal, |
| 218 | risk: None, |
| 219 | child_count, |
| 220 | child_labels: Vec::new(), |
| 221 | child_summary, |
| 222 | phase_count: script.matches("phase(").count(), |
| 223 | writes: writes || elevated, |
| 224 | shell: shell || elevated, |
| 225 | network: network || elevated, |
| 226 | secrets: false, |
| 227 | worktree, |
| 228 | broader_authority: false, |
| 229 | token_budget: None, |
| 230 | budget_label: budget_label(None), |
| 231 | elevated, |
| 232 | reasons, |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// Assess a compiled Workflow IR for the approval card / receipt. |
| 237 | #[must_use] |
| 238 | pub fn analyze_workflow_spec(spec: &WorkflowSpec) -> WorkflowPlanApprovalSummary { |
| 239 | let elevation = assess_workflow_elevation(spec, ElevationOptions::default()); |
| 240 | summary_from_elevation(elevation, spec.description.clone(), spec.budget.max_tokens) |
| 241 | } |
| 242 | |
| 243 | fn summary_from_elevation( |
| 244 | elevation: WorkflowPlanElevation, |
| 245 | risk: Option<String>, |
| 246 | token_budget: Option<u64>, |
| 247 | ) -> WorkflowPlanApprovalSummary { |
| 248 | WorkflowPlanApprovalSummary { |
| 249 | goal: elevation.goal, |
| 250 | risk, |
| 251 | child_count: elevation.child_count, |
| 252 | child_labels: Vec::new(), |
| 253 | child_summary: elevation.child_summary, |
| 254 | phase_count: 0, |
| 255 | writes: elevation.writes, |
| 256 | shell: elevation.shell, |
| 257 | network: elevation.network, |
| 258 | secrets: elevation.secrets, |
| 259 | worktree: elevation.worktree, |
| 260 | broader_authority: elevation.broader_authority, |
| 261 | token_budget, |
| 262 | budget_label: elevation.budget_label, |
| 263 | elevated: elevation.elevated, |
| 264 | reasons: elevation.reasons, |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /// Decide whether the workflow tool call requires an approval card (#4126). |
| 269 | #[must_use] |
| 270 | pub fn workflow_approval_requirement_for( |
| 271 | input: &Value, |
| 272 | config: &WorkflowConfigToml, |
| 273 | ) -> ApprovalRequirement { |
| 274 | let action = input |
| 275 | .get("action") |
| 276 | .and_then(Value::as_str) |
| 277 | .unwrap_or("start"); |
| 278 | match action { |
| 279 | "status" => ApprovalRequirement::Auto, |
| 280 | "cancel" => ApprovalRequirement::Required, |
| 281 | _ => { |
| 282 | let summary = analyze_workflow_plan_approval(input); |
| 283 | if summary.is_read_only_envelope() { |
| 284 | if config.auto_start_read_only { |
| 285 | ApprovalRequirement::Auto |
| 286 | } else { |
| 287 | ApprovalRequirement::Required |
| 288 | } |
| 289 | } else if config.require_approval_for_writes { |
| 290 | ApprovalRequirement::Required |
| 291 | } else { |
| 292 | ApprovalRequirement::Auto |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | fn empty_summary(goal: String, token_budget: Option<u64>) -> WorkflowPlanApprovalSummary { |
| 299 | WorkflowPlanApprovalSummary { |
| 300 | goal, |
| 301 | risk: None, |
| 302 | child_count: 0, |
| 303 | child_labels: Vec::new(), |
| 304 | child_summary: "0 children".into(), |
| 305 | phase_count: 0, |
| 306 | writes: false, |
| 307 | shell: false, |
| 308 | network: false, |
| 309 | secrets: false, |
| 310 | worktree: false, |
| 311 | broader_authority: false, |
| 312 | token_budget, |
| 313 | budget_label: budget_label(token_budget), |
| 314 | elevated: false, |
| 315 | reasons: Vec::new(), |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | fn analyze_plan_object(plan: &Value) -> WorkflowPlanApprovalSummary { |
| 320 | let goal = plan |
| 321 | .get("goal") |
| 322 | .and_then(Value::as_str) |
| 323 | .unwrap_or("") |
| 324 | .trim() |
| 325 | .to_string(); |
| 326 | let risk = plan |
| 327 | .get("risk") |
| 328 | .and_then(Value::as_str) |
| 329 | .map(str::trim) |
| 330 | .filter(|s| !s.is_empty()) |
| 331 | .map(str::to_string); |
| 332 | // Mirror structured-plan lowering's `plan_risk_to_mode` aliases exactly: |
| 333 | // child role identity never elevates an omitted/read-only plan mode. |
| 334 | let default_mode_is_write = matches!( |
| 335 | risk.as_deref(), |
| 336 | Some( |
| 337 | "writes" |
| 338 | | "write" |
| 339 | | "read_write" |
| 340 | | "readwrite" |
| 341 | | "medium" |
| 342 | | "elevated" |
| 343 | | "high" |
| 344 | | "shell" |
| 345 | | "network" |
| 346 | ) |
| 347 | ); |
| 348 | let token_budget = plan |
| 349 | .get("token_budget") |
| 350 | .and_then(Value::as_u64) |
| 351 | .or_else(|| { |
| 352 | plan.get("budget") |
| 353 | .and_then(|b| b.get("max_tokens")) |
| 354 | .and_then(Value::as_u64) |
| 355 | }); |
| 356 | |
| 357 | let mut child_labels = Vec::new(); |
| 358 | let mut child_count = 0usize; |
| 359 | let mut phase_count = 0usize; |
| 360 | let mut writes = false; |
| 361 | let mut shell = false; |
| 362 | let mut network = false; |
| 363 | let mut secrets = false; |
| 364 | let mut worktree = false; |
| 365 | |
| 366 | if let Some(phases) = plan.get("phases").and_then(Value::as_array) { |
| 367 | phase_count = phases.len(); |
| 368 | for phase in phases { |
| 369 | collect_children( |
| 370 | phase.get("children").and_then(Value::as_array), |
| 371 | &mut child_labels, |
| 372 | &mut child_count, |
| 373 | &mut writes, |
| 374 | &mut shell, |
| 375 | &mut network, |
| 376 | &mut secrets, |
| 377 | &mut worktree, |
| 378 | default_mode_is_write, |
| 379 | ); |
| 380 | } |
| 381 | } |
| 382 | collect_children( |
| 383 | plan.get("children").and_then(Value::as_array), |
| 384 | &mut child_labels, |
| 385 | &mut child_count, |
| 386 | &mut writes, |
| 387 | &mut shell, |
| 388 | &mut network, |
| 389 | &mut secrets, |
| 390 | &mut worktree, |
| 391 | default_mode_is_write, |
| 392 | ); |
| 393 | |
| 394 | if default_mode_is_write { |
| 395 | writes = true; |
| 396 | shell = shell || matches!(risk.as_deref(), Some("elevated" | "high" | "shell")); |
| 397 | network = network || matches!(risk.as_deref(), Some("elevated" | "high" | "network")); |
| 398 | } |
| 399 | |
| 400 | // Parallel write children default to worktree isolation (#4120). |
| 401 | if writes && child_count > 1 { |
| 402 | worktree = true; |
| 403 | } |
| 404 | |
| 405 | let mut reasons = Vec::new(); |
| 406 | if writes { |
| 407 | reasons.push("writes".into()); |
| 408 | } |
| 409 | if shell { |
| 410 | reasons.push("shell".into()); |
| 411 | } |
| 412 | if network { |
| 413 | reasons.push("network".into()); |
| 414 | } |
| 415 | if secrets { |
| 416 | reasons.push("secrets".into()); |
| 417 | } |
| 418 | if worktree { |
| 419 | reasons.push("worktree".into()); |
| 420 | } |
| 421 | let elevated = !reasons.is_empty(); |
| 422 | |
| 423 | let child_summary = if child_labels.is_empty() { |
| 424 | format!( |
| 425 | "{child_count} child{}", |
| 426 | if child_count == 1 { "" } else { "ren" } |
| 427 | ) |
| 428 | } else { |
| 429 | let shown: Vec<_> = child_labels.iter().take(4).map(String::as_str).collect(); |
| 430 | let mut line = format!( |
| 431 | "{child_count} child{}: {}", |
| 432 | if child_count == 1 { "" } else { "ren" }, |
| 433 | shown.join(", ") |
| 434 | ); |
| 435 | if child_labels.len() > 4 { |
| 436 | line.push_str(", …"); |
| 437 | } |
| 438 | line |
| 439 | }; |
| 440 | |
| 441 | WorkflowPlanApprovalSummary { |
| 442 | goal, |
| 443 | risk, |
| 444 | child_count, |
| 445 | child_labels, |
| 446 | child_summary, |
| 447 | phase_count, |
| 448 | writes, |
| 449 | shell, |
| 450 | network, |
| 451 | secrets, |
| 452 | worktree, |
| 453 | broader_authority: false, |
| 454 | token_budget, |
| 455 | budget_label: budget_label(token_budget), |
| 456 | elevated, |
| 457 | reasons, |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | #[allow(clippy::too_many_arguments)] |
| 462 | fn collect_children( |
| 463 | children: Option<&Vec<Value>>, |
| 464 | labels: &mut Vec<String>, |
| 465 | count: &mut usize, |
| 466 | writes: &mut bool, |
| 467 | shell: &mut bool, |
| 468 | network: &mut bool, |
| 469 | secrets: &mut bool, |
| 470 | worktree: &mut bool, |
| 471 | default_mode_is_write: bool, |
| 472 | ) { |
| 473 | let Some(children) = children else { |
| 474 | return; |
| 475 | }; |
| 476 | for child in children { |
| 477 | *count += 1; |
| 478 | if let Some(label) = child |
| 479 | .get("label") |
| 480 | .or_else(|| child.get("id")) |
| 481 | .and_then(Value::as_str) |
| 482 | { |
| 483 | labels.push(label.to_string()); |
| 484 | } |
| 485 | let mode = child |
| 486 | .get("mode") |
| 487 | .and_then(Value::as_str) |
| 488 | .unwrap_or_default() |
| 489 | .trim() |
| 490 | .to_ascii_lowercase(); |
| 491 | let agent_type = child |
| 492 | .get("type") |
| 493 | .or_else(|| child.get("agent_type")) |
| 494 | .and_then(Value::as_str) |
| 495 | .unwrap_or("general") |
| 496 | .trim() |
| 497 | .to_ascii_lowercase(); |
| 498 | let effective_read_write = match mode.as_str() { |
| 499 | "read_only" | "readonly" => false, |
| 500 | "read_write" | "readwrite" | "writes" | "write" => true, |
| 501 | "" => default_mode_is_write, |
| 502 | other => other.contains("write") && !other.contains("read_only"), |
| 503 | }; |
| 504 | if effective_read_write { |
| 505 | *writes = true; |
| 506 | // Write-capable builders/workers may run shell beyond read-only. |
| 507 | // Keep the legacy runtime names for stored Workflow plans. |
| 508 | if matches!( |
| 509 | agent_type.as_str(), |
| 510 | "builder" | "implement" | "implementer" | "worker" | "general" |
| 511 | ) { |
| 512 | *shell = true; |
| 513 | } |
| 514 | } |
| 515 | if child |
| 516 | .get("permissions") |
| 517 | .and_then(|p| p.get("allow_write")) |
| 518 | .and_then(Value::as_bool) |
| 519 | == Some(true) |
| 520 | { |
| 521 | *writes = true; |
| 522 | } |
| 523 | if child |
| 524 | .get("permissions") |
| 525 | .and_then(|p| p.get("allow_network")) |
| 526 | .and_then(Value::as_bool) |
| 527 | == Some(true) |
| 528 | { |
| 529 | *network = true; |
| 530 | } |
| 531 | let isolation = child |
| 532 | .get("isolation") |
| 533 | .and_then(Value::as_str) |
| 534 | .unwrap_or_default(); |
| 535 | if isolation == "worktree" { |
| 536 | *worktree = true; |
| 537 | } |
| 538 | if let Some(tools) = child |
| 539 | .get("permissions") |
| 540 | .and_then(|p| p.get("allowed_tools")) |
| 541 | .and_then(Value::as_array) |
| 542 | { |
| 543 | for tool in tools { |
| 544 | let authority = tool_name_authority(tool.as_str().unwrap_or_default()); |
| 545 | *shell |= authority.shell; |
| 546 | *network |= authority.network; |
| 547 | *writes |= authority.writes; |
| 548 | *secrets |= authority.secrets; |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | /// Tool names a script quotes, in any quote style (`"Web"`, `'Web'`, |
| 555 | /// `` `Web` ``), combined. Only identifier-like literals count, so prompt |
| 556 | /// text in the script is not read as a tool name. |
| 557 | fn script_tool_authority(script: &str) -> ToolAuthority { |
| 558 | let mut authority = ToolAuthority::default(); |
| 559 | let mut chars = script.chars(); |
| 560 | while let Some(c) = chars.next() { |
| 561 | if !matches!(c, '"' | '\'' | '`') { |
| 562 | continue; |
| 563 | } |
| 564 | let mut literal = String::new(); |
| 565 | let mut escaped = false; |
| 566 | for next in chars.by_ref() { |
| 567 | if escaped { |
| 568 | escaped = false; |
| 569 | } else if next == '\\' { |
| 570 | escaped = true; |
| 571 | } else if next == c { |
| 572 | break; |
| 573 | } |
| 574 | literal.push(next); |
| 575 | } |
| 576 | let looks_like_tool = !literal.is_empty() |
| 577 | && literal.len() <= 64 |
| 578 | && literal |
| 579 | .chars() |
| 580 | .next() |
| 581 | .is_some_and(|first| first.is_ascii_alphabetic()) |
| 582 | && literal.chars().all(|ch| { |
| 583 | ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-' | '(' | ')' | '*' | ' ') |
| 584 | }); |
| 585 | if looks_like_tool { |
| 586 | let found = tool_name_authority(&literal); |
| 587 | authority.shell |= found.shell; |
| 588 | authority.network |= found.network; |
| 589 | authority.writes |= found.writes; |
| 590 | authority.secrets |= found.secrets; |
| 591 | } |
| 592 | } |
| 593 | authority |
| 594 | } |
| 595 | |
| 596 | fn script_suggests_writes(script: &str) -> bool { |
| 597 | let lower = script.to_ascii_lowercase(); |
| 598 | lower.contains("implementer") |
| 599 | || lower.contains("read_write") |
| 600 | || lower.contains("allow_write") |
| 601 | || lower.contains("write_file") |
| 602 | || lower.contains("\"write\"") |
| 603 | || lower.contains("\"edit\"") |
| 604 | || lower.contains("\"file\"") |
| 605 | || lower.contains("apply_patch") |
| 606 | || script_tool_authority(script).writes |
| 607 | } |
| 608 | |
| 609 | fn script_suggests_shell(script: &str) -> bool { |
| 610 | let lower = script.to_ascii_lowercase(); |
| 611 | lower.contains("exec_shell") |
| 612 | || lower.contains("\"bash\"") |
| 613 | || lower.contains("bash(") |
| 614 | || ((lower.contains("allowedtools") || lower.contains("allowed_tools")) |
| 615 | && (lower.contains("shell") || lower.contains("bash"))) |
| 616 | || script_tool_authority(script).shell |
| 617 | } |
| 618 | |
| 619 | fn script_suggests_network(script: &str) -> bool { |
| 620 | let lower = script.to_ascii_lowercase(); |
| 621 | lower.contains("allow_network") |
| 622 | || lower.contains("web_search") |
| 623 | || lower.contains("fetch_url") |
| 624 | || lower.contains("\"web\"") |
| 625 | || script_tool_authority(script).network |
| 626 | } |
| 627 | |
| 628 | fn count_script_tasks(script: &str) -> usize { |
| 629 | script.matches("task(").count() |
| 630 | } |
| 631 | |
| 632 | fn budget_label(token_budget: Option<u64>) -> String { |
| 633 | match token_budget { |
| 634 | Some(n) => format!("{n} tokens"), |
| 635 | None => "unbounded".to_string(), |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | fn yn(v: bool) -> &'static str { |
| 640 | if v { "yes" } else { "no" } |
| 641 | } |
| 642 | |
| 643 | fn truncate(s: &str, max: usize) -> String { |
| 644 | let s = s.trim(); |
| 645 | if s.chars().count() <= max { |
| 646 | s.to_string() |
| 647 | } else { |
| 648 | let mut out: String = s.chars().take(max.saturating_sub(1)).collect(); |
| 649 | out.push('…'); |
| 650 | out |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | #[cfg(test)] |
| 655 | mod tests { |
| 656 | use super::*; |
| 657 | use serde_json::json; |
| 658 | |
| 659 | fn config() -> WorkflowConfigToml { |
| 660 | WorkflowConfigToml::default() |
| 661 | } |
| 662 | |
| 663 | #[test] |
| 664 | fn read_only_plan_is_not_elevated_and_auto_starts() { |
| 665 | let input = json!({ |
| 666 | "action": "start", |
| 667 | "plan": { |
| 668 | "goal": "scout crates", |
| 669 | "risk": "read_only", |
| 670 | "token_budget": 50000, |
| 671 | "phases": [{ |
| 672 | "id": "scout", |
| 673 | "children": [ |
| 674 | { "id": "a", "prompt": "look left", "type": "explore" }, |
| 675 | { "id": "b", "prompt": "look right", "type": "explore" } |
| 676 | ] |
| 677 | }] |
| 678 | } |
| 679 | }); |
| 680 | let summary = analyze_workflow_plan_approval(&input); |
| 681 | assert!(!summary.elevated, "{summary:?}"); |
| 682 | assert_eq!(summary.child_count, 2); |
| 683 | assert_eq!(summary.phase_count, 1); |
| 684 | assert!(!summary.writes); |
| 685 | assert_eq!( |
| 686 | workflow_approval_requirement_for(&input, &config()), |
| 687 | ApprovalRequirement::Auto |
| 688 | ); |
| 689 | let fields = summary.card_fields(); |
| 690 | assert_eq!(fields.len(), 6); |
| 691 | assert!( |
| 692 | fields |
| 693 | .iter() |
| 694 | .any(|(k, v)| *k == "Goal" && v.contains("scout")) |
| 695 | ); |
| 696 | assert!(fields.iter().any(|(k, v)| *k == "Writes" && v == "no")); |
| 697 | assert!(fields.iter().any(|(k, v)| *k == "Shell" && v == "no")); |
| 698 | assert!(fields.iter().any(|(k, v)| *k == "Network" && v == "no")); |
| 699 | assert!(fields.iter().any(|(k, _)| *k == "Children")); |
| 700 | assert!(fields.iter().any(|(k, _)| *k == "Budget")); |
| 701 | let impacts = summary.approval_impacts(); |
| 702 | assert!(impacts.iter().any(|i| i.contains("Goal: scout"))); |
| 703 | assert!(impacts.iter().any(|i| i.contains("Writes: no"))); |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn write_plan_is_elevated_with_card_fields_and_requires_approval() { |
| 708 | let input = json!({ |
| 709 | "action": "start", |
| 710 | "plan": { |
| 711 | "goal": "land the fix", |
| 712 | "risk": "writes", |
| 713 | "token_budget": 120000, |
| 714 | "children": [ |
| 715 | { |
| 716 | "id": "builder", |
| 717 | "label": "impl", |
| 718 | "prompt": "patch it", |
| 719 | "type": "implementer", |
| 720 | "mode": "read_write" |
| 721 | } |
| 722 | ] |
| 723 | } |
| 724 | }); |
| 725 | let summary = analyze_workflow_plan_approval(&input); |
| 726 | assert!(summary.elevated); |
| 727 | assert!(summary.writes); |
| 728 | assert!(summary.shell); |
| 729 | assert_eq!( |
| 730 | workflow_approval_requirement_for(&input, &config()), |
| 731 | ApprovalRequirement::Required |
| 732 | ); |
| 733 | let fields = summary.card_fields(); |
| 734 | assert!(fields.iter().any(|(k, v)| *k == "Writes" && v == "yes")); |
| 735 | assert!(fields.iter().any(|(k, v)| *k == "Shell" && v == "yes")); |
| 736 | assert!( |
| 737 | fields |
| 738 | .iter() |
| 739 | .any(|(k, v)| *k == "Budget" && v.contains("120000")) |
| 740 | ); |
| 741 | let impacts = summary.approval_impacts(); |
| 742 | assert!(impacts.iter().any(|i| i.contains("Writes: yes"))); |
| 743 | assert!(impacts.iter().any(|i| i.contains("Approve to launch"))); |
| 744 | let receipt = summary.to_receipt("approved", 99); |
| 745 | assert_eq!(receipt.decision, "approved"); |
| 746 | assert_eq!(receipt.approved_at_ms, 99); |
| 747 | assert_eq!(receipt.goal, "land the fix"); |
| 748 | assert!(receipt.elevated); |
| 749 | assert!(receipt.writes); |
| 750 | } |
| 751 | |
| 752 | #[test] |
| 753 | fn capability_flags_match_tool_family_names_case_insensitively() { |
| 754 | let input = json!({ |
| 755 | "action": "start", |
| 756 | "plan": { |
| 757 | "goal": "scout", |
| 758 | "children": [{ |
| 759 | "prompt": "look", |
| 760 | "type": "explore", |
| 761 | "permissions": { "allowed_tools": ["Bash", "Web", "File"] } |
| 762 | }] |
| 763 | } |
| 764 | }); |
| 765 | let summary = analyze_workflow_plan_approval(&input); |
| 766 | assert!(summary.shell, "{summary:?}"); |
| 767 | assert!(summary.network, "{summary:?}"); |
| 768 | assert!(summary.writes, "{summary:?}"); |
| 769 | |
| 770 | let script = r#"task({ allowedTools: ["Web", "File"] })"#; |
| 771 | assert!(script_suggests_network(script)); |
| 772 | assert!(script_suggests_writes(script)); |
| 773 | } |
| 774 | |
| 775 | #[test] |
| 776 | fn capability_flags_cover_quote_styles_patterns_and_more_families() { |
| 777 | for script in [ |
| 778 | "task({ allowedTools: ['Web', 'File'] })", |
| 779 | "task({ allowedTools: [`Web`, `File`] })", |
| 780 | "task({ allowedTools: ['Web(*)', 'File(*)'] })", |
| 781 | ] { |
| 782 | assert!(script_suggests_network(script), "{script}"); |
| 783 | assert!(script_suggests_writes(script), "{script}"); |
| 784 | } |
| 785 | assert!(script_suggests_shell("task({ allowedTools: ['Bash'] })")); |
| 786 | // Prompt text that mentions a tool is not a tool name. |
| 787 | let prose = "task({ prompt: 'read the file and summarise the web page' })"; |
| 788 | assert!(!script_suggests_writes(prose)); |
| 789 | assert!(!script_suggests_network(prose)); |
| 790 | |
| 791 | let flags = |tools: Value| { |
| 792 | analyze_workflow_plan_approval(&json!({ |
| 793 | "action": "start", |
| 794 | "plan": { |
| 795 | "goal": "scout", |
| 796 | "children": [{ |
| 797 | "prompt": "look", |
| 798 | "type": "explore", |
| 799 | "permissions": { "allowed_tools": tools } |
| 800 | }] |
| 801 | } |
| 802 | })) |
| 803 | }; |
| 804 | let summary = flags(json!([" Web(*) ", "File(src/**)"])); |
| 805 | assert!(summary.network && summary.writes, "{summary:?}"); |
| 806 | let summary = flags(json!(["rlm"])); |
| 807 | assert!(summary.shell && summary.network, "{summary:?}"); |
| 808 | for family in ["github", "Git", "computer", "browser"] { |
| 809 | let summary = flags(json!([family])); |
| 810 | assert!(summary.network && summary.writes, "{family}: {summary:?}"); |
| 811 | } |
| 812 | for family in ["tasks", "automation", "Run"] { |
| 813 | let summary = flags(json!([family])); |
| 814 | assert!(summary.shell, "{family}: {summary:?}"); |
| 815 | } |
| 816 | // Read-only Git tools stay read-only. |
| 817 | let summary = flags(json!(["git_status", "git_diff"])); |
| 818 | assert!(!summary.network && !summary.writes, "{summary:?}"); |
| 819 | } |
| 820 | |
| 821 | #[test] |
| 822 | fn canonical_worker_role_flags_shell_for_write_plan() { |
| 823 | let input = json!({ |
| 824 | "action": "start", |
| 825 | "plan": { |
| 826 | "goal": "land the fix", |
| 827 | "children": [{ |
| 828 | "prompt": "patch it", |
| 829 | "type": "worker", |
| 830 | "mode": "read_write" |
| 831 | }] |
| 832 | } |
| 833 | }); |
| 834 | |
| 835 | let summary = analyze_workflow_plan_approval(&input); |
| 836 | assert!(summary.writes); |
| 837 | assert!(summary.shell); |
| 838 | } |
| 839 | |
| 840 | #[test] |
| 841 | fn lowercase_bash_is_classified_as_shell_authority() { |
| 842 | for script in [ |
| 843 | r#"{"allowed_tools":["bash"]}"#, |
| 844 | r#"bash({"command":"pwd"})"#, |
| 845 | ] { |
| 846 | assert!(script_suggests_shell(script), "{script}"); |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | #[test] |
| 851 | fn read_only_implementer_does_not_request_write_or_shell_authority() { |
| 852 | for child in [ |
| 853 | json!({ |
| 854 | "prompt": "review an implementation", |
| 855 | "type": "implementer", |
| 856 | "mode": "read_only" |
| 857 | }), |
| 858 | json!({ |
| 859 | "prompt": "review under the plan envelope", |
| 860 | "type": "implementer" |
| 861 | }), |
| 862 | ] { |
| 863 | let summary = analyze_workflow_plan_approval(&json!({ |
| 864 | "plan": { |
| 865 | "goal": "read-only implementation review", |
| 866 | "risk": "read_only", |
| 867 | "children": [child] |
| 868 | } |
| 869 | })); |
| 870 | assert!(!summary.writes, "{summary:?}"); |
| 871 | assert!(!summary.shell, "{summary:?}"); |
| 872 | assert!(!summary.elevated, "{summary:?}"); |
| 873 | } |
| 874 | |
| 875 | let omitted_risk = analyze_workflow_plan_approval(&json!({ |
| 876 | "plan": { |
| 877 | "goal": "default-safe implementation review", |
| 878 | "children": [{ "prompt": "inspect", "type": "implementer" }] |
| 879 | } |
| 880 | })); |
| 881 | assert!(!omitted_risk.writes, "{omitted_risk:?}"); |
| 882 | assert!(!omitted_risk.shell, "{omitted_risk:?}"); |
| 883 | |
| 884 | for risk in ["medium", "readwrite"] { |
| 885 | let write_default = analyze_workflow_plan_approval(&json!({ |
| 886 | "plan": { |
| 887 | "goal": "default writer", |
| 888 | "risk": risk, |
| 889 | "children": [{ "prompt": "patch" }] |
| 890 | } |
| 891 | })); |
| 892 | assert!(write_default.writes, "{risk}: {write_default:?}"); |
| 893 | assert!(write_default.shell, "{risk}: {write_default:?}"); |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | #[test] |
| 898 | fn elevated_risk_flags_shell_and_network() { |
| 899 | let summary = analyze_workflow_plan_approval(&json!({ |
| 900 | "plan": { |
| 901 | "goal": "full authority", |
| 902 | "risk": "elevated", |
| 903 | "children": [{ "prompt": "go", "type": "implementer" }] |
| 904 | } |
| 905 | })); |
| 906 | assert!(summary.elevated); |
| 907 | assert!(summary.writes); |
| 908 | assert!(summary.shell); |
| 909 | assert!(summary.network); |
| 910 | let fields = summary.card_fields(); |
| 911 | assert!(fields.iter().any(|(k, v)| *k == "Network" && v == "yes")); |
| 912 | } |
| 913 | |
| 914 | #[test] |
| 915 | fn secrets_and_network_tools_elevate() { |
| 916 | let summary = analyze_workflow_plan_approval(&json!({ |
| 917 | "plan": { |
| 918 | "goal": "creds", |
| 919 | "risk": "read_only", |
| 920 | "children": [{ |
| 921 | "id": "s", |
| 922 | "prompt": "read secrets", |
| 923 | "type": "explore", |
| 924 | "permissions": { |
| 925 | "allow_network": true, |
| 926 | "allowed_tools": ["read_secret", "fetch_url"] |
| 927 | } |
| 928 | }] |
| 929 | } |
| 930 | })); |
| 931 | assert!(summary.elevated); |
| 932 | assert!(summary.secrets); |
| 933 | assert!(summary.network); |
| 934 | } |
| 935 | |
| 936 | #[test] |
| 937 | fn status_is_auto_cancel_is_required() { |
| 938 | assert_eq!( |
| 939 | workflow_approval_requirement_for(&json!({"action": "status"}), &config()), |
| 940 | ApprovalRequirement::Auto |
| 941 | ); |
| 942 | assert_eq!( |
| 943 | workflow_approval_requirement_for( |
| 944 | &json!({"action": "cancel", "run_id": "x"}), |
| 945 | &config() |
| 946 | ), |
| 947 | ApprovalRequirement::Required |
| 948 | ); |
| 949 | } |
| 950 | |
| 951 | #[test] |
| 952 | fn require_approval_for_writes_true_blocks_write_start_read_only_stays_auto() { |
| 953 | let mut cfg = config(); |
| 954 | cfg.require_approval_for_writes = true; |
| 955 | cfg.auto_start_read_only = true; |
| 956 | let write_plan = json!({ |
| 957 | "action": "start", |
| 958 | "plan": { |
| 959 | "goal": "land the fix", |
| 960 | "risk": "writes", |
| 961 | "children": [{ |
| 962 | "prompt": "patch it", |
| 963 | "type": "implementer", |
| 964 | "mode": "read_write" |
| 965 | }] |
| 966 | } |
| 967 | }); |
| 968 | let read_only = json!({ |
| 969 | "action": "start", |
| 970 | "plan": { |
| 971 | "goal": "scout crates", |
| 972 | "risk": "read_only", |
| 973 | "children": [{ "prompt": "look", "type": "explore" }] |
| 974 | } |
| 975 | }); |
| 976 | assert_eq!( |
| 977 | workflow_approval_requirement_for(&write_plan, &cfg), |
| 978 | ApprovalRequirement::Required, |
| 979 | "require_approval_for_writes = true must require the card for a write start" |
| 980 | ); |
| 981 | assert_eq!( |
| 982 | workflow_approval_requirement_for(&read_only, &cfg), |
| 983 | ApprovalRequirement::Auto, |
| 984 | "auto_start_read_only = true must still auto-start a read-only plan" |
| 985 | ); |
| 986 | } |
| 987 | |
| 988 | #[test] |
| 989 | fn require_approval_for_writes_false_allows_elevated_auto() { |
| 990 | let mut cfg = config(); |
| 991 | cfg.require_approval_for_writes = false; |
| 992 | let input = json!({ |
| 993 | "action": "start", |
| 994 | "plan": { |
| 995 | "goal": "write freely", |
| 996 | "risk": "writes", |
| 997 | "children": [{ "prompt": "edit", "type": "implementer" }] |
| 998 | } |
| 999 | }); |
| 1000 | assert_eq!( |
| 1001 | workflow_approval_requirement_for(&input, &cfg), |
| 1002 | ApprovalRequirement::Auto |
| 1003 | ); |
| 1004 | } |
| 1005 | |
| 1006 | #[test] |
| 1007 | fn verify_gates_leave_the_read_only_envelope() { |
| 1008 | let plan = json!({ |
| 1009 | "goal": "scout crates", |
| 1010 | "risk": "read_only", |
| 1011 | "children": [{ "prompt": "look", "type": "explore" }] |
| 1012 | }); |
| 1013 | let without = json!({ "action": "start", "plan": plan.clone() }); |
| 1014 | let with_verify = json!({ "action": "start", "plan": plan, "verify": true }); |
| 1015 | assert_eq!( |
| 1016 | workflow_approval_requirement_for(&without, &config()), |
| 1017 | ApprovalRequirement::Auto |
| 1018 | ); |
| 1019 | let summary = analyze_workflow_plan_approval(&with_verify); |
| 1020 | assert!(summary.elevated && summary.shell, "{summary:?}"); |
| 1021 | assert!(summary.reasons.iter().any(|r| r == "verify_gates")); |
| 1022 | assert_eq!( |
| 1023 | workflow_approval_requirement_for(&with_verify, &config()), |
| 1024 | ApprovalRequirement::Required, |
| 1025 | "completion gates run workspace code and need the approval card" |
| 1026 | ); |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn script_launch_requires_approval() { |
| 1031 | assert_eq!( |
| 1032 | workflow_approval_requirement_for( |
| 1033 | &json!({"action": "start", "script": "return 1;"}), |
| 1034 | &config() |
| 1035 | ), |
| 1036 | ApprovalRequirement::Required |
| 1037 | ); |
| 1038 | } |
| 1039 | |
| 1040 | #[test] |
| 1041 | fn card_fields_always_six_required_labels() { |
| 1042 | let summary = analyze_workflow_plan_approval(&json!({ |
| 1043 | "plan": { |
| 1044 | "goal": "x", |
| 1045 | "risk": "read_only", |
| 1046 | "children": [{ "prompt": "y", "type": "explore" }] |
| 1047 | } |
| 1048 | })); |
| 1049 | let labels: Vec<_> = summary.card_fields().iter().map(|(k, _)| *k).collect(); |
| 1050 | assert_eq!( |
| 1051 | labels, |
| 1052 | vec!["Goal", "Children", "Writes", "Shell", "Network", "Budget"] |
| 1053 | ); |
| 1054 | } |
| 1055 | |
| 1056 | #[test] |
| 1057 | fn nodes_plan_read_only_step_with_canonical_tools_requires_approval() { |
| 1058 | let input = json!({ |
| 1059 | "action": "start", |
| 1060 | "plan": { |
| 1061 | "goal": "inspect with canonical tools", |
| 1062 | "nodes": [{ |
| 1063 | "agent": { |
| 1064 | "id": "scout", |
| 1065 | "prompt": "inspect", |
| 1066 | "agent_type": "explore", |
| 1067 | "mode": "read_only", |
| 1068 | "permissions": { |
| 1069 | "allowed_tools": ["Bash", "Web", "File"] |
| 1070 | } |
| 1071 | } |
| 1072 | }] |
| 1073 | } |
| 1074 | }); |
| 1075 | let summary = analyze_workflow_plan_approval(&input); |
| 1076 | assert!(summary.elevated, "{summary:?}"); |
| 1077 | assert!(summary.writes, "{summary:?}"); |
| 1078 | assert!(summary.shell, "{summary:?}"); |
| 1079 | assert!(summary.network, "{summary:?}"); |
| 1080 | assert_eq!( |
| 1081 | workflow_approval_requirement_for(&input, &config()), |
| 1082 | ApprovalRequirement::Required |
| 1083 | ); |
| 1084 | } |
| 1085 | } |
| 1086 |