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