Skip to main content

kernel/
persistence_fields.rs

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