dk-runner 0.3.0

dkod verification runner — CI/CD pipeline execution
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
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use tokio::sync::mpsc;
use tracing::info;
use uuid::Uuid;

use dk_engine::repo::Engine;

use crate::changeset::scope_command_to_changeset;
use crate::executor::{Executor, StepOutput, StepStatus};
use crate::findings::{Finding, Suggestion};
use crate::steps::{agent_review, command, human_approve, semantic};
use crate::workflow::types::{Stage, Step, StepType, Workflow};

/// Result of running a single step, with metadata for streaming.
#[derive(Debug, Clone)]
pub struct StepResult {
    pub stage_name: String,
    pub step_name: String,
    pub status: StepStatus,
    pub output: String,
    pub required: bool,
    pub findings: Vec<Finding>,
    pub suggestions: Vec<Suggestion>,
}

/// Run an entire workflow: stages sequentially, steps within parallel stages concurrently.
/// Sends `StepResult`s to `tx` as each step completes. Returns `true` if all required steps passed.
///
/// `engine` and `repo_id` are optional — when provided, the semantic step uses the full
/// Engine-backed analysis. Pass `None` for both in tests or contexts without an Engine.
pub async fn run_workflow(
    workflow: &Workflow,
    executor: &dyn Executor,
    work_dir: &Path,
    changeset_files: &[String],
    env: &HashMap<String, String>,
    tx: &mpsc::Sender<StepResult>,
    engine: Option<&Arc<Engine>>,
    repo_id: Option<Uuid>,
    changeset_id: Option<Uuid>,
) -> bool {
    let mut all_passed = true;

    for stage in &workflow.stages {
        info!(stage = %stage.name, parallel = stage.parallel, "running stage");

        let results = if stage.parallel {
            run_stage_parallel(stage, executor, work_dir, changeset_files, env, engine, repo_id, changeset_id)
                .await
        } else {
            run_stage_sequential(stage, executor, work_dir, changeset_files, env, engine, repo_id, changeset_id)
                .await
        };

        for result in results {
            if result.status != StepStatus::Pass && result.required {
                all_passed = false;
            }
            let _ = tx.send(result).await;
        }
    }

    all_passed
}

async fn run_stage_parallel(
    stage: &Stage,
    executor: &dyn Executor,
    work_dir: &Path,
    changeset_files: &[String],
    env: &HashMap<String, String>,
    engine: Option<&Arc<Engine>>,
    repo_id: Option<Uuid>,
    changeset_id: Option<Uuid>,
) -> Vec<StepResult> {
    let mut futures = Vec::new();
    for step in &stage.steps {
        futures.push(run_single_step(
            &stage.name,
            step,
            executor,
            work_dir,
            changeset_files,
            env,
            engine,
            repo_id,
            changeset_id,
        ));
    }
    futures::future::join_all(futures).await
}

async fn run_stage_sequential(
    stage: &Stage,
    executor: &dyn Executor,
    work_dir: &Path,
    changeset_files: &[String],
    env: &HashMap<String, String>,
    engine: Option<&Arc<Engine>>,
    repo_id: Option<Uuid>,
    changeset_id: Option<Uuid>,
) -> Vec<StepResult> {
    let mut results = Vec::new();
    for step in &stage.steps {
        let result = run_single_step(
            &stage.name,
            step,
            executor,
            work_dir,
            changeset_files,
            env,
            engine,
            repo_id,
            changeset_id,
        )
        .await;
        let failed_required = step.required && result.status != StepStatus::Pass;
        results.push(result);
        // Abort early if a required step failed — no point running subsequent
        // steps (e.g., cargo test after cargo check fails with compile errors)
        if failed_required {
            tracing::warn!(
                stage = %stage.name,
                step = %step.name,
                "required step failed — aborting remaining steps in sequential stage"
            );
            break;
        }
    }
    results
}

