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