tandem-server 0.5.5

HTTP server for Tandem engine APIs
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionProfile {
    #[default]
    Strict,
    Guided,
    Yolo,
}

impl ExecutionProfile {
    pub fn as_str(self) -> &'static str {
        match self {
            ExecutionProfile::Strict => "strict",
            ExecutionProfile::Guided => "guided",
            ExecutionProfile::Yolo => "yolo",
        }
    }

    pub fn allows_validation_warning(self) -> bool {
        matches!(self, ExecutionProfile::Guided | ExecutionProfile::Yolo)
    }

    pub fn allows_experimental_continue(self) -> bool {
        matches!(self, ExecutionProfile::Yolo)
    }

    pub fn repair_budget_multiplier(self) -> f32 {
        match self {
            ExecutionProfile::Strict => 1.0,
            ExecutionProfile::Guided => 1.5,
            ExecutionProfile::Yolo => 2.0,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ValidatorClass {
    MissingRequiredSection,
    WeakMarkdownStructure,
    MissingOptionalEvidence,
    ArtifactWordCountBelowMinimum,
    MissingNonconsumedWorkspaceFiles,
    RequiredSourcePathsNotRead,
    MissingRequiredArtifactPath,
    ValidatorKindSpecificSoftCheck,
    RepairBudgetExhausted,
    UnauthorizedWorkspace,
    SecretAccessDenied,
    DestructiveActionRequiresApproval,
    ExternalPublishRequiresApproval,
    TenantPolicyDenied,
    ToolUnauthorized,
    BudgetExceeded,
    KillSwitchEngaged,
    EngineLeaseExpired,
    InvalidApiToken,
    DeterministicVerificationFailed,
}

impl ValidatorClass {
    pub fn is_critical(self) -> bool {
        matches!(
            self,
            ValidatorClass::UnauthorizedWorkspace
                | ValidatorClass::SecretAccessDenied
                | ValidatorClass::DestructiveActionRequiresApproval
                | ValidatorClass::ExternalPublishRequiresApproval
                | ValidatorClass::TenantPolicyDenied
                | ValidatorClass::ToolUnauthorized
                | ValidatorClass::BudgetExceeded
                | ValidatorClass::KillSwitchEngaged
                | ValidatorClass::EngineLeaseExpired
                | ValidatorClass::InvalidApiToken
                | ValidatorClass::DeterministicVerificationFailed
        )
    }

    pub fn is_relaxable_in(self, profile: ExecutionProfile) -> bool {
        if self.is_critical() {
            return false;
        }
        match (self, profile) {
            (_, ExecutionProfile::Strict) => false,
            (
                ValidatorClass::MissingRequiredSection
                | ValidatorClass::WeakMarkdownStructure
                | ValidatorClass::MissingOptionalEvidence
                | ValidatorClass::ArtifactWordCountBelowMinimum
                | ValidatorClass::MissingNonconsumedWorkspaceFiles,
                ExecutionProfile::Guided | ExecutionProfile::Yolo,
            ) => true,
            (
                ValidatorClass::MissingRequiredArtifactPath
                | ValidatorClass::ValidatorKindSpecificSoftCheck
                | ValidatorClass::RepairBudgetExhausted,
                ExecutionProfile::Yolo,
            ) => true,
            _ => false,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            ValidatorClass::MissingRequiredSection => "missing_required_section",
            ValidatorClass::WeakMarkdownStructure => "weak_markdown_structure",
            ValidatorClass::MissingOptionalEvidence => "missing_optional_evidence",
            ValidatorClass::ArtifactWordCountBelowMinimum => "artifact_word_count_below_minimum",
            ValidatorClass::MissingNonconsumedWorkspaceFiles => {
                "missing_nonconsumed_workspace_files"
            }
            ValidatorClass::RequiredSourcePathsNotRead => "required_source_paths_not_read",
            ValidatorClass::MissingRequiredArtifactPath => "missing_required_artifact_path",
            ValidatorClass::ValidatorKindSpecificSoftCheck => "validator_kind_specific_soft_check",
            ValidatorClass::RepairBudgetExhausted => "repair_budget_exhausted",
            ValidatorClass::UnauthorizedWorkspace => "unauthorized_workspace",
            ValidatorClass::SecretAccessDenied => "secret_access_denied",
            ValidatorClass::DestructiveActionRequiresApproval => {
                "destructive_action_requires_approval"
            }
            ValidatorClass::ExternalPublishRequiresApproval => "external_publish_requires_approval",
            ValidatorClass::TenantPolicyDenied => "tenant_policy_denied",
            ValidatorClass::ToolUnauthorized => "tool_unauthorized",
            ValidatorClass::BudgetExceeded => "budget_exceeded",
            ValidatorClass::KillSwitchEngaged => "kill_switch_engaged",
            ValidatorClass::EngineLeaseExpired => "engine_lease_expired",
            ValidatorClass::InvalidApiToken => "invalid_api_token",
            ValidatorClass::DeterministicVerificationFailed => "deterministic_verification_failed",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ValidationOutcome {
    Passed,
    Warning,
    Experimental,
    Blocked,
}

impl ValidationOutcome {
    pub fn as_str(self) -> &'static str {
        match self {
            ValidationOutcome::Passed => "passed",
            ValidationOutcome::Warning => "warning",
            ValidationOutcome::Experimental => "experimental",
            ValidationOutcome::Blocked => "blocked",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RelaxedValidatorClass {
    pub class: ValidatorClass,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    pub original_outcome: ValidationOutcome,
    pub effective_outcome: ValidationOutcome,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProfileValidationDecision {
    pub profile: ExecutionProfile,
    pub original_outcome: ValidationOutcome,
    pub effective_outcome: ValidationOutcome,
    pub should_block: bool,
    pub experimental: bool,
    pub relaxed_classes: Vec<RelaxedValidatorClass>,
}

impl ProfileValidationDecision {
    pub fn passthrough(profile: ExecutionProfile, outcome: ValidationOutcome) -> Self {
        ProfileValidationDecision {
            profile,
            original_outcome: outcome,
            effective_outcome: outcome,
            should_block: matches!(outcome, ValidationOutcome::Blocked),
            experimental: false,
            relaxed_classes: Vec::new(),
        }
    }
}

/// Single chokepoint: given a non-pass validator outcome and the validator
/// classes that triggered it, decide what the run/node should actually see
/// under the active profile. All profile-driven downgrades MUST flow through
/// this function — see `docs/internal/execution-profiles/PROPOSAL.md`
/// "Executor Chokepoint Invariant".
pub fn decide_profile_validation(
    profile: ExecutionProfile,
    original_outcome: ValidationOutcome,
    classes: &[(ValidatorClass, Option<String>)],
    tenant_relaxation_denylist: &[ValidatorClass],
) -> ProfileValidationDecision {
    if matches!(
        original_outcome,
        ValidationOutcome::Passed | ValidationOutcome::Warning
    ) {
        return ProfileValidationDecision::passthrough(profile, original_outcome);
    }

    if classes.is_empty() {
        return ProfileValidationDecision::passthrough(profile, original_outcome);
    }

    let any_critical = classes.iter().any(|(class, _)| class.is_critical());
    if any_critical {
        return ProfileValidationDecision::passthrough(profile, ValidationOutcome::Blocked);
    }

    let any_tenant_denied = classes
        .iter()
        .any(|(class, _)| tenant_relaxation_denylist.contains(class));
    if any_tenant_denied {
        return ProfileValidationDecision::passthrough(profile, ValidationOutcome::Blocked);
    }

    let all_relaxable = classes
        .iter()
        .all(|(class, _)| class.is_relaxable_in(profile));
    if !all_relaxable {
        return ProfileValidationDecision::passthrough(profile, ValidationOutcome::Blocked);
    }

    let effective_outcome = match profile {
        ExecutionProfile::Strict => ValidationOutcome::Blocked,
        ExecutionProfile::Guided => ValidationOutcome::Warning,
        ExecutionProfile::Yolo => ValidationOutcome::Experimental,
    };

    let relaxed_classes = classes
        .iter()
        .map(|(class, detail)| RelaxedValidatorClass {
            class: *class,
            detail: detail.clone(),
            original_outcome,
            effective_outcome,
        })
        .collect();

    ProfileValidationDecision {
        profile,
        original_outcome,
        effective_outcome,
        should_block: matches!(effective_outcome, ValidationOutcome::Blocked),
        experimental: matches!(effective_outcome, ValidationOutcome::Experimental),
        relaxed_classes,
    }
}

/// Marks an output as carrying experimental input taint when one or more
/// upstream node outputs are themselves experimental. Pure metadata: writes
/// `artifact_validation.experimental = true` and
/// `artifact_validation.tainted_inputs = [upstream_node_id, ...]` without
/// touching `output.status`. Returns `true` when taint was applied.
///
/// Rationale (PROPOSAL.md "Experimental Propagation"): a downstream node's
/// own validation may pass even when its inputs were accepted under a
/// relaxed profile. Without taint propagation the run-level
/// "experimental" flag would silently disappear at the first cleanly-passing
/// downstream step. Propagating taint keeps receipts honest and lets
/// `run_completed` consumers filter experimental runs.
pub fn propagate_experimental_input_taint<'a, I>(output: &mut Value, upstream_outputs: I) -> bool
where
    I: IntoIterator<Item = (&'a str, &'a Value)>,
{
    let tainted: Vec<String> = upstream_outputs
        .into_iter()
        .filter_map(|(node_id, upstream_output)| {
            let is_experimental = upstream_output
                .get("artifact_validation")
                .and_then(|av| av.get("experimental"))
                .and_then(Value::as_bool)
                .unwrap_or(false);
            if is_experimental {
                Some(node_id.to_string())
            } else {
                None
            }
        })
        .collect();
    if tainted.is_empty() {
        return false;
    }

    let object = match output.as_object_mut() {
        Some(map) => map,
        None => return false,
    };
    if !object.contains_key("artifact_validation") {
        object.insert(
            "artifact_validation".to_string(),
            Value::Object(serde_json::Map::new()),
        );
    }
    let validation = object
        .get_mut("artifact_validation")
        .and_then(Value::as_object_mut)
        .expect("artifact_validation present (just inserted if missing)");

    let already_experimental = validation
        .get("experimental")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    validation.insert("experimental".to_string(), json!(true));
    validation
        .entry("tainted_inputs".to_string())
        .or_insert_with(|| Value::Array(Vec::new()));
    if let Some(arr) = validation
        .get_mut("tainted_inputs")
        .and_then(Value::as_array_mut)
    {
        for node_id in tainted {
            let already_listed = arr.iter().any(|value| value.as_str() == Some(&node_id));
            if !already_listed {
                arr.push(json!(node_id));
            }
        }
    }
    !already_experimental
}

/// Parses a string into an `ExecutionProfile`, accepting the same
/// snake_case wire form as serde plus a few common aliases. Trims and
/// lowercases the input. Empty strings and unknown values return `None`.
///
/// Used for parsing operator-supplied tenant-default settings (e.g.
/// `TANDEM_DEFAULT_EXECUTION_PROFILE` env var) without forcing operators
/// to remember exact casing.
pub fn parse_execution_profile_str(raw: &str) -> Option<ExecutionProfile> {
    let normalized = raw.trim().to_ascii_lowercase();
    match normalized.as_str() {
        "strict" => Some(ExecutionProfile::Strict),
        "guided" | "assisted" | "warn" => Some(ExecutionProfile::Guided),
        "yolo" | "exploratory" | "lenient" | "permissive" => Some(ExecutionProfile::Yolo),
        _ => None,
    }
}

/// Reads the tenant-level default execution profile from the
/// `TANDEM_DEFAULT_EXECUTION_PROFILE` environment variable. Returns
/// `None` when the variable is unset, empty, or names an unknown value
/// (operators get safe Strict fallback rather than a panic on typos).
///
/// Run-creation paths consult this before falling back to the system
/// default of Guided, so the precedence chain is:
///   run override → workflow policy → tenant default → Guided.
pub fn tenant_default_execution_profile_from_env() -> Option<ExecutionProfile> {
    std::env::var("TANDEM_DEFAULT_EXECUTION_PROFILE")
        .ok()
        .as_deref()
        .and_then(parse_execution_profile_str)
}

/// Parses a comma-separated list of validator class names into the
/// `ValidatorClass` taxonomy. Trims and lowercases each entry; unknown
/// entries are silently skipped (operators get a safe under-restriction
/// fallback rather than a panic on typos). Recognized inputs match the
/// canonical `as_str` form, e.g. `missing_required_section`,
/// `weak_markdown_structure`, `repair_budget_exhausted`.
pub fn parse_validator_class_list(raw: &str) -> Vec<ValidatorClass> {
    raw.split(',')
        .filter_map(|item| {
            let normalized = item.trim().to_ascii_lowercase();
            match normalized.as_str() {
                "missing_required_section" => Some(ValidatorClass::MissingRequiredSection),
                "weak_markdown_structure" => Some(ValidatorClass::WeakMarkdownStructure),
                "missing_optional_evidence" => Some(ValidatorClass::MissingOptionalEvidence),
                "artifact_word_count_below_minimum" => {
                    Some(ValidatorClass::ArtifactWordCountBelowMinimum)
                }
                "missing_nonconsumed_workspace_files" => {
                    Some(ValidatorClass::MissingNonconsumedWorkspaceFiles)
                }
                "missing_required_artifact_path" => {
                    Some(ValidatorClass::MissingRequiredArtifactPath)
                }
                "validator_kind_specific_soft_check" => {
                    Some(ValidatorClass::ValidatorKindSpecificSoftCheck)
                }
                "repair_budget_exhausted" => Some(ValidatorClass::RepairBudgetExhausted),
                _ => None,
            }
        })
        .collect()
}

/// Reads the tenant-level relaxation denylist from the
/// `TANDEM_RELAXATION_DENYLIST` environment variable. Returns the list
/// of `ValidatorClass` values that should NEVER be relaxed under any
/// profile, even when the chokepoint would otherwise allow them.
///
/// Operators set this to insist that specific validator classes always
/// block (e.g. `missing_required_artifact_path,repair_budget_exhausted`)
/// while still benefiting from the rest of the relaxation set under
/// Guided/Lenient. Empty/unset returns an empty Vec — no classes are
/// denied beyond the always-critical hard set.
pub fn tenant_relaxation_denylist_from_env() -> Vec<ValidatorClass> {
    std::env::var("TANDEM_RELAXATION_DENYLIST")
        .ok()
        .as_deref()
        .map(parse_validator_class_list)
        .unwrap_or_default()
}

/// Human-applied accept/reject signal on a relaxed (Guided/Lenient) artifact.
///
/// Together with `relaxed_validator_classes`, this is the input to the
/// graduation loop: classes whose accept-rate is high enough over a rolling
/// window can be promoted from "experimental" to "supported", or moved
/// from Lenient into Guided. `Unmarked` is the default — it represents
/// "no human has reviewed this yet" rather than a neutral verdict, and
/// must not be confused with `Accepted`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "snake_case")]
pub enum HumanDisposition {
    #[default]
    Unmarked,
    Accepted,
    Rejected,
    ReRanStrict,
}

impl HumanDisposition {
    pub fn as_str(self) -> &'static str {
        match self {
            HumanDisposition::Unmarked => "unmarked",
            HumanDisposition::Accepted => "accepted",
            HumanDisposition::Rejected => "rejected",
            HumanDisposition::ReRanStrict => "re_ran_strict",
        }
    }
}

/// Parses a human-disposition string from API/UI input. Accepts the canonical
/// snake_case form plus a few operator-friendly aliases (`approve`/`reject`/
/// `rerun`). Whitespace and case are normalized. Unknown strings return
/// `None` — callers should reject those rather than silently coercing.
pub fn parse_human_disposition_str(raw: &str) -> Option<HumanDisposition> {
    let normalized = raw.trim().to_ascii_lowercase();
    match normalized.as_str() {
        "unmarked" | "" | "none" | "clear" => Some(HumanDisposition::Unmarked),
        "accepted" | "accept" | "approve" | "approved" | "ok" => Some(HumanDisposition::Accepted),
        "rejected" | "reject" | "deny" | "denied" | "fail" => Some(HumanDisposition::Rejected),
        "re_ran_strict" | "rerun_strict" | "rerun-strict" | "rerun" | "re_ran" => {
            Some(HumanDisposition::ReRanStrict)
        }
        _ => None,
    }
}

/// Writes `human_disposition` into `output["artifact_validation"]`. Returns
/// `true` when the value was newly set or changed; `false` when the key
/// already held the same disposition. Creates an empty `artifact_validation`
/// object if one is not yet present, so dispositions can be set on outputs
/// that did not go through the relaxation chokepoint (e.g. Strict runs the
/// human still wants to comment on).
pub fn set_human_disposition_on_output(output: &mut Value, disposition: HumanDisposition) -> bool {
    let object = match output.as_object_mut() {
        Some(map) => map,
        None => return false,
    };
    if !object.contains_key("artifact_validation") {
        object.insert(
            "artifact_validation".to_string(),
            Value::Object(serde_json::Map::new()),
        );
    }
    let validation = match object
        .get_mut("artifact_validation")
        .and_then(Value::as_object_mut)
    {
        Some(map) => map,
        None => return false,
    };
    let previous = validation
        .get("human_disposition")
        .and_then(Value::as_str)
        .map(str::to_string);
    let next = disposition.as_str().to_string();
    if previous.as_deref() == Some(next.as_str()) {
        return false;
    }
    validation.insert("human_disposition".to_string(), json!(next));
    true
}

/// Per-class accept/reject counts for graduation telemetry.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DispositionCounts {
    #[serde(default)]
    pub accepted: u64,
    #[serde(default)]
    pub rejected: u64,
    #[serde(default)]
    pub re_ran_strict: u64,
    #[serde(default)]
    pub unmarked: u64,
}

impl DispositionCounts {
    pub fn record(&mut self, disposition: HumanDisposition) {
        match disposition {
            HumanDisposition::Accepted => self.accepted = self.accepted.saturating_add(1),
            HumanDisposition::Rejected => self.rejected = self.rejected.saturating_add(1),
            HumanDisposition::ReRanStrict => {
                self.re_ran_strict = self.re_ran_strict.saturating_add(1)
            }
            HumanDisposition::Unmarked => self.unmarked = self.unmarked.saturating_add(1),
        }
    }

    pub fn total(&self) -> u64 {
        self.accepted
            .saturating_add(self.rejected)
            .saturating_add(self.re_ran_strict)
            .saturating_add(self.unmarked)
    }

    /// Accept rate over reviewed dispositions (excludes `unmarked`). Returns
    /// `None` when no humans have reviewed any outputs in the bucket — the
    /// dashboard should render that as "insufficient signal" rather than 0%.
    pub fn accept_rate(&self) -> Option<f32> {
        let reviewed = self
            .accepted
            .saturating_add(self.rejected)
            .saturating_add(self.re_ran_strict);
        if reviewed == 0 {
            return None;
        }
        Some(self.accepted as f32 / reviewed as f32)
    }
}

/// Aggregate result of walking a slice of run records: per-`ValidatorClass`
/// disposition counts plus a few totals. Intended for the read-only
/// graduation summary endpoint and any future per-class graduation
/// dashboard. Pure — does not touch state.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ValidatorClassDispositionSummary {
    #[serde(default)]
    pub total_outputs_scanned: u64,
    #[serde(default)]
    pub total_relaxed_outputs: u64,
    #[serde(default)]
    pub by_class: std::collections::BTreeMap<ValidatorClass, DispositionCounts>,
}

/// Walk a slice of node outputs and attribute each output's
/// `human_disposition` (defaulting to `unmarked`) to **every** validator
/// class listed under `relaxed_validator_classes` for that output. Outputs
/// without `relaxed_validator_classes` are not included — they were not
/// relaxed under a profile and therefore have nothing to graduate.
///
/// Pure — does not touch state. The HTTP handler that surfaces this
/// aggregate is responsible for filtering runs by time window and
/// flattening the per-run `node_outputs` into the iterator.
pub fn aggregate_human_dispositions_by_class<'a, I>(outputs: I) -> ValidatorClassDispositionSummary
where
    I: IntoIterator<Item = &'a Value>,
{
    let mut summary = ValidatorClassDispositionSummary::default();
    for output in outputs {
        summary.total_outputs_scanned = summary.total_outputs_scanned.saturating_add(1);
        let validation = match output.get("artifact_validation") {
            Some(value) => value,
            None => continue,
        };
        let relaxed = match validation
            .get("relaxed_validator_classes")
            .and_then(Value::as_array)
        {
            Some(value) if !value.is_empty() => value,
            _ => continue,
        };
        summary.total_relaxed_outputs = summary.total_relaxed_outputs.saturating_add(1);
        let disposition = validation
            .get("human_disposition")
            .and_then(Value::as_str)
            .and_then(parse_human_disposition_str)
            .unwrap_or(HumanDisposition::Unmarked);
        for entry in relaxed {
            let class_name = entry
                .as_str()
                .or_else(|| entry.get("class").and_then(Value::as_str));
            let class_name = match class_name {
                Some(name) => name,
                None => continue,
            };
            if let Some(class) = parse_validator_class_list(class_name).into_iter().next() {
                summary
                    .by_class
                    .entry(class)
                    .or_default()
                    .record(disposition);
            }
        }
    }
    summary
}

/// Profile-aware repair budget multiplier, bounded above by global caps in
/// `AutomationExecutionPolicy`. Returns the effective number of repair
/// attempts allowed for the given declared budget under `profile`.
pub fn effective_repair_budget(declared: u32, profile: ExecutionProfile) -> u32 {
    let multiplier = profile.repair_budget_multiplier();
    let scaled = (declared as f32 * multiplier).ceil();
    scaled.clamp(0.0, u32::MAX as f32) as u32
}

/// Classifies a validator's `unmet_requirements` string into a
/// `ValidatorClass`. Returns `None` for strings that have not yet been
/// taxonomized — those default to "blocking, never relaxable" so behavior
/// stays Strict-equivalent until the class is explicitly added.
pub fn classify_unmet_requirement(raw: &str) -> Option<ValidatorClass> {
    let key = raw
        .split([':', '|'])
        .next()
        .map(str::trim)
        .unwrap_or(raw)
        .trim();
    match key {
        "missing_required_section" | "missing_section" | "section_missing" => {
            Some(ValidatorClass::MissingRequiredSection)
        }
        "weak_markdown_structure"
        | "weak_structure"
        | "weak_markdown"
        | "markdown_structure_missing" => Some(ValidatorClass::WeakMarkdownStructure),
        "missing_optional_evidence"
        | "missing_evidence_optional"
        | "editorial_substance_missing" => Some(ValidatorClass::MissingOptionalEvidence),
        "artifact_word_count_below_minimum" | "artifact_too_short" => {
            Some(ValidatorClass::ArtifactWordCountBelowMinimum)
        }
        "missing_nonconsumed_workspace_files" | "missing_optional_workspace_files" => {
            Some(ValidatorClass::MissingNonconsumedWorkspaceFiles)
        }
        "required_source_paths_not_read" | "required_source_read_paths_not_read" => {
            Some(ValidatorClass::RequiredSourcePathsNotRead)
        }
        "missing_required_artifact_path" | "missing_artifact_path" => {
            Some(ValidatorClass::MissingRequiredArtifactPath)
        }
        "validator_kind_specific_soft_check" | "soft_validator_check" => {
            Some(ValidatorClass::ValidatorKindSpecificSoftCheck)
        }
        "repair_budget_exhausted" => Some(ValidatorClass::RepairBudgetExhausted),
        "unauthorized_workspace" | "workspace_unauthorized" => {
            Some(ValidatorClass::UnauthorizedWorkspace)
        }
        "secret_access_denied" => Some(ValidatorClass::SecretAccessDenied),
        "destructive_action_requires_approval" | "destructive_requires_approval" => {
            Some(ValidatorClass::DestructiveActionRequiresApproval)
        }
        "external_publish_requires_approval" => {
            Some(ValidatorClass::ExternalPublishRequiresApproval)
        }
        "tenant_policy_denied" | "policy_denied" => Some(ValidatorClass::TenantPolicyDenied),
        "tool_unauthorized" | "unauthorized_tool" => Some(ValidatorClass::ToolUnauthorized),
        "budget_exceeded" => Some(ValidatorClass::BudgetExceeded),
        "kill_switch_engaged" => Some(ValidatorClass::KillSwitchEngaged),
        "engine_lease_expired" => Some(ValidatorClass::EngineLeaseExpired),
        "invalid_api_token" => Some(ValidatorClass::InvalidApiToken),
        "deterministic_verification_failed" | "code_patch_apply_failed" => {
            Some(ValidatorClass::DeterministicVerificationFailed)
        }
        _ => None,
    }
}

/// Augments a node `output` JSON value with profile-aware relaxation
/// metadata AND rewrites the executor's blocking signals when the active
/// profile would relax all of its unmet requirements.
///
/// On a successful relaxation, this function writes telemetry into
/// `output["artifact_validation"]` (`relaxed_validator_classes`,
/// `effective_outcome`, `original_validator_outcome`, `execution_profile`,
/// optional `requested_execution_profile`, `experimental`, and
/// `original_status`) AND downgrades the executor-facing fields so the run
/// continues:
///
/// - `output["status"]` becomes `completed_with_warnings` (Guided) or
///   `completed` (Lenient; experimental-flagged via `artifact_validation`).
/// - `output["failure_kind"]` is cleared if it was validation-related.
/// - `output["blocked_reason"]` is cleared.
/// - `artifact_validation.warning_count` is set to the count of relaxed
///   classes so `automation_output_has_warnings` returns true.
///
/// Strict runs and runs whose unmet requirements include any critical or
/// not-yet-classified class are returned untouched.
///
/// Returns `true` when relaxation occurred.
pub fn augment_output_with_profile_relaxation(
    output: &mut Value,
    profile: ExecutionProfile,
    requested_profile: Option<ExecutionProfile>,
    tenant_relaxation_denylist: &[ValidatorClass],
) -> bool {
    let object = match output.as_object_mut() {
        Some(map) => map,
        None => return false,
    };
    let raw_unmet = object
        .get("artifact_validation")
        .and_then(|value| value.get("unmet_requirements"))
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    if raw_unmet.is_empty() {
        return false;
    }
    let mut classes: Vec<(ValidatorClass, Option<String>)> = Vec::new();
    let mut had_unclassified = false;
    for entry in &raw_unmet {
        let raw = match entry.as_str() {
            Some(value) => value.trim(),
            None => continue,
        };
        match classify_unmet_requirement(raw) {
            Some(class) => {
                let detail = raw
                    .splitn(2, [':', '|'])
                    .nth(1)
                    .map(|tail| tail.trim().to_string())
                    .filter(|value| !value.is_empty());
                classes.push((class, detail));
            }
            None => {
                had_unclassified = true;
            }
        }
    }

    let original_outcome = ValidationOutcome::Blocked;
    let decision = decide_profile_validation(
        profile,
        original_outcome,
        &classes,
        tenant_relaxation_denylist,
    );
    let augmented = !decision.relaxed_classes.is_empty()
        && !matches!(decision.effective_outcome, ValidationOutcome::Blocked);
    if !augmented {
        return false;
    }
    if had_unclassified {
        // Conservative: if any unmet requirement is not yet classified, keep
        // Strict-equivalent behavior even when others would relax.
        return false;
    }

    let original_status = object
        .get("status")
        .and_then(Value::as_str)
        .map(str::to_string);
    let original_failure_kind = object
        .get("failure_kind")
        .and_then(Value::as_str)
        .map(str::to_string);

    // Downgrade executor-facing blocking signals so the run continues.
    let new_status = match decision.effective_outcome {
        ValidationOutcome::Warning => "completed_with_warnings",
        ValidationOutcome::Experimental => "completed",
        // Defensive: by construction `effective_outcome` is non-blocking here.
        ValidationOutcome::Passed | ValidationOutcome::Blocked => "completed",
    };
    object.insert("status".to_string(), json!(new_status));
    let validation_failure_kinds = matches!(
        original_failure_kind.as_deref(),
        Some("validation_error") | Some("verification_failed") | Some("artifact_rejected")
    );
    if validation_failure_kinds {
        object.insert("failure_kind".to_string(), Value::Null);
    }
    if matches!(
        object.get("blocked_reason").and_then(Value::as_str),
        Some(text) if !text.is_empty()
    ) {
        object.insert("blocked_reason".to_string(), Value::Null);
    }

    let validation = object
        .get_mut("artifact_validation")
        .and_then(Value::as_object_mut)
        .expect("artifact_validation present (checked above)");
    validation.insert(
        "relaxed_validator_classes".to_string(),
        serde_json::to_value(&decision.relaxed_classes).unwrap_or(Value::Null),
    );
    validation.insert(
        "effective_outcome".to_string(),
        json!(decision.effective_outcome.as_str()),
    );
    validation.insert(
        "original_validator_outcome".to_string(),
        json!(original_outcome.as_str()),
    );
    validation.insert("execution_profile".to_string(), json!(profile.as_str()));
    if let Some(req) = requested_profile {
        validation.insert(
            "requested_execution_profile".to_string(),
            json!(req.as_str()),
        );
    }
    if decision.experimental {
        validation.insert("experimental".to_string(), json!(true));
    }
    if let Some(prev) = original_status {
        validation.insert("original_status".to_string(), json!(prev));
    }
    if let Some(prev) = original_failure_kind {
        validation.insert("original_failure_kind".to_string(), json!(prev));
    }
    let warning_count = decision.relaxed_classes.len() as u64;
    validation.insert("warning_count".to_string(), json!(warning_count));
    true
}

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

    #[test]
    fn execution_profile_serde_round_trip() {
        for (profile, wire) in [
            (ExecutionProfile::Strict, "\"strict\""),
            (ExecutionProfile::Guided, "\"guided\""),
            (ExecutionProfile::Yolo, "\"yolo\""),
        ] {
            let serialized = serde_json::to_string(&profile).unwrap();
            assert_eq!(serialized, wire);
            let deserialized: ExecutionProfile = serde_json::from_str(wire).unwrap();
            assert_eq!(deserialized, profile);
        }
    }

    #[test]
    fn execution_profile_default_is_strict() {
        assert_eq!(ExecutionProfile::default(), ExecutionProfile::Strict);
    }

    #[test]
    fn execution_profile_unknown_string_fails() {
        assert!(serde_json::from_str::<ExecutionProfile>("\"loose\"").is_err());
    }

    #[test]
    fn critical_classes_never_relaxable() {
        let critical = [
            ValidatorClass::UnauthorizedWorkspace,
            ValidatorClass::SecretAccessDenied,
            ValidatorClass::DestructiveActionRequiresApproval,
            ValidatorClass::TenantPolicyDenied,
            ValidatorClass::ToolUnauthorized,
            ValidatorClass::BudgetExceeded,
            ValidatorClass::KillSwitchEngaged,
            ValidatorClass::DeterministicVerificationFailed,
        ];
        for class in critical {
            assert!(class.is_critical(), "{:?} should be critical", class);
            for profile in [
                ExecutionProfile::Strict,
                ExecutionProfile::Guided,
                ExecutionProfile::Yolo,
            ] {
                assert!(
                    !class.is_relaxable_in(profile),
                    "{:?} must not be relaxable in {:?}",
                    class,
                    profile
                );
            }
        }
    }

    #[test]
    fn guided_relaxes_soft_classes() {
        let soft = [
            ValidatorClass::MissingRequiredSection,
            ValidatorClass::WeakMarkdownStructure,
            ValidatorClass::MissingOptionalEvidence,
            ValidatorClass::ArtifactWordCountBelowMinimum,
            ValidatorClass::MissingNonconsumedWorkspaceFiles,
        ];
        for class in soft {
            assert!(class.is_relaxable_in(ExecutionProfile::Guided));
            assert!(class.is_relaxable_in(ExecutionProfile::Yolo));
            assert!(!class.is_relaxable_in(ExecutionProfile::Strict));
        }
    }

    #[test]
    fn yolo_only_classes_not_relaxed_in_guided() {
        let yolo_only = [
            ValidatorClass::MissingRequiredArtifactPath,
            ValidatorClass::ValidatorKindSpecificSoftCheck,
            ValidatorClass::RepairBudgetExhausted,
        ];
        for class in yolo_only {
            assert!(!class.is_relaxable_in(ExecutionProfile::Strict));
            assert!(!class.is_relaxable_in(ExecutionProfile::Guided));
            assert!(class.is_relaxable_in(ExecutionProfile::Yolo));
        }
    }

    #[test]
    fn decide_blocked_under_strict_stays_blocked() {
        let decision = decide_profile_validation(
            ExecutionProfile::Strict,
            ValidationOutcome::Blocked,
            &[(
                ValidatorClass::MissingRequiredSection,
                Some("Sources".into()),
            )],
            &[],
        );
        assert!(decision.should_block);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Blocked);
        assert!(decision.relaxed_classes.is_empty());
    }

    #[test]
    fn decide_soft_under_guided_becomes_warning() {
        let decision = decide_profile_validation(
            ExecutionProfile::Guided,
            ValidationOutcome::Blocked,
            &[(
                ValidatorClass::MissingRequiredSection,
                Some("Sources".into()),
            )],
            &[],
        );
        assert!(!decision.should_block);
        assert!(!decision.experimental);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Warning);
        assert_eq!(decision.relaxed_classes.len(), 1);
        assert_eq!(
            decision.relaxed_classes[0].class,
            ValidatorClass::MissingRequiredSection
        );
        assert_eq!(
            decision.relaxed_classes[0].detail.as_deref(),
            Some("Sources")
        );
    }

    #[test]
    fn decide_soft_under_yolo_becomes_experimental() {
        let decision = decide_profile_validation(
            ExecutionProfile::Yolo,
            ValidationOutcome::Blocked,
            &[(ValidatorClass::MissingRequiredSection, None)],
            &[],
        );
        assert!(!decision.should_block);
        assert!(decision.experimental);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Experimental);
    }

    #[test]
    fn decide_critical_blocks_in_yolo() {
        let decision = decide_profile_validation(
            ExecutionProfile::Yolo,
            ValidationOutcome::Blocked,
            &[
                (ValidatorClass::MissingRequiredSection, None),
                (ValidatorClass::DestructiveActionRequiresApproval, None),
            ],
            &[],
        );
        assert!(decision.should_block);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Blocked);
        assert!(decision.relaxed_classes.is_empty());
    }

    #[test]
    fn decide_tenant_denylist_blocks_in_yolo() {
        let decision = decide_profile_validation(
            ExecutionProfile::Yolo,
            ValidationOutcome::Blocked,
            &[(ValidatorClass::MissingRequiredSection, None)],
            &[ValidatorClass::MissingRequiredSection],
        );
        assert!(decision.should_block);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Blocked);
    }

    #[test]
    fn decide_yolo_only_class_not_relaxed_in_guided() {
        let decision = decide_profile_validation(
            ExecutionProfile::Guided,
            ValidationOutcome::Blocked,
            &[(ValidatorClass::MissingRequiredArtifactPath, None)],
            &[],
        );
        assert!(decision.should_block);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Blocked);
    }

    #[test]
    fn classify_known_strings_to_validator_classes() {
        assert_eq!(
            classify_unmet_requirement("missing_required_section"),
            Some(ValidatorClass::MissingRequiredSection)
        );
        assert_eq!(
            classify_unmet_requirement("missing_required_section: Sources"),
            Some(ValidatorClass::MissingRequiredSection)
        );
        assert_eq!(
            classify_unmet_requirement("destructive_action_requires_approval"),
            Some(ValidatorClass::DestructiveActionRequiresApproval)
        );
        assert_eq!(
            classify_unmet_requirement("budget_exceeded"),
            Some(ValidatorClass::BudgetExceeded)
        );
        assert_eq!(
            classify_unmet_requirement("required_source_paths_not_read"),
            Some(ValidatorClass::RequiredSourcePathsNotRead)
        );
        assert_eq!(
            classify_unmet_requirement("markdown_structure_missing"),
            Some(ValidatorClass::WeakMarkdownStructure)
        );
        assert_eq!(
            classify_unmet_requirement("editorial_substance_missing"),
            Some(ValidatorClass::MissingOptionalEvidence)
        );
        assert_eq!(classify_unmet_requirement("totally_unknown_class"), None);
    }

    #[test]
    fn classifier_critical_strings_remain_critical() {
        let critical_strings = [
            "unauthorized_workspace",
            "secret_access_denied",
            "destructive_action_requires_approval",
            "tenant_policy_denied",
            "tool_unauthorized",
            "budget_exceeded",
            "kill_switch_engaged",
            "deterministic_verification_failed",
        ];
        for raw in critical_strings {
            let class = classify_unmet_requirement(raw)
                .unwrap_or_else(|| panic!("expected classification for {raw}"));
            assert!(
                class.is_critical(),
                "{raw} -> {:?} should be critical",
                class
            );
        }
    }

    #[test]
    fn augment_strict_profile_no_change() {
        let mut output = json!({
            "status": "verify_failed",
            "failure_kind": "validation_error",
            "artifact_validation": {
                "unmet_requirements": ["missing_required_section: Sources"],
            }
        });
        let augmented = augment_output_with_profile_relaxation(
            &mut output,
            ExecutionProfile::Strict,
            None,
            &[],
        );
        assert!(!augmented);
        // Status and failure_kind are preserved under Strict.
        assert_eq!(
            output.get("status").and_then(Value::as_str),
            Some("verify_failed")
        );
        assert_eq!(
            output.get("failure_kind").and_then(Value::as_str),
            Some("validation_error")
        );
        let validation = output.pointer("/artifact_validation").unwrap();
        assert!(validation.get("relaxed_validator_classes").is_none());
        assert!(validation.get("effective_outcome").is_none());
        assert!(validation.get("warning_count").is_none());
    }

    #[test]
    fn augment_guided_writes_warning_outcome_and_downgrades_status() {
        let mut output = json!({
            "status": "verify_failed",
            "failure_kind": "validation_error",
            "blocked_reason": "missing required section `Sources`",
            "artifact_validation": {
                "unmet_requirements": ["missing_required_section: Sources"],
            }
        });
        let augmented = augment_output_with_profile_relaxation(
            &mut output,
            ExecutionProfile::Guided,
            None,
            &[],
        );
        assert!(augmented);
        assert_eq!(
            output.get("status").and_then(Value::as_str),
            Some("completed_with_warnings")
        );
        assert!(output.get("failure_kind").map_or(true, Value::is_null));
        assert!(output.get("blocked_reason").map_or(true, Value::is_null));
        let validation = output.pointer("/artifact_validation").unwrap();
        assert_eq!(
            validation.get("effective_outcome").and_then(Value::as_str),
            Some("warning")
        );
        assert_eq!(
            validation
                .get("original_validator_outcome")
                .and_then(Value::as_str),
            Some("blocked")
        );
        assert_eq!(
            validation.get("execution_profile").and_then(Value::as_str),
            Some("guided")
        );
        assert_eq!(
            validation.get("original_status").and_then(Value::as_str),
            Some("verify_failed")
        );
        assert_eq!(
            validation
                .get("original_failure_kind")
                .and_then(Value::as_str),
            Some("validation_error")
        );
        assert_eq!(
            validation.get("warning_count").and_then(Value::as_u64),
            Some(1)
        );
        assert!(validation.get("experimental").is_none());
        let classes = validation
            .get("relaxed_validator_classes")
            .and_then(Value::as_array)
            .unwrap();
        assert_eq!(classes.len(), 1);
        assert_eq!(
            classes[0].get("class").and_then(Value::as_str),
            Some("missing_required_section")
        );
        assert_eq!(
            classes[0].get("detail").and_then(Value::as_str),
            Some("Sources")
        );
    }

    #[test]
    fn augment_yolo_writes_experimental_flag_and_completes_node() {
        let mut output = json!({
            "status": "verify_failed",
            "failure_kind": "validation_error",
            "artifact_validation": {
                "unmet_requirements": ["missing_required_section: Sources"],
            }
        });
        let augmented = augment_output_with_profile_relaxation(
            &mut output,
            ExecutionProfile::Yolo,
            Some(ExecutionProfile::Yolo),
            &[],
        );
        assert!(augmented);
        assert_eq!(
            output.get("status").and_then(Value::as_str),
            Some("completed")
        );
        assert!(output.get("failure_kind").map_or(true, Value::is_null));
        let validation = output.pointer("/artifact_validation").unwrap();
        assert_eq!(
            validation.get("effective_outcome").and_then(Value::as_str),
            Some("experimental")
        );
        assert_eq!(
            validation.get("experimental").and_then(Value::as_bool),
            Some(true)
        );
        assert_eq!(
            validation
                .get("requested_execution_profile")
                .and_then(Value::as_str),
            Some("yolo")
        );
        assert_eq!(
            validation.get("warning_count").and_then(Value::as_u64),
            Some(1)
        );
    }

    #[test]
    fn augment_yolo_preserves_non_validation_failure_kind() {
        // If the failure_kind is something we did not originate
        // (e.g. provider stream error), do not clear it even when relaxing.
        let mut output = json!({
            "status": "verify_failed",
            "failure_kind": "provider_stream_failed",
            "artifact_validation": {
                "unmet_requirements": ["missing_required_section: Sources"],
            }
        });
        augment_output_with_profile_relaxation(&mut output, ExecutionProfile::Yolo, None, &[]);
        assert_eq!(
            output.get("failure_kind").and_then(Value::as_str),
            Some("provider_stream_failed")
        );
    }

    #[test]
    fn augment_critical_class_blocks_under_yolo() {
        let mut output = json!({
            "artifact_validation": {
                "unmet_requirements": [
                    "missing_required_section: Sources",
                    "destructive_action_requires_approval"
                ],
            }
        });
        let augmented =
            augment_output_with_profile_relaxation(&mut output, ExecutionProfile::Yolo, None, &[]);
        assert!(!augmented);
    }

    #[test]
    fn augment_unclassified_string_is_conservative() {
        let mut output = json!({
            "artifact_validation": {
                "unmet_requirements": [
                    "missing_required_section: Sources",
                    "totally_unknown_class"
                ],
            }
        });
        let augmented =
            augment_output_with_profile_relaxation(&mut output, ExecutionProfile::Yolo, None, &[]);
        assert!(!augmented);
    }

    #[test]
    fn augment_no_unmet_requirements_no_change() {
        let mut output = json!({
            "artifact_validation": {
                "unmet_requirements": [],
            }
        });
        let augmented =
            augment_output_with_profile_relaxation(&mut output, ExecutionProfile::Yolo, None, &[]);
        assert!(!augmented);
    }

    #[test]
    fn taint_propagation_marks_downstream_experimental() {
        let mut output = json!({
            "status": "completed",
            "artifact_validation": {
                "validation_outcome": "passed",
            }
        });
        let upstream_a = json!({
            "artifact_validation": { "experimental": true }
        });
        let upstream_b = json!({
            "artifact_validation": { "experimental": false }
        });
        let tainted = propagate_experimental_input_taint(
            &mut output,
            vec![("node-a", &upstream_a), ("node-b", &upstream_b)],
        );
        assert!(tainted);
        let validation = output.pointer("/artifact_validation").unwrap();
        assert_eq!(
            validation.get("experimental").and_then(Value::as_bool),
            Some(true)
        );
        let tainted_inputs = validation
            .get("tainted_inputs")
            .and_then(Value::as_array)
            .unwrap();
        let names: Vec<&str> = tainted_inputs.iter().filter_map(Value::as_str).collect();
        assert_eq!(names, vec!["node-a"]);
        // Status is intentionally unchanged by taint propagation.
        assert_eq!(
            output.get("status").and_then(Value::as_str),
            Some("completed")
        );
    }

    #[test]
    fn taint_propagation_no_op_when_no_upstream_experimental() {
        let mut output = json!({
            "artifact_validation": { "validation_outcome": "passed" }
        });
        let upstream = json!({ "artifact_validation": { "experimental": false } });
        let tainted = propagate_experimental_input_taint(&mut output, vec![("node-a", &upstream)]);
        assert!(!tainted);
        let validation = output.pointer("/artifact_validation").unwrap();
        assert!(validation.get("experimental").is_none());
        assert!(validation.get("tainted_inputs").is_none());
    }

    #[test]
    fn taint_propagation_creates_artifact_validation_when_absent() {
        let mut output = json!({ "status": "completed" });
        let upstream = json!({ "artifact_validation": { "experimental": true } });
        let tainted =
            propagate_experimental_input_taint(&mut output, vec![("upstream", &upstream)]);
        assert!(tainted);
        let validation = output.pointer("/artifact_validation").unwrap();
        assert_eq!(
            validation.get("experimental").and_then(Value::as_bool),
            Some(true)
        );
    }

    #[test]
    fn taint_propagation_already_experimental_returns_false() {
        let mut output = json!({
            "artifact_validation": { "experimental": true }
        });
        let upstream = json!({ "artifact_validation": { "experimental": true } });
        let tainted =
            propagate_experimental_input_taint(&mut output, vec![("upstream", &upstream)]);
        // Returns false because it was already experimental, but tainted_inputs
        // should still be populated for receipts.
        assert!(!tainted);
        let validation = output.pointer("/artifact_validation").unwrap();
        let tainted_inputs = validation
            .get("tainted_inputs")
            .and_then(Value::as_array)
            .unwrap();
        assert_eq!(tainted_inputs.len(), 1);
    }

    #[test]
    fn parse_execution_profile_accepts_canonical_and_aliases() {
        assert_eq!(
            parse_execution_profile_str("strict"),
            Some(ExecutionProfile::Strict)
        );
        assert_eq!(
            parse_execution_profile_str("Strict"),
            Some(ExecutionProfile::Strict)
        );
        assert_eq!(
            parse_execution_profile_str("  STRICT  "),
            Some(ExecutionProfile::Strict)
        );
        assert_eq!(
            parse_execution_profile_str("guided"),
            Some(ExecutionProfile::Guided)
        );
        assert_eq!(
            parse_execution_profile_str("assisted"),
            Some(ExecutionProfile::Guided)
        );
        assert_eq!(
            parse_execution_profile_str("yolo"),
            Some(ExecutionProfile::Yolo)
        );
        assert_eq!(
            parse_execution_profile_str("exploratory"),
            Some(ExecutionProfile::Yolo)
        );
        assert_eq!(
            parse_execution_profile_str("lenient"),
            Some(ExecutionProfile::Yolo)
        );
    }

    #[test]
    fn parse_execution_profile_rejects_unknown_strings() {
        assert_eq!(parse_execution_profile_str(""), None);
        assert_eq!(parse_execution_profile_str("loose"), None);
        assert_eq!(parse_execution_profile_str("relaxed"), None);
        assert_eq!(parse_execution_profile_str("danger"), None);
    }

    #[test]
    fn parse_validator_class_list_handles_canonical_names() {
        let parsed = parse_validator_class_list(
            "missing_required_section, weak_markdown_structure,repair_budget_exhausted",
        );
        assert_eq!(
            parsed,
            vec![
                ValidatorClass::MissingRequiredSection,
                ValidatorClass::WeakMarkdownStructure,
                ValidatorClass::RepairBudgetExhausted,
            ]
        );
    }

    #[test]
    fn parse_validator_class_list_skips_unknown_entries() {
        let parsed = parse_validator_class_list(
            "missing_required_section,not_a_real_class,weak_markdown_structure",
        );
        assert_eq!(
            parsed,
            vec![
                ValidatorClass::MissingRequiredSection,
                ValidatorClass::WeakMarkdownStructure,
            ]
        );
    }

    #[test]
    fn parse_validator_class_list_handles_empty_and_whitespace() {
        assert!(parse_validator_class_list("").is_empty());
        assert!(parse_validator_class_list("   ,, ,").is_empty());
        assert_eq!(
            parse_validator_class_list("  WEAK_MARKDOWN_STRUCTURE  "),
            vec![ValidatorClass::WeakMarkdownStructure]
        );
    }

    #[test]
    fn denylisted_class_blocks_under_yolo_via_decision() {
        let denylist = vec![ValidatorClass::MissingRequiredSection];
        let decision = decide_profile_validation(
            ExecutionProfile::Yolo,
            ValidationOutcome::Blocked,
            &[(ValidatorClass::MissingRequiredSection, None)],
            &denylist,
        );
        assert!(decision.should_block);
        assert_eq!(decision.effective_outcome, ValidationOutcome::Blocked);
    }

    #[test]
    fn repair_budget_multiplier_per_profile() {
        assert_eq!(effective_repair_budget(2, ExecutionProfile::Strict), 2);
        assert_eq!(effective_repair_budget(2, ExecutionProfile::Guided), 3);
        assert_eq!(effective_repair_budget(2, ExecutionProfile::Yolo), 4);
        assert_eq!(effective_repair_budget(0, ExecutionProfile::Yolo), 0);
        assert_eq!(effective_repair_budget(1, ExecutionProfile::Guided), 2);
    }

    #[test]
    fn parse_human_disposition_canonical_strings() {
        assert_eq!(
            parse_human_disposition_str("accepted"),
            Some(HumanDisposition::Accepted)
        );
        assert_eq!(
            parse_human_disposition_str("rejected"),
            Some(HumanDisposition::Rejected)
        );
        assert_eq!(
            parse_human_disposition_str("re_ran_strict"),
            Some(HumanDisposition::ReRanStrict)
        );
        assert_eq!(
            parse_human_disposition_str("unmarked"),
            Some(HumanDisposition::Unmarked)
        );
    }

    #[test]
    fn parse_human_disposition_aliases_and_normalization() {
        assert_eq!(
            parse_human_disposition_str("  ACCEPT  "),
            Some(HumanDisposition::Accepted)
        );
        assert_eq!(
            parse_human_disposition_str("Reject"),
            Some(HumanDisposition::Rejected)
        );
        assert_eq!(
            parse_human_disposition_str("rerun"),
            Some(HumanDisposition::ReRanStrict)
        );
        assert_eq!(
            parse_human_disposition_str(""),
            Some(HumanDisposition::Unmarked)
        );
        assert_eq!(parse_human_disposition_str("maybe"), None);
    }

    #[test]
    fn set_human_disposition_writes_into_artifact_validation() {
        let mut output = json!({
            "status": "completed_with_warnings",
            "artifact_validation": {
                "execution_profile": "guided",
                "relaxed_validator_classes": [{"class": "missing_required_section"}],
            },
        });
        let changed = set_human_disposition_on_output(&mut output, HumanDisposition::Accepted);
        assert!(changed);
        assert_eq!(
            output
                .pointer("/artifact_validation/human_disposition")
                .and_then(Value::as_str),
            Some("accepted")
        );
    }

    #[test]
    fn set_human_disposition_creates_validation_object_when_absent() {
        let mut output = json!({ "status": "completed" });
        let changed = set_human_disposition_on_output(&mut output, HumanDisposition::ReRanStrict);
        assert!(changed);
        assert_eq!(
            output
                .pointer("/artifact_validation/human_disposition")
                .and_then(Value::as_str),
            Some("re_ran_strict")
        );
    }

    #[test]
    fn set_human_disposition_is_idempotent_on_same_value() {
        let mut output = json!({
            "artifact_validation": { "human_disposition": "accepted" }
        });
        let changed = set_human_disposition_on_output(&mut output, HumanDisposition::Accepted);
        assert!(!changed);
    }

    #[test]
    fn set_human_disposition_overwrites_previous_value() {
        let mut output = json!({
            "artifact_validation": { "human_disposition": "accepted" }
        });
        let changed = set_human_disposition_on_output(&mut output, HumanDisposition::Rejected);
        assert!(changed);
        assert_eq!(
            output
                .pointer("/artifact_validation/human_disposition")
                .and_then(Value::as_str),
            Some("rejected")
        );
    }

    fn output_with_relaxed_classes(classes: &[&str], disposition: Option<&str>) -> Value {
        let entries: Vec<Value> = classes
            .iter()
            .map(|name| {
                json!({
                    "class": name,
                    "original_outcome": "blocked",
                    "effective_outcome": "warning",
                })
            })
            .collect();
        let mut validation = json!({ "relaxed_validator_classes": entries });
        if let Some(value) = disposition {
            validation
                .as_object_mut()
                .unwrap()
                .insert("human_disposition".to_string(), json!(value));
        }
        json!({ "artifact_validation": validation })
    }

    #[test]
    fn aggregate_dispositions_skips_outputs_without_relaxation() {
        let plain = json!({ "status": "completed" });
        let no_classes = json!({
            "artifact_validation": { "relaxed_validator_classes": [] }
        });
        let summary = aggregate_human_dispositions_by_class([&plain, &no_classes]);
        assert_eq!(summary.total_outputs_scanned, 2);
        assert_eq!(summary.total_relaxed_outputs, 0);
        assert!(summary.by_class.is_empty());
    }

    #[test]
    fn aggregate_dispositions_attributes_to_every_relaxed_class() {
        let output = output_with_relaxed_classes(
            &["missing_required_section", "weak_markdown_structure"],
            Some("accepted"),
        );
        let summary = aggregate_human_dispositions_by_class([&output]);
        assert_eq!(summary.total_relaxed_outputs, 1);
        let mrs = summary
            .by_class
            .get(&ValidatorClass::MissingRequiredSection)
            .unwrap();
        assert_eq!(mrs.accepted, 1);
        let wms = summary
            .by_class
            .get(&ValidatorClass::WeakMarkdownStructure)
            .unwrap();
        assert_eq!(wms.accepted, 1);
    }

    #[test]
    fn aggregate_dispositions_defaults_unmarked_when_no_signal() {
        let output = output_with_relaxed_classes(&["missing_required_section"], None);
        let summary = aggregate_human_dispositions_by_class([&output]);
        let counts = summary
            .by_class
            .get(&ValidatorClass::MissingRequiredSection)
            .unwrap();
        assert_eq!(counts.unmarked, 1);
        assert_eq!(counts.accepted, 0);
        assert!(counts.accept_rate().is_none());
    }

    #[test]
    fn aggregate_dispositions_mixed_signals_per_class() {
        let outputs = vec![
            output_with_relaxed_classes(&["missing_required_section"], Some("accepted")),
            output_with_relaxed_classes(&["missing_required_section"], Some("accepted")),
            output_with_relaxed_classes(&["missing_required_section"], Some("rejected")),
            output_with_relaxed_classes(&["missing_required_section"], None),
        ];
        let summary = aggregate_human_dispositions_by_class(outputs.iter());
        let counts = summary
            .by_class
            .get(&ValidatorClass::MissingRequiredSection)
            .unwrap();
        assert_eq!(counts.accepted, 2);
        assert_eq!(counts.rejected, 1);
        assert_eq!(counts.unmarked, 1);
        assert_eq!(counts.total(), 4);
        // accept_rate excludes unmarked: 2 / (2 + 1) = 0.666...
        let rate = counts.accept_rate().unwrap();
        assert!((rate - (2.0 / 3.0)).abs() < 1e-6);
    }

    #[test]
    fn aggregate_dispositions_skips_unknown_class_names() {
        let output = json!({
            "artifact_validation": {
                "relaxed_validator_classes": [
                    {"class": "missing_required_section"},
                    {"class": "totally_made_up_class"}
                ]
            }
        });
        let summary = aggregate_human_dispositions_by_class([&output]);
        assert_eq!(summary.total_relaxed_outputs, 1);
        assert_eq!(summary.by_class.len(), 1);
        assert!(summary
            .by_class
            .contains_key(&ValidatorClass::MissingRequiredSection));
    }
}