bijux-dag-runtime 0.4.0

Execution engine, replay semantics, and runtime policy layer for Bijux DAG graphs.
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
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
//! Adapter conformance checks.

use crate::adapter::{AdapterDescriptor, AdapterOrigin, CacheCompatibilityMode};
use crate::backend::fake::FakeBatchExecutorContract;
use crate::backend_cluster::{KubernetesAdapterContractReport, SlurmAdapterDesignContractReport};
use crate::{NodeTrace, OutputsIndex, PolicyConfig, Runtime, RuntimeConfig};
use bijux_dag_core::parse_graph_strict;
use bijux_dag_core::Severity;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::ffi::OsString;
use std::fs;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdapterConformanceReport {
    pub adapter_id: String,
    pub passed: bool,
    pub violations: Vec<String>,
}

pub fn validate_descriptor(descriptor: &AdapterDescriptor) -> AdapterConformanceReport {
    let mut violations = Vec::new();
    if descriptor.id.trim().is_empty() {
        violations.push("missing adapter id".to_string());
    }
    if descriptor.version.trim().is_empty() {
        violations.push("missing adapter version".to_string());
    }
    if descriptor.supported_kinds.is_empty() {
        violations.push("missing supported kinds".to_string());
    }
    if descriptor.produces_outputs_schema_version.trim().is_empty() {
        violations.push("missing outputs schema version".to_string());
    }
    if descriptor.protocol_version.trim().is_empty() {
        violations.push("missing adapter protocol version".to_string());
    }
    if matches!(descriptor.origin, AdapterOrigin::External)
        && !descriptor.required_effects.filesystem
        && !descriptor.required_effects.env
        && !descriptor.required_effects.network
        && !descriptor.required_effects.clock
    {
        violations.push("external adapter declares no required effects".to_string());
    }
    if matches!(descriptor.origin, AdapterOrigin::External) && descriptor.binary_hash.is_none() {
        violations.push("external adapter missing binary hash".to_string());
    }

    AdapterConformanceReport {
        adapter_id: descriptor.id.clone(),
        passed: violations.is_empty(),
        violations,
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AdapterScenarioStatus {
    Pass,
    Fail,
    Skip,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AdapterScenarioResult {
    pub scenario: String,
    pub status: AdapterScenarioStatus,
    pub enforced_by_runtime: bool,
    pub advisory_only: bool,
    pub checked_by_execution: bool,
    pub reason: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observation: Option<AdapterScenarioObservation>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AdapterConformanceSuiteReport {
    pub adapter_id: String,
    pub adapter_version: String,
    pub origin: AdapterOrigin,
    pub scenarios: Vec<AdapterScenarioResult>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct AdapterScenarioObservation {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_class: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub output_files: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_outputs_schema_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_binary_sha256: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AdapterOutputSchemaCompatibilityReport {
    pub compatible: bool,
    pub compatibility_mode: CacheCompatibilityMode,
    pub produced_schema_version: String,
    pub expected_schema_version: String,
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AdapterReferenceDocument {
    pub descriptors: Vec<AdapterDescriptor>,
    pub conformance: Vec<AdapterConformanceSuiteReport>,
    pub slurm: SlurmAdapterDesignContractReport,
    pub kubernetes: KubernetesAdapterContractReport,
    pub fake_batch: FakeBatchExecutorContract,
}

pub fn validate_output_schema_compatibility(
    mode: CacheCompatibilityMode,
    produced_schema_version: &str,
    expected_schema_version: &str,
) -> AdapterOutputSchemaCompatibilityReport {
    let compatible = match mode {
        CacheCompatibilityMode::FingerprintExact => {
            produced_schema_version == expected_schema_version
        }
    };
    let reason = if compatible {
        "produced output schema matches the expected adapter schema".to_string()
    } else {
        match mode {
            CacheCompatibilityMode::FingerprintExact => format!(
                "cache entry schema '{}' is incompatible with expected schema '{}' under fingerprint-exact compatibility",
                produced_schema_version, expected_schema_version
            ),
        }
    };
    AdapterOutputSchemaCompatibilityReport {
        compatible,
        compatibility_mode: mode,
        produced_schema_version: produced_schema_version.to_string(),
        expected_schema_version: expected_schema_version.to_string(),
        reason,
    }
}

fn scenario(
    name: &str,
    status: AdapterScenarioStatus,
    enforced_by_runtime: bool,
    advisory_only: bool,
    checked_by_execution: bool,
    reason: &str,
    observation: Option<AdapterScenarioObservation>,
) -> AdapterScenarioResult {
    AdapterScenarioResult {
        scenario: name.to_string(),
        status,
        enforced_by_runtime,
        advisory_only,
        checked_by_execution,
        reason: reason.to_string(),
        observation,
    }
}

pub fn build_adapter_conformance_suite(
    descriptor: &AdapterDescriptor,
) -> AdapterConformanceSuiteReport {
    let scenarios = match descriptor.id.as_str() {
        "const" => const_adapter_scenarios(descriptor),
        "shell" => shell_adapter_scenarios(descriptor),
        "python" => python_adapter_scenarios(descriptor),
        "http" => http_adapter_scenarios(descriptor),
        "file_transform" => file_transform_adapter_scenarios(descriptor),
        "container" => container_adapter_scenarios(descriptor),
        _ if matches!(descriptor.origin, AdapterOrigin::External) => {
            external_adapter_scenarios(descriptor)
        }
        _ => unsupported_adapter_scenarios(descriptor),
    };
    AdapterConformanceSuiteReport {
        adapter_id: descriptor.id.clone(),
        adapter_version: descriptor.version.clone(),
        origin: descriptor.origin,
        scenarios,
    }
}

pub fn generate_adapter_reference_markdown(document: &AdapterReferenceDocument) -> String {
    let mut lines = Vec::new();
    lines.push("# Adapter Contract".to_string());
    lines.push(String::new());
    lines.push("This document is generated from runtime adapter descriptors and backend contract references.".to_string());
    lines.push(String::new());
    lines.push("## Scope".to_string());
    lines.push(String::new());
    lines.push(
        "This contract governs the registered runtime adapter identities, the published"
            .to_string(),
    );
    lines.push(
        "conformance scenario meanings, the external adapter handshake boundary, and the"
            .to_string(),
    );
    lines
        .push("backend-specific adapter mappings that the runtime treats as supported".to_string());
    lines.push("integration surfaces.".to_string());
    lines.push(String::new());
    lines.push("## Registered adapters".to_string());
    for descriptor in &document.descriptors {
        lines.push(format!(
            "- `{}` `{}`: kinds={:?}, origin={:?}, schema={}, timeout={}, cancel={}, cache={:?}",
            descriptor.id,
            descriptor.version,
            descriptor.supported_kinds,
            descriptor.origin,
            descriptor.produces_outputs_schema_version,
            descriptor.supports_timeout,
            descriptor.supports_cancel,
            descriptor.cache_compatibility
        ));
    }
    lines.push(String::new());
    lines.push("## Conformance scenarios".to_string());
    for report in &document.conformance {
        lines.push(format!("### {} {}", report.adapter_id, report.adapter_version));
        for scenario in &report.scenarios {
            lines.push(format!(
                "- `{}`: {:?} (enforced_by_runtime={}, advisory_only={}, checked_by_execution={}) - {}",
                scenario.scenario,
                scenario.status,
                scenario.enforced_by_runtime,
                scenario.advisory_only,
                scenario.checked_by_execution,
                scenario.reason
            ));
            if let Some(observation) = &scenario.observation {
                let node_status = observation.node_status.as_deref().unwrap_or("none");
                let failure_code = observation.failure_code.as_deref().unwrap_or("none");
                let adapter_id = observation.adapter_id.as_deref().unwrap_or("unknown");
                let adapter_version = observation.adapter_version.as_deref().unwrap_or("unknown");
                let schema =
                    observation.adapter_outputs_schema_version.as_deref().unwrap_or("unknown");
                let output_files = if observation.output_files.is_empty() {
                    "none".to_string()
                } else {
                    observation.output_files.join(", ")
                };
                lines.push(format!(
                    "  observed status={}, failure_code={}, adapter={}@{}, schema={}, outputs={}",
                    node_status, failure_code, adapter_id, adapter_version, schema, output_files,
                ));
            }
        }
        lines.push(String::new());
    }
    lines.push("## External adapter protocol boundary".to_string());
    lines.push("- `info --json` must emit machine JSON on stdout only.".to_string());
    lines.push("- non-empty stderr during the info handshake is rejected.".to_string());
    lines.push(
        "- `execute` receives `--node-spec`, `--workdir`, `--outdir`, and `--failure-path`."
            .to_string(),
    );
    lines.push(
        "- nonzero adapter exits should write a `FailureInfo` JSON envelope to `--failure-path` for precise runtime failure mapping.".to_string(),
    );
    lines.push(
        "- external adapter binaries are fingerprinted into node trace evidence and cache identity."
            .to_string(),
    );
    lines.push(String::new());
    lines.push("## Slurm contract".to_string());
    lines.push(format!(
        "- submit=`{}`, poll=`{}`, cancel=`{}`",
        document.slurm.contract.submit_command,
        document.slurm.contract.poll_command,
        document.slurm.contract.cancel_command
    ));
    lines.push(format!("- logs: {}", document.slurm.log_collection_mode));
    lines.push(format!("- artifacts: {}", document.slurm.artifact_collection_mode));
    lines.push(String::new());
    lines.push("## Kubernetes contract".to_string());
    lines.push(format!("- namespace: `{}`", document.kubernetes.contract.namespace));
    lines.push(format!("- job spec mapping: {}", document.kubernetes.job_spec_mapping));
    lines.push(format!("- pod status mapping: {}", document.kubernetes.pod_status_mapping));
    lines.push(format!("- logs: {}", document.kubernetes.log_collection_mode));
    lines.push(format!("- artifacts: {}", document.kubernetes.artifact_collection_mode));
    lines.push(format!(
        "- unsupported fields rejected: {}",
        document.kubernetes.unsupported_field_rejection.join(", ")
    ));
    lines.push(String::new());
    lines.push("## Fake batch executor".to_string());
    lines.push(format!(
        "- submit=`{}`, poll=`{}`, cancel=`{}`",
        document.fake_batch.submit_api,
        document.fake_batch.poll_api,
        document.fake_batch.cancel_api
    ));
    lines.push(format!("- states: {}", document.fake_batch.supported_states.join(", ")));
    lines.push(String::new());
    lines.push("## Versioning and change policy".to_string());
    lines.push(String::new());
    lines.push(
        "Any incompatible change to registered adapter identities, conformance scenario"
            .to_string(),
    );
    lines.push(
        "meanings, external adapter protocol fields, or backend contract mappings must".to_string(),
    );
    lines.push("update this contract and the linked adapter tests in the same change.".to_string());
    lines.push(String::new());
    lines.push("## Related tests".to_string());
    lines.push(String::new());
    lines.push("- `crates/bijux-dag-runtime/tests/adapter_runtime_contracts.rs`".to_string());
    lines.push("- `crates/bijux-dag-runtime/tests/adapter_backend_contracts.rs`".to_string());
    lines.push("- `crates/bijux-dag-runtime/tests/adapter_reference_contracts.rs`".to_string());
    lines.push("- `crates/bijux-dag-runtime/tests/adapter_sdk_contract.rs`".to_string());
    lines.push("- `crates/bijux-dag-app/tests/adapter_command_contract.rs`".to_string());
    lines.join("\n")
}

#[derive(Debug)]
struct ConformanceRunRecord {
    trace: NodeTrace,
    outputs_index: Option<OutputsIndex>,
}

impl ConformanceRunRecord {
    fn observation(&self) -> AdapterScenarioObservation {
        AdapterScenarioObservation {
            node_status: Some(self.trace.status.clone()),
            failure_code: self.trace.failure.as_ref().map(|failure| failure.code.clone()),
            failure_class: self
                .trace
                .failure
                .as_ref()
                .and_then(|failure| failure.class.map(|class| class.as_str().to_string())),
            output_files: self
                .outputs_index
                .as_ref()
                .map(|index| index.files.iter().map(|file| file.name.clone()).collect())
                .unwrap_or_default(),
            adapter_id: Some(self.trace.adapter_id.clone()),
            adapter_version: Some(self.trace.adapter_version.clone()),
            adapter_outputs_schema_version: Some(self.trace.adapter_outputs_schema_version.clone()),
            adapter_binary_sha256: self.trace.adapter_binary_sha256.clone(),
        }
    }
}

#[derive(Debug)]
struct ConformanceWorkspace {
    path: PathBuf,
}

impl ConformanceWorkspace {
    fn new(adapter_id: &str, scenario: &str) -> Result<Self, String> {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|error| error.to_string())?
            .as_nanos();
        let unique = NEXT_ID.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!(
            "bijux-adapter-conformance-{adapter_id}-{scenario}-{}-{nanos}-{unique}",
            std::process::id()
        ));
        fs::create_dir_all(&path).map_err(|error| error.to_string())?;
        Ok(Self { path })
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for ConformanceWorkspace {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

#[derive(Debug, Clone)]
struct ScriptedHttpResponse {
    status_line: &'static str,
    body: &'static [u8],
    content_type: &'static str,
    delay: Duration,
}

struct ScriptedHttpServer {
    base_url: String,
    join: Option<thread::JoinHandle<()>>,
}

impl ScriptedHttpServer {
    fn spawn(response: ScriptedHttpResponse) -> Result<Self, String> {
        let listener = TcpListener::bind("127.0.0.1:0").map_err(|error| error.to_string())?;
        let address = listener.local_addr().map_err(|error| error.to_string())?;
        let join = thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
                let mut request = [0_u8; 4096];
                let _ = stream.read(&mut request);
                if !response.delay.is_zero() {
                    thread::sleep(response.delay);
                }
                let headers = format!(
                    "HTTP/1.1 {}\r\ncontent-type: {}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                    response.status_line,
                    response.content_type,
                    response.body.len()
                );
                let _ = stream.write_all(headers.as_bytes());
                let _ = stream.write_all(response.body);
                let _ = stream.flush();
            }
        });
        Ok(Self { base_url: format!("http://{address}"), join: Some(join) })
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}", self.base_url, path)
    }
}

impl Drop for ScriptedHttpServer {
    fn drop(&mut self) {
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
    }
}

struct ScopedEnvVar {
    key: &'static str,
    previous: Option<OsString>,
}

impl ScopedEnvVar {
    fn set(key: &'static str, value: &Path) -> Self {
        let previous = std::env::var_os(key);
        std::env::set_var(key, value);
        Self { key, previous }
    }
}

impl Drop for ScopedEnvVar {
    fn drop(&mut self) {
        if let Some(previous) = &self.previous {
            std::env::set_var(self.key, previous);
        } else {
            std::env::remove_var(self.key);
        }
    }
}

fn python_env_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(())).lock().unwrap_or_else(|error| error.into_inner())
}

fn pass_scenario(
    name: &str,
    enforced_by_runtime: bool,
    advisory_only: bool,
    reason: impl Into<String>,
    observation: Option<AdapterScenarioObservation>,
) -> AdapterScenarioResult {
    scenario(
        name,
        AdapterScenarioStatus::Pass,
        enforced_by_runtime,
        advisory_only,
        true,
        &reason.into(),
        observation,
    )
}

fn fail_scenario(
    name: &str,
    enforced_by_runtime: bool,
    advisory_only: bool,
    reason: impl Into<String>,
    observation: Option<AdapterScenarioObservation>,
) -> AdapterScenarioResult {
    scenario(
        name,
        AdapterScenarioStatus::Fail,
        enforced_by_runtime,
        advisory_only,
        true,
        &reason.into(),
        observation,
    )
}

fn skip_scenario(
    name: &str,
    enforced_by_runtime: bool,
    advisory_only: bool,
    reason: impl Into<String>,
) -> AdapterScenarioResult {
    scenario(
        name,
        AdapterScenarioStatus::Skip,
        enforced_by_runtime,
        advisory_only,
        false,
        &reason.into(),
        None,
    )
}

fn run_scenario_check(
    name: &str,
    record: &ConformanceRunRecord,
    enforced_by_runtime: bool,
    check: impl FnOnce(&ConformanceRunRecord) -> Result<String, String>,
) -> AdapterScenarioResult {
    let observation = Some(record.observation());
    match check(record) {
        Ok(reason) => pass_scenario(name, enforced_by_runtime, false, reason, observation),
        Err(reason) => fail_scenario(name, enforced_by_runtime, false, reason, observation),
    }
}

fn execute_graph_record(
    workspace: &ConformanceWorkspace,
    node_id: &str,
    graph_json: &str,
    config: RuntimeConfig,
) -> Result<ConformanceRunRecord, String> {
    let graph = parse_graph_strict(graph_json)
        .map_err(|error| format!("parse error: {error:?}: {error}"))?;
    let validation_errors = graph
        .validate_with_warnings()
        .into_iter()
        .filter(|diagnostic| diagnostic.severity == Severity::Error)
        .map(|diagnostic| diagnostic.message)
        .collect::<Vec<_>>();
    if !validation_errors.is_empty() {
        return Err(format!("graph validation failed: {}", validation_errors.join("; ")));
    }
    let run_dir = Runtime::new()
        .run(&graph, workspace.path(), config)
        .map_err(|error| format!("run error: {error:?}: {error}"))?;
    let trace_path = run_dir.join("nodes").join(node_id).join("trace.json");
    let trace: NodeTrace =
        serde_json::from_str(&fs::read_to_string(&trace_path).map_err(|error| error.to_string())?)
            .map_err(|error| error.to_string())?;
    let outputs_index_path = run_dir.join("nodes").join(node_id).join("outputs").join("index.json");
    let outputs_index = if outputs_index_path.exists() {
        Some(
            serde_json::from_str(
                &fs::read_to_string(outputs_index_path).map_err(|error| error.to_string())?,
            )
            .map_err(|error| error.to_string())?,
        )
    } else {
        None
    };
    Ok(ConformanceRunRecord { trace, outputs_index })
}

fn expect_success(record: &ConformanceRunRecord, adapter_id: &str) -> Result<String, String> {
    if record.trace.status == "success" {
        Ok(format!("runtime completed {adapter_id} execution successfully"))
    } else {
        Err(format!(
            "expected successful execution for {adapter_id}, observed status {}",
            record.trace.status
        ))
    }
}

fn expect_failure(
    record: &ConformanceRunRecord,
    adapter_id: &str,
    failure_code: &str,
    failure_class: &str,
) -> Result<String, String> {
    let Some(failure) = &record.trace.failure else {
        return Err(format!(
            "expected structured failure for {adapter_id}, but trace contains no failure payload"
        ));
    };
    let observed_class = failure.class.map(|class| class.as_str().to_string()).unwrap_or_default();
    if record.trace.status != "failed" {
        return Err(format!(
            "expected failed status for {adapter_id}, observed {}",
            record.trace.status
        ));
    }
    if failure.code != failure_code {
        return Err(format!(
            "expected failure code {failure_code} for {adapter_id}, observed {}",
            failure.code
        ));
    }
    if observed_class != failure_class {
        return Err(format!(
            "expected failure class {failure_class} for {adapter_id}, observed {observed_class}"
        ));
    }
    Ok(format!(
        "runtime recorded structured failure {failure_code} ({failure_class}) for {adapter_id}"
    ))
}

fn expect_output_manifest(
    record: &ConformanceRunRecord,
    adapter_id: &str,
    expected_files: &[&str],
) -> Result<String, String> {
    let Some(index) = &record.outputs_index else {
        return Err(format!("expected outputs manifest for {adapter_id}, but none was written"));
    };
    let files = index.files.iter().map(|file| file.name.as_str()).collect::<Vec<_>>();
    if expected_files.iter().all(|expected| files.iter().any(|file| file == expected)) {
        Ok(format!(
            "runtime wrote outputs manifest for {adapter_id} with files {}",
            files.join(", ")
        ))
    } else {
        Err(format!(
            "expected outputs manifest for {adapter_id} to contain {:?}, observed {:?}",
            expected_files, files
        ))
    }
}

fn expect_identity_schema(
    record: &ConformanceRunRecord,
    descriptor: &AdapterDescriptor,
) -> Result<String, String> {
    if record.trace.adapter_id != descriptor.id {
        return Err(format!(
            "expected adapter id {}, observed {}",
            descriptor.id, record.trace.adapter_id
        ));
    }
    if record.trace.adapter_version != descriptor.version {
        return Err(format!(
            "expected adapter version {}, observed {}",
            descriptor.version, record.trace.adapter_version
        ));
    }
    if record.trace.adapter_outputs_schema_version != descriptor.produces_outputs_schema_version {
        return Err(format!(
            "expected adapter outputs schema {}, observed {}",
            descriptor.produces_outputs_schema_version, record.trace.adapter_outputs_schema_version
        ));
    }
    Ok(format!(
        "trace recorded adapter identity {}@{} with schema {}",
        descriptor.id, descriptor.version, descriptor.produces_outputs_schema_version
    ))
}

fn execution_error(name: &str, reason: impl Into<String>) -> AdapterScenarioResult {
    scenario(name, AdapterScenarioStatus::Fail, true, false, false, &reason.into(), None)
}

fn runtime_config_with_env_policy() -> RuntimeConfig {
    RuntimeConfig {
        policy: PolicyConfig { clean_env: false, ..PolicyConfig::default() },
        ..RuntimeConfig::default()
    }
}

fn const_graph() -> String {
    json!({
        "spec": "bijux-dag/v0.1",
        "nodes": [{
            "id": "const",
            "kind": "const",
            "outputs": [{"name": "value", "path": "value.json", "media_type": "application/json"}],
            "params": {"value": {"message": "hello"}}
        }],
        "edges": []
    })
    .to_string()
}

fn shell_graph(command: &str, timeout_ms: Option<u64>) -> String {
    let mut node = json!({
        "id": "shell",
        "kind": "shell",
        "outputs": [{"name": "value", "path": "value.txt"}],
        "params": {"argv": ["/bin/sh", "-c", command]},
        "effects": ["filesystem"],
    });
    if let Some(timeout_ms) = timeout_ms {
        node["timeout_ms"] = json!(timeout_ms);
    }
    json!({
        "spec": "bijux-dag/v0.1",
        "nodes": [node],
        "edges": []
    })
    .to_string()
}

fn python_graph(module: &str, function: &str, timeout_ms: Option<u64>) -> String {
    let mut node = json!({
        "id": "python",
        "kind": "python",
        "outputs": [{"name": "result", "path": "result.json", "media_type": "application/json"}],
        "params": {
            "module": module,
            "function": function,
            "value": "payload"
        },
        "effects": ["filesystem", "env"],
        "env_allowlist": ["PYTHONPATH"]
    });
    if let Some(timeout_ms) = timeout_ms {
        node["timeout_ms"] = json!(timeout_ms);
    }
    json!({
        "spec": "bijux-dag/v0.1",
        "nodes": [node],
        "edges": []
    })
    .to_string()
}

fn http_graph(url: &str, timeout_ms: Option<u64>) -> String {
    let mut node = json!({
        "id": "http",
        "kind": "http",
        "outputs": [{"name": "response", "path": "response.json", "media_type": "application/json"}],
        "params": {
            "method": "GET",
            "url": url
        },
        "effects": ["filesystem", "network"]
    });
    if let Some(timeout_ms) = timeout_ms {
        node["timeout_ms"] = json!(timeout_ms);
    }
    json!({
        "spec": "bijux-dag/v0.1",
        "nodes": [node],
        "edges": []
    })
    .to_string()
}

fn file_transform_graph(params: Value, outputs: Vec<Value>, timeout_ms: Option<u64>) -> String {
    let seed_command = "printf 'alpha\\nbeta\\n' > ../outputs/source.txt";
    let mut file_node = json!({
        "id": "file_transform",
        "kind": "file_transform",
        "inputs": ["source"],
        "outputs": outputs,
        "params": params,
        "effects": ["filesystem"]
    });
    if let Some(timeout_ms) = timeout_ms {
        file_node["timeout_ms"] = json!(timeout_ms);
    }
    json!({
        "spec": "bijux-dag/v0.1",
        "nodes": [
            {
                "id": "seed",
                "kind": "shell",
                "outputs": [{"name": "source", "path": "source.txt"}],
                "params": {"argv": ["/bin/sh", "-c", seed_command]},
                "effects": ["filesystem"]
            },
            file_node
        ],
        "edges": [{
            "from": {"node_id": "seed", "port": "source"},
            "to": {"node_id": "file_transform", "port": "source"}
        }]
    })
    .to_string()
}

fn python_runtime_available() -> bool {
    ["python3", "python"].iter().any(|candidate| {
        std::process::Command::new(candidate)
            .arg("--version")
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    })
}

fn write_python_fixture(
    module_dir: &Path,
    module_name: &str,
    contents: &str,
) -> Result<(), String> {
    fs::create_dir_all(module_dir).map_err(|error| error.to_string())?;
    fs::write(module_dir.join(format!("{module_name}.py")), contents)
        .map_err(|error| error.to_string())
}

fn const_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    let workspace = match ConformanceWorkspace::new("const", "success") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let success =
        match execute_graph_record(&workspace, "const", &const_graph(), RuntimeConfig::default()) {
            Ok(record) => record,
            Err(error) => return canonical_execution_failure_suite(descriptor, error),
        };
    vec![
        run_scenario_check("success", &success, true, |record| expect_success(record, "const")),
        skip_scenario(
            "failure",
            false,
            true,
            "const adapter has no runtime failure path for valid node definitions",
        ),
        skip_scenario(
            "missing_output",
            false,
            true,
            "const adapter always materializes its declared value output",
        ),
        skip_scenario("timeout", false, true, "const adapter does not expose timeout-sensitive work"),
        run_scenario_check("output_manifest", &success, true, |record| {
            expect_output_manifest(record, "const", &["value"])
        }),
        skip_scenario(
            "failure_schema",
            false,
            true,
            "const adapter does not emit structured failure payloads for successful value materialization",
        ),
        run_scenario_check("adapter_identity_schema", &success, true, |record| {
            expect_identity_schema(record, descriptor)
        }),
    ]
}

fn shell_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    let success_workspace = match ConformanceWorkspace::new("shell", "success") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let success = match execute_graph_record(
        &success_workspace,
        "shell",
        &shell_graph("printf 'hello' > ../outputs/value.txt", None),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure_workspace = match ConformanceWorkspace::new("shell", "failure") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure = match execute_graph_record(
        &failure_workspace,
        "shell",
        &shell_graph("printf 'partial' > ../outputs/value.txt; printf 'boom' >&2; exit 7", None),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let missing_output_workspace = match ConformanceWorkspace::new("shell", "missing-output") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let missing_output = match execute_graph_record(
        &missing_output_workspace,
        "shell",
        &shell_graph("printf 'no-output'", None),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let timeout_workspace = match ConformanceWorkspace::new("shell", "timeout") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let timeout = match execute_graph_record(
        &timeout_workspace,
        "shell",
        &shell_graph("sleep 1", Some(50)),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    vec![
        run_scenario_check("success", &success, true, |record| expect_success(record, "shell")),
        run_scenario_check("failure", &failure, true, |record| {
            expect_failure(record, "shell", "EXEC_FAIL", "execution")
        }),
        run_scenario_check("missing_output", &missing_output, true, |record| {
            expect_failure(record, "shell", "OUTPUT_MISSING", "user")
        }),
        run_scenario_check("timeout", &timeout, true, |record| {
            expect_failure(record, "shell", "EXEC_TIMEOUT", "timeout")
        }),
        run_scenario_check("output_manifest", &success, true, |record| {
            expect_output_manifest(record, "shell", &["value"])
        }),
        run_scenario_check("failure_schema", &failure, true, |record| {
            expect_failure(record, "shell", "EXEC_FAIL", "execution")
        }),
        run_scenario_check("adapter_identity_schema", &success, true, |record| {
            expect_identity_schema(record, descriptor)
        }),
    ]
}

fn python_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    if !python_runtime_available() {
        return canonical_skip_suite(
            descriptor,
            "python interpreter is unavailable, so runtime-backed python conformance could not execute",
        );
    }

    let _env_lock = python_env_lock();
    let workspace = match ConformanceWorkspace::new("python", "fixtures") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let module_dir = workspace.path().join("python");
    if let Err(error) = write_python_fixture(
        &module_dir,
        "conformance_python_adapter",
        "import time\n\ndef emit(payload):\n    return payload\n\ndef explode(payload):\n    raise ValueError('boom')\n\ndef stall(payload):\n    time.sleep(1)\n    return payload\n",
    ) {
        return canonical_execution_failure_suite(descriptor, error);
    }
    let _pythonpath = ScopedEnvVar::set("PYTHONPATH", &module_dir);

    let success_workspace = match ConformanceWorkspace::new("python", "success") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let success = match execute_graph_record(
        &success_workspace,
        "python",
        &python_graph("conformance_python_adapter", "emit", None),
        runtime_config_with_env_policy(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure_workspace = match ConformanceWorkspace::new("python", "failure") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure = match execute_graph_record(
        &failure_workspace,
        "python",
        &python_graph("conformance_python_adapter", "explode", None),
        runtime_config_with_env_policy(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let timeout_workspace = match ConformanceWorkspace::new("python", "timeout") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let timeout = match execute_graph_record(
        &timeout_workspace,
        "python",
        &python_graph("conformance_python_adapter", "stall", Some(50)),
        runtime_config_with_env_policy(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    vec![
        run_scenario_check("success", &success, true, |record| expect_success(record, "python")),
        run_scenario_check("failure", &failure, true, |record| {
            expect_failure(record, "python", "PYTHON_EXCEPTION", "execution")
        }),
        skip_scenario(
            "missing_output",
            false,
            true,
            "python adapter failures are reported as structured execution exceptions before runtime output inspection",
        ),
        run_scenario_check("timeout", &timeout, true, |record| {
            expect_failure(record, "python", "EXEC_TIMEOUT", "timeout")
        }),
        run_scenario_check("output_manifest", &success, true, |record| {
            expect_output_manifest(record, "python", &["result"])
        }),
        run_scenario_check("failure_schema", &failure, true, |record| {
            expect_failure(record, "python", "PYTHON_EXCEPTION", "execution")
        }),
        run_scenario_check("adapter_identity_schema", &success, true, |record| {
            expect_identity_schema(record, descriptor)
        }),
    ]
}

fn http_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    let success_server = match ScriptedHttpServer::spawn(ScriptedHttpResponse {
        status_line: "200 OK",
        body: br#"{"ok":true}"#,
        content_type: "application/json",
        delay: Duration::ZERO,
    }) {
        Ok(server) => server,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let success_workspace = match ConformanceWorkspace::new("http", "success") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let success = match execute_graph_record(
        &success_workspace,
        "http",
        &http_graph(&success_server.url("/ok"), None),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };

    let failure_server = match ScriptedHttpServer::spawn(ScriptedHttpResponse {
        status_line: "503 Service Unavailable",
        body: b"service down",
        content_type: "text/plain",
        delay: Duration::ZERO,
    }) {
        Ok(server) => server,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure_workspace = match ConformanceWorkspace::new("http", "failure") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure = match execute_graph_record(
        &failure_workspace,
        "http",
        &http_graph(&failure_server.url("/fail"), None),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };

    let timeout_server = match ScriptedHttpServer::spawn(ScriptedHttpResponse {
        status_line: "200 OK",
        body: br#"{"ok":true}"#,
        content_type: "application/json",
        delay: Duration::from_millis(200),
    }) {
        Ok(server) => server,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let timeout_workspace = match ConformanceWorkspace::new("http", "timeout") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let timeout = match execute_graph_record(
        &timeout_workspace,
        "http",
        &http_graph(&timeout_server.url("/slow"), Some(50)),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };

    vec![
        run_scenario_check("success", &success, true, |record| expect_success(record, "http")),
        run_scenario_check("failure", &failure, true, |record| {
            expect_failure(record, "http", "HTTP_STATUS_ERROR", "execution")
        }),
        skip_scenario(
            "missing_output",
            false,
            true,
            "http adapter always materializes the response artifact before runtime output inspection",
        ),
        run_scenario_check("timeout", &timeout, true, |record| {
            expect_failure(record, "http", "EXEC_TIMEOUT", "timeout")
        }),
        run_scenario_check("output_manifest", &success, true, |record| {
            expect_output_manifest(record, "http", &["response"])
        }),
        run_scenario_check("failure_schema", &failure, true, |record| {
            expect_failure(record, "http", "HTTP_STATUS_ERROR", "execution")
        }),
        run_scenario_check("adapter_identity_schema", &success, true, |record| {
            expect_identity_schema(record, descriptor)
        }),
    ]
}

fn file_transform_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    let success_workspace = match ConformanceWorkspace::new("file-transform", "success") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let success = match execute_graph_record(
        &success_workspace,
        "file_transform",
        &file_transform_graph(
            json!({
                "operation": "copy",
                "source": "seed/source",
            }),
            vec![json!({"name": "artifact", "path": "artifact.txt"})],
            None,
        ),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure_workspace = match ConformanceWorkspace::new("file-transform", "failure") {
        Ok(workspace) => workspace,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    let failure = match execute_graph_record(
        &failure_workspace,
        "file_transform",
        &file_transform_graph(
            json!({
                "operation": "copy",
                "source": "seed/missing",
            }),
            vec![json!({"name": "artifact", "path": "artifact.txt"})],
            None,
        ),
        RuntimeConfig::default(),
    ) {
        Ok(record) => record,
        Err(error) => return canonical_execution_failure_suite(descriptor, error),
    };
    vec![
        run_scenario_check("success", &success, true, |record| {
            expect_success(record, "file_transform")
        }),
        run_scenario_check("failure", &failure, true, |record| {
            expect_failure(record, "file_transform", "EXEC_ERROR", "user")
        }),
        skip_scenario(
            "missing_output",
            false,
            true,
            "file_transform validates operation-specific output cardinality before generic runtime missing-output inspection",
        ),
        skip_scenario(
            "timeout",
            descriptor.supports_timeout,
            true,
            "file_transform timeout coverage remains adapter-specific and is not emitted by the generic conformance harness",
        ),
        run_scenario_check("output_manifest", &success, true, |record| {
            expect_output_manifest(record, "file_transform", &["artifact"])
        }),
        run_scenario_check("failure_schema", &failure, true, |record| {
            expect_failure(record, "file_transform", "EXEC_ERROR", "user")
        }),
        run_scenario_check("adapter_identity_schema", &success, true, |record| {
            expect_identity_schema(record, descriptor)
        }),
    ]
}

fn container_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    canonical_skip_suite(
        descriptor,
        "container adapter conformance requires a repository-owned image fixture and remains intentionally skipped until that fixture is defined",
    )
}

fn external_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    canonical_skip_suite(
        descriptor,
        "external adapters require adapter-specific fixtures before runtime-backed conformance can execute safely",
    )
}

fn unsupported_adapter_scenarios(descriptor: &AdapterDescriptor) -> Vec<AdapterScenarioResult> {
    canonical_skip_suite(
        descriptor,
        "no runtime-backed conformance fixture is registered for this adapter",
    )
}

fn canonical_skip_suite(
    descriptor: &AdapterDescriptor,
    reason: &str,
) -> Vec<AdapterScenarioResult> {
    vec![
        skip_scenario("success", true, false, reason),
        skip_scenario("failure", true, false, reason),
        skip_scenario("missing_output", true, false, reason),
        skip_scenario("timeout", descriptor.supports_timeout, !descriptor.supports_timeout, reason),
        skip_scenario("output_manifest", true, false, reason),
        skip_scenario("failure_schema", true, false, reason),
        skip_scenario("adapter_identity_schema", true, false, reason),
    ]
}

fn canonical_execution_failure_suite(
    descriptor: &AdapterDescriptor,
    error: String,
) -> Vec<AdapterScenarioResult> {
    vec![
        execution_error("success", error.clone()),
        execution_error("failure", error.clone()),
        execution_error("missing_output", error.clone()),
        execution_error("timeout", error.clone()),
        execution_error("output_manifest", error.clone()),
        execution_error("failure_schema", error.clone()),
        execution_error("adapter_identity_schema", error),
    ]
    .into_iter()
    .map(|mut scenario| {
        scenario.enforced_by_runtime =
            descriptor.supports_timeout || scenario.scenario != "timeout";
        scenario
    })
    .collect()
}