Skip to main content

adk_harness/approvals/
rule.rs

1//! Standing rules: "don't ask again" decisions bound to a subject and a tool declaration
2//! (spec 3.1 §7.5).
3
4use std::collections::BTreeMap;
5
6use adk_core::principal::{SubjectKind, SubjectRef};
7use adk_core::{ArgPredicate, STATIC_TOOL_ORIGIN, ToolConfirmationRequest, ToolOrigin};
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use super::matcher::{is_protected_path, plain_shell_words};
13
14/// Who a [`StandingRule`] belongs to (spec 3.1 §7.5).
15///
16/// A rule never applies to another subject, another app, or a subject of another kind,
17/// so a person's rule never applies to a `Service` run.
18///
19/// # Example
20///
21/// ```rust
22/// use adk_core::principal::SubjectKind;
23/// use adk_harness::RuleScope;
24///
25/// let scope = RuleScope::User {
26///     app_name: "adk-rust".into(),
27///     user_id: "alice".into(),
28///     subject_kind: SubjectKind::Human,
29/// };
30/// assert_eq!(scope.user_id(), "alice");
31/// assert_eq!(scope.session_id(), None);
32/// ```
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
35pub enum RuleScope {
36    /// Every session of the user in the app.
37    #[serde(rename_all = "camelCase")]
38    User {
39        /// Application name.
40        app_name: String,
41        /// The subject the rule belongs to.
42        user_id: String,
43        /// The subject's kind.
44        subject_kind: SubjectKind,
45    },
46    /// One session of the user.
47    #[serde(rename_all = "camelCase")]
48    Session {
49        /// Application name.
50        app_name: String,
51        /// The subject the rule belongs to.
52        user_id: String,
53        /// The subject's kind.
54        subject_kind: SubjectKind,
55        /// The session.
56        session_id: String,
57    },
58}
59
60impl RuleScope {
61    /// The application the rule belongs to.
62    pub fn app_name(&self) -> &str {
63        match self {
64            Self::User { app_name, .. } | Self::Session { app_name, .. } => app_name,
65        }
66    }
67
68    /// The subject the rule belongs to.
69    pub fn user_id(&self) -> &str {
70        match self {
71            Self::User { user_id, .. } | Self::Session { user_id, .. } => user_id,
72        }
73    }
74
75    /// The subject's kind.
76    pub fn subject_kind(&self) -> SubjectKind {
77        match self {
78            Self::User { subject_kind, .. } | Self::Session { subject_kind, .. } => *subject_kind,
79        }
80    }
81
82    /// The session, for a session-scoped rule.
83    pub fn session_id(&self) -> Option<&str> {
84        match self {
85            Self::User { .. } => None,
86            Self::Session { session_id, .. } => Some(session_id),
87        }
88    }
89}
90
91/// The tool declaration a [`StandingRule`] is bound to (spec 3.1 §7.5, §9.2 I8).
92///
93/// # Example
94///
95/// ```rust
96/// use adk_core::ToolOrigin;
97/// use adk_harness::OriginPin;
98/// use serde_json::json;
99///
100/// let origin = ToolOrigin::new("static", &json!({ "name": "bash" }), None);
101/// let pin = OriginPin::exact(&origin);
102/// assert!(pin.admits(&origin));
103/// assert!(!pin.admits(&ToolOrigin::new("static", &json!({ "name": "bash", "x": 1 }), None)));
104/// ```
105#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
107pub enum OriginPin {
108    /// One publisher and one declaration digest; the rule dies when the declaration changes.
109    #[serde(rename_all = "camelCase")]
110    Exact {
111        /// [`ToolOrigin::source`].
112        source: String,
113        /// [`ToolOrigin::declaration_digest`].
114        declaration_digest: String,
115    },
116    /// Any declaration from one publisher. Operator-only: suggestions never produce it.
117    #[serde(rename_all = "camelCase")]
118    AnyDeclaration {
119        /// [`ToolOrigin::source`].
120        source: String,
121    },
122    /// One publisher and one exact declaration for each tool it names: the file-writing
123    /// tools of a folder rule (spec 3.3 §8.2 "Always allow for this folder"). A call is
124    /// covered only through its own tool's declaration, so the rule stops covering a tool
125    /// whose declaration changes, as an [`Exact`](Self::Exact) pin does.
126    #[serde(rename_all = "camelCase")]
127    ExactEach {
128        /// [`ToolOrigin::source`].
129        source: String,
130        /// Each tool's [`ToolOrigin::declaration_digest`], by tool name.
131        declarations: BTreeMap<String, String>,
132    },
133}
134
135impl OriginPin {
136    /// A pin to exactly `origin`.
137    pub fn exact(origin: &ToolOrigin) -> Self {
138        Self::Exact {
139            source: origin.source.clone(),
140            declaration_digest: origin.declaration_digest.clone(),
141        }
142    }
143
144    /// Whether a call to a tool with `origin` is covered by the pin.
145    pub fn admits(&self, origin: &ToolOrigin) -> bool {
146        match self {
147            Self::Exact { source, declaration_digest } => {
148                *source == origin.source && *declaration_digest == origin.declaration_digest
149            }
150            Self::AnyDeclaration { source } => *source == origin.source,
151            // The digest covers the declaration's name, so it names the tool as well.
152            Self::ExactEach { source, declarations } => {
153                *source == origin.source
154                    && declarations.values().any(|digest| *digest == origin.declaration_digest)
155            }
156        }
157    }
158
159    /// The pinned publisher.
160    pub fn source(&self) -> &str {
161        match self {
162            Self::Exact { source, .. }
163            | Self::AnyDeclaration { source }
164            | Self::ExactEach { source, .. } => source,
165        }
166    }
167}
168
169/// A serializable mirror of [`ArgPredicate`] for stored rules (spec 3.1 §7.5).
170///
171/// # Example
172///
173/// ```rust
174/// use adk_harness::ArgSpec;
175/// use serde_json::json;
176///
177/// let spec = ArgSpec::Equals { pointer: "/unsandboxed".into(), value: json!(true) };
178/// assert!(spec.holds(&json!({ "unsandboxed": true })));
179/// assert_eq!(serde_json::to_value(&spec).unwrap()["equals"]["pointer"], "/unsandboxed");
180/// ```
181#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase", deny_unknown_fields)]
183pub enum ArgSpec {
184    /// See [`ArgPredicate::Equals`].
185    #[serde(rename_all = "camelCase")]
186    Equals {
187        /// JSON pointer to the argument.
188        pointer: String,
189        /// The required value.
190        value: Value,
191    },
192    /// See [`ArgPredicate::InSet`].
193    #[serde(rename_all = "camelCase")]
194    InSet {
195        /// JSON pointer to the argument.
196        pointer: String,
197        /// The permitted values.
198        values: Vec<Value>,
199    },
200    /// See [`ArgPredicate::AtMost`].
201    #[serde(rename_all = "camelCase")]
202    AtMost {
203        /// JSON pointer to the argument.
204        pointer: String,
205        /// The largest permitted value.
206        max: f64,
207    },
208    /// See [`ArgPredicate::StartsWith`].
209    #[serde(rename_all = "camelCase")]
210    StartsWith {
211        /// JSON pointer to the argument.
212        pointer: String,
213        /// The required prefix.
214        prefix: String,
215    },
216    /// See [`ArgPredicate::DomainIn`].
217    #[serde(rename_all = "camelCase")]
218    DomainIn {
219        /// JSON pointer to the argument.
220        pointer: String,
221        /// The permitted hosts.
222        domains: Vec<String>,
223    },
224}
225
226impl ArgSpec {
227    /// The core predicate this mirrors.
228    pub fn to_predicate(&self) -> ArgPredicate {
229        match self {
230            Self::Equals { pointer, value } => ArgPredicate::equals(pointer.clone(), value.clone()),
231            Self::InSet { pointer, values } => {
232                ArgPredicate::in_set(pointer.clone(), values.iter().cloned())
233            }
234            Self::AtMost { pointer, max } => ArgPredicate::at_most(pointer.clone(), *max),
235            Self::StartsWith { pointer, prefix } => {
236                ArgPredicate::starts_with(pointer.clone(), prefix.clone())
237            }
238            Self::DomainIn { pointer, domains } => {
239                ArgPredicate::domain_in(pointer.clone(), domains.iter().cloned())
240            }
241        }
242    }
243
244    /// Whether the predicate holds for `args`.
245    pub fn holds(&self, args: &Value) -> bool {
246        self.to_predicate().holds(args)
247    }
248}
249
250impl From<ArgSpec> for ArgPredicate {
251    fn from(spec: ArgSpec) -> Self {
252        spec.to_predicate()
253    }
254}
255
256/// One condition of a [`StandingRule`] (spec 3.1 §7.5).
257///
258/// # Example
259///
260/// ```rust
261/// use adk_harness::RulePredicate;
262/// use serde_json::json;
263///
264/// let prefix = RulePredicate::ShellPrefix {
265///     pointer: "/command".into(),
266///     tokens: vec!["cargo".into(), "test".into()],
267/// };
268/// assert_eq!(serde_json::to_value(&prefix).unwrap()["shellPrefix"]["tokens"][1], "test");
269/// ```
270#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
271#[serde(rename_all = "camelCase", deny_unknown_fields)]
272pub enum RulePredicate {
273    /// An argument predicate.
274    Arg(ArgSpec),
275    /// The command at `pointer` tokenizes to plain words whose first tokens are `tokens`.
276    #[serde(rename_all = "camelCase")]
277    ShellPrefix {
278        /// JSON pointer to the command.
279        pointer: String,
280        /// The required leading tokens.
281        tokens: Vec<String>,
282    },
283    /// The path at `pointer`, resolved against the workspace root, lies within `dir` and is
284    /// not a protected path.
285    #[serde(rename_all = "camelCase")]
286    PathWithin {
287        /// JSON pointer to the path.
288        pointer: String,
289        /// Directory relative to the workspace root; `.` is the root.
290        dir: String,
291    },
292    /// The call only writes files — `write_file`, `edit_file`, or an `apply_patch` that adds
293    /// files or updates them in place — and every path it writes lies within `dir` and is
294    /// not protected, each resolved as `PathWithin` resolves its path. A delete or a move
295    /// never holds (spec 3.3 §8.2 "Always allow for this folder").
296    #[serde(rename_all = "camelCase")]
297    WritesWithin {
298        /// Directory relative to the workspace root; `.` is the root.
299        dir: String,
300    },
301}
302
303/// What a [`StandingRule`] decides (spec 3.1 §7.5).
304///
305/// # Example
306///
307/// ```rust
308/// use adk_harness::StandingDecision;
309///
310/// assert_eq!(serde_json::to_value(StandingDecision::Allow).unwrap()["kind"], "allow");
311/// ```
312#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(tag = "kind", rename_all = "camelCase", try_from = "RawDecision")]
314pub enum StandingDecision {
315    /// Calls the rule covers run without approval where the mode would ask.
316    Allow,
317    /// Calls the rule covers are refused.
318    Deny {
319        /// Reported to the model.
320        reason: String,
321    },
322}
323
324/// The wire form of [`StandingDecision`], parsed strictly: serde ignores unknown fields
325/// on unit variants of internally tagged enums, and a rule with unknown fields must not
326/// parse (spec 3.1 §9.2 I16).
327#[derive(Deserialize)]
328#[serde(deny_unknown_fields)]
329struct RawDecision {
330    kind: String,
331    #[serde(default)]
332    reason: Option<String>,
333}
334
335impl TryFrom<RawDecision> for StandingDecision {
336    type Error = String;
337
338    fn try_from(raw: RawDecision) -> std::result::Result<Self, Self::Error> {
339        match (raw.kind.as_str(), raw.reason) {
340            ("allow", None) => Ok(Self::Allow),
341            ("deny", Some(reason)) => Ok(Self::Deny { reason }),
342            (kind, _) => Err(format!("unknown standing decision '{kind}'")),
343        }
344    }
345}
346
347/// A standing approval or denial (spec 3.1 §7.5).
348///
349/// Created only by an authenticated human action (spec 3.1 §9.2 I2). A rule with fields
350/// this release does not know fails to parse and is ignored (I16).
351///
352/// # Example
353///
354/// ```rust
355/// use adk_core::principal::{SubjectKind, SubjectRef};
356/// use adk_core::ToolOrigin;
357/// use adk_harness::{OriginPin, RulePredicate, RuleScope, StandingDecision, StandingRule};
358/// use serde_json::json;
359///
360/// let rule = StandingRule {
361///     id: "r1".into(),
362///     scope: RuleScope::User {
363///         app_name: "adk-rust".into(),
364///         user_id: "alice".into(),
365///         subject_kind: SubjectKind::Human,
366///     },
367///     tool: "bash".into(),
368///     origin: OriginPin::exact(&ToolOrigin::new("static", &json!({ "name": "bash" }), None)),
369///     agent: None,
370///     predicates: vec![RulePredicate::ShellPrefix {
371///         pointer: "/command".into(),
372///         tokens: vec!["cargo".into(), "test".into()],
373///     }],
374///     decision: StandingDecision::Allow,
375///     created_by: SubjectRef::human("alice"),
376///     created_at: chrono::Utc::now(),
377///     expires_at: None,
378///     label: "cargo test".into(),
379///     source_fingerprint: None,
380/// };
381/// let json = serde_json::to_value(&rule).unwrap();
382/// assert_eq!(serde_json::from_value::<StandingRule>(json).unwrap(), rule);
383/// ```
384#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
385#[serde(rename_all = "camelCase", deny_unknown_fields)]
386pub struct StandingRule {
387    /// Unique id.
388    pub id: String,
389    /// Who the rule belongs to.
390    pub scope: RuleScope,
391    /// Tool-name glob (`*` any run, `?` one character).
392    pub tool: String,
393    /// The declaration the rule is bound to.
394    pub origin: OriginPin,
395    /// Acting-agent id glob; `None` matches any agent.
396    #[serde(default)]
397    pub agent: Option<String>,
398    /// Every predicate must hold.
399    #[serde(default)]
400    pub predicates: Vec<RulePredicate>,
401    /// What the rule decides.
402    pub decision: StandingDecision,
403    /// The human who created it.
404    pub created_by: SubjectRef,
405    /// When it was created.
406    pub created_at: DateTime<Utc>,
407    /// When it stops applying.
408    #[serde(default)]
409    pub expires_at: Option<DateTime<Utc>>,
410    /// Shown in rule listings.
411    pub label: String,
412    /// Fingerprint of the call the rule was created from, if any.
413    #[serde(default)]
414    pub source_fingerprint: Option<String>,
415}
416
417/// Commands that a shell-prefix suggestion never starts with: each runs an arbitrary
418/// command of its own (spec 3.1 §7.5).
419///
420/// # Example
421///
422/// ```rust
423/// assert!(adk_harness::SHELL_PREFIX_SUGGESTION_DENYLIST.contains(&"sudo"));
424/// ```
425pub const SHELL_PREFIX_SUGGESTION_DENYLIST: &[&str] =
426    &["sh", "bash", "env", "xargs", "eval", "exec", "sudo", "nohup"];
427
428/// The scope a [`RuleSuggestion`] proposes (spec 3.1 §7.5).
429///
430/// # Example
431///
432/// ```rust
433/// assert_eq!(serde_json::to_value(adk_harness::SuggestedScope::User).unwrap(), "user");
434/// ```
435#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
436#[serde(rename_all = "camelCase")]
437pub enum SuggestedScope {
438    /// Every session of the user.
439    User,
440    /// This session only.
441    Session,
442}
443
444/// A rule a prompt offers to remember (spec 3.1 §7.5).
445///
446/// # Example
447///
448/// ```rust
449/// use adk_core::{ToolConfirmationRequest, ToolOrigin};
450/// use adk_harness::StandingRule;
451/// use serde_json::json;
452///
453/// let request = ToolConfirmationRequest::new("bash", json!({ "command": "cargo test --quiet" }))
454///     .with_origin(ToolOrigin::new("static", &json!({ "name": "bash" }), None));
455/// let labels: Vec<_> =
456///     StandingRule::suggestions(&request).into_iter().map(|s| s.label).collect();
457/// assert_eq!(labels, ["bash: cargo test …", "bash: cargo …"]);
458/// ```
459#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
460#[serde(rename_all = "camelCase")]
461pub struct RuleSuggestion {
462    /// What the rule matches, never its scope: surfaces render the scope from
463    /// [`scope`](Self::scope) (spec 3.1 §7.33 fix 1).
464    pub label: String,
465    /// Proposed scope.
466    pub scope: SuggestedScope,
467    /// Tool-name glob.
468    pub tool: String,
469    /// The declaration the rule binds to: [`OriginPin::Exact`], or for a folder rule
470    /// [`OriginPin::ExactEach`] over its file-writing tools.
471    pub origin: OriginPin,
472    /// Conditions.
473    pub predicates: Vec<RulePredicate>,
474    /// The matched commands run project scripts (`cargo test`, `npm test`, `make`), so the
475    /// rule allows whatever those scripts do.
476    pub runs_scripts: bool,
477}
478
479/// The owner and creator a remembered rule is recorded for (spec 3.1 §7.5).
480///
481/// # Example
482///
483/// ```rust
484/// use adk_core::principal::{SubjectKind, SubjectRef};
485/// use adk_harness::RuleOwner;
486///
487/// let owner = RuleOwner {
488///     app_name: "adk-rust".into(),
489///     user_id: "alice".into(),
490///     subject_kind: SubjectKind::Human,
491///     session_id: "s1".into(),
492///     created_by: SubjectRef::human("alice"),
493/// };
494/// # let _ = owner;
495/// ```
496#[derive(Clone, Debug, PartialEq, Eq)]
497pub struct RuleOwner {
498    /// Application name.
499    pub app_name: String,
500    /// The subject the rule belongs to.
501    pub user_id: String,
502    /// The subject's kind.
503    pub subject_kind: SubjectKind,
504    /// The session, used for session-scoped rules.
505    pub session_id: String,
506    /// The human creating the rule.
507    pub created_by: SubjectRef,
508}
509
510impl RuleSuggestion {
511    /// The rule this suggestion becomes when a person accepts it.
512    ///
513    /// # Example
514    ///
515    /// ```rust
516    /// use adk_core::principal::{SubjectKind, SubjectRef};
517    /// use adk_core::{ToolConfirmationRequest, ToolOrigin};
518    /// use adk_harness::{RuleOwner, StandingDecision, StandingRule};
519    /// use serde_json::json;
520    ///
521    /// let request = ToolConfirmationRequest::new("bash", json!({ "command": "make" }))
522    ///     .with_origin(ToolOrigin::new("static", &json!({ "name": "bash" }), None));
523    /// let suggestion = StandingRule::suggestions(&request).remove(0);
524    /// let owner = RuleOwner {
525    ///     app_name: "app".into(),
526    ///     user_id: "alice".into(),
527    ///     subject_kind: SubjectKind::Human,
528    ///     session_id: "s1".into(),
529    ///     created_by: SubjectRef::human("alice"),
530    /// };
531    /// let rule = suggestion.into_rule(&owner, StandingDecision::Allow, None);
532    /// assert_eq!(rule.scope.user_id(), "alice");
533    /// ```
534    pub fn into_rule(
535        self,
536        owner: &RuleOwner,
537        decision: StandingDecision,
538        source_fingerprint: Option<String>,
539    ) -> StandingRule {
540        let scope = match self.scope {
541            SuggestedScope::User => RuleScope::User {
542                app_name: owner.app_name.clone(),
543                user_id: owner.user_id.clone(),
544                subject_kind: owner.subject_kind,
545            },
546            SuggestedScope::Session => RuleScope::Session {
547                app_name: owner.app_name.clone(),
548                user_id: owner.user_id.clone(),
549                subject_kind: owner.subject_kind,
550                session_id: owner.session_id.clone(),
551            },
552        };
553        StandingRule {
554            id: uuid::Uuid::new_v4().to_string(),
555            scope,
556            tool: self.tool,
557            origin: self.origin,
558            agent: None,
559            predicates: self.predicates,
560            decision,
561            created_by: owner.created_by.clone(),
562            created_at: Utc::now(),
563            expires_at: None,
564            label: self.label,
565            source_fingerprint,
566        }
567    }
568}
569
570/// Names of the harness edit tools.
571pub(crate) const EDIT_TOOLS: &[&str] = &["write_file", "edit_file", "apply_patch"];
572
573/// Tools no standing rule ever covers (spec 3.1 §7.5).
574pub(crate) const NEVER_ELIGIBLE_TOOLS: &[&str] =
575    &["exit_plan_mode", "memory_write", "memory_delete"];
576
577/// Commands whose first tokens run project scripts.
578fn runs_scripts(tokens: &[&str]) -> bool {
579    let first = tokens.first().copied().unwrap_or_default();
580    let second = tokens.get(1).copied().unwrap_or_default();
581    match first {
582        "make" | "just" | "gradle" | "./gradlew" | "mvn" | "rake" | "tox" | "nox" => true,
583        "cargo" => !matches!(second, "fmt" | "metadata" | "tree" | "--version" | "search"),
584        "npm" | "pnpm" | "yarn" | "bun" => {
585            matches!(second, "test" | "run" | "start" | "install" | "ci" | "exec" | "build")
586        }
587        "npx" | "bunx" | "node" | "deno" | "python" | "python3" | "ruby" | "perl" | "go" => true,
588        other => other.contains('/'),
589    }
590}
591
592impl StandingRule {
593    /// Rules a prompt for `request` offers to remember (spec 3.1 §7.5).
594    ///
595    /// For `bash`, a `ShellPrefix` on the first two tokens and on the first token (user
596    /// scope), offered only for a command of plain words that does not start with a
597    /// command runner; for edits, `PathWithin` the workspace root or the file's directory
598    /// (session scope), never for a protected path; for any other tool, any arguments for
599    /// this tool pinned to its exact origin (user scope). Every suggestion pins the exact
600    /// declaration, so a request without an origin gets none. `exit_plan_mode`, memory
601    /// writes, payments and unsandboxed retries get none: they are never covered by rules.
602    ///
603    /// # Example
604    ///
605    /// ```rust
606    /// use adk_core::{ToolConfirmationRequest, ToolOrigin};
607    /// use adk_harness::StandingRule;
608    /// use serde_json::json;
609    ///
610    /// let origin = ToolOrigin::new("static", &json!({ "name": "bash" }), None);
611    /// let chained = ToolConfirmationRequest::new("bash", json!({ "command": "ls; rm -rf ~" }))
612    ///     .with_origin(origin.clone());
613    /// assert!(StandingRule::suggestions(&chained).is_empty());
614    /// let wrapped = ToolConfirmationRequest::new("bash", json!({ "command": "sudo ls" }))
615    ///     .with_origin(origin);
616    /// assert!(StandingRule::suggestions(&wrapped).is_empty());
617    /// ```
618    pub fn suggestions(request: &ToolConfirmationRequest) -> Vec<RuleSuggestion> {
619        let Some(origin) = request.origin.as_ref() else {
620            return Vec::new();
621        };
622        let name = request.tool_name.as_str();
623        if NEVER_ELIGIBLE_TOOLS.contains(&name) {
624            return Vec::new();
625        }
626        let pin = OriginPin::exact(origin);
627        let static_tool = origin.source == STATIC_TOOL_ORIGIN;
628        if name == "bash" && static_tool {
629            if request.args.get("unsandboxed").and_then(Value::as_bool) == Some(true) {
630                return Vec::new();
631            }
632            let Some(command) = request.args.get("command").and_then(Value::as_str) else {
633                return Vec::new();
634            };
635            let Some(words) = plain_shell_words(command) else {
636                return Vec::new();
637            };
638            let Some(first) = words.first() else {
639                return Vec::new();
640            };
641            if SHELL_PREFIX_SUGGESTION_DENYLIST.contains(first) {
642                return Vec::new();
643            }
644            let scripts = runs_scripts(&words);
645            let mut out = Vec::new();
646            for width in [2usize, 1] {
647                if words.len() < width {
648                    continue;
649                }
650                let tokens: Vec<String> = words[..width].iter().map(|w| (*w).to_string()).collect();
651                out.push(RuleSuggestion {
652                    label: format!("bash: {} …", tokens.join(" ")),
653                    scope: SuggestedScope::User,
654                    tool: "bash".into(),
655                    origin: pin.clone(),
656                    predicates: vec![RulePredicate::ShellPrefix {
657                        pointer: "/command".into(),
658                        tokens,
659                    }],
660                    runs_scripts: scripts,
661                });
662            }
663            return out;
664        }
665        // Web: the exact host the call named, never a wildcard the human did not type
666        // (spec 3.1 §7.5, §7.20); the browser pack's navigation is a web call too (§7.24).
667        if matches!(
668            name,
669            "web_fetch" | "browser_navigate" | "browser_new_tab" | "browser_new_window"
670        ) && static_tool
671        {
672            let Some(host) =
673                request.args.get("url").and_then(Value::as_str).and_then(crate::web::url_host)
674            else {
675                return Vec::new();
676            };
677            if crate::web::is_private_host(&host) {
678                return Vec::new();
679            }
680            return vec![RuleSuggestion {
681                label: format!("{name}: any page on {host}"),
682                scope: SuggestedScope::User,
683                tool: name.into(),
684                origin: pin,
685                predicates: vec![RulePredicate::Arg(ArgSpec::DomainIn {
686                    pointer: "/url".into(),
687                    domains: vec![host],
688                })],
689                runs_scripts: false,
690            }];
691        }
692        if name == "web_search" && static_tool {
693            let Some(site) = request.args.get("site").and_then(Value::as_str) else {
694                return Vec::new();
695            };
696            let Some(host) = crate::web::url_host(&format!("https://{site}/")) else {
697                return Vec::new();
698            };
699            return vec![RuleSuggestion {
700                label: format!("web_search: searches restricted to {host}"),
701                scope: SuggestedScope::User,
702                tool: "web_search".into(),
703                origin: pin,
704                predicates: vec![RulePredicate::Arg(ArgSpec::Equals {
705                    pointer: "/site".into(),
706                    value: Value::String(host),
707                })],
708                runs_scripts: false,
709            }];
710        }
711        if EDIT_TOOLS.contains(&name) && static_tool {
712            let Some(paths) = crate::edits::edit_paths(name, &request.args) else {
713                return Vec::new();
714            };
715            if paths.is_empty()
716                || paths.iter().any(|path| {
717                    is_protected_path(path) || path.split(['/', '\\']).any(|part| part == "..")
718                })
719            {
720                return Vec::new();
721            }
722            // `apply_patch` reads its paths from the patch; the others from `/path`.
723            let pointer = if name == crate::edits::APPLY_PATCH { "/patch" } else { "/path" };
724            let mut out = vec![RuleSuggestion {
725                label: format!("{name}: anywhere in the workspace"),
726                scope: SuggestedScope::Session,
727                tool: name.to_string(),
728                origin: pin.clone(),
729                predicates: vec![RulePredicate::PathWithin {
730                    pointer: pointer.into(),
731                    dir: ".".into(),
732                }],
733                runs_scripts: false,
734            }];
735            if let Some(dir) = shared_dir(&paths) {
736                out.push(RuleSuggestion {
737                    label: format!("{name}: within {dir}/"),
738                    scope: SuggestedScope::Session,
739                    tool: name.to_string(),
740                    origin: pin,
741                    predicates: vec![RulePredicate::PathWithin { pointer: pointer.into(), dir }],
742                    runs_scripts: false,
743                });
744            }
745            return out;
746        }
747        if static_tool && crate::policy::HARNESS_TOOL_NAMES.contains(&name) {
748            // Reads and todos never ask; nothing to remember.
749            return Vec::new();
750        }
751        vec![RuleSuggestion {
752            label: format!("{name}: any arguments from {}", origin.source),
753            scope: SuggestedScope::User,
754            tool: name.to_string(),
755            origin: pin,
756            predicates: Vec::new(),
757            runs_scripts: false,
758        }]
759    }
760
761    /// The rule "Always allow for this folder" makes for `request` (spec 3.3 §8.2): every file
762    /// write within the folder the call writes in — the workspace root for a file there or an
763    /// absolute path — by any of the harness's file-writing tools, `write_file`, `edit_file`
764    /// and `apply_patch`, each pinned to the declaration `origin_of` gives for it; scoped to
765    /// the session, as the edit suggestions are.
766    ///
767    /// `None` when the call is not one of those tools with that declaration, when it deletes
768    /// or moves a file, or when a path it writes is protected or climbs with `..`.
769    pub(crate) fn folder_suggestion(
770        request: &ToolConfirmationRequest,
771        origin_of: impl Fn(&str) -> Option<ToolOrigin>,
772    ) -> Option<RuleSuggestion> {
773        let origin = request.origin.as_ref()?;
774        let name = request.tool_name.as_str();
775        if origin.source != STATIC_TOOL_ORIGIN
776            || !EDIT_TOOLS.contains(&name)
777            || origin_of(name).as_ref() != Some(origin)
778        {
779            return None;
780        }
781        let paths = crate::edits::written_paths(name, &request.args)?;
782        if paths.is_empty()
783            || paths.iter().any(|path| {
784                is_protected_path(path) || path.split(['/', '\\']).any(|part| part == "..")
785            })
786        {
787            return None;
788        }
789        let declarations = EDIT_TOOLS
790            .iter()
791            .filter_map(|tool| Some((tool.to_string(), origin_of(tool)?)))
792            .filter(|(_, origin)| origin.source == STATIC_TOOL_ORIGIN)
793            .map(|(tool, origin)| (tool, origin.declaration_digest))
794            .collect();
795        let (dir, label) = match shared_dir(&paths) {
796            Some(dir) => (dir.clone(), format!("file writes: within {dir}/")),
797            None => (".".to_string(), "file writes: anywhere in the workspace".to_string()),
798        };
799        Some(RuleSuggestion {
800            label,
801            scope: SuggestedScope::Session,
802            tool: "*".into(),
803            origin: OriginPin::ExactEach { source: STATIC_TOOL_ORIGIN.into(), declarations },
804            predicates: vec![RulePredicate::WritesWithin { dir }],
805            runs_scripts: false,
806        })
807    }
808
809    /// Whether the rule has expired at `now`.
810    ///
811    /// # Example
812    ///
813    /// ```rust,ignore
814    /// assert!(!rule.is_expired(chrono::Utc::now()));
815    /// ```
816    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
817        self.expires_at.is_some_and(|at| now >= at)
818    }
819}
820
821/// The directory every one of `paths` lies within, relative to the workspace root; `None`
822/// when that is the root itself or a path is absolute.
823fn shared_dir(paths: &[String]) -> Option<String> {
824    paths
825        .iter()
826        .map(|path| {
827            std::path::Path::new(path.trim_start_matches("./"))
828                .parent()
829                .map(|parent| parent.to_string_lossy().into_owned())
830                .unwrap_or_default()
831        })
832        .reduce(|shared, next| common_dir(&shared, &next))
833        .filter(|parent| !parent.is_empty() && !parent.starts_with('/'))
834}
835
836/// The longest directory both `a` and `b` lie within, by whole components.
837fn common_dir(a: &str, b: &str) -> String {
838    a.split('/')
839        .zip(b.split('/'))
840        .take_while(|(left, right)| left == right)
841        .map(|(part, _)| part)
842        .collect::<Vec<_>>()
843        .join("/")
844}
845
846#[cfg(test)]
847mod tests {
848    use super::*;
849    use serde_json::json;
850
851    #[test]
852    fn unknown_fields_make_a_rule_unparseable() {
853        let mut value = json!({
854            "id": "r", "scope": { "kind": "user", "appName": "a", "userId": "u", "subjectKind": "human" },
855            "tool": "bash", "origin": { "kind": "exact", "source": "static", "declarationDigest": "sha256:x" },
856            "predicates": [], "decision": { "kind": "allow" },
857            "createdBy": { "kind": "human", "id": "u" }, "createdAt": "2026-10-20T00:00:00Z", "label": "l"
858        });
859        assert!(serde_json::from_value::<StandingRule>(value.clone()).is_ok());
860        value["everything"] = json!(true);
861        assert!(serde_json::from_value::<StandingRule>(value.clone()).is_err());
862        value.as_object_mut().unwrap().remove("everything");
863        value["scope"]["extra"] = json!(1);
864        assert!(serde_json::from_value::<StandingRule>(value.clone()).is_err());
865        value["scope"].as_object_mut().unwrap().remove("extra");
866        value["decision"] = json!({ "kind": "allow", "always": true });
867        assert!(serde_json::from_value::<StandingRule>(value.clone()).is_err());
868        value["decision"] = json!({ "kind": "allow" });
869        value["predicates"] =
870            json!([{ "shellPrefix": { "pointer": "/command", "tokens": [], "x": 1 } }]);
871        assert!(serde_json::from_value::<StandingRule>(value).is_err());
872    }
873
874    #[test]
875    fn edit_suggestions_are_session_scoped_and_skip_protected_paths() {
876        let origin = ToolOrigin::new("static", &json!({ "name": "write_file" }), None);
877        let request = ToolConfirmationRequest::new("write_file", json!({ "path": "src/lib.rs" }))
878            .with_origin(origin.clone());
879        let suggestions = StandingRule::suggestions(&request);
880        assert_eq!(suggestions.len(), 2);
881        assert!(suggestions.iter().all(|s| s.scope == SuggestedScope::Session));
882        let protected = ToolConfirmationRequest::new("write_file", json!({ "path": "AGENTS.md" }))
883            .with_origin(origin);
884        assert!(StandingRule::suggestions(&protected).is_empty());
885    }
886
887    /// The harness's three file-writing tools, as `folder_suggestion` looks them up.
888    fn writer(name: &str) -> Option<ToolOrigin> {
889        EDIT_TOOLS
890            .contains(&name)
891            .then(|| ToolOrigin::new("static", &json!({ "name": name }), None))
892    }
893
894    #[test]
895    fn the_folder_rule_pins_every_file_writing_tool_and_names_the_folder() {
896        let request = ToolConfirmationRequest::new("write_file", json!({ "path": "notes/a.md" }))
897            .with_origin(writer("write_file").unwrap());
898        let folder = StandingRule::folder_suggestion(&request, writer).unwrap();
899        let declarations: BTreeMap<String, String> = EDIT_TOOLS
900            .iter()
901            .map(|tool| (tool.to_string(), writer(tool).unwrap().declaration_digest))
902            .collect();
903        assert_eq!(
904            folder,
905            RuleSuggestion {
906                label: "file writes: within notes/".into(),
907                scope: SuggestedScope::Session,
908                tool: "*".into(),
909                origin: OriginPin::ExactEach { source: "static".into(), declarations },
910                predicates: vec![RulePredicate::WritesWithin { dir: "notes".into() }],
911                runs_scripts: false,
912            }
913        );
914        // Every tool it pins is admitted, and only at its declaration.
915        for tool in EDIT_TOOLS {
916            assert!(folder.origin.admits(&writer(tool).unwrap()), "{tool}");
917        }
918        let changed = ToolOrigin::new("static", &json!({ "name": "edit_file", "v": 2 }), None);
919        assert!(!folder.origin.admits(&changed));
920        let other = ToolOrigin::new("static", &json!({ "name": "read_file" }), None);
921        assert!(!folder.origin.admits(&other));
922        let mcp = ToolOrigin { source: "mcp:fs".into(), ..writer("write_file").unwrap() };
923        assert!(!folder.origin.admits(&mcp));
924
925        // A file at the root is the workspace's folder.
926        let root = ToolConfirmationRequest::new("edit_file", json!({ "path": "a.md" }))
927            .with_origin(writer("edit_file").unwrap());
928        let workspace = StandingRule::folder_suggestion(&root, writer).unwrap();
929        assert_eq!(workspace.label, "file writes: anywhere in the workspace");
930        assert_eq!(workspace.predicates, [RulePredicate::WritesWithin { dir: ".".into() }]);
931    }
932
933    #[test]
934    fn no_folder_rule_for_a_delete_a_move_an_escape_or_another_declaration() {
935        let patch = |text: &str| {
936            ToolConfirmationRequest::new("apply_patch", json!({ "patch": text }))
937                .with_origin(writer("apply_patch").unwrap())
938        };
939        let add = patch("*** Begin Patch\n*** Add File: notes/a.md\n+x\n*** End Patch");
940        assert!(StandingRule::folder_suggestion(&add, writer).is_some());
941        for refused in [
942            patch("*** Begin Patch\n*** Delete File: notes/a.md\n*** End Patch"),
943            patch(
944                "*** Begin Patch\n*** Update File: notes/a.md\n*** Move to: notes/b.md\n@@\n-x\n+y\n*** End Patch",
945            ),
946            ToolConfirmationRequest::new("write_file", json!({ "path": "notes/../a.md" }))
947                .with_origin(writer("write_file").unwrap()),
948            ToolConfirmationRequest::new("write_file", json!({ "path": "notes/AGENTS.md" }))
949                .with_origin(writer("write_file").unwrap()),
950            ToolConfirmationRequest::new("write_file", json!({ "path": "notes/a.md" }))
951                .with_origin(ToolOrigin::new(
952                    "static",
953                    &json!({ "name": "write_file", "v": 2 }),
954                    None,
955                )),
956            ToolConfirmationRequest::new("write_file", json!({ "path": "notes/a.md" })),
957            ToolConfirmationRequest::new("bash", json!({ "command": "touch notes/a.md" }))
958                .with_origin(ToolOrigin::new("static", &json!({ "name": "bash" }), None)),
959        ] {
960            assert_eq!(StandingRule::folder_suggestion(&refused, writer), None, "{refused:?}");
961        }
962    }
963
964    #[test]
965    fn non_waivable_tools_get_no_suggestions() {
966        let origin = ToolOrigin::new("static", &json!({ "name": "exit_plan_mode" }), None);
967        let request = ToolConfirmationRequest::new("exit_plan_mode", json!({ "plan": "x" }))
968            .with_origin(origin);
969        assert!(StandingRule::suggestions(&request).is_empty());
970        let bash = ToolOrigin::new("static", &json!({ "name": "bash" }), None);
971        let retry = ToolConfirmationRequest::new(
972            "bash",
973            json!({ "command": "cargo test", "unsandboxed": true }),
974        )
975        .with_origin(bash);
976        assert!(StandingRule::suggestions(&retry).is_empty());
977    }
978
979    #[test]
980    fn script_runners_are_flagged() {
981        let origin = ToolOrigin::new("static", &json!({ "name": "bash" }), None);
982        for (command, scripts) in [("cargo test", true), ("ls -la", false), ("make", true)] {
983            let request = ToolConfirmationRequest::new("bash", json!({ "command": command }))
984                .with_origin(origin.clone());
985            assert!(StandingRule::suggestions(&request).iter().all(|s| s.runs_scripts == scripts));
986        }
987    }
988}