forjar 1.4.2

Rust-native Infrastructure as Code — bare-metal first, BLAKE3 state, provenance tracing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Graph intelligence extensions — fan-out, fan-in, path count, articulation points.

#[allow(unused_imports)]
use crate::core::{codegen, executor, migrate, parser, planner, resolver, secrets, state, types};
use std::path::Path;

/// FJ-943: Maximum outgoing edges per node (fan-out bottleneck).
pub(crate) fn cmd_graph_resource_dependency_fan_out(file: &Path, json: bool) -> Result<(), String> {
    let content = std::fs::read_to_string(file).map_err(|e| e.to_string())?;
    let config: types::ForjarConfig =
        serde_yaml_ng::from_str(&content).map_err(|e| e.to_string())?;
    let mut fan_outs: Vec<(String, usize)> = config
        .resources
        .iter()
        .map(|(name, res)| (name.clone(), res.depends_on.len()))
        .collect();
    fan_outs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    let max = fan_outs.first().map(|(_, c)| *c).unwrap_or(0);
    if json {
        let items: Vec<String> = fan_outs
            .iter()
            .map(|(n, c)| format!("{{\"resource\":\"{n}\",\"fan_out\":{c}}}"))
            .collect();
        println!(
            "{{\"max_fan_out\":{},\"resources\":[{}]}}",
            max,
            items.join(",")
        );
    } else if fan_outs.is_empty() {
        println!("No resources found.");
    } else {
        println!("Fan-out analysis (max: {max}):");
        for (n, c) in &fan_outs {
            println!("  {n}{c} outgoing");
        }
    }
    Ok(())
}
/// FJ-947: Maximum incoming edges per node (convergence point).
pub(crate) fn cmd_graph_resource_dependency_fan_in(file: &Path, json: bool) -> Result<(), String> {
    let content = std::fs::read_to_string(file).map_err(|e| e.to_string())?;
    let config: types::ForjarConfig =
        serde_yaml_ng::from_str(&content).map_err(|e| e.to_string())?;
    let mut in_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for name in config.resources.keys() {
        in_counts.insert(name.clone(), 0);
    }
    for res in config.resources.values() {
        for dep in &res.depends_on {
            *in_counts.entry(dep.clone()).or_insert(0) += 1;
        }
    }
    let mut fan_ins: Vec<(String, usize)> = in_counts.into_iter().collect();
    fan_ins.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    let max = fan_ins.first().map(|(_, c)| *c).unwrap_or(0);
    if json {
        let items: Vec<String> = fan_ins
            .iter()
            .map(|(n, c)| format!("{{\"resource\":\"{n}\",\"fan_in\":{c}}}"))
            .collect();
        println!(
            "{{\"max_fan_in\":{},\"resources\":[{}]}}",
            max,
            items.join(",")
        );
    } else if fan_ins.is_empty() {
        println!("No resources found.");
    } else {
        println!("Fan-in analysis (max: {max}):");
        for (n, c) in &fan_ins {
            println!("  {n}{c} incoming");
        }
    }
    Ok(())
}
/// FJ-951: Count of distinct dependency paths between all pairs.
pub(crate) fn cmd_graph_resource_dependency_path_count(
    file: &Path,
    json: bool,
) -> Result<(), String> {
    let content = std::fs::read_to_string(file).map_err(|e| e.to_string())?;
    let config: types::ForjarConfig =
        serde_yaml_ng::from_str(&content).map_err(|e| e.to_string())?;
    let names: Vec<&String> = config.resources.keys().collect();
    let n = names.len();
    let mut total_paths = 0usize;
    for i in 0..n {
        for j in 0..n {
            if i != j {
                total_paths += count_paths_between(&config, names[i], names[j]);
            }
        }
    }
    if json {
        println!("{{\"total_dependency_paths\":{total_paths},\"nodes\":{n}}}");
    } else {
        println!("Total dependency paths: {total_paths} ({n} nodes)");
    }
    Ok(())
}
pub(super) fn count_paths_between(config: &types::ForjarConfig, from: &str, to: &str) -> usize {
    if from == to {
        return 1;
    }
    let res = match config.resources.get(from) {
        Some(r) => r,
        None => return 0,
    };
    let mut count = 0;
    for dep in &res.depends_on {
        count += count_paths_between(config, dep, to);
    }
    count
}

