fledge 1.3.0

Dev lifecycle CLI. One tool for the dev loop, any language.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
use anyhow::{bail, Context, Result};
use console::style;
use std::collections::{BTreeMap, HashSet};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use super::{
    evaluate_when, format_duration, step_description, LaneDef, ParallelItem, Step, TaskDef,
    DEFAULT_RETRY_DELAY_SECS, LANES_RUN_SCHEMA,
};

pub(crate) fn execute_lane(
    lane_name: &str,
    lane: &LaneDef,
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
    json: bool,
    from_index: Option<usize>,
) -> Result<()> {
    if json {
        return execute_lane_json(lane_name, lane, tasks, project_dir, from_index);
    }

    let desc = lane.description.as_deref().unwrap_or("(no description)");
    println!(
        "{} {}{}",
        style("▶️ Lane:").cyan().bold(),
        style(lane_name).bold(),
        style(desc).dim()
    );
    if let Some(fi) = from_index {
        println!("  {} starting from step {}", style("").dim(), fi + 1);
    }

    let total_steps = lane.steps.len();
    let mut failures: Vec<String> = Vec::new();
    let lane_start = Instant::now();

    for (i, step) in lane.steps.iter().enumerate() {
        if from_index.is_some_and(|fi| i < fi) {
            println!(
                "  {} Step {} {}",
                style("").dim(),
                i + 1,
                style("(skipped by --from)").dim()
            );
            continue;
        }

        if let Some(when) = step.when() {
            if !evaluate_when(when) {
                println!(
                    "  {} Step {} {} {}",
                    style("").dim(),
                    i + 1,
                    step_description(step),
                    style(format!("(skipped: when '{when}' not met)")).dim()
                );
                continue;
            }
        }

        let retries = step.retries().unwrap_or(0);
        let timeout = step.timeout();
        let retry_delay = step.retry_delay().unwrap_or(DEFAULT_RETRY_DELAY_SECS);
        let step_start = Instant::now();

        let mut last_err = None;
        for attempt in 0..=retries {
            if attempt > 0 {
                std::thread::sleep(Duration::from_secs(retry_delay));
                println!(
                    "  {} Retry {}/{} for step {}",
                    style("").yellow(),
                    attempt,
                    retries,
                    i + 1
                );
            }
            let deadline = timeout.map(|t| Instant::now() + Duration::from_secs(t));
            let result = execute_step_core(step, tasks, project_dir, false, deadline);
            match result {
                Ok(()) => {
                    last_err = None;
                    break;
                }
                Err(e) => {
                    last_err = Some(e);
                }
            }
        }

        let elapsed = step_start.elapsed();

        if let Some(e) = last_err {
            let step_desc = step_description(step);
            if lane.fail_fast {
                bail!(
                    "Lane '{}' failed at step {} ({}) after {}: {}",
                    lane_name,
                    i + 1,
                    step_desc,
                    format_duration(elapsed),
                    e
                );
            }
            eprintln!(
                "  {} Step {} ({}) failed after {}: {}",
                style("").red().bold(),
                i + 1,
                step_desc,
                format_duration(elapsed),
                e
            );
            failures.push(step_desc);
        } else {
            println!(
                "  {} Step {} done {}",
                style("").green(),
                i + 1,
                style(format!("({})", format_duration(elapsed))).dim()
            );
        }
    }

    let total_elapsed = lane_start.elapsed();

    if failures.is_empty() {
        println!(
            "{} Lane {} completed ({} steps in {})",
            style("").green().bold(),
            style(lane_name).green(),
            total_steps,
            format_duration(total_elapsed)
        );
    } else {
        bail!(
            "Lane '{}' completed with {} failure(s) in {}: {}",
            lane_name,
            failures.len(),
            format_duration(total_elapsed),
            failures.join(", ")
        );
    }

    Ok(())
}

