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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Status predictive — age distribution, convergence velocity, failure correlation, churn, staleness, trends.

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

/// FJ-854: Age distribution of resources per machine.
pub(crate) fn cmd_status_machine_resource_age_distribution(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let dist = collect_age_distribution(state_dir, &targets);
    if json {
        let items: Vec<String> = dist
            .iter()
            .map(|(m, with, without)| {
                format!(
                    "{{\"machine\":\"{m}\",\"with_timestamp\":{with},\"without_timestamp\":{without}}}"
                )
            })
            .collect();
        println!("{{\"resource_age_distribution\":[{}]}}", items.join(","));
    } else if dist.is_empty() {
        println!("No age distribution data available.");
    } else {
        println!("Resource age distribution per machine:");
        for (m, with, without) in &dist {
            println!("  {m}{with} with timestamp, {without} without");
        }
    }
    Ok(())
}

fn collect_age_distribution(state_dir: &Path, targets: &[&String]) -> Vec<(String, usize, usize)> {
    let mut results = Vec::new();
    for m in targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        let with_ts = lock
            .resources
            .values()
            .filter(|r| r.applied_at.is_some())
            .count();
        let without_ts = lock
            .resources
            .values()
            .filter(|r| r.applied_at.is_none())
            .count();
        results.push((m.to_string(), with_ts, without_ts));
    }
    results.sort();
    results
}

/// FJ-858: Rate of convergence across fleet.
pub(crate) fn cmd_status_fleet_convergence_velocity(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let velocity = compute_convergence_velocity(state_dir, &targets);
    if json {
        println!(
            "{{\"fleet_convergence_velocity\":{{\"total\":{},\"converged\":{},\"rate\":{:.2}}}}}",
            velocity.0, velocity.1, velocity.2
        );
    } else {
        println!(
            "Fleet convergence velocity: {}/{} resources converged ({:.1}%)",
            velocity.1,
            velocity.0,
            velocity.2 * 100.0
        );
    }
    Ok(())
}

fn compute_convergence_velocity(state_dir: &Path, targets: &[&String]) -> (usize, usize, f64) {
    let mut total = 0usize;
    let mut converged = 0usize;
    for m in targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        total += lock.resources.len();
        converged += lock
            .resources
            .values()
            .filter(|r| r.status == types::ResourceStatus::Converged)
            .count();
    }
    let rate = if total > 0 {
        converged as f64 / total as f64
    } else {
        0.0
    };
    (total, converged, rate)
}

/// FJ-860: Correlate failures across resources.
pub(crate) fn cmd_status_resource_failure_correlation(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let correlations = find_failure_correlations(state_dir, &targets);
    if json {
        let items: Vec<String> = correlations
            .iter()
            .map(|(r, count)| format!("{{\"resource\":\"{r}\",\"failure_count\":{count}}}"))
            .collect();
        println!("{{\"failure_correlations\":[{}]}}", items.join(","));
    } else if correlations.is_empty() {
        println!("No failure correlations found.");
    } else {
        println!("Resource failure correlations (across machines):");
        for (r, count) in &correlations {
            println!("  {r} — failed on {count} machines");
        }
    }
    Ok(())
}

fn find_failure_correlations(state_dir: &Path, targets: &[&String]) -> Vec<(String, usize)> {
    let mut failure_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for m in targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        for (name, rs) in &lock.resources {
            if rs.status == types::ResourceStatus::Failed {
                *failure_counts.entry(name.clone()).or_default() += 1;
            }
        }
    }
    let mut results: Vec<(String, usize)> = failure_counts.into_iter().collect();
    results.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    results
}

/// FJ-862: Resource change frequency per machine over time.
pub(crate) fn cmd_status_machine_resource_churn_rate(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let mut rates: Vec<(String, usize)> = Vec::new();
    for m in &targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        let churn = lock.resources.len();
        rates.push(((*m).clone(), churn));
    }
    rates.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    if json {
        let items: Vec<String> = rates
            .iter()
            .map(|(m, c)| format!("{{\"machine\":\"{m}\",\"resource_count\":{c}}}"))
            .collect();
        println!("{{\"machine_resource_churn_rate\":[{}]}}", items.join(","));
    } else if rates.is_empty() {
        println!("No resource churn data available.");
    } else {
        println!("Machine resource churn rate:");
        for (m, c) in &rates {
            println!("  {m}{c} resources tracked");
        }
    }
    Ok(())
}

/// FJ-866: Identify resources not applied in configurable window (staleness).
pub(crate) fn cmd_status_fleet_resource_staleness(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let mut stale: Vec<(String, String, String)> = Vec::new();
    for m in &targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        for (name, rs) in &lock.resources {
            let age = rs.applied_at.as_deref().unwrap_or("unknown");
            stale.push(((*m).clone(), name.clone(), age.to_string()));
        }
    }
    stale.sort_by(|a, b| a.2.cmp(&b.2));
    if json {
        let items: Vec<String> = stale
            .iter()
            .map(|(m, r, a)| {
                format!("{{\"machine\":\"{m}\",\"resource\":\"{r}\",\"applied_at\":\"{a}\"}}")
            })
            .collect();
        println!("{{\"fleet_resource_staleness\":[{}]}}", items.join(","));
    } else if stale.is_empty() {
        println!("No staleness data available.");
    } else {
        println!("Fleet resource staleness (oldest first):");
        for (m, r, a) in &stale {
            println!("  {m} / {r} — last applied {a}");
        }
    }
    Ok(())
}

