Skip to main content

harn_vm/orchestration/policy/
mod.rs

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