Skip to main content

kernel/graph/
facet_projection.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//! PMEST facet projection — computes a queryable facet map from a node + graph context.
8//!
9//! Spec: `faceted_filter_surface_spec.md §3`
10//!
11//! The projection is **pure** (no mutations). It derives canonical facet values
12//! from durable node data plus graph-structural context (edge degrees, etc.).
13//!
14//! Several facet keys are intentionally derived projections rather than stored
15//! node fields: `domain`, `edge_kinds`, `in_degree`, `out_degree`,
16//! `frame_memberships`, `udc_classes`.
17
18use std::collections::HashSet;
19
20use petgraph::Direction;
21use petgraph::visit::EdgeRef;
22
23use super::filter::{FacetProjection, FacetScalar, FacetValue, facet_keys};
24use super::{ArrangementSubKind, EdgeFamily, Graph, NodeKey};
25
26/// Compute the PMEST facet projection for a single node.
27///
28/// Returns a [`FacetProjection`] (`HashMap<String, FacetValue>`) ready for
29/// evaluation by [`FacetExpr::evaluate`].
30///
31/// Graph-structural facets (degrees, edge kinds, frame memberships) are derived
32/// from `graph` at call time. The projection reflects the current graph state
33/// and must be recomputed when graph structure changes.
34pub fn facet_projection_for_node(graph: &Graph, key: NodeKey) -> Option<FacetProjection> {
35    let node = graph.get_node(key)?;
36    let mut proj: FacetProjection = std::collections::HashMap::new();
37
38    // --- Personality ---
39
40    proj.insert(
41        facet_keys::ADDRESS_KIND.to_string(),
42        FacetValue::Scalar(FacetScalar::Text(format!(
43            "{:?}",
44            node.primary_address().address_kind()
45        ))),
46    );
47
48    if let Ok(url) = url::Url::parse(node.url()) {
49        if let Some(host) = url.host_str() {
50            proj.insert(
51                facet_keys::DOMAIN.to_string(),
52                FacetValue::Scalar(FacetScalar::Text(host.to_string())),
53            );
54        }
55    }
56
57    proj.insert(
58        facet_keys::TITLE.to_string(),
59        FacetValue::Scalar(FacetScalar::Text(node.title.clone())),
60    );
61
62    proj.insert(
63        facet_keys::ADDRESS.to_string(),
64        FacetValue::Scalar(FacetScalar::Text(node.url().to_string())),
65    );
66
67    // --- Matter ---
68
69    if let Some(mime) = &node.media_type {
70        proj.insert(
71            facet_keys::MIME_HINT.to_string(),
72            FacetValue::Scalar(FacetScalar::Text(mime.clone())),
73        );
74    }
75
76    // --- Energy (edge-derived) ---
77
78    let out_edges: Vec<_> = graph.projected_outgoing_relations(key).collect();
79    let in_edges: Vec<_> = graph.projected_incoming_relations(key).collect();
80
81    let out_degree = out_edges.len();
82    let in_degree = in_edges.len();
83
84    let mut edge_kind_labels: HashSet<&'static str> = HashSet::new();
85    for (_, _, payload) in out_edges.iter().chain(in_edges.iter()) {
86        for family in payload.families() {
87            edge_kind_labels.insert(edge_family_label(family));
88        }
89    }
90
91    proj.insert(
92        facet_keys::IN_DEGREE.to_string(),
93        FacetValue::Scalar(FacetScalar::Number(in_degree as f64)),
94    );
95    proj.insert(
96        facet_keys::OUT_DEGREE.to_string(),
97        FacetValue::Scalar(FacetScalar::Number(out_degree as f64)),
98    );
99
100    if !edge_kind_labels.is_empty() {
101        proj.insert(
102            facet_keys::EDGE_KINDS.to_string(),
103            FacetValue::Collection(
104                edge_kind_labels
105                    .into_iter()
106                    .map(|s| FacetScalar::Text(s.to_string()))
107                    .collect(),
108            ),
109        );
110    }
111
112    // Traversal count from outgoing TraversalDerived edges
113    let traversal_count: usize = graph
114        .inner
115        .inner()
116        .edges(key)
117        .filter_map(|e| e.weight().traversal.as_ref())
118        .map(|t| t.metrics.total_navigations as usize)
119        .sum();
120    proj.insert(
121        facet_keys::TRAVERSAL_COUNT.to_string(),
122        FacetValue::Scalar(FacetScalar::Number(traversal_count as f64)),
123    );
124
125    // --- Space ---
126
127    // Frame memberships: nodes that are target of an ArrangementRelation(FrameMember) edge
128    // directed TO this node (i.e., this node is a frame member).
129    // Represented as the source node keys (frame anchors).
130    let frame_memberships: Vec<FacetScalar> = graph
131        .inner
132        .inner()
133        .edges_directed(key, Direction::Incoming)
134        .filter(|e| {
135            e.weight()
136                .arrangement_data()
137                .is_some_and(|a| a.sub_kinds.contains(&ArrangementSubKind::FrameMember))
138        })
139        .map(|e| FacetScalar::Text(format!("{:?}", e.source())))
140        .collect();
141
142    if !frame_memberships.is_empty() {
143        proj.insert(
144            facet_keys::FRAME_MEMBERSHIPS.to_string(),
145            FacetValue::Collection(frame_memberships),
146        );
147    }
148
149    // UDC classes: semantic tags + durable NodeClassification values (Stage A schema).
150    // Tags already use "udc:"-prefixed values; classification values carry the same
151    // scheme-prefixed format (e.g. "udc:519.6") so they slot directly into the same
152    // collection facet.
153    {
154        let mut udc_values: Vec<FacetScalar> = graph
155            .node_content_tags(key)
156            .unwrap_or_default()
157            .into_iter()
158            .map(FacetScalar::Text)
159            .collect();
160        for c in graph.node_classifications(key).unwrap_or_default() {
161            if c.status.is_affirmative() {
162                udc_values.push(FacetScalar::Text(c.value.clone()));
163            }
164        }
165        if !udc_values.is_empty() {
166            proj.insert(
167                facet_keys::UDC_CLASSES.to_string(),
168                FacetValue::Collection(udc_values),
169            );
170        }
171    }
172
173    // --- Time ---
174
175    // last_visited as milliseconds since epoch (best available time source on Node)
176    if let Some(duration) = graph
177        .node_last_visited(key)
178        .and_then(|visited| visited.duration_since(std::time::UNIX_EPOCH).ok())
179    {
180        proj.insert(
181            facet_keys::LAST_TRAVERSAL.to_string(),
182            FacetValue::Scalar(FacetScalar::Number(duration.as_millis() as f64)),
183        );
184    }
185
186    // Lifecycle left the kernel with the browser-state sidecar (boundary pass
187    // slice C); a host that wants a lifecycle facet projects it from its own
188    // runtime state.
189
190    Some(proj)
191}
192
193fn edge_family_label(family: EdgeFamily) -> &'static str {
194    match family {
195        EdgeFamily::Semantic => "Semantic",
196        EdgeFamily::Traversal => "Traversal",
197        EdgeFamily::Containment => "Containment",
198        EdgeFamily::Arrangement => "Arrangement",
199        EdgeFamily::Imported => "Imported",
200        EdgeFamily::Provenance => "Provenance",
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use euclid::default::Point2D;
207
208    use super::*;
209    use crate::graph::Graph;
210    use crate::graph::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
211    use crate::graph::filter::facet_keys;
212
213    fn build_node(graph: &mut Graph, url: &str) -> NodeKey {
214        let GraphDeltaResult::NodeAdded(key) = apply_graph_delta(
215            graph,
216            GraphDelta::AddNode {
217                id: None,
218                url: url.to_string(),
219                position: Point2D::new(0.0, 0.0),
220            },
221        ) else {
222            panic!("expected NodeAdded");
223        };
224        key
225    }
226
227    #[test]
228    fn projection_includes_address_and_domain() {
229        let mut graph = Graph::new();
230        let key = build_node(&mut graph, "https://example.com/page");
231        let proj = facet_projection_for_node(&graph, key).unwrap();
232
233        assert!(proj.contains_key(facet_keys::ADDRESS));
234        assert!(proj.contains_key(facet_keys::DOMAIN));
235        let domain = &proj[facet_keys::DOMAIN];
236        assert_eq!(
237            *domain,
238            FacetValue::Scalar(FacetScalar::Text("example.com".to_string()))
239        );
240    }
241
242    #[test]
243    fn projection_computes_in_out_degree() {
244        let mut graph = Graph::new();
245        let a = build_node(&mut graph, "https://a.test/");
246        let b = build_node(&mut graph, "https://b.test/");
247        apply_graph_delta(
248            &mut graph,
249            GraphDelta::AssertRelation {
250                asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
251                from: a,
252                to: b,
253                assertion: crate::graph::EdgeAssertion::Semantic {
254                    sub_kind: crate::graph::SemanticSubKind::Hyperlink,
255                    label: None,
256                },
257            },
258        );
259
260        let proj_a = facet_projection_for_node(&graph, a).unwrap();
261        let proj_b = facet_projection_for_node(&graph, b).unwrap();
262
263        assert_eq!(
264            proj_a[facet_keys::OUT_DEGREE],
265            FacetValue::Scalar(FacetScalar::Number(1.0))
266        );
267        assert_eq!(
268            proj_b[facet_keys::IN_DEGREE],
269            FacetValue::Scalar(FacetScalar::Number(1.0))
270        );
271        assert!(
272            graph.find_edge_key(a, b).is_none(),
273            "Hyperlink belongs to Resource"
274        );
275        apply_graph_delta(
276            &mut graph,
277            GraphDelta::AppendTraversal {
278                from: a,
279                to: b,
280                trigger: crate::graph::NavigationTrigger::LinkClick,
281                timestamp_ms: Some(100),
282            },
283        );
284        assert!(
285            graph.find_edge_key(a, b).is_some(),
286            "Traversal remains Surface"
287        );
288        let projected = facet_projection_for_node(&graph, a).unwrap();
289        assert_eq!(
290            projected[facet_keys::OUT_DEGREE],
291            FacetValue::Scalar(FacetScalar::Number(2.0))
292        );
293        assert_eq!(
294            projected[facet_keys::TRAVERSAL_COUNT],
295            FacetValue::Scalar(FacetScalar::Number(1.0))
296        );
297        assert_eq!(
298            facet_projection_for_node(&graph, b).unwrap()[facet_keys::IN_DEGREE],
299            FacetValue::Scalar(FacetScalar::Number(2.0))
300        );
301    }
302
303    /// Lifecycle left the kernel with the browser-state sidecar (boundary
304    /// pass slice C): the kernel projection must NOT invent a lifecycle
305    /// facet; a host that wants one projects it from its own runtime state.
306    #[test]
307    fn projection_omits_lifecycle() {
308        let mut graph = Graph::new();
309        let key = build_node(&mut graph, "https://example.com/");
310        let proj = facet_projection_for_node(&graph, key).unwrap();
311        assert!(!proj.contains_key(facet_keys::LIFECYCLE));
312    }
313
314    #[test]
315    fn projection_udc_classes_includes_classification_values() {
316        use crate::graph::{
317            ClassificationProvenance, ClassificationScheme, ClassificationStatus,
318            NodeClassification,
319        };
320        let mut graph = Graph::new();
321        let key = build_node(&mut graph, "https://example.com/");
322        graph.add_node_classification(
323            key,
324            NodeClassification {
325                scheme: ClassificationScheme::Udc,
326                value: "udc:519.6".to_string(),
327                label: Some("Computational mathematics".to_string()),
328                confidence: 1.0,
329                provenance: ClassificationProvenance::UserAuthored,
330                status: ClassificationStatus::Accepted,
331                primary: true,
332            },
333        );
334        let proj = facet_projection_for_node(&graph, key).unwrap();
335        let udc = proj.get(facet_keys::UDC_CLASSES).unwrap();
336        let FacetValue::Collection(items) = udc else {
337            panic!("expected Collection");
338        };
339        assert!(
340            items.contains(&FacetScalar::Text("udc:519.6".to_string())),
341            "classification value must appear in udc_classes facet"
342        );
343    }
344
345    #[test]
346    fn projection_udc_classes_keeps_suggested_classifications_for_review() {
347        use crate::graph::{
348            ClassificationProvenance, ClassificationScheme, ClassificationStatus,
349            NodeClassification,
350        };
351        let mut graph = Graph::new();
352        let key = build_node(&mut graph, "https://example.com/");
353        // add a tag directly
354        graph.insert_node_tag(key, "udc:51".to_string());
355        // add a classification
356        graph.add_node_classification(
357            key,
358            NodeClassification {
359                scheme: ClassificationScheme::Udc,
360                value: "udc:519.6".to_string(),
361                label: None,
362                confidence: 0.9,
363                provenance: ClassificationProvenance::RegistryDerived,
364                status: ClassificationStatus::Suggested,
365                primary: false,
366            },
367        );
368        let proj = facet_projection_for_node(&graph, key).unwrap();
369        let FacetValue::Collection(items) = &proj[facet_keys::UDC_CLASSES] else {
370            panic!("expected Collection");
371        };
372        assert!(items.contains(&FacetScalar::Text("udc:51".to_string())));
373        assert!(!items.contains(&FacetScalar::Text("udc:519.6".to_string())));
374        let retained = graph.node_classifications(key).unwrap();
375        assert_eq!(retained.len(), 1);
376        assert_eq!(retained[0].status, ClassificationStatus::Suggested);
377    }
378
379    #[test]
380    fn classification_facets_include_affirmative_statuses_without_discarding_review() {
381        use crate::types::{
382            ClassificationProvenance, ClassificationScheme, ClassificationStatus,
383            NodeClassification,
384        };
385
386        for scheme in [
387            ClassificationScheme::Udc,
388            ClassificationScheme::ContentKind,
389            ClassificationScheme::Custom("rdf:type".into()),
390        ] {
391            for (status, projected) in [
392                (ClassificationStatus::Accepted, true),
393                (ClassificationStatus::Verified, true),
394                (ClassificationStatus::Imported, true),
395                (ClassificationStatus::Suggested, false),
396                (ClassificationStatus::Rejected, false),
397            ] {
398                let mut graph = Graph::new();
399                let key = build_node(&mut graph, "https://example.test/");
400                graph.insert_node_tag(key, "retained-tag".into());
401                let record = NodeClassification {
402                    scheme: scheme.clone(),
403                    value: "classification-value".into(),
404                    label: Some("Classification".into()),
405                    confidence: 0.8,
406                    provenance: ClassificationProvenance::UserAuthored,
407                    status,
408                    primary: true,
409                };
410                assert!(graph.add_node_classification(key, record.clone()));
411                let facets = facet_projection_for_node(&graph, key).unwrap();
412                let FacetValue::Collection(values) = &facets[facet_keys::UDC_CLASSES] else {
413                    panic!("expected classification collection");
414                };
415                assert!(values.contains(&FacetScalar::Text("retained-tag".into())));
416                assert_eq!(
417                    values.contains(&FacetScalar::Text(record.value.clone())),
418                    projected,
419                    "{record:?}"
420                );
421                assert_eq!(graph.node_classifications(key).unwrap(), vec![record]);
422            }
423        }
424    }
425}