返回 CodeWhale
elevation.rs
根目录 / crates / workflow / src / elevation.rs
1 //! Elevated Workflow plan assessment for approval cards (#4126).
2 //!
3 //! Pure, UI-free analysis of a [`WorkflowSpec`] (and optional planner risk
4 //! string) so callers can decide whether an operator approval card is required
5 //! and what fields that card should show.
6
7 use serde::{Deserialize, Serialize};
8
9 use crate::{
10 IsolationMode, LeafSpec, PermissionSpec, TaskMode, WorkflowNode, WorkflowSpec,
11 leaf_is_write_capable, leaf_wants_worktree,
12 };
13
14 /// Options that refine elevation assessment beyond the IR itself.
15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16 pub struct ElevationOptions {
17 /// Whether the parent session currently allows writes.
18 pub parent_allows_write: bool,
19 /// Whether the parent session currently allows network.
20 pub parent_allows_network: bool,
21 }
22
23 impl Default for ElevationOptions {
24 fn default() -> Self {
25 Self {
26 // Assume Act/read-write parent unless callers narrow posture.
27 parent_allows_write: true,
28 parent_allows_network: true,
29 }
30 }
31 }
32
33 /// Summary of why a Workflow plan needs (or does not need) elevated approval.
34 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35 pub struct WorkflowPlanElevation {
36 pub elevated: bool,
37 pub goal: String,
38 pub child_count: usize,
39 pub child_summary: String,
40 pub writes: bool,
41 pub shell: bool,
42 pub network: bool,
43 pub secrets: bool,
44 pub worktree: bool,
45 pub broader_authority: bool,
46 /// Human-readable budget line for the approval card.
47 pub budget_label: String,
48 /// Distinct elevation reasons (for audit / impact lines).
49 pub reasons: Vec<String>,
50 }
51
52 impl WorkflowPlanElevation {
53 /// Card field labels/values used by the TUI approval modal (#4126).
54 #[must_use]
55 pub fn card_fields(&self) -> Vec<(&'static str, String)> {
56 vec![
57 ("Goal", self.goal.clone()),
58 ("Children", self.child_summary.clone()),
59 ("Writes", yes_no(self.writes)),
60 ("Shell", yes_no(self.shell)),
61 ("Network", yes_no(self.network)),
62 ("Budget", self.budget_label.clone()),
63 ]
64 }
65
66 /// True when the plan is fully inside the read-only envelope.
67 #[must_use]
68 pub fn is_read_only_envelope(&self) -> bool {
69 !self.elevated
70 && !self.writes
71 && !self.shell
72 && !self.network
73 && !self.secrets
74 && !self.worktree
75 && !self.broader_authority
76 }
77 }
78
79 fn yes_no(flag: bool) -> String {
80 if flag {
81 "yes".to_string()
82 } else {
83 "no".to_string()
84 }
85 }
86
87 /// Assess elevation for a compiled [`WorkflowSpec`].
88 #[must_use]
89 pub fn assess_workflow_elevation(
90 spec: &WorkflowSpec,
91 options: ElevationOptions,
92 ) -> WorkflowPlanElevation {
93 let mut child_ids = Vec::new();
94 let mut writes = false;
95 let mut shell = false;
96 let mut network = false;
97 let mut secrets = false;
98 let mut worktree = false;
99
100 walk_nodes(
101 &spec.nodes,
102 /* parallel */ false,
103 &mut child_ids,
104 &mut writes,
105 &mut shell,
106 &mut network,
107 &mut secrets,
108 &mut worktree,
109 );
110
111 // Spec-level permissions also elevate.
112 merge_permissions(
113 &spec.permissions,
114 &mut writes,
115 &mut shell,
116 &mut network,
117 &mut secrets,
118 );
119
120 // The structured-plan lowerer stores its validated risk enum on
121 // `description`, while authored Workflow specs use that field for ordinary
122 // prose. Only consume recognized enum values here: treating free-form
123 // descriptions as unknown risk would falsely report writes, shell, and
124 // network in the approval receipt. Unknown planner risk remains fail-closed
125 // in `assess_plan_risk_string` and is rejected before structured lowering.
126 if let Some(risk) = embedded_plan_risk_hint(spec.description.as_deref()) {
127 apply_plan_risk_hint(Some(risk), &mut writes, &mut shell, &mut network);
128 }
129
130 let effective_tokens = spec.budget.max_tokens.filter(|n| *n > 0);
131
132 let broader_authority =
133 (!options.parent_allows_write && writes) || (!options.parent_allows_network && network);
134
135 let mut reasons = Vec::new();
136 if writes {
137 reasons.push("writes".to_string());
138 }
139 if shell {
140 reasons.push("shell".to_string());
141 }
142 if network {
143 reasons.push("network".to_string());
144 }
145 if secrets {
146 reasons.push("secrets".to_string());
147 }
148 if worktree {
149 reasons.push("worktree".to_string());
150 }
151 if broader_authority {
152 reasons.push("broader_authority".to_string());
153 }
154
155 let elevated = !reasons.is_empty();
156 let child_count = child_ids.len();
157 let child_summary = if child_ids.is_empty() {
158 "0 children".to_string()
159 } else if child_ids.len() <= 4 {
160 format!(
161 "{} child{}: {}",
162 child_ids.len(),
163 if child_ids.len() == 1 { "" } else { "ren" },
164 child_ids.join(", ")
165 )
166 } else {
167 format!(
168 "{} children: {}, {}… (+{})",
169 child_ids.len(),
170 child_ids[0],
171 child_ids[1],
172 child_ids.len() - 2
173 )
174 };
175
176 let budget_label = format_budget_label(effective_tokens, &spec.budget);
177
178 WorkflowPlanElevation {
179 elevated,
180 goal: spec.goal.clone(),
181 child_count,
182 child_summary,
183 writes,
184 shell,
185 network,
186 secrets,
187 worktree,
188 broader_authority,
189 budget_label,
190 reasons,
191 }
192 }
193
194 /// Lightweight assessment from a planner `risk` string alone (before IR lower).
195 #[must_use]
196 pub fn assess_plan_risk_string(risk: Option<&str>) -> PlanRiskHint {
197 match risk.map(str::trim).filter(|s| !s.is_empty()) {
198 None | Some("read_only") | Some("readonly") | Some("low") | Some("safe") => {
199 PlanRiskHint::ReadOnly
200 }
201 Some("writes") | Some("write") | Some("read_write") | Some("readwrite")
202 | Some("medium") => PlanRiskHint::Writes,
203 Some("shell") => PlanRiskHint::Shell,
204 Some("network") => PlanRiskHint::Network,
205 Some("elevated") | Some("high") => PlanRiskHint::Elevated,
206 Some(_) => PlanRiskHint::Elevated,
207 }
208 }
209
210 /// Coarse risk classification from the structured plan `risk` field.
211 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
212 pub enum PlanRiskHint {
213 ReadOnly,
214 Writes,
215 Shell,
216 Network,
217 Elevated,
218 }
219
220 impl PlanRiskHint {
221 #[must_use]
222 pub fn elevates(self) -> bool {
223 !matches!(self, Self::ReadOnly)
224 }
225 }
226
227 fn apply_plan_risk_hint(
228 risk: Option<&str>,
229 writes: &mut bool,
230 shell: &mut bool,
231 network: &mut bool,
232 ) {
233 match assess_plan_risk_string(risk) {
234 PlanRiskHint::ReadOnly => {}
235 PlanRiskHint::Writes => *writes = true,
236 PlanRiskHint::Shell => {
237 *shell = true;
238 *writes = true;
239 }
240 PlanRiskHint::Network => {
241 *network = true;
242 }
243 PlanRiskHint::Elevated => {
244 *writes = true;
245 *shell = true;
246 *network = true;
247 }
248 }
249 }
250
251 fn embedded_plan_risk_hint(description: Option<&str>) -> Option<&str> {
252 let value = description
253 .map(str::trim)
254 .filter(|value| !value.is_empty())?;
255 matches!(
256 value,
257 "read_only"
258 | "readonly"
259 | "low"
260 | "safe"
261 | "writes"
262 | "write"
263 | "read_write"
264 | "readwrite"
265 | "medium"
266 | "shell"
267 | "network"
268 | "elevated"
269 | "high"
270 )
271 .then_some(value)
272 }
273
274 fn format_budget_label(effective_tokens: Option<u64>, budget: &crate::BudgetSpec) -> String {
275 let mut parts = Vec::new();
276 if let Some(tokens) = effective_tokens {
277 parts.push(format!("{tokens} tokens"));
278 }
279 if let Some(steps) = budget.max_steps {
280 parts.push(format!("max_steps={steps}"));
281 }
282 if let Some(timeout) = budget.timeout_secs {
283 parts.push(format!("timeout={timeout}s"));
284 }
285 if let Some(parallel) = budget.max_parallel {
286 parts.push(format!("max_parallel={parallel}"));
287 }
288 if parts.is_empty() {
289 "default".to_string()
290 } else {
291 parts.join(", ")
292 }
293 }
294
295 #[allow(clippy::too_many_arguments)]
296 fn walk_nodes(
297 nodes: &[WorkflowNode],
298 parallel: bool,
299 child_ids: &mut Vec<String>,
300 writes: &mut bool,
301 shell: &mut bool,
302 network: &mut bool,
303 secrets: &mut bool,
304 worktree: &mut bool,
305 ) {
306 for node in nodes {
307 match node {
308 WorkflowNode::Leaf(leaf) => {
309 inspect_leaf(
310 leaf, parallel, child_ids, writes, shell, network, secrets, worktree,
311 );
312 }
313 WorkflowNode::BranchSet(branch) => {
314 merge_permissions(&branch.permissions, writes, shell, network, secrets);
315 walk_nodes(
316 &branch.children,
317 branch.parallel || parallel,
318 child_ids,
319 writes,
320 shell,
321 network,
322 secrets,
323 worktree,
324 );
325 }
326 WorkflowNode::Sequence(seq) => {
327 walk_nodes(
328 &seq.children,
329 parallel,
330 child_ids,
331 writes,
332 shell,
333 network,
334 secrets,
335 worktree,
336 );
337 }
338 WorkflowNode::Reduce(_) => {}
339 }
340 }
341 }
342
343 #[allow(clippy::too_many_arguments)]
344 fn inspect_leaf(
345 leaf: &LeafSpec,
346 parallel: bool,
347 child_ids: &mut Vec<String>,
348 writes: &mut bool,
349 shell: &mut bool,
350 network: &mut bool,
351 secrets: &mut bool,
352 worktree: &mut bool,
353 ) {
354 child_ids.push(leaf.id.clone());
355 if leaf_is_write_capable(leaf) {
356 *writes = true;
357 }
358 merge_permissions(&leaf.permissions, writes, shell, network, secrets);
359 if leaf_wants_worktree(leaf, parallel) || matches!(leaf.isolation, IsolationMode::Worktree) {
360 *worktree = true;
361 }
362 // Explicit read_write mode with shell tools already handled; implementer
363 // without a tool denylist can run shell.
364 if leaf.mode == TaskMode::ReadWrite
365 && leaf.permissions.allowed_tools.is_empty()
366 && matches!(
367 leaf.agent_type,
368 crate::AgentType::Implementer | crate::AgentType::General
369 )
370 {
371 // Write-capable implementers/general agents may run shell beyond
372 // read-only — flag shell as elevated for the approval card.
373 *shell = true;
374 }
375 }
376
377 fn merge_permissions(
378 permissions: &PermissionSpec,
379 writes: &mut bool,
380 shell: &mut bool,
381 network: &mut bool,
382 secrets: &mut bool,
383 ) {
384 if permissions.allow_write {
385 *writes = true;
386 }
387 if permissions.allow_network {
388 *network = true;
389 }
390 for tool in &permissions.allowed_tools {
391 let name = tool.trim();
392 let authority = tool_name_authority(name);
393 if is_write_tool(name) || authority.writes {
394 *writes = true;
395 }
396 if is_shell_tool(name) || authority.shell {
397 *shell = true;
398 }
399 if is_network_tool(name) || authority.network {
400 *network = true;
401 }
402 if is_secret_tool(name) || authority.secrets {
403 *secrets = true;
404 }
405 }
406 }
407
408 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
409 pub struct ToolAuthority {
410 pub shell: bool,
411 pub network: bool,
412 pub writes: bool,
413 pub secrets: bool,
414 }
415
416 #[must_use]
417 pub fn tool_name_authority(raw: &str) -> ToolAuthority {
418 let name = raw
419 .split('(')
420 .next()
421 .unwrap_or_default()
422 .trim()
423 .to_ascii_lowercase();
424 let name = name.as_str();
425 let mut authority = ToolAuthority::default();
426 if name.contains("shell")
427 || name.contains("exec")
428 || name.contains("bash")
429 || name == "run"
430 || name.starts_with("run_")
431 || name == "rlm"
432 {
433 authority.shell = true;
434 }
435 if name.contains("secret") || name.contains("credential") || name == "read_env" {
436 authority.secrets = true;
437 }
438 if matches!(
439 name,
440 "web" | "web_search" | "web_run" | "web.run" | "fetch_url" | "rlm" | "git_fetch"
441 ) || name.starts_with("mcp_")
442 {
443 authority.network = true;
444 }
445 if matches!(
446 name,
447 "file" | "write" | "edit" | "write_file" | "edit_file" | "apply_patch"
448 ) {
449 authority.writes = true;
450 }
451 if matches!(name, "git" | "github" | "gh") || name.starts_with("github_") {
452 authority.network = true;
453 authority.writes = true;
454 }
455 if name.starts_with("computer") || name.starts_with("browser") {
456 authority.network = true;
457 authority.writes = true;
458 }
459 if name.starts_with("computer") {
460 authority.shell = true;
461 }
462 if matches!(
463 name,
464 "task" | "tasks" | "task_create" | "automation" | "automations" | "automation_create"
465 ) {
466 authority.shell = true;
467 authority.writes = true;
468 }
469 authority
470 }
471
472 /// True for a tool that can modify files.
473 ///
474 /// This is the one list. It previously existed twice — here and as half of
475 /// the TUI's `is_write_or_shell_tool` — and the two drifted: `Edit`, the
476 /// model-visible canonical name for the write tool, was in the TUI copy and
477 /// missing here, so a branch or sequence whose `allowed_tools` was `["Edit"]`
478 /// produced an approval card reporting `writes: false` for a spec that could
479 /// in fact write.
480 pub fn is_write_tool(tool: &str) -> bool {
481 matches!(
482 tool.trim(),
483 "Edit"
484 | "write"
485 | "edit"
486 | "write_file"
487 | "edit_file"
488 | "fim_edit"
489 | "apply_patch"
490 | "checklist_write"
491 | "todo_write"
492 )
493 }
494
495 /// True for a tool that can run a shell command.
496 pub fn is_shell_tool(tool: &str) -> bool {
497 matches!(
498 tool.trim(),
499 "exec_shell"
500 | "exec_shell_wait"
501 | "exec_shell_interact"
502 | "exec_wait"
503 | "exec_interact"
504 | "task_shell_start"
505 | "task_shell_wait"
506 | "terminal_run"
507 | "terminal_send"
508 | "terminal_reset"
509 | "code_execution"
510 | "js_execution"
511 )
512 }
513
514 fn is_network_tool(tool: &str) -> bool {
515 matches!(
516 tool,
517 "web_search" | "web_run" | "fetch_url" | "wait_for_dev_server"
518 ) || tool.starts_with("mcp_")
519 }
520
521 fn is_secret_tool(tool: &str) -> bool {
522 let lower = tool.to_ascii_lowercase();
523 lower.contains("secret")
524 || lower.contains("credential")
525 || lower.contains("password")
526 || lower == "read_env"
527 || lower == "env"
528 }
529
530 #[cfg(test)]
531 mod tests {
532 use super::*;
533 use crate::{
534 AgentType, BranchSpec, BudgetSpec, LeafSpec, ModelPolicy, PermissionSpec, SequenceSpec,
535 TaskMode,
536 };
537
538 fn leaf(id: &str, mode: TaskMode) -> LeafSpec {
539 LeafSpec {
540 id: id.to_string(),
541 prompt: format!("do {id}"),
542 agent_type: if mode == TaskMode::ReadWrite {
543 AgentType::Implementer
544 } else {
545 AgentType::Explore
546 },
547 profile: None,
548 role: None,
549 mode,
550 isolation: IsolationMode::Auto,
551 file_scope: Vec::new(),
552 cwd: None,
553 depends_on_results: Vec::new(),
554 budget: BudgetSpec::default(),
555 permissions: PermissionSpec::default(),
556 model_policy: ModelPolicy::default(),
557 }
558 }
559
560 #[test]
561 fn edit_is_recognized_as_a_write_tool() {
562 // #4730: `Edit` is the model-visible canonical write-tool name. It
563 // lived only in the TUI's copy of this list, so the risk assessor
564 // didn't know it was a write.
565 assert!(is_write_tool("Edit"));
566 assert!(is_write_tool(" Edit "));
567 for tool in [
568 "write",
569 "edit",
570 "write_file",
571 "edit_file",
572 "fim_edit",
573 "apply_patch",
574 "checklist_write",
575 "todo_write",
576 ] {
577 assert!(is_write_tool(tool), "{tool} must count as a write");
578 }
579 assert!(!is_write_tool("read_file"));
580 assert!(!is_write_tool("Editor"));
581 for tool in ["terminal_run", "terminal_send", "code_execution"] {
582 assert!(is_shell_tool(tool), "{tool} must count as shell");
583 }
584 }
585
586 #[test]
587 fn branch_allowing_edit_reports_writes_in_its_risk_summary() {
588 // The tool-allowlist path is what produces branch/sequence-level
589 // permission summaries; a spec that can write must not present an
590 // approval card saying it cannot.
591 let spec = spec_with(
592 vec![WorkflowNode::BranchSet(BranchSpec {
593 id: "edits".to_string(),
594 description: None,
595 parallel: false,
596 budget: BudgetSpec::default(),
597 permissions: PermissionSpec {
598 allowed_tools: vec!["Edit".to_string()],
599 ..PermissionSpec::default()
600 },
601 model_policy: ModelPolicy::default(),
602 children: vec![WorkflowNode::Leaf(leaf("child", TaskMode::ReadOnly))],
603 })],
604 None,
605 );
606
607 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
608 assert!(
609 elevation.writes,
610 "branch allowing Edit must report writes: {elevation:?}"
611 );
612 }
613
614 fn spec_with(nodes: Vec<WorkflowNode>, risk: Option<&str>) -> WorkflowSpec {
615 WorkflowSpec {
616 id: Some("test".to_string()),
617 goal: "ship feature".to_string(),
618 description: risk.map(str::to_string),
619 budget: BudgetSpec::default(),
620 permissions: PermissionSpec::default(),
621 model_policy: ModelPolicy::default(),
622 gates: Vec::new(),
623 nodes,
624 }
625 }
626
627 #[test]
628 fn read_only_plan_is_not_elevated() {
629 let spec = spec_with(
630 vec![WorkflowNode::Leaf(leaf("scan", TaskMode::ReadOnly))],
631 Some("read_only"),
632 );
633 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
634 assert!(!elevation.elevated, "{elevation:?}");
635 assert!(elevation.is_read_only_envelope());
636 assert_eq!(elevation.goal, "ship feature");
637 assert!(elevation.child_summary.contains("scan"));
638 assert!(!elevation.writes);
639 assert!(!elevation.shell);
640 assert!(!elevation.network);
641 let fields = elevation.card_fields();
642 assert_eq!(fields.len(), 6);
643 assert!(
644 fields
645 .iter()
646 .any(|(k, v)| *k == "Goal" && v == "ship feature")
647 );
648 assert!(fields.iter().any(|(k, v)| *k == "Writes" && v == "no"));
649 }
650
651 #[test]
652 fn free_form_description_is_not_treated_as_plan_risk() {
653 let spec = spec_with(
654 vec![WorkflowNode::Leaf(leaf("scan", TaskMode::ReadOnly))],
655 Some(
656 "Read-only release acceptance fixture; no step edits files or accesses the network.",
657 ),
658 );
659
660 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
661 assert!(elevation.is_read_only_envelope(), "{elevation:?}");
662 assert!(!elevation.writes, "{elevation:?}");
663 assert!(!elevation.shell, "{elevation:?}");
664 assert!(!elevation.network, "{elevation:?}");
665 assert!(elevation.reasons.is_empty(), "{elevation:?}");
666 }
667
668 #[test]
669 fn read_only_implementer_role_is_not_write_capable_or_elevated() {
670 let mut implementer = leaf("verify-only", TaskMode::ReadOnly);
671 implementer.agent_type = AgentType::Implementer;
672 implementer.role = Some("implementer".to_string());
673 let spec = spec_with(
674 vec![WorkflowNode::BranchSet(BranchSpec {
675 id: "parallel-read-only".to_string(),
676 description: None,
677 parallel: true,
678 budget: BudgetSpec::default(),
679 permissions: PermissionSpec::default(),
680 model_policy: ModelPolicy::default(),
681 children: vec![WorkflowNode::Leaf(implementer)],
682 })],
683 Some("read_only"),
684 );
685
686 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
687 assert!(elevation.is_read_only_envelope(), "{elevation:?}");
688 assert!(!elevation.elevated, "{elevation:?}");
689 assert!(!elevation.writes, "{elevation:?}");
690 assert!(!elevation.shell, "{elevation:?}");
691 assert!(!elevation.worktree, "{elevation:?}");
692 }
693
694 #[test]
695 fn write_plan_elevates_and_flags_shell_for_implementer() {
696 let spec = spec_with(
697 vec![WorkflowNode::Leaf(leaf("impl", TaskMode::ReadWrite))],
698 Some("writes"),
699 );
700 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
701 assert!(elevation.elevated);
702 assert!(elevation.writes);
703 assert!(elevation.shell);
704 assert!(elevation.reasons.iter().any(|r| r == "writes"));
705 }
706
707 #[test]
708 fn network_and_secrets_tools_elevate() {
709 let mut network_leaf = leaf("fetch", TaskMode::ReadOnly);
710 network_leaf.permissions.allow_network = true;
711 network_leaf.permissions.allowed_tools = vec!["fetch_url".to_string()];
712
713 let mut secret_leaf = leaf("creds", TaskMode::ReadOnly);
714 secret_leaf.permissions.allowed_tools = vec!["read_secret".to_string()];
715
716 let spec = spec_with(
717 vec![WorkflowNode::Sequence(SequenceSpec {
718 id: "seq".to_string(),
719 children: vec![
720 WorkflowNode::Leaf(network_leaf),
721 WorkflowNode::Leaf(secret_leaf),
722 ],
723 })],
724 None,
725 );
726 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
727 assert!(elevation.elevated);
728 assert!(elevation.network);
729 assert!(elevation.secrets);
730 assert!(elevation.reasons.iter().any(|r| r == "network"));
731 assert!(elevation.reasons.iter().any(|r| r == "secrets"));
732 }
733
734 #[test]
735 fn parallel_write_children_flag_worktree() {
736 let left = leaf("left", TaskMode::ReadWrite);
737 let right = leaf("right", TaskMode::ReadWrite);
738 let spec = spec_with(
739 vec![WorkflowNode::BranchSet(BranchSpec {
740 id: "parallel".to_string(),
741 description: None,
742 parallel: true,
743 budget: BudgetSpec::default(),
744 permissions: PermissionSpec::default(),
745 model_policy: ModelPolicy::default(),
746 children: vec![WorkflowNode::Leaf(left), WorkflowNode::Leaf(right)],
747 })],
748 Some("writes"),
749 );
750 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
751 assert!(elevation.worktree, "{elevation:?}");
752 assert!(elevation.writes);
753 }
754
755 #[test]
756 fn broader_authority_when_parent_is_read_only() {
757 let spec = spec_with(
758 vec![WorkflowNode::Leaf(leaf("impl", TaskMode::ReadWrite))],
759 Some("writes"),
760 );
761 let elevation = assess_workflow_elevation(
762 &spec,
763 ElevationOptions {
764 parent_allows_write: false,
765 parent_allows_network: false,
766 },
767 );
768 assert!(elevation.broader_authority);
769 assert!(elevation.reasons.iter().any(|r| r == "broader_authority"));
770 }
771
772 #[test]
773 fn plan_risk_string_classifies_elevated_variants() {
774 assert_eq!(
775 assess_plan_risk_string(Some("read_only")),
776 PlanRiskHint::ReadOnly
777 );
778 assert_eq!(
779 assess_plan_risk_string(Some("writes")),
780 PlanRiskHint::Writes
781 );
782 assert_eq!(assess_plan_risk_string(Some("shell")), PlanRiskHint::Shell);
783 assert_eq!(
784 assess_plan_risk_string(Some("network")),
785 PlanRiskHint::Network
786 );
787 assert_eq!(
788 assess_plan_risk_string(Some("elevated")),
789 PlanRiskHint::Elevated
790 );
791 assert_eq!(
792 assess_plan_risk_string(Some("unknown-risk")),
793 PlanRiskHint::Elevated,
794 "unknown planner risk must remain fail-closed"
795 );
796 assert!(assess_plan_risk_string(Some("elevated")).elevates());
797 assert!(!assess_plan_risk_string(Some("read_only")).elevates());
798 }
799
800 #[test]
801 fn card_fields_always_include_required_labels() {
802 let spec = spec_with(
803 vec![WorkflowNode::Leaf(leaf("a", TaskMode::ReadOnly))],
804 None,
805 );
806 let fields = assess_workflow_elevation(&spec, ElevationOptions::default()).card_fields();
807 let labels: Vec<_> = fields.iter().map(|(k, _)| *k).collect();
808 assert_eq!(
809 labels,
810 vec!["Goal", "Children", "Writes", "Shell", "Network", "Budget"]
811 );
812 }
813
814 #[test]
815 fn read_only_leaf_with_canonical_tool_families_elevates() {
816 let mut inspect = leaf("inspect", TaskMode::ReadOnly);
817 inspect.permissions.allowed_tools =
818 vec!["Bash".to_string(), "Web".to_string(), "File".to_string()];
819 let spec = spec_with(vec![WorkflowNode::Leaf(inspect)], Some("read_only"));
820 let elevation = assess_workflow_elevation(&spec, ElevationOptions::default());
821 assert!(elevation.elevated, "{elevation:?}");
822 assert!(elevation.writes, "{elevation:?}");
823 assert!(elevation.shell, "{elevation:?}");
824 assert!(elevation.network, "{elevation:?}");
825 assert_eq!(
826 elevation.reasons,
827 vec![
828 "writes".to_string(),
829 "shell".to_string(),
830 "network".to_string()
831 ]
832 );
833 }
834 }
835
835 lines RUST