bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
impl FalsificationGenerator {
    /// Create new generator with default config
    pub fn new() -> Self {
        Self {
            config: FalsificationConfig::all(),
        }
    }

    /// Create generator with custom config
    pub fn with_config(config: FalsificationConfig) -> Self {
        Self { config }
    }

    /// Generate hypotheses for an installer specification
    pub fn generate_hypotheses(&self, spec: &InstallerInfo) -> Vec<FalsificationHypothesis> {
        let mut hypotheses = Vec::new();

        for step in &spec.steps {
            // Idempotency hypothesis
            if self.config.test_idempotency {
                hypotheses.push(FalsificationHypothesis {
                    id: format!("IDEM-{}", step.id),
                    claim: format!("Step '{}' is idempotent", step.name),
                    category: HypothesisCategory::Idempotency,
                    falsification_method: "Execute step twice, compare final states".to_string(),
                    step_ids: vec![step.id.clone()],
                    expected_evidence: "State after first run equals state after second run"
                        .to_string(),
                    falsifying_evidence: "States differ after repeated execution".to_string(),
                    priority: 9,
                });
            }

            // Determinism hypothesis
            if self.config.test_determinism {
                hypotheses.push(FalsificationHypothesis {
                    id: format!("DET-{}", step.id),
                    claim: format!("Step '{}' is deterministic", step.name),
                    category: HypothesisCategory::Determinism,
                    falsification_method: "Execute step with same inputs twice, compare outputs"
                        .to_string(),
                    step_ids: vec![step.id.clone()],
                    expected_evidence: "Outputs are byte-identical across runs".to_string(),
                    falsifying_evidence: "Outputs differ between runs with same inputs".to_string(),
                    priority: 9,
                });
            }

            // Rollback hypothesis
            if self.config.test_rollback && step.has_rollback {
                hypotheses.push(FalsificationHypothesis {
                    id: format!("ROLL-{}", step.id),
                    claim: format!("Rollback for '{}' is complete", step.name),
                    category: HypothesisCategory::RollbackCompleteness,
                    falsification_method:
                        "Capture state, execute step, rollback, compare to original state"
                            .to_string(),
                    step_ids: vec![step.id.clone()],
                    expected_evidence: "State after rollback equals state before execution"
                        .to_string(),
                    falsifying_evidence: "State differs after rollback".to_string(),
                    priority: 8,
                });
            }

            // Dry-run accuracy hypothesis
            if self.config.test_dry_run {
                hypotheses.push(FalsificationHypothesis {
                    id: format!("DRY-{}", step.id),
                    claim: format!("Dry-run for '{}' accurately predicts changes", step.name),
                    category: HypothesisCategory::DryRunAccuracy,
                    falsification_method:
                        "Run dry-run, capture prediction, execute, compare to actual".to_string(),
                    step_ids: vec![step.id.clone()],
                    expected_evidence: "Dry-run prediction matches actual execution".to_string(),
                    falsifying_evidence: "Prediction differs from actual changes".to_string(),
                    priority: 7,
                });
            }

            // Postcondition validity
            if self.config.test_postconditions && !step.postconditions.is_empty() {
                for (i, pc) in step.postconditions.iter().enumerate() {
                    hypotheses.push(FalsificationHypothesis {
                        id: format!("POST-{}-{}", step.id, i),
                        claim: format!("Postcondition '{}' holds after '{}'", pc, step.name),
                        category: HypothesisCategory::PostconditionValidity,
                        falsification_method: "Execute step, verify postcondition".to_string(),
                        step_ids: vec![step.id.clone()],
                        expected_evidence: format!("Postcondition '{}' is true", pc),
                        falsifying_evidence: format!("Postcondition '{}' is false", pc),
                        priority: 8,
                    });
                }
            }

            // Precondition guard
            if self.config.test_preconditions && !step.preconditions.is_empty() {
                for (i, pre) in step.preconditions.iter().enumerate() {
                    hypotheses.push(FalsificationHypothesis {
                        id: format!("PRE-{}-{}", step.id, i),
                        claim: format!(
                            "Precondition '{}' prevents invalid execution of '{}'",
                            pre, step.name
                        ),
                        category: HypothesisCategory::PreconditionGuard,
                        falsification_method:
                            "Violate precondition, attempt execution, verify failure".to_string(),
                        step_ids: vec![step.id.clone()],
                        expected_evidence: format!(
                            "Step fails when precondition '{}' is not met",
                            pre
                        ),
                        falsifying_evidence: format!(
                            "Step succeeds despite precondition '{}' being false",
                            pre
                        ),
                        priority: 7,
                    });
                }
            }

            // Performance bounds
            if self.config.test_performance {
                if let Some(max_duration) = step.max_duration_ms {
                    hypotheses.push(FalsificationHypothesis {
                        id: format!("PERF-{}", step.id),
                        claim: format!("Step '{}' completes within {}ms", step.name, max_duration),
                        category: HypothesisCategory::PerformanceBound,
                        falsification_method: "Execute step, measure duration".to_string(),
                        step_ids: vec![step.id.clone()],
                        expected_evidence: format!(
                            "Execution completes in under {}ms",
                            max_duration
                        ),
                        falsifying_evidence: format!("Execution exceeds {}ms", max_duration),
                        priority: 5,
                    });
                }
            }
        }

        // Sort by priority (highest first)
        hypotheses.sort_by(|a, b| b.priority.cmp(&a.priority));
        hypotheses
    }

