runkon-flow 0.1.0-alpha

Portable workflow execution engine — DSL, traits, and in-memory reference implementations
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
use std::collections::HashMap;
use std::thread;
use std::time::Duration;

use crate::dsl::{GateNode, GateOptions, GateType, OnFailAction, OnTimeout};
use crate::engine::{emit_event, restore_step, should_skip, ExecutionState};
use crate::engine_error::{EngineError, Result};
use crate::events::EngineEvent;
use crate::status::{WorkflowRunStatus, WorkflowStepStatus};
use crate::traits::persistence::{GateApprovalState, StepUpdate};

fn resume_run_status(state: &ExecutionState, gate_name: &str, context: &str) {
    if let Err(e) = state.persistence.update_run_status(
        &state.workflow_run_id,
        WorkflowRunStatus::Running,
        None,
        None,
    ) {
        tracing::warn!("Gate '{gate_name}': failed to update run status {context}: {e}");
    }
}

pub fn execute_gate(state: &mut ExecutionState, node: &GateNode, iteration: u32) -> Result<()> {
    let pos = state.position;
    state.position += 1;

    // Skip completed gates on resume — restore feedback for downstream steps
    if should_skip(state, &node.name, iteration) {
        tracing::info!("Skipping completed gate '{}'", node.name);
        restore_step(state, &node.name, iteration);
        return Ok(());
    }

    // Quality gates evaluate immediately — no blocking/waiting.
    if node.gate_type == GateType::QualityGate {
        return execute_quality_gate(state, node, pos, iteration);
    }

    // Dry-run: auto-approve all gates
    if state.exec_config.dry_run {
        tracing::info!("gate '{}': dry-run auto-approved", node.name);
        super::insert_step_with_status(
            state,
            &node.name,
            "reviewer",
            pos,
            iteration,
            None,
            WorkflowStepStatus::Completed,
            Some("dry-run: auto-approved".to_string()),
        )?;
        return Ok(());
    }

    // Insert step and mark as waiting
    let step_id = super::insert_step_with_status(
        state,
        &node.name,
        "gate",
        pos,
        iteration,
        None,
        WorkflowStepStatus::Waiting,
        None,
    )?;

    emit_event(
        state,
        EngineEvent::GateWaiting {
            gate_name: node.name.clone(),
        },
    );

    // Resolve gate options (if any) — stored for future use by gate resolvers
    let _resolved_options: HashMap<String, String> = if let Some(ref gate_opts) = node.options {
        match gate_opts {
            GateOptions::Static(map) => map.clone(),
            GateOptions::StepRef(dotted) => {
                let dot = dotted.find('.').ok_or_else(|| {
                    EngineError::Workflow(format!(
                        "Gate '{}': options StepRef '{dotted}' must be in 'step.field' format",
                        node.name
                    ))
                })?;
                let step_key = &dotted[..dot];
                let field_key = &dotted[dot + 1..];
                let result = state.step_results.get(step_key).ok_or_else(|| {
                    EngineError::Workflow(format!(
                        "Gate '{}': options StepRef references step '{step_key}' which has no result yet",
                        node.name
                    ))
                })?;
                let json_str = result.structured_output.as_deref().ok_or_else(|| {
                    EngineError::Workflow(format!(
                        "Gate '{}': step '{step_key}' has no structured_output to extract field '{field_key}' from",
                        node.name
                    ))
                })?;
                let val: serde_json::Value = serde_json::from_str(json_str).map_err(|e| {
                    EngineError::Workflow(format!(
                        "Gate '{}': failed to parse structured_output of step '{step_key}': {e}",
                        node.name
                    ))
                })?;
                let obj = val.get(field_key).and_then(|v| v.as_object()).ok_or_else(|| {
                    EngineError::Workflow(format!(
                        "Gate '{}': field '{field_key}' in step '{step_key}' structured_output is not a JSON object",
                        node.name
                    ))
                })?;
                obj.iter()
                    .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                    .collect()
            }
        }
    } else {
        HashMap::new()
    };

    // Log human gate instructions before entering the poll loop.
    if matches!(
        node.gate_type,
        GateType::HumanApproval | GateType::HumanReview
    ) {
        tracing::info!("Gate '{}' waiting for human action:", node.name);
        if let Some(ref p) = node.prompt {
            tracing::info!("  Prompt: {p}");
        }
        tracing::info!(
            "  Approve:  conductor workflow gate-approve {}",
            state.workflow_run_id
        );
        tracing::info!(
            "  Reject:   conductor workflow gate-reject {}",
            state.workflow_run_id
        );
        if node.gate_type == GateType::HumanReview {
            tracing::info!(
                "  Feedback: conductor workflow gate-feedback {} \"<text>\"",
                state.workflow_run_id
            );
        }
    } else if node.gate_type == GateType::PrApproval {
        tracing::info!("Gate '{}' polling for PR approvals...", node.name);
    } else if node.gate_type == GateType::PrChecks {
        tracing::info!("Gate '{}' polling for PR checks...", node.name);
    }

    // Poll/timeout loop — poll via persistence.get_gate_approval()
    let start = std::time::Instant::now();
    loop {
        if start.elapsed() > Duration::from_secs(node.timeout_secs) {
            return handle_gate_timeout(state, &step_id, node);
        }

        match state.persistence.get_gate_approval(&step_id) {
            Ok(GateApprovalState::Approved {
                feedback,
                selections,
            }) => {
                tracing::info!("Gate '{}' approved", node.name);
                if let Some(ref fb) = feedback {
                    state.last_gate_feedback = Some(fb.clone());
                }
                if let Some(sel) = selections {
                    if !sel.is_empty() {
                        // Store gate selection as feedback
                        state.last_gate_feedback = Some(sel.join(", "));
                    }
                }
                resume_run_status(state, &node.name, "after approval");
                emit_event(
                    state,
                    EngineEvent::GateResolved {
                        gate_name: node.name.clone(),
                        approved: true,
                    },
                );
                return Ok(());
            }
            Ok(GateApprovalState::Rejected { feedback }) => {
                tracing::warn!("Gate '{}' rejected", node.name);
                state.all_succeeded = false;
                resume_run_status(state, &node.name, "after rejection");
                emit_event(
                    state,
                    EngineEvent::GateResolved {
                        gate_name: node.name.clone(),
                        approved: false,
                    },
                );
                let reason = feedback.unwrap_or_else(|| format!("Gate '{}' rejected", node.name));
                return Err(EngineError::Workflow(reason));
            }
            Ok(GateApprovalState::Pending) => {
                thread::sleep(state.exec_config.poll_interval);
            }
            Err(e) => {
                tracing::warn!("Gate '{}': error checking approval state: {e}", node.name);
                thread::sleep(state.exec_config.poll_interval);
            }
        }

        // Check cancellation
        match state.persistence.is_run_cancelled(&state.workflow_run_id) {
            Ok(true) => {
                state
                    .cancellation
                    .cancel(crate::cancellation_reason::CancellationReason::UserRequested(None));
                return Err(EngineError::Cancelled(
                    crate::cancellation_reason::CancellationReason::UserRequested(None),
                ));
            }
            Ok(false) => {}
            Err(e) => {
                tracing::warn!(
                    "Database error during cancellation check for gate '{}': {}",
                    node.name,
                    e
                );
            }
        }
    }
}