/// FJ-955: Identify articulation points whose removal disconnects graph.
pub(crate) fn cmd_graph_resource_dependency_articulation_points(
    file: &Path,
    json: bool,
) -> Result<(), String> {
    let content = std::fs::read_to_string(file).map_err(|e| e.to_string())?;
    let config: types::ForjarConfig =
        serde_yaml_ng::from_str(&content).map_err(|e| e.to_string())?;
    let names: Vec<String> = config.resources.keys().cloned().collect();
    let n = names.len();
    let mut points = Vec::new();
    let base_components = count_components_undirected(&config, &names, None);
    for i in 0..n {
        let removed = count_components_undirected(&config, &names, Some(&names[i]));
        if removed > base_components {
            points.push(names[i].clone());
        }
    }
    points.sort();
    if json {
        let items: Vec<String> = points.iter().map(|p| format!("\"{p}\"")).collect();
        println!("{{\"articulation_points\":[{}]}}", items.join(","));
    } else if points.is_empty() {
        println!("No articulation points found.");
    } else {
        println!("Articulation points:");
        for p in &points {
            println!("  {p}");
        }
    }
    Ok(())
}

pub(super) fn count_components_undirected(
    config: &types::ForjarConfig,
    names: &[String],
    exclude: Option<&str>,
) -> usize {
    let active: Vec<&String> = names
        .iter()
        .filter(|n| exclude != Some(n.as_str()))
        .collect();
    let mut visited = std::collections::HashSet::new();
    let mut components = 0;
    for name in &active {
        if visited.contains(name.as_str()) {
            continue;
        }
        components += 1;
        flood_fill_component(config, name, exclude, &mut visited);
    }
    components
}

pub(super) fn flood_fill_component<'a>(
    config: &'a types::ForjarConfig,
    start: &'a str,
    exclude: Option<&str>,
    visited: &mut std::collections::HashSet<&'a str>,
) {
    let mut stack = vec![start];
    while let Some(v) = stack.pop() {
        if visited.contains(v) {
            continue;
        }
        visited.insert(v);
        push_forward_neighbors(config, v, exclude, visited, &mut stack);
        push_reverse_neighbors(config, v, exclude, visited, &mut stack);
    }
}

pub(super) fn push_forward_neighbors<'a>(
    config: &'a types::ForjarConfig,
    v: &str,
    exclude: Option<&str>,
    visited: &std::collections::HashSet<&str>,
    stack: &mut Vec<&'a str>,
) {
    if let Some(res) = config.resources.get(v) {
        for dep in &res.depends_on {
            if exclude != Some(dep.as_str()) && !visited.contains(dep.as_str()) {
                stack.push(dep);
            }
        }
    }
}

pub(super) fn push_reverse_neighbors<'a>(
    config: &'a types::ForjarConfig,
    v: &str,
    exclude: Option<&str>,
    visited: &std::collections::HashSet<&str>,
    stack: &mut Vec<&'a str>,
) {
    for (other_name, other_res) in &config.resources {
        if exclude != Some(other_name.as_str())
            && other_res.depends_on.contains(&v.to_string())
            && !visited.contains(other_name.as_str())
        {
            stack.push(other_name);
        }
    }
}

/// FJ-959: Longest dependency path in the DAG (critical chain).
pub(crate) fn cmd_graph_resource_dependency_longest_path(
    file: &Path,
    json: bool,
) -> Result<(), String> {
    let content = std::fs::read_to_string(file).map_err(|e| e.to_string())?;
    let config: types::ForjarConfig =
        serde_yaml_ng::from_str(&content).map_err(|e| e.to_string())?;
    let names: Vec<String> = config.resources.keys().cloned().collect();
    let mut longest = 0usize;
    let mut longest_path: Vec<String> = Vec::new();
    for name in &names {
        let mut path = Vec::new();
        let depth = dag_longest_from(&config, name, &mut path);
        if depth > longest {
            longest = depth;
            longest_path = path;
        }
    }
    if json {
        let path_items: Vec<String> = longest_path.iter().map(|p| format!("\"{p}\"")).collect();
        println!(
            "{{\"longest_path_length\":{},\"path\":[{}]}}",
            longest,
            path_items.join(",")
        );
    } else if longest == 0 {
        println!("No dependency paths found.");
    } else {
        println!("Longest dependency path ({longest} hops):");
        println!("  {}", longest_path.join(""));
    }
    Ok(())
}

