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