lux-blueprint 0.2.5

Blueprint DSL parser, transpiler, and executor for luxctl
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
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
use crate::executor::context::{Context, ExecutionMode};
use crate::executor::error::ExecutionError;
use crate::executor::expect::{evaluate_expectations, evaluate_input, process_captures};
use crate::executor::probes::execute_probe;
use crate::transpiler::ir::*;
use crate::transpiler::validate::topological_sort;
use log::debug;
use std::collections::{HashMap, HashSet};
use std::time::Instant;

pub struct Engine {
    pub ctx: Context,
    task_slug: Option<String>,
}

impl Engine {
    pub fn new(ctx: Context) -> Self {
        Self {
            ctx,
            task_slug: None,
        }
    }

    pub fn with_task(mut self, slug: &str) -> Self {
        self.task_slug = Some(slug.to_string());
        self
    }

    pub async fn execute(&mut self, bp: &Blueprint) -> Result<BlueprintResult, ExecutionError> {
        let start = Instant::now();

        let phase_order =
            topological_sort(&bp.phases).map_err(|e| ExecutionError::new(e.to_string()))?;

        let phase_map: HashMap<&str, &Phase> =
            bp.phases.iter().map(|p| (p.name.as_str(), p)).collect();

        let mut phase_results = Vec::new();
        let mut failed_phases: HashSet<String> = HashSet::new();
        let mut overall_status = Status::Passed;

        for phase_name in &phase_order {
            let phase = match phase_map.get(phase_name.as_str()) {
                Some(p) => p,
                None => continue,
            };

            if phase.depends_on.iter().any(|d| failed_phases.contains(d)) {
                failed_phases.insert(phase_name.clone());
                phase_results.push(PhaseResult {
                    name: phase_name.clone(),
                    slug: phase.meta.slug.clone(),
                    status: Status::Skipped,
                    steps: Vec::new(),
                    duration_ms: 0,
                });
                continue;
            }

            let phase_result = self.execute_phase(phase).await?;
            if phase_result.status == Status::Failed {
                failed_phases.insert(phase_name.clone());
                overall_status = Status::Failed;
            }
            phase_results.push(phase_result);
        }

        Ok(BlueprintResult {
            name: bp.name.clone(),
            status: overall_status,
            phases: phase_results,
            duration_ms: start.elapsed().as_millis() as u64,
            captured: self.ctx.variables.clone(),
            input_provided: self.ctx.user_inputs.clone(),
        })
    }

    async fn execute_phase(&mut self, phase: &Phase) -> Result<PhaseResult, ExecutionError> {
        let start = Instant::now();
        let mut step_results = Vec::new();
        let mut phase_status = Status::Passed;

        debug!("phase: \"{}\" (slug: {:?})", phase.name, phase.meta.slug);

        // phase-level slug filtering: skip entire phase if slug doesn't match
        if let Some(ref slug) = self.task_slug {
            if let Some(ref phase_slug) = phase.meta.slug {
                if phase_slug != slug {
                    debug!("  skipping phase (slug mismatch: want={}, got={})", slug, phase_slug);
                    return Ok(PhaseResult {
                        name: phase.name.clone(),
                        slug: phase.meta.slug.clone(),
                        status: Status::Skipped,
                        steps: Vec::new(),
                        duration_ms: 0,
                    });
                }
            }
        }

        for step in &phase.steps {
            // step-level slug filtering: only when phase has no slug (backward compat)
            if let Some(ref slug) = self.task_slug {
                if phase.meta.slug.is_none() {
                    if let Some(ref step_slug) = step.meta.slug {
                        if step_slug != slug {
                            continue;
                        }
                    }
                }
            }

            let has_input = !step.inputs.is_empty();
            match self.ctx.mode {
                ExecutionMode::Validate if has_input => {
                    step_results.push(skipped_step(&step.name));
                    continue;
                }
                ExecutionMode::Result if !has_input => {
                    step_results.push(skipped_step(&step.name));
                    continue;
                }
                _ => {}
            }

            if step.requires.iter().any(|var| !self.ctx.has_variable(var)) {
                step_results.push(skipped_step(&step.name));
                continue;
            }

            if has_input && self.ctx.mode == ExecutionMode::Result {
                for input_decl in &step.inputs {
                    if self.ctx.get_user_input(&input_decl.name).is_none() {
                        let slug_display = step.meta.slug.as_deref().unwrap_or(&step.name);
                        return Err(ExecutionError::new(format!(
                            "missing required flag: --{}\n  Run: luxctl result --task {} --{} <your value>",
                            input_decl.name, slug_display, input_decl.name
                        )));
                    }
                }
            }

            let step_result = self.execute_step_with_retry(step).await?;
            if step_result.status != Status::Passed && step_result.status != Status::Skipped {
                phase_status = Status::Failed;
            }
            step_results.push(step_result);
        }

        Ok(PhaseResult {
            name: phase.name.clone(),
            slug: phase.meta.slug.clone(),
            status: phase_status,
            steps: step_results,
            duration_ms: start.elapsed().as_millis() as u64,
        })
    }

