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