fn execute_lane_json(
    lane_name: &str,
    lane: &LaneDef,
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
    from_index: Option<usize>,
) -> Result<()> {
    let total_steps = lane.steps.len();
    let mut step_results: Vec<serde_json::Value> = Vec::new();
    let mut failures: Vec<String> = Vec::new();
    let lane_start = Instant::now();

    for (i, step) in lane.steps.iter().enumerate() {
        let step_desc = step_description(step);

        if from_index.is_some_and(|fi| i < fi) {
            step_results.push(serde_json::json!({
                "step": i + 1,
                "name": step_desc,
                "success": serde_json::Value::Null,
                "duration_ms": serde_json::Value::Null,
                "error": serde_json::Value::Null,
                "skipped": true,
                "reason": "--from",
            }));
            continue;
        }

        if let Some(when) = step.when() {
            if !evaluate_when(when) {
                step_results.push(serde_json::json!({
                    "step": i + 1,
                    "name": step_desc,
                    "success": serde_json::Value::Null,
                    "duration_ms": serde_json::Value::Null,
                    "error": serde_json::Value::Null,
                    "skipped": true,
                    "reason": format!("when '{}' not met", when),
                }));
                continue;
            }
        }

        let retries = step.retries().unwrap_or(0);
        let timeout = step.timeout();
        let retry_delay = step.retry_delay().unwrap_or(DEFAULT_RETRY_DELAY_SECS);
        let step_start = Instant::now();

        let mut attempts = 0u32;
        let mut last_err = None;
        for attempt in 0..=retries {
            if attempt > 0 {
                std::thread::sleep(Duration::from_secs(retry_delay));
            }
            attempts = attempt + 1;
            let deadline = timeout.map(|t| Instant::now() + Duration::from_secs(t));
            let result = execute_step_core(step, tasks, project_dir, true, deadline);
            match result {
                Ok(()) => {
                    last_err = None;
                    break;
                }
                Err(e) => {
                    last_err = Some(e);
                }
            }
        }

        let elapsed = step_start.elapsed();
        let success = last_err.is_none();
        let error_msg = last_err.map(|e| e.to_string());

        let mut entry = serde_json::json!({
            "step": i + 1,
            "name": step_desc,
            "success": success,
            "duration_ms": elapsed.as_millis() as u64,
            "error": error_msg,
        });
        if attempts > 1 {
            entry["attempts"] = serde_json::json!(attempts);
        }

        step_results.push(entry);

        if !success {
            failures.push(step_desc.clone());
            if lane.fail_fast {
                break;
            }
        }
    }

    let total_elapsed = lane_start.elapsed();
    let success = failures.is_empty();

    let mut output = serde_json::json!({
        "schema_version": LANES_RUN_SCHEMA,
        "lane": lane_name,
        "description": lane.description.as_deref().unwrap_or(""),
        "total_steps": total_steps,
        "success": success,
        "duration_ms": total_elapsed.as_millis() as u64,
        "fail_fast": lane.fail_fast,
        "steps": step_results,
        "failures": failures,
    });
    if let Some(fi) = from_index {
        output["from_step"] = serde_json::json!(fi + 1);
    }

    println!("{}", serde_json::to_string_pretty(&output)?);

    if !success {
        bail!(
            "Lane '{}' completed with {} failure(s)",
            lane_name,
            failures.len()
        );
    }

    Ok(())
}

