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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Doctor diagnostics.

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

#[derive(Debug)]
struct DoctorCheck {
    name: String,
    status: DoctorStatus,
    detail: String,
}

#[derive(Debug, PartialEq)]
enum DoctorStatus {
    Pass,
    Warn,
    Fail,
}

impl DoctorStatus {
    #[allow(dead_code)]
    fn label(&self) -> &'static str {
        match self {
            DoctorStatus::Pass => "pass",
            DoctorStatus::Warn => "warn",
            DoctorStatus::Fail => "FAIL",
        }
    }

    fn json_label(&self) -> &'static str {
        match self {
            DoctorStatus::Pass => "pass",
            DoctorStatus::Warn => "warn",
            DoctorStatus::Fail => "fail",
        }
    }
}

fn check_bash() -> DoctorCheck {
    use std::process::Command;
    match Command::new("bash").arg("--version").output() {
        Ok(out) => {
            let ver = String::from_utf8_lossy(&out.stdout);
            let version_str = ver.lines().next().unwrap_or("").to_string();
            if let Some(pos) = version_str.find("version ") {
                let after = &version_str[pos + 8..];
                let major: u32 = after
                    .chars()
                    .take_while(|c| c.is_ascii_digit())
                    .collect::<String>()
                    .parse()
                    .unwrap_or(0);
                if major >= 4 {
                    DoctorCheck {
                        name: "bash".to_string(),
                        status: DoctorStatus::Pass,
                        detail: format!(
                            "bash {}",
                            &after[..after
                                .find(|c: char| c.is_whitespace() || c == '(')
                                .unwrap_or(after.len())]
                        ),
                    }
                } else {
                    DoctorCheck {
                        name: "bash".to_string(),
                        status: DoctorStatus::Fail,
                        detail: format!("bash {major} (need >= 4.0)"),
                    }
                }
            } else {
                DoctorCheck {
                    name: "bash".to_string(),
                    status: DoctorStatus::Warn,
                    detail: "cannot parse bash version".to_string(),
                }
            }
        }
        Err(_) => DoctorCheck {
            name: "bash".to_string(),
            status: DoctorStatus::Fail,
            detail: "bash not found in PATH".to_string(),
        },
    }
}

fn check_ssh() -> DoctorCheck {
    use std::process::Command;
    match Command::new("ssh").arg("-V").output() {
        Ok(out) => {
            let ver = String::from_utf8_lossy(&out.stderr);
            let version_line = ver.lines().next().unwrap_or("ssh available").to_string();
            DoctorCheck {
                name: "ssh".to_string(),
                status: DoctorStatus::Pass,
                detail: version_line,
            }
        }
        Err(_) => DoctorCheck {
            name: "ssh".to_string(),
            status: DoctorStatus::Fail,
            detail: "ssh not found (needed for remote machines)".to_string(),
        },
    }
}

fn check_container_runtime(runtime: &str) -> DoctorCheck {
    use std::process::Command;
    match Command::new(runtime).arg("--version").output() {
        Ok(out) => {
            let ver = String::from_utf8_lossy(&out.stdout);
            let version_line = ver.lines().next().unwrap_or(runtime).trim().to_string();
            DoctorCheck {
                name: runtime.to_string(),
                status: DoctorStatus::Pass,
                detail: version_line,
            }
        }
        Err(_) => DoctorCheck {
            name: runtime.to_string(),
            status: DoctorStatus::Fail,
            detail: format!("{runtime} not found (needed for container machines)"),
        },
    }
}

fn check_age_identity() -> DoctorCheck {
    #[cfg(not(feature = "encryption"))]
    {
        DoctorCheck {
            name: "age".to_string(),
            status: DoctorStatus::Warn,
            detail: "encryption feature not compiled in".to_string(),
        }
    }
    #[cfg(feature = "encryption")]
    match secrets::load_identities(None) {
        Ok(ids) if !ids.is_empty() => DoctorCheck {
            name: "age".to_string(),
            status: DoctorStatus::Pass,
            detail: format!("{} identity loaded", ids.len()),
        },
        Ok(_) => DoctorCheck {
            name: "age".to_string(),
            status: DoctorStatus::Fail,
            detail: "no age identity (set FORJAR_AGE_KEY or use --identity)".to_string(),
        },
        Err(e) => DoctorCheck {
            name: "age".to_string(),
            status: DoctorStatus::Fail,
            detail: format!("age identity error: {e}"),
        },
    }
}

