Skip to main content

omega_cognitive_kernel/body/
mod.rs

1//! Body / sensor / actuator bus — edge-device channel layer.
2//!
3//! Minimal live implementation (no hardware I/O yet).
4//!
5//! Safety rules (non-negotiable):
6//! - Never issues tokens or writes CAS.
7//! - `write_authorized` is always `false` on every return packet from this module.
8//! - Sensor `inject` is in-memory simulation only.
9//! - Actuator `propose_command` returns a proposal payload only without mutating channel value.
10//! - `apply_command` commits value only when called from a gated execute path.
11
12use crate::prelude::*;
13use alloc::collections::BTreeMap;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17impl ChannelKind {
18    pub fn parse(raw: &str) -> core::result::Result<Self, String> {
19        let normalized = raw.trim().to_ascii_lowercase();
20        if normalized.is_empty() || normalized == "sensor" {
21            Ok(Self::Sensor)
22        } else if normalized == "actuator" {
23            Ok(Self::Actuator)
24        } else if normalized == "bidirectional" {
25            Ok(Self::Bidirectional)
26        } else {
27            Err(format!(
28                "kind must be one of [actuator, bidirectional, sensor], got '{normalized}'"
29            ))
30        }
31    }
32
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Self::Sensor => "sensor",
36            Self::Actuator => "actuator",
37            Self::Bidirectional => "bidirectional",
38        }
39    }
40}
41
42/// Lifecycle status returned in [`BodyPacket`].
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum BodyPacketStatus {
46    Registered,
47    Ok,
48    Injected,
49    Proposed,
50    Applied,
51    Rejected,
52    UnknownChannel,
53}
54
55/// Structured actuator command proposal emitted before token-gated execution.
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57pub struct BodyCommandProposal {
58    pub action: String,
59    pub channel: String,
60    pub value: Value,
61    pub reason: String,
62    pub kind: ChannelKind,
63    pub applied: bool,
64    pub ts_ms: u64,
65}
66
67/// Packet returned by every [`BodyBus`] operation.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub struct BodyPacket {
70    pub status: BodyPacketStatus,
71    pub channel: String,
72    pub kind: Option<ChannelKind>,
73    pub value: Option<Value>,
74    pub updated_at_ms: Option<u64>,
75    pub write_authorized: bool,
76    pub applied: bool,
77    pub error: Option<String>,
78    pub proposal: Option<BodyCommandProposal>,
79}
80
81/// Channel metadata snapshot returned by [`BodyBus::list_channels`].
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct BodyChannelInfo {
84    pub name: String,
85    pub kind: ChannelKind,
86    pub has_value: bool,
87    pub updated_at_ms: Option<u64>,
88}
89
90/// Aggregate observability summary for [`BodyBus`].
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct BodySummary {
93    pub channel_count: usize,
94    pub sensors: usize,
95    pub actuators: usize,
96    pub bidirectional: usize,
97    pub channels: Vec<BodyChannelInfo>,
98    pub write_authorized: bool,
99    pub note: &'static str,
100}
101
102#[derive(Debug, Clone)]
103struct ChannelState {
104    kind: ChannelKind,
105    value: Option<Value>,
106    updated_at_ms: Option<u64>,
107    meta: BTreeMap<String, Value>,
108    last_command: Option<BodyCommandProposal>,
109}
110
111/// Named in-memory channels for sensors and actuators.
112///
113/// Channels hold the last known value in memory. Nothing here authorizes
114/// world writes or CAS mutations.
115#[derive(Debug, Clone, Default)]
116pub struct BodyBus {
117    channels: BTreeMap<String, ChannelState>,
118}
119
120impl BodyBus {
121    pub fn new() -> Self {
122        Self::default()
123    }
124
125    pub fn register(
126        &mut self,
127        name: &str,
128        kind: ChannelKind,
129        meta: Option<BTreeMap<String, Value>>,
130    ) -> core::result::Result<BodyPacket, String> {
131        let trimmed = name.trim();
132        if trimmed.is_empty() {
133            return Err("channel name must be non-empty".to_string());
134        }
135        let key = trimmed.to_string();
136        let existing = self.channels.get(&key);
137        let value = existing.and_then(|c| c.value.clone());
138        let updated_at_ms = existing.and_then(|c| c.updated_at_ms);
139        let last_command = existing.and_then(|c| c.last_command.clone());
140
141        self.channels.insert(
142            key.clone(),
143            ChannelState {
144                kind,
145                value,
146                updated_at_ms,
147                meta: meta.unwrap_or_default(),
148                last_command,
149            },
150        );
151        Ok(self.packet(&key, BodyPacketStatus::Registered, None))
152    }
153
154    pub fn unregister(&mut self, name: &str) -> bool {
155        self.channels.remove(name).is_some()
156    }
157
158    pub fn channel_meta(&self, name: &str) -> Option<&BTreeMap<String, Value>> {
159        self.channels.get(name).map(|c| &c.meta)
160    }
161
162    pub fn list_channels(&self) -> Vec<BodyChannelInfo> {
163        self.channels
164            .iter()
165            .map(|(name, ch)| BodyChannelInfo {
166                name: name.clone(),
167                kind: ch.kind,
168                has_value: ch.value.is_some(),
169                updated_at_ms: ch.updated_at_ms,
170            })
171            .collect()
172    }
173
174    /// Read last known value for a channel (observation only).
175    pub fn read(&self, name: &str) -> BodyPacket {
176        if !self.channels.contains_key(name) {
177            return self.packet(
178                name,
179                BodyPacketStatus::UnknownChannel,
180                Some("not_registered"),
181            );
182        }
183        self.packet(name, BodyPacketStatus::Ok, None)
184    }
185
186    /// Simulate a sensor reading (in-memory only).
187    ///
188    /// Allowed for `Sensor` and `Bidirectional` channels. Does not touch the world.
189    pub fn inject(&mut self, name: &str, value: Value, timestamp_ms: u64) -> BodyPacket {
190        let Some(ch) = self.channels.get_mut(name) else {
191            return self.packet(
192                name,
193                BodyPacketStatus::UnknownChannel,
194                Some("not_registered"),
195            );
196        };
197        if ch.kind == ChannelKind::Actuator {
198            return self.packet(
199                name,
200                BodyPacketStatus::Rejected,
201                Some("inject_not_allowed_on_actuator"),
202            );
203        }
204        ch.value = Some(value);
205        ch.updated_at_ms = Some(timestamp_ms);
206        self.packet(name, BodyPacketStatus::Injected, None)
207    }
208
209    /// Build an actuator command proposal without mutating the channel value.
210    pub fn propose_command(
211        &mut self,
212        name: &str,
213        value: Value,
214        reason: &str,
215        timestamp_ms: u64,
216    ) -> BodyPacket {
217        let Some(ch) = self.channels.get_mut(name) else {
218            return self.packet(
219                name,
220                BodyPacketStatus::UnknownChannel,
221                Some("not_registered"),
222            );
223        };
224        if ch.kind == ChannelKind::Sensor {
225            return self.packet(
226                name,
227                BodyPacketStatus::Rejected,
228                Some("command_not_allowed_on_sensor"),
229            );
230        }
231        let proposal = BodyCommandProposal {
232            action: "body_command".to_string(),
233            channel: name.to_string(),
234            value,
235            reason: reason.to_string(),
236            kind: ch.kind,
237            applied: false,
238            ts_ms: timestamp_ms,
239        };
240        ch.last_command = Some(proposal.clone());
241        let mut pkt = self.packet(name, BodyPacketStatus::Proposed, None);
242        pkt.proposal = Some(proposal);
243        pkt
244    }
245
246    /// Commit actuator value after a token-gated execute step.
247    ///
248    /// Still never issues tokens or writes CAS; `write_authorized` stays `false`.
249    pub fn apply_command(&mut self, name: &str, value: Value, timestamp_ms: u64) -> BodyPacket {
250        let Some(ch) = self.channels.get_mut(name) else {
251            return self.packet(
252                name,
253                BodyPacketStatus::UnknownChannel,
254                Some("not_registered"),
255            );
256        };
257        if ch.kind == ChannelKind::Sensor {
258            return self.packet(
259                name,
260                BodyPacketStatus::Rejected,
261                Some("command_not_allowed_on_sensor"),
262            );
263        }
264        let proposal = BodyCommandProposal {
265            action: "body_command".to_string(),
266            channel: name.to_string(),
267            value: value.clone(),
268            reason: String::new(),
269            kind: ch.kind,
270            applied: true,
271            ts_ms: timestamp_ms,
272        };
273        ch.value = Some(value);
274        ch.updated_at_ms = Some(timestamp_ms);
275        ch.last_command = Some(proposal);
276        let mut pkt = self.packet(name, BodyPacketStatus::Applied, None);
277        pkt.write_authorized = false;
278        pkt.applied = true;
279        pkt
280    }
281
282    pub fn summary(&self) -> BodySummary {
283        let mut sensors = 0usize;
284        let mut actuators = 0usize;
285        let mut bidirectional = 0usize;
286        for ch in self.channels.values() {
287            match ch.kind {
288                ChannelKind::Sensor => sensors += 1,
289                ChannelKind::Actuator => actuators += 1,
290                ChannelKind::Bidirectional => bidirectional += 1,
291            }
292        }
293        BodySummary {
294            channel_count: self.channels.len(),
295            sensors,
296            actuators,
297            bidirectional,
298            channels: self.list_channels(),
299            write_authorized: false,
300            note: "body_bus_gated_via_suggestion",
301        }
302    }
303
304    fn packet(&self, name: &str, status: BodyPacketStatus, error: Option<&str>) -> BodyPacket {
305        let ch = self.channels.get(name);
306        BodyPacket {
307            status,
308            channel: name.to_string(),
309            kind: ch.map(|c| c.kind),
310            value: ch.and_then(|c| c.value.clone()),
311            updated_at_ms: ch.and_then(|c| c.updated_at_ms),
312            write_authorized: false,
313            applied: false,
314            error: error.map(str::to_string),
315            proposal: None,
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use serde_json::json;
324
325    #[test]
326    fn register_list_and_unregister_channels() {
327        let mut bus = BodyBus::new();
328        assert!(bus.register("  ", ChannelKind::Sensor, None).is_err());
329
330        let pkt = bus
331            .register("temp", ChannelKind::Sensor, None)
332            .expect("register sensor");
333        assert_eq!(pkt.status, BodyPacketStatus::Registered);
334        assert!(!pkt.write_authorized);
335
336        bus.register("valve", ChannelKind::Actuator, None)
337            .expect("register actuator");
338        let list = bus.list_channels();
339        assert_eq!(list.len(), 2);
340        assert_eq!(list[0].name, "temp");
341        assert_eq!(list[1].name, "valve");
342
343        assert!(bus.unregister("temp"));
344        assert!(!bus.unregister("temp"));
345    }
346
347    #[test]
348    fn sensor_inject_and_reject_actuator() {
349        let mut bus = BodyBus::new();
350        bus.register("temp", ChannelKind::Sensor, None).unwrap();
351        bus.register("motor", ChannelKind::Actuator, None).unwrap();
352
353        let injected = bus.inject("temp", json!(23.5), 1_000);
354        assert_eq!(injected.status, BodyPacketStatus::Injected);
355        assert_eq!(injected.value, Some(json!(23.5)));
356        assert!(!injected.write_authorized);
357
358        let rejected = bus.inject("motor", json!(1.0), 1_001);
359        assert_eq!(rejected.status, BodyPacketStatus::Rejected);
360        assert_eq!(
361            rejected.error.as_deref(),
362            Some("inject_not_allowed_on_actuator")
363        );
364        assert!(!rejected.write_authorized);
365    }
366
367    #[test]
368    fn propose_does_not_mutate_until_apply_and_never_authorizes_writes() {
369        let mut bus = BodyBus::new();
370        bus.register("temp", ChannelKind::Sensor, None).unwrap();
371        bus.register("servo", ChannelKind::Bidirectional, None)
372            .unwrap();
373
374        let sensor_cmd = bus.propose_command("temp", json!(10), "test", 2_000);
375        assert_eq!(sensor_cmd.status, BodyPacketStatus::Rejected);
376        assert_eq!(
377            sensor_cmd.error.as_deref(),
378            Some("command_not_allowed_on_sensor")
379        );
380
381        let proposed = bus.propose_command("servo", json!(45), "align", 2_001);
382        assert_eq!(proposed.status, BodyPacketStatus::Proposed);
383        assert!(proposed.value.is_none());
384        assert!(proposed.proposal.is_some());
385        assert!(!proposed.write_authorized);
386
387        let applied = bus.apply_command("servo", json!(45), 2_002);
388        assert_eq!(applied.status, BodyPacketStatus::Applied);
389        assert!(applied.applied);
390        assert_eq!(applied.value, Some(json!(45)));
391        assert!(!applied.write_authorized);
392
393        let summary = bus.summary();
394        assert_eq!(summary.sensors, 1);
395        assert_eq!(summary.bidirectional, 1);
396        assert!(!summary.write_authorized);
397    }
398}
399/// Supported channel directions on [`BodyBus`].
400#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
401#[serde(rename_all = "snake_case")]
402pub enum ChannelKind {
403    Sensor,
404    Actuator,
405    Bidirectional,
406}