arkhe-forge-core 0.15.0

L1 primitives for ArkheForge Runtime: Core 5 (User / Actor / Space / Entry / Activity) + ShellBrand invariant-lifetime isolation + deterministic entity-id derivation. Pure compute, no I/O.
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
//! Space primitive — container / scope.

use std::collections::BTreeSet;

use arkhe_kernel::abi::{EntityId, Tick, TypeCode};
use serde::{Deserialize, Serialize};

use crate::action::{ActionCompute, ArkheAction as _};
use crate::actor::ActorId;
use crate::brand::ShellId;
use crate::component::{ArkheComponent as _, BoundedString};
use crate::context::{ensure_schema_version, ActionContext, ActionError};
use crate::ArkheAction;
use crate::ArkheComponent;
// E14.L1-Deny enforcement on Action::compute.
use crate::arkhe_pure;

/// Opaque handle into the runtime Space namespace.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SpaceId(EntityId);

impl SpaceId {
    /// Construct a `SpaceId` from a runtime-allocated `EntityId`. Callers
    /// must hold proof (spawn event, admin scope, or test fixture) that the
    /// id belongs to the Space namespace — this constructor does not verify.
    #[inline]
    #[must_use]
    pub fn new(id: EntityId) -> Self {
        Self(id)
    }

    /// Underlying entity handle.
    #[inline]
    #[must_use]
    pub fn get(self) -> EntityId {
        self.0
    }
}

/// Space structural kind. `Extension` is an escape hatch — shell manifest must
/// register the `type_code` with a `schema_hash` pin (E-space-6 / A15).
///
/// On-wire tag is the postcard VARIANT INDEX (0..N in declaration order), not
/// the `repr(u8)` discriminant — the explicit `= 255` is a C-ABI hint, never
/// the serialized byte.
#[non_exhaustive]
#[repr(u8)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum SpaceKind {
    /// Flat list (e.g. BBS board).
    Flat = 0,
    /// Tree (e.g. nested comments).
    Tree = 1,
    /// Graph (e.g. follow graph).
    Graph = 2,
    /// Hashtag aggregation.
    Hashtag = 3,
    /// Per-actor feed.
    ActorFeed = 4,
    /// Shell-defined extension kind.
    Extension {
        /// Extension dispatch code.
        type_code: TypeCode,
    } = 255,
}

/// Visibility policy for Space contents.
#[non_exhaustive]
#[repr(u8)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum Visibility {
    /// World-readable.
    Public = 0,
    /// Restricted by L2 role-check.
    RestrictedByRole = 1,
    /// Readable by subscribers only.
    SubscribersOnly = 2,
    /// Private invitation list (see `SpaceMembership`).
    PrivateInvite = 3,
    /// End-to-end encrypted.
    Encrypted = 4,
}

/// Space configuration Component — exactly one per Space (E-space-1).
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ArkheComponent)]
#[arkhe(type_code = 0x0003_0201, schema_version = 1)]
pub struct SpaceConfig {
    /// Wire-level schema version tag.
    pub schema_version: u16,
    /// Shell identity — immutable.
    pub shell_id: ShellId,
    /// URL-safe slug — unique within shell.
    pub slug: BoundedString<32>,
    /// Structural kind.
    pub kind: SpaceKind,
    /// Visibility policy.
    pub visibility: Visibility,
    /// Creating actor (must be in same shell — E-space-5).
    pub creator: ActorId,
    /// Parent Space in the DAG. Immutable after creation (E-space-7 / P5).
    pub parent_space: Option<SpaceId>,
    /// Creation tick.
    pub created_tick: Tick,
}

/// Cached parent-chain depth — enables O(1) cycle / depth check (E-space-4).
/// Monotone, computed from parent's `depth + 1` at spawn.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, ArkheComponent)]
#[arkhe(type_code = 0x0003_0202, schema_version = 1)]
pub struct ParentChainDepth {
    /// Wire-level schema version tag.
    pub schema_version: u16,
    /// Depth (0 = root, max [`MAX_SPACE_DEPTH`]).
    pub depth: u8,
}

/// Membership list for `Visibility::PrivateInvite` Spaces (X3 DM support).
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ArkheComponent)]
#[arkhe(type_code = 0x0003_0203, schema_version = 1)]
pub struct SpaceMembership {
    /// Wire-level schema version tag.
    pub schema_version: u16,
    /// Permitted actor set — canonical `BTreeSet` ordering for deterministic
    /// serialization.
    pub members: BTreeSet<ActorId>,
}

/// Wire-format Space configuration MINUS the creating actor. The creator is
/// NOT a wire field: the runtime injects the authenticated identity at the
/// dispatch boundary, and [`CreateSpace::compute`] stamps it into the stored
/// [`SpaceConfig`]. This is the structural close of the actor-substitution
/// surface — there is no client-supplied `creator` to spoof.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct SpaceConfigDraft {
    /// Wire-level schema version tag.
    pub schema_version: u16,
    /// Shell identity — immutable.
    pub shell_id: ShellId,
    /// URL-safe slug — unique within shell.
    pub slug: BoundedString<32>,
    /// Structural kind.
    pub kind: SpaceKind,
    /// Visibility policy.
    pub visibility: Visibility,
    /// Parent Space in the DAG. Immutable after creation (E-space-7 / P5).
    pub parent_space: Option<SpaceId>,
    /// Creation tick.
    pub created_tick: Tick,
}

