aprender-orchestrate 0.31.2

Sovereign AI orchestration: autonomous agents, ML serving, code analysis, and transpilation pipelines
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Falsification Report Generation
//!
//! Generates reports from test execution results.

use serde::{Deserialize, Serialize};
use std::fmt::Write as FmtWrite;

/// Test outcome
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TestOutcome {
    /// Test passed (claim not falsified)
    Passed,
    /// Test failed (claim falsified - this is good!)
    Falsified,
    /// Test skipped
    Skipped,
    /// Test errored (infrastructure issue)
    Error,
}

/// Falsification report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FalsificationReport {
    /// Spec name
    pub spec_name: String,
    /// Test results
    pub results: Vec<TestResult>,
    /// Summary statistics
    pub summary: FalsificationSummary,
    /// Generation timestamp
    pub generated_at: String,
}

/// Single test result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestResult {
    /// Test ID
    pub id: String,
    /// Test name
    pub name: String,
    /// Category
    pub category: String,
    /// Points
    pub points: u32,
    /// Outcome
    pub outcome: TestOutcome,
    /// Error message if any
    pub error: Option<String>,
    /// Evidence collected
    pub evidence: Vec<String>,
}

/// Summary statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FalsificationSummary {
    /// Total tests
    pub total_tests: usize,
    /// Total points
    pub total_points: u32,
    /// Tests passed
    pub passed: usize,
    /// Tests falsified (failures = success in Popperian methodology!)
    pub falsified: usize,
    /// Tests skipped
    pub skipped: usize,
    /// Tests errored
    pub errors: usize,
    /// Falsification rate (target: 5-15%)
    pub falsification_rate: f64,
    /// Points by category
    pub points_by_category: std::collections::HashMap<String, CategoryStats>,
}

/// Category statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CategoryStats {
    pub total: u32,
    pub passed: u32,
    pub falsified: u32,
}

impl FalsificationReport {
    /// Create a new report
    pub fn new(spec_name: String) -> Self {
        Self {
            spec_name,
            results: Vec::new(),
            summary: FalsificationSummary::default(),
            generated_at: chrono::Utc::now().to_rfc3339(),
        }
    }

    /// Add a test result
    pub fn add_result(&mut self, result: TestResult) {
        self.results.push(result);
    }

    /// Finalize and compute summary
    pub fn finalize(&mut self) {
        self.summary.total_tests = self.results.len();
        self.summary.total_points = self.results.iter().map(|r| r.points).sum();

        for result in &self.results {
            match result.outcome {
                TestOutcome::Passed => self.summary.passed += 1,
                TestOutcome::Falsified => self.summary.falsified += 1,
                TestOutcome::Skipped => self.summary.skipped += 1,
                TestOutcome::Error => self.summary.errors += 1,
            }

            let entry = self.summary.points_by_category.entry(result.category.clone()).or_default();
            entry.total += result.points;
            match result.outcome {
                TestOutcome::Passed => entry.passed += result.points,
                TestOutcome::Falsified => entry.falsified += result.points,
                _ => {}
            }
        }

        let executed = self.summary.passed + self.summary.falsified;
        if executed > 0 {
            self.summary.falsification_rate = (self.summary.falsified as f64) / (executed as f64);
        }
    }

    /// Format as markdown
    pub fn format_markdown(&self) -> String {
        let mut out = String::new();

        writeln!(out, "# Falsification Report: {}", self.spec_name).ok();
        writeln!(out).ok();
        writeln!(out, "**Generated**: {}", self.generated_at).ok();
        writeln!(out, "**Total Points**: {}", self.summary.total_points).ok();
        writeln!(out, "**Falsifications Found**: {} (target: 5-15%)", self.summary.falsified).ok();
        writeln!(out).ok();

        writeln!(out, "## Summary").ok();
        writeln!(out).ok();
        writeln!(out, "| Category | Points | Passed | Failed | Pass Rate |").ok();
        writeln!(out, "|----------|--------|--------|--------|-----------|").ok();

        for (category, stats) in &self.summary.points_by_category {
            let pass_rate = if stats.total > 0 {
                (stats.passed as f64 / stats.total as f64) * 100.0
            } else {
                0.0
            };
            writeln!(
                out,
                "| {} | {} | {} | {} | {:.0}% |",
                category, stats.total, stats.passed, stats.falsified, pass_rate
            )
            .ok();
        }
        writeln!(out).ok();

        // Verdict
        let verdict =
            if self.summary.falsification_rate >= 0.05 && self.summary.falsification_rate <= 0.15 {
                "Healthy falsification rate - specification is well-tested"
            } else if self.summary.falsification_rate < 0.05 {
                "Low falsification rate - consider more edge cases"
            } else {
                "High falsification rate - specification needs hardening"
            };

        writeln!(
            out,
            "**Verdict**: {:.1}% falsification rate - {}",
            self.summary.falsification_rate * 100.0,
            verdict
        )
        .ok();
        writeln!(out).ok();

        // Falsifications (failures = success!)
        if self.summary.falsified > 0 {
            writeln!(out, "## Falsifications (Failures = Success!)").ok();
            writeln!(out).ok();

            for result in &self.results {
                if result.outcome == TestOutcome::Falsified {
                    writeln!(out, "### {}: {}", result.id, result.name).ok();
                    writeln!(out, "**Status**: FALSIFIED").ok();
                    writeln!(out, "**Points**: {}", result.points).ok();
                    if let Some(err) = &result.error {
                        writeln!(out, "**Details**: {}", err).ok();
                    }
                    for evidence in &result.evidence {
                        writeln!(out, "- {}", evidence).ok();
                    }
                    writeln!(out).ok();
                }
            }
        }

        out
    }

