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