mere-kernel 0.0.3

Portable identity, authority, and mutation kernel for the Mere browser. Renamed from graphshell-core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright 2026 Mark Alan Boykin
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// SPDX-License-Identifier: MPL-2.0

//! PMEST facet projection — computes a queryable facet map from a node + graph context.
//!
//! Spec: `faceted_filter_surface_spec.md §3`
//!
//! The projection is **pure** (no mutations). It derives canonical facet values
//! from durable node data plus graph-structural context (edge degrees, etc.).
//!
//! Several facet keys are intentionally derived projections rather than stored
//! node fields: `domain`, `edge_kinds`, `in_degree`, `out_degree`,
//! `frame_memberships`, `udc_classes`.

use std::collections::HashSet;

use petgraph::Direction;
use petgraph::visit::EdgeRef;

use super::filter::{FacetProjection, FacetScalar, FacetValue, facet_keys};
use super::{ArrangementSubKind, EdgeFamily, Graph, NodeKey};

/// Compute the PMEST facet projection for a single node.
///
/// Returns a [`FacetProjection`] (`HashMap<String, FacetValue>`) ready for
/// evaluation by [`FacetExpr::evaluate`].
///
/// Graph-structural facets (degrees, edge kinds, frame memberships) are derived
/// from `graph` at call time. The projection reflects the current graph state
/// and must be recomputed when graph structure changes.
pub fn facet_projection_for_node(graph: &Graph, key: NodeKey) -> Option<FacetProjection> {
    let node = graph.get_node(key)?;
    let mut proj: FacetProjection = std::collections::HashMap::new();

    // --- Personality ---

    proj.insert(
        facet_keys::ADDRESS_KIND.to_string(),
        FacetValue::Scalar(FacetScalar::Text(format!(
            "{:?}",
            node.primary_address().address_kind()
        ))),
    );

    if let Ok(url) = url::Url::parse(node.url()) {
        if let Some(host) = url.host_str() {
            proj.insert(
                facet_keys::DOMAIN.to_string(),
                FacetValue::Scalar(FacetScalar::Text(host.to_string())),
            );
        }
    }

    proj.insert(
        facet_keys::TITLE.to_string(),
        FacetValue::Scalar(FacetScalar::Text(node.title.clone())),
    );

    proj.insert(
        facet_keys::ADDRESS.to_string(),
        FacetValue::Scalar(FacetScalar::Text(node.url().to_string())),
    );

    // --- Matter ---

    if let Some(mime) = &node.media_type {
        proj.insert(
            facet_keys::MIME_HINT.to_string(),
            FacetValue::Scalar(FacetScalar::Text(mime.clone())),
        );
    }

    // --- Energy (edge-derived) ---

    let out_edges: Vec<_> = graph.projected_outgoing_relations(key).collect();
    let in_edges: Vec<_> = graph.projected_incoming_relations(key).collect();

    let out_degree = out_edges.len();
    let in_degree = in_edges.len();

    let mut edge_kind_labels: HashSet<&'static str> = HashSet::new();
    for (_, _, payload) in out_edges.iter().chain(in_edges.iter()) {
        for family in payload.families() {
            edge_kind_labels.insert(edge_family_label(family));
        }
    }

    proj.insert(
        facet_keys::IN_DEGREE.to_string(),
        FacetValue::Scalar(FacetScalar::Number(in_degree as f64)),
    );
    proj.insert(
        facet_keys::OUT_DEGREE.to_string(),
        FacetValue::Scalar(FacetScalar::Number(out_degree as f64)),
    );

    if !edge_kind_labels.is_empty() {
        proj.insert(
            facet_keys::EDGE_KINDS.to_string(),
            FacetValue::Collection(
                edge_kind_labels
                    .into_iter()
                    .map(|s| FacetScalar::Text(s.to_string()))
                    .collect(),
            ),
        );
    }

    // Traversal count from outgoing TraversalDerived edges
    let traversal_count: usize = graph
        .inner
        .inner()
        .edges(key)
        .filter_map(|e| e.weight().traversal.as_ref())
        .map(|t| t.metrics.total_navigations as usize)
        .sum();
    proj.insert(
        facet_keys::TRAVERSAL_COUNT.to_string(),
        FacetValue::Scalar(FacetScalar::Number(traversal_count as f64)),
    );

    // --- Space ---

    // Frame memberships: nodes that are target of an ArrangementRelation(FrameMember) edge
    // directed TO this node (i.e., this node is a frame member).
    // Represented as the source node keys (frame anchors).
    let frame_memberships: Vec<FacetScalar> = graph
        .inner
        .inner()
        .edges_directed(key, Direction::Incoming)
        .filter(|e| {
            e.weight()
                .arrangement_data()
                .is_some_and(|a| a.sub_kinds.contains(&ArrangementSubKind::FrameMember))
        })
        .map(|e| FacetScalar::Text(format!("{:?}", e.source())))
        .collect();

    if !frame_memberships.is_empty() {
        proj.insert(
            facet_keys::FRAME_MEMBERSHIPS.to_string(),
            FacetValue::Collection(frame_memberships),
        );
    }

    // UDC classes: semantic tags + durable NodeClassification values (Stage A schema).
    // Tags already use "udc:"-prefixed values; classification values carry the same
    // scheme-prefixed format (e.g. "udc:519.6") so they slot directly into the same
    // collection facet.
    {
        let mut udc_values: Vec<FacetScalar> = graph
            .node_content_tags(key)
            .unwrap_or_default()
            .into_iter()
            .map(FacetScalar::Text)
            .collect();
        for c in graph.node_classifications(key).unwrap_or_default() {
            if c.status.is_affirmative() {
                udc_values.push(FacetScalar::Text(c.value.clone()));
            }
        }
        if !udc_values.is_empty() {
            proj.insert(
                facet_keys::UDC_CLASSES.to_string(),
                FacetValue::Collection(udc_values),
            );
        }
    }

    // --- Time ---

    // last_visited as milliseconds since epoch (best available time source on Node)
    if let Some(duration) = graph
        .node_last_visited(key)
        .and_then(|visited| visited.duration_since(std::time::UNIX_EPOCH).ok())
    {
        proj.insert(
            facet_keys::LAST_TRAVERSAL.to_string(),
            FacetValue::Scalar(FacetScalar::Number(duration.as_millis() as f64)),
        );
    }

    // Lifecycle left the kernel with the browser-state sidecar (boundary pass
    // slice C); a host that wants a lifecycle facet projects it from its own
    // runtime state.

    Some(proj)
}

