Skip to main content

memstead_base/graph/
chain.rs

1//! A chain scope: the subgraph reachable from one root along a named
2//! rel-type set in one direction — the reduced set the export formats
3//! and the topology projection render when a caller asks for a chain
4//! instead of a whole mem.
5//!
6//! One resolver, one walker. The scope is resolved here once, through
7//! [`reachable_via`](crate::graph::query::reachable_via) — the same
8//! primitive `memstead_search`'s `expand_via` uses, so direction means
9//! the same thing on both surfaces: applied at EVERY hop, a pure
10//! transitive closure. The renderers then filter their existing
11//! per-entity passes by the resolved set; nothing is rendered twice and
12//! no second walker exists.
13
14use std::collections::HashSet;
15
16use serde::Serialize;
17
18use crate::entity::EntityId;
19use crate::graph::query::{ReachedVia, TraversalDirection, reachable_via};
20use crate::runtime_validator::validate_rel_type;
21
22/// What a caller asks for: a root entity, the rel-types to follow, the
23/// direction to follow them in, and how many hops.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
25pub struct ChainScope {
26    /// The entity the walk starts from; it is always part of the set.
27    pub root: EntityId,
28    /// Rel-types followed at every hop. Validated against the mem's
29    /// schema vocabulary before the walk.
30    pub via: Vec<String>,
31    /// Direction applied at every hop.
32    pub direction: TraversalDirection,
33    /// Maximum hops; `usize::MAX` for an unbounded walk.
34    pub depth: usize,
35}
36
37/// A resolved chain: the root plus everything reached, in any mem. The
38/// renderers filter to their mem; cross-mem members stay in the set so
39/// an edge into one renders as a reached (marked) target, not as an
40/// unresolved link.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ChainSet {
43    pub scope: ChainScope,
44    /// Root plus reached ids.
45    pub ids: HashSet<EntityId>,
46    /// Every reached entity with the edge it was first reached by.
47    pub reached: Vec<ReachedVia>,
48}
49
50impl ChainSet {
51    pub fn contains(&self, id: &EntityId) -> bool {
52        self.ids.contains(id)
53    }
54
55    /// One line naming the scope, for the headers of scoped renderings.
56    pub fn describe(&self) -> String {
57        let depth = if self.scope.depth == usize::MAX {
58            "unbounded".to_string()
59        } else {
60            self.scope.depth.to_string()
61        };
62        format!(
63            "root {} via {} direction {} depth {}",
64            self.scope.root,
65            self.scope.via.join(","),
66            self.scope.direction.as_wire(),
67            depth
68        )
69    }
70}
71
72impl TraversalDirection {
73    /// Stable wire form.
74    pub fn as_wire(self) -> &'static str {
75        match self {
76            TraversalDirection::Out => "out",
77            TraversalDirection::In => "in",
78            TraversalDirection::Both => "both",
79        }
80    }
81
82    /// Inverse of [`Self::as_wire`]; `None` for an unknown string.
83    pub fn from_wire(s: &str) -> Option<Self> {
84        match s {
85            "out" => Some(TraversalDirection::Out),
86            "in" => Some(TraversalDirection::In),
87            "both" => Some(TraversalDirection::Both),
88            _ => None,
89        }
90    }
91
92    /// Every wire string.
93    pub const WIRE_VALUES: &'static [&'static str] = &["out", "in", "both"];
94}
95
96impl crate::Engine {
97    /// Resolve `scope` against `mem`: the mem must be mounted, the root
98    /// must be a real (non-stub) entity of that mem, `via` must be
99    /// non-empty and every rel-type known to the mem's schema
100    /// (`INVALID_REL_TYPE` naming the vocabulary otherwise), and the walk
101    /// follows `reachable_via` with the scope's direction at every hop.
102    pub fn chain_set(&self, mem: &str, scope: &ChainScope) -> Result<ChainSet, crate::EngineError> {
103        if self.mount(mem).is_none() {
104            return Err(self.unknown_mem_error(mem));
105        }
106        let root = self
107            .store()
108            .get(&scope.root)
109            .filter(|e| !e.stub)
110            .ok_or_else(|| self.not_found(scope.root.as_ref()))?;
111        if root.mem != mem {
112            return Err(crate::EngineError::InvalidInput(format!(
113                "root {} lives in mem '{}', not in the exported mem '{mem}'",
114                scope.root, root.mem
115            )));
116        }
117        if scope.via.is_empty() {
118            return Err(crate::EngineError::InvalidInput(
119                "a chain needs at least one rel-type in `via`".to_string(),
120            ));
121        }
122        if let Some(schema) = self.schema_for(mem) {
123            for rel in &scope.via {
124                validate_rel_type(rel, &schema).map_err(crate::EngineError::Validation)?;
125            }
126        }
127        let reached = reachable_via(
128            self.store(),
129            &scope.root,
130            &scope.via,
131            scope.depth,
132            scope.direction,
133        );
134        let mut ids: HashSet<EntityId> = reached.iter().map(|r| r.id.clone()).collect();
135        ids.insert(scope.root.clone());
136        Ok(ChainSet {
137            scope: scope.clone(),
138            ids,
139            reached,
140        })
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use crate::backend::MemBackend;
147    use crate::graph::query::TraversalDirection;
148
149    use super::ChainScope;
150
151    /// root --A--> a1 --B--> a2 ; root --C--> c1 ; back --A--> root
152    /// (reachable only against `out`); a1 also cites x in another mem.
153    fn engine() -> (crate::Engine, tempfile::TempDir) {
154        let tmp = tempfile::TempDir::new().unwrap();
155        let seed = |dir: &std::path::Path, files: &[(&str, &str)]| {
156            std::fs::create_dir_all(dir).unwrap();
157            let writer = crate::storage::FilesystemBackend::new(dir.to_path_buf());
158            for (name, body) in files {
159                writer
160                    .write_entity(std::path::Path::new(name), body.as_bytes())
161                    .unwrap();
162            }
163            writer
164                .commit("seed", &crate::vcs::CommitContext::internal())
165                .unwrap();
166        };
167        let spec = |title: &str, rels: &str| {
168            format!(
169                "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# {title}\n\n## Identity\n\n{title}. See [[a2]] and [[c1]].\n{rels}"
170            )
171        };
172        let m = tmp.path().join("m");
173        let other = tmp.path().join("other");
174        seed(
175            &m,
176            &[
177                (
178                    "root.md",
179                    &spec(
180                        "Root",
181                        "\n## Relationships\n\n- **USES**: [[a1]]\n- **PART_OF**: [[c1]]\n",
182                    ),
183                ),
184                (
185                    "a1.md",
186                    &spec(
187                        "A1",
188                        "\n## Relationships\n\n- **DEPENDS_ON**: [[a2]]\n- **USES**: [[other--x]]\n",
189                    ),
190                ),
191                ("a2.md", &spec("A2", "")),
192                ("c1.md", &spec("C1", "")),
193                (
194                    "back.md",
195                    &spec("Back", "\n## Relationships\n\n- **USES**: [[root]]\n"),
196                ),
197            ],
198        );
199        seed(&other, &[("x.md", &spec("X", ""))]);
200        let mount = |mem: &str, path: std::path::PathBuf| {
201            (
202                crate::Mount {
203                    mem: mem.to_string(),
204                    schema: Some(memstead_schema::SchemaRef::new(
205                        "default",
206                        semver::Version::new(1, 0, 0),
207                    )),
208                    storage: crate::MountStorage::Folder { path: path.clone() },
209                    capability: crate::MountCapability::Write,
210                    lifecycle: crate::MountLifecycle::Eager,
211                    cross_linkable: true,
212                    migration_target: None,
213                },
214                Box::new(crate::storage::FilesystemBackend::new(path))
215                    as Box<dyn crate::MemBackend>,
216            )
217        };
218        let engine =
219            crate::Engine::from_mounts(vec![mount("m", m), mount("other", other)]).unwrap();
220        (engine, tmp)
221    }
222
223    fn scope(via: &[&str], direction: TraversalDirection, depth: usize) -> ChainScope {
224        ChainScope {
225            root: crate::EntityId::canonical("m--root"),
226            via: via.iter().map(|s| s.to_string()).collect(),
227            direction,
228            depth,
229        }
230    }
231
232    fn ids(engine: &crate::Engine, s: &ChainScope) -> Vec<String> {
233        let mut v: Vec<String> = engine
234            .chain_set("m", s)
235            .unwrap()
236            .ids
237            .iter()
238            .map(|i| i.to_string())
239            .collect();
240        v.sort();
241        v
242    }
243
244    /// The set is root plus exactly what the rel-types reach in the
245    /// direction, at every hop; the other rel-type and the
246    /// against-direction referrer stay out; depth 1 drops the second hop;
247    /// `in` walks the other way; cross-mem reached nodes stay in the set.
248    #[test]
249    fn chain_set_follows_via_and_direction_at_every_hop() {
250        let (engine, _tmp) = engine();
251        assert_eq!(
252            ids(
253                &engine,
254                &scope(&["USES", "DEPENDS_ON"], TraversalDirection::Out, usize::MAX)
255            ),
256            vec!["m--a1", "m--a2", "m--root", "other--x"]
257        );
258        assert_eq!(
259            ids(
260                &engine,
261                &scope(&["USES", "DEPENDS_ON"], TraversalDirection::Out, 1)
262            ),
263            vec!["m--a1", "m--root"]
264        );
265        assert_eq!(
266            ids(
267                &engine,
268                &scope(&["USES"], TraversalDirection::In, usize::MAX)
269            ),
270            vec!["m--back", "m--root"]
271        );
272        assert_eq!(
273            ids(
274                &engine,
275                &scope(&["PART_OF"], TraversalDirection::Out, usize::MAX)
276            ),
277            vec!["m--c1", "m--root"]
278        );
279        let set = engine
280            .chain_set(
281                "m",
282                &scope(&["USES", "DEPENDS_ON"], TraversalDirection::Out, usize::MAX),
283            )
284            .unwrap();
285        assert_eq!(set.reached.len(), 3);
286        assert!(
287            set.describe()
288                .contains("root m--root via USES,DEPENDS_ON direction out depth unbounded")
289        );
290    }
291
292    /// Refusals: an unknown rel-type names the vocabulary, a missing root
293    /// is ENTITY_NOT_FOUND, an empty via and a root outside the mem are
294    /// INVALID_INPUT, an unknown mem is UNKNOWN_MEM.
295    #[test]
296    fn chain_set_refuses_typed() {
297        let (engine, _tmp) = engine();
298        let err = engine
299            .chain_set("m", &scope(&["NOPE"], TraversalDirection::Out, 3))
300            .unwrap_err();
301        assert_eq!(err.code(), "INVALID_REL_TYPE", "{err}");
302        assert!(
303            err.details().to_string().contains("USES"),
304            "the recovery payload names the vocabulary: {}",
305            err.details()
306        );
307        let missing = ChainScope {
308            root: crate::EntityId::canonical("m--missing"),
309            ..scope(&["USES"], TraversalDirection::Out, 3)
310        };
311        assert_eq!(
312            engine.chain_set("m", &missing).unwrap_err().code(),
313            "ENTITY_NOT_FOUND"
314        );
315        assert_eq!(
316            engine
317                .chain_set("m", &scope(&[], TraversalDirection::Out, 3))
318                .unwrap_err()
319                .code(),
320            "INVALID_INPUT"
321        );
322        assert_eq!(
323            engine
324                .chain_set("other", &scope(&["USES"], TraversalDirection::Out, 3))
325                .unwrap_err()
326                .code(),
327            "INVALID_INPUT",
328            "root in another mem"
329        );
330        assert_eq!(
331            engine
332                .chain_set("ghost", &scope(&["USES"], TraversalDirection::Out, 3))
333                .unwrap_err()
334                .code(),
335            "UNKNOWN_MEM"
336        );
337    }
338
339    /// The scoped renderers carry exactly the chain's in-mem entities,
340    /// mark links to excluded entities unresolved, and the unscoped call
341    /// stays byte-identical to the pre-scope output.
342    #[test]
343    fn scoped_renderers_reduce_and_unscoped_stays_identical() {
344        let (engine, _tmp) = engine();
345        let chain = engine
346            .chain_set(
347                "m",
348                &scope(&["USES", "DEPENDS_ON"], TraversalDirection::Out, usize::MAX),
349            )
350            .unwrap();
351
352        // HTML
353        let full = engine.render_html_export("m", "2026-09-02").unwrap();
354        let same = engine
355            .render_html_export_scoped("m", "2026-09-02", None)
356            .unwrap();
357        assert_eq!(full, same, "None is byte-identical to the unscoped export");
358        let reduced = engine
359            .render_html_export_scoped("m", "2026-09-02", Some(&chain))
360            .unwrap();
361        for id in ["m--root", "m--a1", "m--a2"] {
362            assert!(reduced.contains(&format!("id=\"{id}\"")), "{id} rendered");
363        }
364        for id in ["m--c1", "m--back"] {
365            assert!(!reduced.contains(&format!("id=\"{id}\"")), "{id} excluded");
366        }
367        assert!(reduced.contains("Chain:"), "header names the chain");
368        assert!(
369            reduced.contains("unresolved"),
370            "links to excluded entities are marked"
371        );
372        assert!(reduced.contains("3 entities"));
373
374        // llms-txt
375        let ctx = crate::engine::export_llms_txt::LlmsTxtContext {
376            authority: None,
377            href_prefix: String::new(),
378            wider_project: Vec::new(),
379        };
380        let full = engine.render_llms_txt("m", &ctx).unwrap();
381        assert_eq!(
382            full,
383            engine.render_llms_txt_scoped("m", &ctx, None).unwrap()
384        );
385        let reduced = engine
386            .render_llms_txt_scoped("m", &ctx, Some(&chain))
387            .unwrap();
388        assert!(
389            reduced
390                .contains("Chain: root m--root via USES,DEPENDS_ON direction out depth unbounded")
391        );
392        assert!(reduced.contains("Entities: 3"));
393        assert!(reduced.contains("# A2"));
394        assert!(!reduced.contains("# C1"));
395        assert!(!reduced.contains("# Back"));
396        // The link to the included a2 resolves; the link to the excluded
397        // c1 is left unresolved (the linkifier's plain-text form), never
398        // a link to a page this document does not contain.
399        assert!(reduced.contains("[A2](entity/m--a2)"), "{reduced}");
400        assert!(reduced.contains(" and c1."), "{reduced}");
401        assert!(!reduced.contains("entity/m--c1"), "{reduced}");
402
403        // Topology
404        let full = engine.mem_topology("m").unwrap();
405        assert_eq!(full, engine.mem_topology_scoped("m", None).unwrap());
406        let reduced = engine.mem_topology_scoped("m", Some(&chain)).unwrap();
407        let node_ids: Vec<&str> = reduced.nodes.iter().map(|n| n.id.as_str()).collect();
408        assert_eq!(node_ids, vec!["m--a1", "m--a2", "m--root"]);
409        let edges: Vec<(String, String, bool)> = reduced
410            .edges
411            .iter()
412            .map(|e| (e.source.clone(), e.target.clone(), e.target_in_mem))
413            .collect();
414        assert_eq!(
415            edges,
416            vec![
417                ("m--a1".to_string(), "m--a2".to_string(), true),
418                ("m--a1".to_string(), "other--x".to_string(), false),
419                ("m--root".to_string(), "m--a1".to_string(), true),
420            ],
421            "edges with both ends in the chain, cross-mem target marked"
422        );
423    }
424}