forjar 1.15.0

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
//! FJ-2301: Log viewer runtime — reads run logs from state/<machine>/runs/.
//!
//! Replaces the stub in dispatch_misc_b.rs with actual file I/O.
//! Reads `meta.yaml` and `*.log` files from the run directory structure.

use crate::core::types::RunMeta;
use std::path::Path;

/// A discovered run on disk.
#[derive(Debug)]
pub(crate) struct DiscoveredRun {
    pub(crate) machine: String,
    pub(crate) run_id: String,
    pub(crate) meta: RunMeta,
    pub(crate) run_dir: std::path::PathBuf,
}

/// Modification time of a run directory, in nanoseconds since the epoch.
///
/// Dogfood #208: the retention sort must be a TOTAL order. `started_at` alone
/// has second resolution (and is absent on runs written by older forjars), so
/// runs tie, the stable sort falls back to readdir/hash order, and `--gc`
/// deletes an arbitrary subset. mtime breaks the tie deterministically.
fn run_mtime_nanos(dir: &Path) -> u128 {
    std::fs::metadata(dir)
        .and_then(|m| m.modified())
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_nanos())
        .unwrap_or(0)
}

/// Discover all runs under a state directory, optionally filtered.
pub(crate) fn discover_runs(
    state_dir: &Path,
    machine_filter: Option<&str>,
    run_filter: Option<&str>,
    failures_only: bool,
) -> Vec<DiscoveredRun> {
    let mut runs = Vec::new();
    let entries = match std::fs::read_dir(state_dir) {
        Ok(e) => e,
        Err(_) => return runs,
    };

    for entry in entries.flatten() {
        let machine_dir = entry.path();
        if !machine_dir.is_dir() {
            continue;
        }
        let machine_name = entry.file_name().to_string_lossy().to_string();

        // Skip non-machine directories (images, etc.)
        if machine_name == "images" || machine_name.starts_with('.') {
            continue;
        }

        if let Some(filter) = machine_filter {
            if machine_name != filter {
                continue;
            }
        }

        let runs_dir = machine_dir.join("runs");
        if !runs_dir.is_dir() {
            continue;
        }

        let run_entries = match std::fs::read_dir(&runs_dir) {
            Ok(e) => e,
            Err(_) => continue,
        };

        for run_entry in run_entries.flatten() {
            let run_dir = run_entry.path();
            if !run_dir.is_dir() {
                continue;
            }
            let run_id = run_entry.file_name().to_string_lossy().to_string();

            if let Some(filter) = run_filter {
                if run_id != filter {
                    continue;
                }
            }

            let meta_path = run_dir.join("meta.yaml");
            let meta = if meta_path.exists() {
                match std::fs::read_to_string(&meta_path) {
                    Ok(content) => match serde_yaml_ng::from_str::<RunMeta>(&content) {
                        Ok(m) => m,
                        Err(_) => continue,
                    },
                    Err(_) => continue,
                }
            } else {
                continue;
            };

            if failures_only && meta.summary.failed == 0 {
                continue;
            }

            runs.push(DiscoveredRun {
                machine: machine_name.clone(),
                run_id,
                meta,
                run_dir,
            });
        }
    }

    sort_runs_newest_first(&mut runs);
    runs
}

/// Sort runs newest-first under a total order: started_at, then directory
/// mtime, then run id. Deterministic even when timestamps tie or are absent.
pub(crate) fn sort_runs_newest_first(runs: &mut [DiscoveredRun]) {
    let mtimes: std::collections::HashMap<String, u128> = runs
        .iter()
        .map(|r| (r.run_id.clone(), run_mtime_nanos(&r.run_dir)))
        .collect();
    runs.sort_by(|a, b| {
        let ka = (
            a.meta.started_at.as_deref().unwrap_or(""),
            mtimes.get(&a.run_id).copied().unwrap_or(0),
            a.run_id.as_str(),
        );
        let kb = (
            b.meta.started_at.as_deref().unwrap_or(""),
            mtimes.get(&b.run_id).copied().unwrap_or(0),
            b.run_id.as_str(),
        );
        kb.cmp(&ka)
    });
}

/// Read a specific log file content for a resource in a run.
fn read_log_file(run_dir: &Path, resource_id: &str, action: &str) -> Option<String> {
    let log_path = run_dir.join(format!("{resource_id}.{action}.log"));
    std::fs::read_to_string(&log_path).ok()
}

