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