forjar 1.25.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Failure analysis.

use super::helpers::*;
use crate::core::{state, types};
use std::path::Path;

/// Filter machines list by optional machine filter.
fn filter_machines<'a>(machines: &'a [String], machine: Option<&str>) -> Vec<&'a String> {
    if let Some(m) = machine {
        machines.iter().filter(|x| x.as_str() == m).collect()
    } else {
        machines.iter().collect()
    }
}

/// Load a StateLock from a lock.yaml file, returning None on any error.
fn load_lock_from_yaml(state_dir: &Path, m: &str) -> Option<types::StateLock> {
    let lock_path = state_dir.join(m).join("state.lock.yaml");
    let content = std::fs::read_to_string(&lock_path).ok()?;
    serde_yaml_ng::from_str(&content).ok()
}

// ── FJ-482: status --top-failures ──

/// Collect failure counts from state locks.
fn collect_failure_counts(
    state_dir: &Path,
    machines: &[String],
) -> Result<Vec<(String, usize)>, String> {
    let mut failure_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for m in machines {
        if let Some(lock) = state::load_lock(state_dir, m).map_err(|e| e.to_string())? {
            for (rname, rl) in &lock.resources {
                if rl.status == types::ResourceStatus::Failed {
                    *failure_counts.entry(format!("{m}:{rname}")).or_insert(0) += 1;
                }
            }
        }
    }
    let mut ranked: Vec<(String, usize)> = failure_counts.into_iter().collect();
    ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    Ok(ranked)
}

pub(crate) fn cmd_status_top_failures(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let all_machines = discover_machines(state_dir);
    let machines: Vec<String> = if let Some(m) = machine {
        all_machines.into_iter().filter(|n| n == m).collect()
    } else {
        all_machines
    };
    let ranked = collect_failure_counts(state_dir, &machines)?;
    if json {
        let items: Vec<serde_json::Value> = ranked
            .iter()
            .map(|(name, count)| serde_json::json!({"resource": name, "failures": count}))
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({"top_failures": items}))
                .unwrap_or_default()
        );
    } else if ranked.is_empty() {
        println!("{} No failed resources", green(""));
    } else {
        println!("Top Failing Resources");
        println!("{}", "".repeat(40));
        for (name, count) in &ranked {
            println!("  {name:40} {count} failure(s)");
        }
    }
    Ok(())
}

/// FJ-672: Show resources failed since a given timestamp
pub(crate) fn cmd_status_failed_since(
    state_dir: &Path,
    machine: Option<&str>,
    since: &str,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets = filter_machines(&machines, machine);

    let mut failed = Vec::new();
    for m in &targets {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        if !lock_path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&lock_path).unwrap_or_default();
        let lock: crate::core::types::StateLock = match serde_yaml_ng::from_str(&content) {
            Ok(l) => l,
            Err(_) => continue,
        };

        for (rname, rlock) in &lock.resources {
            if !matches!(rlock.status, crate::core::types::ResourceStatus::Failed) {
                continue;
            }
            let applied = rlock.applied_at.clone().unwrap_or_default();
            if applied.as_str() >= since {
                failed.push(((*m).clone(), rname.clone(), applied));
            }
        }
    }

    print_failed_since_output(&failed, since, json);
    Ok(())
}

