Skip to main content

memstead_base/engine/
gates.rs

1//! The gates brief — the engine-rendered standing of every declared
2//! gated transition: `transition_requires_checks` (the related entities'
3//! checks) and `transition_requires_self_check` (the entity's own check).
4//!
5//! For each mounted mem whose schema declares the constraint on at
6//! least one type, the brief lists every non-stub entity of a gated
7//! type with its gated field's current value, whether it stands at the
8//! gated value ("closed") or before it ("open"), and — for open
9//! entities — the related-set coverage the transition would require:
10//! how many related entities the declared edges reach and which of
11//! them lack a fresh confirming check record. The related-set
12//! enumeration is [`crate::ops::health::transition_gate_standing`],
13//! the same code the write-time refusal runs, so the brief can never
14//! disagree with the gate.
15//!
16//! Open entities are listed in dependency order: a topological sort
17//! over the edges BETWEEN gated entities whose rel-type the schema
18//! declares acyclic (in the planning schema that is plan → plan
19//! REQUIRES; any schema's acyclic ordering vocabulary works the same),
20//! prerequisites first, ties by id. The brief reports state, never
21//! policy: which open entity a consumer acts on next — and which it
22//! must refuse (a human-gate marker, a parked status) — stays the
23//! consumer's judgement over its schema's vocabulary.
24//!
25//! The renderer is the shared engine entry point
26//! ([`Engine::render_gates_brief`]) per the brief-family precedent
27//! (due, ingest, sync): CLI verb, byte-identical everywhere,
28//! deliberately no MCP tool.
29
30use std::collections::HashMap;
31
32use memstead_schema::ConstraintDef;
33
34use super::Engine;
35use crate::entity::MetadataValue;
36
37impl Engine {
38    /// Render the gates brief as markdown. `mem_filter` restricts to
39    /// one mem; the default walks every mounted mem whose schema
40    /// declares the constraint. Deterministic given the store and the
41    /// check ledger.
42    pub fn render_gates_brief(&self, mem_filter: Option<&str>) -> String {
43        let checks = self.check_standing_provider();
44        let mut sections: Vec<String> = Vec::new();
45        let mut declaring_mems: Vec<String> = Vec::new();
46
47        let mut mems: Vec<&str> = self
48            .mounts
49            .iter()
50            .map(|m| m.mount.mem.as_str())
51            .filter(|m| mem_filter.is_none_or(|f| f == *m))
52            .collect();
53        mems.sort_unstable();
54
55        for mem in mems {
56            let Some(schema) = self.schemas.get(mem) else {
57                continue;
58            };
59            // The gated types of this schema, with their declarations.
60            let mut gated: Vec<(&str, &ConstraintDef)> = Vec::new();
61            for td in schema.types.values() {
62                for c in &td.constraints {
63                    if matches!(
64                        c,
65                        ConstraintDef::TransitionRequiresChecks { .. }
66                            | ConstraintDef::TransitionRequiresSelfCheck { .. }
67                    ) {
68                        gated.push((td.name.as_str(), c));
69                    }
70                }
71            }
72            if gated.is_empty() {
73                continue;
74            }
75            gated.sort_by_key(|(name, _)| *name);
76            declaring_mems.push(mem.to_string());
77
78            let mut lines: Vec<String> = Vec::new();
79            lines.push(format!("## {mem}"));
80            lines.push(String::new());
81
82            for (type_name, c) in &gated {
83                // The entity's own check: its standing is the coverage.
84                if let ConstraintDef::TransitionRequiresSelfCheck {
85                    field,
86                    to_value,
87                    check_kind,
88                    ..
89                } = c
90                {
91                    lines.push(format!(
92                        "Gate: `{type_name}` — `{field}: {to_value}` requires a fresh, independent \
93                         confirming `{check_kind}` check record on the entity itself."
94                    ));
95                    lines.push(String::new());
96                    let mut entities: Vec<_> = self
97                        .store
98                        .all_entities()
99                        .filter(|e| e.mem == mem && !e.stub && e.entity_type == *type_name)
100                        .collect();
101                    entities.sort_by(|a, b| a.id.0.cmp(&b.id.0));
102                    let mut closed: Vec<String> = Vec::new();
103                    let mut open: Vec<String> = Vec::new();
104                    for e in entities {
105                        let value = match e.metadata.get(field.as_str()) {
106                            Some(MetadataValue::String(s)) => s.clone(),
107                            Some(v) => v.to_frontmatter_string(),
108                            None => String::new(),
109                        };
110                        if value == *to_value {
111                            closed.push(format!("`{}`", e.id.0));
112                            continue;
113                        }
114                        let standing = checks(e, check_kind);
115                        let coverage = if standing.confirms() {
116                            format!("own `{check_kind}` check confirmed — gate satisfiable")
117                        } else {
118                            format!(
119                                "own `{check_kind}` check unconfirmed ({})",
120                                standing.label()
121                            )
122                        };
123                        open.push(format!(
124                            "- `{}` — {field}: {} — {coverage}",
125                            e.id.0,
126                            if value.is_empty() {
127                                "(unset)"
128                            } else {
129                                value.as_str()
130                            },
131                        ));
132                    }
133                    lines.push(format!(
134                        "Closed (at `{to_value}`): {}",
135                        if closed.is_empty() {
136                            "none".to_string()
137                        } else {
138                            closed.join(", ")
139                        }
140                    ));
141                    lines.push(String::new());
142                    if open.is_empty() {
143                        lines.push("Open: none — every gated entity stands closed.".to_string());
144                    } else {
145                        lines.push("Open:".to_string());
146                        lines.extend(open);
147                    }
148                    lines.push(String::new());
149                    continue;
150                }
151                let ConstraintDef::TransitionRequiresChecks {
152                    field,
153                    to_value,
154                    relationships,
155                    direction,
156                    min_related,
157                    ..
158                } = c
159                else {
160                    continue;
161                };
162                let floor = if *min_related > 0 {
163                    format!(
164                        ", and at least {min_related} such entit{}",
165                        if *min_related == 1 { "y" } else { "ies" }
166                    )
167                } else {
168                    String::new()
169                };
170                lines.push(format!(
171                    "Gate: `{type_name}` — `{field}: {to_value}` requires a fresh confirming \
172                     check record on every entity related via [{}] ({}){floor}.",
173                    relationships.join(", "),
174                    direction,
175                ));
176                lines.push(String::new());
177
178                // Every non-stub entity of the gated type.
179                let entities: Vec<_> = self
180                    .store
181                    .all_entities()
182                    .filter(|e| e.mem == mem && !e.stub && e.entity_type == *type_name)
183                    .collect();
184                let mut closed: Vec<String> = Vec::new();
185                struct OpenRow {
186                    id: String,
187                    value: String,
188                    total: usize,
189                    unchecked: Vec<crate::ops::health::UncheckedRelated>,
190                }
191                let mut open: Vec<OpenRow> = Vec::new();
192                for e in &entities {
193                    let value = match e.metadata.get(field.as_str()) {
194                        Some(MetadataValue::String(s)) => s.clone(),
195                        Some(v) => v.to_frontmatter_string(),
196                        None => String::new(),
197                    };
198                    if value == *to_value {
199                        closed.push(e.id.0.clone());
200                    } else {
201                        let (total, unchecked) = crate::ops::health::transition_gate_standing(
202                            &self.store,
203                            e,
204                            relationships,
205                            *direction,
206                            None,
207                            Some(&checks),
208                        );
209                        open.push(OpenRow {
210                            id: e.id.0.clone(),
211                            value,
212                            total,
213                            unchecked,
214                        });
215                    }
216                }
217                closed.sort();
218
219                // Dependency order over acyclic edges between gated
220                // entities: an edge source depends on its target, so
221                // targets (prerequisites) list first.
222                let acyclic: Vec<&str> = schema
223                    .manifest
224                    .relationships
225                    .definitions
226                    .iter()
227                    .filter(|r| r.acyclic)
228                    .map(|r| r.name.as_str())
229                    .collect();
230                let open_ids: Vec<String> = open.iter().map(|r| r.id.clone()).collect();
231                let mut prereqs: HashMap<String, Vec<String>> = HashMap::new();
232                for e in &entities {
233                    if !open_ids.contains(&e.id.0) {
234                        continue;
235                    }
236                    for rel in &e.relationships {
237                        if acyclic.contains(&rel.rel_type.as_str())
238                            && open_ids.contains(&rel.target.0)
239                            && rel.target.0 != e.id.0
240                        {
241                            prereqs
242                                .entry(e.id.0.clone())
243                                .or_default()
244                                .push(rel.target.0.clone());
245                        }
246                    }
247                }
248                let mut ordered: Vec<&OpenRow> = Vec::new();
249                let mut placed: Vec<&str> = Vec::new();
250                let mut remaining: Vec<&OpenRow> = open.iter().collect();
251                remaining.sort_by(|a, b| a.id.cmp(&b.id));
252                while !remaining.is_empty() {
253                    let idx = remaining.iter().position(|r| {
254                        prereqs
255                            .get(&r.id)
256                            .is_none_or(|p| p.iter().all(|d| placed.contains(&d.as_str())))
257                    });
258                    // A cycle among open entities cannot arise (the
259                    // edges are engine-enforced acyclic); the fallback
260                    // keeps the loop total anyway.
261                    let idx = idx.unwrap_or(0);
262                    let row = remaining.remove(idx);
263                    placed.push(row.id.as_str());
264                    ordered.push(row);
265                }
266
267                lines.push(format!(
268                    "Closed (at `{to_value}`): {}",
269                    if closed.is_empty() {
270                        "none".to_string()
271                    } else {
272                        closed
273                            .iter()
274                            .map(|id| format!("`{id}`"))
275                            .collect::<Vec<_>>()
276                            .join(", ")
277                    }
278                ));
279                lines.push(String::new());
280                if ordered.is_empty() {
281                    lines.push("Open: none — every gated entity stands closed.".to_string());
282                } else {
283                    lines.push("Open, in dependency order (prerequisites first):".to_string());
284                    for row in &ordered {
285                        let coverage = if row.total == 0 {
286                            "no related entities — the gate is vacuously satisfiable".to_string()
287                        } else if row.unchecked.is_empty() {
288                            format!(
289                                "{}/{} related confirmed — gate satisfiable",
290                                row.total, row.total
291                            )
292                        } else {
293                            format!(
294                                "{}/{} related confirmed — unconfirmed: {}",
295                                row.total - row.unchecked.len(),
296                                row.total,
297                                row.unchecked
298                                    .iter()
299                                    .map(|u| format!("`{}` ({})", u.id, u.state))
300                                    .collect::<Vec<_>>()
301                                    .join(", ")
302                            )
303                        };
304                        lines.push(format!(
305                            "- `{}` — {field}: {} — {coverage}",
306                            row.id,
307                            if row.value.is_empty() {
308                                "(unset)"
309                            } else {
310                                row.value.as_str()
311                            },
312                        ));
313                    }
314                }
315                lines.push(String::new());
316            }
317            sections.push(lines.join("\n"));
318        }
319
320        let mut out = String::from("# Gates brief\n\n");
321        if declaring_mems.is_empty() {
322            out.push_str(match mem_filter {
323                Some(f) => {
324                    sections.push(format!(
325                        "No gated transition (`transition_requires_checks` or \
326                         `transition_requires_self_check`) declared by the schema of `{f}` (or \
327                         the mem is not mounted)."
328                    ));
329                    ""
330                }
331                None => {
332                    "No mounted mem's schema declares a gated transition \
333                     (`transition_requires_checks` or `transition_requires_self_check`)."
334                }
335            });
336        }
337        out.push_str(&sections.join("\n"));
338        if !out.ends_with('\n') {
339            out.push('\n');
340        }
341        out
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    /// A workspace with no gate-declaring schema renders the honest
348    /// empty brief — never an empty string, never an invented section.
349    /// The substantive standing logic is covered by
350    /// `ops::health::tests::transition_requires_checks_gates_on_derived_state`
351    /// (shared enumeration), and the rendered shape by this project's
352    /// own live workspace.
353    #[test]
354    fn brief_names_the_no_gates_case() {
355        let tmp = tempfile::TempDir::new().unwrap();
356        let dir = tmp.path().join("plain");
357        std::fs::create_dir_all(&dir).unwrap();
358        let engine = crate::Engine::from_mounts(vec![(
359            crate::engine::test_helpers::folder_mount("plain", dir.clone()),
360            Box::new(crate::storage::FilesystemBackend::new(dir))
361                as Box<dyn crate::backend::MemBackend>,
362        )])
363        .unwrap();
364        let brief = engine.render_gates_brief(None);
365        assert!(
366            brief.contains("No mounted mem's schema declares"),
367            "{brief}"
368        );
369        let filtered = engine.render_gates_brief(Some("plain"));
370        assert!(filtered.contains("No gated transition"), "{filtered}");
371    }
372}