/// Actions actually recorded on disk for `resource_id` in this run.
///
/// Dogfood #208 (logs-resource-filter-drops-the-matching-resource): the filter
/// used to probe a hardcoded `apply`/`check`/`destroy` action list, but forjar
/// writes the PLANNED action (`create`, `update`, `delete`, …). Every probe
/// missed, so `--resource <existing>` was byte-identical to
/// `--resource <nonexistent>`: all rows suppressed, rc=0. Discover the actions
/// from the run directory instead of guessing them.
pub(crate) fn actions_for_resource(run_dir: &Path, resource_id: &str) -> Vec<String> {
    list_log_files(run_dir)
        .into_iter()
        .filter(|(res, _)| res == resource_id)
        .map(|(_, action)| action)
        .collect()
}

/// Read the script file for a resource in a run.
fn read_script_file(run_dir: &Path, resource_id: &str) -> Option<String> {
    let script_path = run_dir.join(format!("{resource_id}.script"));
    std::fs::read_to_string(&script_path).ok()
}

/// List all .log files in a run directory.
fn list_log_files(run_dir: &Path) -> Vec<(String, String)> {
    let mut logs = Vec::new();
    let entries = match std::fs::read_dir(run_dir) {
        Ok(e) => e,
        Err(_) => return logs,
    };
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if let Some(stem) = name.strip_suffix(".log") {
            if let Some((resource, action)) = stem.rsplit_once('.') {
                logs.push((resource.to_string(), action.to_string()));
            }
        }
    }
    logs.sort();
    logs
}

/// FJ-2301: Log viewer — reads actual run logs from disk.
#[allow(clippy::too_many_arguments)]
pub(crate) fn cmd_logs(
    state_dir: &Path,
    machine: Option<&str>,
    run: Option<&str>,
    resource: Option<&str>,
    failures: bool,
    show_script: bool,
    all_machines: bool,
    json: bool,
) -> Result<(), String> {
    let machine_filter = if all_machines { None } else { machine };
    let runs = discover_runs(state_dir, machine_filter, run, failures);

    if json {
        print_logs_json(&runs, resource, show_script)
    } else {
        print_logs_text(&runs, resource, show_script)
    }
}

fn print_logs_text(
    runs: &[DiscoveredRun],
    resource_filter: Option<&str>,
    show_script: bool,
) -> Result<(), String> {
    if runs.is_empty() {
        println!("No run logs found.");
        println!("  (run `forjar apply` to generate logs in state/<machine>/runs/)");
        return Ok(());
    }

    for run in runs {
        let meta = &run.meta;
        let started = meta.started_at.as_deref().unwrap_or("unknown");
        let gen = meta
            .generation
            .map(|g| format!(", gen {g}"))
            .unwrap_or_default();
        println!(
            "\nRun {} ({}{}) on {}",
            run.run_id, started, gen, run.machine
        );
        print_run_summary(&meta.summary);

        if let Some(res_id) = resource_filter {
            print_resource_log(&run.run_dir, res_id, show_script);
        } else {
            let log_files = list_log_files(&run.run_dir);
            for (res_id, action) in &log_files {
                let status = meta.resources.get(res_id);
                let status_str = match status {
                    Some(crate::core::types::ResourceRunStatus::Noop) => "noop",
                    Some(crate::core::types::ResourceRunStatus::Converged {
                        failed: true, ..
                    }) => "FAILED",
                    Some(crate::core::types::ResourceRunStatus::Converged { .. }) => "converged",
                    Some(crate::core::types::ResourceRunStatus::Skipped { .. }) => "skipped",
                    None => "unknown",
                };
                println!("  {res_id} ({action}) — {status_str}");
                // Dogfood #208 (logs-script-flag-noop): --script must add the
                // executed script to the output. It used to be byte-identical
                // to plain `logs`.
                if show_script {
                    match read_script_file(&run.run_dir, res_id) {
                        Some(script) if !script.is_empty() => {
                            println!("    --- {res_id}.script ---");
                            for line in script.lines() {
                                println!("    {line}");
                            }
                        }
                        _ => println!("    (no script recorded)"),
                    }
                }
            }
        }
    }
    Ok(())
}

fn print_run_summary(summary: &crate::core::types::RunSummary) {
    println!(
        "  {} total: {} converged, {} noop, {} failed, {} skipped",
        summary.total, summary.converged, summary.noop, summary.failed, summary.skipped,
    );
}

fn print_resource_log(run_dir: &Path, resource_id: &str, show_script: bool) {
    let actions = actions_for_resource(run_dir, resource_id);
    if actions.is_empty() {
        println!("  (no log for resource '{resource_id}' in this run)");
        return;
    }
    for action in &actions {
        if let Some(content) = read_log_file(run_dir, resource_id, action) {
            println!("\n--- {resource_id}.{action}.log ---");
            println!("{content}");
        }
    }
    if show_script {
        match read_script_file(run_dir, resource_id) {
            Some(script) if !script.is_empty() => {
                println!("\n--- {resource_id}.script ---");
                println!("{script}");
            }
            _ => println!("  (no script recorded for '{resource_id}')"),
        }
    }
}