    async fn execute_step_with_retry(&mut self, step: &Step) -> Result<StepResult, ExecutionError> {
        let max_attempts = step.retry.as_ref().map_or(1, |r| r.max_attempts);
        let delay = step.retry.as_ref().map(|r| r.delay);
        let mut last_result = None;

        for attempt in 0..max_attempts {
            let result = self.execute_step_once(step, attempt).await?;
            if result.status == Status::Passed {
                return Ok(result);
            }
            last_result = Some(result);
            if attempt + 1 < max_attempts {
                if let Some(d) = delay {
                    tokio::time::sleep(d).await;
                }
            }
        }

        Ok(last_result.unwrap_or_else(|| StepResult {
            name: step.name.clone(),
            status: Status::Failed,
            expectations: Vec::new(),
            captures: Vec::new(),
            input_matched: None,
            duration_ms: 0,
            retry_count: max_attempts,
        }))
    }

    async fn execute_step_once(
        &mut self,
        step: &Step,
        attempt: u32,
    ) -> Result<StepResult, ExecutionError> {
        let start = Instant::now();
        let timeout = step.timeout.or(Some(self.ctx.config.timeout));

        debug!(
            "  step: \"{}\" (timeout: {:?}, attempt: {})",
            step.name, timeout, attempt
        );
        debug!("    probe: {:?}", step.probe);

        // timeout is passed into exec probes so the child process is killed on expiry.
        // for non-exec probes, the outer tokio::time::timeout still applies.
        let probe_result = if let Some(t) = timeout {
            match tokio::time::timeout(t, execute_probe(&step.probe, &self.ctx, timeout)).await {
                Ok(result) => result?,
                Err(_) => {
                    return Ok(StepResult {
                        name: step.name.clone(),
                        status: Status::Error("probe timed out".to_string()),
                        expectations: Vec::new(),
                        captures: Vec::new(),
                        input_matched: None,
                        duration_ms: start.elapsed().as_millis() as u64,
                        retry_count: attempt,
                    });
                }
            }
        } else {
            execute_probe(&step.probe, &self.ctx, timeout).await?
        };

        debug!(
            "    probe result: exit={:?}, duration={}ms, stdout_len={}",
            probe_result.fields.get("exit"),
            probe_result.duration_ms,
            probe_result.raw_stdout.as_ref().map_or(0, |s| s.len()),
        );

        let has_input = !step.inputs.is_empty();
        let (expect_results, input_matched, captured) = if has_input
            && self.ctx.mode == ExecutionMode::Result
        {
            let input = &step.inputs[0];
            let user_value = self
                .ctx
                .get_user_input(&input.name)
                .unwrap_or("")
                .to_string();
            let (matched, exp_results) = evaluate_input(
                &input.name,
                &user_value,
                &step.expectations,
                &probe_result,
                &self.ctx,
            );
            let captured = process_captures(&step.captures, &probe_result, &mut self.ctx);
            (exp_results, Some(matched), captured)
        } else {
            let exp_results = evaluate_expectations(&step.expectations, &probe_result, &self.ctx);
            let captured = process_captures(&step.captures, &probe_result, &mut self.ctx);
            (exp_results, None, captured)
        };

        let all_passed = expect_results.iter().all(|r| r.status == Status::Passed);
        let input_ok = input_matched.unwrap_or(true);

        Ok(StepResult {
            name: step.name.clone(),
            status: if all_passed && input_ok {
                Status::Passed
            } else {
                Status::Failed
            },
            expectations: expect_results,
            captures: captured,
            input_matched,
            duration_ms: start.elapsed().as_millis() as u64,
            retry_count: attempt,
        })
    }
}