fn edge_family_label(family: EdgeFamily) -> &'static str {
    match family {
        EdgeFamily::Semantic => "Semantic",
        EdgeFamily::Traversal => "Traversal",
        EdgeFamily::Containment => "Containment",
        EdgeFamily::Arrangement => "Arrangement",
        EdgeFamily::Imported => "Imported",
        EdgeFamily::Provenance => "Provenance",
    }
}

#[cfg(test)]
mod tests {
    use euclid::default::Point2D;

    use super::*;
    use crate::graph::Graph;
    use crate::graph::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
    use crate::graph::filter::facet_keys;

    fn build_node(graph: &mut Graph, url: &str) -> NodeKey {
        let GraphDeltaResult::NodeAdded(key) = apply_graph_delta(
            graph,
            GraphDelta::AddNode {
                id: None,
                url: url.to_string(),
                position: Point2D::new(0.0, 0.0),
            },
        ) else {
            panic!("expected NodeAdded");
        };
        key
    }

    #[test]
    fn projection_includes_address_and_domain() {
        let mut graph = Graph::new();
        let key = build_node(&mut graph, "https://example.com/page");
        let proj = facet_projection_for_node(&graph, key).unwrap();

        assert!(proj.contains_key(facet_keys::ADDRESS));
        assert!(proj.contains_key(facet_keys::DOMAIN));
        let domain = &proj[facet_keys::DOMAIN];
        assert_eq!(
            *domain,
            FacetValue::Scalar(FacetScalar::Text("example.com".to_string()))
        );
    }

    #[test]
    fn projection_computes_in_out_degree() {
        let mut graph = Graph::new();
        let a = build_node(&mut graph, "https://a.test/");
        let b = build_node(&mut graph, "https://b.test/");
        apply_graph_delta(
            &mut graph,
            GraphDelta::AssertRelation {
                asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
                from: a,
                to: b,
                assertion: crate::graph::EdgeAssertion::Semantic {
                    sub_kind: crate::graph::SemanticSubKind::Hyperlink,
                    label: None,
                },
            },
        );

        let proj_a = facet_projection_for_node(&graph, a).unwrap();
        let proj_b = facet_projection_for_node(&graph, b).unwrap();

        assert_eq!(
            proj_a[facet_keys::OUT_DEGREE],
            FacetValue::Scalar(FacetScalar::Number(1.0))
        );
        assert_eq!(
            proj_b[facet_keys::IN_DEGREE],
            FacetValue::Scalar(FacetScalar::Number(1.0))
        );
        assert!(
            graph.find_edge_key(a, b).is_none(),
            "Hyperlink belongs to Resource"
        );
        apply_graph_delta(
            &mut graph,
            GraphDelta::AppendTraversal {
                from: a,
                to: b,
                trigger: crate::graph::NavigationTrigger::LinkClick,
                timestamp_ms: Some(100),
            },
        );
        assert!(
            graph.find_edge_key(a, b).is_some(),
            "Traversal remains Surface"
        );
        let projected = facet_projection_for_node(&graph, a).unwrap();
        assert_eq!(
            projected[facet_keys::OUT_DEGREE],
            FacetValue::Scalar(FacetScalar::Number(2.0))
        );
        assert_eq!(
            projected[facet_keys::TRAVERSAL_COUNT],
            FacetValue::Scalar(FacetScalar::Number(1.0))
        );
        assert_eq!(
            facet_projection_for_node(&graph, b).unwrap()[facet_keys::IN_DEGREE],
            FacetValue::Scalar(FacetScalar::Number(2.0))
        );
    }

