Skip to main content

weirdnet_agent/
policy.rs

1//! Approval policy: tiers, per-companion per-site grants, task approvals and
2//! standing "Always allow" rules.
3//!
4//! Rules (Companions design v1):
5//! - Tier `Read` (attached content) always runs; the app decides what is attached.
6//! - Tier `Never` is never offered.
7//! - A site set to [`SiteLevel::Off`] blocks every navigate, research and interact
8//!   step there; nothing overrides it.
9//! - [`SiteLevel::Act`] lets navigate and interact run without asking on that site,
10//!   for that companion only.
11//! - Navigate and research ask once per task ([`Scope::Task`]) or can be covered by a
12//!   standing allow ([`AllowRule`]); a skipped approval is reported as a [`SkipNotice`].
13//! - Interact asks every time unless approved for this task on this site or the site is Act.
14//! - Signed-in research is never covered by a standing allow; it needs a task approval
15//!   given while signed-in was on.
16//! - An all-companions allow covers an [`AgentKind::External`] agent only after the user
17//!   approved one of its requests.
18//! - Revoking takes effect at the next evaluation.
19
20use std::collections::{BTreeMap, BTreeSet};
21use std::sync::{Arc, RwLock};
22
23use serde::{Deserialize, Serialize};
24
25use crate::identity::{AgentId, AgentIdentity, AgentKind};
26
27/// How much a tool can do.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum Tier {
31    /// Tier 0: reads only what the user attached.
32    Read,
33    /// Tier 1: navigates (open, switch, scroll, find, bookmark).
34    Navigate,
35    /// Tier R: background research and open-world reads.
36    Research,
37    /// Tier 2: changes page or world state (click, fill, submit, destructive tools).
38    Interact,
39    /// Tier 3: never available to agents.
40    Never,
41}
42
43impl Tier {
44    /// Default tier from MCP-style annotations: destructive → Interact,
45    /// read-only closed-world → Read, read-only open-world → Research, otherwise Navigate.
46    pub fn from_annotations(read_only: bool, destructive: bool, open_world: bool) -> Self {
47        if destructive {
48            Tier::Interact
49        } else if read_only && !open_world {
50            Tier::Read
51        } else if read_only {
52            Tier::Research
53        } else {
54            Tier::Navigate
55        }
56    }
57
58    fn rank(self) -> u8 {
59        match self {
60            Tier::Read => 0,
61            Tier::Navigate | Tier::Research => 1,
62            Tier::Interact => 2,
63            Tier::Never => 3,
64        }
65    }
66
67    /// Whether `other` is the same as or strictly stricter than `self`.
68    /// Users may make a tool stricter, never looser.
69    pub fn allows_override_to(self, other: Tier) -> bool {
70        other == self || other.rank() > self.rank()
71    }
72}
73
74/// Per-companion, per-site permission level.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum SiteLevel {
78    Off,
79    #[default]
80    Ask,
81    Act,
82}
83
84/// Which companions a standing allow covers.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum CompanionScope {
88    One(AgentId),
89    All,
90}
91
92/// What a standing allow skips approval for.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "snake_case", tag = "tier")]
95pub enum AllowRule {
96    /// Navigate on one site, or everywhere when `site` is `None`.
97    Navigate { site: Option<String> },
98    /// Research everywhere, optionally limited to one search provider.
99    Research { provider: Option<String> },
100}
101
102/// A revocable "Always allow".
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104pub struct StandingAllow {
105    pub id: u64,
106    pub companion: CompanionScope,
107    pub rule: AllowRule,
108    pub created_unix_ms: u64,
109}
110
111/// What the user picked on an approval card.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case", tag = "scope")]
114pub enum Scope {
115    /// Just this step.
116    Once,
117    /// The rest of this task (for interact: on this site).
118    Task,
119    /// Navigate: Always allow on this site. Interact: set this site to Act for this companion.
120    AlwaysSite { all_companions: bool },
121    /// Navigate: Always allow everywhere.
122    AlwaysEverywhere { all_companions: bool },
123    /// Research: Always allow, optionally only with the request's provider.
124    AlwaysResearch { all_companions: bool, provider_only: bool },
125}
126
127/// One step the agent wants to take, as the policy sees it.
128#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
129pub struct ActionRequest {
130    pub tier: Option<Tier>,
131    /// Normalised host the step touches, if any (see [`site_of`]).
132    pub site: Option<String>,
133    /// Search provider for research steps.
134    pub provider: Option<String>,
135    /// Research that would use the user's signed-in session.
136    pub signed_in: bool,
137}
138
139impl ActionRequest {
140    pub fn new(tier: Tier) -> Self {
141        Self { tier: Some(tier), ..Self::default() }
142    }
143
144    pub fn site(mut self, site: impl Into<String>) -> Self {
145        self.site = Some(site.into());
146        self
147    }
148
149    pub fn provider(mut self, provider: impl Into<String>) -> Self {
150        self.provider = Some(provider.into());
151        self
152    }
153
154    pub fn signed_in(mut self, on: bool) -> Self {
155        self.signed_in = on;
156        self
157    }
158
159    fn tier(&self) -> Tier {
160        self.tier.unwrap_or(Tier::Never)
161    }
162}
163
164/// Approvals that last until the task ends.
165#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
166pub struct TaskApprovals {
167    pub navigate: bool,
168    pub research: bool,
169    pub research_signed_in: bool,
170    pub interact_sites: BTreeSet<String>,
171}
172
173/// An approval skipped because of a standing allow; shown as a notice with Stop.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub struct SkipNotice {
176    pub allow_id: u64,
177    pub tier: Tier,
178    pub site: Option<String>,
179    /// For research, the provider the query goes to.
180    pub provider: Option<String>,
181}
182
183/// Why a step can't run.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
185#[serde(rename_all = "snake_case", tag = "reason")]
186pub enum DenyReason {
187    #[error("this kind of action is never available to agents")]
188    Never,
189    #[error("site {site} is set to Off")]
190    SiteOff { site: String },
191    #[error("the user declined")]
192    Declined,
193}
194
195/// What the user is asked, with the scopes the card may offer.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct ApprovalPrompt {
198    pub agent: AgentId,
199    pub request: ActionRequest,
200    pub offers: Vec<Scope>,
201}
202
203/// Result of evaluating one request.
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub enum Decision {
206    Allow,
207    AllowWithNotice(SkipNotice),
208    Ask(ApprovalPrompt),
209    Deny(DenyReason),
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
213pub enum PolicyError {
214    #[error("scope {0:?} is not offered for this request")]
215    ScopeNotOffered(Scope),
216}
217
218/// Persistent policy state for one user: grants, standing allows and which
219/// External agents have been approved once. Serialize it to store or sync.
220#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
221pub struct Policy {
222    #[serde(default)]
223    grants: BTreeMap<AgentId, BTreeMap<String, SiteLevel>>,
224    #[serde(default)]
225    allows: Vec<StandingAllow>,
226    #[serde(default)]
227    next_allow_id: u64,
228    #[serde(default)]
229    approved_external: BTreeSet<AgentId>,
230}
231
232/// Policy shared between running sessions and settings; a revoke is seen at the next step.
233pub type SharedPolicy = Arc<RwLock<Policy>>;
234
235impl Policy {
236    pub fn new() -> Self {
237        Self::default()
238    }
239
240    pub fn shared(self) -> SharedPolicy {
241        Arc::new(RwLock::new(self))
242    }
243
244    pub fn site_level(&self, agent: &AgentId, site: &str) -> SiteLevel {
245        self.grants.get(agent).and_then(|m| m.get(&normalize_site(site))).copied().unwrap_or_default()
246    }
247
248    pub fn set_site_level(&mut self, agent: &AgentId, site: &str, level: SiteLevel) {
249        let site = normalize_site(site);
250        let map = self.grants.entry(agent.clone()).or_default();
251        if level == SiteLevel::Ask {
252            map.remove(&site);
253        } else {
254            map.insert(site, level);
255        }
256    }
257
258    /// Per-site grants for one companion (non-default levels only).
259    pub fn grants_for(&self, agent: &AgentId) -> impl Iterator<Item = (&str, SiteLevel)> {
260        self.grants.get(agent).into_iter().flat_map(|m| m.iter().map(|(s, l)| (s.as_str(), *l)))
261    }
262
263    pub fn add_allow(&mut self, companion: CompanionScope, rule: AllowRule, now_unix_ms: u64) -> u64 {
264        let rule = match rule {
265            AllowRule::Navigate { site } => AllowRule::Navigate { site: site.map(|s| normalize_site(&s)) },
266            r => r,
267        };
268        if let Some(existing) = self.allows.iter().find(|a| a.companion == companion && a.rule == rule) {
269            return existing.id;
270        }
271        self.next_allow_id += 1;
272        let id = self.next_allow_id;
273        self.allows.push(StandingAllow { id, companion, rule, created_unix_ms: now_unix_ms });
274        id
275    }
276
277    /// Every standing allow, for the settings list.
278    pub fn allows(&self) -> &[StandingAllow] {
279        &self.allows
280    }
281
282    /// Standing allows that name this companion directly or cover all companions.
283    pub fn allows_for<'a>(&'a self, agent: &'a AgentId) -> impl Iterator<Item = &'a StandingAllow> {
284        self.allows.iter().filter(move |a| match &a.companion {
285            CompanionScope::One(id) => id == agent,
286            CompanionScope::All => true,
287        })
288    }
289
290    pub fn revoke(&mut self, allow_id: u64) -> bool {
291        let before = self.allows.len();
292        self.allows.retain(|a| a.id != allow_id);
293        before != self.allows.len()
294    }
295
296    pub fn revoke_all(&mut self) {
297        self.allows.clear();
298    }
299
300    pub fn is_external_approved(&self, agent: &AgentId) -> bool {
301        self.approved_external.contains(agent)
302    }
303
304    /// Forgets everything about one companion (for example when it is removed).
305    pub fn forget_agent(&mut self, agent: &AgentId) {
306        self.grants.remove(agent);
307        self.approved_external.remove(agent);
308        self.allows.retain(|a| a.companion != CompanionScope::One(agent.clone()));
309    }
310
311    fn matching_allow(&self, who: &AgentIdentity, req: &ActionRequest) -> Option<&StandingAllow> {
312        self.allows.iter().find(|a| {
313            let companion_ok = match &a.companion {
314                CompanionScope::One(id) => *id == who.id,
315                CompanionScope::All => who.kind != AgentKind::External || self.approved_external.contains(&who.id),
316            };
317            companion_ok
318                && match (&a.rule, req.tier()) {
319                    (AllowRule::Navigate { site: None }, Tier::Navigate) => true,
320                    (AllowRule::Navigate { site: Some(s) }, Tier::Navigate) => req.site.as_deref().map(normalize_site).as_deref() == Some(s),
321                    (AllowRule::Research { provider }, Tier::Research) if !req.signed_in => {
322                        provider.is_none() || provider.as_deref() == req.provider.as_deref()
323                    }
324                    _ => false,
325                }
326        })
327    }
328
329    /// Scopes an approval card may offer for this request.
330    pub fn offers(&self, req: &ActionRequest) -> Vec<Scope> {
331        let has_site = req.site.is_some();
332        match req.tier() {
333            Tier::Navigate => {
334                let mut v = vec![Scope::Once, Scope::Task];
335                if has_site {
336                    v.push(Scope::AlwaysSite { all_companions: false });
337                    v.push(Scope::AlwaysSite { all_companions: true });
338                }
339                v.push(Scope::AlwaysEverywhere { all_companions: false });
340                v.push(Scope::AlwaysEverywhere { all_companions: true });
341                v
342            }
343            Tier::Research if req.signed_in => vec![Scope::Once, Scope::Task],
344            Tier::Research => {
345                let mut v = vec![Scope::Once, Scope::Task];
346                for all in [false, true] {
347                    v.push(Scope::AlwaysResearch { all_companions: all, provider_only: false });
348                    if req.provider.is_some() {
349                        v.push(Scope::AlwaysResearch { all_companions: all, provider_only: true });
350                    }
351                }
352                v
353            }
354            Tier::Interact if has_site => vec![Scope::Once, Scope::Task, Scope::AlwaysSite { all_companions: false }],
355            Tier::Interact => vec![Scope::Once],
356            Tier::Read | Tier::Never => Vec::new(),
357        }
358    }
359
360    /// Decides whether `who` may take the step now.
361    pub fn evaluate(&self, who: &AgentIdentity, req: &ActionRequest, task: &TaskApprovals) -> Decision {
362        let tier = req.tier();
363        match tier {
364            Tier::Never => return Decision::Deny(DenyReason::Never),
365            Tier::Read => return Decision::Allow,
366            _ => {}
367        }
368        let level = req.site.as_deref().map(|s| self.site_level(&who.id, s));
369        if level == Some(SiteLevel::Off) {
370            return Decision::Deny(DenyReason::SiteOff { site: normalize_site(req.site.as_deref().unwrap_or_default()) });
371        }
372        let ask = || Decision::Ask(ApprovalPrompt { agent: who.id.clone(), request: req.clone(), offers: self.offers(req) });
373        let notice = |a: &StandingAllow| {
374            Decision::AllowWithNotice(SkipNotice {
375                allow_id: a.id,
376                tier,
377                site: req.site.as_deref().map(normalize_site),
378                provider: req.provider.clone(),
379            })
380        };
381        match tier {
382            Tier::Navigate => {
383                if level == Some(SiteLevel::Act) || task.navigate {
384                    Decision::Allow
385                } else if let Some(a) = self.matching_allow(who, req) {
386                    notice(a)
387                } else {
388                    ask()
389                }
390            }
391            Tier::Research => {
392                if req.signed_in {
393                    if task.research_signed_in { Decision::Allow } else { ask() }
394                } else if task.research {
395                    Decision::Allow
396                } else if let Some(a) = self.matching_allow(who, req) {
397                    notice(a)
398                } else {
399                    ask()
400                }
401            }
402            Tier::Interact => {
403                let site_ok = req.site.as_deref().is_some_and(|s| task.interact_sites.contains(&normalize_site(s)));
404                if level == Some(SiteLevel::Act) || site_ok { Decision::Allow } else { ask() }
405            }
406            Tier::Read | Tier::Never => unreachable!(),
407        }
408    }
409
410    /// Records the user's answer to an approval card.
411    pub fn apply(
412        &mut self,
413        who: &AgentIdentity,
414        req: &ActionRequest,
415        scope: &Scope,
416        task: &mut TaskApprovals,
417        now_unix_ms: u64,
418    ) -> Result<(), PolicyError> {
419        if !self.offers(req).contains(scope) {
420            return Err(PolicyError::ScopeNotOffered(scope.clone()));
421        }
422        if who.kind == AgentKind::External {
423            self.approved_external.insert(who.id.clone());
424        }
425        let companion = |all: bool| if all { CompanionScope::All } else { CompanionScope::One(who.id.clone()) };
426        let site = req.site.as_deref().map(normalize_site);
427        match (req.tier(), scope) {
428            (_, Scope::Once) => {}
429            (Tier::Navigate, Scope::Task) => task.navigate = true,
430            (Tier::Research, Scope::Task) => {
431                task.research = true;
432                if req.signed_in {
433                    task.research_signed_in = true;
434                }
435            }
436            (Tier::Interact, Scope::Task) => {
437                if let Some(s) = site {
438                    task.interact_sites.insert(s);
439                }
440            }
441            (Tier::Navigate, Scope::AlwaysSite { all_companions }) => {
442                self.add_allow(companion(*all_companions), AllowRule::Navigate { site }, now_unix_ms);
443            }
444            (Tier::Interact, Scope::AlwaysSite { .. }) => {
445                if let Some(s) = site {
446                    self.set_site_level(&who.id, &s, SiteLevel::Act);
447                }
448            }
449            (Tier::Navigate, Scope::AlwaysEverywhere { all_companions }) => {
450                self.add_allow(companion(*all_companions), AllowRule::Navigate { site: None }, now_unix_ms);
451            }
452            (Tier::Research, Scope::AlwaysResearch { all_companions, provider_only }) => {
453                let provider = if *provider_only { req.provider.clone() } else { None };
454                self.add_allow(companion(*all_companions), AllowRule::Research { provider }, now_unix_ms);
455            }
456            _ => return Err(PolicyError::ScopeNotOffered(scope.clone())),
457        }
458        Ok(())
459    }
460}
461
462fn normalize_site(site: &str) -> String {
463    let s = site.trim().trim_end_matches('.').to_ascii_lowercase();
464    s.strip_prefix("www.").map(str::to_string).unwrap_or(s)
465}
466
467/// Host part of a URL, lower-cased and without `www.`, used as the site key.
468/// Returns `None` for URLs without a host (for example `about:blank`).
469pub fn site_of(url: &str) -> Option<String> {
470    let rest = url.split_once("://")?.1;
471    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
472    let host_port = authority.rsplit('@').next().unwrap_or_default();
473    let host = if let Some(stripped) = host_port.strip_prefix('[') {
474        stripped.split(']').next().unwrap_or_default()
475    } else {
476        host_port.split(':').next().unwrap_or_default()
477    };
478    if host.is_empty() { None } else { Some(normalize_site(host)) }
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    fn atlas() -> AgentIdentity {
486        AgentIdentity::new("atlas", "Atlas", AgentKind::Local)
487    }
488    fn scout() -> AgentIdentity {
489        AgentIdentity::new("scout", "Scout", AgentKind::Node)
490    }
491    fn ext() -> AgentIdentity {
492        AgentIdentity::new("mouser", "Mouser", AgentKind::External)
493    }
494    fn nav(site: &str) -> ActionRequest {
495        ActionRequest::new(Tier::Navigate).site(site)
496    }
497    fn research() -> ActionRequest {
498        ActionRequest::new(Tier::Research).provider("duckduckgo")
499    }
500    fn is_ask(d: &Decision) -> bool {
501        matches!(d, Decision::Ask(_))
502    }
503
504    #[test]
505    fn tiers_from_annotations_and_overrides() {
506        assert_eq!(Tier::from_annotations(true, false, false), Tier::Read);
507        assert_eq!(Tier::from_annotations(true, false, true), Tier::Research);
508        assert_eq!(Tier::from_annotations(false, true, true), Tier::Interact);
509        assert_eq!(Tier::from_annotations(false, false, false), Tier::Navigate);
510        assert!(Tier::Read.allows_override_to(Tier::Interact));
511        assert!(Tier::Interact.allows_override_to(Tier::Never));
512        assert!(!Tier::Interact.allows_override_to(Tier::Navigate));
513        assert!(!Tier::Navigate.allows_override_to(Tier::Research));
514    }
515
516    #[test]
517    fn site_of_parses_hosts() {
518        assert_eq!(site_of("https://www.Tokio.rs/tokio/tutorial?x#y").as_deref(), Some("tokio.rs"));
519        assert_eq!(site_of("http://user:pw@example.com:8080/a").as_deref(), Some("example.com"));
520        assert_eq!(site_of("http://[::1]:3000/").as_deref(), Some("::1"));
521        assert_eq!(site_of("about:blank"), None);
522        assert_eq!(site_of("file:///etc/hosts"), None);
523    }
524
525    #[test]
526    fn read_always_never_never() {
527        let p = Policy::new();
528        let t = TaskApprovals::default();
529        assert_eq!(p.evaluate(&atlas(), &ActionRequest::new(Tier::Read), &t), Decision::Allow);
530        assert_eq!(p.evaluate(&atlas(), &ActionRequest::new(Tier::Never), &t), Decision::Deny(DenyReason::Never));
531        assert!(p.offers(&ActionRequest::new(Tier::Never)).is_empty());
532    }
533
534    #[test]
535    fn navigate_asks_then_task_approval_covers_rest_of_task() {
536        let mut p = Policy::new();
537        let mut t = TaskApprovals::default();
538        let d = p.evaluate(&atlas(), &nav("tokio.rs"), &t);
539        let Decision::Ask(prompt) = d else { panic!("expected ask") };
540        assert!(prompt.offers.contains(&Scope::AlwaysSite { all_companions: false }));
541        p.apply(&atlas(), &nav("tokio.rs"), &Scope::Task, &mut t, 0).unwrap();
542        assert_eq!(p.evaluate(&atlas(), &nav("docs.rs"), &t), Decision::Allow);
543        // A new task asks again.
544        assert!(is_ask(&p.evaluate(&atlas(), &nav("docs.rs"), &TaskApprovals::default())));
545    }
546
547    #[test]
548    fn once_does_not_persist() {
549        let mut p = Policy::new();
550        let mut t = TaskApprovals::default();
551        p.apply(&atlas(), &nav("tokio.rs"), &Scope::Once, &mut t, 0).unwrap();
552        assert!(is_ask(&p.evaluate(&atlas(), &nav("tokio.rs"), &t)));
553    }
554
555    #[test]
556    fn always_allow_navigate_site_is_per_companion_and_gives_notice() {
557        let mut p = Policy::new();
558        let mut t = TaskApprovals::default();
559        p.apply(&atlas(), &nav("www.tokio.rs"), &Scope::AlwaysSite { all_companions: false }, &mut t, 5).unwrap();
560        let fresh = TaskApprovals::default();
561        match p.evaluate(&atlas(), &nav("tokio.rs"), &fresh) {
562            Decision::AllowWithNotice(n) => {
563                assert_eq!(n.tier, Tier::Navigate);
564                assert_eq!(n.site.as_deref(), Some("tokio.rs"));
565            }
566            d => panic!("{d:?}"),
567        }
568        assert!(is_ask(&p.evaluate(&atlas(), &nav("docs.rs"), &fresh)));
569        assert!(is_ask(&p.evaluate(&scout(), &nav("tokio.rs"), &fresh)));
570        assert_eq!(p.allows()[0].created_unix_ms, 5);
571    }
572
573    #[test]
574    fn always_allow_everywhere_for_all_companions() {
575        let mut p = Policy::new();
576        let mut t = TaskApprovals::default();
577        p.apply(&atlas(), &nav("a.com"), &Scope::AlwaysEverywhere { all_companions: true }, &mut t, 0).unwrap();
578        let fresh = TaskApprovals::default();
579        assert!(matches!(p.evaluate(&scout(), &nav("b.com"), &fresh), Decision::AllowWithNotice(_)));
580        // Duplicate allows are merged.
581        p.add_allow(CompanionScope::All, AllowRule::Navigate { site: None }, 1);
582        assert_eq!(p.allows().len(), 1);
583    }
584
585    #[test]
586    fn all_companions_allow_covers_external_only_after_first_approval() {
587        let mut p = Policy::new();
588        p.add_allow(CompanionScope::All, AllowRule::Navigate { site: None }, 0);
589        let mut t = TaskApprovals::default();
590        assert!(is_ask(&p.evaluate(&ext(), &nav("a.com"), &t)));
591        p.apply(&ext(), &nav("a.com"), &Scope::Once, &mut t, 0).unwrap();
592        assert!(p.is_external_approved(&ext().id));
593        assert!(matches!(p.evaluate(&ext(), &nav("b.com"), &TaskApprovals::default()), Decision::AllowWithNotice(_)));
594    }
595
596    #[test]
597    fn off_site_beats_everything() {
598        let mut p = Policy::new();
599        p.add_allow(CompanionScope::All, AllowRule::Navigate { site: None }, 0);
600        p.add_allow(CompanionScope::All, AllowRule::Research { provider: None }, 0);
601        p.set_site_level(&atlas().id, "evil.com", SiteLevel::Off);
602        let t = TaskApprovals { navigate: true, research: true, research_signed_in: true, interact_sites: ["evil.com".into()].into() };
603        for tier in [Tier::Navigate, Tier::Research, Tier::Interact] {
604            assert_eq!(
605                p.evaluate(&atlas(), &ActionRequest::new(tier).site("evil.com"), &t),
606                Decision::Deny(DenyReason::SiteOff { site: "evil.com".into() })
607            );
608        }
609        // Off is per companion.
610        assert_eq!(p.evaluate(&scout(), &nav("evil.com"), &t), Decision::Allow);
611    }
612
613    #[test]
614    fn act_site_runs_navigate_and_interact_without_asking() {
615        let mut p = Policy::new();
616        p.set_site_level(&atlas().id, "github.com", SiteLevel::Act);
617        let t = TaskApprovals::default();
618        assert_eq!(p.evaluate(&atlas(), &nav("github.com"), &t), Decision::Allow);
619        assert_eq!(p.evaluate(&atlas(), &ActionRequest::new(Tier::Interact).site("github.com"), &t), Decision::Allow);
620        assert!(is_ask(&p.evaluate(&scout(), &ActionRequest::new(Tier::Interact).site("github.com"), &t)));
621        // Resetting to Ask removes the grant.
622        p.set_site_level(&atlas().id, "github.com", SiteLevel::Ask);
623        assert_eq!(p.grants_for(&atlas().id).count(), 0);
624    }
625
626    #[test]
627    fn interact_scopes() {
628        let mut p = Policy::new();
629        let mut t = TaskApprovals::default();
630        let req = ActionRequest::new(Tier::Interact).site("github.com");
631        let Decision::Ask(prompt) = p.evaluate(&atlas(), &req, &t) else { panic!() };
632        assert_eq!(prompt.offers, vec![Scope::Once, Scope::Task, Scope::AlwaysSite { all_companions: false }]);
633        // Always allow everywhere is never offered for interact.
634        assert_eq!(
635            p.apply(&atlas(), &req, &Scope::AlwaysEverywhere { all_companions: false }, &mut t, 0),
636            Err(PolicyError::ScopeNotOffered(Scope::AlwaysEverywhere { all_companions: false }))
637        );
638        p.apply(&atlas(), &req, &Scope::Task, &mut t, 0).unwrap();
639        assert_eq!(p.evaluate(&atlas(), &req, &t), Decision::Allow);
640        assert!(is_ask(&p.evaluate(&atlas(), &ActionRequest::new(Tier::Interact).site("gitlab.com"), &t)));
641        p.apply(&atlas(), &req, &Scope::AlwaysSite { all_companions: false }, &mut t, 0).unwrap();
642        assert_eq!(p.site_level(&atlas().id, "github.com"), SiteLevel::Act);
643        // Interact without a site only offers Once.
644        assert_eq!(p.offers(&ActionRequest::new(Tier::Interact)), vec![Scope::Once]);
645    }
646
647    #[test]
648    fn research_always_allow_with_provider_limit() {
649        let mut p = Policy::new();
650        let mut t = TaskApprovals::default();
651        p.apply(&atlas(), &research(), &Scope::AlwaysResearch { all_companions: false, provider_only: true }, &mut t, 0).unwrap();
652        let fresh = TaskApprovals::default();
653        match p.evaluate(&atlas(), &research(), &fresh) {
654            Decision::AllowWithNotice(n) => assert_eq!(n.provider.as_deref(), Some("duckduckgo")),
655            d => panic!("{d:?}"),
656        }
657        assert!(is_ask(&p.evaluate(&atlas(), &ActionRequest::new(Tier::Research).provider("google"), &fresh)));
658    }
659
660    #[test]
661    fn signed_in_research_is_never_covered_by_always_allow() {
662        let mut p = Policy::new();
663        p.add_allow(CompanionScope::All, AllowRule::Research { provider: None }, 0);
664        let mut t = TaskApprovals { research: true, ..Default::default() };
665        let req = research().signed_in(true);
666        let Decision::Ask(prompt) = p.evaluate(&atlas(), &req, &t) else { panic!() };
667        assert_eq!(prompt.offers, vec![Scope::Once, Scope::Task]);
668        assert!(p.apply(&atlas(), &req, &Scope::AlwaysResearch { all_companions: false, provider_only: false }, &mut t, 0).is_err());
669        p.apply(&atlas(), &req, &Scope::Task, &mut t, 0).unwrap();
670        assert_eq!(p.evaluate(&atlas(), &req, &t), Decision::Allow);
671    }
672
673    #[test]
674    fn revoke_takes_effect_on_next_evaluation() {
675        let mut p = Policy::new();
676        let id = p.add_allow(CompanionScope::One(atlas().id), AllowRule::Navigate { site: None }, 0);
677        let t = TaskApprovals::default();
678        assert!(matches!(p.evaluate(&atlas(), &nav("a.com"), &t), Decision::AllowWithNotice(_)));
679        assert!(p.revoke(id));
680        assert!(!p.revoke(id));
681        assert!(is_ask(&p.evaluate(&atlas(), &nav("a.com"), &t)));
682        p.add_allow(CompanionScope::All, AllowRule::Navigate { site: None }, 0);
683        p.revoke_all();
684        assert!(p.allows().is_empty());
685    }
686
687    #[test]
688    fn forget_agent_and_serde_roundtrip() {
689        let mut p = Policy::new();
690        p.set_site_level(&atlas().id, "a.com", SiteLevel::Act);
691        p.add_allow(CompanionScope::One(atlas().id), AllowRule::Navigate { site: Some("A.com".into()) }, 7);
692        p.add_allow(CompanionScope::All, AllowRule::Research { provider: Some("kagi".into()) }, 8);
693        let json = serde_json::to_string(&p).unwrap();
694        let back: Policy = serde_json::from_str(&json).unwrap();
695        assert_eq!(back, p);
696        assert_eq!(back.allows_for(&atlas().id).count(), 2);
697        let mut p = back;
698        p.forget_agent(&atlas().id);
699        assert_eq!(p.allows().len(), 1);
700        assert_eq!(p.site_level(&atlas().id, "a.com"), SiteLevel::Ask);
701    }
702}