fn check_state_dir_existence(state_dir: &Path, fix: bool) -> DoctorCheck {
    if state_dir.exists() {
        let test_path = state_dir.join(".doctor-probe");
        match std::fs::write(&test_path, "probe") {
            Ok(()) => {
                let _ = std::fs::remove_file(&test_path);
                DoctorCheck {
                    name: "state-dir".to_string(),
                    status: DoctorStatus::Pass,
                    detail: format!("{} writable", state_dir.display()),
                }
            }
            Err(e) => DoctorCheck {
                name: "state-dir".to_string(),
                status: DoctorStatus::Fail,
                detail: format!("{} not writable: {}", state_dir.display(), e),
            },
        }
    } else if fix {
        match std::fs::create_dir_all(state_dir) {
            Ok(()) => DoctorCheck {
                name: "state-dir".to_string(),
                status: DoctorStatus::Pass,
                detail: format!("{} created (--fix)", state_dir.display()),
            },
            Err(e) => DoctorCheck {
                name: "state-dir".to_string(),
                status: DoctorStatus::Fail,
                detail: format!("cannot create {}: {}", state_dir.display(), e),
            },
        }
    } else {
        DoctorCheck {
            name: "state-dir".to_string(),
            status: DoctorStatus::Warn,
            detail: format!(
                "{} does not exist (will be created on apply)",
                state_dir.display()
            ),
        }
    }
}

fn check_stale_lock(state_dir: &Path, fix: bool) -> Option<DoctorCheck> {
    if !state_dir.exists() {
        return None;
    }
    let lock_path = state_dir.join(".forjar.lock");
    if !lock_path.exists() {
        return None;
    }
    if fix {
        match std::fs::remove_file(&lock_path) {
            Ok(()) => Some(DoctorCheck {
                name: "lock".to_string(),
                status: DoctorStatus::Pass,
                detail: "stale lock removed (--fix)".to_string(),
            }),
            Err(e) => Some(DoctorCheck {
                name: "lock".to_string(),
                status: DoctorStatus::Fail,
                detail: format!("cannot remove lock: {e}"),
            }),
        }
    } else {
        Some(DoctorCheck {
            name: "lock".to_string(),
            status: DoctorStatus::Warn,
            detail: "stale lock file exists (use --fix to remove)".to_string(),
        })
    }
}

fn check_state_dir(fix: bool) -> Vec<DoctorCheck> {
    let mut checks = Vec::new();
    let state_dir = Path::new("state");
    checks.push(check_state_dir_existence(state_dir, fix));
    if let Some(lock_check) = check_stale_lock(state_dir, fix) {
        checks.push(lock_check);
    }
    checks
}

fn check_git() -> DoctorCheck {
    use std::process::Command;
    match Command::new("git").args(["status", "--porcelain"]).output() {
        Ok(out) if out.status.success() => {
            let output = String::from_utf8_lossy(&out.stdout);
            if output.trim().is_empty() {
                DoctorCheck {
                    name: "git".to_string(),
                    status: DoctorStatus::Pass,
                    detail: "working tree clean".to_string(),
                }
            } else {
                let line_count = output.lines().count();
                DoctorCheck {
                    name: "git".to_string(),
                    status: DoctorStatus::Warn,
                    detail: format!("{line_count} uncommitted changes"),
                }
            }
        }
        Ok(_) => DoctorCheck {
            name: "git".to_string(),
            status: DoctorStatus::Warn,
            detail: "not a git repository".to_string(),
        },
        Err(_) => DoctorCheck {
            name: "git".to_string(),
            status: DoctorStatus::Warn,
            detail: "git not found in PATH".to_string(),
        },
    }
}

fn output_doctor_checks_to(
    checks: &[DoctorCheck],
    json: bool,
    out: &mut dyn super::output::OutputWriter,
) {
    if json {
        let items: Vec<String> = checks
            .iter()
            .map(|c| {
                format!(
                    "  {{\"name\":\"{}\",\"status\":\"{}\",\"detail\":\"{}\"}}",
                    c.name,
                    c.status.json_label(),
                    c.detail.replace('\"', "\\\"")
                )
            })
            .collect();
        out.result(&format!("[{}]", items.join(",\n")));
    } else {
        for c in checks {
            let msg = format!("{}: {}", c.name, c.detail);
            match c.status {
                DoctorStatus::Pass => out.success(&msg),
                DoctorStatus::Warn => out.warning(&msg),
                DoctorStatus::Fail => out.error(&msg),
            }
        }
        let (mut p, mut w, mut f) = (0, 0, 0);
        checks.iter().for_each(|c| match c.status {
            DoctorStatus::Pass => p += 1,
            DoctorStatus::Warn => w += 1,
            DoctorStatus::Fail => f += 1,
        });
        out.result(&format!(
            "\n{} checks: {p} pass, {w} warn, {f} fail",
            checks.len()
        ));
    }
    out.flush();
}