/// Execute a lane with no console output. Used by internal callers like
/// `release --pre-lane` and the watch task runner where lane prose would
/// pollute the agent's stdout or trigger noisy re-runs. Honors `when`,
/// `timeout`, and `retries` (including the inter-attempt 1s delay, which
/// is silent here — callers in watch mode may see unexplained delays on
/// flaky steps). Deliberately omits `--from`: that flag is user-facing
/// only and silent execution paths always run from step 1.
pub(crate) fn execute_lane_silent(
    lane_name: &str,
    lane: &LaneDef,
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
) -> Result<()> {
    let mut failures: Vec<String> = Vec::new();

    for (i, step) in lane.steps.iter().enumerate() {
        if let Some(when) = step.when() {
            if !evaluate_when(when) {
                continue;
            }
        }

        let retries = step.retries().unwrap_or(0);
        let timeout = step.timeout();
        let retry_delay = step.retry_delay().unwrap_or(DEFAULT_RETRY_DELAY_SECS);

        let mut last_err = None;
        for attempt in 0..=retries {
            if attempt > 0 {
                std::thread::sleep(Duration::from_secs(retry_delay));
            }
            let deadline = timeout.map(|t| Instant::now() + Duration::from_secs(t));
            let result = execute_step_core(step, tasks, project_dir, true, deadline);
            match result {
                Ok(()) => {
                    last_err = None;
                    break;
                }
                Err(e) => {
                    last_err = Some(e);
                }
            }
        }

        if let Some(e) = last_err {
            let step_desc = step_description(step);
            if lane.fail_fast {
                bail!(
                    "Lane '{}' failed at step {} ({}): {}",
                    lane_name,
                    i + 1,
                    step_desc,
                    e
                );
            }
            failures.push(step_desc);
        }
    }

    if !failures.is_empty() {
        bail!(
            "Lane '{}' completed with {} failure(s)",
            lane_name,
            failures.len()
        );
    }

    Ok(())
}

fn execute_step_core(
    step: &Step,
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
    quiet: bool,
    deadline: Option<Instant>,
) -> Result<()> {
    match step {
        Step::TaskRef(name) | Step::TaskRefFull { task: name, .. } => {
            execute_task_with_deps(name, tasks, project_dir, quiet, deadline)
        }
        Step::Inline { run: cmd, .. } => execute_inline(cmd, project_dir, quiet, deadline),
        Step::Parallel { parallel, .. } => {
            execute_parallel(parallel, tasks, project_dir, quiet, deadline)
        }
    }
}

pub(crate) fn execute_task_with_deps(
    name: &str,
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
    quiet: bool,
    deadline: Option<Instant>,
) -> Result<()> {
    if let Some(d) = deadline {
        if Instant::now() >= d {
            bail!("step timed out");
        }
    }
    let mut visited = HashSet::new();
    execute_task_recursive(name, tasks, project_dir, &mut visited, quiet, deadline)
}

fn execute_task_recursive(
    name: &str,
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
    visited: &mut HashSet<String>,
    quiet: bool,
    deadline: Option<Instant>,
) -> Result<()> {
    if !visited.insert(name.to_string()) {
        bail!(
            "Circular dependency detected: task '{}' depends on itself (chain: {})",
            name,
            visited.iter().cloned().collect::<Vec<_>>().join("")
        );
    }

    let task = tasks
        .get(name)
        .ok_or_else(|| anyhow::anyhow!("Task '{}' not found", name))?;

    for dep in task.deps() {
        execute_task_recursive(dep, tasks, project_dir, visited, quiet, deadline)?;
    }

    execute_single_task(name, task, project_dir, quiet, deadline)
}

fn execute_single_task(
    name: &str,
    task: &TaskDef,
    project_dir: &Path,
    quiet: bool,
    deadline: Option<Instant>,
) -> Result<()> {
    if !quiet {
        println!(
            "  {} {}",
            style("▶️").cyan().bold(),
            style(format!("Running task: {name}")).bold()
        );
    }

    let cmd_str = task.cmd();
    let work_dir = match task.dir() {
        Some(d) => project_dir.join(d),
        None => project_dir.to_path_buf(),
    };

    let shell = if cfg!(windows) { "cmd" } else { "sh" };
    let flag = if cfg!(windows) { "/C" } else { "-c" };

    let mut command = Command::new(shell);
    command.arg(flag).arg(cmd_str).current_dir(&work_dir);

    for (key, value) in task.env() {
        command.env(key, value);
    }

    if quiet {
        command.stdout(std::process::Stdio::null());
        command.stderr(std::process::Stdio::null());
    }

    let status = run_command_with_deadline(&mut command, deadline)
        .with_context(|| format!("running task '{name}'"))?;

    if !status.success() {
        let code = status.code().unwrap_or(1);
        bail!("Task '{}' failed with exit code {}", name, code);
    }

    Ok(())
}

