assura 0.7.1

Contract-first AI-native language. Write what it should do. AI proves it does.
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
//! `assura suggest-from-crash` — propose contracts from cargo-fuzz crash artifacts.

use super::super::*;

/// Options for `assura suggest-from-crash`.
pub(crate) struct SuggestFromCrashOpts<'a> {
    pub crash_input: Option<&'a str>,
    pub crash_dir: Option<&'a str>,
    pub target: &'a str,
    pub stacktrace_file: Option<&'a str>,
    pub llm_provider: &'a str,
    pub llm_model: Option<&'a str>,
    pub output_mode: OutputMode,
    pub verbosity: Verbosity,
}

fn fail_suggest(output_mode: OutputMode, error: &str, message: String) -> ! {
    if output_mode == OutputMode::Json {
        let report = serde_json::json!({
            "ok": false,
            "error": error,
            "message": message,
        });
        println!("{}", serde_json::to_string_pretty(&report).unwrap());
    } else {
        eprintln!("Error: {message}");
    }
    process::exit(1);
}

/// Load annotated Rust items for `suggest-from-crash`.
/// A missing path, a scan error, or a parse error is returned. Callers must
/// not turn that into an empty success.
pub(crate) fn load_crash_target(
    path: &Path,
) -> Result<Vec<(std::path::PathBuf, Vec<assura_rust_analyzer::AnnotatedItem>)>, String> {
    if path.is_dir() {
        assura_rust_analyzer::scan_directory(path).map_err(|e| e.to_string())
    } else if path.is_file() {
        assura_rust_analyzer::parse_rust_file(path)
            .map(|items| vec![(path.to_path_buf(), items)])
            .map_err(|e| e.to_string())
    } else {
        Err(format!("{} is not a file or directory", path.display()))
    }
}

