forjar 1.4.1

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
//! Status intelligence — MTTR estimates, convergence forecasting, budget projections.

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;

pub(super) fn pct(num: usize, den: usize) -> f64 {
    if den > 0 {
        (num as f64 / den as f64) * 100.0
    } else {
        0.0
    }
}

/// FJ-910: Estimate MTTR per machine based on failure/recovery patterns.
pub(crate) fn cmd_status_machine_resource_mttr_estimate(
    sd: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(sd);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let estimates = collect_mttr_estimates(sd, &targets);
    if json {
        let items: Vec<String> = estimates
            .iter()
            .map(|(m, s)| format!("{{\"machine\":\"{m}\",\"mttr_estimate\":\"{s}\"}}"))
            .collect();
        println!("{{\"machine_mttr_estimates\":[{}]}}", items.join(","));
    } else if estimates.is_empty() {
        println!("No MTTR estimate data available.");
    } else {
        println!("Machine MTTR estimates:");
        for (m, s) in &estimates {
            println!("  {m}{s}");
        }
    }
    Ok(())
}

pub(super) fn collect_mttr_estimates(sd: &Path, targets: &[&String]) -> Vec<(String, String)> {
    let mut estimates = Vec::new();
    for m in targets {
        // Read events to compute actual MTTR
        let events_path = sd.join(m).join("events.jsonl");
        let events_content = std::fs::read_to_string(&events_path).ok();

        // Read lock to get current failure count
        let lock_path = sd.join(m).join("state.lock.yaml");
        let lock_content = std::fs::read_to_string(&lock_path).ok();

        let failed = lock_content
            .as_ref()
            .and_then(|c| serde_yaml_ng::from_str::<types::StateLock>(c).ok())
            .map(|lock| {
                lock.resources
                    .values()
                    .filter(|r| matches!(r.status, types::ResourceStatus::Failed))
                    .count()
            })
            .unwrap_or(0);

        let est = match events_content {
            Some(ref content) if !content.is_empty() => {
                let mttr = compute_event_mttr(content);
                match (mttr, failed) {
                    (Some(seconds), f) if f > 0 => format_mttr(seconds, f),
                    (Some(seconds), _) => format_mttr_healthy(seconds),
                    (None, f) if f > 0 => {
                        format!("{f} currently failed — no prior recovery data")
                    }
                    _ => "all healthy — no recovery needed".to_string(),
                }
            }
            _ if failed > 0 => format!("{failed} failed — no event history for MTTR"),
            _ => "no data".to_string(),
        };
        estimates.push(((*m).clone(), est));
    }
    estimates.sort_by(|a, b| a.0.cmp(&b.0));
    estimates
}

fn compute_event_mttr(content: &str) -> Option<f64> {
    let mut fail_times: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
    let mut recovery_durations: Vec<f64> = Vec::new();

    for line in content.lines() {
        let val: serde_json::Value = match serde_json::from_str(line) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let event = val.get("event").and_then(|v| v.as_str()).unwrap_or("");
        let resource = val.get("resource").and_then(|v| v.as_str()).unwrap_or("");
        let ts_str = val.get("ts").and_then(|v| v.as_str()).unwrap_or("");
        let ts = match parse_event_ts(ts_str) {
            Some(t) => t,
            None => continue,
        };

        if event == "resource_failed" || event == "resource_drifted" {
            fail_times.insert(resource.to_string(), ts);
        } else if event == "resource_converged" {
            if let Some(fail_ts) = fail_times.remove(resource) {
                let duration = ts - fail_ts;
                if duration > 0.0 {
                    recovery_durations.push(duration);
                }
            }
        }
    }

    if recovery_durations.is_empty() {
        None
    } else {
        Some(recovery_durations.iter().sum::<f64>() / recovery_durations.len() as f64)
    }
}

fn parse_event_ts(s: &str) -> Option<f64> {
    let parts: Vec<&str> = s.split('T').collect();
    if parts.len() != 2 {
        return None;
    }
    let date: Vec<u32> = parts[0].split('-').filter_map(|p| p.parse().ok()).collect();
    let time_str = parts[1].trim_end_matches('Z');
    let time: Vec<f64> = time_str.split(':').filter_map(|p| p.parse().ok()).collect();
    if date.len() != 3 || time.len() != 3 {
        return None;
    }
    let days = (date[0] as f64 - 1970.0) * 365.25 + (date[1] as f64 - 1.0) * 30.44 + date[2] as f64;
    Some(days * 86400.0 + time[0] * 3600.0 + time[1] * 60.0 + time[2])
}

fn format_mttr(seconds: f64, current_failed: usize) -> String {
    let time = if seconds < 60.0 {
        format!("{seconds:.1}s")
    } else if seconds < 3600.0 {
        format!("{:.1}m", seconds / 60.0)
    } else {
        format!("{:.1}h", seconds / 3600.0)
    };
    format!("MTTR {time} avg — {current_failed} currently failed")
}

fn format_mttr_healthy(seconds: f64) -> String {
    let time = if seconds < 60.0 {
        format!("{seconds:.1}s")
    } else if seconds < 3600.0 {
        format!("{:.1}m", seconds / 60.0)
    } else {
        format!("{:.1}h", seconds / 3600.0)
    };
    format!("MTTR {time} avg — all healthy now")
}