/// FJ-2603: Check sandbox backend availability for `forjar test`.
fn check_sandbox_backends() -> DoctorCheck {
    use crate::core::store::convergence_runner::backend_available;
    use crate::core::types::SandboxBackend;

    let pepita = backend_available(SandboxBackend::Pepita);
    let container = backend_available(SandboxBackend::Container);
    let chroot = backend_available(SandboxBackend::Chroot);

    let mut available = Vec::new();
    if pepita {
        available.push("pepita");
    }
    if container {
        available.push("container");
    }
    if chroot {
        available.push("chroot");
    }

    if available.is_empty() {
        DoctorCheck {
            name: "sandbox".to_string(),
            status: DoctorStatus::Warn,
            detail: "no sandbox backends available (forjar test runs in simulated mode)"
                .to_string(),
        }
    } else {
        DoctorCheck {
            name: "sandbox".to_string(),
            status: DoctorStatus::Pass,
            detail: format!("backends: {}", available.join(", ")),
        }
    }
}
// FJ-251: forjar doctor — pre-flight system checker
pub(crate) fn cmd_doctor(file: Option<&Path>, json: bool, fix: bool) -> Result<(), String> {
    cmd_doctor_with_writer(file, json, fix, &mut super::output::StdoutWriter)
}
/// Inner doctor with injectable OutputWriter (FJ-2920).
pub(crate) fn cmd_doctor_with_writer(
    file: Option<&Path>,
    json: bool,
    fix: bool,
    out: &mut dyn super::output::OutputWriter,
) -> Result<(), String> {
    let mut checks = vec![check_bash()];
    let config: Option<types::ForjarConfig> = if let Some(f) = file {
        match parser::parse_and_validate(f) {
            Ok(c) => Some(c),
            Err(e) => {
                checks.push(DoctorCheck {
                    name: "config".to_string(),
                    status: DoctorStatus::Fail,
                    detail: format!("parse error: {e}"),
                });
                None
            }
        }
    } else {
        None
    };

    let has_ssh_machines = config
        .as_ref()
        .map(|c| {
            c.machines.values().any(|m| {
                m.transport.as_deref() != Some("container")
                    && m.addr != "127.0.0.1"
                    && m.addr != "localhost"
                    && m.addr != "container"
            })
        })
        .unwrap_or(false);

    let has_container_machines = config
        .as_ref()
        .map(|c| {
            c.machines
                .values()
                .any(|m| m.transport.as_deref() == Some("container") || m.addr == "container")
        })
        .unwrap_or(false);

    let has_enc_markers = file
        .and_then(|f| std::fs::read_to_string(f).ok())
        .map(|content| secrets::has_encrypted_markers(&content))
        .unwrap_or(false);

    if has_ssh_machines {
        checks.push(check_ssh());
    }
    if has_container_machines {
        let runtime = config
            .as_ref()
            .and_then(|c| {
                c.machines
                    .values()
                    .find_map(|m| m.container.as_ref().map(|ct| ct.runtime.clone()))
            })
            .unwrap_or_else(|| "docker".to_string());
        checks.push(check_container_runtime(&runtime));
    }

    if has_enc_markers {
        checks.push(check_age_identity());
    }

    checks.extend(check_state_dir(fix));
    checks.push(check_git());
    checks.push(check_sandbox_backends());

    output_doctor_checks_to(&checks, json, out);

    let has_failures = checks.iter().any(|c| c.status == DoctorStatus::Fail);
    if has_failures {
        Err("doctor found failures".to_string())
    } else {
        Ok(())
    }
}

/// FJ-343: Doctor network check — test SSH to all machines.
pub(crate) fn cmd_doctor_network(file: Option<&Path>, json: bool) -> Result<(), String> {
    let config_path = file.unwrap_or_else(|| std::path::Path::new("forjar.yaml"));
    let config = parse_and_validate(config_path)?;

    let mut results: Vec<serde_json::Value> = Vec::new();

    for (name, machine) in &config.machines {
        let is_local = machine.addr == "127.0.0.1" || machine.addr == "localhost";

        let (status, latency_ms) = if is_local {
            ("reachable".to_string(), 0u64)
        } else {
            let start = std::time::Instant::now();
            let user_host = format!("{}@{}", machine.user, machine.addr);
            let mut ssh_args = vec!["-o", "BatchMode=yes", "-o", "ConnectTimeout=5"];
            if let Some(ref key) = machine.ssh_key {
                ssh_args.push("-i");
                ssh_args.push(key);
            }
            ssh_args.push(&user_host);
            ssh_args.push("echo");
            ssh_args.push("ok");
            let result = std::process::Command::new("ssh")
                .args(&ssh_args)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status();
            let elapsed = start.elapsed().as_millis() as u64;
            match result {
                Ok(s) if s.success() => ("reachable".to_string(), elapsed),
                _ => ("unreachable".to_string(), elapsed),
            }
        };

        if json {
            results.push(serde_json::json!({
                "machine": name,
                "addr": machine.addr,
                "status": status,
                "latency_ms": latency_ms,
            }));
        } else {
            let icon = if status == "reachable" {
                green("")
            } else {
                red("")
            };
            println!(
                "  {} {} ({}) — {} ({}ms)",
                icon, name, machine.addr, status, latency_ms
            );
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&results).unwrap_or_default()
        );
    }

    Ok(())
}