dk-runner 0.2.82

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
pub mod checks;
pub mod context;
pub mod safety;
pub mod compat;
pub mod quality;

use std::path::Path;
use std::sync::Arc;
use std::time::Instant;

use uuid::Uuid;

use dk_engine::repo::Engine;

use crate::executor::{StepOutput, StepStatus};
use crate::findings::{Finding, Severity, Suggestion};

use checks::SemanticCheck;

/// Build the full registry of all 9 semantic checks.
fn all_checks() -> Vec<Box<dyn SemanticCheck>> {
    let mut checks: Vec<Box<dyn SemanticCheck>> = Vec::new();
    checks.extend(safety::safety_checks());
    checks.extend(compat::compat_checks());
    checks.extend(quality::quality_checks());
    checks
}

/// Generate a suggestion for a finding (hardcoded mapping by check name).
fn suggest(finding_index: usize, finding: &Finding) -> Option<Suggestion> {
    let (description, replacement) = match finding.check_name.as_str() {
        "no-unsafe-added" => (
            "Wrap unsafe code in a safe abstraction or add a safety comment".to_string(),
            Some("// SAFETY: <explain why this is safe>\nunsafe { ... }".to_string()),
        ),
        "no-unwrap-added" => (
            "Replace .unwrap() with ? operator or .expect(\"reason\")".to_string(),
            Some(".expect(\"TODO: add error context\")".to_string()),
        ),
        "error-handling-preserved" => (
            "Restore the Result return type to maintain error handling".to_string(),
            None,
        ),
        "no-public-removal" => (
            "Restore the public symbol or deprecate it first with #[deprecated]".to_string(),
            None,
        ),
        "signature-stable" => (
            "Keep the original signature and add a new function with the updated signature".to_string(),
            None,
        ),
        "trait-impl-complete" => (
            "Restore the missing method(s) in the impl block".to_string(),
            None,
        ),
        "complexity-limit" => (
            "Refactor into smaller functions to reduce branching complexity".to_string(),
            None,
        ),
        "no-dependency-cycles" => (
            "Break the cycle by extracting shared logic into a separate module".to_string(),
            None,
        ),
        "dead-code-detection" => (
            "Remove the unused function or add a caller".to_string(),
            None,
        ),
        _ => return None,
    };

    Some(Suggestion {
        finding_index,
        description,
        file_path: finding.file_path.clone().unwrap_or_default(),
        replacement,
    })
}

/// Run all (or a filtered subset of) semantic checks against a changeset.
///
/// # Arguments
///
/// * `engine` — the dk-engine orchestrator
/// * `repo_id` — repository UUID
/// * `changeset_files` — relative paths of changed files
/// * `work_dir` — directory where changeset files are materialized
/// * `filter` — if non-empty, only run checks whose names appear in this list
///
/// # Returns
///
/// A tuple of `(StepOutput, Vec<Finding>, Vec<Suggestion>)`.
pub async fn run_semantic_step(
    engine: &Arc<Engine>,
    repo_id: Uuid,
    changeset_files: &[String],
    work_dir: &Path,
    filter: &[String],
) -> (StepOutput, Vec<Finding>, Vec<Suggestion>) {
    let start = Instant::now();

    // Build the check context from graph stores + parsed changeset.
    let ctx = match context::build_check_context(engine, repo_id, changeset_files, work_dir).await
    {
        Ok(ctx) => ctx,
        Err(e) => {
            let output = StepOutput {
                status: StepStatus::Fail,
                stdout: String::new(),
                stderr: format!("Failed to build check context: {e}"),
                duration: start.elapsed(),
            };
            return (output, vec![], vec![]);
        }
    };

    // Collect checks, optionally filtering.
    let checks = all_checks();
    let active_checks: Vec<&Box<dyn SemanticCheck>> = if filter.is_empty() {
        checks.iter().collect()
    } else {
        checks
            .iter()
            .filter(|c| filter.iter().any(|f| f == c.name()))
            .collect()
    };

    // Run each check and aggregate findings.
    let mut all_findings: Vec<Finding> = Vec::new();
    let mut results: Vec<String> = Vec::new();

    for check in &active_checks {
        let findings = check.run(&ctx);
        if findings.is_empty() {
            results.push(format!("[PASS] {}", check.name()));
        } else {
            let errors = findings.iter().filter(|f| f.severity == Severity::Error).count();
            let warnings = findings.iter().filter(|f| f.severity == Severity::Warning).count();
            let infos = findings.iter().filter(|f| f.severity == Severity::Info).count();
            results.push(format!(
                "[FIND] {}{} error(s), {} warning(s), {} info(s)",
                check.name(),
                errors,
                warnings,
                infos
            ));
            all_findings.extend(findings);
        }
    }

    // Generate suggestions for each finding.
    let suggestions: Vec<Suggestion> = all_findings
        .iter()
        .enumerate()
        .filter_map(|(idx, f)| suggest(idx, f))
        .collect();

    // Determine overall status.
    let has_errors = all_findings
        .iter()
        .any(|f| f.severity == Severity::Error);

    let status = if has_errors {
        StepStatus::Fail
    } else {
        StepStatus::Pass
    };

    let output = StepOutput {
        status,
        stdout: results.join("\n"),
        stderr: String::new(),
        duration: start.elapsed(),
    };

    (output, all_findings, suggestions)
}