fn execute_inline(
    cmd: &str,
    project_dir: &Path,
    quiet: bool,
    deadline: Option<Instant>,
) -> Result<()> {
    if !quiet {
        println!(
            "  {} {}",
            style("▶️").cyan().bold(),
            style(format!("Running: {cmd}")).bold()
        );
    }

    let shell = if cfg!(windows) { "cmd" } else { "sh" };
    let flag = if cfg!(windows) { "/C" } else { "-c" };

    let mut command = Command::new(shell);
    command.arg(flag).arg(cmd).current_dir(project_dir);
    if quiet {
        command.stdout(std::process::Stdio::null());
        command.stderr(std::process::Stdio::null());
    }

    let status = run_command_with_deadline(&mut command, deadline)
        .with_context(|| format!("running inline command: {cmd}"))?;

    if !status.success() {
        let code = status.code().unwrap_or(1);
        bail!("Inline command failed with exit code {}: {}", code, cmd);
    }

    Ok(())
}

fn execute_parallel(
    items: &[ParallelItem],
    tasks: &BTreeMap<String, TaskDef>,
    project_dir: &Path,
    quiet: bool,
    deadline: Option<Instant>,
) -> Result<()> {
    let names_display: Vec<String> = items
        .iter()
        .map(|item| match item {
            ParallelItem::TaskRef(name) => name.clone(),
            ParallelItem::Inline { run: cmd } => cmd.clone(),
        })
        .collect();
    if !quiet {
        println!(
            "  {} {}",
            style("▶️").cyan().bold(),
            style(format!("Running parallel: {}", names_display.join(", "))).bold()
        );
    }

    let errors: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));

    thread::scope(|s| {
        let mut handles = Vec::new();

        for item in items {
            let errors = Arc::clone(&errors);
            let handle = s.spawn(move || {
                let result = match item {
                    ParallelItem::TaskRef(name) => {
                        execute_task_with_deps(name, tasks, project_dir, quiet, deadline)
                    }
                    ParallelItem::Inline { run: cmd } => {
                        execute_inline(cmd, project_dir, quiet, deadline)
                    }
                };
                if let Err(e) = result {
                    let label = match item {
                        ParallelItem::TaskRef(name) => name.clone(),
                        ParallelItem::Inline { run: cmd } => cmd.clone(),
                    };
                    if let Ok(mut errs) = errors.lock() {
                        errs.push(format!("{}: {}", label, e));
                    }
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            if let Err(panic_val) = handle.join() {
                let panic_msg = panic_val
                    .downcast_ref::<&str>()
                    .copied()
                    .or_else(|| panic_val.downcast_ref::<String>().map(|s| s.as_str()))
                    .unwrap_or("unknown panic");
                if let Ok(mut errs) = errors.lock() {
                    errs.push(format!("thread panic: {}", panic_msg));
                }
            }
        }
    });

    let errs = errors.lock().unwrap_or_else(|e| e.into_inner());
    if !errs.is_empty() {
        bail!("Parallel step failed:\n  {}", errs.join("\n  "));
    }

    Ok(())
}

fn run_command_with_deadline(
    command: &mut Command,
    deadline: Option<Instant>,
) -> Result<std::process::ExitStatus> {
    match deadline {
        Some(d) => {
            if Instant::now() >= d {
                bail!("step timed out");
            }

            // Reap entire process tree on timeout. Without this, a shell
            // command like `sh -c "echo a && sleep 30"` would leave
            // grandchildren running after the direct child is killed.
            //
            // - Unix: spawn in a fresh process group, signal it with
            //   `killpg(SIGKILL)` on timeout.
            // - Windows: assign the child to a Job Object; on timeout,
            //   `TerminateJobObject` kills every process in the job tree.
            //   The job is configured with NO limit flags — children that
            //   outlive the parent on a successful exit are NOT reaped
            //   when the job handle drops, matching the Unix semantic.
            #[cfg(unix)]
            command.process_group(0);
            let mut child = command.spawn().context("spawning command")?;
            #[cfg(unix)]
            let pgid = child.id() as libc::pid_t;
            #[cfg(windows)]
            let job = setup_windows_job(&child);

            loop {
                // RAII (`#[cfg(windows)] _job: Some(JobHandle)`) closes the
                // job handle on every exit path including the `?` propagation
                // from `try_wait`, preventing a Windows handle leak.
                match child.try_wait().context("waiting for command")? {
                    Some(status) => return Ok(status),
                    None => {
                        if Instant::now() >= d {
                            #[cfg(unix)]
                            // SAFETY: killpg(pgid, SIGKILL) — pgid is the child's own
                            // pgid (set via process_group(0) above) and SIGKILL has no
                            // signal handler to invoke.
                            unsafe {
                                libc::killpg(pgid, libc::SIGKILL);
                            }
                            #[cfg(windows)]
                            match &job {
                                Some(j) => j.terminate(),
                                None => {
                                    let _ = child.kill();
                                }
                            }
                            let _ = child.wait();
                            bail!("step timed out");
                        }
                        std::thread::sleep(Duration::from_millis(50));
                    }
                }
            }
        }
        None => Ok(command.status()?),
    }
}

/// RAII wrapper for a Win32 Job Object handle. Drop closes the handle.
/// The job is configured with no limit flags — closing the handle does
/// not kill members; only an explicit `terminate()` does. This keeps the
/// Windows path's behavior aligned with Unix: tree reaping fires on
/// timeout, never on successful exit (so a step that intentionally
/// backgrounds a daemon does not get its daemon killed).
#[cfg(windows)]
struct JobHandle(windows_sys::Win32::Foundation::HANDLE);

#[cfg(windows)]
impl JobHandle {
    fn terminate(&self) {
        // SAFETY: self.0 is a valid job handle owned by this guard for the
        // lifetime of the borrow; TerminateJobObject is documented to be
        // safe to call on a valid handle. Exit code 1 stands for the
        // synthetic kill.
        unsafe {
            windows_sys::Win32::System::JobObjects::TerminateJobObject(self.0, 1);
        }
    }
}

#[cfg(windows)]
impl Drop for JobHandle {
    fn drop(&mut self) {
        // SAFETY: self.0 is a valid handle returned by CreateJobObjectW
        // and never closed elsewhere — Drop is the single owner of the
        // close call.
        unsafe {
            windows_sys::Win32::Foundation::CloseHandle(self.0);
        }
    }
}

/// Wrap the spawned child in a Job Object so that `TerminateJobObject`
/// reaps the entire process tree on timeout. The race window between
/// `spawn` and `AssignProcessToJobObject` is small for typical shell
/// invocations — a child rarely spawns grandchildren before the assign
/// call lands a few microseconds later. If setup fails (rare; would
/// require resource exhaustion), returns `None` and the timeout path
/// falls back to `child.kill()` which only signals the direct child.
#[cfg(windows)]
fn setup_windows_job(child: &std::process::Child) -> Option<JobHandle> {
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Foundation::HANDLE;
    use windows_sys::Win32::System::JobObjects::{AssignProcessToJobObject, CreateJobObjectW};

    // SAFETY: CreateJobObjectW with null name returns a fresh unnamed job
    // handle or null on failure.
    let job: HANDLE = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
    if job.is_null() {
        return None;
    }
    let guard = JobHandle(job);

    // SAFETY: child's raw handle is valid for the duration of the Child borrow;
    // AssignProcessToJobObject does not retain the handle past the call.
    let assigned = unsafe { AssignProcessToJobObject(job, child.as_raw_handle() as HANDLE) };
    if assigned == 0 {
        // guard's Drop closes the job handle on this path
        return None;
    }

    Some(guard)
}