Skip to main content

kernel/
persistence_fields.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Persistence DTOs for the field layer (`Field` + `Coupling`), field-system
8//! Phase 2.
9//!
10//! Siblings to the `Persisted*` types in [`crate::persistence`] (re-exported
11//! there), kept in their own file so that module stays under the workspace's
12//! per-file ceiling.
13//!
14//! The flat field-layer enums (extent, lifecycle, selector, response) archive
15//! natively under rkyv. The one recursive piece — the scalar/vector AST
16//! ([`FieldDefinition`](crate::graph::FieldDefinition), `Box`-nested) — rides as a
17//! **serde-JSON string** ([`PersistedField::definition_json`]) rather than via
18//! rkyv `omit_bounds`: the kernel AST is deliberately serde-only, the definition
19//! is loaded once and evaluated in memory by numen (no zero-copy benefit), and
20//! a blob keeps the archive flat and the round-trip robust. `serde_json` is
21//! already a base kernel dependency.
22
23use rkyv::{Archive, Deserialize, Serialize};
24
25// ---------------------------------------------------------------------------
26// Field persistence types
27// ---------------------------------------------------------------------------
28
29/// Where a field applies (mirrors `graph::FieldExtent`). `AttachedToNode` stores
30/// the node UUID as a string, matching `PersistedNode::node_id` / `PersistedEdge`.
31#[derive(
32    Archive, Serialize, Deserialize, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize,
33)]
34#[rkyv(derive(Debug, PartialEq))]
35pub enum PersistedFieldExtent {
36    Global,
37    Region {
38        min_x: f32,
39        min_y: f32,
40        max_x: f32,
41        max_y: f32,
42    },
43    AttachedToNode(String),
44    /// A closed world-space polygon (the hulls extent).
45    Polygon {
46        points: Vec<(f32, f32)>,
47    },
48}
49
50impl Default for PersistedFieldExtent {
51    fn default() -> Self {
52        PersistedFieldExtent::Global
53    }
54}
55
56/// Field lifecycle state (mirrors `graph::FieldLifecycle`).
57#[derive(
58    Archive,
59    Serialize,
60    Deserialize,
61    Clone,
62    Copy,
63    Debug,
64    PartialEq,
65    Eq,
66    Default,
67    serde::Serialize,
68    serde::Deserialize,
69)]
70#[rkyv(derive(Debug, PartialEq))]
71pub enum PersistedFieldLifecycle {
72    #[default]
73    Active,
74    Retired,
75}
76
77/// Persisted field. Identity + a JSON-encoded definition AST + extent + lifecycle.
78#[derive(
79    Archive, Serialize, Deserialize, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize,
80)]
81#[rkyv(derive(Debug))]
82pub struct PersistedField {
83    /// Stable field identity (UUID as string).
84    pub id: String,
85    /// Optional authoring name.
86    #[serde(default)]
87    pub name: Option<String>,
88    /// The scalar/vector definition AST, serde-JSON-encoded (see module note).
89    pub definition_json: String,
90    #[serde(default)]
91    pub extent: PersistedFieldExtent,
92    #[serde(default)]
93    pub lifecycle: PersistedFieldLifecycle,
94}
95
96// ---------------------------------------------------------------------------
97// Coupling persistence types
98// ---------------------------------------------------------------------------
99
100/// Which nodes a coupling targets (mirrors `graph::NodeSelector`).
101#[derive(
102    Archive, Serialize, Deserialize, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize,
103)]
104#[rkyv(derive(Debug, PartialEq))]
105pub enum PersistedNodeSelector {
106    All,
107    Tagged(String),
108    Kind(String),
109    NotTagged(String),
110}
111
112/// How a coupling's targets respond to its field (mirrors `graph::CouplingResponse`).
113/// The six force responses are the recognized core; `Open` carries the open-tail
114/// families by IRI. Not `Copy` (the `Open` variant owns a `String`).
115#[derive(
116    Archive, Serialize, Deserialize, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize,
117)]
118#[rkyv(derive(Debug, PartialEq))]
119pub enum PersistedCouplingResponse {
120    AttractToMin,
121    RepelFromMax,
122    AlignVelocity,
123    FlowAdvect,
124    DampenInside { factor: f32 },
125    ContainmentWall,
126    Open { predicate: String },
127}
128
129/// Persisted coupling. Identity + target field + selector + response + strength.
130#[derive(
131    Archive, Serialize, Deserialize, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize,
132)]
133#[rkyv(derive(Debug))]
134pub struct PersistedCoupling {
135    /// Stable coupling identity (UUID as string).
136    pub id: String,
137    /// The field this coupling targets (UUID as string).
138    pub field_id: String,
139    pub selector: PersistedNodeSelector,
140    pub response: PersistedCouplingResponse,
141    pub strength: f32,
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn field_extent_and_lifecycle_serde_roundtrip() {
150        let extents = [
151            PersistedFieldExtent::Global,
152            PersistedFieldExtent::Region {
153                min_x: -1.0,
154                min_y: -2.0,
155                max_x: 3.0,
156                max_y: 4.0,
157            },
158            PersistedFieldExtent::AttachedToNode("abc".into()),
159        ];
160        for e in &extents {
161            let j = serde_json::to_string(e).unwrap();
162            assert_eq!(
163                *e,
164                serde_json::from_str::<PersistedFieldExtent>(&j).unwrap()
165            );
166        }
167        for l in [
168            PersistedFieldLifecycle::Active,
169            PersistedFieldLifecycle::Retired,
170        ] {
171            let j = serde_json::to_string(&l).unwrap();
172            assert_eq!(
173                l,
174                serde_json::from_str::<PersistedFieldLifecycle>(&j).unwrap()
175            );
176        }
177    }
178
179    #[test]
180    fn selector_and_response_serde_roundtrip() {
181        let selectors = [
182            PersistedNodeSelector::All,
183            PersistedNodeSelector::Tagged("t".into()),
184            PersistedNodeSelector::Kind("k".into()),
185            PersistedNodeSelector::NotTagged("n".into()),
186        ];
187        for s in &selectors {
188            let j = serde_json::to_string(s).unwrap();
189            assert_eq!(
190                *s,
191                serde_json::from_str::<PersistedNodeSelector>(&j).unwrap()
192            );
193        }
194        let responses = [
195            PersistedCouplingResponse::AttractToMin,
196            PersistedCouplingResponse::RepelFromMax,
197            PersistedCouplingResponse::AlignVelocity,
198            PersistedCouplingResponse::FlowAdvect,
199            PersistedCouplingResponse::DampenInside { factor: 0.25 },
200            PersistedCouplingResponse::ContainmentWall,
201        ];
202        for r in &responses {
203            let j = serde_json::to_string(r).unwrap();
204            assert_eq!(
205                *r,
206                serde_json::from_str::<PersistedCouplingResponse>(&j).unwrap()
207            );
208        }
209    }
210
211    #[test]
212    fn field_and_coupling_rkyv_roundtrip() {
213        // The flat DTOs archive + read back natively (the AST rides as the
214        // definition_json string).
215        let field = PersistedField {
216            id: "field-1".into(),
217            name: Some("focus".into()),
218            definition_json: "{\"Scalar\":{\"Const\":1.0}}".into(),
219            extent: PersistedFieldExtent::Region {
220                min_x: 0.0,
221                min_y: 0.0,
222                max_x: 10.0,
223                max_y: 10.0,
224            },
225            lifecycle: PersistedFieldLifecycle::Retired,
226        };
227        let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&field).unwrap();
228        let back: PersistedField =
229            rkyv::from_bytes::<PersistedField, rkyv::rancor::Error>(&bytes).unwrap();
230        assert_eq!(back.id, "field-1");
231        assert_eq!(back.lifecycle, PersistedFieldLifecycle::Retired);
232        assert_eq!(back.definition_json, field.definition_json);
233
234        let coupling = PersistedCoupling {
235            id: "c-1".into(),
236            field_id: "field-1".into(),
237            selector: PersistedNodeSelector::Tagged("paper".into()),
238            response: PersistedCouplingResponse::DampenInside { factor: 0.3 },
239            strength: 1.5,
240        };
241        let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&coupling).unwrap();
242        let back: PersistedCoupling =
243            rkyv::from_bytes::<PersistedCoupling, rkyv::rancor::Error>(&bytes).unwrap();
244        assert_eq!(back.field_id, "field-1");
245        assert_eq!(back.strength, 1.5);
246    }
247}