pub(super) fn dag_longest_from(
    config: &types::ForjarConfig,
    node: &str,
    path: &mut Vec<String>,
) -> usize {
    path.push(node.to_string());
    let res = match config.resources.get(node) {
        Some(r) => r,
        None => return 0,
    };
    if res.depends_on.is_empty() {
        return 0;
    }
    let mut max_depth = 0;
    let mut best_path = Vec::new();
    for dep in &res.depends_on {
        let mut sub_path = Vec::new();
        let d = dag_longest_from(config, dep, &mut sub_path);
        if d + 1 > max_depth {
            max_depth = d + 1;
            best_path = sub_path;
        }
    }
    path.extend(best_path);
    max_depth
}

/// FJ-963: Find strongly connected components in dependency graph.
pub(crate) fn cmd_graph_resource_dependency_strongly_connected(
    file: &Path,
    json: bool,
) -> Result<(), String> {
    let content = std::fs::read_to_string(file).map_err(|e| e.to_string())?;
    let config: types::ForjarConfig =
        serde_yaml_ng::from_str(&content).map_err(|e| e.to_string())?;
    let names: Vec<String> = config.resources.keys().cloned().collect();
    let sccs = tarjan_scc(&config, &names);
    let non_trivial: Vec<&Vec<String>> = sccs.iter().filter(|c| c.len() > 1).collect();
    if json {
        let items: Vec<String> = non_trivial
            .iter()
            .map(|c| {
                let members: Vec<String> = c.iter().map(|n| format!("\"{n}\"")).collect();
                format!("[{}]", members.join(","))
            })
            .collect();
        println!(
            "{{\"strongly_connected_components\":[{}],\"count\":{}}}",
            items.join(","),
            non_trivial.len()
        );
    } else if non_trivial.is_empty() {
        println!("No strongly connected components found (DAG is acyclic).");
    } else {
        println!("Strongly connected components:");
        for (i, c) in non_trivial.iter().enumerate() {
            println!("  SCC {}: {}", i + 1, c.join(", "));
        }
    }
    Ok(())
}

pub(super) fn tarjan_scc(config: &types::ForjarConfig, names: &[String]) -> Vec<Vec<String>> {
    let n = names.len();
    let idx_map: std::collections::HashMap<&str, usize> = names
        .iter()
        .enumerate()
        .map(|(i, n)| (n.as_str(), i))
        .collect();
    let mut index_counter = 0usize;
    let mut stack = Vec::new();
    let mut on_stack = vec![false; n];
    let mut indices = vec![usize::MAX; n];
    let mut lowlinks = vec![0usize; n];
    let mut result = Vec::new();

    #[allow(clippy::too_many_arguments)]
    fn strongconnect(
        v: usize,
        config: &types::ForjarConfig,
        names: &[String],
        idx_map: &std::collections::HashMap<&str, usize>,
        index_counter: &mut usize,
        stack: &mut Vec<usize>,
        on_stack: &mut [bool],
        indices: &mut [usize],
        lowlinks: &mut [usize],
        result: &mut Vec<Vec<String>>,
    ) {
        indices[v] = *index_counter;
        lowlinks[v] = *index_counter;
        *index_counter += 1;
        stack.push(v);
        on_stack[v] = true;

        if let Some(res) = config.resources.get(&names[v]) {
            for dep in &res.depends_on {
                if let Some(&w) = idx_map.get(dep.as_str()) {
                    if indices[w] == usize::MAX {
                        strongconnect(
                            w,
                            config,
                            names,
                            idx_map,
                            index_counter,
                            stack,
                            on_stack,
                            indices,
                            lowlinks,
                            result,
                        );
                        lowlinks[v] = lowlinks[v].min(lowlinks[w]);
                    } else if on_stack[w] {
                        lowlinks[v] = lowlinks[v].min(indices[w]);
                    }
                }
            }
        }

        if lowlinks[v] == indices[v] {
            let mut component = Vec::new();
            while let Some(w) = stack.pop() {
                on_stack[w] = false;
                component.push(names[w].clone());
                if w == v {
                    break;
                }
            }
            component.sort();
            result.push(component);
        }
    }

    for i in 0..n {
        if indices[i] == usize::MAX {
            strongconnect(
                i,
                config,
                names,
                &idx_map,
                &mut index_counter,
                &mut stack,
                &mut on_stack,
                &mut indices,
                &mut lowlinks,
                &mut result,
            );
        }
    }
    result
}

pub(super) use super::graph_intelligence_ext_b::*;