Skip to main content

adk_harness/
policy.rs

1//! `HarnessPolicy`: modes, tool classes and standing rules as one [`ToolPolicy`]
2//! (spec 3.1 §7.4, §7.5, §9.1, §9.2).
3//!
4//! Modes and standing rules are a policy, never a callback: the policy runs on every
5//! path before a call can be held, while a callback that answers a call skips the
6//! governed path (spec 3.1 §6 D-2).
7
8use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
9use std::sync::{Arc, Mutex, Weak};
10
11use adk_core::audit_log::{AuditActor, AuditTrail};
12use adk_core::{
13    ActingContext, BUILTIN_TOOL_ORIGIN, PolicyCall, PolicyDecision, STATIC_TOOL_ORIGIN,
14    ToolConfirmationRequest, ToolEffect, ToolOrigin, ToolPolicy, ToolPolicyRequest, async_trait,
15    tool_call_fingerprint,
16};
17use adk_devtools::Workspace;
18use chrono::Utc;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21
22use crate::approvals::StandingRuleStore;
23use crate::approvals::matcher::{
24    RuleCall, RuleEvaluation, RuleOutcome, evaluate_standing_rules, is_protected_path,
25    is_protected_target,
26};
27use crate::audit::HarnessAudit;
28use crate::mode::{HarnessMode, ModeStore};
29use crate::shell::{IsolationStatus, ShellLedger};
30
31/// `policy_ref` of the harness policy; audit records cite it as `tool_policy:adk-harness` (spec 3.1 §7.3).
32///
33/// # Example
34///
35/// ```rust
36/// assert_eq!(adk_harness::HARNESS_POLICY_REF, "adk-harness");
37/// ```
38pub const HARNESS_POLICY_REF: &str = "adk-harness";
39
40/// Names of the tools the harness itself publishes.
41pub(crate) const HARNESS_TOOL_NAMES: &[&str] = &[
42    "read_file",
43    "glob",
44    "grep",
45    "harness_help",
46    "write_file",
47    "edit_file",
48    "apply_patch",
49    "bash",
50    "shell_output",
51    "shell_kill",
52    "write_todos",
53    "update_todo",
54    "exit_plan_mode",
55    "list_skills",
56    "load_skill",
57    "load_skill_resource",
58    "search_skills",
59    "memory_read",
60    "memory_write",
61    "memory_delete",
62    "memory_search",
63    "memory_remember",
64    "web_fetch",
65    "web_search",
66    "mcp_list_resources",
67    "mcp_read_resource",
68];
69
70/// Run policies a harness layer composed, each with the harness it belongs to.
71static COMPOSED_LAYERS: Mutex<Vec<(usize, Weak<dyn ToolPolicy>)>> = Mutex::new(Vec::new());
72
73fn address(policy: &dyn ToolPolicy) -> *const () {
74    std::ptr::from_ref(policy).cast::<()>()
75}
76
77/// Records `policy` as the run policy the harness `owner` composed.
78pub(crate) fn register_composed_layer(owner: usize, policy: &Arc<dyn ToolPolicy>) {
79    let mut layers = COMPOSED_LAYERS.lock().unwrap_or_else(|e| e.into_inner());
80    layers.retain(|(_, layer)| layer.strong_count() > 0);
81    layers.push((owner, Arc::downgrade(policy)));
82}
83
84/// The harness whose layer composed `policy`, if one did.
85pub(crate) fn composed_layer_owner(policy: &dyn ToolPolicy) -> Option<usize> {
86    let target = address(policy);
87    let layers = COMPOSED_LAYERS.lock().unwrap_or_else(|e| e.into_inner());
88    layers
89        .iter()
90        .find(|(_, layer)| layer.strong_count() > 0 && layer.as_ptr().cast::<()>() == target)
91        .map(|(owner, _)| *owner)
92}
93
94/// Whether `policy` is a run policy that a harness layer composed (spec 3.1 §7.3, §9.2 I17).
95///
96/// The check is bound to the policy instance the layer installed, never to its name: a
97/// policy that merely calls itself `adk-harness` is not the harness, so `bash`,
98/// `exit_plan_mode` and a nested harness's run refuse it.
99///
100/// # Example
101///
102/// ```rust
103/// use adk_core::{DeclarativePolicy, StrictestPolicy};
104/// use adk_harness::{HarnessAgent, InstructionsConfig};
105/// use adk_model::{ScriptedLlm, ScriptedResponse};
106/// use std::sync::Arc;
107///
108/// let named = DeclarativePolicy::builder().name("adk-harness").build();
109/// assert!(!adk_harness::has_harness_layer(&named));
110/// let composed = StrictestPolicy::new(vec![Arc::new(named)]);
111/// assert!(!adk_harness::has_harness_layer(&composed));
112///
113/// let dir = tempfile::tempdir().unwrap();
114/// let harness = HarnessAgent::builder("harness")
115///     .model(Arc::new(ScriptedLlm::new("scripted", Vec::<ScriptedResponse>::new())))
116///     .workspace(adk_devtools::Workspace::new(dir.path()))
117///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
118///     .build()
119///     .unwrap();
120/// let config = harness.run_config();
121/// assert!(adk_harness::has_harness_layer(config.tool_policy.as_deref().unwrap()));
122/// ```
123pub fn has_harness_layer(policy: &dyn ToolPolicy) -> bool {
124    composed_layer_owner(policy).is_some()
125}
126
127/// Where a shell call runs, as the policy classes it (spec 3.1 §7.4).
128///
129/// # Example
130///
131/// ```rust
132/// use adk_harness::Isolation;
133///
134/// assert_eq!(serde_json::to_value(Isolation::OsSandbox).unwrap(), "os_sandbox");
135/// ```
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub enum Isolation {
139    /// An active OS sandbox.
140    OsSandbox,
141    /// A container.
142    Container,
143    /// The host, including a degraded sandbox.
144    Host,
145}
146
147/// A call's harness class (spec 3.1 §7.4).
148///
149/// A call's class comes from (`origin.source`, name) in the harness registry, never from
150/// [`ToolEffect`] or MCP hints alone (spec 3.1 §9.2 I12).
151///
152/// # Example
153///
154/// ```rust
155/// use adk_core::ToolEffect;
156/// use adk_harness::ToolKind;
157///
158/// assert!(ToolKind::Edit.rule_eligible());
159/// assert!(!ToolKind::PlanExit.rule_eligible());
160/// let mcp = ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: false };
161/// assert!(mcp.rule_eligible());
162/// ```
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
164#[serde(rename_all = "snake_case")]
165#[non_exhaustive]
166pub enum ToolKind {
167    /// `read_file`, `glob`, `grep`, `harness_help`, `list_skills`, `load_skill`, `load_skill_resource`,
168    /// `search_skills`, `memory_read`, `memory_search`, `mcp_list_resources`,
169    /// `mcp_read_resource` (spec 3.1 §7.21).
170    Read,
171    /// `write_todos`, `update_todo`.
172    Todo,
173    /// `exit_plan_mode`.
174    PlanExit,
175    /// `write_file`, `edit_file`; a protected path is the non-waivable variant.
176    Edit,
177    /// `bash`.
178    Shell(Isolation),
179    /// `bash` with `unsandboxed: true`.
180    ShellEscalation,
181    /// Team member tools.
182    Delegate,
183    /// `memory_write`, `memory_delete`.
184    MemoryWrite,
185    /// `memory_remember`: long-term facts, assumed unless the person's own words verify them
186    /// (spec 3.1 §7.15.2, spec 3.3 §8.1).
187    MemoryPropose,
188    /// `web_fetch`, `web_search`: whether the URL's host is in the allowlist
189    /// (spec 3.1 §7.20).
190    Web {
191        /// Whether the call's host is in `WebConfig::allowed_domains`.
192        allowlisted: bool,
193    },
194    /// Payments pack tools; never waivable.
195    Payment,
196    /// `computer_use_execute`: a desktop action through the computer-use pack; never
197    /// waivable (spec 3.1 §7.24).
198    ComputerUse,
199    /// Any other tool: MCP, browser, extras, skill-activated.
200    External {
201        /// The effect the tool declares.
202        effect: ToolEffect,
203        /// Whether the publisher is trusted to declare its effect.
204        trusted_origin: bool,
205    },
206}
207
208impl ToolKind {
209    /// Whether any standing rule may cover the class (spec 3.1 §7.5).
210    pub fn rule_eligible(&self) -> bool {
211        !matches!(self, Self::PlanExit | Self::Payment | Self::MemoryWrite | Self::ComputerUse)
212    }
213
214    /// Whether the class is the shell or its escalation.
215    pub fn is_shell(&self) -> bool {
216        matches!(self, Self::Shell(_) | Self::ShellEscalation)
217    }
218}
219
220/// Registry of the harness's own tool classes (spec 3.1 §7.4).
221///
222/// A call is a harness class only if the agent is one of the harness's own agents, the
223/// name is registered, and the origin is [`STATIC_TOOL_ORIGIN`]. A caller of
224/// `ToolPolicy::evaluate` without the call's origin gets a class resting on the agent's
225/// tool names, which an `LlmAgent` keeps unique across its tools and toolsets.
226///
227/// # Example
228///
229/// ```rust
230/// use adk_core::{ToolEffect, ToolOrigin};
231/// use adk_harness::{Isolation, ToolClassRegistry, ToolKind};
232/// use serde_json::json;
233///
234/// let registry = ToolClassRegistry::harness_defaults("harness");
235/// let mcp = ToolOrigin::new("mcp:fs", &json!({ "name": "read_file" }), None);
236/// let kind = registry.classify("harness", "read_file", Some(&mcp), &json!({}), ToolEffect::ReadOnly, Isolation::Host, false);
237/// assert_eq!(kind, ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: false });
238/// let own = registry.classify("harness", "read_file", None, &json!({}), ToolEffect::ReadOnly, Isolation::Host, false);
239/// assert_eq!(own, ToolKind::Read);
240/// ```
241#[derive(Clone, Debug, Default)]
242pub struct ToolClassRegistry {
243    agents: BTreeSet<String>,
244    classes: BTreeMap<String, ToolKind>,
245    /// Hosts the web tools reach without approval (spec 3.1 §7.20).
246    web_allowlist: Vec<String>,
247    /// The fetch filter: hosts outside it are denied whatever the mode or rules.
248    fetch_domains: Option<crate::web::SearchDomains>,
249    /// Classes of tools that publishers the harness does not own declare through a
250    /// trusted manifest (spec 3.2 §7.7).
251    origin_classes: Vec<Arc<dyn OriginClasses>>,
252    /// Classes of the harness's own tools decided per call (spec 3.7 X15).
253    call_classes: Vec<Arc<dyn CallClasses>>,
254}
255
256/// Classes tools of a publisher the harness does not own, from a declaration the user
257/// approved rather than from the tool's own hints (spec 3.2 §7.7, 3.1 I12).
258///
259/// The kernel's drivers are classed this way: each driver tool's class comes from the
260/// manifest the user approved at mount (`adk-harness`'s `kernel` feature).
261///
262/// # Example
263///
264/// ```rust
265/// use std::sync::Arc;
266/// use adk_core::{ToolEffect, ToolOrigin};
267/// use adk_harness::{Isolation, OriginClasses, ToolClassRegistry, ToolKind};
268/// use serde_json::json;
269///
270/// #[derive(Debug)]
271/// struct Approved;
272///
273/// impl OriginClasses for Approved {
274///     fn class_of(&self, source: &str, _tool: &str) -> Option<ToolKind> {
275///         (source == "driver:notes")
276///             .then_some(ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: true })
277///     }
278/// }
279///
280/// let registry = ToolClassRegistry::harness_defaults("harness").with_origin_classes(Arc::new(Approved));
281/// let origin = ToolOrigin::new("driver:notes", &json!({ "name": "read" }), None);
282/// let kind = registry.classify("harness", "read", Some(&origin), &json!({}), ToolEffect::NonIdempotent, Isolation::Host, false);
283/// assert_eq!(kind, ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: true });
284/// ```
285pub trait OriginClasses: std::fmt::Debug + Send + Sync {
286    /// The class of a call to `tool` that `source` publishes, or `None` when `source` is
287    /// not one this classes.
288    fn class_of(&self, source: &str, tool: &str) -> Option<ToolKind>;
289}
290
291/// Classes a pack's own tools per call, from the call's arguments (spec 3.7 X15): the vision
292/// pack's tools are `Read` when they stay on the device and `External` when they send an
293/// image off it. Consulted for the harness's own agents and static tools, before the
294/// registered classes.
295///
296/// # Example
297///
298/// ```rust
299/// use std::sync::Arc;
300/// use adk_core::ToolEffect;
301/// use adk_harness::{CallClasses, Isolation, ToolClassRegistry, ToolKind};
302/// use serde_json::{Value, json};
303///
304/// #[derive(Debug)]
305/// struct ByBackend;
306///
307/// impl CallClasses for ByBackend {
308///     fn class_of_call(&self, tool: &str, args: &Value) -> Option<ToolKind> {
309///         (tool == "vision_describe").then(|| match args["backend"].as_str() {
310///             Some("local") => ToolKind::Read,
311///             _ => ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: false },
312///         })
313///     }
314/// }
315///
316/// let registry = ToolClassRegistry::harness_defaults("harness").with_call_classes(Arc::new(ByBackend));
317/// let local = json!({ "backend": "local" });
318/// let kind = registry.classify("harness", "vision_describe", None, &local, ToolEffect::ReadOnly, Isolation::Host, false);
319/// assert_eq!(kind, ToolKind::Read);
320/// ```
321pub trait CallClasses: std::fmt::Debug + Send + Sync {
322    /// The class of a call to `tool` with `args`, or `None` for a tool it does not class.
323    fn class_of_call(&self, tool: &str, args: &Value) -> Option<ToolKind>;
324
325    /// Why a call to `tool` with `args` is denied in `mode` whatever its class allows, or
326    /// `None`. The vision pack denies a call that sends an image off the machine in
327    /// ReadOnly and Plan. The default denies nothing.
328    fn denial_in_mode(&self, tool: &str, args: &Value, mode: HarnessMode) -> Option<String> {
329        let _ = (tool, args, mode);
330        None
331    }
332}
333
334impl ToolClassRegistry {
335    /// An empty registry.
336    pub fn new() -> Self {
337        Self::default()
338    }
339
340    /// The harness tools for the agent named `agent`.
341    pub fn harness_defaults(agent: &str) -> Self {
342        let mut registry = Self::new().with_agent(agent);
343        for name in [
344            "read_file",
345            "glob",
346            "grep",
347            "harness_help",
348            "list_skills",
349            "load_skill",
350            "load_skill_resource",
351            "search_skills",
352        ] {
353            registry.register(name, ToolKind::Read);
354        }
355        registry.register("write_todos", ToolKind::Todo);
356        registry.register("update_todo", ToolKind::Todo);
357        // Allowed in every mode: proposing is free, running is governed (spec 3.2 §7.5).
358        #[cfg(feature = "kernel")]
359        registry.register(crate::kernel::PROPOSE_FOLLOWUP, ToolKind::Todo);
360        // Suggesting an agent adds nothing until a person says yes (spec 3.3 §5.7).
361        #[cfg(feature = "kernel")]
362        registry.register(crate::agents::PROPOSE_AGENT, ToolKind::Todo);
363        registry.register("exit_plan_mode", ToolKind::PlanExit);
364        registry.register("write_file", ToolKind::Edit);
365        registry.register("edit_file", ToolKind::Edit);
366        registry.register("apply_patch", ToolKind::Edit);
367        registry.register("bash", ToolKind::Shell(Isolation::Host));
368        // Reading a shell's output and stopping one only remove effects (spec 3.1 §7.29).
369        registry.register(crate::shell::SHELL_OUTPUT, ToolKind::Read);
370        registry.register(crate::shell::SHELL_KILL, ToolKind::Read);
371        registry.register("memory_read", ToolKind::Read);
372        registry.register("memory_write", ToolKind::MemoryWrite);
373        registry.register("memory_delete", ToolKind::MemoryWrite);
374        registry.register("memory_search", ToolKind::Read);
375        registry.register("memory_remember", ToolKind::MemoryPropose);
376        // The allowlist decision is made per call from the URL's host (spec 3.1 §7.20).
377        registry.register("web_fetch", ToolKind::Web { allowlisted: false });
378        registry.register("web_search", ToolKind::Web { allowlisted: false });
379        registry.register("mcp_list_resources", ToolKind::Read);
380        registry.register("mcp_read_resource", ToolKind::Read);
381        registry
382    }
383
384    /// Sets the hosts `web_fetch` and `web_search` reach without approval
385    /// (spec 3.1 §7.20): exact hosts or `*.example.com`, the `DomainIn` grammar.
386    ///
387    /// # Example
388    ///
389    /// ```rust
390    /// use adk_core::ToolEffect;
391    /// use adk_harness::{Isolation, ToolClassRegistry, ToolKind};
392    /// use serde_json::json;
393    ///
394    /// let registry = ToolClassRegistry::harness_defaults("harness")
395    ///     .with_web_allowlist(["docs.rs", "*.rust-lang.org"]);
396    /// let classify = |args| registry.classify("harness", "web_fetch", None, &args, ToolEffect::ReadOnly, Isolation::Host, false);
397    /// assert_eq!(classify(json!({ "url": "https://docs.rs/x" })), ToolKind::Web { allowlisted: true });
398    /// assert_eq!(classify(json!({ "url": "https://rust-lang.org/" })), ToolKind::Web { allowlisted: false });
399    /// assert_eq!(classify(json!({ "url": "https://user@docs.rs/" })), ToolKind::Web { allowlisted: false });
400    /// ```
401    #[must_use]
402    pub fn with_web_allowlist(
403        mut self,
404        domains: impl IntoIterator<Item = impl Into<String>>,
405    ) -> Self {
406        self.web_allowlist = domains.into_iter().map(|d| d.into().to_ascii_lowercase()).collect();
407        self
408    }
409
410    /// Classes the harness's own tools that `classes` knows per call, from their arguments
411    /// (spec 3.7 X15).
412    #[must_use]
413    pub fn with_call_classes(mut self, classes: Arc<dyn CallClasses>) -> Self {
414        self.call_classes.push(classes);
415        self
416    }
417
418    /// Classes the tools of publishers `classes` knows by their approved declarations
419    /// (spec 3.2 §7.7); consulted for every origin other than the harness's own.
420    #[must_use]
421    pub fn with_origin_classes(mut self, classes: Arc<dyn OriginClasses>) -> Self {
422        self.origin_classes.push(classes);
423        self
424    }
425
426    /// The hosts the web tools reach without approval.
427    pub fn web_allowlist(&self) -> &[String] {
428        &self.web_allowlist
429    }
430
431    /// Sets the fetch filter ([`WebConfig::fetch_domains`](crate::web::WebConfig)): a web
432    /// call whose `url` names a host outside it is denied before anyone is asked, in every
433    /// mode and under every standing rule.
434    ///
435    /// # Example
436    ///
437    /// ```rust
438    /// use adk_harness::ToolClassRegistry;
439    /// use adk_harness::web::SearchDomains;
440    ///
441    /// let registry = ToolClassRegistry::harness_defaults("harness")
442    ///     .with_fetch_domains(Some(SearchDomains::Blocked(vec!["pastebin.com".into()])));
443    /// assert!(registry.fetch_domains().is_some());
444    /// ```
445    #[must_use]
446    pub fn with_fetch_domains(mut self, filter: Option<crate::web::SearchDomains>) -> Self {
447        self.fetch_domains = filter;
448        self
449    }
450
451    /// The fetch filter, if one is set.
452    pub fn fetch_domains(&self) -> Option<&crate::web::SearchDomains> {
453        self.fetch_domains.as_ref()
454    }
455
456    /// Whether the web call `tool` with `args` names an allowlisted host: `web_search` by
457    /// its `site`, every other `Web` tool — `web_fetch`, the browser pack's navigation
458    /// (spec 3.1 §7.24) — by its `url` (absent: not allowlisted).
459    fn web_allowlisted(&self, tool: &str, args: &Value) -> bool {
460        match tool {
461            "web_search" => args.get("site").and_then(Value::as_str).is_some_and(|site| {
462                crate::web::ParsedUrl::parse(&format!("https://{site}/")).is_ok_and(|parsed| {
463                    crate::web::host_allowlisted(&parsed.host, &self.web_allowlist)
464                })
465            }),
466            _ => args
467                .get("url")
468                .and_then(Value::as_str)
469                .is_some_and(|url| crate::web::url_allowlisted(url, &self.web_allowlist)),
470        }
471    }
472
473    /// Adds one of the harness's own agents.
474    #[must_use]
475    pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
476        self.agents.insert(agent.into());
477        self
478    }
479
480    /// Registers `name` as `kind`.
481    pub fn register(&mut self, name: impl Into<String>, kind: ToolKind) {
482        self.classes.insert(name.into(), kind);
483    }
484
485    /// Removes `name`.
486    pub fn unregister(&mut self, name: &str) {
487        self.classes.remove(name);
488    }
489
490    /// Whether `name` is a registered harness tool.
491    pub fn is_registered(&self, name: &str) -> bool {
492        self.classes.contains_key(name)
493    }
494
495    /// Why a call by `agent` to `tool` with `origin` and `args` is denied in `mode`
496    /// ([`CallClasses::denial_in_mode`]), for the harness's own agents and static tools.
497    pub fn denial_in_mode(
498        &self,
499        agent: &str,
500        tool: &str,
501        origin: Option<&ToolOrigin>,
502        args: &Value,
503        mode: HarnessMode,
504    ) -> Option<String> {
505        let static_origin = origin.is_none_or(|origin| origin.source == STATIC_TOOL_ORIGIN);
506        (static_origin && self.agents.contains(agent))
507            .then(|| {
508                self.call_classes
509                    .iter()
510                    .find_map(|classes| classes.denial_in_mode(tool, args, mode))
511            })
512            .flatten()
513    }
514
515    /// The class of a call by `agent` to `tool` with `origin` and `args`.
516    #[allow(clippy::too_many_arguments)]
517    pub fn classify(
518        &self,
519        agent: &str,
520        tool: &str,
521        origin: Option<&ToolOrigin>,
522        args: &Value,
523        effect: ToolEffect,
524        isolation: Isolation,
525        trust_mcp_read_only_hints: bool,
526    ) -> ToolKind {
527        let static_origin = origin.is_none_or(|origin| origin.source == STATIC_TOOL_ORIGIN);
528        if static_origin && self.agents.contains(agent) {
529            if let Some(kind) =
530                self.call_classes.iter().find_map(|classes| classes.class_of_call(tool, args))
531            {
532                return kind;
533            }
534            match self.classes.get(tool) {
535                Some(ToolKind::Shell(_)) => {
536                    return if args.get("unsandboxed").and_then(Value::as_bool) == Some(true) {
537                        ToolKind::ShellEscalation
538                    } else {
539                        ToolKind::Shell(isolation)
540                    };
541                }
542                Some(ToolKind::Web { .. }) => {
543                    return ToolKind::Web { allowlisted: self.web_allowlisted(tool, args) };
544                }
545                Some(kind) => return *kind,
546                None => {}
547            }
548        }
549        if let Some(origin) = origin.filter(|origin| origin.source != STATIC_TOOL_ORIGIN)
550            && let Some(kind) = self
551                .origin_classes
552                .iter()
553                .find_map(|classes| classes.class_of(&origin.source, tool))
554        {
555            return kind;
556        }
557        let trusted_origin = match origin {
558            Some(origin) if origin.source == STATIC_TOOL_ORIGIN => true,
559            Some(origin) if origin.source.starts_with("mcp:") => trust_mcp_read_only_hints,
560            _ => false,
561        };
562        ToolKind::External { effect, trusted_origin }
563    }
564}
565
566/// Rows of [`MODE_TABLE`] (spec 3.1 §7.4).
567///
568/// # Example
569///
570/// ```rust
571/// use adk_harness::{Isolation, TableRow, ToolKind};
572///
573/// assert_eq!(TableRow::of(&ToolKind::Edit, true), TableRow::EditProtected);
574/// assert_eq!(TableRow::of(&ToolKind::Shell(Isolation::Host), false), TableRow::ShellHost);
575/// ```
576#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
577pub enum TableRow {
578    /// Read, Todo, Delegate.
579    ReadTodoDelegate,
580    /// `exit_plan_mode`.
581    PlanExit,
582    /// Edit of a non-protected path.
583    Edit,
584    /// Edit of a protected path.
585    EditProtected,
586    /// Shell in an active OS sandbox.
587    ShellOsSandbox,
588    /// Shell in a container.
589    ShellContainer,
590    /// Shell on the host, including a degraded sandbox.
591    ShellHost,
592    /// Unsandboxed retry.
593    ShellEscalation,
594    /// Memory writes.
595    MemoryWrite,
596    /// Assumed long-term facts (spec 3.1 §7.15.2).
597    MemoryPropose,
598    /// A web call whose host is in the allowlist (spec 3.1 §7.20).
599    WebAllowlisted,
600    /// A web call to any other host.
601    WebOther,
602    /// Payments.
603    Payment,
604    /// A desktop action through the computer-use pack (spec 3.1 §7.24).
605    ComputerUse,
606    /// A read-only tool from a trusted origin.
607    ExternalReadOnlyTrusted,
608    /// Any other tool.
609    ExternalOther,
610}
611
612impl TableRow {
613    /// Every row, in table order.
614    pub const ALL: [TableRow; 16] = [
615        Self::ReadTodoDelegate,
616        Self::PlanExit,
617        Self::Edit,
618        Self::EditProtected,
619        Self::ShellOsSandbox,
620        Self::ShellContainer,
621        Self::ShellHost,
622        Self::ShellEscalation,
623        Self::MemoryWrite,
624        Self::MemoryPropose,
625        Self::WebAllowlisted,
626        Self::WebOther,
627        Self::Payment,
628        Self::ComputerUse,
629        Self::ExternalReadOnlyTrusted,
630        Self::ExternalOther,
631    ];
632
633    /// The row of a call of `kind`; `protected_path` selects the protected edit row.
634    pub fn of(kind: &ToolKind, protected_path: bool) -> Self {
635        match kind {
636            ToolKind::Read | ToolKind::Todo | ToolKind::Delegate => Self::ReadTodoDelegate,
637            ToolKind::PlanExit => Self::PlanExit,
638            ToolKind::Edit if protected_path => Self::EditProtected,
639            ToolKind::Edit => Self::Edit,
640            ToolKind::Shell(Isolation::OsSandbox) => Self::ShellOsSandbox,
641            ToolKind::Shell(Isolation::Container) => Self::ShellContainer,
642            ToolKind::Shell(Isolation::Host) => Self::ShellHost,
643            ToolKind::ShellEscalation => Self::ShellEscalation,
644            ToolKind::MemoryWrite => Self::MemoryWrite,
645            ToolKind::MemoryPropose => Self::MemoryPropose,
646            ToolKind::Web { allowlisted: true } => Self::WebAllowlisted,
647            ToolKind::Web { allowlisted: false } => Self::WebOther,
648            ToolKind::Payment => Self::Payment,
649            ToolKind::ComputerUse => Self::ComputerUse,
650            ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: true } => {
651                Self::ExternalReadOnlyTrusted
652            }
653            ToolKind::External { .. } => Self::ExternalOther,
654        }
655    }
656
657    /// Whether every cell of the row is Deny or a non-waivable approval: no standing rule
658    /// or `tool_approvals` entry ever applies to the row.
659    pub fn is_non_waivable(self) -> bool {
660        matches!(
661            self,
662            Self::PlanExit
663                | Self::EditProtected
664                | Self::ShellEscalation
665                | Self::MemoryWrite
666                | Self::Payment
667                | Self::ComputerUse
668        )
669    }
670
671    fn index(self) -> usize {
672        Self::ALL.iter().position(|row| *row == self).unwrap_or(Self::ALL.len() - 1)
673    }
674}
675
676/// One cell of [`MODE_TABLE`] (spec 3.1 §7.4).
677///
678/// # Example
679///
680/// ```rust
681/// use adk_harness::{ModeCell, PolicySwitches, TableDecision};
682///
683/// let switches = PolicySwitches::default();
684/// assert_eq!(ModeCell::AskOrHostShellInAuto.resolve(&switches), TableDecision::RequireApproval { non_waivable: false });
685/// ```
686#[derive(Clone, Copy, Debug, PartialEq, Eq)]
687pub enum ModeCell {
688    /// Allow.
689    Allow,
690    /// Deny.
691    Deny,
692    /// RequireApproval; a standing rule may allow.
693    Ask,
694    /// RequireApproval, non-waivable: no standing rule or `tool_approvals` entry applies.
695    AskNonWaivable,
696    /// Allow with a read-only workspace mount and no network, only under an active
697    /// enforcer; Deny otherwise.
698    AllowWithActiveEnforcer,
699    /// RequireApproval; Allow when `auto_allow_sandboxed` is on.
700    AskOrAutoAllowSandboxed,
701    /// Allow once protected paths are read-only inside the sandbox (S3); RequireApproval
702    /// until then.
703    AllowWithS3,
704    /// RequireApproval; Allow with `allow_host_shell_in_auto`.
705    AskOrHostShellInAuto,
706}
707
708/// The switches the conditional cells of [`MODE_TABLE`] read (spec 3.1 §7.4).
709///
710/// # Example
711///
712/// ```rust
713/// let switches = adk_harness::PolicySwitches::default();
714/// assert!(!switches.auto_allow_sandboxed);
715/// ```
716#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
717pub struct PolicySwitches {
718    /// `auto_allow_sandboxed` is on (needs S3).
719    pub auto_allow_sandboxed: bool,
720    /// `allow_host_shell_in_auto` is on.
721    pub allow_host_shell_in_auto: bool,
722    /// An OS sandbox enforcer is active for the shell.
723    pub enforcer_active: bool,
724    /// Protected paths are read-only inside the sandbox (adk-sandbox S3).
725    pub sandbox_protects_paths: bool,
726}
727
728/// What a [`ModeCell`] resolves to (spec 3.1 §7.4).
729///
730/// # Example
731///
732/// ```rust
733/// use adk_harness::TableDecision;
734///
735/// assert!(TableDecision::RequireApproval { non_waivable: true }.is_non_waivable());
736/// ```
737#[derive(Clone, Copy, Debug, PartialEq, Eq)]
738pub enum TableDecision {
739    /// Allow.
740    Allow,
741    /// Deny.
742    Deny,
743    /// RequireApproval.
744    RequireApproval {
745        /// No standing rule or `tool_approvals` entry applies.
746        non_waivable: bool,
747    },
748}
749
750impl TableDecision {
751    /// Whether the decision is a non-waivable approval.
752    pub fn is_non_waivable(self) -> bool {
753        matches!(self, Self::RequireApproval { non_waivable: true })
754    }
755}
756
757impl ModeCell {
758    /// Resolves the cell under `switches`.
759    pub fn resolve(self, switches: &PolicySwitches) -> TableDecision {
760        let ask = TableDecision::RequireApproval { non_waivable: false };
761        match self {
762            Self::Allow => TableDecision::Allow,
763            Self::Deny => TableDecision::Deny,
764            Self::Ask => ask,
765            Self::AskNonWaivable => TableDecision::RequireApproval { non_waivable: true },
766            Self::AllowWithActiveEnforcer => {
767                if switches.enforcer_active {
768                    TableDecision::Allow
769                } else {
770                    TableDecision::Deny
771                }
772            }
773            Self::AskOrAutoAllowSandboxed => {
774                if switches.auto_allow_sandboxed && switches.sandbox_protects_paths {
775                    TableDecision::Allow
776                } else {
777                    ask
778                }
779            }
780            Self::AllowWithS3 => {
781                if switches.sandbox_protects_paths {
782                    TableDecision::Allow
783                } else {
784                    ask
785                }
786            }
787            Self::AskOrHostShellInAuto => {
788                if switches.allow_host_shell_in_auto {
789                    TableDecision::Allow
790                } else {
791                    ask
792                }
793            }
794        }
795    }
796}
797
798/// The mode × class table of spec 3.1 §7.4, indexed `[TableRow][mode]` with modes in
799/// [`HarnessMode::ALL`] order (ReadOnly, Plan, Ask, Auto).
800///
801/// # Example
802///
803/// ```rust
804/// use adk_harness::{HarnessMode, ModeCell, decision_cell};
805/// use adk_harness::TableRow;
806///
807/// assert_eq!(decision_cell(HarnessMode::Plan, TableRow::Edit), ModeCell::Deny);
808/// assert_eq!(decision_cell(HarnessMode::Auto, TableRow::Edit), ModeCell::Allow);
809/// ```
810pub const MODE_TABLE: [[ModeCell; 4]; 16] = {
811    use ModeCell::{
812        Allow, AllowWithActiveEnforcer, AllowWithS3, Ask, AskNonWaivable, AskOrAutoAllowSandboxed,
813        AskOrHostShellInAuto, Deny,
814    };
815    [
816        // ReadOnly, Plan, Ask, Auto
817        [Allow, Allow, Allow, Allow],       // Read, Todo, Delegate
818        [Deny, AskNonWaivable, Deny, Deny], // PlanExit
819        [Deny, Deny, Ask, Allow],           // Edit
820        [Deny, Deny, AskNonWaivable, AskNonWaivable], // Edit, protected path
821        [Deny, AllowWithActiveEnforcer, AskOrAutoAllowSandboxed, AllowWithS3], // Shell, OS sandbox
822        [Deny, Deny, AskOrAutoAllowSandboxed, Allow], // Shell, container
823        [Deny, Deny, Ask, AskOrHostShellInAuto], // Shell, host
824        [Deny, Deny, AskNonWaivable, AskNonWaivable], // ShellEscalation
825        [Deny, Deny, AskNonWaivable, AskNonWaivable], // MemoryWrite
826        [Deny, Deny, Allow, Allow],         // MemoryPropose (assumed facts)
827        [Allow, Allow, Allow, Allow],       // Web, allowlisted host
828        [Deny, Deny, Ask, Ask],             // Web, other host
829        [Deny, Deny, AskNonWaivable, AskNonWaivable], // Payment
830        [Deny, Deny, AskNonWaivable, AskNonWaivable], // ComputerUse
831        [Allow, Allow, Allow, Allow],       // External, read-only, trusted
832        [Deny, Deny, Ask, Ask],             // External, other
833    ]
834};
835
836fn mode_index(mode: HarnessMode) -> usize {
837    HarnessMode::ALL.iter().position(|m| *m == mode).unwrap_or(0)
838}
839
840/// The [`MODE_TABLE`] cell for `mode` and `row` (spec 3.1 §7.4).
841///
842/// # Example
843///
844/// ```rust
845/// use adk_harness::{HarnessMode, ModeCell, TableRow, decision_cell};
846///
847/// assert_eq!(decision_cell(HarnessMode::ReadOnly, TableRow::ShellHost), ModeCell::Deny);
848/// ```
849pub fn decision_cell(mode: HarnessMode, row: TableRow) -> ModeCell {
850    MODE_TABLE[row.index()][mode_index(mode)]
851}
852
853/// Steps 4 and 6–9 of the decision function (spec 3.1 §7.4): combines the mode table's
854/// decision with the standing-rule outcome.
855///
856/// Deny from the table or a Deny rule wins; a non-waivable approval ignores every rule;
857/// an Allow rule turns a waivable approval into Allow and changes nothing else.
858///
859/// # Example
860///
861/// ```rust
862/// use adk_core::PolicyDecision;
863/// use adk_harness::approvals::matcher::RuleOutcome;
864/// use adk_harness::{TableDecision, apply_rule};
865///
866/// let allow = RuleOutcome::Allow { rule_id: "r1".into() };
867/// assert_eq!(apply_rule(TableDecision::RequireApproval { non_waivable: false }, &allow, "x"), PolicyDecision::Allow);
868/// assert!(matches!(apply_rule(TableDecision::RequireApproval { non_waivable: true }, &allow, "x"), PolicyDecision::RequireApproval { .. }));
869/// assert!(matches!(apply_rule(TableDecision::Deny, &allow, "x"), PolicyDecision::Deny { .. }));
870/// ```
871pub fn apply_rule(base: TableDecision, rule: &RuleOutcome, reason: &str) -> PolicyDecision {
872    if base == TableDecision::Deny {
873        return PolicyDecision::deny(reason);
874    }
875    if let RuleOutcome::Deny { reason, .. } = rule {
876        return PolicyDecision::deny(format!("a standing rule denies it: {reason}"));
877    }
878    match base {
879        TableDecision::Allow => PolicyDecision::Allow,
880        TableDecision::RequireApproval { non_waivable: true } => PolicyDecision::require_approval(
881            format!("{reason}; it needs a one-time approval and no standing rule applies"),
882        ),
883        TableDecision::RequireApproval { non_waivable: false } => match rule {
884            RuleOutcome::Allow { .. } => PolicyDecision::Allow,
885            _ => PolicyDecision::require_approval(reason),
886        },
887        TableDecision::Deny => PolicyDecision::deny(reason),
888    }
889}
890
891/// The decision function's result with how it was reached.
892#[derive(Clone, Debug)]
893pub(crate) struct Evaluated {
894    pub(crate) decision: PolicyDecision,
895    pub(crate) kind: ToolKind,
896    pub(crate) mode: HarnessMode,
897    pub(crate) base: TableDecision,
898    /// The standing rule that turned an approval into Allow (spec 3.1 §7.33 fix 3).
899    pub(crate) rule: Option<crate::approvals::RuleHit>,
900}
901
902/// What the confirmation handler needs to know about a call the policy did not deny.
903#[derive(Clone, Debug)]
904pub(crate) struct PromptContext {
905    /// Whether the harness itself required approval. When it allowed the call, another
906    /// layer of the run's policy or the agent's confirmation policy held it.
907    pub(crate) harness_held: bool,
908    /// The other layers of the run's policy, for the handler's re-check.
909    pub(crate) peers: Option<Arc<dyn ToolPolicy>>,
910    /// The run's kill switches; a freeze abandons an open prompt (I20).
911    pub(crate) governance: Vec<adk_core::GovernanceControl>,
912    pub(crate) app_name: String,
913    pub(crate) user_id: String,
914    pub(crate) session_id: String,
915    pub(crate) invocation_id: String,
916    pub(crate) agent_name: String,
917    pub(crate) effect: ToolEffect,
918    pub(crate) acting: Option<ActingContext>,
919    pub(crate) audit: Option<AuditTrail>,
920}
921
922impl PromptContext {
923    pub(crate) fn policy_request(&self, tool_name: &str, args: &Value) -> ToolPolicyRequest {
924        let mut request = ToolPolicyRequest::new(tool_name, args.clone())
925            .with_effect(self.effect)
926            .with_agent_name(self.agent_name.clone())
927            .with_identity(self.app_name.clone(), self.user_id.clone(), self.session_id.clone())
928            .with_invocation_id(self.invocation_id.clone());
929        if let Some(acting) = &self.acting {
930            request = request.with_acting_context(acting.clone());
931        }
932        request
933    }
934
935    pub(crate) fn audit(&self) -> Option<HarnessAudit> {
936        let trail = self.audit.clone()?;
937        let actor = match &self.acting {
938            Some(acting) => AuditActor::new(acting, self.invocation_id.clone()),
939            None => AuditActor::for_invocation(
940                &self.app_name,
941                &self.agent_name,
942                &self.user_id,
943                &self.invocation_id,
944            ),
945        };
946        Some(HarnessAudit::new(trail, actor, self.session_id.clone()))
947    }
948}
949
950/// Upper bound of remembered prompt contexts; the oldest are dropped first.
951const PROMPT_CONTEXT_CAP: usize = 4096;
952
953fn call_key(agent: &str, subject: &str, tool: &str, args: &Value) -> String {
954    format!("{agent}\u{1f}{subject}\u{1f}{}", tool_call_fingerprint(tool, args))
955}
956
957/// Contexts by call ID, dropping the oldest beyond [`PROMPT_CONTEXT_CAP`], so the
958/// context of the call being decided is never the one dropped.
959#[derive(Debug, Default)]
960struct ByCall {
961    entries: HashMap<String, (u64, PromptContext)>,
962    order: VecDeque<(u64, String)>,
963    next: u64,
964}
965
966/// Prompt contexts recorded by the policy for the handler, by call ID and by call key.
967#[derive(Debug, Default)]
968pub(crate) struct PromptContexts {
969    by_call: Mutex<ByCall>,
970    by_key: Mutex<HashMap<String, VecDeque<PromptContext>>>,
971}
972
973impl PromptContexts {
974    fn insert(&self, call_id: Option<&str>, key: String, context: PromptContext) {
975        if let Some(call_id) = call_id {
976            let mut by_call = self.by_call.lock().unwrap_or_else(|e| e.into_inner());
977            by_call.next += 1;
978            let seq = by_call.next;
979            by_call.entries.insert(call_id.to_string(), (seq, context.clone()));
980            by_call.order.push_back((seq, call_id.to_string()));
981            while by_call.order.len() > PROMPT_CONTEXT_CAP {
982                let Some((seq, oldest)) = by_call.order.pop_front() else { break };
983                if by_call.entries.get(&oldest).is_some_and(|(at, _)| *at == seq) {
984                    by_call.entries.remove(&oldest);
985                }
986            }
987        }
988        if !context.harness_held {
989            // Only calls the harness held are looked up without their ID.
990            return;
991        }
992        let mut by_key = self.by_key.lock().unwrap_or_else(|e| e.into_inner());
993        if by_key.len() >= PROMPT_CONTEXT_CAP {
994            by_key.clear();
995        }
996        let queue = by_key.entry(key).or_default();
997        queue.push_back(context);
998        while queue.len() > 16 {
999            queue.pop_front();
1000        }
1001    }
1002
1003    /// The context recorded for the call `call_id`, left in place.
1004    #[cfg(feature = "acp-server")]
1005    pub(crate) fn by_call_id(&self, call_id: &str) -> Option<PromptContext> {
1006        let by_call = self.by_call.lock().unwrap_or_else(|e| e.into_inner());
1007        by_call.entries.get(call_id).map(|(_, context)| context.clone())
1008    }
1009
1010    /// Takes the context recorded for `request`, by call ID first.
1011    pub(crate) fn take(&self, request: &ToolConfirmationRequest) -> Option<PromptContext> {
1012        if let Some(call_id) = request.function_call_id.as_deref() {
1013            let found = self
1014                .by_call
1015                .lock()
1016                .unwrap_or_else(|e| e.into_inner())
1017                .entries
1018                .remove(call_id)
1019                .map(|(_, context)| context);
1020            if found.is_some() {
1021                return found;
1022            }
1023        }
1024        let acting = request.acting.as_deref()?;
1025        let subject = acting.on_behalf_of.as_ref().map(|s| s.id.as_str()).unwrap_or_default();
1026        let key = call_key(acting.agent.id.as_str(), subject, &request.tool_name, &request.args);
1027        let mut by_key = self.by_key.lock().unwrap_or_else(|e| e.into_inner());
1028        let queue = by_key.get_mut(&key)?;
1029        let context = queue.pop_front();
1030        if queue.is_empty() {
1031            by_key.remove(&key);
1032        }
1033        context
1034    }
1035}
1036
1037/// Shell facts the policy decides on.
1038#[derive(Clone, Debug)]
1039pub(crate) struct ShellView {
1040    pub(crate) status: IsolationStatus,
1041    pub(crate) allow_unsandboxed_retry: bool,
1042    pub(crate) fail_if_unavailable: bool,
1043    /// The enforcer refuses writes to root-level protected paths by name.
1044    pub(crate) guards_protected_names: bool,
1045}
1046
1047pub(crate) struct PolicyInner {
1048    pub(crate) registry: ToolClassRegistry,
1049    pub(crate) mode_store: Arc<dyn ModeStore>,
1050    pub(crate) default_mode: HarnessMode,
1051    pub(crate) rules: Arc<dyn StandingRuleStore>,
1052    pub(crate) ledger: Arc<dyn ShellLedger>,
1053    pub(crate) workspace: Workspace,
1054    pub(crate) shell: ShellView,
1055    pub(crate) switches: PolicySwitches,
1056    pub(crate) trust_mcp_read_only_hints: bool,
1057    pub(crate) prompts: PromptContexts,
1058    /// Provider-executed web tools the operator enabled (spec 3.1 §7.20, I49).
1059    pub(crate) provider_web_tools: BTreeSet<String>,
1060    #[cfg(feature = "hooks")]
1061    pub(crate) hooks: Option<Arc<crate::hooks::HookRunner>>,
1062    #[cfg(feature = "auth")]
1063    pub(crate) identity: Arc<crate::identity::IdentityGate>,
1064    #[cfg(feature = "observe")]
1065    pub(crate) root_agent: String,
1066    /// The prompter told about calls a standing rule allows (spec 3.1 §7.33 fix 3).
1067    pub(crate) rule_observer: std::sync::OnceLock<Arc<dyn crate::approvals::ApprovalPrompter>>,
1068}
1069
1070/// The harness [`ToolPolicy`] (spec 3.1 §7.4, §7.5).
1071///
1072/// Reads the session's mode from the [`ModeStore`] and the subject's standing rules from
1073/// the [`StandingRuleStore`] on every evaluation, so a tightening or a revocation applies
1074/// at the next call (spec 3.1 §9.2 I4, I14). `configure_run` composes it with the run's
1075/// own policy, the stricter decision winning.
1076///
1077/// # Example
1078///
1079/// ```rust,ignore
1080/// let harness = adk_harness::HarnessAgent::builder("harness").model(model).workspace(ws).build()?;
1081/// let policy = harness.runtime().policy();
1082/// assert_eq!(adk_core::ToolPolicy::policy_ref(policy.as_ref()).as_deref(), Some("adk-harness"));
1083/// ```
1084#[derive(Clone)]
1085pub struct HarnessPolicy {
1086    pub(crate) inner: Arc<PolicyInner>,
1087    audit: Option<AuditTrail>,
1088    peers: Option<Arc<dyn ToolPolicy>>,
1089    governance: Vec<adk_core::GovernanceControl>,
1090}
1091
1092impl std::fmt::Debug for HarnessPolicy {
1093    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1094        f.debug_struct("HarnessPolicy")
1095            .field("default_mode", &self.inner.default_mode)
1096            .field("isolation", &self.inner.shell.status)
1097            .field("audit", &self.audit.is_some())
1098            .finish()
1099    }
1100}
1101
1102impl HarnessPolicy {
1103    pub(crate) fn new(inner: PolicyInner) -> Self {
1104        Self { inner: Arc::new(inner), audit: None, peers: None, governance: Vec::new() }
1105    }
1106
1107    /// This policy, recording `harness.rule.*` evaluations through `audit`.
1108    pub(crate) fn with_audit(&self, audit: Option<AuditTrail>) -> Self {
1109        Self {
1110            inner: self.inner.clone(),
1111            audit,
1112            peers: self.peers.clone(),
1113            governance: self.governance.clone(),
1114        }
1115    }
1116
1117    /// This policy as one layer of a run's policy whose other layers are `peers`, which the
1118    /// confirmation handler re-checks a held call against (spec 3.1 §7.3 compose rule).
1119    pub(crate) fn with_peers(mut self, peers: Option<Arc<dyn ToolPolicy>>) -> Self {
1120        self.peers = peers;
1121        self
1122    }
1123
1124    /// This policy as a layer of a run whose kill switches are `governance`, which the
1125    /// confirmation handler watches while a person decides (spec 3.1 §9.2 I20).
1126    pub(crate) fn with_governance(mut self, governance: Vec<adk_core::GovernanceControl>) -> Self {
1127        self.governance = governance;
1128        self
1129    }
1130
1131    /// Tells `prompter` about every call a standing rule allows when it is evaluated
1132    /// (spec 3.1 §7.33 fix 3); the first prompter set is kept.
1133    pub(crate) fn observe_rules(&self, prompter: Arc<dyn crate::approvals::ApprovalPrompter>) {
1134        let _ = self.inner.rule_observer.set(prompter);
1135    }
1136
1137    /// Identifies the harness this policy belongs to; every clone of the harness shares it.
1138    pub(crate) fn owner_id(&self) -> usize {
1139        Arc::as_ptr(&self.inner) as usize
1140    }
1141
1142    /// The default mode of sessions with no mode record.
1143    pub fn default_mode(&self) -> HarnessMode {
1144        self.inner.default_mode
1145    }
1146
1147    /// The tool-class registry.
1148    pub fn registry(&self) -> &ToolClassRegistry {
1149        &self.inner.registry
1150    }
1151
1152    /// The mode governing `invocation_id` of the session.
1153    ///
1154    /// An unparseable record or an unreadable store is `ReadOnly` (spec 3.1 §7.4).
1155    ///
1156    /// # Example
1157    ///
1158    /// ```rust,ignore
1159    /// let mode = policy.mode_for("app", "alice", "s1", "inv-1").await;
1160    /// ```
1161    pub async fn mode_for(
1162        &self,
1163        app: &str,
1164        user: &str,
1165        session: &str,
1166        invocation_id: &str,
1167    ) -> HarnessMode {
1168        self.mode_and_plan_exit(app, user, session, invocation_id).await.0
1169    }
1170
1171    /// The mode governing `invocation_id`, and whether that invocation already had a plan
1172    /// exit approved.
1173    async fn mode_and_plan_exit(
1174        &self,
1175        app: &str,
1176        user: &str,
1177        session: &str,
1178        invocation_id: &str,
1179    ) -> (HarnessMode, bool) {
1180        match self.inner.mode_store.get(app, user, session).await {
1181            Ok(Some(record)) => (
1182                record.mode_for_invocation(invocation_id),
1183                record.set_by == crate::mode::ModeSource::PlanApproval
1184                    && record.effective_from.as_deref() == Some(invocation_id),
1185            ),
1186            Ok(None) => (self.inner.default_mode, false),
1187            Err(error) => {
1188                tracing::warn!(error = %error, "mode store unavailable; evaluating as read_only");
1189                (HarnessMode::ReadOnly, false)
1190            }
1191        }
1192    }
1193
1194    /// The class of the call `request` describes.
1195    pub fn classify(&self, request: &ToolPolicyRequest, origin: Option<&ToolOrigin>) -> ToolKind {
1196        // A provider-executed web tool the operator enabled is decided as an allowlisted web
1197        // call: enabling it is the allow decision, recorded per run (spec 3.1 §7.20, I49).
1198        if self.inner.provider_web_tools.contains(&request.tool_name) {
1199            return ToolKind::Web { allowlisted: true };
1200        }
1201        self.inner.registry.classify(
1202            &request.agent_name,
1203            &request.tool_name,
1204            origin,
1205            &request.args,
1206            request.effect,
1207            self.inner.shell.status.isolation(),
1208            self.inner.trust_mcp_read_only_hints,
1209        )
1210    }
1211
1212    fn audit_for(&self, request: &ToolPolicyRequest) -> Option<HarnessAudit> {
1213        let trail = self.audit.clone()?;
1214        let actor = match &request.acting {
1215            Some(acting) => AuditActor::new(acting, request.invocation_id.clone()),
1216            None => AuditActor::for_invocation(
1217                &request.app_name,
1218                &request.agent_name,
1219                &request.user_id,
1220                &request.invocation_id,
1221            ),
1222        };
1223        Some(HarnessAudit::new(trail, actor, request.session_id.clone()))
1224    }
1225
1226    /// Step 1 of the decision function: calls refused whatever the mode or rules.
1227    async fn hard_deny(
1228        &self,
1229        request: &ToolPolicyRequest,
1230        origin: Option<&ToolOrigin>,
1231        kind: &ToolKind,
1232    ) -> Option<String> {
1233        // A held call to such a tool would sit in the inbox looking like a take over
1234        // (spec 3.3 §10 H2).
1235        if request.tool_name == crate::take_over::TAKE_OVER_TOOL {
1236            return Some(format!(
1237                "'{}' is reserved for take over; no tool may carry that name",
1238                request.tool_name
1239            ));
1240        }
1241        if origin.is_some_and(|origin| origin.source == BUILTIN_TOOL_ORIGIN)
1242            && is_provider_shell_builtin(&request.tool_name)
1243        {
1244            return Some(format!(
1245                "'{}' is a provider-executed shell; the harness runs commands only through its own bash",
1246                request.tool_name
1247            ));
1248        }
1249        if matches!(kind, ToolKind::Read | ToolKind::Edit)
1250            && let Some(paths) = crate::edits::edit_paths(&request.tool_name, &request.args)
1251            && let Some(path) =
1252                paths.iter().find(|path| self.inner.workspace.resolve(path).is_err())
1253        {
1254            return Some(format!("path '{path}' is outside the workspace"));
1255        }
1256        if matches!(kind, ToolKind::Shell(_))
1257            && self.inner.shell.fail_if_unavailable
1258            && let IsolationStatus::Degraded { requested, reason } = &self.inner.shell.status
1259        {
1260            return Some(format!("the requested {requested} shell is unavailable: {reason}"));
1261        }
1262        if *kind == ToolKind::ShellEscalation {
1263            return self.retry_refusal(request).await;
1264        }
1265        // A web URL naming a loopback, link-local or private literal, or a `.local` /
1266        // `.internal` name, is denied before the tool runs (spec 3.1 §7.20, §9.2 I46).
1267        if matches!(kind, ToolKind::Web { .. })
1268            && let Some(url) = request.args.get("url").and_then(Value::as_str)
1269            && crate::web::url_names_private_target(url)
1270        {
1271            return Some(format!(
1272                "harness.web.private_target: '{}' is a private or local target the harness never fetches",
1273                crate::web::url_host(url).unwrap_or_default()
1274            ));
1275        }
1276        // The fetch filter is a ceiling: no approval or standing rule widens it.
1277        if matches!(kind, ToolKind::Web { .. })
1278            && let Some(filter) = self.inner.registry.fetch_domains()
1279            && let Some(url) = request.args.get("url").and_then(Value::as_str)
1280            && let Some(host) = crate::web::url_host(url)
1281            && !filter.permits(&host)
1282        {
1283            return Some(format!(
1284                "harness.web.domain_not_allowed: '{host}' is outside the harness's fetch filter \
1285                 ({filter}), which no approval widens"
1286            ));
1287        }
1288        None
1289    }
1290
1291    /// Why an unsandboxed retry is refused, or `None` when its `retry_of` is valid
1292    /// (spec 3.1 §7.9, §9.2 I25).
1293    async fn retry_refusal(&self, request: &ToolPolicyRequest) -> Option<String> {
1294        if !self.inner.shell.allow_unsandboxed_retry {
1295            return Some("unsandboxed retries are turned off for this harness".to_string());
1296        }
1297        if self.inner.shell.status.behaves_as_host() {
1298            return Some(
1299                "the shell already runs on the host; there is no sandboxed call to retry".into(),
1300            );
1301        }
1302        let Some(retry_of) = request.args.get("retry_of").and_then(Value::as_str) else {
1303            return Some(
1304                "an unsandboxed command needs retry_of naming the failed sandboxed call".into(),
1305            );
1306        };
1307        if request.args.get("reason").and_then(Value::as_str).is_none_or(|r| r.trim().is_empty()) {
1308            return Some("an unsandboxed retry needs a reason".into());
1309        }
1310        let command = request.args.get("command").and_then(Value::as_str).unwrap_or_default();
1311        match self
1312            .inner
1313            .ledger
1314            .get(&request.app_name, &request.user_id, &request.session_id, retry_of)
1315            .await
1316        {
1317            Ok(Some(entry))
1318                if entry.sandboxed
1319                    && entry.failed()
1320                    && entry.command == command
1321                    && entry.retried_by.is_none() =>
1322            {
1323                None
1324            }
1325            Ok(Some(_)) => Some(format!(
1326                "retry_of '{retry_of}' is not a failed sandboxed call with this exact command that \
1327                 has not been retried"
1328            )),
1329            Ok(None) => Some(format!("retry_of '{retry_of}' names no bash call in this session")),
1330            Err(error) => Some(format!("the shell ledger is unavailable: {error}")),
1331        }
1332    }
1333
1334    /// The decision function of spec 3.1 §7.4.
1335    ///
1336    /// `origin` is the called tool's [`ToolOrigin`] and `call_id` its function call ID, as
1337    /// the governed path passes them through `ToolPolicy::evaluate_call` (spec 3.1 §10 C1).
1338    /// Without an origin no Allow rule matches (Deny rules still do), so a direct
1339    /// `ToolPolicy::evaluate` holds a call a rule would allow, and the confirmation handler
1340    /// re-checks it against the request's origin.
1341    ///
1342    /// # Example
1343    ///
1344    /// ```rust,ignore
1345    /// let decision = policy.decide(&request, Some(&ToolOrigin::of(tool)), Some("call-1")).await;
1346    /// ```
1347    pub async fn decide(
1348        &self,
1349        request: &ToolPolicyRequest,
1350        origin: Option<&ToolOrigin>,
1351        call_id: Option<&str>,
1352    ) -> PolicyDecision {
1353        #[cfg(feature = "observe")]
1354        let span = crate::observe::decision_span(&request.tool_name, &self.inner.shell.status);
1355        #[cfg(feature = "observe")]
1356        let evaluated = {
1357            use tracing::Instrument as _;
1358            self.evaluate_full(request, origin, call_id, true).instrument(span.clone()).await
1359        };
1360        #[cfg(not(feature = "observe"))]
1361        let evaluated = self.evaluate_full(request, origin, call_id, true).await;
1362        #[cfg(feature = "observe")]
1363        {
1364            span.record("harness.tool_kind", crate::observe::tool_kind_label(&evaluated.kind));
1365            span.record("harness.mode", evaluated.mode.as_str());
1366            span.record("harness.decision", format!("{:?}", evaluated.decision).as_str());
1367            if request.agent_name != self.inner.root_agent {
1368                span.record("harness.member", request.agent_name.as_str());
1369            }
1370        }
1371        if evaluated.kind == ToolKind::ShellEscalation {
1372            crate::shell::record_retry_requested(
1373                self.audit_for(request),
1374                self.inner.ledger.as_ref(),
1375                request,
1376                call_id,
1377                &evaluated.decision,
1378            )
1379            .await;
1380        }
1381        evaluated.decision
1382    }
1383
1384    /// The decision function with the class, mode and table decision it reached.
1385    /// `governed` marks the evaluation of the governed path, which records stale and
1386    /// expired rules and remembers a held call's context for the confirmation handler; the
1387    /// handler's re-check passes `false`, so nothing is recorded twice.
1388    pub(crate) async fn evaluate_full(
1389        &self,
1390        request: &ToolPolicyRequest,
1391        origin: Option<&ToolOrigin>,
1392        call_id: Option<&str>,
1393        governed: bool,
1394    ) -> Evaluated {
1395        let kind = self.classify(request, origin);
1396        let deny = |decision: PolicyDecision, mode: HarnessMode| Evaluated {
1397            rule: None,
1398            decision,
1399            kind,
1400            mode,
1401            base: TableDecision::Deny,
1402        };
1403        if let Some(reason) = self.hard_deny(request, origin, &kind).await {
1404            return deny(PolicyDecision::deny(reason), self.inner.default_mode);
1405        }
1406        let (mode, plan_exited) = self
1407            .mode_and_plan_exit(
1408                &request.app_name,
1409                &request.user_id,
1410                &request.session_id,
1411                &request.invocation_id,
1412            )
1413            .await;
1414        if kind == ToolKind::PlanExit && plan_exited {
1415            // The approved mode applies from the next invocation; a second plan exit in this
1416            // one would only ask the person again.
1417            return deny(
1418                PolicyDecision::deny(
1419                    "the plan was already approved in this turn; the new mode applies from the \
1420                     user's next message, so end your turn now",
1421                ),
1422                mode,
1423            );
1424        }
1425        // Without authenticated identity on a served harness, Auto decides as Ask and no
1426        // standing rule applies (spec 3.1 §9.2 I6).
1427        #[cfg(feature = "auth")]
1428        let identity_inert = self.inner.identity.inert(&request.invocation_id);
1429        #[cfg(not(feature = "auth"))]
1430        let identity_inert = false;
1431        let mode =
1432            if identity_inert && mode == HarnessMode::Auto { HarnessMode::Ask } else { mode };
1433        if let Some(reason) = self.inner.registry.denial_in_mode(
1434            &request.agent_name,
1435            &request.tool_name,
1436            origin,
1437            &request.args,
1438            mode,
1439        ) {
1440            return deny(PolicyDecision::deny(reason), mode);
1441        }
1442        // Decided on the target the write reaches, so a symlink inside the workspace does not
1443        // turn a protected file into an ordinary edit (I11, I29).
1444        // Every path the call writes: an `apply_patch` with a protected path anywhere is the
1445        // protected row (spec 3.1 §7.26, I67).
1446        let paths = crate::edits::edit_paths(&request.tool_name, &request.args).unwrap_or_default();
1447        let protected_path = paths
1448            .iter()
1449            .find(|path| is_protected_target(self.inner.workspace.root(), path))
1450            .filter(|_| kind == ToolKind::Edit);
1451        let protected = protected_path.is_some();
1452        let row = TableRow::of(&kind, protected);
1453        let mut switches = self.inner.switches;
1454        // Unapproved sandboxed commands need every protected path in place at this call (I26),
1455        // unless the enforcer keeps a missing or symlinked one from being created or replaced.
1456        if matches!(row, TableRow::ShellOsSandbox | TableRow::ShellContainer)
1457            && switches.sandbox_protects_paths
1458            && !(row == TableRow::ShellOsSandbox && self.inner.shell.guards_protected_names)
1459        {
1460            switches.sandbox_protects_paths =
1461                crate::shell::protected_paths_hold(self.inner.workspace.root());
1462        }
1463        let base = decision_cell(mode, row).resolve(&switches);
1464        let mut reason = describe(&request.tool_name, row, mode, base);
1465        if let Some(path) = protected_path {
1466            if is_protected_path(path) {
1467                if paths.len() > 1 {
1468                    reason.push_str(&format!(" ({path} is protected)"));
1469                }
1470            } else {
1471                reason
1472                    .push_str(&format!(" ({path} resolves through a symlink to a protected path)"));
1473            }
1474        }
1475        if base == TableDecision::Deny {
1476            return deny(PolicyDecision::deny(reason), mode);
1477        }
1478        // 4a: the PreTool hooks may add a Deny and nothing else (spec 3.1 §7.22, §9.2 I53).
1479        // Only the governed evaluation runs them; the handler's re-check does not.
1480        #[cfg(feature = "hooks")]
1481        if governed && let Some(hooks) = &self.inner.hooks {
1482            let scope = crate::hooks::HookScope::from_request(request, call_id);
1483            let class = crate::hooks::class_label(&kind);
1484            let verdict = hooks
1485                .pre_tool(
1486                    &crate::hooks::HookCall {
1487                        tool: &request.tool_name,
1488                        args: &request.args,
1489                        class: &class,
1490                        acting: request.acting.as_ref(),
1491                        function_call_id: call_id,
1492                    },
1493                    mode,
1494                    &scope,
1495                    self.audit_for(request).as_ref(),
1496                )
1497                .await;
1498            if let crate::hooks::PreToolVerdict::Deny { reason: hook_reason } = verdict {
1499                return deny(
1500                    PolicyDecision::deny(format!("denied by a hook: {hook_reason}")),
1501                    mode,
1502                );
1503            }
1504        }
1505
1506        let mut matched_rules = Vec::new();
1507        let evaluation = if kind.rule_eligible() && !identity_inert {
1508            match self
1509                .inner
1510                .rules
1511                .rules_for(&request.app_name, &request.user_id, &request.session_id)
1512                .await
1513            {
1514                Ok(rules) => {
1515                    let call = RuleCall {
1516                        app_name: &request.app_name,
1517                        user_id: &request.user_id,
1518                        session_id: &request.session_id,
1519                        acting: request.acting.as_ref(),
1520                        tool_name: &request.tool_name,
1521                        args: &request.args,
1522                        origin,
1523                        kind,
1524                        workspace_root: self.inner.workspace.root(),
1525                    };
1526                    let evaluation = evaluate_standing_rules(&rules, &call, Utc::now());
1527                    matched_rules = rules;
1528                    evaluation
1529                }
1530                Err(error) => {
1531                    tracing::warn!(error = %error, "standing rules unavailable; asking instead");
1532                    return Evaluated {
1533                        rule: None,
1534                        decision: PolicyDecision::require_approval(format!(
1535                            "{reason}; standing rules are unavailable"
1536                        )),
1537                        kind,
1538                        mode,
1539                        base: TableDecision::RequireApproval { non_waivable: true },
1540                    };
1541                }
1542            }
1543        } else {
1544            RuleEvaluation::default()
1545        };
1546        if governed {
1547            self.record_rule_observations(request, &evaluation).await;
1548        }
1549
1550        let decision = apply_rule(base, &evaluation.outcome, &reason);
1551        let mut rule_hit = None;
1552        if let (PolicyDecision::Allow, RuleOutcome::Allow { rule_id }) =
1553            (&decision, &evaluation.outcome)
1554            && base != TableDecision::Allow
1555        {
1556            tracing::Span::current().record("harness.rule_id", rule_id.as_str());
1557            if let Some(rule) = matched_rules.iter().find(|rule| rule.id == *rule_id) {
1558                let number = match self.inner.rules.list(&request.app_name, &request.user_id).await
1559                {
1560                    Ok(mut all) => {
1561                        all.sort_by_key(|rule| rule.created_at);
1562                        all.iter().position(|listed| listed.id == rule.id).map(|index| index + 1)
1563                    }
1564                    Err(_) => None,
1565                };
1566                let mut hit = crate::approvals::RuleHit::new(
1567                    rule.id.clone(),
1568                    number,
1569                    request.tool_name.clone(),
1570                    rule.label.clone(),
1571                );
1572                hit.function_call_id = call_id.map(str::to_string);
1573                rule_hit = Some(hit);
1574            }
1575            tracing::info!(
1576                tool.name = %request.tool_name,
1577                harness.rule_id = %rule_id,
1578                harness.mode = %mode,
1579                "tool call allowed by a standing rule"
1580            );
1581            if let (Some(audit), Some(rule)) =
1582                (self.audit_for(request), matched_rules.iter().find(|rule| rule.id == *rule_id))
1583            {
1584                let rule_digest = crate::fsutil::hex_digest(
1585                    serde_json::to_string(rule).unwrap_or_default().as_bytes(),
1586                );
1587                let recorded = audit
1588                    .record_draft(
1589                        adk_core::audit_log::AuditRecordDraft::new(
1590                            adk_core::audit_log::AuditRecordKind::Other(
1591                                crate::audit::HARNESS_AUDIT_KIND.to_string(),
1592                            ),
1593                            "harness.rule.matched",
1594                        )
1595                        .policy_ref(format!("tool_policy:{HARNESS_POLICY_REF}")),
1596                        json!({
1597                            "ruleId": rule_id,
1598                            "ruleDigest": rule_digest,
1599                            "tool": request.tool_name,
1600                            "toolSource": origin.map(|origin| origin.source.clone()),
1601                            "declarationDigest": origin.map(|origin| origin.declaration_digest.clone()),
1602                            "functionCallId": call_id,
1603                        }),
1604                    )
1605                    .await;
1606                if let Err(error) = recorded {
1607                    tracing::warn!(error = %error, "could not record harness.rule.matched");
1608                    return Evaluated {
1609                        rule: None,
1610                        decision: PolicyDecision::require_approval(format!(
1611                            "{reason}; the standing rule's audit record could not be written"
1612                        )),
1613                        kind,
1614                        mode,
1615                        base,
1616                    };
1617                }
1618            }
1619        }
1620        // Recorded for every call the harness does not deny: another layer of the run's
1621        // policy, or the agent's confirmation policy, can still hold a call the harness
1622        // allows, and the handler must then ask the person rather than refuse.
1623        if governed && !matches!(decision, PolicyDecision::Deny { .. }) {
1624            let subject = request
1625                .acting
1626                .as_ref()
1627                .and_then(|acting| acting.on_behalf_of.as_ref())
1628                .map_or(request.user_id.as_str(), |subject| subject.id.as_str());
1629            let agent = request
1630                .acting
1631                .as_ref()
1632                .map_or(request.agent_name.as_str(), |acting| acting.agent.id.as_str());
1633            self.inner.prompts.insert(
1634                call_id,
1635                call_key(agent, subject, &request.tool_name, &request.args),
1636                PromptContext {
1637                    harness_held: matches!(decision, PolicyDecision::RequireApproval { .. }),
1638                    peers: self.peers.clone(),
1639                    governance: self.governance.clone(),
1640                    app_name: request.app_name.clone(),
1641                    user_id: request.user_id.clone(),
1642                    session_id: request.session_id.clone(),
1643                    invocation_id: request.invocation_id.clone(),
1644                    agent_name: request.agent_name.clone(),
1645                    effect: request.effect,
1646                    acting: request.acting.clone(),
1647                    audit: self.audit.clone(),
1648                },
1649            );
1650        }
1651        // A call a rule allows runs without a prompt; the person is told (spec 3.1 §7.33
1652        // fix 3). The handler's re-check reports its own hits.
1653        if governed && let (Some(hit), Some(observer)) = (&rule_hit, self.inner.rule_observer.get())
1654        {
1655            observer.rule_applied(hit);
1656        }
1657        Evaluated { decision, kind, mode, base, rule: rule_hit }
1658    }
1659
1660    async fn record_rule_observations(
1661        &self,
1662        request: &ToolPolicyRequest,
1663        evaluation: &RuleEvaluation,
1664    ) {
1665        if evaluation.stale.is_empty() && evaluation.expired.is_empty() {
1666            return;
1667        }
1668        for stale in &evaluation.stale {
1669            tracing::info!(
1670                harness.rule_id = %stale.rule_id,
1671                tool.name = %request.tool_name,
1672                "standing rule is stale: the tool's declaration changed"
1673            );
1674        }
1675        let Some(audit) = self.audit_for(request) else {
1676            return;
1677        };
1678        for stale in &evaluation.stale {
1679            let record = audit
1680                .record(
1681                    "harness.rule.stale",
1682                    json!({
1683                        "ruleId": stale.rule_id,
1684                        "subject": request.user_id,
1685                        "app": request.app_name,
1686                        "tool": request.tool_name,
1687                        "source": stale.pinned_source,
1688                        "declarationDigest": stale.pinned_digest,
1689                        "observedSource": stale.observed_source,
1690                        "observedDigest": stale.observed_digest,
1691                    }),
1692                )
1693                .await;
1694            if let Err(error) = record {
1695                tracing::warn!(error = %error, "could not record harness.rule.stale");
1696            }
1697        }
1698        for rule_id in &evaluation.expired {
1699            if let Err(error) = audit
1700                .record(
1701                    "harness.rule.expired",
1702                    json!({ "ruleId": rule_id, "subject": request.user_id, "app": request.app_name, "tool": request.tool_name }),
1703                )
1704                .await
1705            {
1706                tracing::warn!(error = %error, "could not record harness.rule.expired");
1707            }
1708        }
1709    }
1710
1711    pub(crate) fn prompts(&self) -> &PromptContexts {
1712        &self.inner.prompts
1713    }
1714
1715    pub(crate) fn workspace(&self) -> &Workspace {
1716        &self.inner.workspace
1717    }
1718
1719    pub(crate) fn isolation_status(&self) -> &IsolationStatus {
1720        &self.inner.shell.status
1721    }
1722}
1723
1724/// Anthropic's and OpenAI's provider-executed shell built-ins (spec 3.1 §9.2 I27).
1725fn is_provider_shell_builtin(name: &str) -> bool {
1726    name.starts_with("bash_")
1727        || name == "local_shell"
1728        || name == "shell"
1729        || name.starts_with("code_execution")
1730}
1731
1732fn describe(tool: &str, row: TableRow, mode: HarnessMode, base: TableDecision) -> String {
1733    let class = match row {
1734        TableRow::ReadTodoDelegate => "a read",
1735        TableRow::PlanExit => "the plan exit",
1736        TableRow::Edit => "an edit",
1737        TableRow::EditProtected => "an edit of a protected path",
1738        TableRow::ShellOsSandbox => "a sandboxed shell command",
1739        TableRow::ShellContainer => "a container shell command",
1740        TableRow::ShellHost => "a host shell command (full user permissions, network)",
1741        TableRow::ShellEscalation => "an unsandboxed retry",
1742        TableRow::MemoryWrite => "a memory write",
1743        TableRow::MemoryPropose => "a fact proposal",
1744        TableRow::WebAllowlisted => "a web request to an allowlisted host",
1745        TableRow::WebOther => "a web request to a host outside the allowlist",
1746        TableRow::Payment => "a payment",
1747        TableRow::ComputerUse => "a desktop action",
1748        TableRow::ExternalReadOnlyTrusted => "a trusted read-only tool",
1749        TableRow::ExternalOther => "an external tool",
1750    };
1751    match base {
1752        TableDecision::Deny => format!("'{tool}' is {class}, which {mode} mode does not allow"),
1753        TableDecision::RequireApproval { .. } => {
1754            format!("'{tool}' is {class}, which needs approval in {mode} mode")
1755        }
1756        TableDecision::Allow => format!("'{tool}' is {class}, allowed in {mode} mode"),
1757    }
1758}
1759
1760#[async_trait]
1761impl ToolPolicy for HarnessPolicy {
1762    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
1763        self.evaluate_call(request, &PolicyCall::new()).await
1764    }
1765
1766    async fn evaluate_call(
1767        &self,
1768        request: &ToolPolicyRequest,
1769        call: &PolicyCall<'_>,
1770    ) -> PolicyDecision {
1771        self.decide(request, call.origin, call.function_call_id).await
1772    }
1773
1774    fn policy_ref(&self) -> Option<String> {
1775        Some(HARNESS_POLICY_REF.to_string())
1776    }
1777}
1778
1779/// Auto review: the harness's reviewer, asked only about a call the harness itself holds
1780/// in Auto mode that a standing rule could answer (autonomy parity item 2).
1781///
1782/// A call that is non-waivable — by the table, by tool name, or by a protected path in its
1783/// arguments — and every call in another mode, including Auto decided as Ask without
1784/// authenticated identity, is left to a person without a verdict.
1785pub(crate) struct AutoReview {
1786    inner: Arc<dyn adk_core::ToolReviewer>,
1787    policy: HarnessPolicy,
1788    non_waivable_tools: BTreeSet<String>,
1789    non_waivable_prefixes: Vec<String>,
1790    root: std::path::PathBuf,
1791}
1792
1793impl std::fmt::Debug for AutoReview {
1794    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1795        f.debug_struct("AutoReview").field("inner", &self.inner).finish_non_exhaustive()
1796    }
1797}
1798
1799impl AutoReview {
1800    pub(crate) fn new(
1801        inner: Arc<dyn adk_core::ToolReviewer>,
1802        policy: HarnessPolicy,
1803        non_waivable_tools: BTreeSet<String>,
1804        non_waivable_prefixes: Vec<String>,
1805        root: std::path::PathBuf,
1806    ) -> Self {
1807        Self { inner, policy, non_waivable_tools, non_waivable_prefixes, root }
1808    }
1809}
1810
1811#[async_trait]
1812impl adk_core::ToolReviewer for AutoReview {
1813    fn reviewer(&self) -> adk_core::principal::SubjectRef {
1814        self.inner.reviewer()
1815    }
1816
1817    fn timeout(&self) -> std::time::Duration {
1818        self.inner.timeout()
1819    }
1820
1821    async fn covers(&self, review: &adk_core::ToolReview) -> bool {
1822        if crate::agent::names_non_waivable(
1823            &review.fingerprint,
1824            &self.non_waivable_tools,
1825            &self.non_waivable_prefixes,
1826            &self.root,
1827        ) {
1828            return false;
1829        }
1830        let mut request =
1831            ToolPolicyRequest::new(review.request.tool_name.clone(), review.request.args.clone())
1832                .with_effect(review.effect)
1833                .with_agent_name(review.agent_name.clone())
1834                .with_identity(
1835                    review.scope.app_name.clone(),
1836                    review.scope.user_id.clone(),
1837                    review.scope.session_id.clone(),
1838                )
1839                .with_invocation_id(review.invocation_id.clone());
1840        request.acting = review.request.acting.as_deref().cloned();
1841        // The re-check records nothing and runs no hooks, as the prompting handler's does.
1842        let evaluated = self
1843            .policy
1844            .evaluate_full(
1845                &request,
1846                review.request.origin.as_ref(),
1847                review.request.function_call_id.as_deref(),
1848                false,
1849            )
1850            .await;
1851        evaluated.mode == HarnessMode::Auto
1852            && matches!(evaluated.decision, PolicyDecision::RequireApproval { .. })
1853            && !evaluated.base.is_non_waivable()
1854            && self.inner.covers(review).await
1855    }
1856
1857    async fn review(
1858        &self,
1859        review: &adk_core::ToolReview,
1860    ) -> adk_core::Result<adk_core::ReviewVerdict> {
1861        self.inner.review(review).await
1862    }
1863}
1864
1865#[cfg(all(test, feature = "sandbox"))]
1866mod tests {
1867    use std::sync::Arc;
1868
1869    use adk_core::ToolPolicyRequest;
1870    use adk_model::{ScriptedLlm, ScriptedResponse};
1871    use serde_json::json;
1872
1873    use crate::{HarnessAgent, InstructionsConfig, Preset, ShellIsolation};
1874
1875    /// Review of #1045, finding 5 (#1032 findings 3 and 5): on any host, enforcer or not, the
1876    /// personal preset's policy refuses an unsandboxed retry as turned off, even when the
1877    /// builder asks for the retry after the preset.
1878    #[tokio::test]
1879    async fn the_personal_preset_turns_the_unsandboxed_retry_off() {
1880        let dir = tempfile::tempdir().unwrap();
1881        let agent = HarnessAgent::builder("assistant")
1882            .preset(Preset::Personal)
1883            .shell(ShellIsolation::OsSandbox(Default::default()))
1884            .allow_unsandboxed_retry(true)
1885            .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("ok")])))
1886            .workspace(adk_devtools::Workspace::new(dir.path()).allow_bash(true))
1887            .project_instructions(InstructionsConfig {
1888                user_file: None,
1889                ..InstructionsConfig::default()
1890            })
1891            .build()
1892            .unwrap();
1893        let retry = ToolPolicyRequest::new(
1894            "bash",
1895            json!({ "command": "ls", "unsandboxed": true, "retry_of": "1", "reason": "denied" }),
1896        );
1897        assert_eq!(
1898            agent.runtime().policy.retry_refusal(&retry).await.as_deref(),
1899            Some("unsandboxed retries are turned off for this harness")
1900        );
1901    }
1902}