aidaemon-core 0.21.0

The aidaemon agent kernel: a small, hook-driven agent loop with tools, providers, receipts and resumable state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Typed call effects and owner approvals.
//!
//! A tool declares what one call does and to which target
//! ([`Tool::effects`](crate::Tool::effects)), so policies judge effects
//! rather than tool names. A hook that wants the owner to decide returns
//! [`InterruptKind::OwnerApproval`]; when the resolver denies it, the kernel
//! remembers the request's effects in [`crate::RunState::declined`] for the
//! rest of the run.

use serde::{Deserialize, Serialize};

/// Prefix of the reason recorded when the owner declines an approval.
pub const OWNER_DECLINED: &str = "[OWNER DECLINED]";

/// Prefix of the reason for a call whose owner card got no answer (it
/// expired, could not be delivered, or the turn was cancelled). Not a
/// refusal: nothing is remembered as declined.
pub const OWNER_UNANSWERED: &str = "[NO ANSWER]";

/// Prefix of the reason an outbound secret scan (the
/// [`crate::Safeguard::Egress`] hook) gives when it refuses a call.
pub const EGRESS_BLOCKED: &str = "[EGRESS BLOCKED]";

/// Prefix of the reason the [`crate::AuthorityHook`] gives when a call is
/// outside what the run may do.
pub const AUTHORITY_BLOCKED: &str = "[AUTHORITY BLOCKED]";

/// Prefix of the refusal a rejected egress call returns to the model after
/// the run read untrusted content.
pub const UNTRUSTED_BLOCKED: &str = "[UNTRUSTED BLOCKED]";

/// What kind of thing a call does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EffectClass {
    /// Sends data or acts on a host outside the owner's machine.
    Egress,
    /// Deletes a path.
    Delete,
    /// Creates or modifies a path.
    Write,
    /// Changes configuration stored at a path.
    Configuration,
    /// Uses a stored credential.
    Credential,
    /// Starts a program.
    Process,
    /// One exact call, named by its approval subject. Recorded when the
    /// owner declines a request that declared no effects, so the identical
    /// request is not put to the owner again.
    Call,
}

impl std::fmt::Display for EffectClass {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Egress => "egress",
            Self::Delete => "delete",
            Self::Write => "write",
            Self::Configuration => "configuration",
            Self::Credential => "credential",
            Self::Process => "process",
            Self::Call => "call",
        })
    }
}

impl EffectClass {
    /// Whether targets of this class are paths, so a target covers the
    /// paths below it.
    fn is_path(self) -> bool {
        matches!(self, Self::Delete | Self::Write | Self::Configuration)
    }
}

/// One effect of a call on one target.
///
/// The producer normalizes `target`: lowercase `host:port` for
/// [`EffectClass::Egress`]; an absolute, normalized path for
/// [`EffectClass::Delete`], [`EffectClass::Write`] and
/// [`EffectClass::Configuration`]; the profile name for
/// [`EffectClass::Credential`]; the program name for [`EffectClass::Process`].
/// Build keys with [`EffectKey::path`], [`EffectKey::egress`] and
/// [`EffectKey::named`] so every producer uses the same convention.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EffectKey {
    pub class: EffectClass,
    pub target: String,
}