/// Print output for failed-since command.
fn print_failed_since_output(failed: &[(String, String, String)], since: &str, json: bool) {
    if json {
        print!("{{\"failed\":[");
        for (i, (machine, resource, applied)) in failed.iter().enumerate() {
            if i > 0 {
                print!(",");
            }
            print!(r#"{{"machine":"{machine}","resource":"{resource}","applied_at":"{applied}"}}"#);
        }
        println!("]}}");
    } else if failed.is_empty() {
        println!("No failed resources since {since}");
    } else {
        println!("Failed resources since {} ({}):", since, failed.len());
        for (machine, resource, applied) in failed {
            println!("  {machine}/{resource} (at {applied})");
        }
    }
}

/// FJ-722: Show only failed resources across machines
pub(crate) fn cmd_status_failed_resources(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets = filter_machines(&machines, machine);

    let mut entries = Vec::new();
    for m in &targets {
        if let Some(lock) = load_lock_from_yaml(state_dir, m) {
            for (name, rl) in &lock.resources {
                if format!("{:?}", rl.status) == "Failed" {
                    entries.push((
                        m.to_string(),
                        name.clone(),
                        format!("{:?}", rl.resource_type),
                    ));
                }
            }
        }
    }

    if json {
        let items: Vec<String> = entries
            .iter()
            .map(|(m, name, rtype)| {
                format!("{{\"machine\":\"{m}\",\"resource\":\"{name}\",\"type\":\"{rtype}\"}}")
            })
            .collect();
        println!(
            "{{\"failed_resources\":[{}],\"count\":{}}}",
            items.join(","),
            entries.len()
        );
    } else if entries.is_empty() {
        println!("No failed resources.");
    } else {
        println!("Failed resources:");
        for (m, name, rtype) in &entries {
            println!("  {m} / {name} ({rtype})");
        }
    }
    Ok(())
}

/// FJ-677: Verify BLAKE3 hashes in lock match computed hashes
/// Recompute a resource's on-disk hash and compare it to the lock.
///
/// Returns None when the lock records nothing to compare against — that is
/// "unverifiable", which is deliberately NOT the same as "verified".
fn recheck_resource(rlock: &crate::core::types::ResourceLock) -> Option<bool> {
    let path = rlock.details.get("path")?.as_str()?;
    // `content_hash` is the hash of the DECLARED content, so comparing it to
    // the file on disk answers "does this file still hold what forjar put
    // there". NOT `live_hash` — that is a hash of the state-QUERY's stdout
    // (hash_string_or_sentinel(&qout.stdout) in executor/resource_ops.rs), so
    // comparing it to file bytes fails for every resource, which is a worse
    // defect than the one being fixed. Measured, not assumed: doing that made
    // the untampered control report MISMATCHED.
    let recorded = rlock.details.get("content_hash")?.as_str()?;
    match crate::tripwire::hasher::hash_file(std::path::Path::new(path)) {
        Ok(actual) => Some(actual == recorded),
        // The file is gone or unreadable. That is a MISMATCH, not an absence
        // of evidence to be waved through — the recorded state says a file
        // with that hash should be there.
        Err(_) => Some(false),
    }
}

pub(crate) fn cmd_status_hash_verify(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets = filter_machines(&machines, machine);

    let mut verified = 0u64;
    let mut mismatched = 0u64;
    let mut unverifiable = 0u64;
    let mut total = 0u64;
    let mut bad: Vec<String> = Vec::new();

    for m in &targets {
        if let Some(lock) = load_lock_from_yaml(state_dir, m) {
            for (rname, rlock) in &lock.resources {
                total += 1;
                // ACTUALLY COMPARE THE HASHES.
                //
                // This used to count resources that HAVE a hash — "1/1
                // resources have BLAKE3 hashes" — and call that verification.
                // A tampered file passed, because the RECORDED hash was still
                // non-empty; the file on disk was never read. Ledger id
                // status-hash-verify-verifies-nothing, confirmed at 1.12.3 and
                // still reproducing at 1.16.0.
                match recheck_resource(rlock) {
                    Some(true) => verified += 1,
                    Some(false) => {
                        mismatched += 1;
                        bad.push(format!("{m}/{rname}"));
                    }
                    // Nothing recorded to compare against. Counted separately
                    // and reported: rolling it into `verified` is the original
                    // defect, and rolling it into `mismatched` would fail every
                    // resource type that has no on-disk artifact.
                    None => unverifiable += 1,
                }
            }
        }
    }

    if json {
        println!(
            r#"{{"total":{total},"verified":{verified},"mismatched":{mismatched},"unverifiable":{unverifiable}}}"#
        );
    } else {
        println!(
            "Hash verification: {verified}/{total} match, {mismatched} MISMATCHED, \
             {unverifiable} unverifiable"
        );
        for b in &bad {
            println!("  MISMATCH: {b}");
        }
    }

    // A mismatch is the whole point of the command. Exiting 0 on one would
    // make every CI use of it inert.
    if mismatched > 0 {
        return Err(format!(
            "{mismatched} resource(s) no longer match their recorded hash"
        ));
    }
    Ok(())
}

/// FJ-667: Show age of each lock file entry
pub(crate) fn cmd_status_lock_age(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets = filter_machines(&machines, machine);

    let mut entries = Vec::new();
    for m in &targets {
        if let Some(lock) = load_lock_from_yaml(state_dir, m) {
            for (rname, rlock) in &lock.resources {
                let applied = rlock.applied_at.clone().unwrap_or_default();
                entries.push((m.to_string(), rname.clone(), applied));
            }
        }
    }

    if json {
        print!("{{\"entries\":[");
        for (i, (m, rname, applied)) in entries.iter().enumerate() {
            if i > 0 {
                print!(",");
            }
            print!(r#"{{"machine":"{m}","resource":"{rname}","applied_at":"{applied}"}}"#);
        }
        println!("]}}");
    } else {
        for (m, rname, applied) in &entries {
            println!(
                "{}/{}: applied at {}",
                m,
                rname,
                if applied.is_empty() {
                    "unknown"
                } else {
                    applied
                }
            );
        }
    }
    Ok(())
}

/// FJ-697: Show hash of current config for change detection
pub(crate) fn cmd_status_config_hash(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets = filter_machines(&machines, machine);
    if json {
        let mut entries = Vec::new();
        for m in &targets {
            let lock_path = state_dir.join(m).join("state.lock.yaml");
            if let Ok(data) = std::fs::read_to_string(&lock_path) {
                let hash = crate::tripwire::hasher::hash_string(&data);
                entries.push(format!(
                    "{{\"machine\":\"{m}\",\"config_hash\":\"{hash}\"}}"
                ));
            }
        }
        println!("{{\"config_hashes\":[{}]}}", entries.join(","));
    } else {
        println!("Config hashes:");
        for m in &targets {
            let lock_path = state_dir.join(m).join("state.lock.yaml");
            if let Ok(data) = std::fs::read_to_string(&lock_path) {
                let hash = crate::tripwire::hasher::hash_string(&data);
                println!("  {m}{hash}");
            }
        }
    }
    Ok(())
}

/// FJ-647: AI-powered recommendations based on state analysis
pub(crate) fn cmd_status_recommendations(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let targets = filter_machines(&machines, machine);

    let mut total_resources = 0u64;
    let mut failed_count = 0u64;
    let mut drifted_count = 0u64;

    for m in &targets {
        if let Some(lock) = load_lock_from_yaml(state_dir, m) {
            for (_rname, rlock) in &lock.resources {
                total_resources += 1;
                match rlock.status {
                    crate::core::types::ResourceStatus::Failed => failed_count += 1,
                    crate::core::types::ResourceStatus::Drifted => drifted_count += 1,
                    _ => {}
                }
            }
        }
    }

    let recommendations = build_recommendations(total_resources, failed_count, drifted_count);
    print_recommendations(&recommendations, json);
    Ok(())
}

/// Build recommendation strings based on resource counts.
fn build_recommendations(total: u64, failed: u64, drifted: u64) -> Vec<String> {
    let mut recommendations = Vec::new();
    if failed > 0 {
        recommendations.push(format!(
            "HIGH: {failed} failed resources need attention. Run 'forjar apply' to reconverge."
        ));
    }
    if drifted > 0 {
        recommendations.push(format!(
            "MEDIUM: {drifted} drifted resources detected. Run 'forjar drift' for details."
        ));
    }
    if total == 0 {
        recommendations
            .push("INFO: No resources found. Run 'forjar apply' to initialize state.".to_string());
    }
    if failed == 0 && drifted == 0 && total > 0 {
        recommendations.push(format!(
            "OK: All {total} resources are converged. No action needed."
        ));
    }
    recommendations
}

/// Print recommendations in JSON or text format.
fn print_recommendations(recommendations: &[String], json: bool) {
    if json {
        print!("{{\"recommendations\":[");
        for (i, r) in recommendations.iter().enumerate() {
            if i > 0 {
                print!(",");
            }
            print!(r#""{}""#, r.replace('"', "\\\""));
        }
        println!("]}}");
    } else {
        println!("Recommendations:");
        for r in recommendations {
            println!("  {r}");
        }
    }
}