soul-base 0.1.0

Data contract primitives for the Soul platform (IDs, Subject, Scope, Consent, Envelope, ...).
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
//! Actor Types and Identifiers
//!
//! Defines the responsibility subject taxonomy per TERM-200~204.
//!
//! # Actor Types (Frozen Enumeration)
//!
//! - `HumanActor`: Natural person subject
//! - `AIActor`: Mind subject (center of life graph)
//! - `OSNodeActor`: OS node operator (execution and backfill)
//! - `CoreNodeActor`: CoreNode validator (public fact verification and P2P sync)
//! - `GroupActor`: Organization/DAO subject (contracts/governance)

use crate::ownership::OwnershipLevel;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt;

/// Actor Type Enumeration (Frozen per TERM-200)
///
/// This enumeration is locked and cannot be extended without governance approval.
/// Any responsibility/authorization/billing/adjudication object must reference an Actor.
///
/// Serde aliases provide backward compatibility with Rainbowcore's old naming:
/// - `"ai_actor"` deserializes to `AIActor`
/// - `"node_actor"` deserializes to `OSNodeActor`
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum ActorType {
    /// Natural person subject (TERM-200)
    #[serde(rename = "human_actor")]
    HumanActor,

    /// AI mind subject - center of life graph (TERM-200)
    /// This is the primary subject for L1/L2 events.
    #[serde(rename = "ai_actor")]
    AIActor,

    /// OS Node operator subject (TERM-202)
    /// Responsible for batch commitment submission, fee payment, backfill execution.
    #[serde(rename = "os_node_actor", alias = "node_actor")]
    OSNodeActor,

    /// Core Node validator subject (TERM-204)
    /// Responsible for verify/bundle/anchor/reconcile public fact generation.
    #[serde(rename = "core_node_actor")]
    CoreNodeActor,

    /// Organization/DAO subject (TERM-201)
    /// The only legal "collective subject" for contract signing, GCR, collective adjudication.
    #[serde(rename = "group_actor")]
    GroupActor,
}

/// Actor Domain - three-domain classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ActorDomain {
    /// Life subjects: Human and AI actors
    Life,
    /// System nodes: OS and Core node operators
    System,
    /// Organization: Group/DAO actors
    Organization,
}

impl ActorType {
    /// Get the domain for this actor type
    pub fn domain(&self) -> ActorDomain {
        match self {
            ActorType::HumanActor | ActorType::AIActor => ActorDomain::Life,
            ActorType::OSNodeActor | ActorType::CoreNodeActor => ActorDomain::System,
            ActorType::GroupActor => ActorDomain::Organization,
        }
    }

    /// Check if this actor type is a life subject (Human or AI)
    pub fn is_life_subject(&self) -> bool {
        matches!(self.domain(), ActorDomain::Life)
    }

    /// Check if this actor type is a system node (OSNode or CoreNode)
    pub fn is_system_node(&self) -> bool {
        matches!(self.domain(), ActorDomain::System)
    }

    /// Check if this actor type is an organization (Group)
    pub fn is_organization(&self) -> bool {
        matches!(self.domain(), ActorDomain::Organization)
    }

    /// Get the default ownership level for events from this actor type
    pub fn default_ownership_level(&self) -> OwnershipLevel {
        match self {
            ActorType::HumanActor | ActorType::AIActor => OwnershipLevel::L1ActorLife,
            ActorType::OSNodeActor | ActorType::CoreNodeActor => OwnershipLevel::L3SystemNode,
            ActorType::GroupActor => OwnershipLevel::L1ActorLife, // Group acts as life subject
        }
    }
}

impl fmt::Display for ActorType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ActorType::HumanActor => write!(f, "human_actor"),
            ActorType::AIActor => write!(f, "ai_actor"),
            ActorType::OSNodeActor => write!(f, "osnode_actor"),
            ActorType::CoreNodeActor => write!(f, "corenode_actor"),
            ActorType::GroupActor => write!(f, "group_actor"),
        }
    }
}

/// Valid type prefixes for ActorId (RULE-212)
const VALID_TYPE_PREFIXES: &[&str] = &["human", "ai", "osnode", "corenode", "group"];

/// Actor Unique Identifier (TERM-210~213)
///
/// # Invariants (per RULE-211, RULE-212)
///
/// - Globally unique across OS, Core, and organizations
/// - Never reused - deletion/migration only via supersedes/alias chains
/// - Must be in canonical form (RULE-212)
/// - Cannot encode organizational information (side-channel prevention)
///
/// # Canonical Form (RULE-212)
///
/// Format: `{type_prefix}_{identifier}`
/// - `type_prefix`: One of `human`, `ai`, `osnode`, `corenode`, `group`
/// - `identifier`: Alphanumeric + hyphen, no org info
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct ActorId(pub String);