fn skipped_step(name: &str) -> StepResult {
    StepResult {
        name: name.to_string(),
        status: Status::Skipped,
        expectations: Vec::new(),
        captures: Vec::new(),
        input_matched: None,
        duration_ms: 0,
        retry_count: 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::grammar::parse;
    use crate::transpiler::resolve::transpile;

    async fn run_bp(input: &str, mode: ExecutionMode) -> BlueprintResult {
        let ast = parse(input).unwrap_or_else(|e| panic!("parse: {e}"));
        let bp = transpile(&ast).unwrap_or_else(|e| panic!("transpile: {e}"));
        let ctx = Context::new(bp.config.clone(), mode);
        let mut engine = Engine::new(ctx);
        engine
            .execute(&bp)
            .await
            .unwrap_or_else(|e| panic!("execute: {e}"))
    }

    #[tokio::test]
    async fn test_exec_probe_echo() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "echo" {
            probe exec echo hello
            expect { stdout: "hello" exit: 0 }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
    }

    #[tokio::test]
    async fn test_exec_exit_code() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "exit" {
            probe exec sh -c "exit 42"
            expect { exit: 42 }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
    }

    #[tokio::test]
    async fn test_phase_dependency_skipping() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "first" {
        step "fail" {
            probe exec sh -c "exit 1"
            expect { exit: 0 }
        }
    }
    phase "second" {
        depends-on: "first"
        step "skip" {
            probe exec echo "nope"
            expect { exit: 0 }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Failed);
        assert_eq!(r.phases[1].status, Status::Skipped);
    }

    #[tokio::test]
    async fn test_validate_skips_input_steps() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "probe only" {
            probe exec echo "hello"
            expect { exit: 0 }
        }
        step "with input" {
            input { answer: string }
            probe exec echo "world"
            expect { stdout: "world" }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
        assert_eq!(r.phases[0].steps[1].status, Status::Skipped);
    }

    #[tokio::test]
    async fn test_capture_flows() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "capture" {
            probe exec echo "abc123"
            expect {
                exit: 0
                capture stdout as $my_var
            }
        }
        step "use" {
            requires: $my_var
            probe exec echo $my_var
            expect { stdout: "abc123" exit: 0 }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
        assert!(r.captured.contains_key("$my_var"));
    }

    #[tokio::test]
    async fn test_requires_skips_when_missing() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "needs var" {
            requires: $nonexistent
            probe exec echo "hello"
            expect { exit: 0 }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.phases[0].steps[0].status, Status::Skipped);
    }

    #[tokio::test]
    async fn test_contains_operator() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "check" {
            probe exec echo "hello world foo"
            expect {
                stdout contains: "world"
                exit: 0
            }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
    }

    #[tokio::test]
    async fn test_regex_match() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "t" {
        step "regex" {
            probe exec echo "abc123"
            expect {
                stdout matches: /^[a-z]+\d+$/
                exit: 0
            }
        }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
    }

    #[tokio::test]
    async fn test_multiple_phases() {
        let r = run_bp(
            r#"
blueprint "T" {
    phase "a" {
        step "s1" { probe exec echo "1" expect { exit: 0 } }
    }
    phase "b" {
        depends-on: "a"
        step "s2" { probe exec echo "2" expect { exit: 0 } }
    }
    phase "c" {
        depends-on: "b"
        step "s3" { probe exec echo "3" expect { exit: 0 } }
    }
}
"#,
            ExecutionMode::Validate,
        )
        .await;
        assert_eq!(r.status, Status::Passed);
        assert_eq!(r.phases.len(), 3);
    }

    #[tokio::test]
    async fn test_file_probe() {
        let tmp = tempfile::NamedTempFile::new().unwrap_or_else(|e| panic!("{e}"));
        let path = tmp.path().to_string_lossy().to_string();
        let bp_str = format!(
            r#"
blueprint "T" {{
    phase "t" {{
        step "file" {{
            probe file {path}
            expect {{ exists: true }}
        }}
    }}
}}
"#
        );
        let r = run_bp(&bp_str, ExecutionMode::Validate).await;
        assert_eq!(r.status, Status::Passed);
    }
}