whyyoulying 0.1.0

Proactive detection of Labor Category Fraud and Ghost Billing
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
//! f49–f60 self-eval. Only compiled with tests feature. whyyoulying-test binary runs this.

use std::path::PathBuf;
use std::process::Command;

/// Path to release binary (whyyoulying). E2E tests invoke it.
fn release_bin() -> PathBuf {
    let exe = std::env::current_exe().expect("current exe");
    let dir = exe.parent().expect("parent");
    let stem = exe.file_stem().and_then(|s| s.to_str()).unwrap_or("whyyoulying-test");
    let release_stem = stem.strip_suffix("-test").unwrap_or("whyyoulying");
    let suffix = std::env::consts::EXE_SUFFIX;
    dir.join(format!("{release_stem}{suffix}"))
}

fn fixtures_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures")
}

fn run_bin(args: &[&str]) -> (std::process::Output, String, String) {
    let exe = release_bin();
    let out = Command::new(&exe).args(args).output().unwrap();
    let stdout = String::from_utf8(out.stdout.clone()).unwrap();
    let stderr = String::from_utf8(out.stderr.clone()).unwrap();
    (out, stdout, stderr)
}

/// f30 = run_tests
pub fn f30() -> i32 {
    let mut failed = 0;
    let green = "\x1b[32m";
    let red = "\x1b[31m";
    let reset = "\x1b[0m";

    for (name, pass) in [
        ("f49 unit", f49()),
        ("f50 integration", f50()),
        ("f51 e2e", f51()),
        ("f52 run fixtures", f52()),
        ("f53 min-confidence", f53()),
        ("f54 ingest", f54()),
        ("f55 missing data_path", f55()),
        ("f56 agency filter", f56()),
        ("f57 csv output", f57()),
        ("f58 export-referral", f58()),
        ("f59 export-fbi", f59()),
        ("f60 empty exit zero", f60()),
        // Swiss Army Knife tests
        ("f61 rate inflation", f61()),
        ("f62 overtime padding", f62()),
        ("f63 duplicate billing", f63()),
        ("f64 new rule ids", f64()),
    ] {
        print!("{name}: ");
        if pass {
            println!("{green}PASS{reset}");
        } else {
            println!("{red}FAIL{reset}");
            failed += 1;
        }
    }

    if failed > 0 {
        eprintln!("\n{failed} test(s) failed");
        1
    } else {
        eprintln!("\nall tests passed");
        0
    }
}

fn f49() -> bool {
    use crate::{Alert, Config, Dataset, FraudType, LaborDetector, RuleId};

    let cfg = Config::default();
    assert!(cfg.labor_variance_threshold_pct > 0.0);

    let labor = LaborDetector::new(15.0);
    let ds = Dataset::default();
    let alerts = labor.run(&ds);
    assert!(alerts.is_empty());

    let alert = Alert {
        fraud_type: FraudType::LaborCategory,
        rule_id: RuleId::LaborVariance,
        severity: 5,
        confidence: 85,
        summary: "test".to_string(),
        contract_id: Some("C1".to_string()),
        employee_id: Some("E1".to_string()),
        cage_code: None,
        agency: None,
        predicate_acts: None,
        timestamp: Some("2026-01-01T00:00:00Z".to_string()),
        monetary_impact: None,
        related_alerts: None,
    };
    let json = serde_json::to_string(&alert).unwrap();
    assert!(json.contains("labor_category"));
    assert!(json.contains("LABOR_VARIANCE"));

    true
}