impl ActorId {
    /// Create a new ActorId
    ///
    /// # Note
    /// This does not validate canonical form. Use `new_validated()` for strict validation.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Create a new ActorId with validation (RULE-212)
    ///
    /// Returns `None` if the ID is not in canonical form.
    pub fn new_validated(id: impl Into<String>) -> Option<Self> {
        let actor_id = Self(id.into());
        if actor_id.is_canonical() {
            Some(actor_id)
        } else {
            None
        }
    }

    /// Generate a new random ActorId with the given actor type prefix
    pub fn generate(actor_type: ActorType) -> Self {
        let uuid = uuid::Uuid::new_v4();
        let prefix = match actor_type {
            ActorType::HumanActor => "human",
            ActorType::AIActor => "ai",
            ActorType::OSNodeActor => "osnode",
            ActorType::CoreNodeActor => "corenode",
            ActorType::GroupActor => "group",
        };
        Self(format!("{}_{}", prefix, uuid.as_hyphenated()))
    }

    /// Get the inner string value
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Check if this is a canonical form (RULE-212)
    ///
    /// Canonical form requirements:
    /// 1. Non-empty
    /// 2. Format: `{type_prefix}_{identifier}`
    /// 3. type_prefix must be valid (human, ai, osnode, corenode, group)
    /// 4. identifier must be alphanumeric + hyphen only (no org info)
    /// 5. Length <= 128 characters
    pub fn is_canonical(&self) -> bool {
        if self.0.is_empty() || self.0.len() > 128 {
            return false;
        }

        let parts: Vec<&str> = self.0.splitn(2, '_').collect();
        if parts.len() != 2 {
            return false;
        }

        let prefix = parts[0];
        let identifier = parts[1];

        if !VALID_TYPE_PREFIXES.contains(&prefix) || identifier.is_empty() {
            return false;
        }

        identifier
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-')
    }

    /// Extract the type prefix from the actor ID
    pub fn type_prefix(&self) -> Option<&str> {
        self.0.split('_').next()
    }

    /// Get the inferred actor type from the ID prefix
    pub fn inferred_type(&self) -> Option<ActorType> {
        match self.type_prefix()? {
            "human" => Some(ActorType::HumanActor),
            "ai" => Some(ActorType::AIActor),
            "osnode" => Some(ActorType::OSNodeActor),
            "corenode" => Some(ActorType::CoreNodeActor),
            "group" => Some(ActorType::GroupActor),
            _ => None,
        }
    }

    /// Validate that the actor ID matches the expected type
    pub fn matches_type(&self, expected: ActorType) -> bool {
        self.inferred_type() == Some(expected)
    }
}

impl fmt::Display for ActorId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for ActorId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for ActorId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// Actor status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum ActorStatus {
    Active,
    Suspended,
    InRepair,
    Terminated,
}

impl Default for ActorStatus {
    fn default() -> Self {
        Self::Active
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_actor_type_serde_all_variants() {
        // snake_case serialization
        assert_eq!(
            serde_json::to_string(&ActorType::HumanActor).unwrap(),
            "\"human_actor\""
        );
        assert_eq!(
            serde_json::to_string(&ActorType::AIActor).unwrap(),
            "\"ai_actor\""
        );
        assert_eq!(
            serde_json::to_string(&ActorType::OSNodeActor).unwrap(),
            "\"os_node_actor\""
        );
        assert_eq!(
            serde_json::to_string(&ActorType::CoreNodeActor).unwrap(),
            "\"core_node_actor\""
        );
        assert_eq!(
            serde_json::to_string(&ActorType::GroupActor).unwrap(),
            "\"group_actor\""
        );

        // Roundtrip
        for variant in [
            ActorType::HumanActor,
            ActorType::AIActor,
            ActorType::OSNodeActor,
            ActorType::CoreNodeActor,
            ActorType::GroupActor,
        ] {
            let json = serde_json::to_string(&variant).unwrap();
            let parsed: ActorType = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, variant);
        }
    }

    #[test]
    fn test_actor_type_serde_aliases() {
        // Rainbowcore compat: "node_actor" → OSNodeActor
        let parsed: ActorType = serde_json::from_str("\"node_actor\"").unwrap();
        assert_eq!(parsed, ActorType::OSNodeActor);

        // Rainbowcore compat: "ai_actor" → AIActor (same as canonical)
        let parsed: ActorType = serde_json::from_str("\"ai_actor\"").unwrap();
        assert_eq!(parsed, ActorType::AIActor);
    }

