Skip to main content

kernel/graph/
field_ops.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Field-layer mutators + queries on `Graph` (field-system step 3, Phase 1).
5//!
6//! Fields and couplings are content truth, stored in parallel keyed maps beside
7//! the node/edge petgraph (see the struct fields on [`Graph`]). These mutators
8//! sit on the same single-write-path boundary as the node/edge mutators:
9//! trusted writers (reducer + persistence replay) call them; other paths route
10//! through reducer intents. `quint` reads this layer and evaluates it; nothing
11//! writes back here except an explicit author/pin action.
12
13use super::{Coupling, CouplingId, Field, FieldId, FieldLifecycle, Graph, NodeKey, NodeSelector};
14
15impl Graph {
16    // ── Fields ────────────────────────────────────────────────────────────────
17
18    /// Add or replace a field by its id.
19    pub(crate) fn add_field(&mut self, field: Field) {
20        self.fields.insert(field.id, field);
21    }
22
23    /// Retire a field: mark it `Retired` (keeping its definition for history /
24    /// federation) rather than dropping it. Returns whether the field existed.
25    pub(crate) fn retire_field(&mut self, id: FieldId) -> bool {
26        self.set_field_lifecycle(id, FieldLifecycle::Retired)
27    }
28
29    /// Reactivate a retired field, marking it `Active` again. The inverse of
30    /// [`retire_field`](Self::retire_field); together they make the field
31    /// lifecycle fully round-trippable from the kernel (the activate/retire UX
32    /// drives these). Returns whether the field existed.
33    pub(crate) fn activate_field(&mut self, id: FieldId) -> bool {
34        self.set_field_lifecycle(id, FieldLifecycle::Active)
35    }
36
37    fn set_field_lifecycle(&mut self, id: FieldId, lifecycle: FieldLifecycle) -> bool {
38        match self.fields.get_mut(&id) {
39            Some(field) => {
40                field.lifecycle = lifecycle;
41                true
42            }
43            None => false,
44        }
45    }
46
47    /// The field with this id, if any.
48    pub fn field(&self, id: FieldId) -> Option<&Field> {
49        self.fields.get(&id)
50    }
51
52    /// All fields, in unspecified order.
53    pub fn fields(&self) -> impl Iterator<Item = &Field> {
54        self.fields.values()
55    }
56
57    // ── Couplings ─────────────────────────────────────────────────────────────
58
59    /// Add or replace a coupling by its id.
60    pub(crate) fn add_coupling(&mut self, coupling: Coupling) {
61        self.couplings.insert(coupling.id, coupling);
62    }
63
64    /// Remove a coupling. Returns whether it existed. (Couplings have no
65    /// lifecycle state of their own; retracting drops the rule.)
66    pub(crate) fn retract_coupling(&mut self, id: CouplingId) -> bool {
67        self.couplings.remove(&id).is_some()
68    }
69
70    /// All couplings, in unspecified order.
71    pub fn couplings(&self) -> impl Iterator<Item = &Coupling> {
72        self.couplings.values()
73    }
74
75    /// Couplings whose target is the given field.
76    pub fn couplings_for_field(&self, field: FieldId) -> impl Iterator<Item = &Coupling> + '_ {
77        self.couplings.values().filter(move |c| c.field == field)
78    }
79
80    /// The `strength` of the first coupling targeting `field`, if any (a field
81    /// carries one default coupling). For the roster's per-field strength readout.
82    /// (Field regions — strength tuning.)
83    pub fn field_coupling_strength(&self, field: FieldId) -> Option<f32> {
84        self.couplings
85            .values()
86            .find(|c| c.field == field)
87            .map(|c| c.strength)
88    }
89
90    /// Set the `strength` of every coupling targeting `field`, returning whether any
91    /// was updated — the per-field force-well tuning the roster drives. (Field
92    /// regions — strength tuning.)
93    pub(crate) fn set_field_coupling_strength(&mut self, field: FieldId, strength: f32) -> bool {
94        let mut changed = false;
95        for coupling in self.couplings.values_mut() {
96            if coupling.field == field {
97                coupling.strength = strength;
98                changed = true;
99            }
100        }
101        changed
102    }
103
104    // ── Selector evaluation ───────────────────────────────────────────────────
105
106    /// Resolve a coupling's [`NodeSelector`] to the matching nodes, against node
107    /// tags and classifications. `Kind(k)` matches a node carrying any
108    /// classification whose value is `k` (the v1 interpretation; a
109    /// scheme-qualified match can refine it later).
110    pub fn nodes_matching<'a>(
111        &'a self,
112        selector: &'a NodeSelector,
113    ) -> impl Iterator<Item = NodeKey> + 'a {
114        self.inner.inner().node_indices().filter(move |&key| {
115            let Some(node) = self.inner.node(key) else {
116                return false;
117            };
118            match selector {
119                NodeSelector::All => true,
120                NodeSelector::Tagged(tag) => node.tags.contains(tag),
121                NodeSelector::NotTagged(tag) => !node.tags.contains(tag),
122                NodeSelector::Kind(kind) => self
123                    .node_classifications(key)
124                    .is_some_and(|classes| classes.iter().any(|c| &c.value == kind)),
125            }
126        })
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::super::{CouplingResponse, FieldDefinition, ScalarField};
133    use super::*;
134    use euclid::default::Point2D;
135    use uuid::Uuid;
136
137    fn fid(n: u8) -> FieldId {
138        FieldId::from_uuid(Uuid::from_bytes([n; 16]))
139    }
140    fn cid(n: u8) -> CouplingId {
141        CouplingId::from_uuid(Uuid::from_bytes([n; 16]))
142    }
143    fn scalar_field(id: FieldId) -> Field {
144        Field::new(id, FieldDefinition::Scalar(ScalarField::Const(1.0)))
145    }
146
147    #[test]
148    fn add_field_and_query_round_trip() {
149        let mut g = Graph::new();
150        let id = fid(1);
151        g.add_field(scalar_field(id).with_name("focus"));
152        assert!(g.field(id).is_some());
153        assert_eq!(g.fields().count(), 1);
154        assert_eq!(g.field(id).unwrap().name.as_deref(), Some("focus"));
155    }
156
157    #[test]
158    fn retire_field_marks_retired_keeps_definition() {
159        let mut g = Graph::new();
160        let id = fid(2);
161        g.add_field(scalar_field(id));
162        assert!(g.field(id).unwrap().is_active());
163        assert!(g.retire_field(id));
164        assert!(!g.field(id).unwrap().is_active());
165        // definition retained
166        assert!(matches!(
167            g.field(id).unwrap().definition,
168            FieldDefinition::Scalar(_)
169        ));
170        assert!(!g.retire_field(fid(99)), "unknown field retires false");
171
172        // reactivating is the inverse and round-trips the lifecycle
173        assert!(g.activate_field(id));
174        assert!(g.field(id).unwrap().is_active());
175        assert!(!g.activate_field(fid(99)), "unknown field activates false");
176    }
177
178    #[test]
179    fn couplings_add_query_and_retract() {
180        let mut g = Graph::new();
181        let field = fid(3);
182        let c = Coupling::new(
183            cid(3),
184            field,
185            NodeSelector::All,
186            CouplingResponse::AttractToMin,
187            1.0,
188        );
189        let other = Coupling::new(
190            cid(4),
191            fid(7),
192            NodeSelector::All,
193            CouplingResponse::RepelFromMax,
194            1.0,
195        );
196        g.add_coupling(c);
197        g.add_coupling(other);
198        assert_eq!(g.couplings().count(), 2);
199        assert_eq!(g.couplings_for_field(field).count(), 1);
200        assert!(g.retract_coupling(cid(3)));
201        assert_eq!(g.couplings().count(), 1);
202        assert!(!g.retract_coupling(cid(3)), "second retract is false");
203    }
204
205    #[test]
206    fn nodes_matching_resolves_selectors() {
207        let mut g = Graph::new();
208        let a = g.add_node_with_id(
209            Uuid::from_u128(1),
210            "mere://a".into(),
211            Point2D::new(0.0, 0.0),
212        );
213        let b = g.add_node_with_id(
214            Uuid::from_u128(2),
215            "mere://b".into(),
216            Point2D::new(10.0, 0.0),
217        );
218        if let Some(node) = g.inner.node_mut(a) {
219            node.tags.insert("important".to_string());
220        }
221
222        let all: Vec<_> = g.nodes_matching(&NodeSelector::All).collect();
223        assert_eq!(all.len(), 2);
224
225        let tagged: Vec<_> = g
226            .nodes_matching(&NodeSelector::Tagged("important".into()))
227            .collect();
228        assert_eq!(tagged, vec![a]);
229
230        let not_tagged: Vec<_> = g
231            .nodes_matching(&NodeSelector::NotTagged("important".into()))
232            .collect();
233        assert_eq!(not_tagged, vec![b]);
234
235        let no_kind: Vec<_> = g
236            .nodes_matching(&NodeSelector::Kind("paper".into()))
237            .collect();
238        assert!(no_kind.is_empty());
239    }
240}