/// FJ-914: Forecast convergence trajectory based on current state.
pub(crate) fn cmd_status_fleet_resource_convergence_forecast(
    sd: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(sd);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let forecasts = collect_convergence_forecasts(sd, &targets);
    if json {
        let items: Vec<String> = forecasts
            .iter()
            .map(|(m, c, t)| {
                format!(
                    "{{\"machine\":\"{}\",\"converged\":{},\"total\":{},\"forecast\":\"{}\"}}",
                    m,
                    c,
                    t,
                    forecast_label(*c, *t)
                )
            })
            .collect();
        println!("{{\"convergence_forecast\":[{}]}}", items.join(","));
    } else if forecasts.is_empty() {
        println!("No convergence forecast data available.");
    } else {
        println!("Fleet convergence forecast:");
        for (m, c, t) in &forecasts {
            println!(
                "  {}{}/{} converged ({})",
                m,
                c,
                t,
                forecast_label(*c, *t)
            );
        }
    }
    Ok(())
}

pub(super) fn forecast_label(converged: usize, total: usize) -> String {
    if total == 0 {
        return "no resources".to_string();
    }
    let rate = pct(converged, total);
    if rate >= 100.0 {
        "fully converged".to_string()
    } else if rate >= 80.0 {
        "near convergence".to_string()
    } else if rate >= 50.0 {
        "partial convergence".to_string()
    } else {
        "low convergence".to_string()
    }
}

pub(super) fn collect_convergence_forecasts(
    sd: &Path,
    targets: &[&String],
) -> Vec<(String, usize, usize)> {
    let mut forecasts = Vec::new();
    for m in targets {
        let path = sd.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&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| matches!(r.status, types::ResourceStatus::Converged))
            .count();
        forecasts.push(((*m).clone(), converged, total));
    }
    forecasts.sort_by(|a, b| a.0.cmp(&b.0));
    forecasts
}

/// FJ-916: Forecast error budget depletion based on current failure rate.
pub(crate) fn cmd_status_machine_resource_error_budget_forecast(
    sd: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(sd);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let forecasts = collect_error_budget_forecasts(sd, &targets);
    if json {
        let items: Vec<String> = forecasts
            .iter()
            .map(|(m, f, t)| {
                format!(
                    "{{\"machine\":\"{}\",\"failed\":{},\"total\":{},\"budget_pct\":{:.1}}}",
                    m,
                    f,
                    t,
                    pct(*f, *t)
                )
            })
            .collect();
        println!("{{\"error_budget_forecast\":[{}]}}", items.join(","));
    } else if forecasts.is_empty() {
        println!("No error budget forecast data available.");
    } else {
        println!("Machine error budget forecast:");
        for (m, f, t) in &forecasts {
            let remaining = 100.0 - pct(*f, *t);
            println!("  {m}{remaining:.1}% budget remaining ({f}/{t} failed)");
        }
    }
    Ok(())
}

pub(super) fn collect_error_budget_forecasts(
    sd: &Path,
    targets: &[&String],
) -> Vec<(String, usize, usize)> {
    let mut forecasts = Vec::new();
    for m in targets {
        let path = sd.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&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 failed = lock
            .resources
            .values()
            .filter(|r| matches!(r.status, types::ResourceStatus::Failed))
            .count();
        forecasts.push(((*m).clone(), failed, total));
    }
    forecasts.sort_by(|a, b| a.0.cmp(&b.0));
    forecasts
}

/// FJ-918: Detect lag between dependent resource convergence.
pub(crate) fn cmd_status_machine_resource_dependency_lag(
    sd: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(sd);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let lags = collect_dependency_lag(sd, &targets);
    if json {
        let items: Vec<String> = lags
            .iter()
            .map(|(m, c, f)| {
                format!(
                    "{{\"machine\":\"{}\",\"converged\":{},\"failed\":{},\"lag_detected\":{}}}",
                    m,
                    c,
                    f,
                    *f > 0
                )
            })
            .collect();
        println!("{{\"dependency_lag\":[{}]}}", items.join(","));
    } else if lags.is_empty() {
        println!("No dependency lag data available.");
    } else {
        println!("Machine dependency convergence lag:");
        for (m, c, f) in &lags {
            let lag = if *f > 0 { "lag detected" } else { "in sync" };
            println!("  {}{}/{} converged ({})", m, c, c + f, lag);
        }
    }
    Ok(())
}

pub(super) fn collect_dependency_lag(
    sd: &Path,
    targets: &[&String],
) -> Vec<(String, usize, usize)> {
    let mut lags = Vec::new();
    for m in targets {
        let path = sd.join(m).join("state.lock.yaml");
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lock: types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };
        let converged = lock
            .resources
            .values()
            .filter(|r| matches!(r.status, types::ResourceStatus::Converged))
            .count();
        let failed = lock
            .resources
            .values()
            .filter(|r| matches!(r.status, types::ResourceStatus::Failed))
            .count();
        lags.push(((*m).clone(), converged, failed));
    }
    lags.sort_by(|a, b| a.0.cmp(&b.0));
    lags
}

/// FJ-922: Fleet-wide dependency convergence lag analysis.
pub(crate) fn cmd_status_fleet_resource_dependency_lag(
    sd: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(sd);
    let targets: Vec<&String> = match machine {
        Some(m) => machines.iter().filter(|x| x.as_str() == m).collect(),
        None => machines.iter().collect(),
    };
    let lags = collect_dependency_lag(sd, &targets);
    let total_converged: usize = lags.iter().map(|(_, c, _)| c).sum();
    let total_failed: usize = lags.iter().map(|(_, _, f)| f).sum();
    let total = total_converged + total_failed;
    if json {
        println!("{{\"fleet_dependency_lag\":{{\"total_converged\":{},\"total_failed\":{},\"total\":{},\"lag_pct\":{:.1}}}}}", total_converged, total_failed, total, pct(total_failed, total));
    } else {
        println!(
            "Fleet dependency lag: {}/{} resources converged ({:.1}% lagging)",
            total_converged,
            total,
            pct(total_failed, total)
        );
    }
    Ok(())
}

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