Skip to main content

harn_vm/orchestration/policy/
mod.rs

1//! Policy types and capability-ceiling enforcement.
2
3mod approval_rules;
4mod effects;
5mod nested_budget;
6mod types;
7
8use crate::value::VmDictExt;
9use std::cell::RefCell;
10use std::collections::BTreeMap;
11use std::thread_local;
12
13use serde::{Deserialize, Serialize};
14
15use crate::runtime_limits::RuntimeLimits;
16use crate::tool_annotations::{SideEffectLevel, ToolAnnotations};
17use crate::value::{VmError, VmValue};
18use crate::workspace_path::{classify_workspace_path, WorkspacePathInfo};
19
20pub use crate::tool_annotations::{ToolArgSchema, ToolKind};
21pub use approval_rules::{
22    clear_all_approval_policy_repeat_counts, clear_approval_policy_repeat_counts,
23    next_approval_policy_repeat_count, ApprovalShape, PolicyAction, PolicyEvaluation,
24    PolicyMatchedRule, PolicyRule, PolicyRuleMatch,
25};
26pub use effects::{
27    compute_handoff_effects, effect_kind_label, effect_record_summary, effect_subset_violations,
28    effects_from_metadata, EffectKind, EffectRecord, EffectScope,
29};
30pub use nested_budget::{
31    annotate_nested_execution_options, enter_nested_execution_policy, NestedExecutionGuard,
32    NestedExecutionKind, NESTED_KIND_OPTION_KEY, NESTED_LABEL_OPTION_KEY,
33};
34pub use types::{
35    enforce_tool_arg_constraints, AutoCompactPolicy, BranchSemantics, CapabilityPolicy,
36    ContextPolicy, EqIgnored, EscalationPolicy, FeedbackBounds, FeedbackPolicy, JoinPolicy,
37    MapPolicy, ModelPolicy, NativeToolFallbackPolicy, ProcessSandboxPolicy, ProcessSandboxPreset,
38    ReducePolicy, RetryPolicy, SandboxProfile, StageContract, ToolArgConstraint, TurnPolicy,
39};
40
41thread_local! {
42    static EXECUTION_POLICY_STACK: RefCell<Vec<CapabilityPolicy>> = const { RefCell::new(Vec::new()) };
43    static EXECUTION_APPROVAL_POLICY_STACK: RefCell<Vec<ToolApprovalPolicy>> = const { RefCell::new(Vec::new()) };
44    static TRUSTED_BRIDGE_CALL_DEPTH: RefCell<usize> = const { RefCell::new(0) };
45}
46
47pub fn push_execution_policy(policy: CapabilityPolicy) {
48    EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
49}
50
51pub fn pop_execution_policy() {
52    EXECUTION_POLICY_STACK.with(|stack| {
53        stack.borrow_mut().pop();
54    });
55}
56
57pub fn clear_execution_policy_stacks() {
58    EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().clear());
59    EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().clear());
60    TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow_mut() = 0);
61}
62
63pub fn current_execution_policy() -> Option<CapabilityPolicy> {
64    EXECUTION_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
65}
66
67/// O(1) probe for whether any execution policy scope is active on this
68/// thread/task. Lets hot paths (tool dispatch) skip policy enforcement
69/// entirely without paying the `CapabilityPolicy` clone that
70/// [`current_execution_policy`] performs.
71pub fn execution_policy_active() -> bool {
72    EXECUTION_POLICY_STACK.with(|stack| !stack.borrow().is_empty())
73}
74
75pub fn push_approval_policy(policy: ToolApprovalPolicy) {
76    EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
77}
78
79pub fn pop_approval_policy() {
80    EXECUTION_APPROVAL_POLICY_STACK.with(|stack| {
81        stack.borrow_mut().pop();
82    });
83}
84
85pub fn current_approval_policy() -> Option<ToolApprovalPolicy> {
86    EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
87}
88
89// --- Per-task ambient-scope swap primitives -------------------------------
90//
91// The policy/approval/trusted stacks are thread-locals managed as LIFO scopes.
92// That invariant holds for a single synchronous call stack, but a guard held
93// across an `.await` is unsound: under `spawn_local` (and any work-stealing
94// multi-thread executor) a sibling task interleaves and reads/mutates the same
95// thread-local top-of-stack. `AmbientExecutionScope` (see `ambient_scope`)
96// gives each spawned worker its own scope by swapping these stacks in on
97// poll-enter and back out on poll-exit; these `swap_*` helpers are the O(1)
98// primitives it uses. They are intentionally `pub(crate)` — only the ambient
99// combinator should move whole stacks; ordinary code uses push/pop/current.
100
101pub(crate) fn swap_execution_policy_stack(next: Vec<CapabilityPolicy>) -> Vec<CapabilityPolicy> {
102    EXECUTION_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
103}
104
105pub(crate) fn swap_approval_policy_stack(next: Vec<ToolApprovalPolicy>) -> Vec<ToolApprovalPolicy> {
106    EXECUTION_APPROVAL_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
107}
108
109pub(crate) fn swap_trusted_bridge_depth(next: usize) -> usize {
110    TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| std::mem::replace(&mut *depth.borrow_mut(), next))
111}
112
113pub fn current_tool_annotations(tool: &str) -> Option<ToolAnnotations> {
114    current_execution_policy().and_then(|policy| policy.tool_annotations.get(tool).cloned())
115}
116
117/// The explicit tool allowlist the active execution policy advertises, for
118/// building actionable denial feedback that names what the model *can* call.
119///
120/// Prefers `policy.tools` (the explicit ceiling — what the eval lane sets);
121/// falls back to the annotation registry keys when no explicit list is present.
122/// Returns an empty `Vec` when no policy is active or the surface is unbounded
123/// (allow-all), in which case callers keep their generic guidance.
124pub fn current_allowed_tool_names() -> Vec<String> {
125    let Some(policy) = current_execution_policy() else {
126        return Vec::new();
127    };
128    if !policy.tools.is_empty() {
129        return policy.tools;
130    }
131    policy.tool_annotations.keys().cloned().collect()
132}
133
134pub(super) fn tool_kind_participates_in_write_allowlist(tool_name: &str) -> bool {
135    current_tool_annotations(tool_name)
136        .map(|annotations| !annotations.kind.is_read_only())
137        .unwrap_or(true)
138}
139
140pub struct TrustedBridgeCallGuard;
141
142pub fn allow_trusted_bridge_calls() -> TrustedBridgeCallGuard {
143    TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
144        *depth.borrow_mut() += 1;
145    });
146    TrustedBridgeCallGuard
147}
148
149impl Drop for TrustedBridgeCallGuard {
150    fn drop(&mut self) {
151        TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
152            let mut depth = depth.borrow_mut();
153            *depth = depth.saturating_sub(1);
154        });
155    }
156}
157
158fn policy_allows_tool(policy: &CapabilityPolicy, tool: &str) -> bool {
159    policy.tools.is_empty() || policy.tools.iter().any(|allowed| allowed == tool)
160}
161
162fn policy_grants_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
163    policy
164        .capabilities
165        .get(capability)
166        .is_some_and(|ops| ops.is_empty() || ops.iter().any(|allowed| allowed == op))
167}
168
169fn policy_allows_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
170    if policy.capabilities.is_empty() {
171        // Empty capability map = allow-all (e.g. the root agent policy).
172        return true;
173    }
174    if policy_grants_capability(policy, capability, op) {
175        return true;
176    }
177    // Capability subsumption: a stronger read grant implies the weaker
178    // observations it already exposes. An existence/metadata probe
179    // (`workspace.exists`, used by `file_exists`/`path_status`/`stat`) reveals strictly less
180    // than reading file contents (`workspace.read_text`) or listing a directory
181    // (`workspace.list`) — both of which already disclose whether a path
182    // exists. A policy that grants read/list but withholds the existence probe
183    // is incoherent, and silently wedges any tool that stats a path before
184    // reading it (look, read_file, edit/scaffold preflight). Narrowed worker
185    // policies derived from tool annotations hit this constantly because no
186    // annotation declares `workspace.exists`. Encode the lattice once here so
187    // every narrowed policy benefits, not one dispatch surface at a time.
188    if capability == "workspace" && op == "exists" {
189        return policy_grants_capability(policy, "workspace", "read_text")
190            || policy_grants_capability(policy, "workspace", "list");
191    }
192    false
193}
194
195fn policy_allows_side_effect(policy: &CapabilityPolicy, requested: &str) -> bool {
196    // Rank through the canonical `SideEffectLevel` ladder (single source of
197    // truth). `requested` always comes from a typed `SideEffectLevel::as_str()`,
198    // so it is a known value; a typo'd policy ceiling ranks as `none` (0),
199    // conservatively granting nothing above `none` rather than the previous
200    // `_ => 5` that silently allowed everything.
201    let requested_rank = SideEffectLevel::rank_str(requested);
202    policy
203        .side_effect_level
204        .as_ref()
205        .map(|allowed| SideEffectLevel::rank_str(allowed) >= requested_rank)
206        .unwrap_or(true)
207}
208
209pub(super) fn reject_policy(reason: String) -> Result<(), VmError> {
210    Err(VmError::CategorizedError {
211        message: reason,
212        category: crate::value::ErrorCategory::ToolRejected,
213    })
214}
215
216/// Structured refusal produced by the agent-tool capability gates
217/// (`enforce_current_policy_for_tool`, `enforce_tool_arg_constraints`).
218/// Records the gate identity and the exceeded capability so the dispatch
219/// boundary can build a full [`crate::agent_events::ToolDenial`] for the
220/// model and host. `From<PolicyDenial> for VmError` keeps the legacy
221/// `?`-using callers — which only need the categorized error — unchanged.
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct PolicyDenial {
224    pub gate: crate::agent_events::DenialGate,
225    pub capability: Option<String>,
226    pub reason: String,
227}
228
229impl From<PolicyDenial> for VmError {
230    fn from(denial: PolicyDenial) -> Self {
231        VmError::CategorizedError {
232            message: denial.reason,
233            category: crate::value::ErrorCategory::ToolRejected,
234        }
235    }
236}
237
238pub(super) fn reject_tool(
239    gate: crate::agent_events::DenialGate,
240    capability: Option<String>,
241    reason: String,
242) -> Result<(), PolicyDenial> {
243    Err(PolicyDenial {
244        gate,
245        capability,
246        reason,
247    })
248}
249
250/// Mutation classification for a tool, derived from the pipeline's
251/// declared `ToolKind`. Used in telemetry and pre/post-bridge payloads
252/// while those methods still exist. Returns `"other"` for unannotated
253/// tools (fail-safe; unknown tools don't auto-classify).
254pub fn current_tool_mutation_classification(tool_name: &str) -> String {
255    current_tool_annotations(tool_name)
256        .map(|annotations| annotations.kind.mutation_class().to_string())
257        .unwrap_or_else(|| "other".to_string())
258}
259
260/// Workspace paths declared by this tool call, read from the tool's
261/// annotated `arg_schema.path_params`. Unannotated tools declare no
262/// paths — the VM no longer guesses by common argument names.
263pub fn current_tool_declared_paths(tool_name: &str, args: &serde_json::Value) -> Vec<String> {
264    current_tool_declared_path_entries(tool_name, args)
265        .into_iter()
266        .map(|entry| entry.display_path().to_string())
267        .collect()
268}
269
270/// Rich workspace-path descriptors declared by this tool call. Each
271/// entry preserves the original input while also projecting the path
272/// into workspace-relative and host-absolute forms when that mapping is
273/// known.
274pub fn current_tool_declared_path_entries(
275    tool_name: &str,
276    args: &serde_json::Value,
277) -> Vec<WorkspacePathInfo> {
278    let Some(map) = args.as_object() else {
279        return Vec::new();
280    };
281    let Some(annotations) = current_tool_annotations(tool_name) else {
282        return Vec::new();
283    };
284    let workspace_root = crate::stdlib::process::execution_root_path();
285    let mut entries = Vec::new();
286    for key in &annotations.arg_schema.path_params {
287        if let Some(value) = map.get(key) {
288            match value {
289                serde_json::Value::String(path) if !path.is_empty() => {
290                    entries.push(classify_workspace_path(path, Some(&workspace_root)));
291                }
292                serde_json::Value::Array(items) => {
293                    for item in items.iter().filter_map(|item| item.as_str()) {
294                        if !item.is_empty() {
295                            entries.push(classify_workspace_path(item, Some(&workspace_root)));
296                        }
297                    }
298                }
299                _ => {}
300            }
301        }
302    }
303    entries.sort_by(|a, b| a.display_path().cmp(b.display_path()));
304    entries.dedup_by(|left, right| left.policy_candidates() == right.policy_candidates());
305    entries
306}
307
308pub fn enforce_current_policy_for_builtin(name: &str, args: &[VmValue]) -> Result<(), VmError> {
309    let Some(policy) = current_execution_policy() else {
310        return Ok(());
311    };
312    match name {
313        "find_text"
314            if !policy_allows_capability(&policy, "workspace", "read_text")
315                || !policy_allows_capability(&policy, "workspace", "list") =>
316        {
317            return reject_policy(
318                "builtin 'find_text' exceeds workspace.read_text/workspace.list ceiling"
319                    .to_string(),
320            );
321        }
322        "read_file"
323        | "read_file_result"
324        | "read_file_bytes"
325        | "package_snapshot_open"
326        | "render"
327        | "render_prompt"
328        | "render_with_provenance"
329        | "read_lines"
330            if !policy_allows_capability(&policy, "workspace", "read_text") =>
331        {
332            return reject_policy(format!(
333                "builtin '{name}' exceeds workspace.read_text ceiling"
334            ));
335        }
336        "list_dir" | "walk_dir" | "glob"
337            if !policy_allows_capability(&policy, "workspace", "list") =>
338        {
339            return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
340        }
341        "file_exists" | "path_status" | "stat"
342            if !policy_allows_capability(&policy, "workspace", "exists") =>
343        {
344            return reject_policy(format!("builtin '{name}' exceeds workspace.exists ceiling"));
345        }
346        "write_file" | "write_file_bytes" | "append_file" | "mkdir" | "copy_file" | "move_file"
347            if !policy_allows_capability(&policy, "workspace", "write_text")
348                || !policy_allows_side_effect(&policy, "workspace_write") =>
349        {
350            return reject_policy(format!("builtin '{name}' exceeds workspace write ceiling"));
351        }
352        "delete_file"
353            if !policy_allows_capability(&policy, "workspace", "delete")
354                || !policy_allows_side_effect(&policy, "workspace_write") =>
355        {
356            return reject_policy(
357                "builtin 'delete_file' exceeds workspace.delete ceiling".to_string(),
358            );
359        }
360        "apply_edit"
361            if !policy_allows_capability(&policy, "workspace", "apply_edit")
362                || !policy_allows_side_effect(&policy, "workspace_write") =>
363        {
364            return reject_policy(
365                "builtin 'apply_edit' exceeds workspace.apply_edit ceiling".to_string(),
366            );
367        }
368        "exec"
369        | "exec_at"
370        | "shell"
371        | "shell_at"
372        | "git.repo.discover"
373        | "git.worktree.create"
374        | "git.worktree.remove"
375        | "git.fetch"
376        | "git.rebase"
377        | "git.status"
378        | "git.conflicts"
379        | "git.push"
380        | "git.diff"
381        | "git.merge_base"
382        | "git.tag_list"
383        | "git.describe"
384        | "git.ls_remote"
385            if !policy_allows_capability(&policy, "process", "exec")
386                || !policy_allows_side_effect(&policy, "process_exec") =>
387        {
388            return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
389        }
390        // `__files_upload` needs a stricter workspace.read_text + network
391        // ceiling, so it stays a distinct arm ahead of the shared network arm
392        // below (its name never overlaps the network patterns, so ordering is
393        // immaterial to correctness).
394        "__files_upload"
395            if !policy_allows_capability(&policy, "workspace", "read_text")
396                || !policy_allows_side_effect(&policy, "network") =>
397        {
398            return reject_policy(
399                "builtin '__files_upload' exceeds workspace.read_text/network ceiling".to_string(),
400            );
401        }
402        "http_get"
403        | "http_post"
404        | "http_put"
405        | "http_patch"
406        | "http_delete"
407        | "http_download"
408        | "http_request"
409        | "unix_socket_json_request"
410        | "__net_unix_socket_json_request"
411        | "http_session_request"
412        | "http_stream_open"
413        | "http_stream_read"
414        | "http_stream_close"
415        | "http_stream_info"
416        | "sse_connect"
417        | "sse_receive"
418        | "websocket_accept"
419        | "websocket_connect"
420        | "websocket_route"
421        | "websocket_send"
422        | "websocket_receive"
423        | "websocket_server"
424            if !policy_allows_side_effect(&policy, "network") =>
425        {
426            return reject_policy(format!("builtin '{name}' exceeds network ceiling"));
427        }
428        "llm_call" | "llm_call_safe" | "llm_completion" | "llm_stream" | "llm_stream_call"
429        | "llm_healthcheck" | "agent_loop"
430            if !policy_allows_capability(&policy, "llm", "call") =>
431        {
432            return reject_policy(format!("builtin '{name}' exceeds llm.call ceiling"));
433        }
434        "connector_call"
435            if !policy_allows_capability(&policy, "connector", "call")
436                || !policy_allows_side_effect(&policy, "network") =>
437        {
438            return reject_policy(
439                "builtin 'connector_call' exceeds connector.call/network ceiling".to_string(),
440            );
441        }
442        "secret_get" if !policy_allows_capability(&policy, "connector", "secret_get") => {
443            return reject_policy(
444                "builtin 'secret_get' exceeds connector.secret_get ceiling".to_string(),
445            );
446        }
447        "event_log_emit" if !policy_allows_capability(&policy, "connector", "event_log_emit") => {
448            return reject_policy(
449                "builtin 'event_log_emit' exceeds connector.event_log_emit ceiling".to_string(),
450            );
451        }
452        "metrics_inc" if !policy_allows_capability(&policy, "connector", "metrics_inc") => {
453            return reject_policy(
454                "builtin 'metrics_inc' exceeds connector.metrics_inc ceiling".to_string(),
455            );
456        }
457        "project_fingerprint"
458        | "project_context_profile_native"
459        | "project_scan_native"
460        | "project_scan_tree_native"
461        | "project_walk_tree_native"
462        | "project_catalog_native"
463            if !policy_allows_capability(&policy, "workspace", "list")
464                || !policy_allows_side_effect(&policy, "read_only") =>
465        {
466            return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
467        }
468        "__agent_state_init"
469        | "__agent_state_resume"
470        | "__agent_state_write"
471        | "__agent_state_read"
472        | "__agent_state_list"
473        | "__agent_state_delete"
474        | "__agent_state_handoff"
475            if !policy_allows_capability(&policy, "agent_state", "access") =>
476        {
477            return reject_policy(format!(
478                "builtin '{name}' exceeds agent_state.access ceiling"
479            ));
480        }
481        "vision_ocr"
482            if !policy_allows_capability(&policy, "vision", "ocr")
483                || !policy_allows_side_effect(&policy, "process_exec") =>
484        {
485            return reject_policy(format!(
486                "builtin '{name}' exceeds vision.ocr/process ceiling"
487            ));
488        }
489        "mcp_connect"
490        | "mcp_ensure_active"
491        | "mcp_call"
492        | "mcp_list_tools"
493        | "mcp_list_resources"
494        | "mcp_list_resource_templates"
495        | "mcp_read_resource"
496        | "mcp_list_prompts"
497        | "mcp_get_prompt"
498        | "mcp_server_info"
499        | "mcp_disconnect"
500            if !policy_allows_capability(&policy, "process", "exec")
501                || !policy_allows_side_effect(&policy, "process_exec") =>
502        {
503            return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
504        }
505        "host_call" => {
506            let name = args.first().map(|v| v.display()).unwrap_or_default();
507            let Some((capability, op)) = name.split_once('.') else {
508                return reject_policy(format!(
509                    "host_call '{name}' must use capability.operation naming"
510                ));
511            };
512            if !policy_allows_capability(&policy, capability, op) {
513                return reject_policy(format!(
514                    "host_call {capability}.{op} exceeds capability ceiling"
515                ));
516            }
517            let requested_side_effect = match (capability, op) {
518                ("workspace", "write_text" | "apply_edit" | "delete") => "workspace_write",
519                ("process", "exec") => "process_exec",
520                _ => "read_only",
521            };
522            if !policy_allows_side_effect(&policy, requested_side_effect) {
523                return reject_policy(format!(
524                    "host_call {capability}.{op} exceeds side-effect ceiling"
525                ));
526            }
527        }
528        "host_tool_list" | "host_tool_call"
529            if !policy_allows_capability(&policy, "host", "tool_call") =>
530        {
531            return reject_policy(format!("builtin '{name}' exceeds host.tool_call ceiling"));
532        }
533        _ => {}
534    }
535    Ok(())
536}
537
538pub fn enforce_current_policy_for_bridge_builtin(name: &str) -> Result<(), VmError> {
539    let trusted = TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow() > 0);
540    if trusted {
541        return Ok(());
542    }
543    if current_execution_policy().is_some() {
544        return reject_policy(format!(
545            "bridged builtin '{name}' exceeds execution policy; declare an explicit capability/tool surface instead"
546        ));
547    }
548    Ok(())
549}
550
551pub fn enforce_current_policy_for_tool(tool_name: &str) -> Result<(), PolicyDenial> {
552    use crate::agent_events::DenialGate;
553    let Some(policy) = current_execution_policy() else {
554        return Ok(());
555    };
556    if !policy_allows_tool(&policy, tool_name) {
557        return reject_tool(
558            DenialGate::ToolCeiling,
559            None,
560            format!("tool '{tool_name}' exceeds tool ceiling"),
561        );
562    }
563    if let Some(annotations) = policy.tool_annotations.get(tool_name) {
564        for (capability, ops) in &annotations.capabilities {
565            for op in ops {
566                if !policy_allows_capability(&policy, capability, op) {
567                    return reject_tool(
568                        DenialGate::CapabilityCeiling,
569                        Some(format!("{capability}.{op}")),
570                        format!("tool '{tool_name}' exceeds capability ceiling: {capability}.{op}"),
571                    );
572                }
573            }
574        }
575        let requested_level = annotations.side_effect_level;
576        if requested_level != SideEffectLevel::None
577            && !policy_allows_side_effect(&policy, requested_level.as_str())
578        {
579            return reject_tool(
580                DenialGate::SideEffectCeiling,
581                None,
582                format!(
583                    "tool '{tool_name}' exceeds side-effect ceiling: {}",
584                    requested_level.as_str()
585                ),
586            );
587        }
588    }
589    Ok(())
590}
591
592// ── Output visibility redaction ─────────────────────────────────────
593//
594// Transcript lifecycle (reset, fork, trim, compact) now lives on
595// `crate::agent_sessions` as explicit imperative builtins. All that
596// remains here is the per-call visibility filter, which is
597// output-shaping (not lifecycle).
598
599/// Filter a transcript dict down to the caller-visible subset, based
600/// on the `output_visibility` node option. `None` or any unknown
601/// visibility returns the transcript unchanged — callers are expected
602/// to validate the string against a known set upstream.
603pub fn redact_transcript_visibility(
604    transcript: &VmValue,
605    visibility: Option<&str>,
606) -> Option<VmValue> {
607    let Some(visibility) = visibility else {
608        return Some(transcript.clone());
609    };
610    if visibility != "public" && visibility != "public_only" {
611        return Some(transcript.clone());
612    }
613    let dict = transcript.as_dict()?;
614    let public_messages = match dict.get("messages") {
615        Some(VmValue::List(list)) => list
616            .iter()
617            .filter_map(redact_public_message)
618            .collect::<Vec<_>>(),
619        _ => Vec::new(),
620    };
621    let public_events = match dict.get("events") {
622        Some(VmValue::List(list)) => list
623            .iter()
624            .filter(|event| {
625                event
626                    .as_dict()
627                    .and_then(|d| d.get("visibility"))
628                    .map(|v| v.display())
629                    .map(|value| value == "public")
630                    .unwrap_or(true)
631            })
632            .cloned()
633            .collect::<Vec<_>>(),
634        _ => Vec::new(),
635    };
636    let mut redacted = dict.clone();
637    redacted.insert(
638        crate::value::intern_key("messages"),
639        VmValue::List(std::sync::Arc::new(public_messages)),
640    );
641    redacted.insert(
642        crate::value::intern_key("events"),
643        VmValue::List(std::sync::Arc::new(public_events)),
644    );
645    Some(VmValue::dict(redacted))
646}
647
648fn redact_public_message(message: &VmValue) -> Option<VmValue> {
649    let Some(dict) = message.as_dict() else {
650        return Some(message.clone());
651    };
652    if dict.get("role").map(|value| value.display()).as_deref() == Some("tool_result") {
653        return None;
654    }
655    if dict
656        .get("visibility")
657        .map(|value| value.display())
658        .is_some_and(|visibility| visibility != "public")
659    {
660        return None;
661    }
662
663    let mut redacted = dict.clone();
664    let mut saw_structured_blocks = false;
665    let mut public_text = Vec::new();
666    for key in ["content", "blocks"] {
667        if let Some(VmValue::List(blocks)) = dict.get(key) {
668            saw_structured_blocks = true;
669            let public_blocks = blocks
670                .iter()
671                .filter_map(redact_public_block)
672                .collect::<Vec<_>>();
673            if key == "blocks" || public_text.is_empty() {
674                public_text = text_fragments_from_blocks(&public_blocks);
675            }
676            redacted.insert(
677                crate::value::intern_key(key),
678                VmValue::List(std::sync::Arc::new(public_blocks)),
679            );
680        }
681    }
682    if saw_structured_blocks {
683        if public_text.is_empty() {
684            redacted.remove("text");
685        } else {
686            redacted.put_str("text", public_text.join("\n"));
687        }
688    }
689    Some(VmValue::dict(redacted))
690}
691
692fn redact_public_block(block: &VmValue) -> Option<VmValue> {
693    let Some(dict) = block.as_dict() else {
694        return Some(block.clone());
695    };
696    if dict
697        .get("visibility")
698        .map(|value| value.display())
699        .is_some_and(|visibility| visibility != "public")
700    {
701        return None;
702    }
703    Some(block.clone())
704}
705
706fn text_fragments_from_blocks(blocks: &[VmValue]) -> Vec<String> {
707    blocks
708        .iter()
709        .filter_map(|block| block.as_dict())
710        .filter_map(|dict| dict.get("text"))
711        .filter_map(|text| match text {
712            VmValue::String(value) if !value.is_empty() => Some(value.to_string()),
713            _ => None,
714        })
715        .collect()
716}
717
718pub fn builtin_ceiling() -> CapabilityPolicy {
719    CapabilityPolicy {
720        // `capabilities` is intentionally empty: the host capability manifest
721        // is the sole authority, and an allowlist here would silently block
722        // any capability the host adds later.
723        tools: Vec::new(),
724        capabilities: BTreeMap::new(),
725        workspace_roots: Vec::new(),
726        read_only_roots: Vec::new(),
727        // The builtin ceiling is the runtime's OUTERMOST bound — the top of the
728        // side-effect ladder. Every real policy intersects DOWN from here, so this
729        // must be the maximum level or it would silently cap more-invasive tools
730        // out entirely. It tracks the top of the ladder: `desktop_control`. This
731        // does not loosen anything — a normal agent's surface policy still caps at
732        // the max of ITS tools (e.g. `network`); only a surface that actually
733        // carries a `desktop_control` tool (computer use, gated by the off-by-
734        // default flag) can reach the top.
735        // Tracks the ladder top via `SideEffectLevel::MAX` (never a hardcoded level).
736        side_effect_level: Some(SideEffectLevel::MAX.as_str().to_string()),
737        recursion_limit: Some(RuntimeLimits::DEFAULT.max_nested_execution_depth),
738        tool_arg_constraints: Vec::new(),
739        tool_annotations: BTreeMap::new(),
740        sandbox_profile: SandboxProfile::Worktree,
741        process_sandbox: Default::default(),
742    }
743}
744
745/// Declarative policy for tool approval gating. Allows pipelines to
746/// specify which tools are auto-approved, auto-denied, or require
747/// host confirmation, plus write-path allowlists.
748#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
749#[serde(default)]
750pub struct ToolApprovalPolicy {
751    /// Ordered allow/ask/deny rules over tool metadata, path, command,
752    /// URL, MCP, agent/persona/mode, and repeat-count dimensions.
753    #[serde(default)]
754    pub rules: Vec<PolicyRule>,
755    /// Glob patterns for tools that should be auto-approved.
756    #[serde(default)]
757    pub auto_approve: Vec<String>,
758    /// Glob patterns for tools that should always be denied.
759    #[serde(default)]
760    pub auto_deny: Vec<String>,
761    /// Glob patterns for tools that require host confirmation.
762    #[serde(default)]
763    pub require_approval: Vec<String>,
764    /// Glob patterns for writable paths.
765    #[serde(default)]
766    pub write_path_allowlist: Vec<String>,
767    /// Explicit opt-out for the deny-by-default sensitive-path guard.
768    #[serde(default)]
769    pub allow_sensitive_paths: bool,
770    /// Additional or replacement sensitive path globs. Empty uses the
771    /// runtime defaults such as `.env`, private keys, and credential files.
772    #[serde(default)]
773    pub sensitive_path_patterns: Vec<String>,
774    /// Explicit opt-out for the external-path guard on declared path args.
775    #[serde(default)]
776    pub allow_external_paths: bool,
777    /// Host-absolute roots allowed when `allow_external_paths` is false.
778    #[serde(default)]
779    pub external_roots: Vec<String>,
780    /// Optional repeated-call threshold for the same `(session, tool, args)`.
781    #[serde(default, alias = "repeated_call_limit")]
782    pub repeat_limit: Option<u64>,
783    /// Action for `repeat_limit`; defaults to `ask`.
784    #[serde(default, alias = "repeated_call_action")]
785    pub repeat_action: Option<PolicyAction>,
786}
787
788/// Result of evaluating a tool call against a ToolApprovalPolicy.
789#[derive(Debug, Clone, PartialEq, Eq)]
790pub enum ToolApprovalDecision {
791    /// Tool is auto-approved by policy.
792    AutoApproved,
793    /// Tool is auto-denied by policy.
794    AutoDenied { reason: String },
795    /// Tool requires explicit host approval; the caller already owns the
796    /// tool name and args and forwards them to the host bridge.
797    RequiresHostApproval,
798}
799
800impl ToolApprovalPolicy {
801    pub fn evaluate_detailed(&self, tool_name: &str, args: &serde_json::Value) -> PolicyEvaluation {
802        approval_rules::evaluate_tool_approval_policy(self, tool_name, args, None)
803    }
804
805    pub fn evaluate_detailed_with_repeat(
806        &self,
807        tool_name: &str,
808        args: &serde_json::Value,
809        repeat_count: u64,
810    ) -> PolicyEvaluation {
811        approval_rules::evaluate_tool_approval_policy(self, tool_name, args, Some(repeat_count))
812    }
813
814    /// Evaluate whether a tool call should be approved, denied, or needs
815    /// host confirmation.
816    pub fn evaluate(&self, tool_name: &str, args: &serde_json::Value) -> ToolApprovalDecision {
817        let decision = self.evaluate_detailed(tool_name, args);
818        if decision.is_deny() {
819            return ToolApprovalDecision::AutoDenied {
820                reason: decision.reason,
821            };
822        }
823        if decision.is_ask() {
824            return ToolApprovalDecision::RequiresHostApproval;
825        }
826        ToolApprovalDecision::AutoApproved
827    }
828
829    /// Merge two approval policies, taking the most restrictive combination.
830    /// - auto_approve: only tools approved by BOTH policies stay approved
831    ///   (if either policy has no patterns, the other's patterns are used)
832    /// - auto_deny / require_approval: union (either policy can deny/gate)
833    /// - write_path_allowlist: intersection (both must allow the path)
834    pub fn intersect(&self, other: &ToolApprovalPolicy) -> ToolApprovalPolicy {
835        let auto_approve = if self.auto_approve.is_empty() {
836            other.auto_approve.clone()
837        } else if other.auto_approve.is_empty() {
838            self.auto_approve.clone()
839        } else {
840            self.auto_approve
841                .iter()
842                .filter(|p| other.auto_approve.contains(p))
843                .cloned()
844                .collect()
845        };
846        let mut auto_deny = self.auto_deny.clone();
847        auto_deny.extend(other.auto_deny.iter().cloned());
848        let mut require_approval = self.require_approval.clone();
849        require_approval.extend(other.require_approval.iter().cloned());
850        let write_path_allowlist = if self.write_path_allowlist.is_empty() {
851            other.write_path_allowlist.clone()
852        } else if other.write_path_allowlist.is_empty() {
853            self.write_path_allowlist.clone()
854        } else {
855            self.write_path_allowlist
856                .iter()
857                .filter(|p| other.write_path_allowlist.contains(p))
858                .cloned()
859                .collect()
860        };
861        let mut rules = self.rules.clone();
862        rules.extend(other.rules.iter().cloned());
863        let mut sensitive_path_patterns = self.sensitive_path_patterns.clone();
864        sensitive_path_patterns.extend(other.sensitive_path_patterns.iter().cloned());
865        sensitive_path_patterns.sort();
866        sensitive_path_patterns.dedup();
867        let external_roots = if self.external_roots.is_empty() {
868            other.external_roots.clone()
869        } else if other.external_roots.is_empty() {
870            self.external_roots.clone()
871        } else {
872            self.external_roots
873                .iter()
874                .filter(|root| other.external_roots.contains(root))
875                .cloned()
876                .collect()
877        };
878        ToolApprovalPolicy {
879            rules,
880            auto_approve,
881            auto_deny,
882            require_approval,
883            write_path_allowlist,
884            allow_sensitive_paths: self.allow_sensitive_paths && other.allow_sensitive_paths,
885            sensitive_path_patterns,
886            allow_external_paths: self.allow_external_paths && other.allow_external_paths,
887            external_roots,
888            repeat_limit: match (self.repeat_limit, other.repeat_limit) {
889                (Some(left), Some(right)) => Some(left.min(right)),
890                (Some(left), None) => Some(left),
891                (None, Some(right)) => Some(right),
892                (None, None) => None,
893            },
894            repeat_action: match (self.repeat_action, other.repeat_action) {
895                (Some(PolicyAction::Deny), _) | (_, Some(PolicyAction::Deny)) => {
896                    Some(PolicyAction::Deny)
897                }
898                (Some(PolicyAction::Ask), _) | (_, Some(PolicyAction::Ask)) => {
899                    Some(PolicyAction::Ask)
900                }
901                (Some(PolicyAction::Allow), Some(PolicyAction::Allow)) => Some(PolicyAction::Allow),
902                (Some(action), None) | (None, Some(action)) => Some(action),
903                (None, None) => None,
904            },
905        }
906    }
907}
908
909#[cfg(test)]
910mod approval_policy_tests {
911    use super::*;
912    use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
913    use crate::tool_annotations::{ToolAnnotations, ToolArgSchema, ToolKind};
914
915    fn workspace_caps(ops: &[&str]) -> CapabilityPolicy {
916        CapabilityPolicy {
917            capabilities: std::collections::BTreeMap::from([(
918                "workspace".to_string(),
919                ops.iter().map(|s| s.to_string()).collect(),
920            )]),
921            ..Default::default()
922        }
923    }
924
925    #[test]
926    fn builtin_ceiling_permits_desktop_control_but_a_lower_ceiling_denies_it() {
927        // The runtime's outer bound must admit the most-invasive level, or a
928        // desktop-control (computer-use) tool would be exposed-but-denied under
929        // the default ceiling.
930        let builtin = builtin_ceiling();
931        assert!(policy_allows_side_effect(
932            &builtin,
933            SideEffectLevel::DesktopControl.as_str()
934        ));
935
936        // A narrower policy (e.g. a normal agent whose tools top out at network)
937        // still denies a desktop-control tool — the level is a real gate, not a
938        // no-op.
939        let network_ceiling = CapabilityPolicy {
940            side_effect_level: Some(SideEffectLevel::Network.as_str().to_string()),
941            ..Default::default()
942        };
943        assert!(!policy_allows_side_effect(
944            &network_ceiling,
945            SideEffectLevel::DesktopControl.as_str()
946        ));
947        // ...but that same network ceiling still admits everything at or below it.
948        assert!(policy_allows_side_effect(
949            &network_ceiling,
950            SideEffectLevel::ProcessExec.as_str()
951        ));
952    }
953
954    #[test]
955    fn read_text_subsumes_exists_probe() {
956        // A narrowed worker policy that grants read_text/list (the shape derived
957        // from look/edit/scaffold tool annotations) but never declares the
958        // weaker `workspace.exists` op must still permit `file_exists`,
959        // `path_status`, and `stat`:
960        // existence is strictly less information than reading the file. Without
961        // subsumption this silently wedged every parallel sub-agent (look denied
962        // -> zero progress -> zero edits).
963        push_execution_policy(workspace_caps(&[
964            "read_text",
965            "list",
966            "write_text",
967            "apply_edit",
968        ]));
969        assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
970        assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
971        assert!(enforce_current_policy_for_builtin("stat", &[]).is_ok());
972        pop_execution_policy();
973    }
974
975    #[test]
976    fn list_alone_subsumes_exists_probe() {
977        // Listing a directory already reveals which entries exist.
978        push_execution_policy(workspace_caps(&["list"]));
979        assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
980        assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
981        pop_execution_policy();
982    }
983
984    #[test]
985    fn exists_probe_rejected_without_any_read_grant() {
986        // A write-only grant exposes no read surface, so the existence probe is
987        // genuinely above the ceiling and must still be rejected.
988        push_execution_policy(workspace_caps(&["write_text", "apply_edit"]));
989        assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_err());
990        assert!(enforce_current_policy_for_builtin("path_status", &[]).is_err());
991        pop_execution_policy();
992    }
993
994    #[test]
995    fn auto_deny_takes_precedence_over_auto_approve() {
996        let policy = ToolApprovalPolicy {
997            auto_approve: vec!["*".to_string()],
998            auto_deny: vec!["dangerous_*".to_string()],
999            ..Default::default()
1000        };
1001        assert_eq!(
1002            policy.evaluate("dangerous_rm", &serde_json::json!({})),
1003            ToolApprovalDecision::AutoDenied {
1004                reason: "tool 'dangerous_rm' matches deny pattern 'dangerous_*'".to_string()
1005            }
1006        );
1007    }
1008
1009    #[test]
1010    fn auto_approve_matches_glob() {
1011        let policy = ToolApprovalPolicy {
1012            auto_approve: vec!["read*".to_string(), "search*".to_string()],
1013            ..Default::default()
1014        };
1015        assert_eq!(
1016            policy.evaluate("read_file", &serde_json::json!({})),
1017            ToolApprovalDecision::AutoApproved
1018        );
1019        assert_eq!(
1020            policy.evaluate("search", &serde_json::json!({})),
1021            ToolApprovalDecision::AutoApproved
1022        );
1023    }
1024
1025    #[test]
1026    fn require_approval_emits_decision() {
1027        let policy = ToolApprovalPolicy {
1028            require_approval: vec!["edit*".to_string()],
1029            ..Default::default()
1030        };
1031        let decision = policy.evaluate("edit_file", &serde_json::json!({"path": "foo.rs"}));
1032        assert!(matches!(
1033            decision,
1034            ToolApprovalDecision::RequiresHostApproval
1035        ));
1036    }
1037
1038    #[test]
1039    fn unmatched_tool_defaults_to_approved() {
1040        let policy = ToolApprovalPolicy {
1041            auto_approve: vec!["read*".to_string()],
1042            require_approval: vec!["edit*".to_string()],
1043            ..Default::default()
1044        };
1045        assert_eq!(
1046            policy.evaluate("unknown_tool", &serde_json::json!({})),
1047            ToolApprovalDecision::AutoApproved
1048        );
1049    }
1050
1051    #[test]
1052    fn intersect_merges_deny_lists() {
1053        let a = ToolApprovalPolicy {
1054            auto_deny: vec!["rm*".to_string()],
1055            ..Default::default()
1056        };
1057        let b = ToolApprovalPolicy {
1058            auto_deny: vec!["drop*".to_string()],
1059            ..Default::default()
1060        };
1061        let merged = a.intersect(&b);
1062        assert_eq!(merged.auto_deny.len(), 2);
1063    }
1064
1065    #[test]
1066    fn intersect_restricts_auto_approve_to_common_patterns() {
1067        let a = ToolApprovalPolicy {
1068            auto_approve: vec!["read*".to_string(), "search*".to_string()],
1069            ..Default::default()
1070        };
1071        let b = ToolApprovalPolicy {
1072            auto_approve: vec!["read*".to_string(), "write*".to_string()],
1073            ..Default::default()
1074        };
1075        let merged = a.intersect(&b);
1076        assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1077    }
1078
1079    #[test]
1080    fn intersect_defers_auto_approve_when_one_side_empty() {
1081        let a = ToolApprovalPolicy {
1082            auto_approve: vec!["read*".to_string()],
1083            ..Default::default()
1084        };
1085        let b = ToolApprovalPolicy::default();
1086        let merged = a.intersect(&b);
1087        assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1088    }
1089
1090    #[test]
1091    fn write_path_allowlist_matches_recovered_workspace_relative_path() {
1092        let temp = tempfile::tempdir().unwrap();
1093        std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1094        std::fs::write(temp.path().join("packages/demo/file.txt"), "ok").unwrap();
1095        crate::stdlib::process::set_thread_execution_context(Some(
1096            crate::orchestration::RunExecutionRecord {
1097                cwd: Some(temp.path().to_string_lossy().into_owned()),
1098                project_root: None,
1099                source_dir: Some(temp.path().to_string_lossy().into_owned()),
1100                env: BTreeMap::new(),
1101                adapter: None,
1102                repo_path: None,
1103                worktree_path: None,
1104                branch: None,
1105                base_ref: None,
1106                cleanup: None,
1107            },
1108        ));
1109
1110        let mut tool_annotations = BTreeMap::new();
1111        tool_annotations.insert(
1112            "write_file".to_string(),
1113            ToolAnnotations {
1114                kind: ToolKind::Edit,
1115                arg_schema: ToolArgSchema {
1116                    path_params: vec!["path".to_string()],
1117                    ..Default::default()
1118                },
1119                ..Default::default()
1120            },
1121        );
1122        push_execution_policy(CapabilityPolicy {
1123            tool_annotations,
1124            ..Default::default()
1125        });
1126
1127        let policy = ToolApprovalPolicy {
1128            write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1129            ..Default::default()
1130        };
1131        let decision = policy.evaluate(
1132            "write_file",
1133            &serde_json::json!({"path": "/packages/demo/file.txt"}),
1134        );
1135        assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1136
1137        pop_execution_policy();
1138        crate::stdlib::process::set_thread_execution_context(None);
1139    }
1140
1141    #[test]
1142    fn write_path_allowlist_does_not_block_read_only_tools() {
1143        let temp = tempfile::tempdir().unwrap();
1144        std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1145        std::fs::write(temp.path().join("packages/demo/context.txt"), "ok").unwrap();
1146        crate::stdlib::process::set_thread_execution_context(Some(
1147            crate::orchestration::RunExecutionRecord {
1148                cwd: Some(temp.path().to_string_lossy().into_owned()),
1149                project_root: None,
1150                source_dir: Some(temp.path().to_string_lossy().into_owned()),
1151                env: BTreeMap::new(),
1152                adapter: None,
1153                repo_path: None,
1154                worktree_path: None,
1155                branch: None,
1156                base_ref: None,
1157                cleanup: None,
1158            },
1159        ));
1160
1161        let mut tool_annotations = BTreeMap::new();
1162        tool_annotations.insert(
1163            "read_file".to_string(),
1164            ToolAnnotations {
1165                kind: ToolKind::Read,
1166                arg_schema: ToolArgSchema {
1167                    path_params: vec!["path".to_string()],
1168                    ..Default::default()
1169                },
1170                ..Default::default()
1171            },
1172        );
1173        push_execution_policy(CapabilityPolicy {
1174            tool_annotations,
1175            ..Default::default()
1176        });
1177
1178        let policy = ToolApprovalPolicy {
1179            write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1180            ..Default::default()
1181        };
1182        let decision = policy.evaluate(
1183            "read_file",
1184            &serde_json::json!({"path": "/packages/demo/context.txt"}),
1185        );
1186        assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1187
1188        pop_execution_policy();
1189        crate::stdlib::process::set_thread_execution_context(None);
1190    }
1191
1192    #[test]
1193    fn builtin_policy_covers_fs_read_and_list_helpers() {
1194        clear_execution_policy_stacks();
1195        push_execution_policy(CapabilityPolicy {
1196            capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1197            side_effect_level: Some("read_only".to_string()),
1198            ..CapabilityPolicy::default()
1199        });
1200
1201        for name in [
1202            "read_lines",
1203            "find_text",
1204            "walk_dir",
1205            "glob",
1206            "project_context_profile_native",
1207        ] {
1208            assert!(
1209                enforce_current_policy_for_builtin(name, &[]).is_err(),
1210                "{name} should be rejected when the matching workspace capability is absent"
1211            );
1212        }
1213
1214        pop_execution_policy();
1215    }
1216
1217    #[test]
1218    fn move_file_requires_workspace_write_side_effect() {
1219        clear_execution_policy_stacks();
1220        push_execution_policy(CapabilityPolicy {
1221            capabilities: BTreeMap::from([(
1222                "workspace".to_string(),
1223                vec!["write_text".to_string()],
1224            )]),
1225            side_effect_level: Some("read_only".to_string()),
1226            ..CapabilityPolicy::default()
1227        });
1228
1229        let error = enforce_current_policy_for_builtin("move_file", &[]).unwrap_err();
1230        assert!(
1231            error.to_string().contains("workspace write ceiling"),
1232            "unexpected error: {error}"
1233        );
1234
1235        pop_execution_policy();
1236    }
1237
1238    #[test]
1239    fn unix_socket_json_request_requires_network_side_effect() {
1240        clear_execution_policy_stacks();
1241        push_execution_policy(CapabilityPolicy {
1242            side_effect_level: Some("read_only".to_string()),
1243            ..CapabilityPolicy::default()
1244        });
1245
1246        let error =
1247            enforce_current_policy_for_builtin("__net_unix_socket_json_request", &[]).unwrap_err();
1248        assert!(
1249            error.to_string().contains("network ceiling"),
1250            "unexpected error: {error}"
1251        );
1252
1253        pop_execution_policy();
1254    }
1255
1256    #[test]
1257    fn files_upload_requires_workspace_read_and_network_side_effect() {
1258        clear_execution_policy_stacks();
1259        push_execution_policy(CapabilityPolicy {
1260            capabilities: BTreeMap::from([(
1261                "workspace".to_string(),
1262                vec!["read_text".to_string()],
1263            )]),
1264            side_effect_level: Some("read_only".to_string()),
1265            ..CapabilityPolicy::default()
1266        });
1267
1268        let network_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1269        assert!(
1270            network_error.to_string().contains("network ceiling"),
1271            "unexpected error: {network_error}"
1272        );
1273        pop_execution_policy();
1274
1275        push_execution_policy(CapabilityPolicy {
1276            capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1277            side_effect_level: Some("network".to_string()),
1278            ..CapabilityPolicy::default()
1279        });
1280        let read_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1281        assert!(
1282            read_error.to_string().contains("workspace.read_text"),
1283            "unexpected error: {read_error}"
1284        );
1285
1286        pop_execution_policy();
1287    }
1288}
1289
1290#[cfg(test)]
1291mod turn_policy_tests {
1292    use super::TurnPolicy;
1293
1294    #[test]
1295    fn default_allows_done_sentinel() {
1296        let policy = TurnPolicy::default();
1297        assert!(policy.allow_done_sentinel);
1298        assert!(!policy.require_action_or_yield);
1299        assert!(policy.max_prose_chars.is_none());
1300    }
1301
1302    #[test]
1303    fn deserializing_partial_dict_preserves_done_sentinel_pathway() {
1304        // Pre-existing workflows passed `turn_policy: { require_action_or_yield: true }`
1305        // without knowing about `allow_done_sentinel`. Deserializing such a dict
1306        // must keep the done-sentinel pathway enabled so loop-until-done agents
1307        // don't lose their completion signal.
1308        let policy: TurnPolicy =
1309            serde_json::from_value(serde_json::json!({ "require_action_or_yield": true }))
1310                .expect("deserialize");
1311        assert!(policy.require_action_or_yield);
1312        assert!(policy.allow_done_sentinel);
1313    }
1314
1315    #[test]
1316    fn deserializing_explicit_false_disables_done_sentinel() {
1317        let policy: TurnPolicy = serde_json::from_value(serde_json::json!({
1318            "require_action_or_yield": true,
1319            "allow_done_sentinel": false,
1320        }))
1321        .expect("deserialize");
1322        assert!(policy.require_action_or_yield);
1323        assert!(!policy.allow_done_sentinel);
1324    }
1325}
1326
1327#[cfg(test)]
1328mod visibility_redaction_tests {
1329    use super::*;
1330    use crate::value::VmValue;
1331
1332    fn mock_transcript() -> VmValue {
1333        let messages = vec![
1334            serde_json::json!({"role": "user", "content": "hi"}),
1335            serde_json::json!({"role": "assistant", "content": "hello"}),
1336            serde_json::json!({"role": "tool_result", "content": "internal tool output"}),
1337        ];
1338        crate::llm::helpers::transcript_to_vm_with_events(
1339            Some("test-id".to_string()),
1340            None,
1341            None,
1342            &messages,
1343            Vec::new(),
1344            Vec::new(),
1345            Some("active"),
1346        )
1347    }
1348
1349    fn message_count(transcript: &VmValue) -> usize {
1350        transcript
1351            .as_dict()
1352            .and_then(|d| d.get("messages"))
1353            .and_then(|v| match v {
1354                VmValue::List(list) => Some(list.len()),
1355                _ => None,
1356            })
1357            .unwrap_or(0)
1358    }
1359
1360    #[test]
1361    fn visibility_none_returns_unchanged() {
1362        let t = mock_transcript();
1363        let result = redact_transcript_visibility(&t, None).unwrap();
1364        assert_eq!(message_count(&result), 3);
1365    }
1366
1367    #[test]
1368    fn visibility_public_drops_tool_results() {
1369        let t = mock_transcript();
1370        let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1371        assert_eq!(message_count(&result), 2);
1372    }
1373
1374    #[test]
1375    fn visibility_public_drops_private_content_blocks() {
1376        let t = crate::schema::json_to_vm_value(&serde_json::json!({
1377            "messages": [
1378                {
1379                    "role": "assistant",
1380                    "visibility": "public",
1381                    "text": "visible answer\nsecret chain",
1382                    "content": [
1383                        {"type": "output_text", "text": "visible answer", "visibility": "public"},
1384                        {"type": "reasoning", "text": "secret chain", "visibility": "private"}
1385                    ],
1386                    "blocks": [
1387                        {"type": "output_text", "text": "visible block", "visibility": "public"},
1388                        {"type": "tool_call", "text": "internal args", "visibility": "internal"}
1389                    ]
1390                }
1391            ],
1392            "events": []
1393        }));
1394
1395        let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1396        let rendered = result.display();
1397        assert!(rendered.contains("visible answer"));
1398        assert!(rendered.contains("visible block"));
1399        assert!(!rendered.contains("secret chain"));
1400        assert!(!rendered.contains("internal args"));
1401    }
1402
1403    #[test]
1404    fn visibility_unknown_string_is_pass_through() {
1405        let t = mock_transcript();
1406        let result = redact_transcript_visibility(&t, Some("internal")).unwrap();
1407        assert_eq!(message_count(&result), 3);
1408    }
1409}