fn f50() -> bool {
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let p = tmp.path();

    let contracts = serde_json::json!([{"id":"C1","cage_code":null,"agency":null,"labor_cats":{"Senior":"BA"}}]);
    std::fs::write(p.join("contracts.json"), contracts.to_string()).unwrap();

    let employees = serde_json::json!([{"id":"E1","quals":["BA"],"labor_cat_min":"Junior","verified":false}]);
    std::fs::write(p.join("employees.json"), employees.to_string()).unwrap();

    let labor = serde_json::json!([{"contract_id":"C1","employee_id":"E1","labor_cat":"Principal","hours":40.0,"rate":150.0}]);
    std::fs::write(p.join("labor_charges.json"), labor.to_string()).unwrap();

    let billing = serde_json::json!([{"contract_id":"C1","employee_id":"E99","billed_hours":10.0,"billed_cat":"Junior","period":"2026-01"}]);
    std::fs::write(p.join("billing_records.json"), billing.to_string()).unwrap();

    let ds = crate::Ingest::load_from_path(p).unwrap();
    assert_eq!(ds.contracts.len(), 1);
    assert_eq!(ds.employees.len(), 1);
    assert_eq!(ds.labor_charges.len(), 1);
    assert_eq!(ds.billing_records.len(), 1);

    let labor_det = crate::LaborDetector::new(15.0);
    let ghost_det = crate::GhostDetector::new();
    let labor_alerts = labor_det.run(&ds);
    let ghost_alerts = ghost_det.run(&ds);
    assert!(!labor_alerts.is_empty());
    assert!(labor_alerts.iter().any(|a| format!("{:?}", a.rule_id).contains("LaborQualBelow")));
    assert!(!ghost_alerts.is_empty());
    assert!(ghost_alerts.iter().any(|a| format!("{:?}", a.rule_id).contains("GhostNoEmployee")));

    true
}

fn f51() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f51: fixtures dir required");
    let out = Command::new(release_bin())
        .arg("--data-path")
        .arg(&fixtures)
        .output()
        .unwrap();
    assert!(out.status.success() || out.status.code() == Some(1));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let stderr = String::from_utf8(out.stderr).unwrap();
    if stdout.is_empty() && !out.status.success() {
        eprintln!("f51 stderr: {stderr}");
    }
    if !stdout.is_empty() {
        let parsed: Result<Vec<serde_json::Value>, _> = serde_json::from_str(&stdout);
        assert!(parsed.is_ok(), "f51: stdout should be valid JSON array");
    }
    true
}

fn f52() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f52: fixtures dir required");
    let (out, stdout, _) = run_bin(&["--data-path", fixtures.to_str().unwrap()]);
    assert!(out.status.code() == Some(1));
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&stdout).unwrap();
    assert!(!parsed.is_empty());
    true
}

fn f53() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f53: fixtures dir required");
    let (_, stdout, _) = run_bin(&[
        "--data-path",
        fixtures.to_str().unwrap(),
        "--min-confidence",
        "99",
    ]);
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&stdout).unwrap();
    for a in &parsed {
        assert!(a["confidence"].as_u64().unwrap_or(0) >= 99);
    }
    true
}

fn f54() -> bool {
    let tmp = tempfile::TempDir::new().unwrap();
    std::fs::write(tmp.path().join("contracts.json"), "[]").unwrap();
    let (out, _, _) = run_bin(&["ingest", "--data-path", tmp.path().to_str().unwrap()]);
    assert!(out.status.success());
    true
}

fn f55() -> bool {
    let (out, _, stderr) = run_bin(&["run"]);
    assert!(!out.status.success());
    assert!(stderr.contains("data_path") || stderr.contains("error"));
    true
}

fn f56() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f56: fixtures dir required");
    let (_, stdout, _) = run_bin(&[
        "--data-path",
        fixtures.to_str().unwrap(),
        "--agency",
        "DoD",
    ]);
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&stdout).unwrap();
    for a in &parsed {
        assert_eq!(a["agency"].as_str(), Some("DoD"));
    }
    true
}

fn f57() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f57: fixtures dir required");
    let (_, stdout, _) = run_bin(&[
        "--data-path",
        fixtures.to_str().unwrap(),
        "--output",
        "csv",
    ]);
    assert!(stdout.contains("fraud_type"));
    assert!(stdout.contains("confidence"));
    assert!(stdout.lines().count() >= 2);
    true
}