    /// Generate test cases for hypotheses
    pub fn generate_tests(&self, hypotheses: &[FalsificationHypothesis]) -> Vec<FalsificationTest> {
        hypotheses
            .iter()
            .map(|h| self.generate_test_for_hypothesis(h))
            .collect()
    }

    /// Generate a test for a specific hypothesis
    fn generate_test_for_hypothesis(
        &self,
        hypothesis: &FalsificationHypothesis,
    ) -> FalsificationTest {
        let step_id = hypothesis
            .step_ids
            .first()
            .cloned()
            .unwrap_or_else(|| "unknown".to_string());

        match hypothesis.category {
            HypothesisCategory::Idempotency => FalsificationTest {
                name: format!("test_falsify_idempotency_{}", step_id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![TestAction::CaptureState {
                    label: "initial".to_string(),
                }],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::StatesEqual {
                    state_a: "after_first".to_string(),
                    state_b: "after_second".to_string(),
                }],
                cleanup: vec![],
            },
            HypothesisCategory::Determinism => FalsificationTest {
                name: format!("test_falsify_determinism_{}", step_id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![TestAction::CaptureState {
                    label: "initial".to_string(),
                }],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::StatesEqual {
                    state_a: "output_1".to_string(),
                    state_b: "output_2".to_string(),
                }],
                cleanup: vec![],
            },
            HypothesisCategory::RollbackCompleteness => FalsificationTest {
                name: format!("test_falsify_rollback_{}", step_id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![TestAction::CaptureState {
                    label: "before".to_string(),
                }],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::StatesEqual {
                    state_a: "before".to_string(),
                    state_b: "after_rollback".to_string(),
                }],
                cleanup: vec![TestAction::Rollback {
                    step_id: step_id.clone(),
                }],
            },
            HypothesisCategory::DryRunAccuracy => FalsificationTest {
                name: format!("test_falsify_dry_run_{}", step_id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![TestAction::DryRun {
                    step_id: step_id.clone(),
                }],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::DryRunMatchesExecution {
                    step_id: step_id.clone(),
                }],
                cleanup: vec![],
            },
            HypothesisCategory::PostconditionValidity => FalsificationTest {
                name: format!("test_falsify_postcondition_{}", hypothesis.id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::CommandSucceeds {
                    command: format!("verify_postcondition_{}", hypothesis.id),
                }],
                cleanup: vec![],
            },
            HypothesisCategory::PreconditionGuard => FalsificationTest {
                name: format!("test_falsify_precondition_{}", hypothesis.id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::CommandFails {
                    command: format!("execute_step_{}", step_id),
                }],
                cleanup: vec![],
            },
            HypothesisCategory::PerformanceBound => FalsificationTest {
                name: format!("test_falsify_performance_{}", step_id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![Verification::DurationBelow {
                    max_ms: 60000, // Default 1 minute
                }],
                cleanup: vec![],
            },
            HypothesisCategory::ResourceLimit => FalsificationTest {
                name: format!("test_falsify_resources_{}", step_id),
                hypothesis_id: hypothesis.id.clone(),
                setup: vec![],
                action: TestAction::ExecuteStep {
                    step_id: step_id.clone(),
                },
                verification: vec![],
                cleanup: vec![],
            },
        }
    }

    /// Generate Rust test code for hypotheses
    pub fn generate_rust_tests(&self, hypotheses: &[FalsificationHypothesis]) -> String {
        let mut code = String::new();

        code.push_str("//! Auto-generated falsification tests\n");
        code.push_str("//! Generated by bashrs falsification test generator\n\n");
        code.push_str("#[cfg(test)]\n");
        code.push_str("mod falsification_tests {\n");
        code.push_str("    use super::*;\n\n");

        for h in hypotheses {
            code.push_str(&format!("    /// FALSIFIABLE: \"{}\"\n", h.claim));
            code.push_str(&format!("    /// DISPROOF: {}\n", h.falsifying_evidence));
            code.push_str("    #[test]\n");
            code.push_str(&format!(
                "    fn test_falsify_{}() {{\n",
                h.id.to_lowercase().replace('-', "_")
            ));
            code.push_str("        // Placeholder: implement with step execution\n");
            code.push_str(&format!("        // Method: {}\n", h.falsification_method));
            code.push_str(&format!("        // Expected: {}\n", h.expected_evidence));
            code.push_str("        assert!(true, \"Implement falsification test\");\n");
            code.push_str("    }\n\n");
        }

        code.push_str("}\n");
        code
    }
}

/// Minimal installer info for test generation
#[derive(Debug, Clone, Default)]
pub struct InstallerInfo {
    /// Installer name
    pub name: String,
    /// Installer version
    pub version: String,
    /// Steps in the installer
    pub steps: Vec<StepInfo>,
}

/// Minimal step info for test generation
#[derive(Debug, Clone, Default)]
pub struct StepInfo {
    /// Step ID
    pub id: String,
    /// Step name
    pub name: String,
    /// Whether step has rollback
    pub has_rollback: bool,
    /// Preconditions
    pub preconditions: Vec<String>,
    /// Postconditions
    pub postconditions: Vec<String>,
    /// Max duration in ms
    pub max_duration_ms: Option<u64>,
}

/// Summary report of falsification testing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FalsificationReport {
    /// Installer tested
    pub installer_name: String,
    /// Total hypotheses tested
    pub total_hypotheses: usize,
    /// Hypotheses that were falsified (bugs found)
    pub falsified_count: usize,
    /// Hypotheses that held (no bugs found)
    pub validated_count: usize,
    /// Tests that failed to run
    pub error_count: usize,
    /// Results by category
    pub by_category: HashMap<String, CategorySummary>,
    /// All results
    pub results: Vec<FalsificationResult>,
}

