Skip to main content

inobot_p/
lib.rs

1//! Consent-first safety state for adult human–humanoid intimacy.
2//!
3//! `inobot-p` does not describe intimate acts and does not control hardware. It
4//! models the conditions that must be true before an application may run an
5//! authorized operation: adult human attestation, independent refusal ability,
6//! explicit activity-level agreement from both participants, physical safety
7//! checks, immediate withdrawal, and irreversible emergency stop.
8//!
9//! # Example
10//!
11//! ```
12//! use inobot_p::{Activity, Consent, Participant, SafetyChecklist, SessionPlan};
13//!
14//! let human = Participant::adult_human("human")?;
15//! let robot = Participant::autonomous_humanoid("robot")?;
16//! let activity = Activity::new("private-affection-v1")?;
17//! let plan = SessionPlan::new(human, robot)?;
18//! let human_consent = Consent::new("human", [activity.clone()])?;
19//! let robot_consent = Consent::new("robot", [activity.clone()])?;
20//! let mut session = plan.activate(
21//!     human_consent,
22//!     robot_consent,
23//!     SafetyChecklist::all_confirmed(),
24//! )?;
25//!
26//! let result = session.authorize(&activity, |_| "authorized only in this closure")?;
27//! assert_eq!(result, "authorized only in this closure");
28//! # Ok::<(), inobot_p::Error>(())
29//! ```
30//!
31//! Authorization cannot escape the closure:
32//!
33//! ```compile_fail
34//! use inobot_p::{Activity, Consent, Participant, SafetyChecklist, SessionPlan};
35//! let activity = Activity::new("policy-v1").unwrap();
36//! let plan = SessionPlan::new(
37//!     Participant::adult_human("h").unwrap(),
38//!     Participant::autonomous_humanoid("r").unwrap(),
39//! ).unwrap();
40//! let mut session = plan.activate(
41//!     Consent::new("h", [activity.clone()]).unwrap(),
42//!     Consent::new("r", [activity.clone()]).unwrap(),
43//!     SafetyChecklist::all_confirmed(),
44//! ).unwrap();
45//! let escaped = session.authorize(&activity, |authorization| authorization).unwrap();
46//! ```
47
48#![forbid(unsafe_code)]
49#![warn(missing_docs)]
50
51use std::collections::BTreeSet;
52use std::error::Error as StdError;
53use std::fmt;
54use std::marker::PhantomData;
55
56/// Participant role in a human–humanoid session.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum Role {
59    /// An adult human participant.
60    Human,
61    /// A humanoid agent configured to independently accept or refuse.
62    Humanoid,
63}
64
65/// A session participant with explicit capacity properties.
66#[derive(Debug, Clone, PartialEq, Eq, Hash)]
67pub struct Participant {
68    id: String,
69    role: Role,
70    adult_attested: bool,
71    independent_refusal: bool,
72}
73
74impl Participant {
75    /// Creates a human participant with an explicit 18+ attestation and the
76    /// ability to independently refuse.
77    pub fn adult_human(id: impl Into<String>) -> Result<Self, Error> {
78        Ok(Self {
79            id: required(id.into(), "participant id")?,
80            role: Role::Human,
81            adult_attested: true,
82            independent_refusal: true,
83        })
84    }
85
86    /// Creates a humanoid participant configured to accept or refuse without
87    /// the human participant being able to override that refusal.
88    pub fn autonomous_humanoid(id: impl Into<String>) -> Result<Self, Error> {
89        Ok(Self {
90            id: required(id.into(), "participant id")?,
91            role: Role::Humanoid,
92            adult_attested: false,
93            independent_refusal: true,
94        })
95    }
96
97    /// Creates an explicitly ineligible human profile for validation and UI
98    /// flows where adulthood has not been confirmed.
99    pub fn unattested_human(id: impl Into<String>) -> Result<Self, Error> {
100        Ok(Self {
101            id: required(id.into(), "participant id")?,
102            role: Role::Human,
103            adult_attested: false,
104            independent_refusal: true,
105        })
106    }
107
108    /// Creates a humanoid profile that cannot independently refuse and is
109    /// therefore ineligible for session activation.
110    pub fn non_autonomous_humanoid(id: impl Into<String>) -> Result<Self, Error> {
111        Ok(Self {
112            id: required(id.into(), "participant id")?,
113            role: Role::Humanoid,
114            adult_attested: false,
115            independent_refusal: false,
116        })
117    }
118
119    /// Returns the stable participant ID.
120    pub fn id(&self) -> &str {
121        &self.id
122    }
123
124    /// Returns the participant role.
125    pub const fn role(&self) -> Role {
126        self.role
127    }
128
129    /// Returns whether an adult human attestation is recorded.
130    pub const fn adult_attested(&self) -> bool {
131        self.adult_attested
132    }
133
134    /// Returns whether the participant can independently refuse.
135    pub const fn independent_refusal(&self) -> bool {
136        self.independent_refusal
137    }
138}
139
140/// An opaque, non-explicit activity identifier selected by the host app.
141///
142/// The identifier should name a host-defined policy entry rather than contain
143/// sensitive free-form details.
144#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
145pub struct Activity(String);
146
147impl Activity {
148    /// Creates a non-empty policy identifier.
149    pub fn new(id: impl Into<String>) -> Result<Self, Error> {
150        Ok(Self(required(id.into(), "activity id")?))
151    }
152
153    /// Returns the policy identifier.
154    pub fn id(&self) -> &str {
155        &self.0
156    }
157}
158
159/// Explicit allow-list consent from one participant.
160///
161/// There is deliberately no wildcard permission: an absent activity is a
162/// refusal for that activity.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct Consent {
165    participant_id: String,
166    allowed: BTreeSet<Activity>,
167}
168
169impl Consent {
170    /// Creates consent for exactly the supplied activities.
171    pub fn new(
172        participant_id: impl Into<String>,
173        allowed: impl IntoIterator<Item = Activity>,
174    ) -> Result<Self, Error> {
175        Ok(Self {
176            participant_id: required(participant_id.into(), "participant id")?,
177            allowed: allowed.into_iter().collect(),
178        })
179    }
180
181    /// Creates an explicit refusal of every activity.
182    pub fn refuse_all(participant_id: impl Into<String>) -> Result<Self, Error> {
183        Self::new(participant_id, [])
184    }
185
186    /// Returns the consenting participant ID.
187    pub fn participant_id(&self) -> &str {
188        &self.participant_id
189    }
190
191    /// Returns whether this participant explicitly allowed an activity.
192    pub fn allows(&self, activity: &Activity) -> bool {
193        self.allowed.contains(activity)
194    }
195
196    /// Returns explicitly allowed activities in stable order.
197    pub fn allowed(&self) -> impl Iterator<Item = &Activity> {
198        self.allowed.iter()
199    }
200}
201
202/// Physical, capacity, and privacy checks required before activation.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub struct SafetyChecklist {
205    /// Human capacity and ability to make a present decision were confirmed.
206    pub human_capacity_confirmed: bool,
207    /// A reachable physical emergency stop was confirmed.
208    pub emergency_stop_reachable: bool,
209    /// Force and speed limits appropriate to the host system are enabled.
210    pub force_and_speed_limits_enabled: bool,
211    /// Collision detection is enabled.
212    pub collision_detection_enabled: bool,
213    /// Both parties acknowledged the host application's privacy behavior.
214    pub privacy_acknowledged: bool,
215}
216
217impl SafetyChecklist {
218    /// Returns a checklist with all mandatory items confirmed.
219    pub const fn all_confirmed() -> Self {
220        Self {
221            human_capacity_confirmed: true,
222            emergency_stop_reachable: true,
223            force_and_speed_limits_enabled: true,
224            collision_detection_enabled: true,
225            privacy_acknowledged: true,
226        }
227    }
228
229    /// Returns a checklist with no items confirmed.
230    pub const fn none_confirmed() -> Self {
231        Self {
232            human_capacity_confirmed: false,
233            emergency_stop_reachable: false,
234            force_and_speed_limits_enabled: false,
235            collision_detection_enabled: false,
236            privacy_acknowledged: false,
237        }
238    }
239
240    /// Returns whether every mandatory item is confirmed.
241    pub const fn is_complete(self) -> bool {
242        self.human_capacity_confirmed
243            && self.emergency_stop_reachable
244            && self.force_and_speed_limits_enabled
245            && self.collision_detection_enabled
246            && self.privacy_acknowledged
247    }
248}
249
250/// A validated human–humanoid pair before consent and safety activation.
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct SessionPlan {
253    human: Participant,
254    humanoid: Participant,
255}
256
257impl SessionPlan {
258    /// Creates a plan, enforcing distinct IDs, an adult-attested human, and an
259    /// independently refusing humanoid.
260    pub fn new(first: Participant, second: Participant) -> Result<Self, Error> {
261        if first.id == second.id {
262            return Err(Error::DuplicateParticipant(first.id));
263        }
264        let (human, humanoid) = match (first.role, second.role) {
265            (Role::Human, Role::Humanoid) => (first, second),
266            (Role::Humanoid, Role::Human) => (second, first),
267            _ => return Err(Error::RequiredRoles),
268        };
269        if !human.adult_attested {
270            return Err(Error::AdultAttestationRequired);
271        }
272        if !human.independent_refusal || !humanoid.independent_refusal {
273            return Err(Error::IndependentRefusalRequired);
274        }
275        Ok(Self { human, humanoid })
276    }
277
278    /// Returns the human participant.
279    pub const fn human(&self) -> &Participant {
280        &self.human
281    }
282
283    /// Returns the humanoid participant.
284    pub const fn humanoid(&self) -> &Participant {
285        &self.humanoid
286    }
287
288    /// Activates a session only after matching consent records and all safety
289    /// checks are supplied.
290    pub fn activate(
291        self,
292        first_consent: Consent,
293        second_consent: Consent,
294        checklist: SafetyChecklist,
295    ) -> Result<ActiveSession, Error> {
296        if !checklist.is_complete() {
297            return Err(Error::IncompleteSafetyChecklist);
298        }
299        let (human_consent, humanoid_consent) = if first_consent.participant_id == self.human.id
300            && second_consent.participant_id == self.humanoid.id
301        {
302            (first_consent, second_consent)
303        } else if second_consent.participant_id == self.human.id
304            && first_consent.participant_id == self.humanoid.id
305        {
306            (second_consent, first_consent)
307        } else {
308            return Err(Error::ConsentParticipantMismatch);
309        };
310        Ok(ActiveSession {
311            human: self.human,
312            humanoid: self.humanoid,
313            human_consent,
314            humanoid_consent,
315            status: SessionStatus::Active,
316            event_sequence: 0,
317        })
318    }
319}
320
321/// Terminal and active session states.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum SessionStatus {
324    /// Safety checks passed and neither participant has withdrawn.
325    Active,
326    /// A participant withdrew all consent.
327    ConsentWithdrawn {
328        /// ID of the participant who withdrew.
329        by: String,
330    },
331    /// An emergency stop was invoked.
332    EmergencyStopped {
333        /// Host-defined identifier for the stop source.
334        by: String,
335    },
336    /// The session ended normally.
337    Completed,
338}
339
340impl SessionStatus {
341    /// Returns whether authorization may still be requested.
342    pub const fn is_active(&self) -> bool {
343        matches!(self, Self::Active)
344    }
345}
346
347/// A short-lived proof available only inside [`ActiveSession::authorize`].
348#[derive(Debug)]
349pub struct Authorization<'a> {
350    activity: &'a Activity,
351    sequence: u64,
352    session_borrow: PhantomData<&'a mut ActiveSession>,
353}
354
355impl Authorization<'_> {
356    /// Returns the mutually authorized activity.
357    pub const fn activity(&self) -> &Activity {
358        self.activity
359    }
360
361    /// Returns the monotonically increasing authorization sequence.
362    pub const fn sequence(&self) -> u64 {
363        self.sequence
364    }
365}
366
367/// An activated session with revocable, activity-level authorization.
368#[derive(Debug)]
369pub struct ActiveSession {
370    human: Participant,
371    humanoid: Participant,
372    human_consent: Consent,
373    humanoid_consent: Consent,
374    status: SessionStatus,
375    event_sequence: u64,
376}
377
378impl ActiveSession {
379    /// Returns the current status.
380    pub const fn status(&self) -> &SessionStatus {
381        &self.status
382    }
383
384    /// Returns whether both current consent allow-lists include an activity.
385    pub fn mutually_allows(&self, activity: &Activity) -> bool {
386        self.status.is_active()
387            && self.human_consent.allows(activity)
388            && self.humanoid_consent.allows(activity)
389    }
390
391    /// Runs one host operation only while the session is active and both
392    /// participants explicitly allow the activity.
393    ///
394    /// The authorization borrows the session call and is not a detached,
395    /// reusable permit. Host applications should keep physical operations
396    /// bounded and call this method again before every step.
397    pub fn authorize<R>(
398        &mut self,
399        activity: &Activity,
400        operation: impl for<'a> FnOnce(Authorization<'a>) -> R,
401    ) -> Result<R, Error> {
402        if !self.status.is_active() {
403            return Err(Error::SessionNotActive);
404        }
405        if !self.human_consent.allows(activity) {
406            return Err(Error::ActivityNotAllowed {
407                participant: self.human.id.clone(),
408                activity: activity.id().to_owned(),
409            });
410        }
411        if !self.humanoid_consent.allows(activity) {
412            return Err(Error::ActivityNotAllowed {
413                participant: self.humanoid.id.clone(),
414                activity: activity.id().to_owned(),
415            });
416        }
417        self.event_sequence = self
418            .event_sequence
419            .checked_add(1)
420            .ok_or(Error::SequenceOverflow)?;
421        Ok(operation(Authorization {
422            activity,
423            sequence: self.event_sequence,
424            session_borrow: PhantomData,
425        }))
426    }
427
428    /// Withdraws all consent for one participant and irreversibly stops the
429    /// session. Either participant may withdraw at any time.
430    pub fn withdraw(&mut self, participant_id: &str) -> Result<(), Error> {
431        self.ensure_participant(participant_id)?;
432        if !self.status.is_active() {
433            return Err(Error::SessionNotActive);
434        }
435        self.status = SessionStatus::ConsentWithdrawn {
436            by: participant_id.to_owned(),
437        };
438        Ok(())
439    }
440
441    /// Invokes an irreversible emergency stop.
442    pub fn emergency_stop(&mut self, source: impl Into<String>) -> Result<(), Error> {
443        let source = required(source.into(), "emergency stop source")?;
444        if !self.status.is_active() {
445            return Err(Error::SessionNotActive);
446        }
447        self.status = SessionStatus::EmergencyStopped { by: source };
448        Ok(())
449    }
450
451    /// Marks a still-active session complete. Completed sessions cannot resume.
452    pub fn complete(&mut self) -> Result<(), Error> {
453        if !self.status.is_active() {
454            return Err(Error::SessionNotActive);
455        }
456        self.status = SessionStatus::Completed;
457        Ok(())
458    }
459
460    fn ensure_participant(&self, participant_id: &str) -> Result<(), Error> {
461        if participant_id == self.human.id || participant_id == self.humanoid.id {
462            Ok(())
463        } else {
464            Err(Error::UnknownParticipant(participant_id.to_owned()))
465        }
466    }
467}
468
469/// Validation and authorization errors.
470#[derive(Debug, Clone, PartialEq, Eq)]
471#[non_exhaustive]
472pub enum Error {
473    /// A required identifier contained only whitespace.
474    EmptyField(&'static str),
475    /// Both participants used the same ID.
476    DuplicateParticipant(String),
477    /// A plan did not contain exactly one human and one humanoid.
478    RequiredRoles,
479    /// The human participant did not carry an explicit 18+ attestation.
480    AdultAttestationRequired,
481    /// One participant could not independently refuse.
482    IndependentRefusalRequired,
483    /// Consent records did not belong to the planned participants.
484    ConsentParticipantMismatch,
485    /// One or more mandatory safety checks were false.
486    IncompleteSafetyChecklist,
487    /// Authorization was requested after withdrawal, stop, or completion.
488    SessionNotActive,
489    /// One participant did not explicitly allow an activity.
490    ActivityNotAllowed {
491        /// Participant refusing or lacking an explicit allow entry.
492        participant: String,
493        /// Host-defined activity identifier.
494        activity: String,
495    },
496    /// A withdrawal named someone outside the session.
497    UnknownParticipant(String),
498    /// Authorization sequence arithmetic overflowed.
499    SequenceOverflow,
500}
501
502impl fmt::Display for Error {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        match self {
505            Self::EmptyField(field) => write!(f, "{field} cannot be empty"),
506            Self::DuplicateParticipant(id) => write!(f, "duplicate participant ID: {id}"),
507            Self::RequiredRoles => f.write_str("session requires one human and one humanoid"),
508            Self::AdultAttestationRequired => f.write_str("adult human attestation is required"),
509            Self::IndependentRefusalRequired => {
510                f.write_str("both participants must be able to independently refuse")
511            }
512            Self::ConsentParticipantMismatch => {
513                f.write_str("consent records do not match planned participants")
514            }
515            Self::IncompleteSafetyChecklist => {
516                f.write_str("every mandatory safety check must be confirmed")
517            }
518            Self::SessionNotActive => f.write_str("session is not active"),
519            Self::ActivityNotAllowed {
520                participant,
521                activity,
522            } => write!(
523                f,
524                "participant {participant} did not allow activity {activity}"
525            ),
526            Self::UnknownParticipant(id) => write!(f, "unknown participant: {id}"),
527            Self::SequenceOverflow => f.write_str("authorization sequence overflow"),
528        }
529    }
530}
531
532impl StdError for Error {}
533
534fn required(value: String, field: &'static str) -> Result<String, Error> {
535    if value.trim().is_empty() {
536        Err(Error::EmptyField(field))
537    } else {
538        Ok(value)
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    fn activity() -> Activity {
547        Activity::new("affection-v1").unwrap()
548    }
549
550    fn plan() -> SessionPlan {
551        SessionPlan::new(
552            Participant::adult_human("h").unwrap(),
553            Participant::autonomous_humanoid("r").unwrap(),
554        )
555        .unwrap()
556    }
557
558    fn active_with(human_allows: bool, robot_allows: bool) -> ActiveSession {
559        let act = activity();
560        plan()
561            .activate(
562                Consent::new("h", human_allows.then_some(act.clone())).unwrap(),
563                Consent::new("r", robot_allows.then_some(act)).unwrap(),
564                SafetyChecklist::all_confirmed(),
565            )
566            .unwrap()
567    }
568
569    #[test]
570    fn adult_attestation_is_mandatory() {
571        let result = SessionPlan::new(
572            Participant::unattested_human("h").unwrap(),
573            Participant::autonomous_humanoid("r").unwrap(),
574        );
575        assert!(matches!(result, Err(Error::AdultAttestationRequired)));
576    }
577
578    #[test]
579    fn independent_humanoid_refusal_is_mandatory() {
580        let result = SessionPlan::new(
581            Participant::adult_human("h").unwrap(),
582            Participant::non_autonomous_humanoid("r").unwrap(),
583        );
584        assert!(matches!(result, Err(Error::IndependentRefusalRequired)));
585    }
586
587    #[test]
588    fn every_safety_check_is_mandatory() {
589        let act = activity();
590        let result = plan().activate(
591            Consent::new("h", [act.clone()]).unwrap(),
592            Consent::new("r", [act]).unwrap(),
593            SafetyChecklist::none_confirmed(),
594        );
595        assert!(matches!(result, Err(Error::IncompleteSafetyChecklist)));
596    }
597
598    #[test]
599    fn mutual_explicit_consent_authorizes_bounded_operation() {
600        let mut session = active_with(true, true);
601        let act = activity();
602        let observed = session
603            .authorize(&act, |authorization| {
604                (
605                    authorization.activity().id().to_owned(),
606                    authorization.sequence(),
607                )
608            })
609            .unwrap();
610        assert_eq!(observed, ("affection-v1".to_owned(), 1));
611        assert_eq!(session.authorize(&act, |a| a.sequence()).unwrap(), 2);
612    }
613
614    #[test]
615    fn either_participants_absence_of_consent_blocks() {
616        let act = activity();
617        let mut human_refuses = active_with(false, true);
618        assert!(matches!(
619            human_refuses.authorize(&act, |_| ()),
620            Err(Error::ActivityNotAllowed { participant, .. }) if participant == "h"
621        ));
622        let mut robot_refuses = active_with(true, false);
623        assert!(matches!(
624            robot_refuses.authorize(&act, |_| ()),
625            Err(Error::ActivityNotAllowed { participant, .. }) if participant == "r"
626        ));
627    }
628
629    #[test]
630    fn withdrawal_immediately_and_irreversibly_blocks() {
631        let act = activity();
632        let mut session = active_with(true, true);
633        session.withdraw("r").unwrap();
634        assert_eq!(
635            session.status(),
636            &SessionStatus::ConsentWithdrawn { by: "r".to_owned() }
637        );
638        assert!(matches!(
639            session.authorize(&act, |_| ()),
640            Err(Error::SessionNotActive)
641        ));
642        assert!(matches!(session.complete(), Err(Error::SessionNotActive)));
643    }
644
645    #[test]
646    fn emergency_stop_is_irreversible() {
647        let act = activity();
648        let mut session = active_with(true, true);
649        session.emergency_stop("physical-button").unwrap();
650        assert_eq!(
651            session.status(),
652            &SessionStatus::EmergencyStopped {
653                by: "physical-button".to_owned()
654            }
655        );
656        assert!(matches!(
657            session.authorize(&act, |_| ()),
658            Err(Error::SessionNotActive)
659        ));
660    }
661
662    #[test]
663    fn normal_completion_prevents_future_authorization() {
664        let act = activity();
665        let mut session = active_with(true, true);
666        session.complete().unwrap();
667        assert_eq!(session.status(), &SessionStatus::Completed);
668        assert!(matches!(
669            session.authorize(&act, |_| ()),
670            Err(Error::SessionNotActive)
671        ));
672    }
673
674    #[test]
675    fn consent_records_must_match_both_participants() {
676        let result = plan().activate(
677            Consent::refuse_all("h").unwrap(),
678            Consent::refuse_all("someone-else").unwrap(),
679            SafetyChecklist::all_confirmed(),
680        );
681        assert!(matches!(result, Err(Error::ConsentParticipantMismatch)));
682    }
683}