impl EffectKey {
    /// A path effect (`Delete`, `Write`, `Configuration`) on an absolute
    /// path, normalized lexically: empty and `.` components dropped, `..`
    /// resolved, no trailing slash. `None` for a relative path or one that
    /// climbs above `/`. The filesystem is not consulted (symlinks are not
    /// resolved). A Windows path with a drive (`C:\Users\x`, `c:/Users/x`)
    /// is absolute too, written `C:/Users/x`: `\` and `/` both separate its
    /// components, and the drive letter is uppercase.
    pub fn path(class: EffectClass, raw: &str) -> Option<EffectKey> {
        let (root, rest, separators): (String, &str, &[char]) = match raw.as_bytes() {
            [b'/', ..] => (String::new(), raw, &['/']),
            [drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic() => (
                format!("{}:", (*drive as char).to_ascii_uppercase()),
                &raw[2..],
                &['/', '\\'],
            ),
            _ => return None,
        };
        let mut parts: Vec<&str> = Vec::new();
        for part in rest.split(separators) {
            match part {
                "" | "." => {}
                ".." => {
                    parts.pop()?;
                }
                part => parts.push(part),
            }
        }
        Some(EffectKey {
            class,
            target: format!("{root}/{}", parts.join("/")),
        })
    }

    /// An egress effect on `host`, with target `host:port`: the host
    /// lowercased and without a trailing dot (`h.example.` is `h.example`),
    /// and the port given or else the scheme's default (http
    /// 80, https 443, ssh 22; 0 for an unknown scheme).
    pub fn egress(scheme: &str, host: &str, port: Option<u16>) -> EffectKey {
        let port = port.unwrap_or_else(|| match scheme.to_ascii_lowercase().as_str() {
            "http" => 80,
            "https" => 443,
            "ssh" => 22,
            _ => 0,
        });
        EffectKey {
            class: EffectClass::Egress,
            target: format!("{}:{port}", host.to_ascii_lowercase().trim_end_matches('.')),
        }
    }

    /// An effect named by an identifier rather than a path or host: the
    /// profile name for [`EffectClass::Credential`], the program name for
    /// [`EffectClass::Process`].
    pub fn named(class: EffectClass, name: &str) -> EffectKey {
        EffectKey {
            class,
            target: name.to_string(),
        }
    }

    /// Same class, and the same target or, for path classes, one target is
    /// the other or below it. Targets are compared as given, so both keys
    /// must be normalized (built with [`EffectKey::path`],
    /// [`EffectKey::egress`] or [`EffectKey::named`]): `h.example.invalid`
    /// does not overlap `h.example.invalid:443`, and `/a/../b` does not
    /// overlap `/b`.
    pub fn overlaps(&self, other: &EffectKey) -> bool {
        if self.class != other.class {
            return false;
        }
        if self.target == other.target {
            return true;
        }
        self.class.is_path()
            && (path_covers(&self.target, &other.target)
                || path_covers(&other.target, &self.target))
    }
}

/// Whether `inner` is `outer` or a path below it, compared by component.
fn path_covers(outer: &str, inner: &str) -> bool {
    let outer = outer.trim_end_matches('/');
    let inner = inner.trim_end_matches('/');
    if outer == inner {
        return true;
    }
    // After trimming, the root is empty and covers every absolute path.
    inner
        .strip_prefix(outer)
        .is_some_and(|rest| rest.starts_with('/'))
}

/// The effects of one call, declared by its tool from the arguments.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CallEffects {
    pub keys: Vec<EffectKey>,
    /// `keys` lists everything the call does. `false` means the tool could
    /// not tell (an opaque script), so policies must not read the list as
    /// exhaustive.
    pub complete: bool,
    /// Every part of the call was read and `keys` name what it changes,
    /// though the tool does not vouch for the list as `complete` (a shell
    /// command made only of programs it models: a copy into the work area,
    /// a listing, `date`). After the owner declines a step, such a call that
    /// deletes nothing and reaches nothing outside is not taken for the
    /// declined action by another route.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub understood: bool,
}

impl CallEffects {
    /// Effects not declared: the call may do anything.
    pub fn unknown() -> Self {
        Self {
            keys: Vec::new(),
            complete: false,
            understood: false,
        }
    }

    /// The call has no effects (a read).
    pub fn none() -> Self {
        Self {
            keys: Vec::new(),
            complete: true,
            understood: true,
        }
    }