/// FJ-868: Convergence trend per machine over time.
pub(crate) fn cmd_status_machine_convergence_trend(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let mut trends: Vec<(String, usize, usize, f64)> = Vec::new();
    for m in &targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        let total = lock.resources.len();
        let converged = lock
            .resources
            .values()
            .filter(|r| r.status == types::ResourceStatus::Converged)
            .count();
        let pct = if total > 0 {
            (converged as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        trends.push(((*m).clone(), converged, total, pct));
    }
    trends.sort_by(|a, b| {
        a.3.partial_cmp(&b.3)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.0.cmp(&b.0))
    });
    if json {
        let items: Vec<String> = trends
            .iter()
            .map(|(m, c, t, p)| {
                format!("{{\"machine\":\"{m}\",\"converged\":{c},\"total\":{t},\"pct\":{p:.1}}}")
            })
            .collect();
        println!("{{\"machine_convergence_trend\":[{}]}}", items.join(","));
    } else if trends.is_empty() {
        println!("No convergence trend data available.");
    } else {
        println!("Machine convergence trend:");
        for (m, c, t, p) in &trends {
            println!("  {m}{c}/{t} converged ({p:.1}%)");
        }
    }
    Ok(())
}

/// FJ-870: Resource density and capacity metrics per machine.
pub(crate) fn cmd_status_machine_capacity_utilization(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let mut utilization: Vec<(String, usize)> = Vec::new();
    for m in &targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        utilization.push(((*m).clone(), lock.resources.len()));
    }
    utilization.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    if json {
        let items: Vec<String> = utilization
            .iter()
            .map(|(m, c)| format!("{{\"machine\":\"{m}\",\"resource_count\":{c}}}"))
            .collect();
        println!("{{\"machine_capacity_utilization\":[{}]}}", items.join(","));
    } else if utilization.is_empty() {
        println!("No capacity utilization data available.");
    } else {
        println!("Machine capacity utilization:");
        for (m, c) in &utilization {
            println!("  {m}{c} resources");
        }
    }
    Ok(())
}

/// FJ-874: Measure configuration diversity across fleet.
pub(crate) fn cmd_status_fleet_configuration_entropy(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let entries = collect_type_entropy(state_dir, &targets);
    let total: usize = entries.iter().map(|(_, c)| c).sum();
    if json {
        let items: Vec<String> = entries
            .iter()
            .map(|(t, c)| format!("{{\"type\":\"{t}\",\"count\":{c}}}"))
            .collect();
        println!(
            "{{\"fleet_configuration_entropy\":{{\"total\":{},\"types\":[{}]}}}}",
            total,
            items.join(",")
        );
    } else if entries.is_empty() {
        println!("No configuration entropy data available.");
    } else {
        println!("Fleet configuration entropy ({total} total resources):");
        for (t, c) in &entries {
            let pct = if total > 0 {
                (*c as f64 / total as f64) * 100.0
            } else {
                0.0
            };
            println!("  {t}{c} ({pct:.1}%)");
        }
    }
    Ok(())
}

fn collect_type_entropy(state_dir: &Path, targets: &[&String]) -> Vec<(String, usize)> {
    let mut type_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for m in targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        for rs in lock.resources.values() {
            *type_counts
                .entry(format!("{:?}", rs.resource_type))
                .or_default() += 1;
        }
    }
    let mut entries: Vec<(String, usize)> = type_counts.into_iter().collect();
    entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    entries
}

/// FJ-876: Time since last successful apply per resource.
pub(crate) fn cmd_status_machine_resource_freshness(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let mut freshness: Vec<(String, String, String)> = Vec::new();
    for m in &targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&lock_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        for (name, rs) in &lock.resources {
            let last_apply = rs.applied_at.as_deref().unwrap_or("never");
            freshness.push(((*m).clone(), name.clone(), last_apply.to_string()));
        }
    }
    freshness.sort_by(|a, b| a.2.cmp(&b.2).then(a.0.cmp(&b.0)).then(a.1.cmp(&b.1)));
    if json {
        let items: Vec<String> = freshness
            .iter()
            .map(|(m, r, a)| {
                format!("{{\"machine\":\"{m}\",\"resource\":\"{r}\",\"last_apply\":\"{a}\"}}")
            })
            .collect();
        println!("{{\"machine_resource_freshness\":[{}]}}", items.join(","));
    } else if freshness.is_empty() {
        println!("No resource freshness data available.");
    } else {
        println!("Machine resource freshness (oldest first):");
        for (m, r, a) in &freshness {
            println!("  {m} / {r} — last applied {a}");
        }
    }
    Ok(())
}