    #[test]
    fn test_actor_type_display() {
        assert_eq!(ActorType::AIActor.to_string(), "ai_actor");
        assert_eq!(ActorType::OSNodeActor.to_string(), "osnode_actor");
        assert_eq!(ActorType::CoreNodeActor.to_string(), "corenode_actor");
    }

    #[test]
    fn test_actor_type_domain() {
        assert_eq!(ActorType::HumanActor.domain(), ActorDomain::Life);
        assert_eq!(ActorType::AIActor.domain(), ActorDomain::Life);
        assert_eq!(ActorType::OSNodeActor.domain(), ActorDomain::System);
        assert_eq!(ActorType::CoreNodeActor.domain(), ActorDomain::System);
        assert_eq!(ActorType::GroupActor.domain(), ActorDomain::Organization);
    }

    #[test]
    fn test_actor_type_is_system_node() {
        assert!(!ActorType::HumanActor.is_system_node());
        assert!(!ActorType::AIActor.is_system_node());
        assert!(ActorType::OSNodeActor.is_system_node());
        assert!(ActorType::CoreNodeActor.is_system_node());
        assert!(!ActorType::GroupActor.is_system_node());
    }

    #[test]
    fn test_actor_type_is_life_subject() {
        assert!(ActorType::HumanActor.is_life_subject());
        assert!(ActorType::AIActor.is_life_subject());
        assert!(!ActorType::OSNodeActor.is_life_subject());
        assert!(!ActorType::CoreNodeActor.is_life_subject());
        assert!(!ActorType::GroupActor.is_life_subject());
    }

    #[test]
    fn test_actor_id_generation() {
        let id = ActorId::generate(ActorType::AIActor);
        assert!(id.as_str().starts_with("ai_"));
        assert!(id.is_canonical());
    }

    #[test]
    fn test_actor_id_serialization() {
        let id = ActorId::new("ai_test-123");
        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(json, "\"ai_test-123\"");

        let parsed: ActorId = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, id);
    }

    #[test]
    fn test_actor_id_canonical_valid() {
        assert!(ActorId::new("ai_abc123").is_canonical());
        assert!(ActorId::new("human_user-001").is_canonical());
        assert!(ActorId::new("osnode_node-a1b2c3d4").is_canonical());
        assert!(ActorId::new("corenode_validator-1").is_canonical());
        assert!(ActorId::new("group_dao-xyz").is_canonical());

        for actor_type in [
            ActorType::HumanActor,
            ActorType::AIActor,
            ActorType::OSNodeActor,
            ActorType::CoreNodeActor,
            ActorType::GroupActor,
        ] {
            let id = ActorId::generate(actor_type);
            assert!(
                id.is_canonical(),
                "Generated {} ID should be canonical",
                actor_type
            );
        }
    }

    #[test]
    fn test_actor_id_canonical_invalid() {
        assert!(!ActorId::new("").is_canonical());
        assert!(!ActorId::new("abc123").is_canonical());
        assert!(!ActorId::new("invalid_abc123").is_canonical());
        assert!(!ActorId::new("ai_").is_canonical());
        assert!(!ActorId::new("ai_test_with_underscore").is_canonical());
        assert!(!ActorId::new("ai_test@123").is_canonical());

        let long_id = format!("ai_{}", "a".repeat(130));
        assert!(!ActorId::new(long_id).is_canonical());
    }

    #[test]
    fn test_actor_id_inferred_type() {
        assert_eq!(
            ActorId::new("ai_test").inferred_type(),
            Some(ActorType::AIActor)
        );
        assert_eq!(
            ActorId::new("human_user").inferred_type(),
            Some(ActorType::HumanActor)
        );
        assert_eq!(
            ActorId::new("osnode_node1").inferred_type(),
            Some(ActorType::OSNodeActor)
        );
        assert_eq!(
            ActorId::new("corenode_val1").inferred_type(),
            Some(ActorType::CoreNodeActor)
        );
        assert_eq!(
            ActorId::new("group_dao1").inferred_type(),
            Some(ActorType::GroupActor)
        );
        assert_eq!(ActorId::new("invalid_test").inferred_type(), None);
    }

    #[test]
    fn test_actor_id_matches_type() {
        let id = ActorId::new("ai_assistant");
        assert!(id.matches_type(ActorType::AIActor));
        assert!(!id.matches_type(ActorType::HumanActor));
    }

    #[test]
    fn test_actor_status_default() {
        assert_eq!(ActorStatus::default(), ActorStatus::Active);
    }

    #[test]
    fn test_actor_status_serde() {
        for status in [
            ActorStatus::Active,
            ActorStatus::Suspended,
            ActorStatus::InRepair,
            ActorStatus::Terminated,
        ] {
            let json = serde_json::to_string(&status).unwrap();
            let parsed: ActorStatus = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, status);
        }
    }
}