/// Backward-compatible entry point for the scheduler (no Engine required).
///
/// Validates check names against the registry and reports pass/skip.
/// This will be replaced once the scheduler is wired with Engine access (Task 9).
pub async fn run_semantic_step_simple(checks: &[String]) -> StepOutput {
    let start = Instant::now();
    let registry = all_checks();
    let known_names: Vec<&str> = registry.iter().map(|c| c.name()).collect();

    let mut results = Vec::new();
    let mut all_pass = true;

    for check in checks {
        if known_names.contains(&check.as_str()) {
            results.push(format!(
                "[PASS] {}: auto-approved (engine not wired yet)",
                check
            ));
        } else {
            results.push(format!("[SKIP] {}: unknown check", check));
            all_pass = false;
        }
    }

    let status = if all_pass {
        StepStatus::Pass
    } else {
        StepStatus::Skip
    };

    StepOutput {
        status,
        stdout: results.join("\n"),
        stderr: String::new(),
        duration: start.elapsed(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_all_checks_registered() {
        let checks = all_checks();
        assert_eq!(checks.len(), 9, "Expected 9 semantic checks, got {}", checks.len());
    }

    #[test]
    fn test_check_names_unique() {
        let checks = all_checks();
        let mut names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
        let total = names.len();
        names.sort();
        names.dedup();
        assert_eq!(
            names.len(),
            total,
            "Duplicate check names found"
        );
    }

    #[test]
    fn test_check_names_are_expected() {
        let checks = all_checks();
        let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();

        let expected = [
            "no-unsafe-added",
            "no-unwrap-added",
            "error-handling-preserved",
            "no-public-removal",
            "signature-stable",
            "trait-impl-complete",
            "complexity-limit",
            "no-dependency-cycles",
            "dead-code-detection",
        ];

        for name in &expected {
            assert!(
                names.contains(name),
                "Missing expected check: {}",
                name
            );
        }
    }

    #[test]
    fn test_suggest_returns_suggestion_for_known_checks() {
        let finding = Finding {
            severity: Severity::Error,
            check_name: "no-unsafe-added".into(),
            message: "test".into(),
            file_path: Some("src/lib.rs".into()),
            line: Some(1),
            symbol: None,
        };

        let suggestion = suggest(0, &finding);
        assert!(suggestion.is_some());
        assert_eq!(suggestion.unwrap().finding_index, 0);
    }

    #[test]
    fn test_suggest_returns_none_for_unknown_check() {
        let finding = Finding {
            severity: Severity::Info,
            check_name: "unknown-check-xyz".into(),
            message: "test".into(),
            file_path: None,
            line: None,
            symbol: None,
        };

        assert!(suggest(0, &finding).is_none());
    }

    // ── Integration tests for individual semantic checks ──────────────

    #[test]
    fn test_safety_no_unsafe_detects_unsafe_block() {
        use checks::{CheckContext, ChangedFile, SemanticCheck};
        use safety::NoUnsafeAdded;

        let ctx = CheckContext {
            before_symbols: Vec::new(),
            after_symbols: Vec::new(),
            before_call_graph: Vec::new(),
            after_call_graph: Vec::new(),
            before_deps: Vec::new(),
            after_deps: Vec::new(),
            changed_files: vec![ChangedFile {
                path: "src/lib.rs".to_string(),
                content: Some("fn foo() {\n    unsafe {\n        ptr::read(p)\n    }\n}".to_string()),
            }],
        };

        let check = NoUnsafeAdded::new();
        let findings = check.run(&ctx);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].severity, Severity::Error);
    }

    #[test]
    fn test_compat_no_public_removal() {
        use checks::{CheckContext, SemanticCheck};
        use compat::NoPublicRemoval;
        use dk_core::types::*;

        let sym = Symbol {
            id: uuid::Uuid::new_v4(),
            name: "foo".to_string(),
            qualified_name: "crate::foo".to_string(),
            kind: SymbolKind::Function,
            visibility: Visibility::Public,
            file_path: "src/lib.rs".into(),
            span: Span { start_byte: 0, end_byte: 100 },
            signature: Some("fn foo()".to_string()),
            doc_comment: None,
            parent: None,
            last_modified_by: None,
            last_modified_intent: None,
        };

        let ctx = CheckContext {
            before_symbols: vec![sym],
            after_symbols: Vec::new(),
            before_call_graph: Vec::new(),
            after_call_graph: Vec::new(),
            before_deps: Vec::new(),
            after_deps: Vec::new(),
            changed_files: Vec::new(),
        };

        let check = NoPublicRemoval::new();
        let findings = check.run(&ctx);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].check_name, "no-public-removal");
    }

    #[test]
    fn test_safety_no_unwrap_detects_unwrap() {
        use checks::{CheckContext, ChangedFile, SemanticCheck};
        use safety::NoUnwrapAdded;

        let ctx = CheckContext {
            before_symbols: Vec::new(),
            after_symbols: Vec::new(),
            before_call_graph: Vec::new(),
            after_call_graph: Vec::new(),
            before_deps: Vec::new(),
            after_deps: Vec::new(),
            changed_files: vec![ChangedFile {
                path: "src/lib.rs".to_string(),
                content: Some("let x = foo.unwrap();".to_string()),
            }],
        };

        let check = NoUnwrapAdded::new();
        let findings = check.run(&ctx);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].severity, Severity::Warning);
    }

    #[test]
    fn test_quality_complexity_limit() {
        use checks::{CheckContext, ChangedFile, SemanticCheck};
        use quality::ComplexityLimit;

        // Wrap the deeply nested branching in a function so per-function
        // complexity tracking detects it.
        let inner = (0..15).map(|i| format!("if x > {} {{", i)).collect::<Vec<_>>().join("\n")
            + &"\n}".repeat(15);
        let deeply_nested = format!("fn deep() {{\n{}\n}}", inner);

        let ctx = CheckContext {
            before_symbols: Vec::new(),
            after_symbols: Vec::new(),
            before_call_graph: Vec::new(),
            after_call_graph: Vec::new(),
            before_deps: Vec::new(),
            after_deps: Vec::new(),
            changed_files: vec![ChangedFile {
                path: "src/lib.rs".to_string(),
                content: Some(deeply_nested),
            }],
        };

        let check = ComplexityLimit::with_threshold(10);
        let findings = check.run(&ctx);
        assert!(!findings.is_empty(), "should detect high complexity");
    }
}