Skip to main content

tilo_action_policy/
member.rs

1//! Who a workspace's people, agents and bots are, and who made a change.
2
3use serde::{Deserialize, Serialize};
4use tilo_app_id::AppId;
5
6use crate::person::PersonId;
7
8/// A person, agent or bot in a workspace.
9#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum MemberId {
12    /// A person, by their root public key ([`PersonId`]).
13    Person(PersonId),
14    /// An agent: its id and the person it acts for, whom its certificate chains to. The pair is
15    /// the agent: `scout` acting for one person and `scout` acting for another are two members,
16    /// each with its own person's reach, answers and stops.
17    Agent {
18        id: String,
19        person: PersonId,
20    },
21    Bot(String),
22}
23
24/// The prefix of a direct conversation's id: the members it is with follow
25/// it, sorted, as JSON.
26pub const DIRECT_CONVERSATION_PREFIX: &str = "direct:";
27
28impl MemberId {
29    /// The value a text mark naming this member holds, in the one form: the id as JSON
30    /// (`{"person":…}`). A mention in any text is stored as this.
31    #[must_use]
32    pub fn mark_value(&self) -> String {
33        serde_json::to_string(self).unwrap_or_default()
34    }
35
36    /// The member a text mark's `value` names ([`Self::mark_value`]); `None` for a value
37    /// naming anything else.
38    #[must_use]
39    pub fn of_mark_value(value: &str) -> Option<Self> {
40        value
41            .starts_with('{')
42            .then(|| serde_json::from_str(value).ok())
43            .flatten()
44    }
45
46    /// The id of the one direct conversation with exactly `members`, as every
47    /// app that reads or writes conversations spells it: derived from the
48    /// set, so two devices that open the same conversation at once make one,
49    /// and neither has to create it first.
50    #[must_use]
51    pub fn direct_conversation(members: impl IntoIterator<Item = Self>) -> String {
52        let mut members: Vec<Self> = members.into_iter().collect();
53        members.sort();
54        members.dedup();
55        let members = serde_json::to_string(&members).unwrap_or_default();
56        format!("{DIRECT_CONVERSATION_PREFIX}{members}")
57    }
58
59    /// The members the direct conversation `id` is with, or none when `id`
60    /// names no direct conversation.
61    #[must_use]
62    pub fn direct_conversation_members(id: &str) -> Option<Vec<Self>> {
63        let members = id.strip_prefix(DIRECT_CONVERSATION_PREFIX)?;
64        serde_json::from_str::<Vec<Self>>(members)
65            .ok()
66            .filter(|members| !members.is_empty())
67    }
68
69    #[track_caller]
70    #[must_use]
71    pub fn person(id: impl Into<PersonId>) -> Self {
72        Self::Person(id.into())
73    }
74
75    /// `id` as a person, when it is a person's bare root key: an id read from
76    /// stored data or another device, which [`Self::person`] would panic on.
77    #[must_use]
78    pub fn parsed_person(id: &str) -> Option<Self> {
79        PersonId::parse(id).ok().map(Self::Person)
80    }
81
82    /// The agent `id` acting for `person`.
83    #[track_caller]
84    #[must_use]
85    pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
86        Self::Agent {
87            id: id.into(),
88            person: person.into(),
89        }
90    }
91
92    #[must_use]
93    pub fn bot(id: impl Into<String>) -> Self {
94        Self::Bot(id.into())
95    }
96
97    /// The id inside the kind: an agent's own id, without its person.
98    #[must_use]
99    pub fn id(&self) -> &str {
100        match self {
101            Self::Person(id) => id.as_str(),
102            Self::Agent { id, .. } | Self::Bot(id) => id,
103        }
104    }
105
106    #[must_use]
107    pub fn agent_id(&self) -> Option<&str> {
108        match self {
109            Self::Agent { id, .. } => Some(id),
110            Self::Person(_) | Self::Bot(_) => None,
111        }
112    }
113
114    /// The person an agent acts for, when this is an agent.
115    #[must_use]
116    pub fn agent_person(&self) -> Option<&PersonId> {
117        match self {
118            Self::Agent { person, .. } => Some(person),
119            Self::Person(_) | Self::Bot(_) => None,
120        }
121    }
122
123    /// The agent's id and its person, when this is an agent.
124    #[must_use]
125    pub fn as_agent(&self) -> Option<(&str, &PersonId)> {
126        match self {
127            Self::Agent { id, person } => Some((id, person)),
128            Self::Person(_) | Self::Bot(_) => None,
129        }
130    }
131
132    #[must_use]
133    pub fn bot_id(&self) -> Option<&str> {
134        match self {
135            Self::Bot(id) => Some(id),
136            Self::Person(_) | Self::Agent { .. } => None,
137        }
138    }
139
140    /// The person this is, when it is one.
141    #[must_use]
142    pub fn as_person(&self) -> Option<&PersonId> {
143        match self {
144            Self::Person(id) => Some(id),
145            Self::Agent { .. } | Self::Bot(_) => None,
146        }
147    }
148
149    /// The person this is, by their root key, when it is one.
150    #[must_use]
151    pub fn person_id(&self) -> Option<&str> {
152        self.as_person().map(PersonId::as_str)
153    }
154
155    #[must_use]
156    pub const fn is_person(&self) -> bool {
157        matches!(self, Self::Person(_))
158    }
159
160    #[must_use]
161    pub const fn is_agent(&self) -> bool {
162        matches!(self, Self::Agent { .. })
163    }
164
165    #[must_use]
166    pub const fn is_bot(&self) -> bool {
167        matches!(self, Self::Bot(_))
168    }
169
170    /// The bytes a document names this member's changes by: a person's root key as written, an
171    /// agent's `agent:<person>/<id>`, a bot's `bot:<id>`, as history reads them back.
172    #[must_use]
173    pub fn actor_bytes(&self) -> Vec<u8> {
174        match self {
175            Self::Person(id) => id.as_str().as_bytes().to_vec(),
176            Self::Agent { id, person } => {
177                [b"agent:", person.as_str().as_bytes(), b"/", id.as_bytes()].concat()
178            }
179            Self::Bot(id) => [b"bot:", id.as_bytes()].concat(),
180        }
181    }
182
183    /// The member whose changes a document names by `bytes` ([`Self::actor_bytes`]); `None` for
184    /// bytes no member writes as.
185    #[must_use]
186    pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
187        let text = std::str::from_utf8(bytes).ok()?;
188        let nonempty = |id: &str| (!id.is_empty()).then(|| id.to_owned());
189        if let Some(agent) = text.strip_prefix("agent:") {
190            let (person, id) = agent.split_once('/')?;
191            let person = PersonId::parse(&nonempty(person)?).ok()?;
192            return nonempty(id).map(|id| Self::Agent { id, person });
193        }
194        if let Some(id) = text.strip_prefix("bot:") {
195            return nonempty(id).map(Self::Bot);
196        }
197        nonempty(text).and_then(|id| PersonId::parse(&id).ok().map(Self::Person))
198    }
199}
200
201impl std::fmt::Display for MemberId {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        match self {
204            Self::Person(id) => write!(f, "person {}", short(id.as_str())),
205            Self::Agent { id, person } => write!(f, "agent {id} of {}", short(person.as_str())),
206            Self::Bot(id) => write!(f, "bot {}", short(id)),
207        }
208    }
209}
210
211fn short(id: &str) -> &str {
212    id.get(..12).unwrap_or(id)
213}
214
215/// An automation: saved steps with triggers, running for the member who owns
216/// it. Not a member.
217#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
218#[serde(transparent)]
219pub struct AutomationId(pub String);
220
221impl AutomationId {
222    #[must_use]
223    pub fn new(id: impl Into<String>) -> Self {
224        Self(id.into())
225    }
226
227    #[must_use]
228    pub fn as_str(&self) -> &str {
229        &self.0
230    }
231}
232
233/// One context of one agent: a conversation with a Tilo agent, or one Claude
234/// Code session.
235#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
236#[serde(transparent)]
237pub struct AgentSessionId(pub String);
238
239impl AgentSessionId {
240    #[must_use]
241    pub fn new(id: impl Into<String>) -> Self {
242        Self(id.into())
243    }
244
245    #[must_use]
246    pub fn as_str(&self) -> &str {
247        &self.0
248    }
249}
250
251/// The resource a change was made for: a chat message, an issue.
252#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
253#[serde(transparent)]
254pub struct ResourceId(pub String);
255
256impl ResourceId {
257    #[must_use]
258    pub fn new(id: impl Into<String>) -> Self {
259        Self(id.into())
260    }
261
262    #[must_use]
263    pub fn as_str(&self) -> &str {
264        &self.0
265    }
266}
267
268impl std::fmt::Display for ResourceId {
269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        f.write_str(&self.0)
271    }
272}
273
274/// Who made a change: a member, an automation running for one, or an app acting by itself.
275#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
276#[serde(rename_all = "snake_case")]
277pub enum Actor {
278    Member(MemberId),
279    Automation(AutomationId),
280    /// An app changing its own resources: a trigger it declares, or a migration of its
281    /// package.
282    App(AppId),
283    /// Someone with no identity in the workspace, by the key (hex) their page made and signs
284    /// each call with: a visitor at a public entry. It is no member and holds only what the
285    /// workspace opens to any key ([`crate::Grantee::AnyKey`]).
286    Visitor(String),
287}
288
289impl Actor {
290    #[must_use]
291    pub fn member(member: MemberId) -> Self {
292        Self::Member(member)
293    }
294
295    #[must_use]
296    pub fn automation(id: impl Into<String>) -> Self {
297        Self::Automation(AutomationId::new(id))
298    }
299
300    /// The grantee a grant names this actor by, when it is a member: an
301    /// automation is its owner's.
302    #[must_use]
303    pub fn grantee(&self) -> Option<crate::Grantee> {
304        Some(crate::granted_to(self.member_id()?))
305    }
306
307    /// The member, when the actor is one.
308    #[must_use]
309    pub fn member_id(&self) -> Option<&MemberId> {
310        match self {
311            Self::Member(member) => Some(member),
312            Self::Automation(_) | Self::App(_) | Self::Visitor(_) => None,
313        }
314    }
315
316    /// The person, when the actor is one.
317    #[must_use]
318    pub fn person_id(&self) -> Option<&str> {
319        self.member_id().and_then(MemberId::person_id)
320    }
321
322    /// The agent, when the actor is one.
323    #[must_use]
324    pub fn agent_id(&self) -> Option<&str> {
325        self.member_id().and_then(MemberId::agent_id)
326    }
327
328    /// The app, when the actor is one acting by itself.
329    #[must_use]
330    pub fn app(&self) -> Option<&AppId> {
331        match self {
332            Self::App(app) => Some(app),
333            Self::Member(_) | Self::Automation(_) | Self::Visitor(_) => None,
334        }
335    }
336
337    /// The bytes a document names this actor's changes by: a member's
338    /// [`MemberId::actor_bytes`], an automation's `automation:<id>`.
339    #[must_use]
340    pub fn actor_bytes(&self) -> Vec<u8> {
341        match self {
342            Self::Member(member) => member.actor_bytes(),
343            Self::Automation(id) => [b"automation:", id.as_str().as_bytes()].concat(),
344            Self::App(app) => [b"app:", app.as_str().as_bytes()].concat(),
345            Self::Visitor(key) => [b"visitor:", key.as_bytes()].concat(),
346        }
347    }
348
349    /// The actor whose changes a document names by `bytes` ([`Self::actor_bytes`]); `None` for
350    /// bytes no actor writes as.
351    #[must_use]
352    pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
353        let nonempty = |id: &[u8]| {
354            std::str::from_utf8(id)
355                .ok()
356                .filter(|id| !id.is_empty())
357                .map(str::to_owned)
358        };
359        if let Some(id) = bytes.strip_prefix(b"automation:") {
360            return nonempty(id).map(|id| Self::Automation(AutomationId(id)));
361        }
362        if let Some(app) = bytes.strip_prefix(b"app:") {
363            return nonempty(app).map(|app| Self::App(AppId::new(app)));
364        }
365        if let Some(key) = bytes.strip_prefix(b"visitor:") {
366            return nonempty(key).map(Self::Visitor);
367        }
368        MemberId::of_actor_bytes(bytes).map(Self::Member)
369    }
370
371    /// The id inside the actor: a member's, an automation's or an app's.
372    #[must_use]
373    pub fn id(&self) -> &str {
374        match self {
375            Self::Member(member) => member.id(),
376            Self::Automation(id) => id.as_str(),
377            Self::App(app) => app.as_str(),
378            Self::Visitor(key) => key,
379        }
380    }
381}
382
383impl From<Actor> for Acting {
384    fn from(actor: Actor) -> Self {
385        Self {
386            by: actor,
387            agent_session: None,
388            app: None,
389            cause: None,
390            foreign_device: false,
391            handed: false,
392            acted_for: Vec::new(),
393        }
394    }
395}
396
397impl From<MemberId> for Actor {
398    fn from(member: MemberId) -> Self {
399        Self::Member(member)
400    }
401}
402
403impl std::fmt::Display for Actor {
404    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405        match self {
406            Self::Member(member) => member.fmt(f),
407            Self::Automation(id) => write!(f, "automation {}", id.as_str()),
408            Self::App(app) => write!(f, "app {app}"),
409            Self::Visitor(key) => write!(f, "visitor {}", key.get(..8).unwrap_or(key)),
410        }
411    }
412}
413
414/// Who made a change, and who they acted for, as a tree: an automation a person
415/// set up, run by an agent, for two people, is
416/// `Automation(1) for [Agent(1) for [Person(Q), Person(X)]]`.
417///
418/// Every format writes every field. A signed claim keeps the text its signer wrote, so an entry
419/// written by a build that left unnamed fields out still checks against its own bytes.
420#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
421pub struct Acting {
422    pub by: Actor,
423    /// The app the change was made through.
424    #[serde(default)]
425    pub app: Option<AppId>,
426    /// The agent session that acted, when an agent did.
427    #[serde(default)]
428    pub agent_session: Option<AgentSessionId>,
429    /// What started the work: the chat message, the issue.
430    #[serde(default)]
431    pub cause: Option<ResourceId>,
432    /// A person working from a device that is not theirs.
433    #[serde(default)]
434    pub foreign_device: bool,
435    /// An agent a person's own device handed its session to, acting for that
436    /// person: it carries the delegation a device gives its agents
437    /// ([`Self::handed_preset`]). A claim the signer of a change makes,
438    /// honoured only from the device of the person it acts for
439    /// ([`crate::MemberAccess::may_write_for`]).
440    #[serde(default)]
441    pub handed: bool,
442    /// Who this actor acted for. Empty for a person acting themselves.
443    #[serde(default, rename = "for")]
444    pub acted_for: Vec<Acting>,
445}
446
447impl Acting {
448    /// A member acting for themselves.
449    #[must_use]
450    pub fn member(member: MemberId) -> Self {
451        Self {
452            by: Actor::Member(member),
453            agent_session: None,
454            app: None,
455            cause: None,
456            foreign_device: false,
457            handed: false,
458            acted_for: Vec::new(),
459        }
460    }
461
462    #[track_caller]
463    #[must_use]
464    pub fn person(id: impl Into<PersonId>) -> Self {
465        Self::member(MemberId::person(id))
466    }
467
468    /// An app acting by itself: a trigger it declares, or a migration of its
469    /// package.
470    #[must_use]
471    pub fn by_app(id: impl Into<AppId>) -> Self {
472        Self {
473            by: Actor::App(id.into()),
474            agent_session: None,
475            app: None,
476            cause: None,
477            foreign_device: false,
478            handed: false,
479            acted_for: Vec::new(),
480        }
481    }
482
483    /// The agent `id` of `person` acting. Whom it acts for in this tree is its
484    /// [`Self::acting_for`]: its person, or someone it answers as well.
485    #[track_caller]
486    #[must_use]
487    pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
488        Self::member(MemberId::agent(id, person))
489    }
490
491    /// A visitor signing with `key`, a key no certificate in the workspace names
492    /// ([`Actor::Visitor`]).
493    #[must_use]
494    pub fn visitor(key: &[u8; 32]) -> Self {
495        Self::from(Actor::Visitor(hex::encode(key)))
496    }
497
498    /// The key of the visitor acting, when one is.
499    #[must_use]
500    pub fn visitor_key(&self) -> Option<[u8; 32]> {
501        match &self.by {
502            Actor::Visitor(key) => hex::decode(key).ok()?.try_into().ok(),
503            _ => None,
504        }
505    }
506
507    #[must_use]
508    pub fn bot(id: impl Into<String>) -> Self {
509        Self::member(MemberId::bot(id))
510    }
511
512    /// The same acting, through the app `app`.
513    #[must_use]
514    pub fn in_app(mut self, app: impl Into<AppId>) -> Self {
515        self.app = Some(app.into());
516        self
517    }
518
519    #[must_use]
520    pub fn automation(id: impl Into<String>) -> Self {
521        Self {
522            by: Actor::automation(id),
523            agent_session: None,
524            app: None,
525            cause: None,
526            foreign_device: false,
527            handed: false,
528            acted_for: Vec::new(),
529        }
530    }
531
532    /// The same acting, for `who` too.
533    #[must_use]
534    pub fn acting_for(mut self, who: Acting) -> Self {
535        self.acted_for.push(who);
536        self
537    }
538
539    /// The same agent acting, as the agent of `owner`, the person it belongs to: where it
540    /// answers someone else, `owner` bounds it as well, so a turn answering one person through
541    /// another's agent does no more than both people and the agent may, on every resource. An
542    /// acting that names `owner` already is returned as it is.
543    #[must_use]
544    pub fn agent_of(mut self, owner: impl Into<PersonId>) -> Self {
545        let owner = owner.into();
546        if !self.people().contains(&owner.as_str()) {
547            self.acted_for.push(Self::person(owner));
548        }
549        self
550    }
551
552    /// The same acting, from a device that is not theirs when `foreign`.
553    #[must_use]
554    pub fn on_foreign_device(mut self, foreign: bool) -> Self {
555        self.foreign_device = foreign;
556        self
557    }
558
559    /// The agent `agent` acting for `person`, carrying the delegation the
560    /// person handed it ([`Self::handed`]).
561    #[must_use]
562    #[track_caller]
563    pub fn handed_agent(agent: impl Into<String>, person: impl Into<PersonId>) -> Self {
564        let person = person.into();
565        Self::agent(agent, person.clone())
566            .handed()
567            .acting_for(Self::member(MemberId::Person(person)))
568    }
569
570    /// This work, handed on to the agent `agent` that its agent started (a sub-agent): one more
571    /// actor in the chain. It is an agent of its starter's person, acting for the person its
572    /// starter acts for and carrying the preset an agent gets for them ([`Self::handed`]), and
573    /// through this whole tree, so every agent and person before it bounds what it does too: it
574    /// does no more than its starter's turn may. `None` when no agent acts here to start it.
575    #[must_use]
576    pub fn handed_on(self, agent: impl Into<String>) -> Option<Self> {
577        let starter = self.member_id()?.agent_person()?.clone();
578        let mut on = Self::member(MemberId::Agent {
579            id: agent.into(),
580            person: starter,
581        })
582        .handed();
583        if let Some(person) = self.acted_for_person() {
584            on = on.acting_for(Self::person(person.to_owned()));
585        }
586        Some(on.acting_for(self))
587    }
588
589    /// The same acting, by an agent a person's own device handed its session
590    /// to ([`Self::handed`]).
591    #[must_use]
592    pub const fn handed(mut self) -> Self {
593        self.handed = true;
594        self
595    }
596
597    /// Who made a change that names this acting as its invoker, signed by the
598    /// device acting as `signer`: this tree, for the signer, so the signer's
599    /// grants bound it. Only a member the signer may write for reaches here
600    /// ([`crate::MemberAccess::may_write_for`]): the signer's own person, or an
601    /// agent it runs. A handed agent keeps its delegation from a device of the
602    /// person it acts for; a device that is not that person's own hands nothing on.
603    #[must_use]
604    pub fn signed_by(mut self, signer: &Self) -> Self {
605        // A device that is not the person's own hands nothing on: the preset a handed agent
606        // carries is its own device's gift, so a change that device's person signs from
607        // somewhere else carries none of it.
608        if signer.foreign_device {
609            self.unhand();
610        }
611        let person = signer
612            .direct_person()
613            .filter(|_| !signer.foreign_device)
614            .map(str::to_owned);
615        // The tree names the signing person already: it is theirs as it is.
616        if let Some(person) = person
617            && self.people().contains(&person.as_str())
618        {
619            return self;
620        }
621        if self.app.is_none() {
622            self.app.clone_from(&signer.app);
623        }
624        self.acting_for(signer.clone())
625    }
626
627    /// Clears [`Self::handed`] on every node: what a device hands on is the delegation of the
628    /// device it is, and one that is nobody's own hands nothing.
629    fn unhand(&mut self) {
630        self.handed = false;
631        for node in &mut self.acted_for {
632            node.unhand();
633        }
634    }
635
636    /// The same acting, caused by the resource `cause`.
637    #[must_use]
638    pub fn caused_by(mut self, cause: impl Into<String>) -> Self {
639        self.cause = Some(ResourceId::new(cause));
640        self
641    }
642
643    /// The same acting, in the agent session `session`.
644    #[must_use]
645    pub fn in_session(mut self, session: impl Into<String>) -> Self {
646        self.agent_session = Some(AgentSessionId::new(session));
647        self
648    }
649
650    /// Whether someone acted for a person here: software, a device that is not
651    /// theirs, or another person on whose behalf this one acted.
652    #[must_use]
653    pub fn delegated(&self) -> bool {
654        self.foreign_device
655            || !self.acted_for.is_empty()
656            || !matches!(self.by, Actor::Member(MemberId::Person(_)))
657    }
658
659    /// Whether this is a person acting themselves, from their own device.
660    #[must_use]
661    pub fn direct(&self) -> bool {
662        !self.delegated()
663    }
664
665    /// The person acting themselves, from their own device.
666    #[must_use]
667    pub fn direct_person(&self) -> Option<&str> {
668        if !self.direct() {
669            return None;
670        }
671        let Actor::Member(MemberId::Person(person)) = &self.by else {
672            return None;
673        };
674        Some(person.as_str())
675    }
676
677    /// The app the change went through.
678    #[must_use]
679    pub fn app(&self) -> Option<&AppId> {
680        self.app.as_ref()
681    }
682
683    /// The actor, when it is a member.
684    #[must_use]
685    pub fn member_id(&self) -> Option<&MemberId> {
686        self.by.member_id()
687    }
688
689    #[must_use]
690    pub fn is_person(&self) -> bool {
691        self.by.member_id().is_some_and(MemberId::is_person)
692    }
693
694    #[must_use]
695    pub fn is_agent(&self) -> bool {
696        self.by.member_id().is_some_and(MemberId::is_agent)
697    }
698
699    #[must_use]
700    pub fn is_bot(&self) -> bool {
701        self.by.member_id().is_some_and(MemberId::is_bot)
702    }
703
704    #[must_use]
705    pub fn is_automation(&self) -> bool {
706        matches!(self.by, Actor::Automation(_))
707    }
708
709    #[must_use]
710    pub fn person_id(&self) -> Option<&str> {
711        self.by.member_id().and_then(MemberId::person_id)
712    }
713
714    #[must_use]
715    pub fn agent_id(&self) -> Option<&str> {
716        self.by.member_id().and_then(MemberId::agent_id)
717    }
718
719    #[must_use]
720    pub fn bot_id(&self) -> Option<&str> {
721        self.by.member_id().and_then(MemberId::bot_id)
722    }
723
724    /// The person this acting is for, when it is not the actor itself.
725    #[must_use]
726    pub fn acted_for_person(&self) -> Option<&str> {
727        self.acted_for
728            .first()
729            .and_then(|node| node.by.member_id())
730            .and_then(MemberId::person_id)
731    }
732
733    /// Every member in the tree, the actor first.
734    pub fn members(&self) -> Vec<&MemberId> {
735        let mut members: Vec<&MemberId> = self.by.member_id().into_iter().collect();
736        for node in &self.acted_for {
737            members.extend(node.members());
738        }
739        members
740    }
741
742    /// Every node of the tree, itself first.
743    pub fn nodes(&self) -> Vec<&Self> {
744        std::iter::once(self)
745            .chain(self.acted_for.iter().flat_map(Self::nodes))
746            .collect()
747    }
748
749    /// The people in the tree, in tree order.
750    pub fn people(&self) -> Vec<&str> {
751        self.nodes()
752            .into_iter()
753            .filter_map(|node| node.by.member_id().and_then(MemberId::person_id))
754            .collect()
755    }
756}
757
758/// The agent member a key the person approved acts as wherever it is
759/// admitted: `grant-` and its device key, hex. History names its changes by
760/// it, and receivers find the key's certificate by it ([`key_of_agent`]).
761#[must_use]
762pub fn key_agent_id(device_public_key: &[u8; 32]) -> String {
763    format!("{KEY_AGENT_PREFIX}{}", hex::encode(device_public_key))
764}
765
766/// The device key of the key whose agent `agent` is ([`key_agent_id`]);
767/// `None` for any other agent.
768#[must_use]
769pub fn key_of_agent(agent: &str) -> Option<[u8; 32]> {
770    let hex = agent.strip_prefix(KEY_AGENT_PREFIX)?;
771    hex::decode(hex).ok()?.try_into().ok()
772}
773
774/// What [`key_agent_id`] starts with.
775const KEY_AGENT_PREFIX: &str = "grant-";
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780
781    tilo_test_env::scenario! {
782        fn a_member_tree_names_and_writes_its_members;
783
784        phase a_tree_names_every_member_and_person_in_it;
785        {
786            let acting =
787                Acting::agent("claude", "q").acting_for(Acting::person("q").acting_for(Acting::person("x")));
788            assert!(acting.delegated());
789            assert_eq!(acting.direct_person(), None);
790            assert_eq!(
791                acting.members(),
792                [
793                    &MemberId::agent("claude", "q"),
794                    &MemberId::person("q"),
795                    &MemberId::person("x")
796                ]
797            );
798            assert_eq!(acting.people(), vec!["q", "x"]);
799            let person = Acting::person("q");
800            assert!(person.direct());
801            assert_eq!(person.direct_person(), Some("q"));
802            assert!(Acting::person("q").on_foreign_device(true).delegated());
803        }
804
805        phase an_agent_answering_someone_else_is_bounded_by_its_own_person_too;
806        {
807            let for_bo = Acting::handed_agent("scout", "bo").agent_of("ada");
808            assert_eq!(for_bo.people(), vec!["bo", "ada"], "Bo first, Ada bounding it");
809            assert_eq!(for_bo.acted_for_person(), Some("bo"), "it answers Bo");
810            let for_ada = Acting::handed_agent("scout", "ada").agent_of("ada");
811            assert_eq!(for_ada, Acting::handed_agent("scout", "ada"), "its own person once");
812        }
813
814        phase a_sub_agent_is_one_more_actor_in_its_starters_chain;
815        // Bo's turn on Ada's agent starts a sub-agent: it works for Bo, and everyone before it
816        // in the chain bounds it, Ada's agent and Ada too.
817        {
818            let starter = Acting::agent("scout", "ada").acting_for(Acting::person("bo")).agent_of("ada");
819            let helper = starter.clone().handed_on("helper").expect("an agent starts it");
820            assert_eq!(helper.member_id(), Some(&MemberId::agent("helper", "ada")), "Ada's agent's");
821            assert_eq!(helper.acted_for_person(), Some("bo"), "it works for Bo");
822            assert!(helper.handed, "with the preset an agent gets for Bo");
823            assert!(helper.people().contains(&"ada"), "Ada bounds it: {helper:?}");
824            assert!(
825                helper.nodes().iter().any(|node| **node == starter),
826                "its starter's whole tree bounds it: {helper:?}"
827            );
828            // The starter's own key signs the sub-agent's work: it keeps the preset, as work
829            // handed on whose chain names the person the key belongs to.
830            let signer = Acting::agent("scout", "ada").acting_for(Acting::person("ada"));
831            let signed = helper.signed_by(&signer);
832            assert!(signed.handed, "{signed:?}");
833        }
834
835        phase a_member_is_read_back_from_the_bytes_a_document_names_it_by;
836        {
837            for member in [
838                MemberId::person(PersonId::from_root([5; 32])),
839                MemberId::agent("helper", PersonId::from_root([5; 32])),
840                MemberId::bot("mod"),
841            ] {
842                assert_eq!(
843                    MemberId::of_actor_bytes(&member.actor_bytes()),
844                    Some(member)
845                );
846            }
847            assert_eq!(MemberId::of_actor_bytes(b"automation:1"), None);
848            assert_eq!(MemberId::of_actor_bytes(b"agent:"), None);
849            assert_eq!(MemberId::of_actor_bytes(b""), None);
850        }
851
852        phase the_tree_is_written_as_it_is_read;
853        {
854            let acting = Acting::automation("1")
855                .acting_for(
856                    Acting::agent("claude", "q")
857                        .acting_for(Acting::person("q"))
858                        .acting_for(Acting::person("x")),
859                )
860                .caused_by("chat.message:m1");
861            let json = serde_json::to_string(&acting).unwrap();
862            assert_eq!(serde_json::from_str::<Acting>(&json).unwrap(), acting);
863            assert!(json.contains("\"for\""), "{json}");
864        }
865    }
866}