Skip to main content

aidaemon_core/
approval.rs

1//! Typed call effects and owner approvals.
2//!
3//! A tool declares what one call does and to which target
4//! ([`Tool::effects`](crate::Tool::effects)), so policies judge effects
5//! rather than tool names. A hook that wants the owner to decide returns
6//! [`InterruptKind::OwnerApproval`]; when the resolver denies it, the kernel
7//! remembers the request's effects in [`crate::RunState::declined`] for the
8//! rest of the run.
9
10use serde::{Deserialize, Serialize};
11
12/// Prefix of the reason recorded when the owner declines an approval.
13pub const OWNER_DECLINED: &str = "[OWNER DECLINED]";
14
15/// Prefix of the reason for a call whose owner card got no answer (it
16/// expired, could not be delivered, or the turn was cancelled). Not a
17/// refusal: nothing is remembered as declined.
18pub const OWNER_UNANSWERED: &str = "[NO ANSWER]";
19
20/// Prefix of the reason an outbound secret scan (the
21/// [`crate::Safeguard::Egress`] hook) gives when it refuses a call.
22pub const EGRESS_BLOCKED: &str = "[EGRESS BLOCKED]";
23
24/// Prefix of the reason the [`crate::AuthorityHook`] gives when a call is
25/// outside what the run may do.
26pub const AUTHORITY_BLOCKED: &str = "[AUTHORITY BLOCKED]";
27
28/// Prefix of the refusal a rejected egress call returns to the model after
29/// the run read untrusted content.
30pub const UNTRUSTED_BLOCKED: &str = "[UNTRUSTED BLOCKED]";
31
32/// What kind of thing a call does.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum EffectClass {
37    /// Sends data or acts on a host outside the owner's machine.
38    Egress,
39    /// Deletes a path.
40    Delete,
41    /// Creates or modifies a path.
42    Write,
43    /// Changes configuration stored at a path.
44    Configuration,
45    /// Uses a stored credential.
46    Credential,
47    /// Starts a program.
48    Process,
49    /// One exact call, named by its approval subject. Recorded when the
50    /// owner declines a request that declared no effects, so the identical
51    /// request is not put to the owner again.
52    Call,
53}
54
55impl std::fmt::Display for EffectClass {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.write_str(match self {
58            Self::Egress => "egress",
59            Self::Delete => "delete",
60            Self::Write => "write",
61            Self::Configuration => "configuration",
62            Self::Credential => "credential",
63            Self::Process => "process",
64            Self::Call => "call",
65        })
66    }
67}
68
69impl EffectClass {
70    /// Whether targets of this class are paths, so a target covers the
71    /// paths below it.
72    fn is_path(self) -> bool {
73        matches!(self, Self::Delete | Self::Write | Self::Configuration)
74    }
75}
76
77/// One effect of a call on one target.
78///
79/// The producer normalizes `target`: lowercase `host:port` for
80/// [`EffectClass::Egress`]; an absolute, normalized path for
81/// [`EffectClass::Delete`], [`EffectClass::Write`] and
82/// [`EffectClass::Configuration`]; the profile name for
83/// [`EffectClass::Credential`]; the program name for [`EffectClass::Process`].
84/// Build keys with [`EffectKey::path`], [`EffectKey::egress`] and
85/// [`EffectKey::named`] so every producer uses the same convention.
86#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
87pub struct EffectKey {
88    pub class: EffectClass,
89    pub target: String,
90}
91
92impl EffectKey {
93    /// A path effect (`Delete`, `Write`, `Configuration`) on an absolute
94    /// path, normalized lexically: empty and `.` components dropped, `..`
95    /// resolved, no trailing slash. `None` for a relative path or one that
96    /// climbs above `/`. The filesystem is not consulted (symlinks are not
97    /// resolved). A Windows path with a drive (`C:\Users\x`, `c:/Users/x`)
98    /// is absolute too, written `C:/Users/x`: `\` and `/` both separate its
99    /// components, and the drive letter is uppercase.
100    pub fn path(class: EffectClass, raw: &str) -> Option<EffectKey> {
101        let (root, rest, separators): (String, &str, &[char]) = match raw.as_bytes() {
102            [b'/', ..] => (String::new(), raw, &['/']),
103            [drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic() => (
104                format!("{}:", (*drive as char).to_ascii_uppercase()),
105                &raw[2..],
106                &['/', '\\'],
107            ),
108            _ => return None,
109        };
110        let mut parts: Vec<&str> = Vec::new();
111        for part in rest.split(separators) {
112            match part {
113                "" | "." => {}
114                ".." => {
115                    parts.pop()?;
116                }
117                part => parts.push(part),
118            }
119        }
120        Some(EffectKey {
121            class,
122            target: format!("{root}/{}", parts.join("/")),
123        })
124    }
125
126    /// An egress effect on `host`, with target `host:port`: the host
127    /// lowercased and without a trailing dot (`h.example.` is `h.example`),
128    /// and the port given or else the scheme's default (http
129    /// 80, https 443, ssh 22; 0 for an unknown scheme).
130    pub fn egress(scheme: &str, host: &str, port: Option<u16>) -> EffectKey {
131        let port = port.unwrap_or_else(|| match scheme.to_ascii_lowercase().as_str() {
132            "http" => 80,
133            "https" => 443,
134            "ssh" => 22,
135            _ => 0,
136        });
137        EffectKey {
138            class: EffectClass::Egress,
139            target: format!("{}:{port}", host.to_ascii_lowercase().trim_end_matches('.')),
140        }
141    }
142
143    /// An effect named by an identifier rather than a path or host: the
144    /// profile name for [`EffectClass::Credential`], the program name for
145    /// [`EffectClass::Process`].
146    pub fn named(class: EffectClass, name: &str) -> EffectKey {
147        EffectKey {
148            class,
149            target: name.to_string(),
150        }
151    }
152
153    /// Same class, and the same target or, for path classes, one target is
154    /// the other or below it. Targets are compared as given, so both keys
155    /// must be normalized (built with [`EffectKey::path`],
156    /// [`EffectKey::egress`] or [`EffectKey::named`]): `h.example.invalid`
157    /// does not overlap `h.example.invalid:443`, and `/a/../b` does not
158    /// overlap `/b`.
159    pub fn overlaps(&self, other: &EffectKey) -> bool {
160        if self.class != other.class {
161            return false;
162        }
163        if self.target == other.target {
164            return true;
165        }
166        self.class.is_path()
167            && (path_covers(&self.target, &other.target)
168                || path_covers(&other.target, &self.target))
169    }
170}
171
172/// Whether `inner` is `outer` or a path below it, compared by component.
173fn path_covers(outer: &str, inner: &str) -> bool {
174    let outer = outer.trim_end_matches('/');
175    let inner = inner.trim_end_matches('/');
176    if outer == inner {
177        return true;
178    }
179    // After trimming, the root is empty and covers every absolute path.
180    inner
181        .strip_prefix(outer)
182        .is_some_and(|rest| rest.starts_with('/'))
183}
184
185/// The effects of one call, declared by its tool from the arguments.
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub struct CallEffects {
188    pub keys: Vec<EffectKey>,
189    /// `keys` lists everything the call does. `false` means the tool could
190    /// not tell (an opaque script), so policies must not read the list as
191    /// exhaustive.
192    pub complete: bool,
193    /// Every part of the call was read and `keys` name what it changes,
194    /// though the tool does not vouch for the list as `complete` (a shell
195    /// command made only of programs it models: a copy into the work area,
196    /// a listing, `date`). After the owner declines a step, such a call that
197    /// deletes nothing and reaches nothing outside is not taken for the
198    /// declined action by another route.
199    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
200    pub understood: bool,
201}
202
203impl CallEffects {
204    /// Effects not declared: the call may do anything.
205    pub fn unknown() -> Self {
206        Self {
207            keys: Vec::new(),
208            complete: false,
209            understood: false,
210        }
211    }
212
213    /// The call has no effects (a read).
214    pub fn none() -> Self {
215        Self {
216            keys: Vec::new(),
217            complete: true,
218            understood: true,
219        }
220    }
221
222    /// The effects a call's declared access implies, for a tool that
223    /// declares [`crate::Tool::access`] but not [`crate::Tool::effects`]:
224    /// every written path ([`EffectKey::path`]) a [`EffectClass::Write`]
225    /// (and a [`EffectClass::Delete`] too for a destructive tool), every
226    /// host contacted an [`EffectClass::Egress`] (`host:port`, the port
227    /// from the declaration, else the scheme's, https for a bare host), every command a
228    /// [`EffectClass::Process`] named by its program. A read-only tool
229    /// changes nothing, so only its hosts count. Never `complete`: the tool
230    /// declared what it touches, not that the list is all it does. A
231    /// relative path names no key (declare absolute paths, as
232    /// `Workspace::declare` gives). [`CallEffects::unknown`] for an empty
233    /// manifest.
234    ///
235    /// With these keys an owner's denial binds the rest of the run: a later
236    /// call that writes the same path, by any tool, is refused.
237    pub fn from_access(
238        access: &crate::AccessManifest,
239        annotations: crate::ToolAnnotations,
240    ) -> Self {
241        let mut keys: Vec<EffectKey> = Vec::new();
242        let mut push = |key: EffectKey| {
243            if !keys.contains(&key) {
244                keys.push(key);
245            }
246        };
247        if !annotations.read_only {
248            for path in &access.writes {
249                if let Some(key) = EffectKey::path(EffectClass::Write, path) {
250                    if annotations.destructive {
251                        push(EffectKey {
252                            class: EffectClass::Delete,
253                            target: key.target.clone(),
254                        });
255                    }
256                    push(key);
257                }
258            }
259            for command in &access.commands {
260                if let Some(program) = program_name(command) {
261                    push(EffectKey::named(EffectClass::Process, program));
262                }
263            }
264        }
265        for host in &access.hosts {
266            if let Some(key) = host_effect(host) {
267                push(key);
268            }
269        }
270        Self {
271            keys,
272            complete: false,
273            understood: false,
274        }
275    }
276
277    /// The tool vouches that the call changes no file: the list is
278    /// `complete` and names no path. For a call that may change things
279    /// (whose default effects are [`CallEffects::unknown`]), scope and
280    /// approval policies take an empty [`crate::AccessManifest`] as "changes
281    /// no path", not "paths not declared". A delegation, a ticket or an
282    /// order lookup declares this with [`CallEffects::none`] or its own
283    /// non-path keys. Effects never describe reads.
284    pub fn touches_no_paths(&self) -> bool {
285        self.complete && !self.keys.iter().any(|key| key.class.is_path())
286    }
287}
288
289/// The program a declared command runs: its first word, without its
290/// directory.
291fn program_name(command: &str) -> Option<&str> {
292    let first = command.split_whitespace().next()?;
293    let program = first.rsplit('/').next().unwrap_or(first);
294    (!program.is_empty()).then_some(program)
295}
296
297/// The egress effect of a declared host: `host`, `host:port`, or a URL
298/// (`scheme://user@host:port/path`).
299fn host_effect(declared: &str) -> Option<EffectKey> {
300    let declared = declared.trim();
301    let (scheme, rest) = match declared.split_once("://") {
302        Some((scheme, rest)) => (scheme, rest),
303        None => ("https", declared),
304    };
305    let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
306    let authority = authority.rsplit('@').next().unwrap_or(authority);
307    let (host, port) = if let Some(bracketed) = authority.strip_prefix('[') {
308        // An IPv6 literal: `[::1]` or `[::1]:8080`.
309        let (host, after) = bracketed.split_once(']')?;
310        (host, after.strip_prefix(':').and_then(|p| p.parse().ok()))
311    } else {
312        match authority.rsplit_once(':') {
313            Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => {
314                (host, port.parse().ok())
315            }
316            _ => (authority, None),
317        }
318    };
319    if host.is_empty() {
320        return None;
321    }
322    Some(EffectKey::egress(scheme, host, port))
323}
324
325/// How much is at stake in an approval request.
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
327#[serde(rename_all = "snake_case")]
328#[non_exhaustive]
329pub enum ApprovalRisk {
330    /// A call new to the owner with nothing known to be at stake.
331    Low,
332    Medium,
333    High,
334    Critical,
335}
336
337/// What the owner is asked to approve.
338#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
339pub struct OwnerApprovalRequest {
340    /// The effects the call would have. A denial records them in
341    /// [`crate::RunState::declined`].
342    pub effects: Vec<EffectKey>,
343    /// What the owner sees.
344    pub summary: String,
345    /// The exact action string that stored grants are matched against (for
346    /// example a command line, or `METHOD url`).
347    pub subject: String,
348    pub risk: ApprovalRisk,
349    #[serde(default, skip_serializing_if = "Vec::is_empty")]
350    pub warnings: Vec<String>,
351    /// What the card says, as typed facts each channel renders. Plain
352    /// words only, never authority: grants match `subject`. `None` shows
353    /// `summary` and `warnings` as they are.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub card: Option<Box<ApprovalCard>>,
356}
357
358impl OwnerApprovalRequest {
359    /// A request with no declared effects and no card: the owner sees
360    /// `summary` and `warnings`, and stored grants match `subject`.
361    pub fn plain(
362        summary: impl Into<String>,
363        subject: impl Into<String>,
364        risk: ApprovalRisk,
365        warnings: Vec<String>,
366    ) -> Self {
367        Self {
368            effects: Vec::new(),
369            summary: summary.into(),
370            subject: subject.into(),
371            risk,
372            warnings,
373            card: None,
374        }
375    }
376
377    /// The request to ask the owner about `call`, the way
378    /// `aidaemon_policies::ApprovalPolicy` asks: the call's declared effects
379    /// (from `info`), its tool and arguments as the subject grants match,
380    /// [`ApprovalRisk::Critical`] for a destructive tool and
381    /// [`ApprovalRisk::High`] otherwise, and a card naming the action (a
382    /// command line collapsed under its title, else the tool with its
383    /// arguments collapsed). `why` ends the summary when it is not empty.
384    ///
385    /// A hook asks with it through [`crate::ToolDecision::ask`]:
386    ///
387    /// ```
388    /// use aidaemon_core::{OwnerApprovalRequest, ToolCall, ToolDecision, ToolInfo};
389    ///
390    /// fn decide(call: &ToolCall, info: &ToolInfo) -> ToolDecision {
391    ///     ToolDecision::ask(OwnerApprovalRequest::for_call(call, info, "it spends money"))
392    /// }
393    /// ```
394    pub fn for_call(call: &crate::ToolCall, info: &crate::ToolInfo, why: &str) -> Self {
395        Self::for_tool(&call.name, &call.arguments, info, why)
396    }
397
398    /// [`OwnerApprovalRequest::for_call`] from a tool name and arguments
399    /// (`Value::Null` when there are none).
400    pub fn for_tool(
401        tool: &str,
402        arguments: &serde_json::Value,
403        info: &crate::ToolInfo,
404        why: &str,
405    ) -> Self {
406        let subject = if arguments.is_null() {
407            tool.to_string()
408        } else {
409            format!("{tool} {arguments}")
410        };
411        let why = why.trim();
412        Self {
413            card: Some(Box::new(call_card(tool, arguments, info))),
414            effects: info.effects.keys.clone(),
415            summary: if why.is_empty() {
416                format!("Run {subject}")
417            } else {
418                format!("Run {subject}: {why}")
419            },
420            subject,
421            risk: if info.annotations.destructive {
422                ApprovalRisk::Critical
423            } else {
424                ApprovalRisk::High
425            },
426            warnings: Vec::new(),
427        }
428    }
429}
430
431/// The card for a call asked about, from the call's own fields and its
432/// annotations: a command line (with its own title) shown collapsed under a
433/// plain sentence, else the tool's name with its arguments collapsed. Never
434/// the raw JSON as the headline.
435fn call_card(tool: &str, arguments: &serde_json::Value, info: &crate::ToolInfo) -> ApprovalCard {
436    let text = |key: &str| arguments.get(key).and_then(serde_json::Value::as_str);
437    let action = match text("command").or_else(|| text("script")) {
438        Some(line) => CardAction::Command {
439            line: line.to_string(),
440            title: text("description")
441                .map(|title| title.split_whitespace().collect::<Vec<_>>().join(" "))
442                .filter(|title| !title.is_empty()),
443            looks_inside: Vec::new(),
444        },
445        None => CardAction::Use {
446            what: format!("use {}", tool.replace('_', " ")),
447            detail: (!arguments.is_null()).then(|| arguments.to_string()),
448        },
449    };
450    ApprovalCard {
451        impact: info.annotations.destructive.then(|| HighImpact::Deletes {
452            targets: Vec::new(),
453        }),
454        ..ApprovalCard::new(action)
455    }
456}
457
458/// An approval card's content as facts, so every channel says the same
459/// thing in its own formatting: who asks, what will happen, why the owner
460/// is asked, and the one high-impact effect worth a warning.
461#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
462pub struct ApprovalCard {
463    /// The helper asking ("Drupal install"); `None` for the assistant
464    /// itself.
465    #[serde(default, skip_serializing_if = "Option::is_none")]
466    pub asked_by: Option<String>,
467    /// The helper run asking, when a coding agent a run launched asks: the
468    /// key a client finds that agent by.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub run: Option<String>,
471    pub action: CardAction,
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub reason: Option<AskReason>,
474    /// The effect that earns a warning. `None` for ordinary work, which
475    /// gets no warning however the request's risk is rated.
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub impact: Option<HighImpact>,
478}
479
480impl ApprovalCard {
481    pub fn new(action: CardAction) -> Self {
482        Self {
483            asked_by: None,
484            run: None,
485            action,
486            reason: None,
487            impact: None,
488        }
489    }
490}
491
492/// What allowing the call does.
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
494#[serde(rename_all = "snake_case", tag = "kind")]
495#[non_exhaustive]
496pub enum CardAction {
497    /// Run a command on the owner's computer.
498    Command {
499        /// The exact line that runs (secrets hidden); shown collapsed,
500        /// never as the headline.
501        line: String,
502        /// The few plain words the call gave for itself (`description`).
503        #[serde(default, skip_serializing_if = "Option::is_none")]
504        title: Option<String>,
505        /// The folders a read-only command only looks inside, by name.
506        #[serde(default, skip_serializing_if = "Vec::is_empty")]
507        looks_inside: Vec<String>,
508    },
509    /// Let the browser open a site on this computer.
510    OpenLocalSite {
511        site: String,
512        /// How long a one-time allowance lasts.
513        once_minutes: u64,
514    },
515    /// Click a button on a web site in the browser (one whose effect the
516    /// page's script decides). Allow Once covers only this click; allowing
517    /// it for the session covers buttons on `site` (an origin) until the
518    /// browser session ends. Forms, passwords and payment fields still ask
519    /// every time.
520    ClickOnSite {
521        site: String,
522        /// The selector the click targets, shown collapsed.
523        #[serde(default, skip_serializing_if = "Option::is_none")]
524        target: Option<String>,
525    },
526    /// Use a tool; `what` completes "wants to …".
527    Use {
528        what: String,
529        /// The call's arguments as they would run, shown collapsed.
530        #[serde(default, skip_serializing_if = "Option::is_none")]
531        detail: Option<String>,
532    },
533    /// The agent asks the owner to do something themselves on a live
534    /// surface (sign in, enter a code), then press Done. `what` is the
535    /// agent's few words; `site` the host only.
536    TakeOver {
537        surface_id: String,
538        what: String,
539        #[serde(default, skip_serializing_if = "Option::is_none")]
540        site: Option<String>,
541        /// Whether a sign-in made there is kept for later tasks.
542        #[serde(default, skip_serializing_if = "Option::is_none")]
543        keeps_sign_in: Option<bool>,
544        /// Where the owner's app opens the live view, when the daemon has an
545        /// address a phone can reach. The id in it grants nothing alone.
546        #[serde(default, skip_serializing_if = "Option::is_none")]
547        open_url: Option<String>,
548    },
549}
550
551/// Why the owner is asked.
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553#[serde(rename_all = "snake_case", tag = "kind")]
554#[non_exhaustive]
555pub enum AskReason {
556    /// The work read content from outside, and the clean check could not
557    /// confirm this step fits the request.
558    ReadOutsideContent {
559        /// The check's one sentence, addressed to the owner.
560        #[serde(default, skip_serializing_if = "Option::is_none")]
561        check_says: Option<String>,
562    },
563    /// The owner said no to a step earlier in this run, and what this call
564    /// does cannot be fully told, so it is not run unasked.
565    AfterADecline {
566        /// What the owner said no to, in a few plain words (the declined
567        /// step's own title, or what it would have changed).
568        #[serde(default, skip_serializing_if = "Option::is_none")]
569        declined: Option<String>,
570    },
571}
572
573/// An effect that deserves a warning on the card.
574#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
575#[serde(rename_all = "snake_case", tag = "kind")]
576#[non_exhaustive]
577pub enum HighImpact {
578    /// Deletes files: the targets when they can be read.
579    Deletes {
580        #[serde(default, skip_serializing_if = "Vec::is_empty")]
581        targets: Vec<String>,
582    },
583    /// Sends or posts something to another service.
584    Sends,
585    /// Spends money.
586    Spends,
587    /// Writes outside the work area.
588    WritesOutsideWorkArea,
589}
590
591/// Who an interruption is waiting for.
592#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
593#[serde(rename_all = "snake_case")]
594#[non_exhaustive]
595pub enum InterruptKind {
596    /// A check of a call made after the run read untrusted content (and,
597    /// for interruptions saved before kinds existed, any interruption).
598    #[default]
599    Untrusted,
600    /// The owner must approve the call.
601    OwnerApproval(OwnerApprovalRequest),
602}
603
604/// Owner declines shared by a family of runs: a run and the child runs it
605/// starts (and their children). A decline recorded in any of them reaches
606/// every other one before its next call, so a parent is refused an effect
607/// the owner declined inside its child, and a running child is refused one
608/// the owner declined in its parent after the child started.
609///
610/// Attach it with [`crate::RunState::share_declines`]. The kernel exchanges
611/// it with the run's own [`crate::RunState::declined`] when a turn starts,
612/// before each call is judged, when the owner declines, and when the run
613/// ends; the run's own list stays the serialized source of truth (so a
614/// parent whose child was declined something never ends `Succeeded`). The
615/// handle itself is not serialized: a run resumed from saved state keeps
616/// its own declines and shares them again once the application reattaches
617/// a set.
618///
619/// It only grows. Clones share one set.
620#[derive(Clone, Default)]
621pub struct SharedDeclines(std::sync::Arc<std::sync::Mutex<Vec<EffectKey>>>);
622
623impl SharedDeclines {
624    pub fn new() -> Self {
625        Self::default()
626    }
627
628    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<EffectKey>> {
629        self.0.lock().unwrap_or_else(|e| e.into_inner())
630    }
631
632    /// Add effects (duplicates are ignored).
633    pub fn record(&self, effects: &[EffectKey]) {
634        let mut shared = self.lock();
635        for effect in effects {
636            if !shared.contains(effect) {
637                shared.push(effect.clone());
638            }
639        }
640    }
641
642    /// Every effect declined so far, in the order first recorded.
643    pub fn snapshot(&self) -> Vec<EffectKey> {
644        self.lock().clone()
645    }
646
647    /// Publish `local`'s effects and take in the others'. Returns whether
648    /// `local` grew.
649    pub(crate) fn exchange(&self, local: &mut Vec<EffectKey>) -> bool {
650        let mut shared = self.lock();
651        for effect in local.iter() {
652            if !shared.contains(effect) {
653                shared.push(effect.clone());
654            }
655        }
656        let before = local.len();
657        for effect in shared.iter() {
658            if !local.contains(effect) {
659                local.push(effect.clone());
660            }
661        }
662        local.len() > before
663    }
664
665    /// Both handles share one set.
666    pub fn same_set(&self, other: &SharedDeclines) -> bool {
667        std::sync::Arc::ptr_eq(&self.0, &other.0)
668    }
669}
670
671/// Two handles are equal when they share one set.
672impl PartialEq for SharedDeclines {
673    fn eq(&self, other: &Self) -> bool {
674        self.same_set(other)
675    }
676}
677
678impl std::fmt::Debug for SharedDeclines {
679    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680        f.debug_tuple("SharedDeclines")
681            .field(&self.snapshot())
682            .finish()
683    }
684}