fn f58() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f58: fixtures dir required");
    let tmp = tempfile::TempDir::new().unwrap();
    let p = tmp.path().join("ref.json");
    let (out, _, _) = run_bin(&[
        "--data-path",
        fixtures.to_str().unwrap(),
        "export-referral",
        "--path",
        p.to_str().unwrap(),
    ]);
    assert!(out.status.code() == Some(0) || out.status.code() == Some(1));
    assert!(p.exists());
    let content = std::fs::read_to_string(&p).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert!(parsed["document_type"].as_str().unwrap().contains("DoD"));
    true
}

fn f59() -> bool {
    let fixtures = fixtures_path();
    assert!(fixtures.exists(), "f59: fixtures dir required");
    let tmp = tempfile::TempDir::new().unwrap();
    let p = tmp.path().join("fbi.json");
    let (out, _, _) = run_bin(&[
        "--data-path",
        fixtures.to_str().unwrap(),
        "export-referral",
        "--fbi",
        "--path",
        p.to_str().unwrap(),
    ]);
    assert!(out.status.code() == Some(0) || out.status.code() == Some(1));
    let content = std::fs::read_to_string(&p).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert!(parsed["document_type"].as_str().unwrap().contains("FBI"));
    true
}

fn f60() -> bool {
    let tmp = tempfile::TempDir::new().unwrap();
    std::fs::write(tmp.path().join("contracts.json"), "[]").unwrap();
    std::fs::write(tmp.path().join("employees.json"), "[]").unwrap();
    std::fs::write(tmp.path().join("labor_charges.json"), "[]").unwrap();
    std::fs::write(tmp.path().join("billing_records.json"), "[]").unwrap();
    let (out, stdout, _) = run_bin(&["--data-path", tmp.path().to_str().unwrap()]);
    assert!(out.status.success());
    assert_eq!(stdout.trim(), "[]");
    true
}

// === Swiss Army Knife Integration Tests ===

fn f61() -> bool {
    // Test RateInflationDetector
    use crate::RateInflationDetector;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let p = tmp.path();

    // Create test data with rate inflation scenario
    let contracts = serde_json::json!([{"id":"C1","cage_code":"1ABC2","agency":"DoD","labor_cats":{"Senior":"BA"}}]);
    std::fs::write(p.join("contracts.json"), contracts.to_string()).unwrap();

    let employees = serde_json::json!([{"id":"E1","quals":["BA"],"labor_cat_min":"Senior","verified":true}]);
    std::fs::write(p.join("employees.json"), employees.to_string()).unwrap();

    // Employee paid $100/hr but billed at $150/hr (50% inflation)
    let labor = serde_json::json!([
        {"contract_id":"C1","employee_id":"E1","labor_cat":"Senior","hours":40.0,"rate":100.0},
        {"contract_id":"C1","employee_id":"E1","labor_cat":"Senior","hours":40.0,"rate":150.0}
    ]);
    std::fs::write(p.join("labor_charges.json"), labor.to_string()).unwrap();

    let billing = serde_json::json!([{"contract_id":"C1","employee_id":"E1","billed_hours":40.0,"billed_cat":"Senior","period":"2026-01"}]);
    std::fs::write(p.join("billing_records.json"), billing.to_string()).unwrap();

    let ds = crate::Ingest::load_from_path(p).unwrap();
    let det = RateInflationDetector::new(25.0);
    let alerts = det.run(&ds);
    // Test that detector runs without error
    let _ = alerts;
    true
}

