1use serde_json::{json, Value};
5
6use crate::load::{load, LoadError};
7use crate::model::{Graph, Node};
8use crate::rules::{evaluate, unmatched_rules, Evaluation, Status};
9use crate::structure::{self, Finding, Structure};
10
11pub struct Report {
13 pub graph: Graph,
15 pub load_errors: Vec<LoadError>,
17 pub structure: Structure,
19 pub evaluation: Evaluation,
21}
22
23pub fn check(files: Vec<(String, String)>) -> Report {
25 let (graph, load_errors) = load(files);
26 let mut structure = structure::check(&graph);
27 for id in unmatched_rules(&graph) {
28 structure.warnings.push(Finding { node: id, kind: "rule_matches_nothing", reference: None });
29 }
30 structure.warnings.sort_by_key(|f| (f.node.clone(), f.kind, f.reference.clone().unwrap_or_default()));
31 let evaluation = evaluate(&graph);
32 Report { graph, load_errors, structure, evaluation }
33}
34
35pub fn node_to_json(n: &Node) -> Value {
37 let links: Vec<Value> = n
38 .links
39 .iter()
40 .map(|l| {
41 let mut m = json!({"type": l.kind, "to": l.to});
42 if let Some(k) = &l.key {
43 m["key"] = json!(k);
44 }
45 if !l.fields.is_empty() {
46 m["fields"] = json!(l.fields);
47 }
48 m
49 })
50 .collect();
51 json!({"id": n.id, "type": n.kind, "title": n.title, "parent": n.parent, "plane": n.plane,
52 "fields": n.fields, "links": links, "body": n.body})
53}
54
55fn findings_to_json(list: &[Finding]) -> Value {
56 Value::Array(list.iter().map(|f| json!({"node": f.node, "kind": f.kind, "ref": f.reference})).collect())
57}
58
59impl Report {
60 pub fn to_json(&self) -> Value {
62 json!({
63 "load_errors": self.load_errors.iter().map(|e| json!({"file": e.file, "kind": e.kind})).collect::<Vec<_>>(),
64 "nodes": self.graph.nodes().map(node_to_json).collect::<Vec<_>>(),
65 "structure": {
66 "errors": findings_to_json(&self.structure.errors),
67 "warnings": findings_to_json(&self.structure.warnings),
68 },
69 "results": self.evaluation.results.iter().map(|r| json!({
70 "node": r.node, "rule": r.rule, "severity": r.severity, "status": r.status.as_str()
71 })).collect::<Vec<_>>(),
72 "ghosts": self.evaluation.ghosts.iter().map(|g| json!({
73 "node": g.node, "rule": g.rule, "link": g.link, "to_type": g.to_type, "plane": g.plane
74 })).collect::<Vec<_>>(),
75 })
76 }
77
78 pub fn exit_code(&self) -> i32 {
80 let failed_error_rule = self.evaluation.results.iter().any(|r| r.status == Status::Fail && r.severity == "error");
81 i32::from(!self.load_errors.is_empty() || !self.structure.errors.is_empty() || failed_error_rule)
82 }
83
84 pub fn human(&self) -> String {
86 let mut out = String::new();
87 let line = |out: &mut String, s: String| {
88 out.push_str(&s);
89 out.push('\n');
90 };
91 for e in &self.load_errors {
92 line(&mut out, format!("ERROR {}: {}", e.file, e.kind));
93 }
94 for f in &self.structure.errors {
95 line(&mut out, format!("ERROR {}: {} {}", f.node, f.kind, f.reference.as_deref().unwrap_or("")).trim_end().to_string());
96 }
97 for f in &self.structure.warnings {
98 line(&mut out, format!("warn {}: {} {}", f.node, f.kind, f.reference.as_deref().unwrap_or("")).trim_end().to_string());
99 }
100 for r in self.evaluation.results.iter().filter(|r| r.status == Status::Fail) {
101 line(&mut out, format!("{:<6} {}: fails {}", r.severity, r.node, r.rule));
102 }
103 line(
104 &mut out,
105 format!(
106 "{} nodes, {} load errors, {} errors, {} warnings",
107 self.graph.len(),
108 self.load_errors.len(),
109 self.structure.errors.len(),
110 self.structure.warnings.len()
111 ),
112 );
113 out
114 }
115
116 pub fn show(&self, id: &str) -> Option<String> {
118 let n = self.graph.get(id)?;
119 let mut out = format!("{} ({})\n", n.title, n.kind.as_deref().unwrap_or("?"));
120 out.push_str(&format!("id: {}\n", n.id));
121 if let Some(p) = &n.parent {
122 out.push_str(&format!("parent: {p}\n"));
123 }
124 if let Some(p) = &n.plane {
125 out.push_str(&format!("plane: {p}\n"));
126 }
127 if !n.fields.is_empty() {
128 out.push_str("fields:\n");
129 for (k, v) in &n.fields {
130 out.push_str(&format!(" {k}: {v}\n"));
131 }
132 }
133 if !n.links.is_empty() {
134 out.push_str("links out:\n");
135 for l in &n.links {
136 let key = l.key.as_deref().map(|k| format!("#{k}")).unwrap_or_default();
137 out.push_str(&format!(" {} -> {}{}\n", l.kind, l.to, key));
138 }
139 }
140 let inbound: Vec<String> = self
142 .graph
143 .nodes()
144 .flat_map(|o| o.links.iter().filter(|l| l.to == id).map(move |l| format!(" {} <- {}\n", l.kind, o.id)))
145 .collect();
146 if !inbound.is_empty() {
147 out.push_str("links in:\n");
148 inbound.iter().for_each(|s| out.push_str(s));
149 }
150 let results: Vec<_> = self.evaluation.results.iter().filter(|r| r.node == id).collect();
151 if !results.is_empty() {
152 out.push_str("rules:\n");
153 for r in results {
154 out.push_str(&format!(" {} {} ({})\n", r.status.as_str(), r.rule, r.severity));
155 }
156 }
157 if !n.body.is_empty() {
158 out.push_str(&format!("\n{}\n", n.body));
159 }
160 Some(out)
161 }
162}
163
164fn many(n: usize, word: &str) -> String {
165 format!("{n} {word}{}", if n == 1 { "" } else { "s" })
166}
167
168impl Report {
169 pub fn index(&self) -> String {
173 use std::collections::BTreeMap;
174 let nodes: Vec<&Node> = self.graph.nodes().collect();
175 let kind = |n: &Node| n.kind.clone().unwrap_or_else(|| "(no type)".to_string());
176 let fails = |id: &str| self.evaluation.results.iter().filter(|r| r.node == id && r.status == Status::Fail).count();
177 let is = |n: &Node, k: &str| n.kind.as_deref() == Some(k);
178
179 let mut planes: Vec<&Node> = nodes.iter().copied().filter(|n| is(n, "plane")).collect();
181 planes.sort_by(|a, b| {
182 let o = |n: &Node| n.fields.get("order").and_then(Value::as_f64).unwrap_or(f64::MAX);
183 o(a).partial_cmp(&o(b)).unwrap_or(std::cmp::Ordering::Equal).then(a.id.cmp(&b.id))
184 });
185 let groups: Vec<&Node> = nodes.iter().copied().filter(|n| is(n, "group")).collect();
186 let rules: Vec<&Node> = nodes.iter().copied().filter(|n| is(n, "rule")).collect();
187 let content: Vec<&Node> = nodes.iter().copied().filter(|n| !["plane", "group", "rule", "type", "link-type", "pack"].iter().any(|k| is(n, k))).collect();
188 let failing: usize = self.evaluation.results.iter().filter(|r| r.status == Status::Fail).count();
189
190 let mut out = String::from("# Model index\n\n");
191 out.push_str(&format!(
192 "{} nodes: {} on {}, {}, {}. {} failing checks, {}, {}, {}.\n",
193 self.graph.len(), content.len(), many(planes.len(), "plane"), many(groups.len(), "group"), many(rules.len(), "rule"),
194 failing, many(self.structure.errors.len(), "structure error"), many(self.structure.warnings.len(), "warning"), many(self.load_errors.len(), "load error")
195 ));
196 out.push_str("Generated by `trumly index`; do not edit. Open a node with `trumly show ID` or the MCP `get_node` tool.\n");
197
198 out.push_str("\n## Planes\n\n");
199 for (i, p) in planes.iter().enumerate() {
200 let n = content.iter().filter(|c| c.plane.as_deref() == Some(p.id.as_str())).count();
201 out.push_str(&format!("{}. `{}` {}: {}\n", i + 1, p.id, p.title, many(n, "node")));
202 }
203 if planes.is_empty() {
204 out.push_str("None declared.\n");
205 }
206
207 if !groups.is_empty() {
208 out.push_str("\n## Groups\n\n");
209 let ids: std::collections::BTreeSet<&str> = groups.iter().map(|g| g.id.as_str()).collect();
210 fn walk(out: &mut String, groups: &[&Node], nodes: &[&Node], ids: &std::collections::BTreeSet<&str>, parent: Option<&str>, depth: usize) {
211 for g in groups.iter().filter(|g| match g.parent.as_deref() { Some(p) if ids.contains(p) => Some(p) == parent, _ => parent.is_none() }) {
212 let members = nodes.iter().filter(|n| n.parent.as_deref() == Some(g.id.as_str())).count();
213 out.push_str(&format!("{}- `{}` {} ({})\n", " ".repeat(depth), g.id, g.title, many(members, "member")));
214 if depth < 8 {
215 walk(out, groups, nodes, ids, Some(&g.id), depth + 1);
216 }
217 }
218 }
219 walk(&mut out, &groups, &nodes, &ids, None, 0);
220 }
221
222 let packs: Vec<&Node> = nodes.iter().copied().filter(|n| is(n, "pack")).collect();
223 if !packs.is_empty() {
224 out.push_str("\n## Packs\n\n");
225 for p in &packs {
226 let f = |k: &str| p.fields.get(k).and_then(Value::as_str).unwrap_or("");
227 out.push_str(&format!("- `{}` {}: {}\n", f("name"), f("version"), f("description")));
228 }
229 }
230
231 out.push_str("\n## Nodes\n");
232 let section = |out: &mut String, heading: &str, list: Vec<&Node>| {
233 if list.is_empty() {
234 return;
235 }
236 out.push_str(&format!("\n### {} ({})\n", heading, list.len()));
237 let mut by_type: BTreeMap<String, Vec<&Node>> = BTreeMap::new();
238 for n in list {
239 by_type.entry(kind(n)).or_default().push(n);
240 }
241 for (t, ns) in by_type {
242 out.push_str(&format!("\n**{}** ({})\n", t, ns.len()));
243 for n in ns {
244 let mut line = format!("- `{}` {}", n.id, n.title);
245 if let Some(p) = &n.parent {
246 line.push_str(&format!(" [in {p}]"));
247 }
248 let f = fails(&n.id);
249 if f > 0 {
250 line.push_str(&format!(" ({f} failing)"));
251 }
252 out.push_str(&line);
253 out.push('\n');
254 }
255 }
256 };
257 for p in &planes {
258 section(&mut out, &format!("{}, plane `{}`", p.title, p.id), content.iter().copied().filter(|c| c.plane.as_deref() == Some(p.id.as_str())).collect());
259 }
260 let known: std::collections::BTreeSet<&str> = planes.iter().map(|p| p.id.as_str()).collect();
261 section(&mut out, "Not on a plane", content.iter().copied().filter(|c| c.plane.as_deref().is_none_or(|p| !known.contains(p))).collect());
262
263 if !rules.is_empty() {
264 out.push_str("\n## Rules\n\n");
265 for r in &rules {
266 let on = r.fields.get("enabled").and_then(Value::as_bool) != Some(false);
267 let sev = r.fields.get("severity").and_then(Value::as_str).unwrap_or("warn");
268 let failed = self.evaluation.results.iter().filter(|x| x.rule == r.id && x.status == Status::Fail).count();
269 let state = if on { format!("{failed} failing") } else { "off".to_string() };
270 out.push_str(&format!("- `{}` {} ({}, {})\n", r.id, r.fields.get("statement").and_then(Value::as_str).unwrap_or(&r.title), sev, state));
271 }
272 }
273
274 let mut problems = String::new();
275 for e in &self.load_errors {
276 problems.push_str(&format!("- load error {}: {}\n", e.file, e.kind));
277 }
278 for f in &self.structure.errors {
279 problems.push_str(&format!("- error `{}`: {} {}\n", f.node, f.kind, f.reference.as_deref().unwrap_or("")).replace(" \n", "\n"));
280 }
281 for f in &self.structure.warnings {
282 problems.push_str(&format!("- warning `{}`: {} {}\n", f.node, f.kind, f.reference.as_deref().unwrap_or("")).replace(" \n", "\n"));
283 }
284 for r in self.evaluation.results.iter().filter(|r| r.status == Status::Fail) {
285 problems.push_str(&format!("- {} `{}` fails `{}`\n", r.severity, r.node, r.rule));
286 }
287 if !problems.is_empty() {
288 out.push_str("\n## Findings\n\n");
289 out.push_str(&problems);
290 }
291 out
292 }
293}
294
295#[cfg(test)]
296mod index_tests {
297 use super::*;
298
299 fn file(path: &str, text: &str) -> (String, String) {
300 (path.to_string(), text.to_string())
301 }
302
303 #[test]
304 fn index_lists_planes_groups_nodes_and_findings() {
305 let report = check(vec![
306 file("build.md", "---\nid: build\ntype: plane\ntitle: Build\nfields: { order: 2 }\n---\n"),
307 file("intent.md", "---\nid: intent\ntype: plane\ntitle: Intent\nfields: { order: 1 }\n---\n"),
308 file("group-app.md", "---\nid: group-app\ntype: group\ntitle: App\n---\n"),
309 file("component-api.md", "---\nid: component-api\ntype: component\ntitle: API\nplane: build\nparent: group-app\n---\n"),
310 file("rule-x.md", "---\nid: rule-x\ntype: rule\ntitle: x\nfields:\n statement: Components need a note\n severity: warn\n applies_to: { type: component }\n check: { require_fields: [note] }\n---\n"),
311 ]);
312 let text = report.index();
313 assert!(text.contains("1. `intent`"), "planes in declared order:\n{text}");
314 assert!(text.contains("2. `build`"));
315 assert!(text.contains("- `group-app` App (1 member)"));
316 assert!(text.contains("- `component-api` API [in group-app] (1 failing)"));
317 assert!(text.contains("- `rule-x` Components need a note (warn, 1 failing)"));
318 assert!(text.contains("warn `component-api` fails `rule-x`"));
319 assert!(text.find("1. `intent`") < text.find("2. `build`"));
320 }
321}