/// Evaluate a quality gate by checking a prior step's structured output against a threshold.
pub fn execute_quality_gate(
    state: &mut ExecutionState,
    node: &GateNode,
    pos: i64,
    iteration: u32,
) -> Result<()> {
    let qg = node.quality_gate.as_ref().ok_or_else(|| {
        EngineError::Workflow(format!(
            "Quality gate '{}' is missing required quality_gate configuration (source, threshold)",
            node.name
        ))
    })?;
    let source = qg.source.as_str();
    let threshold = qg.threshold;
    let on_fail_action = qg.on_fail_action.clone();

    let step_id = super::insert_step_record(state, &node.name, "gate", pos, iteration, None)?;
    let generation = state.expect_lease_generation();

    let set_step_status = |status: WorkflowStepStatus, context: &str| -> Result<()> {
        state.persistence.update_step(
            &step_id,
            StepUpdate {
                generation,
                status,
                child_run_id: None,
                result_text: Some(context.to_string()),
                context_out: None,
                markers_out: None,
                retry_count: None,
                structured_output: None,
                step_error: None,
            },
        )
    };

    // Look up the source step's structured output
    let (confidence, degradation_reason): (u32, Option<String>) = match state
        .step_results
        .get(source)
    {
        Some(result) => {
            if let Some(ref json_str) = result.structured_output {
                match serde_json::from_str::<serde_json::Value>(json_str) {
                    Ok(val) => {
                        if let Some(c) = val.get("confidence").and_then(|v| v.as_u64()) {
                            (c.min(100) as u32, None)
                        } else if let Some(f) = val.get("confidence").and_then(|v| v.as_f64()) {
                            ((f as u64).min(100) as u32, None)
                        } else {
                            let reason = format!(
                                "'confidence' key missing or not a number in structured output from '{}'",
                                source
                            );
                            tracing::warn!("quality_gate '{}': {}", node.name, reason);
                            (0, Some(reason))
                        }
                    }
                    Err(e) => {
                        let reason =
                            format!("failed to parse structured output from '{}': {}", source, e);
                        tracing::warn!("quality_gate '{}': {}", node.name, reason);
                        (0, Some(reason))
                    }
                }
            } else {
                let reason = format!("source step '{}' has no structured output", source);
                tracing::warn!("quality_gate '{}': {}", node.name, reason);
                (0, Some(reason))
            }
        }
        None => {
            let msg = format!(
                "Quality gate '{}': source step '{}' not found in step results",
                node.name, source
            );
            set_step_status(WorkflowStepStatus::Failed, &msg)?;
            return Err(EngineError::Workflow(msg));
        }
    };

    let passed = confidence >= threshold;
    let mut context = format!(
        "quality_gate: confidence={}, threshold={}, result={}",
        confidence,
        threshold,
        if passed { "pass" } else { "fail" }
    );
    if let Some(ref reason) = degradation_reason {
        context.push_str(&format!(" (confidence defaulted to 0: {})", reason));
    }

    if passed {
        tracing::info!(
            "quality_gate '{}': passed (confidence {} >= threshold {})",
            node.name,
            confidence,
            threshold
        );
        set_step_status(WorkflowStepStatus::Completed, &context)?;
    } else {
        tracing::warn!(
            "quality_gate '{}': failed (confidence {} < threshold {})",
            node.name,
            confidence,
            threshold
        );
        match on_fail_action {
            OnFailAction::Fail => {
                set_step_status(WorkflowStepStatus::Failed, &context)?;
                return Err(EngineError::Workflow(format!(
                    "Quality gate '{}' failed: confidence {} is below threshold {}",
                    node.name, confidence, threshold
                )));
            }
            OnFailAction::Continue => {
                set_step_status(
                    WorkflowStepStatus::Completed,
                    &format!("{} (on_fail=continue, proceeding)", context),
                )?;
            }
        }
    }

    Ok(())
}

