1mod approval_rules;
4mod effects;
5mod nested_budget;
6mod operator_grant;
7mod types;
8
9use crate::value::VmDictExt;
10use std::cell::RefCell;
11use std::collections::BTreeMap;
12use std::thread_local;
13
14use serde::{Deserialize, Serialize};
15
16use crate::runtime_limits::RuntimeLimits;
17use crate::tool_annotations::{SideEffectLevel, ToolAnnotations};
18use crate::value::{VmError, VmValue};
19use crate::workspace_path::{classify_workspace_path, WorkspacePathInfo};
20
21pub use crate::tool_annotations::{ToolArgSchema, ToolKind};
22pub use approval_rules::{
23 clear_all_approval_policy_repeat_counts, clear_approval_policy_repeat_counts,
24 next_approval_policy_repeat_count, next_approval_unavailable_class_repeat_count, ApprovalShape,
25 PolicyAction, PolicyEvaluation, PolicyMatchedRule, PolicyRule, PolicyRuleMatch,
26 ToolApprovalRequest,
27};
28pub use effects::{
29 compute_handoff_effects, effect_kind_label, effect_record_summary, effect_subset_violations,
30 effects_from_metadata, EffectKind, EffectRecord, EffectScope,
31};
32pub(crate) use effects::{effect_allowed_by_ceiling, runtime_effects_from_contract};
33pub use nested_budget::{
34 annotate_nested_execution_options, enter_nested_execution_policy, NestedExecutionGuard,
35 NestedExecutionKind, NESTED_KIND_OPTION_KEY, NESTED_LABEL_OPTION_KEY,
36};
37pub(crate) use operator_grant::{
38 clear_operator_approval_grants, swap_operator_approval_grant_stack,
39};
40pub use operator_grant::{
41 current_operator_approval_grant, install_operator_approval_grant, OperatorApprovalGrant,
42 OperatorApprovalGrantGuard,
43};
44pub use types::{
45 enforce_tool_arg_constraints, AutoCompactPolicy, BranchSemantics, CapabilityPolicy,
46 ContextPolicy, EqIgnored, EscalationPolicy, FeedbackBounds, FeedbackPolicy, JoinPolicy,
47 MapPolicy, ModelPolicy, NativeToolFallbackPolicy, ProcessSandboxPolicy, ProcessSandboxPreset,
48 ReducePolicy, RequiredSuccessfulTool, RetryPolicy, SandboxProfile, StageContract,
49 ToolArgConstraint, TurnPolicy,
50};
51
52thread_local! {
53 static EXECUTION_POLICY_STACK: RefCell<Vec<CapabilityPolicy>> = const { RefCell::new(Vec::new()) };
54 static EXECUTION_APPROVAL_POLICY_STACK: RefCell<Vec<ToolApprovalPolicy>> = const { RefCell::new(Vec::new()) };
55 static TRUSTED_BRIDGE_CALL_DEPTH: RefCell<usize> = const { RefCell::new(0) };
56}
57
58pub fn push_execution_policy(policy: CapabilityPolicy) {
59 EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
60}
61
62pub fn pop_execution_policy() {
63 EXECUTION_POLICY_STACK.with(|stack| {
64 stack.borrow_mut().pop();
65 });
66}
67
68pub fn clear_execution_policy_stacks() {
69 EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().clear());
70 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().clear());
71 clear_operator_approval_grants();
72 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow_mut() = 0);
73}
74
75pub fn current_execution_policy() -> Option<CapabilityPolicy> {
76 EXECUTION_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
77}
78
79pub fn execution_policy_active() -> bool {
84 EXECUTION_POLICY_STACK.with(|stack| !stack.borrow().is_empty())
85}
86
87pub fn push_approval_policy(policy: ToolApprovalPolicy) {
88 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
89}
90
91pub fn pop_approval_policy() {
92 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| {
93 stack.borrow_mut().pop();
94 });
95}
96
97pub fn current_approval_policy() -> Option<ToolApprovalPolicy> {
98 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
99}
100
101pub(crate) fn swap_execution_policy_stack(next: Vec<CapabilityPolicy>) -> Vec<CapabilityPolicy> {
114 EXECUTION_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
115}
116
117pub(crate) fn swap_approval_policy_stack(next: Vec<ToolApprovalPolicy>) -> Vec<ToolApprovalPolicy> {
118 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
119}
120
121pub(crate) fn swap_trusted_bridge_depth(next: usize) -> usize {
122 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| std::mem::replace(&mut *depth.borrow_mut(), next))
123}
124
125pub fn current_tool_annotations(tool: &str) -> Option<ToolAnnotations> {
126 current_execution_policy().and_then(|policy| policy.tool_annotations.get(tool).cloned())
127}
128
129pub fn current_allowed_tool_names() -> Vec<String> {
137 let Some(policy) = current_execution_policy() else {
138 return Vec::new();
139 };
140 if policy.tools_are_restricted() {
141 return policy.allowed_tool_patterns().map(str::to_string).collect();
142 }
143 policy.tool_annotations.keys().cloned().collect()
144}
145
146pub(super) fn tool_kind_participates_in_write_allowlist(tool_name: &str) -> bool {
147 current_tool_annotations(tool_name)
148 .map(|annotations| !annotations.kind.is_read_only())
149 .unwrap_or(true)
150}
151
152pub struct TrustedBridgeCallGuard;
153
154pub fn allow_trusted_bridge_calls() -> TrustedBridgeCallGuard {
155 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
156 *depth.borrow_mut() += 1;
157 });
158 TrustedBridgeCallGuard
159}
160
161impl Drop for TrustedBridgeCallGuard {
162 fn drop(&mut self) {
163 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
164 let mut depth = depth.borrow_mut();
165 *depth = depth.saturating_sub(1);
166 });
167 }
168}
169
170fn policy_allows_tool(policy: &CapabilityPolicy, tool: &str) -> bool {
171 policy.tool_pattern_allows(tool)
172}
173
174fn policy_grants_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
175 policy
176 .capabilities
177 .get(capability)
178 .is_some_and(|ops| ops.is_empty() || ops.iter().any(|allowed| allowed == op))
179}
180
181fn policy_allows_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
182 if !policy.capabilities_are_restricted() {
183 return true;
185 }
186 if policy.capabilities_deny_all() {
187 return false;
188 }
189 if policy_grants_capability(policy, capability, op) {
190 return true;
191 }
192 if capability == "workspace" && op == "exists" {
204 return policy_grants_capability(policy, "workspace", "read_text")
205 || policy_grants_capability(policy, "workspace", "list");
206 }
207 false
208}
209
210fn policy_allows_side_effect(policy: &CapabilityPolicy, requested: &str) -> bool {
211 let requested_rank = SideEffectLevel::rank_str(requested);
217 policy
218 .side_effect_level
219 .as_ref()
220 .map(|allowed| SideEffectLevel::rank_str(allowed) >= requested_rank)
221 .unwrap_or(true)
222}
223
224pub(super) fn reject_policy(reason: String) -> Result<(), VmError> {
225 Err(VmError::CategorizedError {
226 message: reason,
227 category: crate::value::ErrorCategory::ToolRejected,
228 })
229}
230
231#[derive(Clone, Debug, PartialEq, Eq)]
238pub struct PolicyDenial {
239 pub gate: crate::agent_events::DenialGate,
240 pub capability: Option<String>,
241 pub reason: String,
242 pub side_effect_ceiling: Option<SideEffectCeilingViolation>,
247}
248
249#[derive(Clone, Copy, Debug, Eq, PartialEq)]
253pub struct SideEffectCeilingViolation {
254 pub ceiling: SideEffectLevel,
255 pub required_level: SideEffectLevel,
256}
257
258#[derive(Clone, Debug, Eq, PartialEq)]
262pub(crate) struct SideEffectCeilingGrant {
263 tool_name: String,
264 violation: SideEffectCeilingViolation,
265}
266
267impl PolicyDenial {
268 pub(crate) fn side_effect_grant_for(&self, tool_name: &str) -> Option<SideEffectCeilingGrant> {
270 self.side_effect_ceiling
271 .map(|violation| SideEffectCeilingGrant {
272 tool_name: tool_name.to_string(),
273 violation,
274 })
275 }
276}
277
278impl SideEffectCeilingGrant {
279 fn matches(&self, tool_name: &str, violation: SideEffectCeilingViolation) -> bool {
280 self.tool_name == tool_name && self.violation == violation
281 }
282}
283
284impl From<PolicyDenial> for VmError {
285 fn from(denial: PolicyDenial) -> Self {
286 VmError::CategorizedError {
287 message: denial.reason,
288 category: crate::value::ErrorCategory::ToolRejected,
289 }
290 }
291}
292
293pub(super) fn reject_tool(
294 gate: crate::agent_events::DenialGate,
295 capability: Option<String>,
296 particulars: String,
297) -> Result<(), PolicyDenial> {
298 Err(PolicyDenial {
299 gate,
300 capability,
301 reason: gate.render_reason(particulars),
302 side_effect_ceiling: None,
303 })
304}
305
306pub fn current_tool_mutation_classification(tool_name: &str) -> String {
311 current_tool_annotations(tool_name)
312 .map(|annotations| annotations.kind.mutation_class().to_string())
313 .unwrap_or_else(|| "other".to_string())
314}
315
316pub fn current_tool_declared_paths(tool_name: &str, args: &serde_json::Value) -> Vec<String> {
320 current_tool_declared_path_entries(tool_name, args)
321 .into_iter()
322 .map(|entry| entry.display_path().to_string())
323 .collect()
324}
325
326pub fn current_tool_declared_path_entries(
331 tool_name: &str,
332 args: &serde_json::Value,
333) -> Vec<WorkspacePathInfo> {
334 let Some(annotations) = current_tool_annotations(tool_name) else {
335 return Vec::new();
336 };
337 tool_declared_path_entries(&annotations, args)
338}
339
340pub fn tool_declared_path_entries(
346 annotations: &crate::tool_annotations::ToolAnnotations,
347 args: &serde_json::Value,
348) -> Vec<WorkspacePathInfo> {
349 let Some(map) = args.as_object() else {
350 return Vec::new();
351 };
352 let workspace_root = crate::stdlib::process::execution_root_path();
353 let mut entries = Vec::new();
354 for key in &annotations.arg_schema.path_params {
355 if let Some(value) = map.get(key) {
356 match value {
357 serde_json::Value::String(path) if !path.is_empty() => {
358 entries.push(classify_workspace_path(path, Some(&workspace_root)));
359 }
360 serde_json::Value::Array(items) => {
361 for item in items.iter().filter_map(|item| item.as_str()) {
362 if !item.is_empty() {
363 entries.push(classify_workspace_path(item, Some(&workspace_root)));
364 }
365 }
366 }
367 _ => {}
368 }
369 }
370 }
371 entries.sort_by(|a, b| a.display_path().cmp(b.display_path()));
372 entries.dedup_by(|left, right| left.policy_candidates() == right.policy_candidates());
373 entries
374}
375
376pub fn enforce_current_policy_for_builtin(name: &str, args: &[VmValue]) -> Result<(), VmError> {
377 let Some(policy) = current_execution_policy() else {
378 return Ok(());
379 };
380 if let Some(entry) = crate::stdlib::all_builtin_manifest()
381 .iter()
382 .find(|entry| entry.name == name)
383 {
384 if let harn_builtin_meta::BuiltinExposure::CapabilityFunction { authority_argument } =
385 entry.contract.exposure
386 {
387 if args.get(usize::from(authority_argument)).is_none() {
388 return reject_policy(format!(
389 "capability function '{name}' is missing authority argument {authority_argument}"
390 ));
391 }
392 if let Some(effect) =
393 effects::runtime_effects_from_contract(entry.contract.effects, args)
394 .into_iter()
395 .find(|effect| !effects::effect_allowed_by_ceiling(effect, &policy))
396 {
397 return reject_policy(format!(
398 "capability function '{name}' exceeds the active effect ceiling: {}",
399 effects::effect_record_summary(&effect)
400 ));
401 }
402 return Ok(());
403 }
404 }
405 if effects::builtin_has_network_effect(name)
406 && (!policy_allows_capability(&policy, "network", "http")
407 || !policy_allows_side_effect(&policy, "network"))
408 {
409 return reject_policy(format!("builtin '{name}' exceeds network.http ceiling"));
410 }
411 match name {
412 "find_text" | "find_evidence"
413 if !policy_allows_capability(&policy, "workspace", "read_text")
414 || !policy_allows_capability(&policy, "workspace", "list") =>
415 {
416 return reject_policy(format!(
417 "builtin '{name}' exceeds workspace.read_text/workspace.list ceiling"
418 ));
419 }
420 "read_file"
421 | "read_file_result"
422 | "read_file_bytes"
423 | "package_snapshot_open"
424 | "render"
425 | "render_prompt"
426 | "render_with_provenance"
427 | "read_lines"
428 if !policy_allows_capability(&policy, "workspace", "read_text") =>
429 {
430 return reject_policy(format!(
431 "builtin '{name}' exceeds workspace.read_text ceiling"
432 ));
433 }
434 "list_dir" | "walk_dir" | "glob"
435 if !policy_allows_capability(&policy, "workspace", "list") =>
436 {
437 return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
438 }
439 "file_exists" | "path_status" | "stat"
440 if !policy_allows_capability(&policy, "workspace", "exists") =>
441 {
442 return reject_policy(format!("builtin '{name}' exceeds workspace.exists ceiling"));
443 }
444 "write_file"
445 | "write_file_bytes"
446 | "replace_file"
447 | "replace_file_result"
448 | "replace_file_bytes"
449 | "replace_file_bytes_result"
450 | "append_file"
451 | "append_file_locked"
452 | "mkdir"
453 | "copy_file"
454 | "move_file"
455 if !policy_allows_capability(&policy, "workspace", "write_text")
456 || !policy_allows_side_effect(&policy, "workspace_write") =>
457 {
458 return reject_policy(format!("builtin '{name}' exceeds workspace write ceiling"));
459 }
460 "delete_file"
461 if !policy_allows_capability(&policy, "workspace", "delete")
462 || !policy_allows_side_effect(&policy, "workspace_write") =>
463 {
464 return reject_policy(
465 "builtin 'delete_file' exceeds workspace.delete ceiling".to_string(),
466 );
467 }
468 "apply_edit"
469 if !policy_allows_capability(&policy, "workspace", "apply_edit")
470 || !policy_allows_side_effect(&policy, "workspace_write") =>
471 {
472 return reject_policy(
473 "builtin 'apply_edit' exceeds workspace.apply_edit ceiling".to_string(),
474 );
475 }
476 "exec"
477 | "exec_at"
478 | "shell"
479 | "shell_at"
480 | "git.repo.discover"
481 | "git.worktree.create"
482 | "git.worktree.remove"
483 | "git.fetch"
484 | "git.rebase"
485 | "git.status"
486 | "git.conflicts"
487 | "git.push"
488 | "git.diff"
489 | "git.merge_base"
490 | "git.tag_list"
491 | "git.describe"
492 | "git.ls_remote"
493 if !policy_allows_capability(&policy, "process", "exec")
494 || !policy_allows_side_effect(&policy, "process_exec") =>
495 {
496 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
497 }
498 "__files_upload" if !policy_allows_capability(&policy, "workspace", "read_text") => {
503 return reject_policy(
504 "builtin '__files_upload' exceeds workspace.read_text/network ceiling".to_string(),
505 );
506 }
507 "llm_call" | "llm_call_safe" | "llm_completion" | "llm_stream" | "llm_stream_call"
508 | "llm_healthcheck" | "agent_loop"
509 if !policy_allows_capability(&policy, "llm", "call") =>
510 {
511 return reject_policy(format!("builtin '{name}' exceeds llm.call ceiling"));
512 }
513 "connector_call"
514 if !policy_allows_capability(&policy, "connector", "call")
515 || !policy_allows_side_effect(&policy, "network") =>
516 {
517 return reject_policy(
518 "builtin 'connector_call' exceeds connector.call/network ceiling".to_string(),
519 );
520 }
521 "secret_get" if !policy_allows_capability(&policy, "connector", "secret_get") => {
522 return reject_policy(
523 "builtin 'secret_get' exceeds connector.secret_get ceiling".to_string(),
524 );
525 }
526 "event_log_emit" if !policy_allows_capability(&policy, "connector", "event_log_emit") => {
527 return reject_policy(
528 "builtin 'event_log_emit' exceeds connector.event_log_emit ceiling".to_string(),
529 );
530 }
531 "metrics_inc" if !policy_allows_capability(&policy, "connector", "metrics_inc") => {
532 return reject_policy(
533 "builtin 'metrics_inc' exceeds connector.metrics_inc ceiling".to_string(),
534 );
535 }
536 "project_fingerprint"
537 | "project_context_profile_native"
538 | "project_scan_native"
539 | "project_scan_tree_native"
540 | "project_walk_tree_native"
541 | "project_catalog_native"
542 if !policy_allows_capability(&policy, "workspace", "list")
543 || !policy_allows_side_effect(&policy, "read_only") =>
544 {
545 return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
546 }
547 "__agent_state_init"
548 | "__agent_state_resume"
549 | "__agent_state_write"
550 | "__agent_state_read"
551 | "__agent_state_list"
552 | "__agent_state_delete"
553 | "__agent_state_handoff"
554 if !policy_allows_capability(&policy, "agent_state", "access") =>
555 {
556 return reject_policy(format!(
557 "builtin '{name}' exceeds agent_state.access ceiling"
558 ));
559 }
560 "vision_ocr"
561 if !policy_allows_capability(&policy, "vision", "ocr")
562 || !policy_allows_side_effect(&policy, "process_exec") =>
563 {
564 return reject_policy(format!(
565 "builtin '{name}' exceeds vision.ocr/process ceiling"
566 ));
567 }
568 "mcp_connect"
569 | "mcp_ensure_active"
570 | "mcp_call"
571 | "mcp_list_tools"
572 | "mcp_list_resources"
573 | "mcp_list_resource_templates"
574 | "mcp_read_resource"
575 | "mcp_list_prompts"
576 | "mcp_get_prompt"
577 | "mcp_server_info"
578 | "mcp_disconnect"
579 if !policy_allows_capability(&policy, "process", "exec")
580 || !policy_allows_side_effect(&policy, "process_exec") =>
581 {
582 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
583 }
584 "host_call" => {
585 let name = args.first().map(|v| v.display()).unwrap_or_default();
586 let Some((capability, op)) = name.split_once('.') else {
587 return reject_policy(format!(
588 "host_call '{name}' must use capability.operation naming"
589 ));
590 };
591 if !policy_allows_capability(&policy, capability, op) {
592 return reject_policy(format!(
593 "host_call {capability}.{op} exceeds capability ceiling"
594 ));
595 }
596 let requested_side_effect = match (capability, op) {
597 ("workspace", "write_text" | "apply_edit" | "delete") => "workspace_write",
598 ("process", "exec") => "process_exec",
599 _ => "read_only",
600 };
601 if !policy_allows_side_effect(&policy, requested_side_effect) {
602 return reject_policy(format!(
603 "host_call {capability}.{op} exceeds side-effect ceiling"
604 ));
605 }
606 }
607 "host_tool_list" | "host_tool_call"
608 if !policy_allows_capability(&policy, "host", "tool_call") =>
609 {
610 return reject_policy(format!("builtin '{name}' exceeds host.tool_call ceiling"));
611 }
612 _ => {}
613 }
614 Ok(())
615}
616
617pub fn enforce_current_policy_for_capability(
619 capability: harn_builtin_meta::CapabilityId,
620 method: &str,
621 args: &[VmValue],
622) -> Result<(), VmError> {
623 let Some(policy) = current_execution_policy() else {
624 return Ok(());
625 };
626 let entry = crate::stdlib::all_builtin_manifest().iter().find(|entry| {
627 matches!(
628 entry.contract.exposure,
629 harn_builtin_meta::BuiltinExposure::HarnessMethod {
630 capability: candidate,
631 method: candidate_method,
632 } if candidate == capability && candidate_method == method
633 )
634 });
635 let Some(entry) = entry else {
636 return reject_policy(format!(
637 "undeclared Harness capability method `harness.{}.{method}`",
638 capability.field_name()
639 ));
640 };
641 let denied = effects::runtime_effects_from_contract(entry.contract.effects, args)
642 .into_iter()
643 .find(|effect| !effects::effect_allowed_by_ceiling(effect, &policy));
644 if let Some(effect) = denied {
645 return reject_policy(format!(
646 "harness.{}.{method} exceeds the active effect ceiling: {}",
647 capability.field_name(),
648 effects::effect_record_summary(&effect)
649 ));
650 }
651 Ok(())
652}
653
654pub fn enforce_current_policy_for_bridge_builtin(name: &str) -> Result<(), VmError> {
655 let trusted = TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow() > 0);
656 if trusted {
657 return Ok(());
658 }
659 if current_execution_policy().is_some() {
660 return reject_policy(format!(
661 "bridged builtin '{name}' exceeds execution policy; declare an explicit capability/tool surface instead"
662 ));
663 }
664 Ok(())
665}
666
667pub fn enforce_current_policy_for_tool(tool_name: &str) -> Result<(), PolicyDenial> {
668 enforce_current_policy_for_tool_with_side_effect_grant(tool_name, None)
669}
670
671pub(crate) fn enforce_current_policy_for_tool_with_side_effect_grant(
676 tool_name: &str,
677 side_effect_grant: Option<&SideEffectCeilingGrant>,
678) -> Result<(), PolicyDenial> {
679 use crate::agent_events::DenialGate;
680 let Some(policy) = current_execution_policy() else {
681 return Ok(());
682 };
683 if !policy_allows_tool(&policy, tool_name) {
684 return reject_tool(
685 DenialGate::ToolCeiling,
686 None,
687 format!("tool '{tool_name}' is not in the active allowed-tool list"),
688 );
689 }
690 if let Some(annotations) = policy.tool_annotations.get(tool_name) {
691 for (capability, ops) in &annotations.capabilities {
692 for op in ops {
693 if !policy_allows_capability(&policy, capability, op) {
694 return reject_tool(
695 DenialGate::CapabilityCeiling,
696 Some(format!("{capability}.{op}")),
697 format!("tool '{tool_name}' requires {capability}.{op}"),
698 );
699 }
700 }
701 }
702 let requested_level = annotations.side_effect_level;
703 if requested_level != SideEffectLevel::None
704 && !policy_allows_side_effect(&policy, requested_level.as_str())
705 {
706 let ceiling = policy
707 .side_effect_level
708 .as_deref()
709 .map(SideEffectLevel::parse)
710 .expect("a side-effect refusal requires an active policy ceiling");
711 let violation = SideEffectCeilingViolation {
712 ceiling,
713 required_level: requested_level,
714 };
715 if side_effect_grant.is_some_and(|grant| grant.matches(tool_name, violation)) {
716 return Ok(());
717 }
718 return Err(PolicyDenial {
719 gate: DenialGate::SideEffectCeiling,
720 capability: None,
721 reason: DenialGate::SideEffectCeiling.render_reason(format!(
722 "tool '{tool_name}' requires side-effect level '{}' but the active ceiling is '{}'",
723 requested_level.as_str(),
724 ceiling.as_str(),
725 )),
726 side_effect_ceiling: Some(violation),
727 });
728 }
729 }
730 Ok(())
731}
732
733pub fn redact_transcript_visibility(
745 transcript: &VmValue,
746 visibility: Option<&str>,
747) -> Option<VmValue> {
748 let Some(visibility) = visibility else {
749 return Some(transcript.clone());
750 };
751 if visibility != "public" && visibility != "public_only" {
752 return Some(transcript.clone());
753 }
754 let dict = transcript.as_dict()?;
755 let public_messages = match dict.get("messages") {
756 Some(VmValue::List(list)) => list
757 .iter()
758 .filter_map(redact_public_message)
759 .collect::<Vec<_>>(),
760 _ => Vec::new(),
761 };
762 let public_events = match dict.get("events") {
763 Some(VmValue::List(list)) => list
764 .iter()
765 .filter(|event| {
766 event
767 .as_dict()
768 .and_then(|d| d.get("visibility"))
769 .map(|v| v.display())
770 .map(|value| value == "public")
771 .unwrap_or(true)
772 })
773 .cloned()
774 .collect::<Vec<_>>(),
775 _ => Vec::new(),
776 };
777 let mut redacted = dict.clone();
778 redacted.insert(
779 crate::value::intern_key("messages"),
780 VmValue::List(std::sync::Arc::new(public_messages)),
781 );
782 redacted.insert(
783 crate::value::intern_key("events"),
784 VmValue::List(std::sync::Arc::new(public_events)),
785 );
786 Some(VmValue::dict(redacted))
787}
788
789fn redact_public_message(message: &VmValue) -> Option<VmValue> {
790 let Some(dict) = message.as_dict() else {
791 return Some(message.clone());
792 };
793 if dict.get("role").map(|value| value.display()).as_deref() == Some("tool_result") {
794 return None;
795 }
796 if dict
797 .get("visibility")
798 .map(|value| value.display())
799 .is_some_and(|visibility| visibility != "public")
800 {
801 return None;
802 }
803
804 let mut redacted = dict.clone();
805 let mut saw_structured_blocks = false;
806 let mut public_text = Vec::new();
807 for key in ["content", "blocks"] {
808 if let Some(VmValue::List(blocks)) = dict.get(key) {
809 saw_structured_blocks = true;
810 let public_blocks = blocks
811 .iter()
812 .filter_map(redact_public_block)
813 .collect::<Vec<_>>();
814 if key == "blocks" || public_text.is_empty() {
815 public_text = text_fragments_from_blocks(&public_blocks);
816 }
817 redacted.insert(
818 crate::value::intern_key(key),
819 VmValue::List(std::sync::Arc::new(public_blocks)),
820 );
821 }
822 }
823 if saw_structured_blocks {
824 if public_text.is_empty() {
825 redacted.remove("text");
826 } else {
827 redacted.put_str("text", public_text.join("\n"));
828 }
829 }
830 Some(VmValue::dict(redacted))
831}
832
833fn redact_public_block(block: &VmValue) -> Option<VmValue> {
834 let Some(dict) = block.as_dict() else {
835 return Some(block.clone());
836 };
837 if dict
838 .get("visibility")
839 .map(|value| value.display())
840 .is_some_and(|visibility| visibility != "public")
841 {
842 return None;
843 }
844 Some(block.clone())
845}
846
847fn text_fragments_from_blocks(blocks: &[VmValue]) -> Vec<String> {
848 blocks
849 .iter()
850 .filter_map(|block| block.as_dict())
851 .filter_map(|dict| dict.get("text"))
852 .filter_map(|text| match text {
853 VmValue::String(value) if !value.is_empty() => Some(value.to_string()),
854 _ => None,
855 })
856 .collect()
857}
858
859pub fn builtin_ceiling() -> CapabilityPolicy {
860 CapabilityPolicy {
861 tools: Vec::new(),
865 capabilities: BTreeMap::new(),
866 workspace_roots: Vec::new(),
867 read_only_roots: Vec::new(),
868 side_effect_level: Some(SideEffectLevel::MAX.as_str().to_string()),
878 recursion_limit: Some(RuntimeLimits::DEFAULT.max_nested_execution_depth),
879 tool_arg_constraints: Vec::new(),
880 tool_annotations: BTreeMap::new(),
881 sandbox_profile: SandboxProfile::Worktree,
882 process_sandbox: Default::default(),
883 }
884}
885
886#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
890#[serde(default)]
891pub struct ToolApprovalPolicy {
892 #[serde(default)]
895 pub rules: Vec<PolicyRule>,
896 #[serde(default)]
898 pub auto_approve: Vec<String>,
899 #[serde(default)]
901 pub auto_deny: Vec<String>,
902 #[serde(default)]
904 pub require_approval: Vec<String>,
905 #[serde(default)]
907 pub write_path_allowlist: Vec<String>,
908 #[serde(default)]
910 pub allow_sensitive_paths: bool,
911 #[serde(default)]
914 pub sensitive_path_patterns: Vec<String>,
915 #[serde(default)]
917 pub allow_external_paths: bool,
918 #[serde(default)]
920 pub external_roots: Vec<String>,
921 #[serde(default, alias = "repeated_call_limit")]
923 pub repeat_limit: Option<u64>,
924 #[serde(default, alias = "repeated_call_action")]
926 pub repeat_action: Option<PolicyAction>,
927}
928
929#[derive(Debug, Clone, PartialEq, Eq)]
931pub enum ToolApprovalDecision {
932 AutoApproved,
934 AutoDenied { reason: String },
936 RequiresHostApproval,
939}
940
941impl ToolApprovalPolicy {
942 pub fn evaluate_detailed(&self, tool_name: &str, args: &serde_json::Value) -> PolicyEvaluation {
943 approval_rules::evaluate_tool_approval_policy(self, tool_name, args, None)
944 }
945
946 pub fn evaluate_detailed_with_repeat(
947 &self,
948 tool_name: &str,
949 args: &serde_json::Value,
950 repeat_count: u64,
951 ) -> PolicyEvaluation {
952 approval_rules::evaluate_tool_approval_policy(self, tool_name, args, Some(repeat_count))
953 }
954
955 pub fn evaluate(&self, tool_name: &str, args: &serde_json::Value) -> ToolApprovalDecision {
958 let decision = self.evaluate_detailed(tool_name, args);
959 if decision.is_deny() {
960 return ToolApprovalDecision::AutoDenied {
961 reason: decision.reason,
962 };
963 }
964 if decision.is_ask() {
965 return ToolApprovalDecision::RequiresHostApproval;
966 }
967 ToolApprovalDecision::AutoApproved
968 }
969
970 pub fn intersect(&self, other: &ToolApprovalPolicy) -> ToolApprovalPolicy {
976 let auto_approve = if self.auto_approve.is_empty() {
977 other.auto_approve.clone()
978 } else if other.auto_approve.is_empty() {
979 self.auto_approve.clone()
980 } else {
981 self.auto_approve
982 .iter()
983 .filter(|p| other.auto_approve.contains(p))
984 .cloned()
985 .collect()
986 };
987 let mut auto_deny = self.auto_deny.clone();
988 auto_deny.extend(other.auto_deny.iter().cloned());
989 let mut require_approval = self.require_approval.clone();
990 require_approval.extend(other.require_approval.iter().cloned());
991 let write_path_allowlist = if self.write_path_allowlist.is_empty() {
992 other.write_path_allowlist.clone()
993 } else if other.write_path_allowlist.is_empty() {
994 self.write_path_allowlist.clone()
995 } else {
996 self.write_path_allowlist
997 .iter()
998 .filter(|p| other.write_path_allowlist.contains(p))
999 .cloned()
1000 .collect()
1001 };
1002 let mut rules = self.rules.clone();
1003 rules.extend(other.rules.iter().cloned());
1004 let mut sensitive_path_patterns = self.sensitive_path_patterns.clone();
1005 sensitive_path_patterns.extend(other.sensitive_path_patterns.iter().cloned());
1006 sensitive_path_patterns.sort();
1007 sensitive_path_patterns.dedup();
1008 let external_roots = if self.external_roots.is_empty() {
1009 other.external_roots.clone()
1010 } else if other.external_roots.is_empty() {
1011 self.external_roots.clone()
1012 } else {
1013 self.external_roots
1014 .iter()
1015 .filter(|root| other.external_roots.contains(root))
1016 .cloned()
1017 .collect()
1018 };
1019 ToolApprovalPolicy {
1020 rules,
1021 auto_approve,
1022 auto_deny,
1023 require_approval,
1024 write_path_allowlist,
1025 allow_sensitive_paths: self.allow_sensitive_paths && other.allow_sensitive_paths,
1026 sensitive_path_patterns,
1027 allow_external_paths: self.allow_external_paths && other.allow_external_paths,
1028 external_roots,
1029 repeat_limit: match (self.repeat_limit, other.repeat_limit) {
1030 (Some(left), Some(right)) => Some(left.min(right)),
1031 (Some(left), None) => Some(left),
1032 (None, Some(right)) => Some(right),
1033 (None, None) => None,
1034 },
1035 repeat_action: match (self.repeat_action, other.repeat_action) {
1036 (Some(PolicyAction::Deny), _) | (_, Some(PolicyAction::Deny)) => {
1037 Some(PolicyAction::Deny)
1038 }
1039 (Some(PolicyAction::Ask), _) | (_, Some(PolicyAction::Ask)) => {
1040 Some(PolicyAction::Ask)
1041 }
1042 (Some(PolicyAction::Allow), Some(PolicyAction::Allow)) => Some(PolicyAction::Allow),
1043 (Some(action), None) | (None, Some(action)) => Some(action),
1044 (None, None) => None,
1045 },
1046 }
1047 }
1048}
1049
1050#[cfg(test)]
1051mod approval_policy_tests {
1052 use super::*;
1053 use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
1054 use crate::tool_annotations::{ToolAnnotations, ToolArgSchema, ToolKind};
1055
1056 fn workspace_caps(ops: &[&str]) -> CapabilityPolicy {
1057 CapabilityPolicy {
1058 capabilities: std::collections::BTreeMap::from([(
1059 "workspace".to_string(),
1060 ops.iter().map(|s| s.to_string()).collect(),
1061 )]),
1062 ..Default::default()
1063 }
1064 }
1065
1066 #[test]
1067 fn builtin_ceiling_permits_desktop_control_but_a_lower_ceiling_denies_it() {
1068 let builtin = builtin_ceiling();
1072 assert!(policy_allows_side_effect(
1073 &builtin,
1074 SideEffectLevel::DesktopControl.as_str()
1075 ));
1076
1077 let network_ceiling = CapabilityPolicy {
1081 side_effect_level: Some(SideEffectLevel::Network.as_str().to_string()),
1082 ..Default::default()
1083 };
1084 assert!(!policy_allows_side_effect(
1085 &network_ceiling,
1086 SideEffectLevel::DesktopControl.as_str()
1087 ));
1088 assert!(policy_allows_side_effect(
1090 &network_ceiling,
1091 SideEffectLevel::ProcessExec.as_str()
1092 ));
1093 }
1094
1095 #[test]
1096 fn read_text_subsumes_exists_probe() {
1097 push_execution_policy(workspace_caps(&[
1105 "read_text",
1106 "list",
1107 "write_text",
1108 "apply_edit",
1109 ]));
1110 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
1111 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
1112 assert!(enforce_current_policy_for_builtin("stat", &[]).is_ok());
1113 pop_execution_policy();
1114 }
1115
1116 #[test]
1117 fn list_alone_subsumes_exists_probe() {
1118 push_execution_policy(workspace_caps(&["list"]));
1120 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
1121 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
1122 pop_execution_policy();
1123 }
1124
1125 #[test]
1126 fn exists_probe_rejected_without_any_read_grant() {
1127 push_execution_policy(workspace_caps(&["write_text", "apply_edit"]));
1130 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_err());
1131 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_err());
1132 pop_execution_policy();
1133 }
1134
1135 #[test]
1136 fn auto_deny_takes_precedence_over_auto_approve() {
1137 let policy = ToolApprovalPolicy {
1138 auto_approve: vec!["*".to_string()],
1139 auto_deny: vec!["dangerous_*".to_string()],
1140 ..Default::default()
1141 };
1142 assert_eq!(
1143 policy.evaluate("dangerous_rm", &serde_json::json!({})),
1144 ToolApprovalDecision::AutoDenied {
1145 reason: "tool 'dangerous_rm' matches deny pattern 'dangerous_*'".to_string()
1146 }
1147 );
1148 }
1149
1150 #[test]
1151 fn auto_approve_matches_glob() {
1152 let policy = ToolApprovalPolicy {
1153 auto_approve: vec!["read*".to_string(), "search*".to_string()],
1154 ..Default::default()
1155 };
1156 assert_eq!(
1157 policy.evaluate("read_file", &serde_json::json!({})),
1158 ToolApprovalDecision::AutoApproved
1159 );
1160 assert_eq!(
1161 policy.evaluate("search", &serde_json::json!({})),
1162 ToolApprovalDecision::AutoApproved
1163 );
1164 }
1165
1166 #[test]
1167 fn require_approval_emits_decision() {
1168 let policy = ToolApprovalPolicy {
1169 require_approval: vec!["edit*".to_string()],
1170 ..Default::default()
1171 };
1172 let decision = policy.evaluate("edit_file", &serde_json::json!({"path": "foo.rs"}));
1173 assert!(matches!(
1174 decision,
1175 ToolApprovalDecision::RequiresHostApproval
1176 ));
1177 }
1178
1179 #[test]
1180 fn unmatched_tool_defaults_to_approved() {
1181 let policy = ToolApprovalPolicy {
1182 auto_approve: vec!["read*".to_string()],
1183 require_approval: vec!["edit*".to_string()],
1184 ..Default::default()
1185 };
1186 assert_eq!(
1187 policy.evaluate("unknown_tool", &serde_json::json!({})),
1188 ToolApprovalDecision::AutoApproved
1189 );
1190 }
1191
1192 #[test]
1193 fn intersect_merges_deny_lists() {
1194 let a = ToolApprovalPolicy {
1195 auto_deny: vec!["rm*".to_string()],
1196 ..Default::default()
1197 };
1198 let b = ToolApprovalPolicy {
1199 auto_deny: vec!["drop*".to_string()],
1200 ..Default::default()
1201 };
1202 let merged = a.intersect(&b);
1203 assert_eq!(merged.auto_deny.len(), 2);
1204 }
1205
1206 #[test]
1207 fn intersect_restricts_auto_approve_to_common_patterns() {
1208 let a = ToolApprovalPolicy {
1209 auto_approve: vec!["read*".to_string(), "search*".to_string()],
1210 ..Default::default()
1211 };
1212 let b = ToolApprovalPolicy {
1213 auto_approve: vec!["read*".to_string(), "write*".to_string()],
1214 ..Default::default()
1215 };
1216 let merged = a.intersect(&b);
1217 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1218 }
1219
1220 #[test]
1221 fn intersect_defers_auto_approve_when_one_side_empty() {
1222 let a = ToolApprovalPolicy {
1223 auto_approve: vec!["read*".to_string()],
1224 ..Default::default()
1225 };
1226 let b = ToolApprovalPolicy::default();
1227 let merged = a.intersect(&b);
1228 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1229 }
1230
1231 #[test]
1232 fn write_path_allowlist_matches_recovered_workspace_relative_path() {
1233 let temp = tempfile::tempdir().unwrap();
1234 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1235 std::fs::write(temp.path().join("packages/demo/file.txt"), "ok").unwrap();
1236 crate::stdlib::process::set_thread_execution_context(Some(
1237 crate::orchestration::RunExecutionRecord {
1238 cwd: Some(temp.path().to_string_lossy().into_owned()),
1239 project_root: None,
1240 source_dir: Some(temp.path().to_string_lossy().into_owned()),
1241 env: BTreeMap::new(),
1242 adapter: None,
1243 repo_path: None,
1244 worktree_path: None,
1245 branch: None,
1246 base_ref: None,
1247 cleanup: None,
1248 environment_policy: Default::default(),
1249 grants: Vec::new(),
1250 },
1251 ));
1252
1253 let mut tool_annotations = BTreeMap::new();
1254 tool_annotations.insert(
1255 "write_file".to_string(),
1256 ToolAnnotations {
1257 kind: ToolKind::Edit,
1258 arg_schema: ToolArgSchema {
1259 path_params: vec!["path".to_string()],
1260 ..Default::default()
1261 },
1262 ..Default::default()
1263 },
1264 );
1265 push_execution_policy(CapabilityPolicy {
1266 tool_annotations,
1267 ..Default::default()
1268 });
1269
1270 let policy = ToolApprovalPolicy {
1271 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1272 ..Default::default()
1273 };
1274 let decision = policy.evaluate(
1275 "write_file",
1276 &serde_json::json!({"path": "/packages/demo/file.txt"}),
1277 );
1278 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1279
1280 pop_execution_policy();
1281 crate::stdlib::process::set_thread_execution_context(None);
1282 }
1283
1284 #[test]
1285 fn write_path_allowlist_does_not_block_read_only_tools() {
1286 let temp = tempfile::tempdir().unwrap();
1287 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1288 std::fs::write(temp.path().join("packages/demo/context.txt"), "ok").unwrap();
1289 crate::stdlib::process::set_thread_execution_context(Some(
1290 crate::orchestration::RunExecutionRecord {
1291 cwd: Some(temp.path().to_string_lossy().into_owned()),
1292 project_root: None,
1293 source_dir: Some(temp.path().to_string_lossy().into_owned()),
1294 env: BTreeMap::new(),
1295 adapter: None,
1296 repo_path: None,
1297 worktree_path: None,
1298 branch: None,
1299 base_ref: None,
1300 cleanup: None,
1301 environment_policy: Default::default(),
1302 grants: Vec::new(),
1303 },
1304 ));
1305
1306 let mut tool_annotations = BTreeMap::new();
1307 tool_annotations.insert(
1308 "read_file".to_string(),
1309 ToolAnnotations {
1310 kind: ToolKind::Read,
1311 arg_schema: ToolArgSchema {
1312 path_params: vec!["path".to_string()],
1313 ..Default::default()
1314 },
1315 ..Default::default()
1316 },
1317 );
1318 push_execution_policy(CapabilityPolicy {
1319 tool_annotations,
1320 ..Default::default()
1321 });
1322
1323 let policy = ToolApprovalPolicy {
1324 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1325 ..Default::default()
1326 };
1327 let decision = policy.evaluate(
1328 "read_file",
1329 &serde_json::json!({"path": "/packages/demo/context.txt"}),
1330 );
1331 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1332
1333 pop_execution_policy();
1334 crate::stdlib::process::set_thread_execution_context(None);
1335 }
1336
1337 #[test]
1338 fn builtin_policy_covers_fs_read_and_list_helpers() {
1339 clear_execution_policy_stacks();
1340 push_execution_policy(CapabilityPolicy {
1341 capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1342 side_effect_level: Some("read_only".to_string()),
1343 ..CapabilityPolicy::default()
1344 });
1345
1346 for name in [
1347 "read_lines",
1348 "find_text",
1349 "find_evidence",
1350 "walk_dir",
1351 "glob",
1352 "project_context_profile_native",
1353 ] {
1354 assert!(
1355 enforce_current_policy_for_builtin(name, &[]).is_err(),
1356 "{name} should be rejected when the matching workspace capability is absent"
1357 );
1358 }
1359
1360 pop_execution_policy();
1361 }
1362
1363 #[test]
1364 fn move_file_requires_workspace_write_side_effect() {
1365 clear_execution_policy_stacks();
1366 push_execution_policy(CapabilityPolicy {
1367 capabilities: BTreeMap::from([(
1368 "workspace".to_string(),
1369 vec!["write_text".to_string()],
1370 )]),
1371 side_effect_level: Some("read_only".to_string()),
1372 ..CapabilityPolicy::default()
1373 });
1374
1375 let error = enforce_current_policy_for_builtin("move_file", &[]).unwrap_err();
1376 assert!(
1377 error.to_string().contains("workspace write ceiling"),
1378 "unexpected error: {error}"
1379 );
1380
1381 pop_execution_policy();
1382 }
1383
1384 #[test]
1385 fn unix_socket_json_request_requires_network_side_effect() {
1386 clear_execution_policy_stacks();
1387 push_execution_policy(CapabilityPolicy {
1388 side_effect_level: Some("read_only".to_string()),
1389 ..CapabilityPolicy::default()
1390 });
1391
1392 let error =
1393 enforce_current_policy_for_builtin("__net_unix_socket_json_request", &[]).unwrap_err();
1394 assert!(
1395 error.to_string().contains("network.http ceiling"),
1396 "unexpected error: {error}"
1397 );
1398
1399 pop_execution_policy();
1400 }
1401
1402 #[test]
1403 fn files_upload_requires_workspace_read_and_network_side_effect() {
1404 clear_execution_policy_stacks();
1405 push_execution_policy(CapabilityPolicy {
1406 capabilities: BTreeMap::from([
1407 ("workspace".to_string(), vec!["read_text".to_string()]),
1408 ("network".to_string(), vec!["http".to_string()]),
1409 ]),
1410 side_effect_level: Some("read_only".to_string()),
1411 ..CapabilityPolicy::default()
1412 });
1413
1414 let network_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1415 assert!(
1416 network_error.to_string().contains("network.http ceiling"),
1417 "unexpected error: {network_error}"
1418 );
1419 pop_execution_policy();
1420
1421 push_execution_policy(CapabilityPolicy {
1422 capabilities: BTreeMap::from([
1423 ("workspace".to_string(), vec!["exists".to_string()]),
1424 ("network".to_string(), vec!["http".to_string()]),
1425 ]),
1426 side_effect_level: Some("network".to_string()),
1427 ..CapabilityPolicy::default()
1428 });
1429 let read_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1430 assert!(
1431 read_error.to_string().contains("workspace.read_text"),
1432 "unexpected error: {read_error}"
1433 );
1434
1435 pop_execution_policy();
1436 }
1437}
1438
1439#[cfg(test)]
1440mod turn_policy_tests {
1441 use super::TurnPolicy;
1442
1443 #[test]
1444 fn default_allows_done_sentinel() {
1445 let policy = TurnPolicy::default();
1446 assert!(policy.allow_done_sentinel);
1447 assert!(!policy.require_action_or_yield);
1448 assert!(policy.max_prose_chars.is_none());
1449 }
1450
1451 #[test]
1452 fn deserializing_partial_dict_preserves_done_sentinel_pathway() {
1453 let policy: TurnPolicy =
1458 serde_json::from_value(serde_json::json!({ "require_action_or_yield": true }))
1459 .expect("deserialize");
1460 assert!(policy.require_action_or_yield);
1461 assert!(policy.allow_done_sentinel);
1462 }
1463
1464 #[test]
1465 fn deserializing_explicit_false_disables_done_sentinel() {
1466 let policy: TurnPolicy = serde_json::from_value(serde_json::json!({
1467 "require_action_or_yield": true,
1468 "allow_done_sentinel": false,
1469 }))
1470 .expect("deserialize");
1471 assert!(policy.require_action_or_yield);
1472 assert!(!policy.allow_done_sentinel);
1473 }
1474}
1475
1476#[cfg(test)]
1477mod visibility_redaction_tests {
1478 use super::*;
1479 use crate::value::VmValue;
1480
1481 fn mock_transcript() -> VmValue {
1482 let messages = vec![
1483 serde_json::json!({"role": "user", "content": "hi"}),
1484 serde_json::json!({"role": "assistant", "content": "hello"}),
1485 serde_json::json!({"role": "tool_result", "content": "internal tool output"}),
1486 ];
1487 crate::llm::helpers::transcript_to_vm_with_events(
1488 Some("test-id".to_string()),
1489 None,
1490 None,
1491 &messages,
1492 Vec::new(),
1493 Vec::new(),
1494 Some("active"),
1495 )
1496 }
1497
1498 fn message_count(transcript: &VmValue) -> usize {
1499 transcript
1500 .as_dict()
1501 .and_then(|d| d.get("messages"))
1502 .and_then(|v| match v {
1503 VmValue::List(list) => Some(list.len()),
1504 _ => None,
1505 })
1506 .unwrap_or(0)
1507 }
1508
1509 #[test]
1510 fn visibility_none_returns_unchanged() {
1511 let t = mock_transcript();
1512 let result = redact_transcript_visibility(&t, None).unwrap();
1513 assert_eq!(message_count(&result), 3);
1514 }
1515
1516 #[test]
1517 fn visibility_public_drops_tool_results() {
1518 let t = mock_transcript();
1519 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1520 assert_eq!(message_count(&result), 2);
1521 }
1522
1523 #[test]
1524 fn visibility_public_drops_private_content_blocks() {
1525 let t = crate::schema::json_to_vm_value(&serde_json::json!({
1526 "messages": [
1527 {
1528 "role": "assistant",
1529 "visibility": "public",
1530 "text": "visible answer\nsecret chain",
1531 "content": [
1532 {"type": "output_text", "text": "visible answer", "visibility": "public"},
1533 {"type": "reasoning", "text": "secret chain", "visibility": "private"}
1534 ],
1535 "blocks": [
1536 {"type": "output_text", "text": "visible block", "visibility": "public"},
1537 {"type": "tool_call", "text": "internal args", "visibility": "internal"}
1538 ]
1539 }
1540 ],
1541 "events": []
1542 }));
1543
1544 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1545 let rendered = result.display();
1546 assert!(rendered.contains("visible answer"));
1547 assert!(rendered.contains("visible block"));
1548 assert!(!rendered.contains("secret chain"));
1549 assert!(!rendered.contains("internal args"));
1550 }
1551
1552 #[test]
1553 fn visibility_unknown_string_is_pass_through() {
1554 let t = mock_transcript();
1555 let result = redact_transcript_visibility(&t, Some("internal")).unwrap();
1556 assert_eq!(message_count(&result), 3);
1557 }
1558}