impl SpaceConfigDraft {
    /// Promote a draft to a stored [`SpaceConfig`] by stamping the
    /// authenticated `creator` — the single source of truth injected by the
    /// runtime, never a wire field.
    #[must_use]
    fn into_config(self, creator: ActorId) -> SpaceConfig {
        SpaceConfig {
            schema_version: self.schema_version,
            shell_id: self.shell_id,
            slug: self.slug,
            kind: self.kind,
            visibility: self.visibility,
            creator,
            parent_space: self.parent_space,
            created_tick: self.created_tick,
        }
    }
}

/// Spawn a fresh Space under `config`.
///
/// The payload carries no creating actor: the recorded creator is the
/// authenticated identity the runtime injects via
/// [`ActionContext::acting_actor`](crate::context::ActionContext::acting_actor),
/// so it cannot be substituted.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ArkheAction)]
#[arkhe(type_code = 0x0001_0201, schema_version = 1, band = 1)]
pub struct CreateSpace {
    /// Wire-level schema version tag.
    pub schema_version: u16,
    /// Initial configuration minus the creating actor (injected at dispatch).
    pub config: SpaceConfigDraft,
}

impl ActionCompute for CreateSpace {
    #[arkhe_pure]
    fn compute<'i>(&self, ctx: &mut ActionContext<'i>) -> Result<(), ActionError> {
        // Validate-then-copy: wire schema versions are checked against the
        // canonical constants before any other gate, so a stale or forged
        // version never reaches the stored config.
        ensure_schema_version(Self::SCHEMA_VERSION, self.schema_version)?;
        ensure_schema_version(SpaceConfig::SCHEMA_VERSION, self.config.schema_version)?;

        // Single source of truth: the creating actor is the authenticated
        // identity the runtime injected at dispatch — never a wire field.
        // A user-scoped action with no injected actor cannot proceed.
        let creator = ctx.acting_actor().ok_or(ActionError::AuthorizationFailed(
            "space requires an authenticated actor",
        ))?;

        // E-user-3 C3 MC — refuse Action when the creator's backing user is
        // already in `GdprStatus::ErasurePending`. `GdprEraseUser` owns the
        // write that sets that pointer (its own `UserGdprState` component).
        ctx.ensure_actor_eligible(creator, ctx.tick())?;

        // E-space-4 MC — parent chain depth check. A parent reference that
        // would push the child past `MAX_SPACE_DEPTH` is rejected; a None
        // parent roots at depth 0. The `ParentChainDepth` O(1) cache is
        // read from the attached `InstanceView` (E8 invariant).
        let child_depth: u8 = match self.config.parent_space {
            Some(parent_id) => {
                let parent_depth = ctx
                    .read::<ParentChainDepth>(parent_id.get())?
                    .ok_or(ActionError::InvalidInput("parent space not found"))?;
                let next = parent_depth.depth.saturating_add(1);
                if next > MAX_SPACE_DEPTH {
                    return Err(ActionError::InvalidInput("space depth exceeded"));
                }
                next
            }
            None => 0,
        };

        // Stamp the injected creator into the stored config (authenticated
        // creator), then spawn + attach.
        let config = self.config.clone().into_config(creator);
        let space_entity = ctx.spawn_entity_for::<SpaceConfig>()?;
        ctx.set_component(space_entity, &config)?;
        ctx.set_component(
            space_entity,
            &ParentChainDepth {
                schema_version: 1,
                depth: child_depth,
            },
        )?;
        Ok(())
    }
}