pub fn handle_gate_timeout(
    state: &mut ExecutionState,
    step_id: &str,
    node: &GateNode,
) -> Result<()> {
    tracing::warn!("Gate '{}' timed out", node.name);
    let generation = state.expect_lease_generation();
    match node.on_timeout {
        OnTimeout::Fail => {
            state.persistence.update_step(
                step_id,
                StepUpdate {
                    generation,
                    status: WorkflowStepStatus::Failed,
                    child_run_id: None,
                    result_text: Some("gate timed out".to_string()),
                    context_out: None,
                    markers_out: None,
                    retry_count: None,
                    structured_output: None,
                    step_error: Some(format!("Gate '{}' timed out", node.name)),
                },
            )?;
            state.all_succeeded = false;
            resume_run_status(state, &node.name, "after timeout (fail)");
            Err(EngineError::Workflow(format!(
                "Gate '{}' timed out",
                node.name
            )))
        }
        OnTimeout::Continue => {
            state.persistence.update_step(
                step_id,
                StepUpdate {
                    generation,
                    status: WorkflowStepStatus::TimedOut,
                    child_run_id: None,
                    result_text: Some("gate timed out (continuing)".to_string()),
                    context_out: None,
                    markers_out: None,
                    retry_count: None,
                    structured_output: None,
                    step_error: None,
                },
            )?;
            resume_run_status(state, &node.name, "after timeout (continue)");
            Ok(())
        }
    }
}