    /// The effects a call's declared access implies, for a tool that
    /// declares [`crate::Tool::access`] but not [`crate::Tool::effects`]:
    /// every written path ([`EffectKey::path`]) a [`EffectClass::Write`]
    /// (and a [`EffectClass::Delete`] too for a destructive tool), every
    /// host contacted an [`EffectClass::Egress`] (`host:port`, the port
    /// from the declaration, else the scheme's, https for a bare host), every command a
    /// [`EffectClass::Process`] named by its program. A read-only tool
    /// changes nothing, so only its hosts count. Never `complete`: the tool
    /// declared what it touches, not that the list is all it does. A
    /// relative path names no key (declare absolute paths, as
    /// `Workspace::declare` gives). [`CallEffects::unknown`] for an empty
    /// manifest.
    ///
    /// With these keys an owner's denial binds the rest of the run: a later
    /// call that writes the same path, by any tool, is refused.
    pub fn from_access(
        access: &crate::AccessManifest,
        annotations: crate::ToolAnnotations,
    ) -> Self {
        let mut keys: Vec<EffectKey> = Vec::new();
        let mut push = |key: EffectKey| {
            if !keys.contains(&key) {
                keys.push(key);
            }
        };
        if !annotations.read_only {
            for path in &access.writes {
                if let Some(key) = EffectKey::path(EffectClass::Write, path) {
                    if annotations.destructive {
                        push(EffectKey {
                            class: EffectClass::Delete,
                            target: key.target.clone(),
                        });
                    }
                    push(key);
                }
            }
            for command in &access.commands {
                if let Some(program) = program_name(command) {
                    push(EffectKey::named(EffectClass::Process, program));
                }
            }
        }
        for host in &access.hosts {
            if let Some(key) = host_effect(host) {
                push(key);
            }
        }
        Self {
            keys,
            complete: false,
            understood: false,
        }
    }

    /// The tool vouches that the call changes no file: the list is
    /// `complete` and names no path. For a call that may change things
    /// (whose default effects are [`CallEffects::unknown`]), scope and
    /// approval policies take an empty [`crate::AccessManifest`] as "changes
    /// no path", not "paths not declared". A delegation, a ticket or an
    /// order lookup declares this with [`CallEffects::none`] or its own
    /// non-path keys. Effects never describe reads.
    pub fn touches_no_paths(&self) -> bool {
        self.complete && !self.keys.iter().any(|key| key.class.is_path())
    }
}

/// The program a declared command runs: its first word, without its
/// directory.
fn program_name(command: &str) -> Option<&str> {
    let first = command.split_whitespace().next()?;
    let program = first.rsplit('/').next().unwrap_or(first);
    (!program.is_empty()).then_some(program)
}

/// The egress effect of a declared host: `host`, `host:port`, or a URL
/// (`scheme://user@host:port/path`).
fn host_effect(declared: &str) -> Option<EffectKey> {
    let declared = declared.trim();
    let (scheme, rest) = match declared.split_once("://") {
        Some((scheme, rest)) => (scheme, rest),
        None => ("https", declared),
    };
    let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
    let authority = authority.rsplit('@').next().unwrap_or(authority);
    let (host, port) = if let Some(bracketed) = authority.strip_prefix('[') {
        // An IPv6 literal: `[::1]` or `[::1]:8080`.
        let (host, after) = bracketed.split_once(']')?;
        (host, after.strip_prefix(':').and_then(|p| p.parse().ok()))
    } else {
        match authority.rsplit_once(':') {
            Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => {
                (host, port.parse().ok())
            }
            _ => (authority, None),
        }
    };
    if host.is_empty() {
        return None;
    }
    Some(EffectKey::egress(scheme, host, port))
}

/// How much is at stake in an approval request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ApprovalRisk {
    /// A call new to the owner with nothing known to be at stake.
    Low,
    Medium,
    High,
    Critical,
}

/// What the owner is asked to approve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OwnerApprovalRequest {
    /// The effects the call would have. A denial records them in
    /// [`crate::RunState::declined`].
    pub effects: Vec<EffectKey>,
    /// What the owner sees.
    pub summary: String,
    /// The exact action string that stored grants are matched against (for
    /// example a command line, or `METHOD url`).
    pub subject: String,
    pub risk: ApprovalRisk,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
    /// What the card says, as typed facts each channel renders. Plain
    /// words only, never authority: grants match `subject`. `None` shows
    /// `summary` and `warnings` as they are.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub card: Option<Box<ApprovalCard>>,
}