    /// Format as JSON
    pub fn format_json(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
    }

    /// Format as text
    pub fn format_text(&self) -> String {
        let mut out = String::new();

        writeln!(out, "FALSIFICATION REPORT: {}", self.spec_name).ok();
        writeln!(out, "{}", "=".repeat(60)).ok();
        writeln!(out).ok();

        writeln!(out, "Total Points: {}", self.summary.total_points).ok();
        writeln!(
            out,
            "Falsifications: {} ({:.1}%)",
            self.summary.falsified,
            self.summary.falsification_rate * 100.0
        )
        .ok();
        writeln!(out).ok();

        for result in &self.results {
            let status = match result.outcome {
                TestOutcome::Passed => "PASS",
                TestOutcome::Falsified => "FAIL",
                TestOutcome::Skipped => "SKIP",
                TestOutcome::Error => "ERR",
            };
            writeln!(out, "[{}] {}: {} ({} pts)", status, result.id, result.name, result.points)
                .ok();
        }

        out
    }
}

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

    #[test]
    fn test_report_creation() {
        let report = FalsificationReport::new("test-spec".to_string());
        assert_eq!(report.spec_name, "test-spec");
    }

    #[test]
    fn test_report_finalize() {
        let mut report = FalsificationReport::new("test".to_string());

        report.add_result(TestResult {
            id: "BC-001".to_string(),
            name: "Test 1".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Passed,
            error: None,
            evidence: vec![],
        });

        report.add_result(TestResult {
            id: "BC-002".to_string(),
            name: "Test 2".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Falsified,
            error: Some("Found edge case".to_string()),
            evidence: vec!["Input: empty".to_string()],
        });

        report.finalize();

        assert_eq!(report.summary.total_tests, 2);
        assert_eq!(report.summary.passed, 1);
        assert_eq!(report.summary.falsified, 1);
        assert!((report.summary.falsification_rate - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_format_markdown() {
        let mut report = FalsificationReport::new("test".to_string());
        report.add_result(TestResult {
            id: "BC-001".to_string(),
            name: "Empty input".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Passed,
            error: None,
            evidence: vec![],
        });
        report.finalize();

        let md = report.format_markdown();
        assert!(md.contains("Falsification Report"));
        assert!(md.contains("boundary"));
    }

    #[test]
    fn test_format_json() {
        let mut report = FalsificationReport::new("json-test".to_string());
        report.add_result(TestResult {
            id: "BC-001".to_string(),
            name: "Test".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Passed,
            error: None,
            evidence: vec![],
        });
        report.finalize();

        let json = report.format_json();
        assert!(json.contains("json-test"));
        assert!(json.contains("BC-001"));
        assert!(json.contains("boundary"));
    }

    #[test]
    fn test_format_text() {
        let mut report = FalsificationReport::new("text-test".to_string());
        report.add_result(TestResult {
            id: "BC-001".to_string(),
            name: "Test".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Passed,
            error: None,
            evidence: vec![],
        });
        report.add_result(TestResult {
            id: "BC-002".to_string(),
            name: "Test 2".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Falsified,
            error: None,
            evidence: vec![],
        });
        report.finalize();

        let text = report.format_text();
        assert!(text.contains("FALSIFICATION REPORT"));
        assert!(text.contains("text-test"));
        assert!(text.contains("[PASS]"));
        assert!(text.contains("[FAIL]"));
    }

    #[test]
    fn test_test_outcome_equality() {
        assert_eq!(TestOutcome::Passed, TestOutcome::Passed);
        assert_eq!(TestOutcome::Falsified, TestOutcome::Falsified);
        assert_eq!(TestOutcome::Skipped, TestOutcome::Skipped);
        assert_eq!(TestOutcome::Error, TestOutcome::Error);
        assert_ne!(TestOutcome::Passed, TestOutcome::Falsified);
    }

    #[test]
    fn test_falsification_summary_default() {
        let summary = FalsificationSummary::default();
        assert_eq!(summary.total_tests, 0);
        assert_eq!(summary.total_points, 0);
        assert_eq!(summary.passed, 0);
        assert_eq!(summary.falsified, 0);
        assert_eq!(summary.skipped, 0);
        assert_eq!(summary.errors, 0);
        assert!((summary.falsification_rate - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_category_stats_default() {
        let stats = CategoryStats::default();
        assert_eq!(stats.total, 0);
        assert_eq!(stats.passed, 0);
        assert_eq!(stats.falsified, 0);
    }

    #[test]
    fn test_report_with_all_outcomes() {
        let mut report = FalsificationReport::new("all-outcomes".to_string());

        report.add_result(TestResult {
            id: "T-001".to_string(),
            name: "Passed".to_string(),
            category: "test".to_string(),
            points: 1,
            outcome: TestOutcome::Passed,
            error: None,
            evidence: vec![],
        });
        report.add_result(TestResult {
            id: "T-002".to_string(),
            name: "Falsified".to_string(),
            category: "test".to_string(),
            points: 2,
            outcome: TestOutcome::Falsified,
            error: None,
            evidence: vec![],
        });
        report.add_result(TestResult {
            id: "T-003".to_string(),
            name: "Skipped".to_string(),
            category: "test".to_string(),
            points: 3,
            outcome: TestOutcome::Skipped,
            error: None,
            evidence: vec![],
        });
        report.add_result(TestResult {
            id: "T-004".to_string(),
            name: "Error".to_string(),
            category: "test".to_string(),
            points: 4,
            outcome: TestOutcome::Error,
            error: Some("Infra issue".to_string()),
            evidence: vec![],
        });

        report.finalize();

        assert_eq!(report.summary.total_tests, 4);
        assert_eq!(report.summary.passed, 1);
        assert_eq!(report.summary.falsified, 1);
        assert_eq!(report.summary.skipped, 1);
        assert_eq!(report.summary.errors, 1);
    }

    #[test]
    fn test_report_format_text_status_codes() {
        let mut report = FalsificationReport::new("status".to_string());
        report.add_result(TestResult {
            id: "T-001".to_string(),
            name: "Skip".to_string(),
            category: "test".to_string(),
            points: 1,
            outcome: TestOutcome::Skipped,
            error: None,
            evidence: vec![],
        });
        report.add_result(TestResult {
            id: "T-002".to_string(),
            name: "Err".to_string(),
            category: "test".to_string(),
            points: 1,
            outcome: TestOutcome::Error,
            error: None,
            evidence: vec![],
        });
        report.finalize();

        let text = report.format_text();
        assert!(text.contains("[SKIP]"));
        assert!(text.contains("[ERR]"));
    }

    #[test]
    fn test_markdown_with_falsifications() {
        let mut report = FalsificationReport::new("falsify-test".to_string());
        report.add_result(TestResult {
            id: "BC-001".to_string(),
            name: "Edge case".to_string(),
            category: "boundary".to_string(),
            points: 5,
            outcome: TestOutcome::Falsified,
            error: Some("Assertion failed".to_string()),
            evidence: vec!["Input: empty".to_string(), "Expected: error".to_string()],
        });
        report.finalize();

        let md = report.format_markdown();
        assert!(md.contains("Falsifications (Failures = Success!)"));
        assert!(md.contains("BC-001"));
        assert!(md.contains("FALSIFIED"));
        assert!(md.contains("Assertion failed"));
        assert!(md.contains("Input: empty"));
    }

    #[test]
    fn test_markdown_healthy_rate() {
        let mut report = FalsificationReport::new("healthy".to_string());
        for i in 0..19 {
            report.add_result(TestResult {
                id: format!("T-{:03}", i),
                name: format!("Test {}", i),
                category: "test".to_string(),
                points: 1,
                outcome: TestOutcome::Passed,
                error: None,
                evidence: vec![],
            });
        }
        report.add_result(TestResult {
            id: "T-019".to_string(),
            name: "Falsified".to_string(),
            category: "test".to_string(),
            points: 1,
            outcome: TestOutcome::Falsified,
            error: None,
            evidence: vec![],
        });
        report.finalize();

        // 1/20 = 5% = healthy
        let md = report.format_markdown();
        assert!(md.contains("well-tested"));
    }

    #[test]
    fn test_markdown_low_falsification_rate() {
        let mut report = FalsificationReport::new("low".to_string());
        for i in 0..100 {
            report.add_result(TestResult {
                id: format!("T-{:03}", i),
                name: format!("Test {}", i),
                category: "test".to_string(),
                points: 1,
                outcome: TestOutcome::Passed,
                error: None,
                evidence: vec![],
            });
        }
        report.finalize();

        let md = report.format_markdown();
        assert!(md.contains("more edge cases"));
    }
}