fn f62() -> bool {
    // Test OvertimePaddingDetector
    use crate::OvertimePaddingDetector;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let p = tmp.path();

    let contracts = serde_json::json!([{"id":"C1","cage_code":"1ABC2","agency":"DoD","labor_cats":{}}]);
    std::fs::write(p.join("contracts.json"), contracts.to_string()).unwrap();

    let employees = serde_json::json!([{"id":"E1","quals":[],"labor_cat_min":null,"verified":true}]);
    std::fs::write(p.join("employees.json"), employees.to_string()).unwrap();

    // 70 hours in one week (exceeds 60 hr threshold)
    let labor = serde_json::json!([{"contract_id":"C1","employee_id":"E1","labor_cat":"Senior","hours":70.0,"rate":null,"period":"2026-01-W1"}]);
    std::fs::write(p.join("labor_charges.json"), labor.to_string()).unwrap();

    let billing = serde_json::json!([{"contract_id":"C1","employee_id":"E1","billed_hours":70.0,"billed_cat":"Senior","period":"2026-01-W1"}]);
    std::fs::write(p.join("billing_records.json"), billing.to_string()).unwrap();

    let ds = crate::Ingest::load_from_path(p).unwrap();
    let det = OvertimePaddingDetector::new(60.0, 240.0);
    let alerts = det.run(&ds);
    // Test that detector runs and detects overtime
    assert!(!alerts.is_empty(), "f62: should detect overtime padding");
    assert!(alerts.iter().any(|a| format!("{:?}", a.rule_id).contains("OvertimePadding")));
    true
}

fn f63() -> bool {
    // Test DuplicateBillingDetector
    use crate::DuplicateBillingDetector;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let p = tmp.path();

    let contracts = serde_json::json!([
        {"id":"C1","cage_code":"1ABC2","agency":"DoD","labor_cats":{}},
        {"id":"C2","cage_code":"1ABC2","agency":"DoD","labor_cats":{}}
    ]);
    std::fs::write(p.join("contracts.json"), contracts.to_string()).unwrap();

    let employees = serde_json::json!([{"id":"E1","quals":[],"labor_cat_min":null,"verified":true}]);
    std::fs::write(p.join("employees.json"), employees.to_string()).unwrap();

    let labor = serde_json::json!([{"contract_id":"C1","employee_id":"E1","labor_cat":"Senior","hours":40.0,"rate":null,"period":"2026-01-W1"}]);
    std::fs::write(p.join("labor_charges.json"), labor.to_string()).unwrap();

    // Same employee, same hours, same period, different contracts = duplicate billing
    let billing = serde_json::json!([
        {"contract_id":"C1","employee_id":"E1","billed_hours":40.0,"billed_cat":"Senior","period":"2026-01-W1"},
        {"contract_id":"C2","employee_id":"E1","billed_hours":40.0,"billed_cat":"Senior","period":"2026-01-W1"}
    ]);
    std::fs::write(p.join("billing_records.json"), billing.to_string()).unwrap();

    let ds = crate::Ingest::load_from_path(p).unwrap();
    let det = DuplicateBillingDetector::new();
    let alerts = det.run(&ds);
    assert!(!alerts.is_empty(), "f63: should detect duplicate billing");
    assert!(alerts.iter().any(|a| format!("{:?}", a.rule_id).contains("DuplicateBilling")));
    true
}

fn f64() -> bool {
    // Test new RuleId variants exist and serialize correctly
    use crate::types::RuleId;

    let variants = [
        RuleId::RateInflation,
        RuleId::OvertimePadding,
        RuleId::DuplicateBilling,
    ];

    for rule in &variants {
        let json = serde_json::to_string(&rule).unwrap();
        assert!(!json.is_empty());
        // Verify they serialize to SCREAMING_SNAKE_CASE
        assert!(json.chars().next().unwrap().is_uppercase() || json.contains("_"));
    }

    // Verify display formatting
    assert_eq!(format!("{}", RuleId::RateInflation), "RATE_INFLATION");
    assert_eq!(format!("{}", RuleId::OvertimePadding), "OVERTIME_PADDING");
    assert_eq!(format!("{}", RuleId::DuplicateBilling), "DUPLICATE_BILLING");

    true
}