impl OwnerApprovalRequest {
    /// The request to ask the owner about `call`, the way
    /// `aidaemon_policies::ApprovalPolicy` asks: the call's declared effects
    /// (from `info`), its tool and arguments as the subject grants match,
    /// [`ApprovalRisk::Critical`] for a destructive tool and
    /// [`ApprovalRisk::High`] otherwise, and a card naming the action (a
    /// command line collapsed under its title, else the tool with its
    /// arguments collapsed). `why` ends the summary when it is not empty.
    ///
    /// A hook asks with it through [`crate::ToolDecision::ask`]:
    ///
    /// ```
    /// use aidaemon_core::{OwnerApprovalRequest, ToolCall, ToolDecision, ToolInfo};
    ///
    /// fn decide(call: &ToolCall, info: &ToolInfo) -> ToolDecision {
    ///     ToolDecision::ask(OwnerApprovalRequest::for_call(call, info, "it spends money"))
    /// }
    /// ```
    pub fn for_call(call: &crate::ToolCall, info: &crate::ToolInfo, why: &str) -> Self {
        Self::for_tool(&call.name, &call.arguments, info, why)
    }

    /// [`OwnerApprovalRequest::for_call`] from a tool name and arguments
    /// (`Value::Null` when there are none).
    pub fn for_tool(
        tool: &str,
        arguments: &serde_json::Value,
        info: &crate::ToolInfo,
        why: &str,
    ) -> Self {
        let subject = if arguments.is_null() {
            tool.to_string()
        } else {
            format!("{tool} {arguments}")
        };
        let why = why.trim();
        Self {
            card: Some(Box::new(call_card(tool, arguments, info))),
            effects: info.effects.keys.clone(),
            summary: if why.is_empty() {
                format!("Run {subject}")
            } else {
                format!("Run {subject}: {why}")
            },
            subject,
            risk: if info.annotations.destructive {
                ApprovalRisk::Critical
            } else {
                ApprovalRisk::High
            },
            warnings: Vec::new(),
        }
    }
}

/// The card for a call asked about, from the call's own fields and its
/// annotations: a command line (with its own title) shown collapsed under a
/// plain sentence, else the tool's name with its arguments collapsed. Never
/// the raw JSON as the headline.
fn call_card(tool: &str, arguments: &serde_json::Value, info: &crate::ToolInfo) -> ApprovalCard {
    let text = |key: &str| arguments.get(key).and_then(serde_json::Value::as_str);
    let action = match text("command").or_else(|| text("script")) {
        Some(line) => CardAction::Command {
            line: line.to_string(),
            title: text("description")
                .map(|title| title.split_whitespace().collect::<Vec<_>>().join(" "))
                .filter(|title| !title.is_empty()),
            looks_inside: Vec::new(),
        },
        None => CardAction::Use {
            what: format!("use {}", tool.replace('_', " ")),
            detail: (!arguments.is_null()).then(|| arguments.to_string()),
        },
    };
    ApprovalCard {
        impact: info.annotations.destructive.then(|| HighImpact::Deletes {
            targets: Vec::new(),
        }),
        ..ApprovalCard::new(action)
    }
}

/// An approval card's content as facts, so every channel says the same
/// thing in its own formatting: who asks, what will happen, why the owner
/// is asked, and the one high-impact effect worth a warning.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalCard {
    /// The helper asking ("Drupal install"); `None` for the assistant
    /// itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asked_by: Option<String>,
    pub action: CardAction,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<AskReason>,
    /// The effect that earns a warning. `None` for ordinary work, which
    /// gets no warning however the request's risk is rated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub impact: Option<HighImpact>,
}

impl ApprovalCard {
    pub fn new(action: CardAction) -> Self {
        Self {
            asked_by: None,
            action,
            reason: None,
            impact: None,
        }
    }
}

/// What allowing the call does.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum CardAction {
    /// Run a command on the owner's computer.
    Command {
        /// The exact line that runs (secrets hidden); shown collapsed,
        /// never as the headline.
        line: String,
        /// The few plain words the call gave for itself (`description`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// The folders a read-only command only looks inside, by name.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        looks_inside: Vec<String>,
    },
    /// Let the browser open a site on this computer.
    OpenLocalSite {
        site: String,
        /// How long a one-time allowance lasts.
        once_minutes: u64,
    },
    /// Click a button on a web site in the browser (one whose effect the
    /// page's script decides). Allow Once covers only this click; allowing
    /// it for the session covers buttons on `site` (an origin) until the
    /// browser session ends. Forms, passwords and payment fields still ask
    /// every time.
    ClickOnSite {
        site: String,
        /// The selector the click targets, shown collapsed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target: Option<String>,
    },
    /// Use a tool; `what` completes "wants to …".
    Use {
        what: String,
        /// The call's arguments as they would run, shown collapsed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
    },
    /// The agent asks the owner to do something themselves on a live
    /// surface (sign in, enter a code), then press Done. `what` is the
    /// agent's few words; `site` the host only.
    TakeOver {
        surface_id: String,
        what: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        site: Option<String>,
        /// Whether a sign-in made there is kept for later tasks.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        keeps_sign_in: Option<bool>,
        /// Where the owner's app opens the live view, when the daemon has an
        /// address a phone can reach. The id in it grants nothing alone.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        open_url: Option<String>,
    },
}

