Skip to main content

memstead_base/graph/
topology.rs

1//! Bulk per-mem topology projection — `{nodes, edges, communities}`
2//! for one mem, in one call, coordinate-free.
3//!
4//! "Projection" here is a render view of the live store, not the
5//! pipeline's projection-binding; the two nouns are unrelated. The
6//! shape exists for UI consumers (HTTP surfaces, CLI) that
7//! would otherwise assemble topology from paged list reads plus
8//! per-entity relation calls — the measured N+1 path — or re-derive it
9//! per surface (the `serve/` precedent this module hoists).
10//!
11//! Contract decisions, deliberate and shared by every consumer:
12//!
13//! - **Coordinate-free.** Layout is the consumer's job; no x/y/z ever.
14//! - **Unpaged, untruncated.** The design target is 1,000–5,000
15//!   entities per mem, served whole. Any future scale cut must be
16//!   declared on-surface, never silent.
17//! - **Cross-mem edges ride, source-in-mem only.** An edge whose
18//!   source entity lives in the projected mem is included even when
19//!   its target lives elsewhere (`target_in_mem: false`) — the
20//!   engine's established asymmetric convention (community bridges,
21//!   health). Composing every mem's projection therefore yields the
22//!   complete workspace graph with each cross-mem edge exactly once.
23//! - **Global community ids.** Assignments come from the
24//!   workspace-global Louvain partition (never re-run per mem), keyed
25//!   by the partition's own cluster ids — the same cluster carries the
26//!   same id across per-mem projections from one snapshot, so
27//!   multi-mem consumers can compose without renumbering.
28
29use serde::Serialize;
30
31/// One entity as a topology node. Coordinate-free by design.
32#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
33pub struct TopologyNode {
34    pub id: String,
35    pub title: String,
36    pub entity_type: String,
37    /// Global Louvain cluster id from the workspace partition; `None`
38    /// when the partition carries no assignment for this entity.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub community: Option<String>,
41    /// True for stub entities (unresolved references) — consumers
42    /// choose their own rendering; nothing is dropped here.
43    pub stub: bool,
44}
45
46/// One directed relationship edge whose source lives in the projected
47/// mem.
48#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
49pub struct TopologyEdge {
50    pub source: String,
51    pub target: String,
52    pub rel_type: String,
53    /// `false` marks a cross-mem edge: the target entity lives outside
54    /// the projected mem (reported here, at the source mem, only).
55    pub target_in_mem: bool,
56}
57
58/// One global cluster's presence in the projected mem.
59#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
60pub struct TopologyCommunity {
61    /// Global cluster id (workspace partition).
62    pub id: String,
63    /// How many of the cluster's members live in the projected mem.
64    pub size_in_mem: usize,
65}
66
67/// The full per-mem projection.
68#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
69pub struct MemTopology {
70    pub mem: String,
71    pub nodes: Vec<TopologyNode>,
72    pub edges: Vec<TopologyEdge>,
73    /// Clusters with at least one member in the mem, sorted by id.
74    pub communities: Vec<TopologyCommunity>,
75}
76
77impl crate::Engine {
78    /// Project `mem`'s current topology from the live store — every
79    /// entity in the mem, every relationship edge sourced in the mem
80    /// (cross-mem targets marked), and the mem's community roster from
81    /// the global partition. Recomputed on every call, never
82    /// incremental: deleted or renamed entities are simply absent from
83    /// the next projection. Unknown mems refuse with
84    /// [`crate::EngineError::UnknownMem`].
85    pub fn mem_topology(&self, mem: &str) -> Result<MemTopology, crate::EngineError> {
86        self.mem_topology_scoped(mem, None)
87    }
88
89    /// [`Self::mem_topology`] reduced to a chain: only the mem's entities
90    /// in `chain` become nodes, and only the edges whose both ends are in
91    /// the chain (the target possibly in another mem, marked) become
92    /// edges — the subgraph the chain induces. `None` is the whole mem,
93    /// byte-identical to the unscoped projection.
94    pub fn mem_topology_scoped(
95        &self,
96        mem: &str,
97        chain: Option<&crate::graph::chain::ChainSet>,
98    ) -> Result<MemTopology, crate::EngineError> {
99        if self.mount(mem).is_none() {
100            return Err(self.unknown_mem_error(mem));
101        }
102        Ok(project_mem_topology(
103            self.store(),
104            self.communities(),
105            mem,
106            chain,
107        ))
108    }
109}
110
111/// The projection itself, over any store and partition: every entity
112/// of `mem` (the whole mem, or the chain-induced subgraph when `chain`
113/// is given), every relationship edge sourced in it (cross-mem targets
114/// marked), and the mem's community roster from `louvain`. THE single
115/// derivation: [`crate::Engine::mem_topology`] is this function over
116/// the live engine store, and a consumer that holds a store without
117/// an engine (a validated archive about to be published, an in-memory
118/// load) calls it directly rather than re-deriving nodes, edges and
119/// communities on its own. Deterministic order: nodes by id, edges by
120/// (source, target, rel_type), communities by cluster id.
121pub fn project_mem_topology(
122    store: &crate::store::Store,
123    louvain: &crate::graph::LouvainOutput,
124    mem: &str,
125    chain: Option<&crate::graph::chain::ChainSet>,
126) -> MemTopology {
127    let mut nodes = Vec::new();
128    let mut edges = Vec::new();
129    let mut community_sizes: std::collections::BTreeMap<String, usize> =
130        std::collections::BTreeMap::new();
131
132    for entity in store.all_entities() {
133        if entity.mem != mem {
134            continue;
135        }
136        if let Some(chain) = chain
137            && !chain.contains(&entity.id)
138        {
139            continue;
140        }
141        let id = entity.id.to_string();
142        let community = louvain.entity_cluster_map.get(&id).cloned();
143        if let Some(cluster) = &community {
144            *community_sizes.entry(cluster.clone()).or_insert(0) += 1;
145        }
146        nodes.push(TopologyNode {
147            id: id.clone(),
148            title: entity.title.clone(),
149            entity_type: entity.entity_type.clone(),
150            community,
151            stub: entity.stub,
152        });
153        for edge in store.outgoing(&entity.id) {
154            if let Some(chain) = chain
155                && !chain.contains(&edge.target)
156            {
157                continue;
158            }
159            let target_in_mem = store
160                .get(&edge.target)
161                .map(|t| t.mem == mem)
162                .unwrap_or(false);
163            edges.push(TopologyEdge {
164                source: id.clone(),
165                target: edge.target.to_string(),
166                rel_type: edge.rel_type.clone(),
167                target_in_mem,
168            });
169        }
170    }
171
172    // Deterministic order: stable frames, simple assertions.
173    nodes.sort_by(|a, b| a.id.cmp(&b.id));
174    edges.sort_by(|a, b| {
175        (&a.source, &a.target, &a.rel_type).cmp(&(&b.source, &b.target, &b.rel_type))
176    });
177    let communities = community_sizes
178        .into_iter()
179        .map(|(id, size_in_mem)| TopologyCommunity { id, size_in_mem })
180        .collect();
181
182    MemTopology {
183        mem: mem.to_string(),
184        nodes,
185        edges,
186        communities,
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use crate::backend::MemBackend;
193
194    /// Two folder mems, one cross-mem edge (seeded in the markdown so
195    /// no mutation-time policy is involved). The projection must keep
196    /// the cross-mem edge at its source mem only, use global cluster
197    /// ids, carry no layout fields, and refuse unknown mems typed.
198    fn two_mem_engine() -> (crate::Engine, tempfile::TempDir) {
199        let tmp = tempfile::TempDir::new().unwrap();
200        let seed = |dir: &std::path::Path, files: &[(&str, &str)]| {
201            std::fs::create_dir_all(dir).unwrap();
202            let writer = crate::storage::FilesystemBackend::new(dir.to_path_buf());
203            for (name, body) in files {
204                writer
205                    .write_entity(std::path::Path::new(name), body.as_bytes())
206                    .unwrap();
207            }
208            // write_entity buffers; the commit flushes to disk.
209            writer
210                .commit("seed", &crate::vcs::CommitContext::internal())
211                .unwrap();
212        };
213        let specs_dir = tmp.path().join("specs");
214        let vendor_dir = tmp.path().join("vendor");
215        seed(
216            &specs_dir,
217            &[
218                (
219                    "alpha.md",
220                    "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Alpha\n\n## Identity\n\nA.\n\n## Relationships\n\n- **USES**: [[beta]]\n- **DEPENDS_ON**: [[vendor--gamma]]\n",
221                ),
222                (
223                    "beta.md",
224                    "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Beta\n\n## Identity\n\nB.\n",
225                ),
226            ],
227        );
228        seed(
229            &vendor_dir,
230            &[(
231                "gamma.md",
232                "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Gamma\n\n## Identity\n\nC.\n",
233            )],
234        );
235        let mount = |mem: &str, path: std::path::PathBuf| {
236            (
237                crate::Mount {
238                    mem: mem.to_string(),
239                    schema: Some(memstead_schema::SchemaRef::new(
240                        "default",
241                        semver::Version::new(1, 0, 0),
242                    )),
243                    storage: crate::MountStorage::Folder { path: path.clone() },
244                    capability: crate::MountCapability::Write,
245                    lifecycle: crate::MountLifecycle::Eager,
246                    cross_linkable: true,
247                    migration_target: None,
248                },
249                Box::new(crate::storage::FilesystemBackend::new(path))
250                    as Box<dyn crate::MemBackend>,
251            )
252        };
253        let engine = crate::Engine::from_mounts(vec![
254            mount("specs", specs_dir),
255            mount("vendor", vendor_dir),
256        ])
257        .unwrap();
258        (engine, tmp)
259    }
260
261    #[test]
262    fn projection_is_faithful_composable_and_coordinate_free() {
263        let (engine, _tmp) = two_mem_engine();
264
265        let specs = engine.mem_topology("specs").unwrap();
266        let vendor = engine.mem_topology("vendor").unwrap();
267
268        // Node fidelity: exactly the mem's entities.
269        let specs_ids: Vec<&str> = specs.nodes.iter().map(|n| n.id.as_str()).collect();
270        assert_eq!(specs_ids, vec!["specs--alpha", "specs--beta"]);
271        assert_eq!(vendor.nodes.len(), 1);
272        assert_eq!(vendor.nodes[0].id, "vendor--gamma");
273
274        // Cross-mem composition: the DEPENDS_ON edge rides at its
275        // source mem with the target marked outside; the target mem's
276        // projection does not repeat it — union carries it once.
277        let cross: Vec<_> = specs
278            .edges
279            .iter()
280            .filter(|e| e.rel_type == "DEPENDS_ON")
281            .collect();
282        assert_eq!(cross.len(), 1);
283        assert_eq!(cross[0].target, "vendor--gamma");
284        assert!(!cross[0].target_in_mem);
285        assert!(
286            vendor.edges.iter().all(|e| e.rel_type != "DEPENDS_ON"),
287            "cross-mem edge must not repeat at the target mem: {:?}",
288            vendor.edges
289        );
290        // In-mem edge is marked in-mem.
291        let uses: Vec<_> = specs
292            .edges
293            .iter()
294            .filter(|e| e.rel_type == "USES")
295            .collect();
296        assert_eq!(uses.len(), 1);
297        assert!(uses[0].target_in_mem);
298
299        // Community stability: assignments equal the global partition's
300        // and share ids across the two projections' rosters.
301        let louvain = engine.communities();
302        for node in specs.nodes.iter().chain(vendor.nodes.iter()) {
303            assert_eq!(
304                node.community.as_ref(),
305                louvain.entity_cluster_map.get(&node.id),
306                "node {} must carry the global assignment",
307                node.id
308            );
309        }
310
311        // Coordinate-free: no layout key anywhere in the payload.
312        let json = serde_json::to_string(&specs).unwrap();
313        for forbidden in ["\"x\":", "\"y\":", "\"z\":", "position", "layout"] {
314            assert!(
315                !json.contains(forbidden),
316                "layout field leaked: {forbidden}"
317            );
318        }
319
320        // Unknown mem refuses typed.
321        let err = engine.mem_topology("ghost").unwrap_err();
322        assert!(matches!(err, crate::EngineError::UnknownMem { name: m, .. } if m == "ghost"));
323    }
324}
325
326#[cfg(test)]
327mod scale_tests {
328    use crate::backend::MemBackend;
329
330    /// Design-target guard (plan criterion: "a mem at the design-target
331    /// entity count is served whole — no page cap, no top-N
332    /// truncation"). 1,500 entities sit mid-target (1,000–5,000); a
333    /// future page cap or truncation lands as a failure here, not
334    /// silently.
335    #[test]
336    fn design_target_mem_is_served_whole() {
337        const N: usize = 1_500;
338        let tmp = tempfile::TempDir::new().unwrap();
339        let dir = tmp.path().join("bulk");
340        std::fs::create_dir_all(&dir).unwrap();
341        let writer = crate::storage::FilesystemBackend::new(dir.clone());
342        for i in 0..N {
343            // Chain edges so the edge count scales with the node count.
344            let rel = if i > 0 {
345                format!("\n## Relationships\n\n- **USES**: [[node-{}]]\n", i - 1)
346            } else {
347                String::new()
348            };
349            let body = format!(
350                "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Node {i}\n\n## Identity\n\nBulk node {i}.\n{rel}"
351            );
352            writer
353                .write_entity(
354                    std::path::Path::new(&format!("node-{i}.md")),
355                    body.as_bytes(),
356                )
357                .unwrap();
358        }
359        writer
360            .commit("seed bulk", &crate::vcs::CommitContext::internal())
361            .unwrap();
362
363        let mount = crate::Mount {
364            mem: "bulk".to_string(),
365            schema: Some(memstead_schema::SchemaRef::new(
366                "default",
367                semver::Version::new(1, 0, 0),
368            )),
369            storage: crate::MountStorage::Folder { path: dir.clone() },
370            capability: crate::MountCapability::Write,
371            lifecycle: crate::MountLifecycle::Eager,
372            cross_linkable: false,
373            migration_target: None,
374        };
375        let backend =
376            Box::new(crate::storage::FilesystemBackend::new(dir)) as Box<dyn crate::MemBackend>;
377        let engine = crate::Engine::from_mounts(vec![(mount, backend)]).unwrap();
378
379        let topology = engine.mem_topology("bulk").unwrap();
380        assert_eq!(topology.nodes.len(), N, "every node, no cap");
381        assert_eq!(topology.edges.len(), N - 1, "every edge, no cap");
382    }
383}