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