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        | "render"
326        | "render_prompt"
327        | "render_with_provenance"
328        | "read_lines"
329            if !policy_allows_capability(&policy, "workspace", "read_text") =>
330        {
331            return reject_policy(format!(
332                "builtin '{name}' exceeds workspace.read_text ceiling"
333            ));
334        }
335        "list_dir" | "walk_dir" | "glob"
336            if !policy_allows_capability(&policy, "workspace", "list") =>
337        {
338            return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
339        }
340        "file_exists" | "path_status" | "stat"
341            if !policy_allows_capability(&policy, "workspace", "exists") =>
342        {
343            return reject_policy(format!("builtin '{name}' exceeds workspace.exists ceiling"));
344        }
345        "write_file" | "write_file_bytes" | "append_file" | "mkdir" | "copy_file" | "move_file"
346            if !policy_allows_capability(&policy, "workspace", "write_text")
347                || !policy_allows_side_effect(&policy, "workspace_write") =>
348        {
349            return reject_policy(format!("builtin '{name}' exceeds workspace write ceiling"));
350        }
351        "delete_file"
352            if !policy_allows_capability(&policy, "workspace", "delete")
353                || !policy_allows_side_effect(&policy, "workspace_write") =>
354        {
355            return reject_policy(
356                "builtin 'delete_file' exceeds workspace.delete ceiling".to_string(),
357            );
358        }
359        "apply_edit"
360            if !policy_allows_capability(&policy, "workspace", "apply_edit")
361                || !policy_allows_side_effect(&policy, "workspace_write") =>
362        {
363            return reject_policy(
364                "builtin 'apply_edit' exceeds workspace.apply_edit ceiling".to_string(),
365            );
366        }
367        "exec"
368        | "exec_at"
369        | "shell"
370        | "shell_at"
371        | "git.repo.discover"
372        | "git.worktree.create"
373        | "git.worktree.remove"
374        | "git.fetch"
375        | "git.rebase"
376        | "git.status"
377        | "git.conflicts"
378        | "git.push"
379        | "git.diff"
380        | "git.merge_base"
381            if !policy_allows_capability(&policy, "process", "exec")
382                || !policy_allows_side_effect(&policy, "process_exec") =>
383        {
384            return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
385        }
386        // `__files_upload` needs a stricter workspace.read_text + network
387        // ceiling, so it stays a distinct arm ahead of the shared network arm
388        // below (its name never overlaps the network patterns, so ordering is
389        // immaterial to correctness).
390        "__files_upload"
391            if !policy_allows_capability(&policy, "workspace", "read_text")
392                || !policy_allows_side_effect(&policy, "network") =>
393        {
394            return reject_policy(
395                "builtin '__files_upload' exceeds workspace.read_text/network ceiling".to_string(),
396            );
397        }
398        "http_get"
399        | "http_post"
400        | "http_put"
401        | "http_patch"
402        | "http_delete"
403        | "http_download"
404        | "http_request"
405        | "unix_socket_json_request"
406        | "__net_unix_socket_json_request"
407        | "http_session_request"
408        | "http_stream_open"
409        | "http_stream_read"
410        | "http_stream_close"
411        | "http_stream_info"
412        | "sse_connect"
413        | "sse_receive"
414        | "websocket_accept"
415        | "websocket_connect"
416        | "websocket_route"
417        | "websocket_send"
418        | "websocket_receive"
419        | "websocket_server"
420            if !policy_allows_side_effect(&policy, "network") =>
421        {
422            return reject_policy(format!("builtin '{name}' exceeds network ceiling"));
423        }
424        "llm_call" | "llm_call_safe" | "llm_completion" | "llm_stream" | "llm_stream_call"
425        | "llm_healthcheck" | "agent_loop"
426            if !policy_allows_capability(&policy, "llm", "call") =>
427        {
428            return reject_policy(format!("builtin '{name}' exceeds llm.call ceiling"));
429        }
430        "connector_call"
431            if !policy_allows_capability(&policy, "connector", "call")
432                || !policy_allows_side_effect(&policy, "network") =>
433        {
434            return reject_policy(
435                "builtin 'connector_call' exceeds connector.call/network ceiling".to_string(),
436            );
437        }
438        "secret_get" if !policy_allows_capability(&policy, "connector", "secret_get") => {
439            return reject_policy(
440                "builtin 'secret_get' exceeds connector.secret_get ceiling".to_string(),
441            );
442        }
443        "event_log_emit" if !policy_allows_capability(&policy, "connector", "event_log_emit") => {
444            return reject_policy(
445                "builtin 'event_log_emit' exceeds connector.event_log_emit ceiling".to_string(),
446            );
447        }
448        "metrics_inc" if !policy_allows_capability(&policy, "connector", "metrics_inc") => {
449            return reject_policy(
450                "builtin 'metrics_inc' exceeds connector.metrics_inc ceiling".to_string(),
451            );
452        }
453        "project_fingerprint"
454        | "project_context_profile_native"
455        | "project_scan_native"
456        | "project_scan_tree_native"
457        | "project_walk_tree_native"
458        | "project_catalog_native"
459            if !policy_allows_capability(&policy, "workspace", "list")
460                || !policy_allows_side_effect(&policy, "read_only") =>
461        {
462            return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
463        }
464        "__agent_state_init"
465        | "__agent_state_resume"
466        | "__agent_state_write"
467        | "__agent_state_read"
468        | "__agent_state_list"
469        | "__agent_state_delete"
470        | "__agent_state_handoff"
471            if !policy_allows_capability(&policy, "agent_state", "access") =>
472        {
473            return reject_policy(format!(
474                "builtin '{name}' exceeds agent_state.access ceiling"
475            ));
476        }
477        "vision_ocr"
478            if !policy_allows_capability(&policy, "vision", "ocr")
479                || !policy_allows_side_effect(&policy, "process_exec") =>
480        {
481            return reject_policy(format!(
482                "builtin '{name}' exceeds vision.ocr/process ceiling"
483            ));
484        }
485        "mcp_connect"
486        | "mcp_ensure_active"
487        | "mcp_call"
488        | "mcp_list_tools"
489        | "mcp_list_resources"
490        | "mcp_list_resource_templates"
491        | "mcp_read_resource"
492        | "mcp_list_prompts"
493        | "mcp_get_prompt"
494        | "mcp_server_info"
495        | "mcp_disconnect"
496            if !policy_allows_capability(&policy, "process", "exec")
497                || !policy_allows_side_effect(&policy, "process_exec") =>
498        {
499            return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
500        }
501        "host_call" => {
502            let name = args.first().map(|v| v.display()).unwrap_or_default();
503            let Some((capability, op)) = name.split_once('.') else {
504                return reject_policy(format!(
505                    "host_call '{name}' must use capability.operation naming"
506                ));
507            };
508            if !policy_allows_capability(&policy, capability, op) {
509                return reject_policy(format!(
510                    "host_call {capability}.{op} exceeds capability ceiling"
511                ));
512            }
513            let requested_side_effect = match (capability, op) {
514                ("workspace", "write_text" | "apply_edit" | "delete") => "workspace_write",
515                ("process", "exec") => "process_exec",
516                _ => "read_only",
517            };
518            if !policy_allows_side_effect(&policy, requested_side_effect) {
519                return reject_policy(format!(
520                    "host_call {capability}.{op} exceeds side-effect ceiling"
521                ));
522            }
523        }
524        "host_tool_list" | "host_tool_call"
525            if !policy_allows_capability(&policy, "host", "tool_call") =>
526        {
527            return reject_policy(format!("builtin '{name}' exceeds host.tool_call ceiling"));
528        }
529        _ => {}
530    }
531    Ok(())
532}
533
534pub fn enforce_current_policy_for_bridge_builtin(name: &str) -> Result<(), VmError> {
535    let trusted = TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow() > 0);
536    if trusted {
537        return Ok(());
538    }
539    if current_execution_policy().is_some() {
540        return reject_policy(format!(
541            "bridged builtin '{name}' exceeds execution policy; declare an explicit capability/tool surface instead"
542        ));
543    }
544    Ok(())
545}
546
547pub fn enforce_current_policy_for_tool(tool_name: &str) -> Result<(), PolicyDenial> {
548    use crate::agent_events::DenialGate;
549    let Some(policy) = current_execution_policy() else {
550        return Ok(());
551    };
552    if !policy_allows_tool(&policy, tool_name) {
553        return reject_tool(
554            DenialGate::ToolCeiling,
555            None,
556            format!("tool '{tool_name}' exceeds tool ceiling"),
557        );
558    }
559    if let Some(annotations) = policy.tool_annotations.get(tool_name) {
560        for (capability, ops) in &annotations.capabilities {
561            for op in ops {
562                if !policy_allows_capability(&policy, capability, op) {
563                    return reject_tool(
564                        DenialGate::CapabilityCeiling,
565                        Some(format!("{capability}.{op}")),
566                        format!("tool '{tool_name}' exceeds capability ceiling: {capability}.{op}"),
567                    );
568                }
569            }
570        }
571        let requested_level = annotations.side_effect_level;
572        if requested_level != SideEffectLevel::None
573            && !policy_allows_side_effect(&policy, requested_level.as_str())
574        {
575            return reject_tool(
576                DenialGate::SideEffectCeiling,
577                None,
578                format!(
579                    "tool '{tool_name}' exceeds side-effect ceiling: {}",
580                    requested_level.as_str()
581                ),
582            );
583        }
584    }
585    Ok(())
586}
587
588// ── Output visibility redaction ─────────────────────────────────────
589//
590// Transcript lifecycle (reset, fork, trim, compact) now lives on
591// `crate::agent_sessions` as explicit imperative builtins. All that
592// remains here is the per-call visibility filter, which is
593// output-shaping (not lifecycle).
594
595/// Filter a transcript dict down to the caller-visible subset, based
596/// on the `output_visibility` node option. `None` or any unknown
597/// visibility returns the transcript unchanged — callers are expected
598/// to validate the string against a known set upstream.
599pub fn redact_transcript_visibility(
600    transcript: &VmValue,
601    visibility: Option<&str>,
602) -> Option<VmValue> {
603    let Some(visibility) = visibility else {
604        return Some(transcript.clone());
605    };
606    if visibility != "public" && visibility != "public_only" {
607        return Some(transcript.clone());
608    }
609    let dict = transcript.as_dict()?;
610    let public_messages = match dict.get("messages") {
611        Some(VmValue::List(list)) => list
612            .iter()
613            .filter_map(redact_public_message)
614            .collect::<Vec<_>>(),
615        _ => Vec::new(),
616    };
617    let public_events = match dict.get("events") {
618        Some(VmValue::List(list)) => list
619            .iter()
620            .filter(|event| {
621                event
622                    .as_dict()
623                    .and_then(|d| d.get("visibility"))
624                    .map(|v| v.display())
625                    .map(|value| value == "public")
626                    .unwrap_or(true)
627            })
628            .cloned()
629            .collect::<Vec<_>>(),
630        _ => Vec::new(),
631    };
632    let mut redacted = dict.clone();
633    redacted.insert(
634        crate::value::intern_key("messages"),
635        VmValue::List(std::sync::Arc::new(public_messages)),
636    );
637    redacted.insert(
638        crate::value::intern_key("events"),
639        VmValue::List(std::sync::Arc::new(public_events)),
640    );
641    Some(VmValue::dict(redacted))
642}
643
644fn redact_public_message(message: &VmValue) -> Option<VmValue> {
645    let Some(dict) = message.as_dict() else {
646        return Some(message.clone());
647    };
648    if dict.get("role").map(|value| value.display()).as_deref() == Some("tool_result") {
649        return None;
650    }
651    if dict
652        .get("visibility")
653        .map(|value| value.display())
654        .is_some_and(|visibility| visibility != "public")
655    {
656        return None;
657    }
658
659    let mut redacted = dict.clone();
660    let mut saw_structured_blocks = false;
661    let mut public_text = Vec::new();
662    for key in ["content", "blocks"] {
663        if let Some(VmValue::List(blocks)) = dict.get(key) {
664            saw_structured_blocks = true;
665            let public_blocks = blocks
666                .iter()
667                .filter_map(redact_public_block)
668                .collect::<Vec<_>>();
669            if key == "blocks" || public_text.is_empty() {
670                public_text = text_fragments_from_blocks(&public_blocks);
671            }
672            redacted.insert(
673                crate::value::intern_key(key),
674                VmValue::List(std::sync::Arc::new(public_blocks)),
675            );
676        }
677    }
678    if saw_structured_blocks {
679        if public_text.is_empty() {
680            redacted.remove("text");
681        } else {
682            redacted.put_str("text", public_text.join("\n"));
683        }
684    }
685    Some(VmValue::dict(redacted))
686}
687
688fn redact_public_block(block: &VmValue) -> Option<VmValue> {
689    let Some(dict) = block.as_dict() else {
690        return Some(block.clone());
691    };
692    if dict
693        .get("visibility")
694        .map(|value| value.display())
695        .is_some_and(|visibility| visibility != "public")
696    {
697        return None;
698    }
699    Some(block.clone())
700}
701
702fn text_fragments_from_blocks(blocks: &[VmValue]) -> Vec<String> {
703    blocks
704        .iter()
705        .filter_map(|block| block.as_dict())
706        .filter_map(|dict| dict.get("text"))
707        .filter_map(|text| match text {
708            VmValue::String(value) if !value.is_empty() => Some(value.to_string()),
709            _ => None,
710        })
711        .collect()
712}
713
714pub fn builtin_ceiling() -> CapabilityPolicy {
715    CapabilityPolicy {
716        // `capabilities` is intentionally empty: the host capability manifest
717        // is the sole authority, and an allowlist here would silently block
718        // any capability the host adds later.
719        tools: Vec::new(),
720        capabilities: BTreeMap::new(),
721        workspace_roots: Vec::new(),
722        read_only_roots: Vec::new(),
723        // The builtin ceiling is the runtime's OUTERMOST bound — the top of the
724        // side-effect ladder. Every real policy intersects DOWN from here, so this
725        // must be the maximum level or it would silently cap more-invasive tools
726        // out entirely. It tracks the top of the ladder: `desktop_control`. This
727        // does not loosen anything — a normal agent's surface policy still caps at
728        // the max of ITS tools (e.g. `network`); only a surface that actually
729        // carries a `desktop_control` tool (computer use, gated by the off-by-
730        // default flag) can reach the top.
731        // Tracks the ladder top via `SideEffectLevel::MAX` (never a hardcoded level).
732        side_effect_level: Some(SideEffectLevel::MAX.as_str().to_string()),
733        recursion_limit: Some(RuntimeLimits::DEFAULT.max_nested_execution_depth),
734        tool_arg_constraints: Vec::new(),
735        tool_annotations: BTreeMap::new(),
736        sandbox_profile: SandboxProfile::Worktree,
737        process_sandbox: Default::default(),
738    }
739}
740
741/// Declarative policy for tool approval gating. Allows pipelines to
742/// specify which tools are auto-approved, auto-denied, or require
743/// host confirmation, plus write-path allowlists.
744#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
745#[serde(default)]
746pub struct ToolApprovalPolicy {
747    /// Ordered allow/ask/deny rules over tool metadata, path, command,
748    /// URL, MCP, agent/persona/mode, and repeat-count dimensions.
749    #[serde(default)]
750    pub rules: Vec<PolicyRule>,
751    /// Glob patterns for tools that should be auto-approved.
752    #[serde(default)]
753    pub auto_approve: Vec<String>,
754    /// Glob patterns for tools that should always be denied.
755    #[serde(default)]
756    pub auto_deny: Vec<String>,
757    /// Glob patterns for tools that require host confirmation.
758    #[serde(default)]
759    pub require_approval: Vec<String>,
760    /// Glob patterns for writable paths.
761    #[serde(default)]
762    pub write_path_allowlist: Vec<String>,
763    /// Explicit opt-out for the deny-by-default sensitive-path guard.
764    #[serde(default)]
765    pub allow_sensitive_paths: bool,
766    /// Additional or replacement sensitive path globs. Empty uses the
767    /// runtime defaults such as `.env`, private keys, and credential files.
768    #[serde(default)]
769    pub sensitive_path_patterns: Vec<String>,
770    /// Explicit opt-out for the external-path guard on declared path args.
771    #[serde(default)]
772    pub allow_external_paths: bool,
773    /// Host-absolute roots allowed when `allow_external_paths` is false.
774    #[serde(default)]
775    pub external_roots: Vec<String>,
776    /// Optional repeated-call threshold for the same `(session, tool, args)`.
777    #[serde(default, alias = "repeated_call_limit")]
778    pub repeat_limit: Option<u64>,
779    /// Action for `repeat_limit`; defaults to `ask`.
780    #[serde(default, alias = "repeated_call_action")]
781    pub repeat_action: Option<PolicyAction>,
782}
783
784/// Result of evaluating a tool call against a ToolApprovalPolicy.
785#[derive(Debug, Clone, PartialEq, Eq)]
786pub enum ToolApprovalDecision {
787    /// Tool is auto-approved by policy.
788    AutoApproved,
789    /// Tool is auto-denied by policy.
790    AutoDenied { reason: String },
791    /// Tool requires explicit host approval; the caller already owns the
792    /// tool name and args and forwards them to the host bridge.
793    RequiresHostApproval,
794}
795
796impl ToolApprovalPolicy {
797    pub fn evaluate_detailed(&self, tool_name: &str, args: &serde_json::Value) -> PolicyEvaluation {
798        approval_rules::evaluate_tool_approval_policy(self, tool_name, args, None)
799    }
800
801    pub fn evaluate_detailed_with_repeat(
802        &self,
803        tool_name: &str,
804        args: &serde_json::Value,
805        repeat_count: u64,
806    ) -> PolicyEvaluation {
807        approval_rules::evaluate_tool_approval_policy(self, tool_name, args, Some(repeat_count))
808    }
809
810    /// Evaluate whether a tool call should be approved, denied, or needs
811    /// host confirmation.
812    pub fn evaluate(&self, tool_name: &str, args: &serde_json::Value) -> ToolApprovalDecision {
813        let decision = self.evaluate_detailed(tool_name, args);
814        if decision.is_deny() {
815            return ToolApprovalDecision::AutoDenied {
816                reason: decision.reason,
817            };
818        }
819        if decision.is_ask() {
820            return ToolApprovalDecision::RequiresHostApproval;
821        }
822        ToolApprovalDecision::AutoApproved
823    }
824
825    /// Merge two approval policies, taking the most restrictive combination.
826    /// - auto_approve: only tools approved by BOTH policies stay approved
827    ///   (if either policy has no patterns, the other's patterns are used)
828    /// - auto_deny / require_approval: union (either policy can deny/gate)
829    /// - write_path_allowlist: intersection (both must allow the path)
830    pub fn intersect(&self, other: &ToolApprovalPolicy) -> ToolApprovalPolicy {
831        let auto_approve = if self.auto_approve.is_empty() {
832            other.auto_approve.clone()
833        } else if other.auto_approve.is_empty() {
834            self.auto_approve.clone()
835        } else {
836            self.auto_approve
837                .iter()
838                .filter(|p| other.auto_approve.contains(p))
839                .cloned()
840                .collect()
841        };
842        let mut auto_deny = self.auto_deny.clone();
843        auto_deny.extend(other.auto_deny.iter().cloned());
844        let mut require_approval = self.require_approval.clone();
845        require_approval.extend(other.require_approval.iter().cloned());
846        let write_path_allowlist = if self.write_path_allowlist.is_empty() {
847            other.write_path_allowlist.clone()
848        } else if other.write_path_allowlist.is_empty() {
849            self.write_path_allowlist.clone()
850        } else {
851            self.write_path_allowlist
852                .iter()
853                .filter(|p| other.write_path_allowlist.contains(p))
854                .cloned()
855                .collect()
856        };
857        let mut rules = self.rules.clone();
858        rules.extend(other.rules.iter().cloned());
859        let mut sensitive_path_patterns = self.sensitive_path_patterns.clone();
860        sensitive_path_patterns.extend(other.sensitive_path_patterns.iter().cloned());
861        sensitive_path_patterns.sort();
862        sensitive_path_patterns.dedup();
863        let external_roots = if self.external_roots.is_empty() {
864            other.external_roots.clone()
865        } else if other.external_roots.is_empty() {
866            self.external_roots.clone()
867        } else {
868            self.external_roots
869                .iter()
870                .filter(|root| other.external_roots.contains(root))
871                .cloned()
872                .collect()
873        };
874        ToolApprovalPolicy {
875            rules,
876            auto_approve,
877            auto_deny,
878            require_approval,
879            write_path_allowlist,
880            allow_sensitive_paths: self.allow_sensitive_paths && other.allow_sensitive_paths,
881            sensitive_path_patterns,
882            allow_external_paths: self.allow_external_paths && other.allow_external_paths,
883            external_roots,
884            repeat_limit: match (self.repeat_limit, other.repeat_limit) {
885                (Some(left), Some(right)) => Some(left.min(right)),
886                (Some(left), None) => Some(left),
887                (None, Some(right)) => Some(right),
888                (None, None) => None,
889            },
890            repeat_action: match (self.repeat_action, other.repeat_action) {
891                (Some(PolicyAction::Deny), _) | (_, Some(PolicyAction::Deny)) => {
892                    Some(PolicyAction::Deny)
893                }
894                (Some(PolicyAction::Ask), _) | (_, Some(PolicyAction::Ask)) => {
895                    Some(PolicyAction::Ask)
896                }
897                (Some(PolicyAction::Allow), Some(PolicyAction::Allow)) => Some(PolicyAction::Allow),
898                (Some(action), None) | (None, Some(action)) => Some(action),
899                (None, None) => None,
900            },
901        }
902    }
903}
904
905#[cfg(test)]
906mod approval_policy_tests {
907    use super::*;
908    use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
909    use crate::tool_annotations::{ToolAnnotations, ToolArgSchema, ToolKind};
910
911    fn workspace_caps(ops: &[&str]) -> CapabilityPolicy {
912        CapabilityPolicy {
913            capabilities: std::collections::BTreeMap::from([(
914                "workspace".to_string(),
915                ops.iter().map(|s| s.to_string()).collect(),
916            )]),
917            ..Default::default()
918        }
919    }
920
921    #[test]
922    fn builtin_ceiling_permits_desktop_control_but_a_lower_ceiling_denies_it() {
923        // The runtime's outer bound must admit the most-invasive level, or a
924        // desktop-control (computer-use) tool would be exposed-but-denied under
925        // the default ceiling.
926        let builtin = builtin_ceiling();
927        assert!(policy_allows_side_effect(
928            &builtin,
929            SideEffectLevel::DesktopControl.as_str()
930        ));
931
932        // A narrower policy (e.g. a normal agent whose tools top out at network)
933        // still denies a desktop-control tool — the level is a real gate, not a
934        // no-op.
935        let network_ceiling = CapabilityPolicy {
936            side_effect_level: Some(SideEffectLevel::Network.as_str().to_string()),
937            ..Default::default()
938        };
939        assert!(!policy_allows_side_effect(
940            &network_ceiling,
941            SideEffectLevel::DesktopControl.as_str()
942        ));
943        // ...but that same network ceiling still admits everything at or below it.
944        assert!(policy_allows_side_effect(
945            &network_ceiling,
946            SideEffectLevel::ProcessExec.as_str()
947        ));
948    }
949
950    #[test]
951    fn read_text_subsumes_exists_probe() {
952        // A narrowed worker policy that grants read_text/list (the shape derived
953        // from look/edit/scaffold tool annotations) but never declares the
954        // weaker `workspace.exists` op must still permit `file_exists`,
955        // `path_status`, and `stat`:
956        // existence is strictly less information than reading the file. Without
957        // subsumption this silently wedged every parallel sub-agent (look denied
958        // -> zero progress -> zero edits).
959        push_execution_policy(workspace_caps(&[
960            "read_text",
961            "list",
962            "write_text",
963            "apply_edit",
964        ]));
965        assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
966        assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
967        assert!(enforce_current_policy_for_builtin("stat", &[]).is_ok());
968        pop_execution_policy();
969    }
970
971    #[test]
972    fn list_alone_subsumes_exists_probe() {
973        // Listing a directory already reveals which entries exist.
974        push_execution_policy(workspace_caps(&["list"]));
975        assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
976        assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
977        pop_execution_policy();
978    }
979
980    #[test]
981    fn exists_probe_rejected_without_any_read_grant() {
982        // A write-only grant exposes no read surface, so the existence probe is
983        // genuinely above the ceiling and must still be rejected.
984        push_execution_policy(workspace_caps(&["write_text", "apply_edit"]));
985        assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_err());
986        assert!(enforce_current_policy_for_builtin("path_status", &[]).is_err());
987        pop_execution_policy();
988    }
989
990    #[test]
991    fn auto_deny_takes_precedence_over_auto_approve() {
992        let policy = ToolApprovalPolicy {
993            auto_approve: vec!["*".to_string()],
994            auto_deny: vec!["dangerous_*".to_string()],
995            ..Default::default()
996        };
997        assert_eq!(
998            policy.evaluate("dangerous_rm", &serde_json::json!({})),
999            ToolApprovalDecision::AutoDenied {
1000                reason: "tool 'dangerous_rm' matches deny pattern 'dangerous_*'".to_string()
1001            }
1002        );
1003    }
1004
1005    #[test]
1006    fn auto_approve_matches_glob() {
1007        let policy = ToolApprovalPolicy {
1008            auto_approve: vec!["read*".to_string(), "search*".to_string()],
1009            ..Default::default()
1010        };
1011        assert_eq!(
1012            policy.evaluate("read_file", &serde_json::json!({})),
1013            ToolApprovalDecision::AutoApproved
1014        );
1015        assert_eq!(
1016            policy.evaluate("search", &serde_json::json!({})),
1017            ToolApprovalDecision::AutoApproved
1018        );
1019    }
1020
1021    #[test]
1022    fn require_approval_emits_decision() {
1023        let policy = ToolApprovalPolicy {
1024            require_approval: vec!["edit*".to_string()],
1025            ..Default::default()
1026        };
1027        let decision = policy.evaluate("edit_file", &serde_json::json!({"path": "foo.rs"}));
1028        assert!(matches!(
1029            decision,
1030            ToolApprovalDecision::RequiresHostApproval
1031        ));
1032    }
1033
1034    #[test]
1035    fn unmatched_tool_defaults_to_approved() {
1036        let policy = ToolApprovalPolicy {
1037            auto_approve: vec!["read*".to_string()],
1038            require_approval: vec!["edit*".to_string()],
1039            ..Default::default()
1040        };
1041        assert_eq!(
1042            policy.evaluate("unknown_tool", &serde_json::json!({})),
1043            ToolApprovalDecision::AutoApproved
1044        );
1045    }
1046
1047    #[test]
1048    fn intersect_merges_deny_lists() {
1049        let a = ToolApprovalPolicy {
1050            auto_deny: vec!["rm*".to_string()],
1051            ..Default::default()
1052        };
1053        let b = ToolApprovalPolicy {
1054            auto_deny: vec!["drop*".to_string()],
1055            ..Default::default()
1056        };
1057        let merged = a.intersect(&b);
1058        assert_eq!(merged.auto_deny.len(), 2);
1059    }
1060
1061    #[test]
1062    fn intersect_restricts_auto_approve_to_common_patterns() {
1063        let a = ToolApprovalPolicy {
1064            auto_approve: vec!["read*".to_string(), "search*".to_string()],
1065            ..Default::default()
1066        };
1067        let b = ToolApprovalPolicy {
1068            auto_approve: vec!["read*".to_string(), "write*".to_string()],
1069            ..Default::default()
1070        };
1071        let merged = a.intersect(&b);
1072        assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1073    }
1074
1075    #[test]
1076    fn intersect_defers_auto_approve_when_one_side_empty() {
1077        let a = ToolApprovalPolicy {
1078            auto_approve: vec!["read*".to_string()],
1079            ..Default::default()
1080        };
1081        let b = ToolApprovalPolicy::default();
1082        let merged = a.intersect(&b);
1083        assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1084    }
1085
1086    #[test]
1087    fn write_path_allowlist_matches_recovered_workspace_relative_path() {
1088        let temp = tempfile::tempdir().unwrap();
1089        std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1090        std::fs::write(temp.path().join("packages/demo/file.txt"), "ok").unwrap();
1091        crate::stdlib::process::set_thread_execution_context(Some(
1092            crate::orchestration::RunExecutionRecord {
1093                cwd: Some(temp.path().to_string_lossy().into_owned()),
1094                source_dir: Some(temp.path().to_string_lossy().into_owned()),
1095                env: BTreeMap::new(),
1096                adapter: None,
1097                repo_path: None,
1098                worktree_path: None,
1099                branch: None,
1100                base_ref: None,
1101                cleanup: None,
1102            },
1103        ));
1104
1105        let mut tool_annotations = BTreeMap::new();
1106        tool_annotations.insert(
1107            "write_file".to_string(),
1108            ToolAnnotations {
1109                kind: ToolKind::Edit,
1110                arg_schema: ToolArgSchema {
1111                    path_params: vec!["path".to_string()],
1112                    ..Default::default()
1113                },
1114                ..Default::default()
1115            },
1116        );
1117        push_execution_policy(CapabilityPolicy {
1118            tool_annotations,
1119            ..Default::default()
1120        });
1121
1122        let policy = ToolApprovalPolicy {
1123            write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1124            ..Default::default()
1125        };
1126        let decision = policy.evaluate(
1127            "write_file",
1128            &serde_json::json!({"path": "/packages/demo/file.txt"}),
1129        );
1130        assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1131
1132        pop_execution_policy();
1133        crate::stdlib::process::set_thread_execution_context(None);
1134    }
1135
1136    #[test]
1137    fn write_path_allowlist_does_not_block_read_only_tools() {
1138        let temp = tempfile::tempdir().unwrap();
1139        std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1140        std::fs::write(temp.path().join("packages/demo/context.txt"), "ok").unwrap();
1141        crate::stdlib::process::set_thread_execution_context(Some(
1142            crate::orchestration::RunExecutionRecord {
1143                cwd: Some(temp.path().to_string_lossy().into_owned()),
1144                source_dir: Some(temp.path().to_string_lossy().into_owned()),
1145                env: BTreeMap::new(),
1146                adapter: None,
1147                repo_path: None,
1148                worktree_path: None,
1149                branch: None,
1150                base_ref: None,
1151                cleanup: None,
1152            },
1153        ));
1154
1155        let mut tool_annotations = BTreeMap::new();
1156        tool_annotations.insert(
1157            "read_file".to_string(),
1158            ToolAnnotations {
1159                kind: ToolKind::Read,
1160                arg_schema: ToolArgSchema {
1161                    path_params: vec!["path".to_string()],
1162                    ..Default::default()
1163                },
1164                ..Default::default()
1165            },
1166        );
1167        push_execution_policy(CapabilityPolicy {
1168            tool_annotations,
1169            ..Default::default()
1170        });
1171
1172        let policy = ToolApprovalPolicy {
1173            write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1174            ..Default::default()
1175        };
1176        let decision = policy.evaluate(
1177            "read_file",
1178            &serde_json::json!({"path": "/packages/demo/context.txt"}),
1179        );
1180        assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1181
1182        pop_execution_policy();
1183        crate::stdlib::process::set_thread_execution_context(None);
1184    }
1185
1186    #[test]
1187    fn builtin_policy_covers_fs_read_and_list_helpers() {
1188        clear_execution_policy_stacks();
1189        push_execution_policy(CapabilityPolicy {
1190            capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1191            side_effect_level: Some("read_only".to_string()),
1192            ..CapabilityPolicy::default()
1193        });
1194
1195        for name in [
1196            "read_lines",
1197            "find_text",
1198            "walk_dir",
1199            "glob",
1200            "project_context_profile_native",
1201        ] {
1202            assert!(
1203                enforce_current_policy_for_builtin(name, &[]).is_err(),
1204                "{name} should be rejected when the matching workspace capability is absent"
1205            );
1206        }
1207
1208        pop_execution_policy();
1209    }
1210
1211    #[test]
1212    fn move_file_requires_workspace_write_side_effect() {
1213        clear_execution_policy_stacks();
1214        push_execution_policy(CapabilityPolicy {
1215            capabilities: BTreeMap::from([(
1216                "workspace".to_string(),
1217                vec!["write_text".to_string()],
1218            )]),
1219            side_effect_level: Some("read_only".to_string()),
1220            ..CapabilityPolicy::default()
1221        });
1222
1223        let error = enforce_current_policy_for_builtin("move_file", &[]).unwrap_err();
1224        assert!(
1225            error.to_string().contains("workspace write ceiling"),
1226            "unexpected error: {error}"
1227        );
1228
1229        pop_execution_policy();
1230    }
1231
1232    #[test]
1233    fn unix_socket_json_request_requires_network_side_effect() {
1234        clear_execution_policy_stacks();
1235        push_execution_policy(CapabilityPolicy {
1236            side_effect_level: Some("read_only".to_string()),
1237            ..CapabilityPolicy::default()
1238        });
1239
1240        let error =
1241            enforce_current_policy_for_builtin("__net_unix_socket_json_request", &[]).unwrap_err();
1242        assert!(
1243            error.to_string().contains("network ceiling"),
1244            "unexpected error: {error}"
1245        );
1246
1247        pop_execution_policy();
1248    }
1249
1250    #[test]
1251    fn files_upload_requires_workspace_read_and_network_side_effect() {
1252        clear_execution_policy_stacks();
1253        push_execution_policy(CapabilityPolicy {
1254            capabilities: BTreeMap::from([(
1255                "workspace".to_string(),
1256                vec!["read_text".to_string()],
1257            )]),
1258            side_effect_level: Some("read_only".to_string()),
1259            ..CapabilityPolicy::default()
1260        });
1261
1262        let network_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1263        assert!(
1264            network_error.to_string().contains("network ceiling"),
1265            "unexpected error: {network_error}"
1266        );
1267        pop_execution_policy();
1268
1269        push_execution_policy(CapabilityPolicy {
1270            capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1271            side_effect_level: Some("network".to_string()),
1272            ..CapabilityPolicy::default()
1273        });
1274        let read_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1275        assert!(
1276            read_error.to_string().contains("workspace.read_text"),
1277            "unexpected error: {read_error}"
1278        );
1279
1280        pop_execution_policy();
1281    }
1282}
1283
1284#[cfg(test)]
1285mod turn_policy_tests {
1286    use super::TurnPolicy;
1287
1288    #[test]
1289    fn default_allows_done_sentinel() {
1290        let policy = TurnPolicy::default();
1291        assert!(policy.allow_done_sentinel);
1292        assert!(!policy.require_action_or_yield);
1293        assert!(policy.max_prose_chars.is_none());
1294    }
1295
1296    #[test]
1297    fn deserializing_partial_dict_preserves_done_sentinel_pathway() {
1298        // Pre-existing workflows passed `turn_policy: { require_action_or_yield: true }`
1299        // without knowing about `allow_done_sentinel`. Deserializing such a dict
1300        // must keep the done-sentinel pathway enabled so loop-until-done agents
1301        // don't lose their completion signal.
1302        let policy: TurnPolicy =
1303            serde_json::from_value(serde_json::json!({ "require_action_or_yield": true }))
1304                .expect("deserialize");
1305        assert!(policy.require_action_or_yield);
1306        assert!(policy.allow_done_sentinel);
1307    }
1308
1309    #[test]
1310    fn deserializing_explicit_false_disables_done_sentinel() {
1311        let policy: TurnPolicy = serde_json::from_value(serde_json::json!({
1312            "require_action_or_yield": true,
1313            "allow_done_sentinel": false,
1314        }))
1315        .expect("deserialize");
1316        assert!(policy.require_action_or_yield);
1317        assert!(!policy.allow_done_sentinel);
1318    }
1319}
1320
1321#[cfg(test)]
1322mod visibility_redaction_tests {
1323    use super::*;
1324    use crate::value::VmValue;
1325
1326    fn mock_transcript() -> VmValue {
1327        let messages = vec![
1328            serde_json::json!({"role": "user", "content": "hi"}),
1329            serde_json::json!({"role": "assistant", "content": "hello"}),
1330            serde_json::json!({"role": "tool_result", "content": "internal tool output"}),
1331        ];
1332        crate::llm::helpers::transcript_to_vm_with_events(
1333            Some("test-id".to_string()),
1334            None,
1335            None,
1336            &messages,
1337            Vec::new(),
1338            Vec::new(),
1339            Some("active"),
1340        )
1341    }
1342
1343    fn message_count(transcript: &VmValue) -> usize {
1344        transcript
1345            .as_dict()
1346            .and_then(|d| d.get("messages"))
1347            .and_then(|v| match v {
1348                VmValue::List(list) => Some(list.len()),
1349                _ => None,
1350            })
1351            .unwrap_or(0)
1352    }
1353
1354    #[test]
1355    fn visibility_none_returns_unchanged() {
1356        let t = mock_transcript();
1357        let result = redact_transcript_visibility(&t, None).unwrap();
1358        assert_eq!(message_count(&result), 3);
1359    }
1360
1361    #[test]
1362    fn visibility_public_drops_tool_results() {
1363        let t = mock_transcript();
1364        let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1365        assert_eq!(message_count(&result), 2);
1366    }
1367
1368    #[test]
1369    fn visibility_public_drops_private_content_blocks() {
1370        let t = crate::schema::json_to_vm_value(&serde_json::json!({
1371            "messages": [
1372                {
1373                    "role": "assistant",
1374                    "visibility": "public",
1375                    "text": "visible answer\nsecret chain",
1376                    "content": [
1377                        {"type": "output_text", "text": "visible answer", "visibility": "public"},
1378                        {"type": "reasoning", "text": "secret chain", "visibility": "private"}
1379                    ],
1380                    "blocks": [
1381                        {"type": "output_text", "text": "visible block", "visibility": "public"},
1382                        {"type": "tool_call", "text": "internal args", "visibility": "internal"}
1383                    ]
1384                }
1385            ],
1386            "events": []
1387        }));
1388
1389        let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1390        let rendered = result.display();
1391        assert!(rendered.contains("visible answer"));
1392        assert!(rendered.contains("visible block"));
1393        assert!(!rendered.contains("secret chain"));
1394        assert!(!rendered.contains("internal args"));
1395    }
1396
1397    #[test]
1398    fn visibility_unknown_string_is_pass_through() {
1399        let t = mock_transcript();
1400        let result = redact_transcript_visibility(&t, Some("internal")).unwrap();
1401        assert_eq!(message_count(&result), 3);
1402    }
1403}