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