1mod types;
4
5use std::cell::RefCell;
6use std::collections::BTreeMap;
7use std::rc::Rc;
8use std::thread_local;
9
10use serde::{Deserialize, Serialize};
11
12use super::glob_match;
13use crate::event_log::{active_event_log, EventLog, LogEvent, Topic};
14use crate::tool_annotations::{SideEffectLevel, ToolAnnotations};
15use crate::triggers::dispatcher::current_dispatch_context;
16use crate::trust_graph::AutonomyTier;
17use crate::value::{VmError, VmValue};
18use crate::workspace_path::{classify_workspace_path, WorkspacePathInfo};
19
20pub use crate::tool_annotations::{ToolArgSchema, ToolKind};
21pub use types::{
22 enforce_tool_arg_constraints, AutoCompactPolicy, BranchSemantics, CapabilityPolicy,
23 ContextPolicy, EqIgnored, EscalationPolicy, JoinPolicy, MapPolicy, ModelPolicy,
24 NativeToolFallbackPolicy, ReducePolicy, RetryPolicy, StageContract, ToolArgConstraint,
25 TurnPolicy,
26};
27
28thread_local! {
29 static EXECUTION_POLICY_STACK: RefCell<Vec<CapabilityPolicy>> = const { RefCell::new(Vec::new()) };
30 static EXECUTION_APPROVAL_POLICY_STACK: RefCell<Vec<ToolApprovalPolicy>> = const { RefCell::new(Vec::new()) };
31 static TRUSTED_BRIDGE_CALL_DEPTH: RefCell<usize> = const { RefCell::new(0) };
32}
33
34pub fn push_execution_policy(policy: CapabilityPolicy) {
35 EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
36}
37
38pub fn pop_execution_policy() {
39 EXECUTION_POLICY_STACK.with(|stack| {
40 stack.borrow_mut().pop();
41 });
42}
43
44pub fn current_execution_policy() -> Option<CapabilityPolicy> {
45 EXECUTION_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
46}
47
48pub fn push_approval_policy(policy: ToolApprovalPolicy) {
49 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
50}
51
52pub fn pop_approval_policy() {
53 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| {
54 stack.borrow_mut().pop();
55 });
56}
57
58pub fn current_approval_policy() -> Option<ToolApprovalPolicy> {
59 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
60}
61
62pub fn current_tool_annotations(tool: &str) -> Option<ToolAnnotations> {
63 current_execution_policy().and_then(|policy| policy.tool_annotations.get(tool).cloned())
64}
65
66fn tool_kind_participates_in_write_allowlist(tool_name: &str) -> bool {
67 current_tool_annotations(tool_name)
68 .map(|annotations| !annotations.kind.is_read_only())
69 .unwrap_or(true)
70}
71
72pub struct TrustedBridgeCallGuard;
73
74pub fn allow_trusted_bridge_calls() -> TrustedBridgeCallGuard {
75 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
76 *depth.borrow_mut() += 1;
77 });
78 TrustedBridgeCallGuard
79}
80
81impl Drop for TrustedBridgeCallGuard {
82 fn drop(&mut self) {
83 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
84 let mut depth = depth.borrow_mut();
85 *depth = depth.saturating_sub(1);
86 });
87 }
88}
89
90fn policy_allows_tool(policy: &CapabilityPolicy, tool: &str) -> bool {
91 policy.tools.is_empty() || policy.tools.iter().any(|allowed| allowed == tool)
92}
93
94fn policy_allows_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
95 policy.capabilities.is_empty()
96 || policy
97 .capabilities
98 .get(capability)
99 .is_some_and(|ops| ops.is_empty() || ops.iter().any(|allowed| allowed == op))
100}
101
102fn policy_allows_side_effect(policy: &CapabilityPolicy, requested: &str) -> bool {
103 fn rank(v: &str) -> usize {
104 match v {
105 "none" => 0,
106 "read_only" => 1,
107 "workspace_write" => 2,
108 "process_exec" => 3,
109 "network" => 4,
110 _ => 5,
111 }
112 }
113 policy
114 .side_effect_level
115 .as_ref()
116 .map(|allowed| rank(allowed) >= rank(requested))
117 .unwrap_or(true)
118}
119
120pub(super) fn reject_policy(reason: String) -> Result<(), VmError> {
121 Err(VmError::CategorizedError {
122 message: reason,
123 category: crate::value::ErrorCategory::ToolRejected,
124 })
125}
126
127pub fn current_tool_mutation_classification(tool_name: &str) -> String {
132 current_tool_annotations(tool_name)
133 .map(|annotations| annotations.kind.mutation_class().to_string())
134 .unwrap_or_else(|| "other".to_string())
135}
136
137pub fn current_tool_declared_paths(tool_name: &str, args: &serde_json::Value) -> Vec<String> {
141 current_tool_declared_path_entries(tool_name, args)
142 .into_iter()
143 .map(|entry| entry.display_path().to_string())
144 .collect()
145}
146
147pub fn current_tool_declared_path_entries(
152 tool_name: &str,
153 args: &serde_json::Value,
154) -> Vec<WorkspacePathInfo> {
155 let Some(map) = args.as_object() else {
156 return Vec::new();
157 };
158 let Some(annotations) = current_tool_annotations(tool_name) else {
159 return Vec::new();
160 };
161 let workspace_root = crate::stdlib::process::execution_root_path();
162 let mut entries = Vec::new();
163 for key in &annotations.arg_schema.path_params {
164 if let Some(value) = map.get(key) {
165 match value {
166 serde_json::Value::String(path) if !path.is_empty() => {
167 entries.push(classify_workspace_path(path, Some(&workspace_root)));
168 }
169 serde_json::Value::Array(items) => {
170 for item in items.iter().filter_map(|item| item.as_str()) {
171 if !item.is_empty() {
172 entries.push(classify_workspace_path(item, Some(&workspace_root)));
173 }
174 }
175 }
176 _ => {}
177 }
178 }
179 }
180 entries.sort_by(|a, b| a.display_path().cmp(b.display_path()));
181 entries.dedup_by(|left, right| left.policy_candidates() == right.policy_candidates());
182 entries
183}
184
185fn builtin_mutates_state(name: &str) -> bool {
186 matches!(
187 name,
188 "write_file"
189 | "append_file"
190 | "mkdir"
191 | "copy_file"
192 | "delete_file"
193 | "apply_edit"
194 | "exec"
195 | "exec_at"
196 | "shell"
197 | "shell_at"
198 | "host_call"
199 | "store_set"
200 | "store_delete"
201 | "store_save"
202 | "store_clear"
203 | "metadata_set"
204 | "metadata_save"
205 | "metadata_refresh_hashes"
206 | "invalidate_facts"
207 | "checkpoint"
208 | "checkpoint_delete"
209 | "checkpoint_clear"
210 | "__agent_state_write"
211 | "__agent_state_delete"
212 | "__agent_state_handoff"
213 | "mcp_release"
214 )
215}
216
217fn emit_autonomy_proposal_event(
218 tier: AutonomyTier,
219 builtin_name: &str,
220 args: &[VmValue],
221) -> Result<(), VmError> {
222 let Some(context) = current_dispatch_context() else {
223 return Ok(());
224 };
225 let Some(log) = active_event_log() else {
226 return Ok(());
227 };
228 let topic = Topic::new(crate::TRIGGER_OUTBOX_TOPIC)
229 .map_err(|error| VmError::Runtime(format!("autonomy proposal topic error: {error}")))?;
230 let mut headers = BTreeMap::new();
231 headers.insert(
232 "trace_id".to_string(),
233 context.trigger_event.trace_id.0.clone(),
234 );
235 headers.insert("agent".to_string(), context.agent_id.clone());
236 headers.insert("autonomy_tier".to_string(), tier.as_str().to_string());
237 let payload = serde_json::json!({
238 "agent": context.agent_id,
239 "action": context.action,
240 "builtin": builtin_name,
241 "args": args.iter().map(crate::llm::vm_value_to_json).collect::<Vec<_>>(),
242 "trace_id": context.trigger_event.trace_id.0,
243 "replay_of_event_id": context.replay_of_event_id,
244 "autonomy_tier": tier,
245 "proposal": true,
246 });
247 futures::executor::block_on(log.append(
248 &topic,
249 LogEvent::new("dispatch_proposed", payload).with_headers(headers),
250 ))
251 .map(|_| ())
252 .map_err(|error| VmError::Runtime(format!("failed to append autonomy proposal: {error}")))
253}
254
255fn enforce_dispatch_autonomy_for_builtin(name: &str, args: &[VmValue]) -> Result<(), VmError> {
256 let Some(context) = current_dispatch_context() else {
257 return Ok(());
258 };
259 if !builtin_mutates_state(name) {
260 return Ok(());
261 }
262 match context.autonomy_tier {
263 AutonomyTier::Shadow => {
264 emit_autonomy_proposal_event(AutonomyTier::Shadow, name, args)?;
265 Ok(())
266 }
267 AutonomyTier::Suggest => {
268 emit_autonomy_proposal_event(AutonomyTier::Suggest, name, args)?;
269 Ok(())
270 }
271 AutonomyTier::ActWithApproval | AutonomyTier::ActAuto => Ok(()),
272 }
273}
274
275pub fn enforce_current_policy_for_builtin(name: &str, args: &[VmValue]) -> Result<(), VmError> {
276 enforce_dispatch_autonomy_for_builtin(name, args)?;
277 let Some(policy) = current_execution_policy() else {
278 return Ok(());
279 };
280 match name {
281 "read_file" if !policy_allows_capability(&policy, "workspace", "read_text") => {
282 return reject_policy(format!(
283 "builtin '{name}' exceeds workspace.read_text ceiling"
284 ));
285 }
286 "list_dir" if !policy_allows_capability(&policy, "workspace", "list") => {
287 return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
288 }
289 "file_exists" | "stat" if !policy_allows_capability(&policy, "workspace", "exists") => {
290 return reject_policy(format!("builtin '{name}' exceeds workspace.exists ceiling"));
291 }
292 "write_file" | "append_file" | "mkdir" | "copy_file"
293 if !policy_allows_capability(&policy, "workspace", "write_text")
294 || !policy_allows_side_effect(&policy, "workspace_write") =>
295 {
296 return reject_policy(format!("builtin '{name}' exceeds workspace write ceiling"));
297 }
298 "delete_file"
299 if !policy_allows_capability(&policy, "workspace", "delete")
300 || !policy_allows_side_effect(&policy, "workspace_write") =>
301 {
302 return reject_policy(
303 "builtin 'delete_file' exceeds workspace.delete ceiling".to_string(),
304 );
305 }
306 "apply_edit"
307 if !policy_allows_capability(&policy, "workspace", "apply_edit")
308 || !policy_allows_side_effect(&policy, "workspace_write") =>
309 {
310 return reject_policy(
311 "builtin 'apply_edit' exceeds workspace.apply_edit ceiling".to_string(),
312 );
313 }
314 "exec" | "exec_at" | "shell" | "shell_at"
315 if !policy_allows_capability(&policy, "process", "exec")
316 || !policy_allows_side_effect(&policy, "process_exec") =>
317 {
318 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
319 }
320 "http_get" | "http_post" | "http_put" | "http_patch" | "http_delete" | "http_request"
321 if !policy_allows_side_effect(&policy, "network") =>
322 {
323 return reject_policy(format!("builtin '{name}' exceeds network ceiling"));
324 }
325 "mcp_connect"
326 | "mcp_call"
327 | "mcp_list_tools"
328 | "mcp_list_resources"
329 | "mcp_list_resource_templates"
330 | "mcp_read_resource"
331 | "mcp_list_prompts"
332 | "mcp_get_prompt"
333 | "mcp_server_info"
334 | "mcp_disconnect"
335 if !policy_allows_capability(&policy, "process", "exec")
336 || !policy_allows_side_effect(&policy, "process_exec") =>
337 {
338 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
339 }
340 "host_call" => {
341 let name = args.first().map(|v| v.display()).unwrap_or_default();
342 let Some((capability, op)) = name.split_once('.') else {
343 return reject_policy(format!(
344 "host_call '{name}' must use capability.operation naming"
345 ));
346 };
347 if !policy_allows_capability(&policy, capability, op) {
348 return reject_policy(format!(
349 "host_call {capability}.{op} exceeds capability ceiling"
350 ));
351 }
352 let requested_side_effect = match (capability, op) {
353 ("workspace", "write_text" | "apply_edit" | "delete") => "workspace_write",
354 ("process", "exec") => "process_exec",
355 _ => "read_only",
356 };
357 if !policy_allows_side_effect(&policy, requested_side_effect) {
358 return reject_policy(format!(
359 "host_call {capability}.{op} exceeds side-effect ceiling"
360 ));
361 }
362 }
363 _ => {}
364 }
365 Ok(())
366}
367
368pub fn enforce_current_policy_for_bridge_builtin(name: &str) -> Result<(), VmError> {
369 let trusted = TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow() > 0);
370 if trusted {
371 return Ok(());
372 }
373 if current_execution_policy().is_some() {
374 return reject_policy(format!(
375 "bridged builtin '{name}' exceeds execution policy; declare an explicit capability/tool surface instead"
376 ));
377 }
378 Ok(())
379}
380
381pub fn enforce_current_policy_for_tool(tool_name: &str) -> Result<(), VmError> {
382 let Some(policy) = current_execution_policy() else {
383 return Ok(());
384 };
385 if !policy_allows_tool(&policy, tool_name) {
386 return reject_policy(format!("tool '{tool_name}' exceeds tool ceiling"));
387 }
388 if let Some(annotations) = policy.tool_annotations.get(tool_name) {
389 for (capability, ops) in &annotations.capabilities {
390 for op in ops {
391 if !policy_allows_capability(&policy, capability, op) {
392 return reject_policy(format!(
393 "tool '{tool_name}' exceeds capability ceiling: {capability}.{op}"
394 ));
395 }
396 }
397 }
398 let requested_level = annotations.side_effect_level;
399 if requested_level != SideEffectLevel::None
400 && !policy_allows_side_effect(&policy, requested_level.as_str())
401 {
402 return reject_policy(format!(
403 "tool '{tool_name}' exceeds side-effect ceiling: {}",
404 requested_level.as_str()
405 ));
406 }
407 }
408 Ok(())
409}
410
411pub fn redact_transcript_visibility(
423 transcript: &VmValue,
424 visibility: Option<&str>,
425) -> Option<VmValue> {
426 let Some(visibility) = visibility else {
427 return Some(transcript.clone());
428 };
429 if visibility != "public" && visibility != "public_only" {
430 return Some(transcript.clone());
431 }
432 let dict = transcript.as_dict()?;
433 let public_messages = match dict.get("messages") {
434 Some(VmValue::List(list)) => list
435 .iter()
436 .filter(|message| {
437 message
438 .as_dict()
439 .and_then(|d| d.get("role"))
440 .map(|v| v.display())
441 .map(|role| role != "tool_result")
442 .unwrap_or(true)
443 })
444 .cloned()
445 .collect::<Vec<_>>(),
446 _ => Vec::new(),
447 };
448 let public_events = match dict.get("events") {
449 Some(VmValue::List(list)) => list
450 .iter()
451 .filter(|event| {
452 event
453 .as_dict()
454 .and_then(|d| d.get("visibility"))
455 .map(|v| v.display())
456 .map(|value| value == "public")
457 .unwrap_or(true)
458 })
459 .cloned()
460 .collect::<Vec<_>>(),
461 _ => Vec::new(),
462 };
463 let mut redacted = dict.clone();
464 redacted.insert(
465 "messages".to_string(),
466 VmValue::List(Rc::new(public_messages)),
467 );
468 redacted.insert("events".to_string(), VmValue::List(Rc::new(public_events)));
469 Some(VmValue::Dict(Rc::new(redacted)))
470}
471
472pub fn builtin_ceiling() -> CapabilityPolicy {
473 CapabilityPolicy {
474 tools: Vec::new(),
478 capabilities: BTreeMap::new(),
479 workspace_roots: Vec::new(),
480 side_effect_level: Some("network".to_string()),
481 recursion_limit: Some(8),
482 tool_arg_constraints: Vec::new(),
483 tool_annotations: BTreeMap::new(),
484 }
485}
486
487#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
491#[serde(default)]
492pub struct ToolApprovalPolicy {
493 #[serde(default)]
495 pub auto_approve: Vec<String>,
496 #[serde(default)]
498 pub auto_deny: Vec<String>,
499 #[serde(default)]
501 pub require_approval: Vec<String>,
502 #[serde(default)]
504 pub write_path_allowlist: Vec<String>,
505}
506
507#[derive(Debug, Clone, PartialEq, Eq)]
509pub enum ToolApprovalDecision {
510 AutoApproved,
512 AutoDenied { reason: String },
514 RequiresHostApproval,
517}
518
519impl ToolApprovalPolicy {
520 pub fn evaluate(&self, tool_name: &str, args: &serde_json::Value) -> ToolApprovalDecision {
523 for pattern in &self.auto_deny {
525 if glob_match(pattern, tool_name) {
526 return ToolApprovalDecision::AutoDenied {
527 reason: format!("tool '{tool_name}' matches deny pattern '{pattern}'"),
528 };
529 }
530 }
531
532 if !self.write_path_allowlist.is_empty()
533 && tool_kind_participates_in_write_allowlist(tool_name)
534 {
535 let paths = super::current_tool_declared_path_entries(tool_name, args);
536 for path in &paths {
537 let allowed = self.write_path_allowlist.iter().any(|pattern| {
538 path.policy_candidates()
539 .iter()
540 .any(|candidate| glob_match(pattern, candidate))
541 });
542 if !allowed {
543 return ToolApprovalDecision::AutoDenied {
544 reason: format!(
545 "tool '{tool_name}' targets '{}' which is not in the write-path allowlist",
546 path.display_path()
547 ),
548 };
549 }
550 }
551 }
552
553 for pattern in &self.auto_approve {
554 if glob_match(pattern, tool_name) {
555 return ToolApprovalDecision::AutoApproved;
556 }
557 }
558
559 for pattern in &self.require_approval {
560 if glob_match(pattern, tool_name) {
561 return ToolApprovalDecision::RequiresHostApproval;
562 }
563 }
564
565 ToolApprovalDecision::AutoApproved
566 }
567
568 pub fn intersect(&self, other: &ToolApprovalPolicy) -> ToolApprovalPolicy {
574 let auto_approve = if self.auto_approve.is_empty() {
575 other.auto_approve.clone()
576 } else if other.auto_approve.is_empty() {
577 self.auto_approve.clone()
578 } else {
579 self.auto_approve
580 .iter()
581 .filter(|p| other.auto_approve.contains(p))
582 .cloned()
583 .collect()
584 };
585 let mut auto_deny = self.auto_deny.clone();
586 auto_deny.extend(other.auto_deny.iter().cloned());
587 let mut require_approval = self.require_approval.clone();
588 require_approval.extend(other.require_approval.iter().cloned());
589 let write_path_allowlist = if self.write_path_allowlist.is_empty() {
590 other.write_path_allowlist.clone()
591 } else if other.write_path_allowlist.is_empty() {
592 self.write_path_allowlist.clone()
593 } else {
594 self.write_path_allowlist
595 .iter()
596 .filter(|p| other.write_path_allowlist.contains(p))
597 .cloned()
598 .collect()
599 };
600 ToolApprovalPolicy {
601 auto_approve,
602 auto_deny,
603 require_approval,
604 write_path_allowlist,
605 }
606 }
607}
608
609#[cfg(test)]
610mod approval_policy_tests {
611 use super::*;
612 use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
613 use crate::tool_annotations::{ToolAnnotations, ToolArgSchema, ToolKind};
614
615 #[test]
616 fn auto_deny_takes_precedence_over_auto_approve() {
617 let policy = ToolApprovalPolicy {
618 auto_approve: vec!["*".to_string()],
619 auto_deny: vec!["dangerous_*".to_string()],
620 ..Default::default()
621 };
622 assert_eq!(
623 policy.evaluate("dangerous_rm", &serde_json::json!({})),
624 ToolApprovalDecision::AutoDenied {
625 reason: "tool 'dangerous_rm' matches deny pattern 'dangerous_*'".to_string()
626 }
627 );
628 }
629
630 #[test]
631 fn auto_approve_matches_glob() {
632 let policy = ToolApprovalPolicy {
633 auto_approve: vec!["read*".to_string(), "search*".to_string()],
634 ..Default::default()
635 };
636 assert_eq!(
637 policy.evaluate("read_file", &serde_json::json!({})),
638 ToolApprovalDecision::AutoApproved
639 );
640 assert_eq!(
641 policy.evaluate("search", &serde_json::json!({})),
642 ToolApprovalDecision::AutoApproved
643 );
644 }
645
646 #[test]
647 fn require_approval_emits_decision() {
648 let policy = ToolApprovalPolicy {
649 require_approval: vec!["edit*".to_string()],
650 ..Default::default()
651 };
652 let decision = policy.evaluate("edit_file", &serde_json::json!({"path": "foo.rs"}));
653 assert!(matches!(
654 decision,
655 ToolApprovalDecision::RequiresHostApproval
656 ));
657 }
658
659 #[test]
660 fn unmatched_tool_defaults_to_approved() {
661 let policy = ToolApprovalPolicy {
662 auto_approve: vec!["read*".to_string()],
663 require_approval: vec!["edit*".to_string()],
664 ..Default::default()
665 };
666 assert_eq!(
667 policy.evaluate("unknown_tool", &serde_json::json!({})),
668 ToolApprovalDecision::AutoApproved
669 );
670 }
671
672 #[test]
673 fn intersect_merges_deny_lists() {
674 let a = ToolApprovalPolicy {
675 auto_deny: vec!["rm*".to_string()],
676 ..Default::default()
677 };
678 let b = ToolApprovalPolicy {
679 auto_deny: vec!["drop*".to_string()],
680 ..Default::default()
681 };
682 let merged = a.intersect(&b);
683 assert_eq!(merged.auto_deny.len(), 2);
684 }
685
686 #[test]
687 fn intersect_restricts_auto_approve_to_common_patterns() {
688 let a = ToolApprovalPolicy {
689 auto_approve: vec!["read*".to_string(), "search*".to_string()],
690 ..Default::default()
691 };
692 let b = ToolApprovalPolicy {
693 auto_approve: vec!["read*".to_string(), "write*".to_string()],
694 ..Default::default()
695 };
696 let merged = a.intersect(&b);
697 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
698 }
699
700 #[test]
701 fn intersect_defers_auto_approve_when_one_side_empty() {
702 let a = ToolApprovalPolicy {
703 auto_approve: vec!["read*".to_string()],
704 ..Default::default()
705 };
706 let b = ToolApprovalPolicy::default();
707 let merged = a.intersect(&b);
708 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
709 }
710
711 #[test]
712 fn write_path_allowlist_matches_recovered_workspace_relative_path() {
713 let temp = tempfile::tempdir().unwrap();
714 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
715 std::fs::write(temp.path().join("packages/demo/file.txt"), "ok").unwrap();
716 crate::stdlib::process::set_thread_execution_context(Some(
717 crate::orchestration::RunExecutionRecord {
718 cwd: Some(temp.path().to_string_lossy().into_owned()),
719 source_dir: Some(temp.path().to_string_lossy().into_owned()),
720 env: BTreeMap::new(),
721 adapter: None,
722 repo_path: None,
723 worktree_path: None,
724 branch: None,
725 base_ref: None,
726 cleanup: None,
727 },
728 ));
729
730 let mut tool_annotations = BTreeMap::new();
731 tool_annotations.insert(
732 "write_file".to_string(),
733 ToolAnnotations {
734 kind: ToolKind::Edit,
735 arg_schema: ToolArgSchema {
736 path_params: vec!["path".to_string()],
737 ..Default::default()
738 },
739 ..Default::default()
740 },
741 );
742 push_execution_policy(CapabilityPolicy {
743 tool_annotations,
744 ..Default::default()
745 });
746
747 let policy = ToolApprovalPolicy {
748 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
749 ..Default::default()
750 };
751 let decision = policy.evaluate(
752 "write_file",
753 &serde_json::json!({"path": "/packages/demo/file.txt"}),
754 );
755 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
756
757 pop_execution_policy();
758 crate::stdlib::process::set_thread_execution_context(None);
759 }
760
761 #[test]
762 fn write_path_allowlist_does_not_block_read_only_tools() {
763 let temp = tempfile::tempdir().unwrap();
764 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
765 std::fs::write(temp.path().join("packages/demo/context.txt"), "ok").unwrap();
766 crate::stdlib::process::set_thread_execution_context(Some(
767 crate::orchestration::RunExecutionRecord {
768 cwd: Some(temp.path().to_string_lossy().into_owned()),
769 source_dir: Some(temp.path().to_string_lossy().into_owned()),
770 env: BTreeMap::new(),
771 adapter: None,
772 repo_path: None,
773 worktree_path: None,
774 branch: None,
775 base_ref: None,
776 cleanup: None,
777 },
778 ));
779
780 let mut tool_annotations = BTreeMap::new();
781 tool_annotations.insert(
782 "read_file".to_string(),
783 ToolAnnotations {
784 kind: ToolKind::Read,
785 arg_schema: ToolArgSchema {
786 path_params: vec!["path".to_string()],
787 ..Default::default()
788 },
789 ..Default::default()
790 },
791 );
792 push_execution_policy(CapabilityPolicy {
793 tool_annotations,
794 ..Default::default()
795 });
796
797 let policy = ToolApprovalPolicy {
798 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
799 ..Default::default()
800 };
801 let decision = policy.evaluate(
802 "read_file",
803 &serde_json::json!({"path": "/packages/demo/context.txt"}),
804 );
805 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
806
807 pop_execution_policy();
808 crate::stdlib::process::set_thread_execution_context(None);
809 }
810}
811
812#[cfg(test)]
813mod turn_policy_tests {
814 use super::TurnPolicy;
815
816 #[test]
817 fn default_allows_done_sentinel() {
818 let policy = TurnPolicy::default();
819 assert!(policy.allow_done_sentinel);
820 assert!(!policy.require_action_or_yield);
821 assert!(policy.max_prose_chars.is_none());
822 }
823
824 #[test]
825 fn deserializing_partial_dict_preserves_done_sentinel_pathway() {
826 let policy: TurnPolicy =
831 serde_json::from_value(serde_json::json!({ "require_action_or_yield": true }))
832 .expect("deserialize");
833 assert!(policy.require_action_or_yield);
834 assert!(policy.allow_done_sentinel);
835 }
836
837 #[test]
838 fn deserializing_explicit_false_disables_done_sentinel() {
839 let policy: TurnPolicy = serde_json::from_value(serde_json::json!({
840 "require_action_or_yield": true,
841 "allow_done_sentinel": false,
842 }))
843 .expect("deserialize");
844 assert!(policy.require_action_or_yield);
845 assert!(!policy.allow_done_sentinel);
846 }
847}
848
849#[cfg(test)]
850mod visibility_redaction_tests {
851 use super::*;
852 use crate::value::VmValue;
853
854 fn mock_transcript() -> VmValue {
855 let messages = vec![
856 serde_json::json!({"role": "user", "content": "hi"}),
857 serde_json::json!({"role": "assistant", "content": "hello"}),
858 serde_json::json!({"role": "tool_result", "content": "internal tool output"}),
859 ];
860 crate::llm::helpers::transcript_to_vm_with_events(
861 Some("test-id".to_string()),
862 None,
863 None,
864 &messages,
865 Vec::new(),
866 Vec::new(),
867 Some("active"),
868 )
869 }
870
871 fn message_count(transcript: &VmValue) -> usize {
872 transcript
873 .as_dict()
874 .and_then(|d| d.get("messages"))
875 .and_then(|v| match v {
876 VmValue::List(list) => Some(list.len()),
877 _ => None,
878 })
879 .unwrap_or(0)
880 }
881
882 #[test]
883 fn visibility_none_returns_unchanged() {
884 let t = mock_transcript();
885 let result = redact_transcript_visibility(&t, None).unwrap();
886 assert_eq!(message_count(&result), 3);
887 }
888
889 #[test]
890 fn visibility_public_drops_tool_results() {
891 let t = mock_transcript();
892 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
893 assert_eq!(message_count(&result), 2);
894 }
895
896 #[test]
897 fn visibility_unknown_string_is_pass_through() {
898 let t = mock_transcript();
899 let result = redact_transcript_visibility(&t, Some("internal")).unwrap();
900 assert_eq!(message_count(&result), 3);
901 }
902}