/// Summary for a category
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CategorySummary {
    /// Total tests in category
    pub total: usize,
    /// Tests that falsified hypothesis
    pub falsified: usize,
    /// Tests that validated hypothesis
    pub validated: usize,
}

impl FalsificationReport {
    /// Create report from results
    pub fn from_results(
        installer_name: &str,
        results: Vec<FalsificationResult>,
        hypotheses: &[FalsificationHypothesis],
    ) -> Self {
        let mut by_category: HashMap<String, CategorySummary> = HashMap::new();

        let mut falsified_count = 0;
        let mut validated_count = 0;
        let mut error_count = 0;

        for result in &results {
            if result.error.is_some() {
                error_count += 1;
                continue;
            }

            if result.falsified {
                falsified_count += 1;
            } else {
                validated_count += 1;
            }

            // Find hypothesis category
            if let Some(h) = hypotheses.iter().find(|h| h.id == result.hypothesis_id) {
                let cat = format!("{:?}", h.category);
                let entry = by_category.entry(cat).or_default();
                entry.total += 1;
                if result.falsified {
                    entry.falsified += 1;
                } else {
                    entry.validated += 1;
                }
            }
        }

        Self {
            installer_name: installer_name.to_string(),
            total_hypotheses: results.len(),
            falsified_count,
            validated_count,
            error_count,
            by_category,
            results,
        }
    }

    /// Format as human-readable report
    pub fn format(&self) -> String {
        let mut report = String::new();

        report.push_str(&format!("Falsification Report: {}\n", self.installer_name));
        report.push_str(&"=".repeat(50));
        report.push('\n');

        report.push_str(&format!(
            "Total hypotheses tested: {}\n",
            self.total_hypotheses
        ));
        report.push_str(&format!(
            "  ✓ Validated: {} (no bugs found)\n",
            self.validated_count
        ));
        report.push_str(&format!(
            "  ✗ Falsified: {} (bugs found!)\n",
            self.falsified_count
        ));
        if self.error_count > 0 {
            report.push_str(&format!("  ⚠ Errors: {}\n", self.error_count));
        }

        report.push_str("\nBy Category:\n");
        for (cat, summary) in &self.by_category {
            report.push_str(&format!(
                "  {}: {}/{} validated\n",
                cat, summary.validated, summary.total
            ));
        }

        if self.falsified_count > 0 {
            report.push_str("\nFalsified Hypotheses (Bugs Found):\n");
            for result in &self.results {
                if result.falsified {
                    report.push_str(&format!("  - {}\n", result.hypothesis_id));
                    for evidence in &result.evidence {
                        if !evidence.supports_hypothesis {
                            report.push_str(&format!("{}\n", evidence.observation));
                        }
                    }
                }
            }
        }

        report
    }
}

#[cfg(test)]
#[path = "falsification_tests_sample_insta.rs"]
mod tests_extracted;