    /// Lifecycle left the kernel with the browser-state sidecar (boundary
    /// pass slice C): the kernel projection must NOT invent a lifecycle
    /// facet; a host that wants one projects it from its own runtime state.
    #[test]
    fn projection_omits_lifecycle() {
        let mut graph = Graph::new();
        let key = build_node(&mut graph, "https://example.com/");
        let proj = facet_projection_for_node(&graph, key).unwrap();
        assert!(!proj.contains_key(facet_keys::LIFECYCLE));
    }

    #[test]
    fn projection_udc_classes_includes_classification_values() {
        use crate::graph::{
            ClassificationProvenance, ClassificationScheme, ClassificationStatus,
            NodeClassification,
        };
        let mut graph = Graph::new();
        let key = build_node(&mut graph, "https://example.com/");
        graph.add_node_classification(
            key,
            NodeClassification {
                scheme: ClassificationScheme::Udc,
                value: "udc:519.6".to_string(),
                label: Some("Computational mathematics".to_string()),
                confidence: 1.0,
                provenance: ClassificationProvenance::UserAuthored,
                status: ClassificationStatus::Accepted,
                primary: true,
            },
        );
        let proj = facet_projection_for_node(&graph, key).unwrap();
        let udc = proj.get(facet_keys::UDC_CLASSES).unwrap();
        let FacetValue::Collection(items) = udc else {
            panic!("expected Collection");
        };
        assert!(
            items.contains(&FacetScalar::Text("udc:519.6".to_string())),
            "classification value must appear in udc_classes facet"
        );
    }

    #[test]
    fn projection_udc_classes_keeps_suggested_classifications_for_review() {
        use crate::graph::{
            ClassificationProvenance, ClassificationScheme, ClassificationStatus,
            NodeClassification,
        };
        let mut graph = Graph::new();
        let key = build_node(&mut graph, "https://example.com/");
        // add a tag directly
        graph.insert_node_tag(key, "udc:51".to_string());
        // add a classification
        graph.add_node_classification(
            key,
            NodeClassification {
                scheme: ClassificationScheme::Udc,
                value: "udc:519.6".to_string(),
                label: None,
                confidence: 0.9,
                provenance: ClassificationProvenance::RegistryDerived,
                status: ClassificationStatus::Suggested,
                primary: false,
            },
        );
        let proj = facet_projection_for_node(&graph, key).unwrap();
        let FacetValue::Collection(items) = &proj[facet_keys::UDC_CLASSES] else {
            panic!("expected Collection");
        };
        assert!(items.contains(&FacetScalar::Text("udc:51".to_string())));
        assert!(!items.contains(&FacetScalar::Text("udc:519.6".to_string())));
        let retained = graph.node_classifications(key).unwrap();
        assert_eq!(retained.len(), 1);
        assert_eq!(retained[0].status, ClassificationStatus::Suggested);
    }

    #[test]
    fn classification_facets_include_affirmative_statuses_without_discarding_review() {
        use crate::types::{
            ClassificationProvenance, ClassificationScheme, ClassificationStatus,
            NodeClassification,
        };

        for scheme in [
            ClassificationScheme::Udc,
            ClassificationScheme::ContentKind,
            ClassificationScheme::Custom("rdf:type".into()),
        ] {
            for (status, projected) in [
                (ClassificationStatus::Accepted, true),
                (ClassificationStatus::Verified, true),
                (ClassificationStatus::Imported, true),
                (ClassificationStatus::Suggested, false),
                (ClassificationStatus::Rejected, false),
            ] {
                let mut graph = Graph::new();
                let key = build_node(&mut graph, "https://example.test/");
                graph.insert_node_tag(key, "retained-tag".into());
                let record = NodeClassification {
                    scheme: scheme.clone(),
                    value: "classification-value".into(),
                    label: Some("Classification".into()),
                    confidence: 0.8,
                    provenance: ClassificationProvenance::UserAuthored,
                    status,
                    primary: true,
                };
                assert!(graph.add_node_classification(key, record.clone()));
                let facets = facet_projection_for_node(&graph, key).unwrap();
                let FacetValue::Collection(values) = &facets[facet_keys::UDC_CLASSES] else {
                    panic!("expected classification collection");
                };
                assert!(values.contains(&FacetScalar::Text("retained-tag".into())));
                assert_eq!(
                    values.contains(&FacetScalar::Text(record.value.clone())),
                    projected,
                    "{record:?}"
                );
                assert_eq!(graph.node_classifications(key).unwrap(), vec![record]);
            }
        }
    }
}