async fn run_single_step(
    stage_name: &str,
    step: &Step,
    executor: &dyn Executor,
    work_dir: &Path,
    changeset_files: &[String],
    env: &HashMap<String, String>,
    engine: Option<&Arc<Engine>>,
    repo_id: Option<Uuid>,
    changeset_id: Option<Uuid>,
) -> StepResult {
    info!(step = %step.name, "running step");

    match &step.step_type {
        StepType::Command { run } => {
            let cmd = if step.changeset_aware {
                let local_files: Vec<String> = if let Some(sub) = &step.work_dir {
                    let prefix = format!("{}/", sub.display());
                    changeset_files
                        .iter()
                        .filter_map(|f| f.strip_prefix(&prefix).map(|s| s.to_string()))
                        .collect()
                } else {
                    changeset_files.to_vec()
                };
                scope_command_to_changeset(run, &local_files)
                    .unwrap_or_else(|| run.clone())
            } else {
                run.clone()
            };
            let step_work_dir = match &step.work_dir {
                Some(sub) => work_dir.join(sub),
                None => work_dir.to_path_buf(),
            };
            let output =
                match command::run_command_step(executor, &cmd, &step_work_dir, step.timeout, env).await {
                    Ok(out) => out,
                    Err(e) => StepOutput {
                        status: StepStatus::Fail,
                        stdout: String::new(),
                        stderr: e.to_string(),
                        duration: std::time::Duration::ZERO,
                    },
                };

            let combined_output = if output.stderr.is_empty() {
                output.stdout
            } else {
                format!("{}{}", output.stdout, output.stderr)
            };

            StepResult {
                stage_name: stage_name.to_string(),
                step_name: step.name.clone(),
                status: output.status,
                output: combined_output,
                required: step.required,
                findings: Vec::new(),
                suggestions: Vec::new(),
            }
        }
        StepType::Semantic { checks } => {
            if let (Some(eng), Some(rid)) = (engine, repo_id) {
                // Full Engine-backed semantic analysis
                let (output, findings, suggestions) = semantic::run_semantic_step(
                    eng,
                    rid,
                    changeset_files,
                    work_dir,
                    checks,
                )
                .await;

                let combined_output = if output.stderr.is_empty() {
                    output.stdout
                } else {
                    format!("{}{}", output.stdout, output.stderr)
                };

                StepResult {
                    stage_name: stage_name.to_string(),
                    step_name: step.name.clone(),
                    status: output.status,
                    output: combined_output,
                    required: step.required,
                    findings,
                    suggestions,
                }
            } else {
                // Fallback to simple shim (no Engine available)
                let output = semantic::run_semantic_step_simple(checks).await;

                let combined_output = if output.stderr.is_empty() {
                    output.stdout
                } else {
                    format!("{}{}", output.stdout, output.stderr)
                };

                StepResult {
                    stage_name: stage_name.to_string(),
                    step_name: step.name.clone(),
                    status: output.status,
                    output: combined_output,
                    required: step.required,
                    findings: Vec::new(),
                    suggestions: Vec::new(),
                }
            }
        }
        StepType::AgentReview { prompt } => {
            let provider = agent_review::claude::ClaudeReviewProvider::from_env();
            if let Some(provider) = provider {
                let mut diff = String::new();
                let mut files = Vec::new();
                for path in changeset_files {
                    let full_path = work_dir.join(path);
                    if let Ok(content) = tokio::fs::read_to_string(&full_path).await {
                        diff.push_str(&format!("--- {path}\n+++ {path}\n{content}\n"));
                        files.push(agent_review::provider::FileContext {
                            path: path.clone(),
                            content,
                        });
                    }
                }
                let (output, findings, suggestions) =
                    agent_review::run_agent_review_step_with_provider(
                        &provider, &diff, files, prompt,
                    )
                    .await;
                return StepResult {
                    stage_name: stage_name.to_string(),
                    step_name: step.name.clone(),
                    status: output.status,
                    output: if output.stderr.is_empty() {
                        output.stdout
                    } else {
                        format!("{}{}", output.stdout, output.stderr)
                    },
                    required: step.required,
                    findings,
                    suggestions,
                };
            }
            // No provider: use legacy stub
            let output = agent_review::run_agent_review_step(prompt).await;
            StepResult {
                stage_name: stage_name.to_string(),
                step_name: step.name.clone(),
                status: output.status,
                output: if output.stderr.is_empty() {
                    output.stdout
                } else {
                    format!("{}{}", output.stdout, output.stderr)
                },
                required: step.required,
                findings: Vec::new(),
                suggestions: Vec::new(),
            }
        }
        StepType::HumanApprove => {
            if let (Some(eng), Some(cid)) = (engine, changeset_id) {
                let (output, findings) = human_approve::run_human_approve_step_with_engine(
                    eng, cid, Some(step.timeout),
                ).await;
                return StepResult {
                    stage_name: stage_name.to_string(),
                    step_name: step.name.clone(),
                    status: output.status,
                    output: if output.stderr.is_empty() { output.stdout } else { format!("{}{}", output.stdout, output.stderr) },
                    required: step.required,
                    findings,
                    suggestions: Vec::new(),
                };
            }
            let output = human_approve::run_human_approve_step().await;
            StepResult {
                stage_name: stage_name.to_string(),
                step_name: step.name.clone(),
                status: output.status,
                output: if output.stderr.is_empty() { output.stdout } else { format!("{}{}", output.stdout, output.stderr) },
                required: step.required,
                findings: Vec::new(),
                suggestions: Vec::new(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::executor::process::ProcessExecutor;
    use crate::workflow::types::*;
    use std::time::Duration;

    #[tokio::test]
    async fn test_run_workflow_passes() {
        let wf = Workflow {
            name: "test".into(),
            timeout: Duration::from_secs(30),
            stages: vec![Stage {
                name: "checks".into(),
                parallel: false,
                steps: vec![Step {
                    name: "echo-test".into(),
                    step_type: StepType::Command {
                        run: "echo hello".into(),
                    },
                    timeout: Duration::from_secs(5),
                    required: true,
                    changeset_aware: false,
                    work_dir: None,
                }],
            }],
            allowed_commands: vec![],
        };

        let exec = ProcessExecutor::new();
        let (tx, mut rx) = mpsc::channel(32);
        let dir = std::env::temp_dir();

        let passed =
            run_workflow(&wf, &exec, &dir, &[], &HashMap::new(), &tx, None, None, None).await;
        drop(tx);
        assert!(passed);
        let result = rx.recv().await.unwrap();
        assert_eq!(result.status, StepStatus::Pass);
    }

    #[tokio::test]
    async fn test_failing_required_step() {
        let wf = Workflow {
            name: "test".into(),
            timeout: Duration::from_secs(30),
            stages: vec![Stage {
                name: "checks".into(),
                parallel: false,
                steps: vec![Step {
                    name: "disallowed".into(),
                    step_type: StepType::Command {
                        run: "false_cmd_not_in_allowlist".into(),
                    },
                    timeout: Duration::from_secs(5),
                    required: true,
                    changeset_aware: false,
                    work_dir: None,
                }],
            }],
            allowed_commands: vec![],
        };

        let exec = ProcessExecutor::new();
        let (tx, _rx) = mpsc::channel(32);
        let dir = std::env::temp_dir();

        let passed =
            run_workflow(&wf, &exec, &dir, &[], &HashMap::new(), &tx, None, None, None).await;
        drop(tx);
        assert!(!passed);
    }

    #[tokio::test]
    async fn test_parallel_stage() {
        let wf = Workflow {
            name: "test".into(),
            timeout: Duration::from_secs(30),
            stages: vec![Stage {
                name: "parallel-checks".into(),
                parallel: true,
                steps: vec![
                    Step {
                        name: "echo-a".into(),
                        step_type: StepType::Command {
                            run: "echo a".into(),
                        },
                        timeout: Duration::from_secs(5),
                        required: true,
                        changeset_aware: false,
                        work_dir: None,
                    },
                    Step {
                        name: "echo-b".into(),
                        step_type: StepType::Command {
                            run: "echo b".into(),
                        },
                        timeout: Duration::from_secs(5),
                        required: true,
                        changeset_aware: false,
                        work_dir: None,
                    },
                ],
            }],
            allowed_commands: vec![],
        };

        let exec = ProcessExecutor::new();
        let (tx, mut rx) = mpsc::channel(32);
        let dir = std::env::temp_dir();

        let passed =
            run_workflow(&wf, &exec, &dir, &[], &HashMap::new(), &tx, None, None, None).await;
        drop(tx);
        assert!(passed);

        let mut results = Vec::new();
        while let Some(r) = rx.recv().await {
            results.push(r);
        }
        assert_eq!(results.len(), 2);
    }
}