fn print_logs_json(
    runs: &[DiscoveredRun],
    resource_filter: Option<&str>,
    show_script: bool,
) -> Result<(), String> {
    let mut entries = Vec::new();
    for run in runs {
        let mut run_obj = serde_json::json!({
            "run_id": run.run_id,
            "machine": run.machine,
            "command": run.meta.command,
            "started_at": run.meta.started_at,
            "finished_at": run.meta.finished_at,
            "duration_secs": run.meta.duration_secs,
            "generation": run.meta.generation,
            "summary": {
                "total": run.meta.summary.total,
                "converged": run.meta.summary.converged,
                "noop": run.meta.summary.noop,
                "failed": run.meta.summary.failed,
                "skipped": run.meta.summary.skipped,
            },
        });

        if let Some(res_id) = resource_filter {
            let mut logs = serde_json::Map::new();
            for action in &["apply", "check", "destroy"] {
                if let Some(content) = read_log_file(&run.run_dir, res_id, action) {
                    logs.insert(format!("{action}_log"), serde_json::Value::String(content));
                }
            }
            if show_script {
                if let Some(script) = read_script_file(&run.run_dir, res_id) {
                    logs.insert("script".into(), serde_json::Value::String(script));
                }
            }
            run_obj["resource_logs"] = serde_json::Value::Object(logs);
        } else {
            let log_files = list_log_files(&run.run_dir);
            let file_list: Vec<String> = log_files
                .iter()
                .map(|(r, a)| format!("{r}.{a}.log"))
                .collect();
            run_obj["log_files"] = serde_json::json!(file_list);
            if show_script {
                let mut scripts = serde_json::Map::new();
                for (res_id, _) in &log_files {
                    let body = read_script_file(&run.run_dir, res_id).unwrap_or_default();
                    scripts.insert(res_id.clone(), serde_json::Value::String(body));
                }
                run_obj["scripts"] = serde_json::Value::Object(scripts);
            }
        }
        entries.push(run_obj);
    }

    let output = serde_json::json!({ "runs": entries });
    println!(
        "{}",
        serde_json::to_string_pretty(&output).unwrap_or_default()
    );
    Ok(())
}

/// FJ-2301: Follow mode — tail a run's log directory until interrupted.
///
/// Dogfood #208 (logs-follow-does-not-follow-and-ignores-run): this used to
/// print a "watching …" banner and return in ~5ms without streaming a byte,
/// and it resolved the target as "newest" before consulting `--run`, so
/// `--follow --run <older>` silently watched a different run.
pub(crate) fn cmd_logs_follow(
    state_dir: &Path,
    machine: Option<&str>,
    run: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let Some(target) = resolve_follow_target(state_dir, machine, run, json)? else {
        return Ok(());
    };
    super::logs_follow::tail_run_dir(
        &target.run_dir,
        json,
        &mut super::logs_follow::Forever,
        std::time::Duration::from_millis(400),
    );
    Ok(())
}

/// Resolve which run `--follow` should watch, and print the banner.
///
/// Dogfood #208: `--run` is consulted BEFORE "newest wins". An explicit run id
/// that matches nothing is an error, not a silent fallback to another run.
/// Returns `Ok(None)` when there is simply nothing to follow yet.
pub(crate) fn resolve_follow_target(
    state_dir: &Path,
    machine: Option<&str>,
    run: Option<&str>,
    json: bool,
) -> Result<Option<DiscoveredRun>, String> {
    let mut runs = discover_runs(state_dir, machine, run, false);
    if runs.is_empty() {
        if let Some(requested) = run {
            return Err(format!(
                "no run logs found for run id '{requested}' (see `forjar logs` for known run ids)"
            ));
        }
        if json {
            let output = serde_json::json!({
                "action": "follow",
                "status": "no_runs",
                "message": "no run logs found to follow",
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&output).unwrap_or_default()
            );
        } else {
            println!("Follow mode: no run logs found.");
            println!("  Start `forjar apply` in another terminal to generate logs.");
        }
        return Ok(None);
    }

    let latest = runs.remove(0);
    if json {
        let output = serde_json::json!({
            "action": "follow",
            "status": "watching",
            "run_id": latest.run_id,
            "machine": latest.machine,
            "run_dir": latest.run_dir.display().to_string(),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&output).unwrap_or_default()
        );
    } else {
        println!(
            "Follow mode: watching {}/{} ({})",
            latest.machine,
            latest.run_id,
            latest.run_dir.display()
        );
        println!("  Press Ctrl+C to stop.");
    }
    Ok(Some(latest))
}