/// Maximum parent-chain depth (invariant E-space-4). Deeper trees reject with
/// `DepthExceeded`.
pub const MAX_SPACE_DEPTH: u8 = 64;

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::action::ArkheAction;
    use crate::component::ArkheComponent;

    fn ent(v: u64) -> EntityId {
        EntityId::new(v).unwrap()
    }

    #[test]
    fn space_config_serde_roundtrip_postcard() {
        let cfg = SpaceConfig {
            schema_version: 1,
            shell_id: ShellId([0x01; 16]),
            slug: BoundedString::<32>::new("general").unwrap(),
            kind: SpaceKind::Tree,
            visibility: Visibility::Public,
            creator: ActorId::new(ent(42)),
            parent_space: None,
            created_tick: Tick(0),
        };
        let bytes = postcard::to_stdvec(&cfg).unwrap();
        let back: SpaceConfig = postcard::from_bytes(&bytes).unwrap();
        assert_eq!(cfg, back);
    }

    #[test]
    fn space_membership_preserves_canonical_order() {
        let mut set = BTreeSet::new();
        set.insert(ActorId::new(ent(3)));
        set.insert(ActorId::new(ent(1)));
        set.insert(ActorId::new(ent(2)));
        let m = SpaceMembership {
            schema_version: 1,
            members: set,
        };
        let serialized_once = postcard::to_stdvec(&m).unwrap();

        let mut set2 = BTreeSet::new();
        set2.insert(ActorId::new(ent(2)));
        set2.insert(ActorId::new(ent(1)));
        set2.insert(ActorId::new(ent(3)));
        let m2 = SpaceMembership {
            schema_version: 1,
            members: set2,
        };
        assert_eq!(serialized_once, postcard::to_stdvec(&m2).unwrap());
    }

    #[test]
    fn space_config_action_type_codes() {
        assert_eq!(SpaceConfig::TYPE_CODE, 0x0003_0201);
        assert_eq!(ParentChainDepth::TYPE_CODE, 0x0003_0202);
        assert_eq!(SpaceMembership::TYPE_CODE, 0x0003_0203);
        assert_eq!(CreateSpace::TYPE_CODE, 0x0001_0201);
        assert_eq!(CreateSpace::BAND, 1);
    }

    #[test]
    fn max_space_depth_is_sixty_four() {
        assert_eq!(MAX_SPACE_DEPTH, 64);
    }

    fn draft() -> SpaceConfigDraft {
        SpaceConfigDraft {
            schema_version: 1,
            shell_id: ShellId([0x01; 16]),
            slug: BoundedString::<32>::new("general").unwrap(),
            kind: SpaceKind::Flat,
            visibility: Visibility::Public,
            parent_space: None,
            created_tick: Tick(0),
        }
    }

    #[test]
    fn create_space_records_injected_creator_not_a_wire_field() {
        use crate::action::ActionCompute;
        use arkhe_kernel::abi::{CapabilityMask, InstanceId, Principal};

        let injected = ActorId::new(ent(0xC1));
        let act = CreateSpace {
            schema_version: 1,
            config: draft(),
        };
        let mut c = ActionContext::new(
            [0u8; 32],
            InstanceId::new(1).unwrap(),
            Tick(7),
            Principal::System,
            CapabilityMask::SYSTEM,
        )
        .with_actor(Some(injected));
        act.compute(&mut c).expect("injected creator → compute ok");
        let recorded = c.ops().iter().find_map(|op| match op {
            arkhe_kernel::state::Op::SetComponent {
                type_code, bytes, ..
            } if *type_code == TypeCode(SpaceConfig::TYPE_CODE) => {
                postcard::from_bytes::<SpaceConfig>(bytes).ok()
            }
            _ => None,
        });
        assert_eq!(
            recorded.expect("config present").creator,
            injected,
            "recorded creator must equal the injected acting actor",
        );
    }

    #[test]
    fn create_space_rejects_wire_schema_mismatch() {
        use crate::action::ActionCompute;
        use arkhe_kernel::abi::{CapabilityMask, InstanceId, Principal};

        let mut c = ActionContext::new(
            [0u8; 32],
            InstanceId::new(1).unwrap(),
            Tick(7),
            Principal::System,
            CapabilityMask::SYSTEM,
        )
        .with_actor(Some(ActorId::new(ent(0xC1))));

        // Action-level wire field — first check, fires before the auth gate.
        let mut act = CreateSpace {
            schema_version: 0xBEEF,
            config: draft(),
        };
        let err = act
            .compute(&mut c)
            .expect_err("wire schema mismatch must reject");
        assert!(
            matches!(
                err,
                ActionError::SchemaMismatch {
                    expected: 1,
                    got: 0xBEEF,
                }
            ),
            "got {err:?}",
        );
        assert!(c.ops().is_empty(), "no Ops on rejection");

        // Nested config field — validated before the copy into the stored
        // SpaceConfig.
        act.schema_version = 1;
        act.config.schema_version = 0xBEEF;
        let err = act
            .compute(&mut c)
            .expect_err("config schema mismatch must reject");
        assert!(
            matches!(
                err,
                ActionError::SchemaMismatch {
                    expected: 1,
                    got: 0xBEEF,
                }
            ),
            "got {err:?}",
        );
        assert!(c.ops().is_empty(), "no Ops on rejection");

        // Matching versions proceed.
        act.config.schema_version = 1;
        act.compute(&mut c).expect("matching versions → Ok");
    }

    #[test]
    fn create_space_without_injected_actor_rejects() {
        use crate::action::ActionCompute;
        use arkhe_kernel::abi::{CapabilityMask, InstanceId, Principal};

        let act = CreateSpace {
            schema_version: 1,
            config: draft(),
        };
        let mut c = ActionContext::new(
            [0u8; 32],
            InstanceId::new(1).unwrap(),
            Tick(7),
            Principal::System,
            CapabilityMask::SYSTEM,
        );
        let err = act
            .compute(&mut c)
            .expect_err("no injected actor must reject");
        assert!(matches!(err, ActionError::AuthorizationFailed(_)));
        assert!(c.ops().is_empty(), "no Ops on rejection");
    }
}