/// Why the owner is asked.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum AskReason {
    /// The work read content from outside, and the clean check could not
    /// confirm this step fits the request.
    ReadOutsideContent {
        /// The check's one sentence, addressed to the owner.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        check_says: Option<String>,
    },
    /// The owner said no to a step earlier in this run, and what this call
    /// does cannot be fully told, so it is not run unasked.
    AfterADecline {
        /// What the owner said no to, in a few plain words (the declined
        /// step's own title, or what it would have changed).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        declined: Option<String>,
    },
}

/// An effect that deserves a warning on the card.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum HighImpact {
    /// Deletes files: the targets when they can be read.
    Deletes {
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        targets: Vec<String>,
    },
    /// Sends or posts something to another service.
    Sends,
    /// Spends money.
    Spends,
    /// Writes outside the work area.
    WritesOutsideWorkArea,
}

/// Who an interruption is waiting for.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum InterruptKind {
    /// A check of a call made after the run read untrusted content (and,
    /// for interruptions saved before kinds existed, any interruption).
    #[default]
    Untrusted,
    /// The owner must approve the call.
    OwnerApproval(OwnerApprovalRequest),
}

/// Owner declines shared by a family of runs: a run and the child runs it
/// starts (and their children). A decline recorded in any of them reaches
/// every other one before its next call, so a parent is refused an effect
/// the owner declined inside its child, and a running child is refused one
/// the owner declined in its parent after the child started.
///
/// Attach it with [`crate::RunState::share_declines`]. The kernel exchanges
/// it with the run's own [`crate::RunState::declined`] when a turn starts,
/// before each call is judged, when the owner declines, and when the run
/// ends; the run's own list stays the serialized source of truth (so a
/// parent whose child was declined something never ends `Succeeded`). The
/// handle itself is not serialized: a run resumed from saved state keeps
/// its own declines and shares them again once the application reattaches
/// a set.
///
/// It only grows. Clones share one set.
#[derive(Clone, Default)]
pub struct SharedDeclines(std::sync::Arc<std::sync::Mutex<Vec<EffectKey>>>);

impl SharedDeclines {
    pub fn new() -> Self {
        Self::default()
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<EffectKey>> {
        self.0.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Add effects (duplicates are ignored).
    pub fn record(&self, effects: &[EffectKey]) {
        let mut shared = self.lock();
        for effect in effects {
            if !shared.contains(effect) {
                shared.push(effect.clone());
            }
        }
    }

    /// Every effect declined so far, in the order first recorded.
    pub fn snapshot(&self) -> Vec<EffectKey> {
        self.lock().clone()
    }

    /// Publish `local`'s effects and take in the others'. Returns whether
    /// `local` grew.
    pub(crate) fn exchange(&self, local: &mut Vec<EffectKey>) -> bool {
        let mut shared = self.lock();
        for effect in local.iter() {
            if !shared.contains(effect) {
                shared.push(effect.clone());
            }
        }
        let before = local.len();
        for effect in shared.iter() {
            if !local.contains(effect) {
                local.push(effect.clone());
            }
        }
        local.len() > before
    }

    /// Both handles share one set.
    pub fn same_set(&self, other: &SharedDeclines) -> bool {
        std::sync::Arc::ptr_eq(&self.0, &other.0)
    }
}

/// Two handles are equal when they share one set.
impl PartialEq for SharedDeclines {
    fn eq(&self, other: &Self) -> bool {
        self.same_set(other)
    }
}

impl std::fmt::Debug for SharedDeclines {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("SharedDeclines")
            .field(&self.snapshot())
            .finish()
    }
}