Skip to main content

harn_vm/orchestration/policy/
mod.rs

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