memstead_base/engine/gates.rs
1//! The gates brief — the engine-rendered standing of every declared
2//! `transition_requires_checks` gate (graph-plans plan 03, the yes
3//! branch of the gated-transition spike).
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!(c, ConstraintDef::TransitionRequiresChecks { .. }) {
64 gated.push((td.name.as_str(), c));
65 }
66 }
67 }
68 if gated.is_empty() {
69 continue;
70 }
71 gated.sort_by_key(|(name, _)| *name);
72 declaring_mems.push(mem.to_string());
73
74 let mut lines: Vec<String> = Vec::new();
75 lines.push(format!("## {mem}"));
76 lines.push(String::new());
77
78 for (type_name, c) in &gated {
79 let ConstraintDef::TransitionRequiresChecks {
80 field,
81 to_value,
82 relationships,
83 direction,
84 min_related,
85 ..
86 } = c
87 else {
88 continue;
89 };
90 let floor = if *min_related > 0 {
91 format!(
92 ", and at least {min_related} such entit{}",
93 if *min_related == 1 { "y" } else { "ies" }
94 )
95 } else {
96 String::new()
97 };
98 lines.push(format!(
99 "Gate: `{type_name}` — `{field}: {to_value}` requires a fresh confirming \
100 check record on every entity related via [{}] ({}){floor}.",
101 relationships.join(", "),
102 match direction {
103 memstead_schema::PropagationDirection::Incoming => "incoming",
104 memstead_schema::PropagationDirection::Outgoing => "outgoing",
105 },
106 ));
107 lines.push(String::new());
108
109 // Every non-stub entity of the gated type.
110 let entities: Vec<_> = self
111 .store
112 .all_entities()
113 .filter(|e| e.mem == mem && !e.stub && e.entity_type == *type_name)
114 .collect();
115 let mut closed: Vec<String> = Vec::new();
116 struct OpenRow {
117 id: String,
118 value: String,
119 total: usize,
120 unchecked: Vec<crate::ops::health::UncheckedRelated>,
121 }
122 let mut open: Vec<OpenRow> = Vec::new();
123 for e in &entities {
124 let value = match e.metadata.get(field.as_str()) {
125 Some(MetadataValue::String(s)) => s.clone(),
126 Some(v) => v.to_frontmatter_string(),
127 None => String::new(),
128 };
129 if value == *to_value {
130 closed.push(e.id.0.clone());
131 } else {
132 let (total, unchecked) = crate::ops::health::transition_gate_standing(
133 &self.store,
134 e,
135 relationships,
136 *direction,
137 None,
138 Some(&checks),
139 );
140 open.push(OpenRow {
141 id: e.id.0.clone(),
142 value,
143 total,
144 unchecked,
145 });
146 }
147 }
148 closed.sort();
149
150 // Dependency order over acyclic edges between gated
151 // entities: an edge source depends on its target, so
152 // targets (prerequisites) list first.
153 let acyclic: Vec<&str> = schema
154 .manifest
155 .relationships
156 .definitions
157 .iter()
158 .filter(|r| r.acyclic)
159 .map(|r| r.name.as_str())
160 .collect();
161 let open_ids: Vec<String> = open.iter().map(|r| r.id.clone()).collect();
162 let mut prereqs: HashMap<String, Vec<String>> = HashMap::new();
163 for e in &entities {
164 if !open_ids.contains(&e.id.0) {
165 continue;
166 }
167 for rel in &e.relationships {
168 if acyclic.contains(&rel.rel_type.as_str())
169 && open_ids.contains(&rel.target.0)
170 && rel.target.0 != e.id.0
171 {
172 prereqs
173 .entry(e.id.0.clone())
174 .or_default()
175 .push(rel.target.0.clone());
176 }
177 }
178 }
179 let mut ordered: Vec<&OpenRow> = Vec::new();
180 let mut placed: Vec<&str> = Vec::new();
181 let mut remaining: Vec<&OpenRow> = open.iter().collect();
182 remaining.sort_by(|a, b| a.id.cmp(&b.id));
183 while !remaining.is_empty() {
184 let idx = remaining.iter().position(|r| {
185 prereqs
186 .get(&r.id)
187 .is_none_or(|p| p.iter().all(|d| placed.contains(&d.as_str())))
188 });
189 // A cycle among open entities cannot arise (the
190 // edges are engine-enforced acyclic); the fallback
191 // keeps the loop total anyway.
192 let idx = idx.unwrap_or(0);
193 let row = remaining.remove(idx);
194 placed.push(row.id.as_str());
195 ordered.push(row);
196 }
197
198 lines.push(format!(
199 "Closed (at `{to_value}`): {}",
200 if closed.is_empty() {
201 "none".to_string()
202 } else {
203 closed
204 .iter()
205 .map(|id| format!("`{id}`"))
206 .collect::<Vec<_>>()
207 .join(", ")
208 }
209 ));
210 lines.push(String::new());
211 if ordered.is_empty() {
212 lines.push("Open: none — every gated entity stands closed.".to_string());
213 } else {
214 lines.push("Open, in dependency order (prerequisites first):".to_string());
215 for row in &ordered {
216 let coverage = if row.total == 0 {
217 "no related entities — the gate is vacuously satisfiable".to_string()
218 } else if row.unchecked.is_empty() {
219 format!(
220 "{}/{} related confirmed — gate satisfiable",
221 row.total, row.total
222 )
223 } else {
224 format!(
225 "{}/{} related confirmed — unconfirmed: {}",
226 row.total - row.unchecked.len(),
227 row.total,
228 row.unchecked
229 .iter()
230 .map(|u| format!("`{}` ({})", u.id, u.state))
231 .collect::<Vec<_>>()
232 .join(", ")
233 )
234 };
235 lines.push(format!(
236 "- `{}` — {field}: {} — {coverage}",
237 row.id,
238 if row.value.is_empty() {
239 "(unset)"
240 } else {
241 row.value.as_str()
242 },
243 ));
244 }
245 }
246 lines.push(String::new());
247 }
248 sections.push(lines.join("\n"));
249 }
250
251 let mut out = String::from("# Gates brief\n\n");
252 if declaring_mems.is_empty() {
253 out.push_str(match mem_filter {
254 Some(f) => {
255 sections.push(format!(
256 "No `transition_requires_checks` gate declared by the schema of `{f}` \
257 (or the mem is not mounted)."
258 ));
259 ""
260 }
261 None => "No mounted mem's schema declares a `transition_requires_checks` gate.",
262 });
263 }
264 out.push_str(§ions.join("\n"));
265 if !out.ends_with('\n') {
266 out.push('\n');
267 }
268 out
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 /// A workspace with no gate-declaring schema renders the honest
275 /// empty brief — never an empty string, never an invented section.
276 /// The substantive standing logic is covered by
277 /// `ops::health::tests::transition_requires_checks_gates_on_derived_state`
278 /// (shared enumeration), and the rendered shape by this project's
279 /// own live workspace.
280 #[test]
281 fn brief_names_the_no_gates_case() {
282 let tmp = tempfile::TempDir::new().unwrap();
283 let dir = tmp.path().join("plain");
284 std::fs::create_dir_all(&dir).unwrap();
285 let engine = crate::Engine::from_mounts(vec![(
286 crate::engine::test_helpers::folder_mount("plain", dir.clone()),
287 Box::new(crate::storage::FilesystemBackend::new(dir))
288 as Box<dyn crate::backend::MemBackend>,
289 )])
290 .unwrap();
291 let brief = engine.render_gates_brief(None);
292 assert!(
293 brief.contains("No mounted mem's schema declares"),
294 "{brief}"
295 );
296 let filtered = engine.render_gates_brief(Some("plain"));
297 assert!(
298 filtered.contains("No `transition_requires_checks` gate declared"),
299 "{filtered}"
300 );
301 }
302}