1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
25pub struct ChainScope {
26 pub root: EntityId,
28 pub via: Vec<String>,
31 pub direction: TraversalDirection,
33 pub depth: usize,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ChainSet {
43 pub scope: ChainScope,
44 pub ids: HashSet<EntityId>,
46 pub reached: Vec<ReachedVia>,
48}
49
50impl ChainSet {
51 pub fn contains(&self, id: &EntityId) -> bool {
52 self.ids.contains(id)
53 }
54
55 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 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 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 pub const WIRE_VALUES: &'static [&'static str] = &["out", "in", "both"];
94}
95
96impl crate::Engine {
97 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 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 #[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 #[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 #[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 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 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 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 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}