pub(crate) fn run_suggest_from_crash(opts: SuggestFromCrashOpts<'_>) {
    use assura_llm::fuzz::*;
    use assura_llm::{cache::LlmCache, types::LlmConfig};

    let SuggestFromCrashOpts {
        crash_input,
        crash_dir,
        target,
        stacktrace_file,
        llm_provider,
        llm_model,
        output_mode,
        verbosity,
    } = opts;

    // Load crash artifacts
    let artifacts: Vec<CrashArtifact> = if let Some(input) = crash_input {
        match CrashArtifact::from_file(Path::new(input)) {
            Ok(a) => vec![a],
            Err(e) => {
                if output_mode == OutputMode::Json {
                    let report = serde_json::json!({
                        "ok": false,
                        "error": "crash_input_read_failed",
                        "path": input,
                        "message": format!("Error reading crash artifact {input}: {e}"),
                    });
                    println!("{}", serde_json::to_string_pretty(&report).unwrap());
                } else {
                    eprintln!("Error reading crash artifact {input}: {e}");
                }
                process::exit(1);
            }
        }
    } else if let Some(dir) = crash_dir {
        match CrashArtifact::from_directory(Path::new(dir)) {
            Ok(a) if a.is_empty() => {
                if output_mode == OutputMode::Json {
                    println!(
                        "{}",
                        serde_json::json!({
                            "artifacts": 0,
                            "function": null,
                            "total_suggestions": 0,
                            "crashes": [],
                            "message": format!("No crash artifacts found in {dir}"),
                        })
                    );
                } else if verbosity != Verbosity::Quiet {
                    println!("No crash artifacts found in {dir}");
                }
                return;
            }
            Ok(a) => a,
            Err(e) => {
                if output_mode == OutputMode::Json {
                    let report = serde_json::json!({
                        "ok": false,
                        "error": "crash_dir_read_failed",
                        "path": dir,
                        "message": format!("Error reading crash directory {dir}: {e}"),
                    });
                    println!("{}", serde_json::to_string_pretty(&report).unwrap());
                } else {
                    eprintln!("Error reading crash directory {dir}: {e}");
                }
                process::exit(1);
            }
        }
    } else {
        if output_mode == OutputMode::Json {
            let report = serde_json::json!({
                "ok": false,
                "error": "missing_crash_input",
                "message": "specify --crash-input or --crash-dir",
            });
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
        } else {
            eprintln!("Error: specify --crash-input or --crash-dir");
        }
        process::exit(1);
    };

    // Parse stack trace (if provided)
    let stack_trace = stacktrace_file.and_then(|f| {
        std::fs::read_to_string(f)
            .map(|text| StackTrace::parse(&text))
            .ok()
    });

    // Scan target Rust source for annotated items
    let target_path = Path::new(target);
    let file_items = if !target_path.is_dir() && !target_path.is_file() {
        if output_mode == OutputMode::Json {
            let report = serde_json::json!({
                "ok": false,
                "error": "target_not_found",
                "path": target,
                "message": format!("{target} is not a file or directory"),
            });
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
        } else {
            eprintln!("Error: {target} is not a file or directory");
        }
        process::exit(1);
    } else {
        match load_crash_target(target_path) {
            Ok(items) => items,
            Err(message) => fail_suggest(output_mode, "target_scan_failed", message),
        }
    };

    // Build contract database to find existing contracts
    let contract_db = assura_llm::ContractDatabase::from_scan(&file_items);

    // Configure LLM provider
    if !crate::suggest::LLM_PROVIDERS
        .iter()
        .any(|p| *p == llm_provider.to_ascii_lowercase())
    {
        if output_mode == OutputMode::Json {
            let report = serde_json::json!({
                "ok": false,
                "error": "llm_provider",
                "message": format!("unknown LLM provider '{llm_provider}'"),
                "did_you_mean": crate::suggest::did_you_mean(
                    llm_provider,
                    crate::suggest::LLM_PROVIDERS
                ),
            });
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
        } else {
            eprintln!("LLM provider error: unknown LLM provider '{llm_provider}'");
            if let Some(hint) =
                crate::suggest::did_you_mean(llm_provider, crate::suggest::LLM_PROVIDERS)
            {
                eprintln!("did you mean {hint}?");
            }
        }
        process::exit(1);
    }
    let config = LlmConfig::from_provider(llm_provider, llm_model);

    let cache = LlmCache::new(&config.cache_dir);

    let provider = match assura_llm::HttpProvider::new(config) {
        Ok(p) => p,
        Err(e) => {
            if output_mode == OutputMode::Json {
                let report = serde_json::json!({
                    "ok": false,
                    "error": "llm_provider",
                    "message": format!("{e}"),
                    "hint": "Set the API key environment variable to enable LLM analysis.",
                });
                println!("{}", serde_json::to_string_pretty(&report).unwrap());
            } else {
                eprintln!("LLM provider error: {e}");
                eprintln!("Set the API key environment variable to enable LLM analysis.");
            }
            process::exit(1);
        }
    };

    if verbosity != Verbosity::Quiet && output_mode != OutputMode::Json {
        println!(
            "suggest-from-crash: {} artifact(s), target: {target}",
            artifacts.len()
        );
    }

    // Determine the target function name from stack trace (if available)
    let crash_fn_name = stack_trace
        .as_ref()
        .and_then(|t| t.crash_function())
        .map(|f| {
            // Extract the function name from the fully qualified path
            f.function_name
                .rsplit("::")
                .next()
                .unwrap_or(&f.function_name)
                .to_string()
        });

    // Read the target file source for LLM context
    let target_source = if target_path.is_file() {
        match std::fs::read_to_string(target_path) {
            Ok(text) => text,
            Err(e) => fail_suggest(
                output_mode,
                "target_read_failed",
                format!("reading {}: {e}", target_path.display()),
            ),
        }
    } else {
        // If it's a directory, use stack trace to find the specific file
        stack_trace
            .as_ref()
            .and_then(|t| t.crash_function())
            .and_then(|f| f.file.as_ref())
            .and_then(|file| std::fs::read_to_string(file).ok())
            .unwrap_or_else(|| "(source not available)".to_string())
    };

    let fn_name = crash_fn_name.as_deref().unwrap_or("(unknown function)");

    // Get existing contracts for the function
    let existing: Vec<String> = contract_db
        .lookup_function(fn_name)
        .map(|c| {
            c.requires
                .iter()
                .map(|r| format!("#[requires({r})]"))
                .chain(c.ensures.iter().map(|e| format!("#[ensures({e})]")))
                .collect()
        })
        .unwrap_or_default();

    let mut all_results: Vec<serde_json::Value> = Vec::new();
    let mut total_suggestions = 0usize;
    let mut llm_errors: Vec<serde_json::Value> = Vec::new();

    // Track seen crashes for deduplication
    let mut seen_keys = std::collections::HashSet::new();

    for artifact in &artifacts {
        let dedup_key = format!(
            "{}:{}",
            fn_name,
            stack_trace
                .as_ref()
                .and_then(|t| t.panic_message.as_deref())
                .unwrap_or("unknown")
        );

        if !seen_keys.insert(dedup_key) {
            if verbosity == Verbosity::Verbose && output_mode != OutputMode::Json {
                println!(
                    "  skipping {} (duplicate crash class)",
                    artifact.path.display()
                );
            }
            continue;
        }

        if verbosity == Verbosity::Verbose && output_mode != OutputMode::Json {
            println!(
                "  analyzing {} ({}, {})",
                artifact.path.display(),
                artifact.crash_kind,
                artifact.input_summary,
            );
        }

        match suggest_from_crash(
            &provider,
            &cache,
            &target_source,
            fn_name,
            artifact,
            stack_trace.as_ref(),
            &existing,
        ) {
            Ok(resp) if !resp.suggestions.is_empty() => {
                total_suggestions += resp.suggestions.len();

                if output_mode == OutputMode::Json {
                    all_results.push(serde_json::json!({
                        "artifact": artifact.path.display().to_string(),
                        "crash_kind": artifact.crash_kind.to_string(),
                        "function": fn_name,
                        "suggestions": resp.suggestions,
                    }));
                } else if verbosity != Verbosity::Quiet {
                    println!("\n  {} ({}):", artifact.path.display(), artifact.crash_kind,);
                    for s in &resp.suggestions {
                        println!(
                            "    #[{}({})]  confidence: {:.0}%",
                            s.kind,
                            s.expression,
                            s.confidence * 100.0,
                        );
                        println!("      prevents: {}", s.prevents);
                        if verbosity == Verbosity::Verbose {
                            println!("      reasoning: {}", s.reasoning);
                        }
                    }
                }
            }
            Ok(_) => {
                if verbosity == Verbosity::Verbose && output_mode != OutputMode::Json {
                    println!("  {} no suggestions", artifact.path.display());
                }
            }
            Err(e) => {
                let msg = e.to_string();
                llm_errors.push(serde_json::json!({
                    "artifact": artifact.path.display().to_string(),
                    "error": msg,
                }));
                // Human diagnostics on stderr; JSON carries errors in the body.
                if output_mode != OutputMode::Json {
                    eprintln!("  {}: LLM error: {e}", artifact.path.display(),);
                }
            }
        }
    }

    // Output
    if output_mode == OutputMode::Json {
        let summary = serde_json::json!({
            "artifacts": artifacts.len(),
            "function": fn_name,
            "total_suggestions": total_suggestions,
            "crashes": all_results,
            "errors": llm_errors,
            "success": llm_errors.is_empty(),
        });
        println!("{}", serde_json::to_string_pretty(&summary).unwrap());
        if !llm_errors.is_empty() {
            process::exit(1);
        }
    } else if verbosity != Verbosity::Quiet {
        println!(
            "\nsuggest-from-crash: {} artifact(s) analyzed, {} suggestion(s)",
            artifacts.len(),
            total_suggestions,
        );
        if !llm_errors.is_empty() {
            eprintln!("{} LLM error(s)", llm_errors.len());
            process::exit(1);
        }
    } else if !llm_errors.is_empty() {
        process::exit(1);
    }
}

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

    #[test]
    fn load_crash_target_reports_unparseable_rust() {
        let dir = std::env::temp_dir().join(format!(
            "assura_suggest_scan_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("broken.rs"), "fn (\n").unwrap();
        let err = load_crash_target(&dir).expect_err("scan errors must surface");
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            err.contains("broken.rs"),
            "parse error must name the failing file: {err}"
        );
    }
}