polydat 0.1.0

Polydat โ€” generation kernel for deterministic variate generation in nb-rs (formerly nbrs-variates)
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
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Programmatic assembly API for building GK kernels.
//!
//! The assembler validates wiring and types, auto-inserts edge adapters,
//! topologically sorts nodes, and produces either a Phase 1 runtime
//! kernel or a Phase 2 compiled kernel.

use std::collections::HashMap;

use crate::compiled::{CompiledKernelRaw, CompiledKernelPush, CompiledKernelPull, CompiledKernelPushPull};
use crate::engine::{self, GraphAnalysis, ProvMode, P2Engine};
use crate::kernel::{GkKernel, GkProgram, WireSource};
use crate::node::{GkNode, PortType};
use crate::nodes::convert::{F64ToString, U64ToF64, U64ToString};
use crate::nodes::json::JsonToStr;

/// A reference to a value in the assembler: either a coordinate or a
/// node output port.
#[derive(Debug, Clone)]
pub enum WireRef {
    /// A graph input, by name.
    Input(String),
    /// A node output: `(node_name, output_port_index)`.
    Node(String, usize),
}

impl WireRef {
    /// Convenience: reference the first (or only) output of a named node.
    pub fn node(name: impl Into<String>) -> Self {
        WireRef::Node(name.into(), 0)
    }

    /// Reference a specific output port of a named node.
    pub fn node_port(name: impl Into<String>, port: usize) -> Self {
        WireRef::Node(name.into(), port)
    }

    /// Reference a graph input by name.
    pub fn input(name: impl Into<String>) -> Self {
        WireRef::Input(name.into())
    }
}

struct PendingNode {
    name: String,
    node: Box<dyn GkNode>,
    inputs: Vec<WireRef>,
}

/// Errors that can occur during assembly.
#[derive(Debug)]
pub enum AssemblyError {
    UnknownWire(String),
    TypeMismatch {
        from_node: String,
        from_port: usize,
        from_type: PortType,
        to_node: String,
        to_port: usize,
        to_type: PortType,
    },
    DuplicateNode(String),
    CycleDetected,
    ArityMismatch {
        node_name: String,
        expected: usize,
        got: usize,
    },
    /// Catch-all for errors from downstream phases (e.g., strict mode).
    Other(String),
}

impl std::fmt::Display for AssemblyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AssemblyError::UnknownWire(name) => {
                write!(f, "unknown wire: '{name}'\n\n")?;
                writeln!(f, "  No node output or coordinate named '{name}' exists.")?;
                write!(f, "  Check spelling, or add a node that produces this output.")
            }
            AssemblyError::TypeMismatch {
                from_node, from_port, from_type, to_node, to_port, to_type,
            } => {
                writeln!(f, "type mismatch: cannot connect {from_type} output to {to_type} input")?;
                writeln!(f)?;
                writeln!(f, "  {from_node} [{from_port}]  โ”€โ”€({from_type})โ”€โ”€โ–ถ  {to_node} [{to_port}] expects {to_type}")?;
                writeln!(f)?;
                // Suggest auto-adapters that exist
                let suggestion = match (from_type, to_type) {
                    (PortType::U64, PortType::Str) => Some("This should auto-convert. If you see this, file a bug."),
                    (PortType::F64, PortType::Str) => Some("This should auto-convert. If you see this, file a bug."),
                    (PortType::U64, PortType::F64) => Some("This should auto-convert. If you see this, file a bug."),
                    (PortType::U64, PortType::Bytes) => Some("Add u64_to_bytes() between them to convert."),
                    (PortType::Str, PortType::Bytes) => Some("String cannot be directly used as bytes."),
                    (PortType::U64, PortType::Json) => Some("Add to_json() between them to wrap as JSON."),
                    (PortType::Str, PortType::Json) => Some("Add str_to_json() to parse the string as JSON."),
                    (PortType::Bytes, PortType::Str) => Some("Add to_hex() or to_base64() to convert bytes to string."),
                    (PortType::Bytes, PortType::U64) => Some("Bytes cannot be directly converted to u64."),
                    _ => None,
                };
                if let Some(hint) = suggestion {
                    write!(f, "  Hint: {hint}")?;
                }
                Ok(())
            }
            AssemblyError::DuplicateNode(name) => {
                write!(f, "duplicate node name: '{name}'\n\n")?;
                write!(f, "  Two nodes cannot share the same name.")
            }
            AssemblyError::CycleDetected => {
                write!(f, "cycle detected in DAG\n\n")?;
                writeln!(f, "  The graph contains a loop. GK graphs must be acyclic")?;
                write!(f, "  (data flows in one direction only).")
            }
            AssemblyError::ArityMismatch { node_name, expected, got } => {
                write!(f, "wrong number of inputs for '{node_name}'\n\n")?;
                writeln!(f, "  Expected {expected} input(s), but got {got}.")?;
                if *got < *expected {
                    write!(f, "  Connect more wires to this node's input ports.")
                } else {
                    write!(f, "  Disconnect extra wires from this node.")
                }
            }
            AssemblyError::Other(msg) => write!(f, "{msg}"),
        }
    }
}

impl std::error::Error for AssemblyError {}

/// Validated, topologically sorted intermediate form.
struct ResolvedDag {
    /// Nodes in topological order.
    nodes: Vec<Box<dyn GkNode>>,
    /// Per-node wiring (in topological order).
    wiring: Vec<Vec<WireSource>>,
    /// All input definitions (coordinates + captures).
    input_defs: Vec<crate::kernel::InputDef>,
    /// Number of coordinate inputs.
    coord_count: usize,
    /// Output name โ†’ (node_index_in_sorted, output_port_index).
    output_map: HashMap<String, (usize, usize)>,
    /// Output names in declaration order.
    output_order: Vec<String>,
    /// Source text for diagnostics.
    source: String,
    /// Diagnostic context.
    context: String,
    /// Output binding modifiers.
    output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
    /// Names declared with `init` (SRD 11 ยง"Init Binding Contract").
    const_outputs: std::collections::HashSet<String>,
}

impl ResolvedDag {
    /// Coordinate input names (for P2/P3 kernels that use positional u64 buffers).
    fn input_names(&self) -> Vec<String> {
        self.input_defs[..self.coord_count].iter()
            .map(|d| d.name.clone()).collect()
    }
}

/// Builder for assembling a GK kernel programmatically.
pub struct GkAssembler {
    /// All input definitions. Coordinates come first (indices 0..coord_count).
    input_defs: Vec<crate::kernel::InputDef>,
    /// How many of the inputs are coordinates.
    coord_count: usize,
    nodes: Vec<PendingNode>,
    /// Output declarations in insertion order.
    output_order: Vec<String>,
    outputs: HashMap<String, WireRef>,
    /// Original source text for diagnostics. Set by the DSL compiler.
    source: String,
    /// Diagnostic context (e.g., "workload.yaml bindings").
    context: String,
    /// Binding modifiers for named outputs.
    output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
    /// Names declared with the `const` keyword. Subject to the
    /// init-binding contract (SRD 11 ยง"Init Binding Contract").
    const_outputs: std::collections::HashSet<String>,
    /// SRD 15 ยง"Strict Wire Mode": when true, the resolver
    /// auto-inserts `AssertValue` nodes in front of every wire
    /// input whose declared `Port.constraint` can't be statically
    /// proven satisfied by the source.
    pub(crate) strict_values: bool,
    /// SRD 15: when true, the resolver auto-inserts `AssertType`
    /// nodes in front of wires where the source's runtime variant
    /// can't be statically proven to match the sink's declared
    /// `PortType`. Today this is mainly latent โ€” the type system
    /// already proves variants match for nearly every wire โ€” so
    /// the flag exists for forward compatibility with dynamic
    /// JSON navigation, `Ext` unwraps, and cross-adapter values.
    pub(crate) strict_types: bool,
}

impl GkAssembler {
    /// Create a new assembler with the given coordinate names.
    pub fn new(input_names: Vec<String>) -> Self {
        let coord_count = input_names.len();
        let input_defs: Vec<crate::kernel::InputDef> = input_names.into_iter()
            .map(|name| crate::kernel::InputDef {
                name,
                default: crate::node::Value::U64(0),
                port_type: crate::node::PortType::U64,
                kind: crate::kernel::InputKind::Coordinate,
            })
            .collect();
        Self {
            input_defs,
            coord_count,
            nodes: Vec::new(),
            output_order: Vec::new(),
            outputs: HashMap::new(),
            source: String::new(),
            context: "(assembler)".into(),
            output_modifiers: HashMap::new(),
            const_outputs: std::collections::HashSet::new(),
            strict_values: false,
            strict_types: false,
        }
    }

    /// Enable strict-wire-mode auto-insertion of value/type assertion
    /// nodes (SRD 15 ยง"Strict Wire Mode"). Off by default โ€” the
    /// caller (compiler / DSL pragma extractor) opts in.
    pub fn set_strict_wires(&mut self, strict_types: bool, strict_values: bool) {
        self.strict_types = strict_types;
        self.strict_values = strict_values;
    }

    /// Set the source text and diagnostic context for this assembler.
    /// Called by the DSL compiler to attach the original GK source.
    pub fn set_context(&mut self, source: &str, context: &str) {
        self.source = source.to_string();
        self.context = context.to_string();
    }

    /// Add a node to the assembler with the given name and input wiring.
    pub fn add_node(
        &mut self,
        name: impl Into<String>,
        node: Box<dyn GkNode>,
        inputs: Vec<WireRef>,
    ) -> &mut Self {
        self.nodes.push(PendingNode {
            name: name.into(),
            node,
            inputs,
        });
        self
    }

    /// Set the binding modifier for a named output.
    pub fn set_output_modifier(&mut self, name: &str, modifier: crate::dsl::ast::BindingModifier) {
        if modifier != crate::dsl::ast::BindingModifier::NONE {
            self.output_modifiers.insert(name.to_string(), modifier);
        }
    }

    /// Mark an output as declared with the `const` keyword. Compile-
    /// time and scope-activation checks (SRD 11 ยง"Init Binding
    /// Contract") read this set to enforce const-like-constraint
    /// semantics on the binding.
    pub fn mark_const_output(&mut self, name: &str) {
        self.const_outputs.insert(name.to_string());
    }

    /// Designate a wire as a named output variate.
    pub fn add_output(&mut self, name: impl Into<String>, wire: WireRef) -> &mut Self {
        let name = name.into();
        if !self.outputs.contains_key(&name) {
            self.output_order.push(name.clone());
        }
        self.outputs.insert(name, wire);
        self
    }

    /// Declare an additional named input.
    ///
    /// Added after coordinate inputs. Nodes wire to it via
    /// `WireRef::input(name)` โ€” same as coordinate inputs.
    /// `kind` controls the lifecycle classification used by the
    /// init-binding contract (see [SRD 11](../../../docs/sysref/11_gk_evaluation.md)
    /// ยง"Effectively-Const Nodes"): `IterationExtern` for slots
    /// populated by `materialize_wiring_from_outer`, `CapturePort` for slots
    /// written by capture extraction.
    pub fn add_input(&mut self, name: impl Into<String>, default: crate::node::Value, port_type: crate::node::PortType, kind: crate::kernel::InputKind) -> &mut Self {
        self.input_defs.push(crate::kernel::InputDef {
            name: name.into(),
            default,
            port_type,
            kind,
        });
        self
    }

    /// Return the names of all inputs (coordinates + captures).
    pub fn input_names(&self) -> Vec<&str> {
        self.input_defs.iter().map(|d| d.name.as_str()).collect()
    }

    /// Query the output port type of a named node (first output).
    /// Returns U64 if the node is not found.
    pub fn node_output_type(&self, name: &str) -> crate::node::PortType {
        self.nodes.iter()
            .find(|n| n.name == name)
            .and_then(|n| n.node.meta().outs.first())
            .map(|p| p.typ)
            .unwrap_or(crate::node::PortType::U64)
    }

    /// Return the names of declared outputs.
    pub fn output_names(&self) -> Vec<&str> {
        self.outputs.keys().map(|s| s.as_str()).collect()
    }

    /// Look up the output port type of a named node.
    ///
    /// Returns the first output port's `PortType` if the node exists.
    pub fn output_type(&self, name: &str) -> Option<PortType> {
        self.nodes.iter()
            .find(|pn| pn.name == name)
            .and_then(|pn| pn.node.meta().outs.first())
            .map(|port| port.typ)
    }

    /// Look up the port type of a graph input by name.
    pub fn input_type(&self, name: &str) -> Option<PortType> {
        self.input_defs.iter()
            .find(|d| d.name == name)
            .map(|d| d.port_type)
    }

    /// Look up the produced port type of a `WireRef`. Returns `None`
    /// if the wire's source isn't yet known to the assembler (e.g.
    /// it points to a not-yet-added node โ€” a bug in the binding
    /// compiler if it happens).
    pub fn wire_type(&self, wire: &WireRef) -> Option<PortType> {
        match wire {
            WireRef::Input(name) => self.input_type(name),
            WireRef::Node(name, port_idx) => self.nodes.iter()
                .find(|pn| &pn.name == name)
                .and_then(|pn| pn.node.meta().outs.get(*port_idx))
                .map(|p| p.typ),
        }
    }

    /// Validate, resolve, and produce a Phase 1 runtime kernel.
    pub fn compile(self) -> Result<GkKernel, AssemblyError> {
        self.compile_with_log(None)
    }

    /// Compile with diagnostic event logging.
    pub fn compile_with_log(self, mut log: Option<&mut crate::dsl::events::CompileEventLog>) -> Result<GkKernel, AssemblyError> {
        let resolved = self.resolve_with_log(log.as_deref_mut())?;
        let _coord_names = resolved.input_names();
        let modifiers = resolved.output_modifiers.clone();
        let kernel = GkKernel::new_with_inputs(
            resolved.nodes,
            resolved.wiring,
            resolved.input_defs,
            resolved.coord_count,
            resolved.output_map,
            resolved.output_order,
            resolved.const_outputs,
            modifiers,
            &resolved.source,
            &resolved.context,
            log,
        ).map_err(AssemblyError::Other)?;
        Ok(kernel)
    }

    /// Compile with strict mode: config wire violations are errors,
    /// implicit type coercions are rejected, unused bindings flagged.
    pub fn compile_strict(self, strict: bool) -> Result<GkKernel, AssemblyError> {
        if !strict {
            return self.compile();
        }
        let resolved = self.resolve()?;
        let _coord_names = resolved.input_names();

        // Strict: reject implicit type coercions (auto-inserted adapter nodes)
        // Adapters have names starting with "__" and containing type conversion hints
        let adapter_count = resolved.nodes.iter()
            .filter(|n| {
                let name = &n.meta().name;
                name.starts_with("__adapt_") || name.starts_with("__u64_to_") || name.starts_with("__f64_to_")
                    || name.starts_with("__bool_to_") || name.starts_with("__str_to_")
            })
            .count();
        if adapter_count > 0 {
            return Err(AssemblyError::Other(format!(
                "strict mode: {adapter_count} implicit type coercion(s) inserted. \
                 Use explicit conversion functions (e.g., u64_to_f64, f64_to_u64)."
            )));
        }

        let modifiers = resolved.output_modifiers.clone();
        let kernel = GkKernel::new_strict_with_inputs(
            resolved.nodes,
            resolved.wiring,
            resolved.input_defs,
            resolved.coord_count,
            resolved.output_map,
            resolved.output_order,
            resolved.const_outputs,
            modifiers,
            &resolved.source,
            &resolved.context,
            None,
        ).map_err(AssemblyError::Other)?;
        Ok(kernel)
    }

    /// Validate, resolve, and attempt Phase 2 compilation.
    ///
    /// Returns `Ok(CompiledKernelPushPull)` if all nodes are u64-only and provide
    /// `compiled_u64()`. Falls back to `Err(GkKernel)` (a working Phase 1
    /// kernel) if any node cannot be compiled.
    pub fn try_compile(self) -> Result<CompiledKernelPushPull, GkKernel> {
        let resolved = self.resolve().expect("assembly validation failed");
        let _coord_names = resolved.input_names();
        let coord_names = resolved.input_names();
        let coord_count = coord_names.len();

        // Try to extract compiled_u64 from every node
        let mut compiled_ops = Vec::with_capacity(resolved.nodes.len());
        let mut all_compilable = true;
        for node in &resolved.nodes {
            if let Some(op) = node.compiled_u64() {
                compiled_ops.push(Some(op));
            } else {
                all_compilable = false;
                compiled_ops.push(None);
            }
        }

        if !all_compilable {
            // Fall back to Phase 1
            return Err(GkKernel::new(
                resolved.nodes,
                resolved.wiring,
                coord_names,
                resolved.output_map,
                &resolved.source,
                &resolved.context,
            ));
        }

        // Assign buffer slots: coordinates first, then each node's
        // output ports in topological order.
        let mut slot_base: Vec<usize> = Vec::with_capacity(resolved.nodes.len());
        let mut next_slot = coord_count;
        for node in &resolved.nodes {
            slot_base.push(next_slot);
            next_slot += node.meta().outs.len();
        }
        let total_slots = next_slot;

        // Build compiled steps
        let mut steps = Vec::with_capacity(resolved.nodes.len());
        for (node_idx, op) in compiled_ops.into_iter().enumerate() {
            let op = op.unwrap(); // safe: all_compilable checked above

            // Map wiring to buffer slot indices
            let input_slots: Vec<usize> = resolved.wiring[node_idx]
                .iter()
                .map(|source| match source {
                    WireSource::Input(c) => *c,
                    WireSource::NodeOutput(upstream, port) => slot_base[*upstream] + port,
                })
                .collect();

            let output_count = resolved.nodes[node_idx].meta().outs.len();
            let output_slots: Vec<usize> = (0..output_count)
                .map(|p| slot_base[node_idx] + p)
                .collect();

            steps.push((op, input_slots, output_slots));
        }

        // Remap output names to buffer slots
        let output_map: HashMap<String, usize> = resolved
            .output_map
            .iter()
            .map(|(name, (node_idx, port))| {
                (name.clone(), slot_base[*node_idx] + port)
            })
            .collect();

        Ok(CompiledKernelPushPull::new(
            coord_count, total_slots, steps, output_map,
            GkProgram::compute_dependents(
                &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
                coord_count,
            ),
        ))
    }

    /// Phase 2 compilation without provenance caching.
    pub fn try_compile_raw(self) -> Result<CompiledKernelRaw, GkKernel> {
        let resolved = match self.resolve() {
            Ok(r) => r,
            Err(_) => return Err(GkKernel::new(vec![], vec![], vec![], HashMap::new(), "", "(fallback)")),
        };
        let coord_names = resolved.input_names();
        let coord_count = coord_names.len();
        let mut slot_base: Vec<usize> = Vec::with_capacity(resolved.nodes.len());
        let mut next_slot = coord_count;
        for node in &resolved.nodes {
            slot_base.push(next_slot);
            next_slot += node.meta().outs.len();
        }
        let total_slots = next_slot;
        let mut compiled_ops = Vec::with_capacity(resolved.nodes.len());
        let mut all_compilable = true;
        for node in &resolved.nodes {
            if let Some(op) = node.compiled_u64() {
                compiled_ops.push(Some(op));
            } else {
                all_compilable = false;
                compiled_ops.push(None);
            }
        }
        if !all_compilable {
            return Err(GkKernel::new(
                resolved.nodes, resolved.wiring, coord_names.clone(), resolved.output_map,
                &resolved.source, &resolved.context,
            ));
        }
        let mut steps = Vec::with_capacity(resolved.nodes.len());
        for (node_idx, op) in compiled_ops.into_iter().enumerate() {
            let op = op.unwrap();
            let input_slots: Vec<usize> = resolved.wiring[node_idx].iter()
                .map(|source| match source {
                    WireSource::Input(c) => *c,
                    WireSource::NodeOutput(upstream, port) => slot_base[*upstream] + port,
                }).collect();
            let output_count = resolved.nodes[node_idx].meta().outs.len();
            let output_slots: Vec<usize> = (0..output_count).map(|p| slot_base[node_idx] + p).collect();
            steps.push((op, input_slots, output_slots));
        }
        let output_map = resolved.output_map.iter()
            .map(|(name, (node_idx, port))| (name.clone(), slot_base[*node_idx] + port))
            .collect();
        Ok(CompiledKernelRaw::new(coord_count, total_slots, steps, output_map))
    }

    /// Phase 2 compilation with push-side provenance only (no cone guard).
    pub fn try_compile_push(self) -> Result<CompiledKernelPush, GkKernel> {
        let resolved = match self.resolve() {
            Ok(r) => r,
            Err(_) => return Err(GkKernel::new(vec![], vec![], vec![], HashMap::new(), "", "(fallback)")),
        };
        let coord_names = resolved.input_names();
        let (coord_count, total_slots, steps, output_map) =
            match Self::build_p2_layout(&resolved) {
                Some(r) => r,
                None => return Err(GkKernel::new(
                    resolved.nodes, resolved.wiring, coord_names, resolved.output_map,
                    &resolved.source, &resolved.context)),
            };
        let dependents = GkProgram::compute_dependents(
            &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
            coord_count,
        );
        Ok(CompiledKernelPush::new(coord_count, total_slots, steps, output_map, dependents))
    }

    /// Phase 2 compilation with pull-side cone guard only (no per-node skip).
    pub fn try_compile_pull(self) -> Result<CompiledKernelPull, GkKernel> {
        let resolved = match self.resolve() {
            Ok(r) => r,
            Err(_) => return Err(GkKernel::new(vec![], vec![], vec![], HashMap::new(), "", "(fallback)")),
        };
        let coord_names = resolved.input_names();
        let (coord_count, total_slots, steps, output_map) =
            match Self::build_p2_layout(&resolved) {
                Some(r) => r,
                None => return Err(GkKernel::new(
                    resolved.nodes, resolved.wiring, coord_names, resolved.output_map,
                    &resolved.source, &resolved.context)),
            };
        let dependents = GkProgram::compute_dependents(
            &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
            coord_count,
        );
        Ok(CompiledKernelPull::new(coord_count, total_slots, steps, output_map, &dependents))
    }

    /// Shared: extract P2 compiled steps + slot layout from resolved DAG.
    /// Returns None if any node lacks a compiled_u64 implementation.
    fn build_p2_layout(
        resolved: &ResolvedDag,
    ) -> Option<(usize, usize, Vec<(crate::node::CompiledU64Op, Vec<usize>, Vec<usize>)>, HashMap<String, usize>)> {
        let coord_count = resolved.coord_count;
        let mut slot_base: Vec<usize> = Vec::with_capacity(resolved.nodes.len());
        let mut next_slot = coord_count;
        for node in &resolved.nodes {
            slot_base.push(next_slot);
            next_slot += node.meta().outs.len();
        }
        let total_slots = next_slot;

        let mut compiled_ops = Vec::with_capacity(resolved.nodes.len());
        for node in &resolved.nodes {
            compiled_ops.push(node.compiled_u64()?);
        }

        let mut steps = Vec::with_capacity(resolved.nodes.len());
        for (node_idx, op) in compiled_ops.into_iter().enumerate() {
            let input_slots: Vec<usize> = resolved.wiring[node_idx].iter()
                .map(|source| match source {
                    WireSource::Input(c) => *c,
                    WireSource::NodeOutput(upstream, port) => slot_base[*upstream] + port,
                }).collect();
            let output_count = resolved.nodes[node_idx].meta().outs.len();
            let output_slots: Vec<usize> = (0..output_count).map(|p| slot_base[node_idx] + p).collect();
            steps.push((op, input_slots, output_slots));
        }
        let output_map = resolved.output_map.iter()
            .map(|(name, (node_idx, port))| (name.clone(), slot_base[*node_idx] + port))
            .collect();

        Some((coord_count, total_slots, steps, output_map))
    }

    /// Shared: resolve nodes to JIT steps + slot layout.
    #[cfg(feature = "jit")]
    fn build_jit_layout(resolved: &ResolvedDag)
        -> Result<(usize, usize, Vec<(crate::jit::JitOp, Vec<usize>, Vec<usize>)>, HashMap<String, usize>), String>
    {
        let coord_count = resolved.coord_count;
        let mut slot_base: Vec<usize> = Vec::with_capacity(resolved.nodes.len());
        let mut next_slot = coord_count;
        for node in &resolved.nodes { slot_base.push(next_slot); next_slot += node.meta().outs.len(); }
        let total_slots = next_slot;

        let mut jit_steps = Vec::new();
        for (node_idx, node) in resolved.nodes.iter().enumerate() {
            let jit_op = crate::jit::classify_node(node.as_ref());
            let input_slots: Vec<usize> = resolved.wiring[node_idx].iter()
                .map(|s| match s {
                    WireSource::Input(c) => *c,
                    WireSource::NodeOutput(u, p) => slot_base[*u] + p,
                }).collect();
            let output_slots: Vec<usize> = (0..node.meta().outs.len())
                .map(|p| slot_base[node_idx] + p).collect();
            jit_steps.push((jit_op, input_slots, output_slots));
        }

        if jit_steps.iter().any(|(op, _, _)| matches!(op, crate::jit::JitOp::Fallback)) {
            return Err("some nodes cannot be JIT-compiled".into());
        }

        let output_map = resolved.output_map.iter()
            .map(|(name, (ni, p))| (name.clone(), slot_base[*ni] + p)).collect();
        Ok((coord_count, total_slots, jit_steps, output_map))
    }

    /// Phase 3 JIT: push+pull (full provenance).
    #[cfg(feature = "jit")]
    pub fn try_compile_jit(self) -> Result<crate::jit::JitKernelPushPull, String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let (coord_count, total_slots, jit_steps, output_map) = Self::build_jit_layout(&resolved)?;
        let deps = GkProgram::compute_dependents(
            &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
        crate::jit::compile_jit_push_pull(coord_count, total_slots, jit_steps, output_map, resolved.nodes, deps)
    }

    /// Phase 3 JIT: raw (no provenance).
    #[cfg(feature = "jit")]
    pub fn try_compile_jit_raw(self) -> Result<crate::jit::JitKernelRaw, String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let (coord_count, total_slots, jit_steps, output_map) = Self::build_jit_layout(&resolved)?;
        crate::jit::compile_jit_raw(coord_count, total_slots, jit_steps, output_map, resolved.nodes)
    }

    /// Phase 3 JIT: push-only (per-node dirty tracking, no cone guard).
    #[cfg(feature = "jit")]
    pub fn try_compile_jit_push(self) -> Result<crate::jit::JitKernelPush, String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let (coord_count, total_slots, jit_steps, output_map) = Self::build_jit_layout(&resolved)?;
        let deps = GkProgram::compute_dependents(
            &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
        crate::jit::compile_jit_push(coord_count, total_slots, jit_steps, output_map, resolved.nodes, deps)
    }

    /// Phase 3 JIT: pull-only (cone guard, no per-node dirty tracking).
    #[cfg(feature = "jit")]
    pub fn try_compile_jit_pull(self) -> Result<crate::jit::JitKernelPull, String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let (coord_count, total_slots, jit_steps, output_map) = Self::build_jit_layout(&resolved)?;
        let deps = GkProgram::compute_dependents(
            &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
        crate::jit::compile_jit_pull(coord_count, total_slots, jit_steps, output_map, resolved.nodes, &deps)
    }

    /// Analyze the graph and auto-select the optimal P2 provenance mode.
    ///
    /// Returns a `P2Engine` enum wrapping the monomorphic kernel variant.
    /// The selection is based on graph structure (cone sizes, input count).
    pub fn auto_compile_p2(self) -> Result<(P2Engine, GraphAnalysis), String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let analysis = engine::analyze_graph(&resolved.nodes, &resolved.wiring, &resolved.output_map);
        let mode = engine::select_prov_mode(&analysis);

        let (coord_count, total_slots, steps, output_map) =
            match Self::build_p2_layout(&resolved) {
                Some(r) => r,
                None => return Err("not all nodes support P2 compilation".into()),
            };

        let engine = match mode {
            ProvMode::Raw => {
                P2Engine::Raw(CompiledKernelRaw::new(coord_count, total_slots, steps, output_map))
            }
            ProvMode::Pull => {
                let deps = GkProgram::compute_dependents(
                    &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
                P2Engine::Pull(CompiledKernelPull::new(coord_count, total_slots, steps, output_map, &deps))
            }
            ProvMode::PushPull => {
                let deps = GkProgram::compute_dependents(
                    &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
                P2Engine::PushPull(CompiledKernelPushPull::new(coord_count, total_slots, steps, output_map, deps))
            }
        };
        Ok((engine, analysis))
    }

    /// Analyze the graph and auto-select the optimal P3 JIT provenance mode.
    #[cfg(feature = "jit")]
    pub fn auto_compile_p3(self) -> Result<(engine::P3Engine, GraphAnalysis), String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let analysis = engine::analyze_graph(&resolved.nodes, &resolved.wiring, &resolved.output_map);
        let mode = engine::select_prov_mode(&analysis);

        let (coord_count, total_slots, jit_steps, output_map) =
            Self::build_jit_layout(&resolved)?;

        let engine = match mode {
            ProvMode::Raw => {
                let k = crate::jit::compile_jit_raw(coord_count, total_slots, jit_steps, output_map, resolved.nodes)?;
                engine::P3Engine::Raw(k)
            }
            ProvMode::Pull => {
                let deps = GkProgram::compute_dependents(
                    &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
                let k = crate::jit::compile_jit_pull(coord_count, total_slots, jit_steps, output_map, resolved.nodes, &deps)?;
                engine::P3Engine::Pull(k)
            }
            ProvMode::PushPull => {
                let deps = GkProgram::compute_dependents(
                    &GkProgram::compute_provenance(&resolved.nodes, &resolved.wiring), coord_count);
                let k = crate::jit::compile_jit_push_pull(coord_count, total_slots, jit_steps, output_map, resolved.nodes, deps)?;
                engine::P3Engine::PushPull(k)
            }
        };
        Ok((engine, analysis))
    }

    /// Validate, resolve, and compile a hybrid kernel where each node
    /// runs at its optimal level (JIT native code or Phase 2 closure).
    ///
    /// This always succeeds for u64-only DAGs โ€” no all-or-nothing
    /// fallback. JIT-able nodes get native code, others get closures.
    pub fn compile_hybrid(self) -> Result<crate::hybrid::HybridKernel, String> {
        let resolved = self.resolve().map_err(|e| format!("{e}"))?;
        let _coord_names = resolved.input_names();
        let coord_count = resolved.coord_count;

        let mut slot_bases: Vec<usize> = Vec::with_capacity(resolved.nodes.len());
        let mut next_slot = coord_count;
        for node in &resolved.nodes {
            slot_bases.push(next_slot);
            next_slot += node.meta().outs.len();
        }
        let total_slots = next_slot;

        let output_map: HashMap<String, usize> = resolved
            .output_map
            .iter()
            .map(|(name, (node_idx, port))| {
                (name.clone(), slot_bases[*node_idx] + port)
            })
            .collect();

        let mut kernel = crate::hybrid::build_hybrid(
            &resolved.nodes,
            &resolved.wiring,
            coord_count,
            total_slots,
            &slot_bases,
            output_map,
        )?;
        kernel.retain_nodes(resolved.nodes);
        Ok(kernel)
    }

    /// Internal: validate, resolve wiring, insert adapters, topological sort.
    fn resolve(self) -> Result<ResolvedDag, AssemblyError> {
        self.resolve_with_log(None)
    }

    fn resolve_with_log(self, mut log: Option<&mut crate::dsl::events::CompileEventLog>) -> Result<ResolvedDag, AssemblyError> {
        // Build name โ†’ index map for nodes
        let mut name_to_idx: HashMap<String, usize> = HashMap::new();
        for (i, pn) in self.nodes.iter().enumerate() {
            if name_to_idx.contains_key(&pn.name) {
                return Err(AssemblyError::DuplicateNode(pn.name.clone()));
            }
            name_to_idx.insert(pn.name.clone(), i);
        }

        // Build input name โ†’ index map (covers both coords and captures)
        let input_to_idx: HashMap<String, usize> = self
            .input_defs
            .iter()
            .enumerate()
            .map(|(i, d)| (d.name.clone(), i))
            .collect();

        // Validate arity
        for pn in &self.nodes {
            let expected = pn.node.meta().wire_inputs().len();
            let got = pn.inputs.len();
            if expected != got {
                return Err(AssemblyError::ArityMismatch {
                    node_name: pn.name.clone(),
                    expected,
                    got,
                });
            }
        }

        let mut all_nodes: Vec<PendingNode> = Vec::new();
        let mut all_name_to_idx: HashMap<String, usize> = HashMap::new();
        let mut adapter_count = 0usize;
        let mut assertion_count = 0usize;
        let strict_values = self.strict_values;
        let strict_types = self.strict_types;

        for pn in self.nodes {
            let idx = all_nodes.len();
            all_name_to_idx.insert(pn.name.clone(), idx);
            all_nodes.push(pn);
        }

        let mut resolved_wiring: Vec<Vec<WireSource>> = Vec::new();

        for node_idx in 0..all_nodes.len() {
            let mut node_wiring = Vec::new();

            for (port_idx, wire_ref) in all_nodes[node_idx].inputs.clone().iter().enumerate() {
                let expected_type = all_nodes[node_idx].node.meta().wire_inputs()[port_idx].typ;

                let (source, source_type) = match wire_ref {
                    WireRef::Input(name) => {
                        let input_idx = input_to_idx
                            .get(name)
                            .ok_or_else(|| AssemblyError::UnknownWire(name.clone()))?;
                        let source_type = self.input_defs[*input_idx].port_type;
                        (WireSource::Input(*input_idx), source_type)
                    }
                    WireRef::Node(name, out_port) => {
                        let src_idx = all_name_to_idx
                            .get(name)
                            .ok_or_else(|| AssemblyError::UnknownWire(name.clone()))?;
                        let src_type = all_nodes[*src_idx].node.meta().outs[*out_port].typ;
                        (WireSource::NodeOutput(*src_idx, *out_port), src_type)
                    }
                };

                // Printf accepts any input type โ€” skip type checking for it.
                // `pick` is also type-flexible: its selector wires must be
                // Bool but its value wires can be any type so long as they
                // share a common type at eval โ€” uniformity is enforced at
                // eval time (SRD-66 ยง"Surface 3"). The variadic ctor can't
                // know the value-half port type at construction, so we
                // declare placeholder ports and skip the assembler check;
                // the per-eval validator catches mismatches with a clear
                // panic via `enrich_eval_panic`.
                //
                // The `log_*` family is also type-polymorphic by intent:
                // `log_info(regex_match(...))` is the canonical SRD-66
                // probe-phase shape, where the input is Bool. Without
                // skipping the check, the assembler inserts a Boolโ†’Str
                // adapter that converts the value, breaking the
                // result-binding writeback (the cell receives Str("false")
                // instead of Bool(false), and downstream `pick` rejects
                // it as non-bool). The eval is a pass-through, so the
                // actual value flows through unchanged.
                // `exactly_one_value` is similarly type-polymorphic:
                // its eval inspects the actual `Value` variant and
                // walks structural shape (Json / VecF32 / VecI32) or
                // passes through scalars. The declared input port
                // type is a placeholder. Without the skip, an
                // upstream `Json` body (the magic `body` extern's
                // declared type) gets coerced to `Str` via the
                // `JsonToStr` adapter โ€” at which point the SRD-66
                // probe shape `regex_match(exactly_one_value(body), โ€ฆ)`
                // sees JSON-serialised text with `\n` literal
                // escapes, and `^`-anchored regexes never match
                // inside `create_statement` columns.
                let node_name_for_typing = &all_nodes[node_idx].node.meta().name;
                let skip_type_check = node_name_for_typing == "printf"
                    || node_name_for_typing == "pick"
                    || node_name_for_typing == "log_debug"
                    || node_name_for_typing == "log_info"
                    || node_name_for_typing == "log_warn"
                    || node_name_for_typing == "log_error"
                    || node_name_for_typing == "exactly_one_value"
                    || node_name_for_typing == "json_text"
                    || node_name_for_typing == "str_concat";

                if skip_type_check || source_type == expected_type {
                    node_wiring.push(source);
                } else if let Some(adapter) = auto_adapter(source_type, expected_type) {
                    let adapter_name = format!("__adapt_{adapter_count}");
                    adapter_count += 1;
                    let adapter_idx = all_nodes.len();

                    if let Some(ref mut log) = log {
                        let from_name = match wire_ref {
                            WireRef::Input(n) => n.clone(),
                            WireRef::Node(n, _) => n.clone(),
                        };
                        log.push(crate::dsl::events::CompileEvent::TypeAdapterInserted {
                            from_node: from_name,
                            to_node: all_nodes[node_idx].name.clone(),
                            adapter: format!("{source_type:?}โ†’{expected_type:?}"),
                        });
                    }

                    all_name_to_idx.insert(adapter_name.clone(), adapter_idx);

                    let adapter_wiring = vec![source];
                    while resolved_wiring.len() <= adapter_idx {
                        resolved_wiring.push(Vec::new());
                    }
                    resolved_wiring[adapter_idx] = adapter_wiring;

                    all_nodes.push(PendingNode {
                        name: adapter_name,
                        node: adapter,
                        inputs: vec![],
                    });

                    node_wiring.push(WireSource::NodeOutput(adapter_idx, 0));
                } else {
                    let from_name = match wire_ref {
                        WireRef::Input(n) => n.clone(),
                        WireRef::Node(n, _) => n.clone(),
                    };
                    return Err(AssemblyError::TypeMismatch {
                        from_node: from_name,
                        from_port: match wire_ref {
                            WireRef::Input(_) => 0,
                            WireRef::Node(_, p) => *p,
                        },
                        from_type: source_type,
                        to_node: all_nodes[node_idx].name.clone(),
                        to_port: port_idx,
                        to_type: expected_type,
                    });
                }

                // === Strict-wire assertion insertion (SRD 15) ===
                //
                // After a wire is resolved (and any type adapter
                // inserted), look at the sink port's declared
                // `constraint`. If strict_values is on, we either
                // prove the source already satisfies it (skip) or
                // splice an `AssertValue` node in front of the
                // sink. The skip cases mirror the four bullets in
                // SRD 15 ยง"Strict Wire Mode": static type match is
                // already handled by the adapter pass above; here
                // we cover constant sources and upstream-assertion
                // chains for value constraints.
                let sink_port = &all_nodes[node_idx].node.meta().wire_inputs()[port_idx];
                if let Some(constraint) = sink_port.constraint.clone() {
                    let last_source = node_wiring.last().expect("wire just pushed").clone();
                    if strict_values && !value_constraint_proven(
                        &all_nodes,
                        &last_source,
                        &constraint,
                    ) {
                        let assert_name = format!("__assert_v_{assertion_count}");
                        assertion_count += 1;
                        let assert_idx = all_nodes.len();

                        if let Some(ref mut log) = log {
                            let from_name = match wire_ref {
                                WireRef::Input(n) => n.clone(),
                                WireRef::Node(n, _) => n.clone(),
                            };
                            log.push(crate::dsl::events::CompileEvent::AssertionInserted {
                                from_node: from_name,
                                to_node: all_nodes[node_idx].name.clone(),
                                kind: format!("{:?} value-assert {:?}",
                                    expected_type, &constraint),
                            });
                        }

                        all_name_to_idx.insert(assert_name.clone(), assert_idx);
                        let assert_wiring = vec![last_source];
                        while resolved_wiring.len() <= assert_idx {
                            resolved_wiring.push(Vec::new());
                        }
                        resolved_wiring[assert_idx] = assert_wiring;

                        all_nodes.push(PendingNode {
                            name: assert_name,
                            node: crate::nodes::assertions::assert_value_node(
                                expected_type,
                                constraint,
                            ),
                            inputs: vec![],
                        });

                        // Replace the just-pushed source with the
                        // assertion's output.
                        *node_wiring.last_mut().unwrap() =
                            WireSource::NodeOutput(assert_idx, 0);
                    } else if let Some(ref mut log) = log {
                        let from_name = match wire_ref {
                            WireRef::Input(n) => n.clone(),
                            WireRef::Node(n, _) => n.clone(),
                        };
                        log.push(crate::dsl::events::CompileEvent::AssertionSkipped {
                            from_node: from_name,
                            to_node: all_nodes[node_idx].name.clone(),
                            reason: assertion_skip_reason(
                                strict_values,
                                &all_nodes,
                                &last_source,
                                &constraint,
                            ),
                        });
                    }
                } else if strict_types && source_type != expected_type {
                    // Type mismatch was already adapted above; the
                    // post-adapter wire is statically the right
                    // type. No assertion needed. Tracking the skip
                    // here is forward-compatible โ€” once dynamic
                    // type cases (JSON nav, Ext unwraps) appear,
                    // this is where the AssertType insertion would
                    // hook in.
                }
            }

            while resolved_wiring.len() <= node_idx {
                resolved_wiring.push(Vec::new());
            }
            resolved_wiring[node_idx] = node_wiring;
        }

        while resolved_wiring.len() < all_nodes.len() {
            resolved_wiring.push(Vec::new());
        }

        // --- Node fusion optimization ---
        //
        // Recognize fusible subgraph patterns and replace them with
        // semantically equivalent fused nodes. See SRD 36.
        {
            let rules = crate::fusion::default_rules();
            if !rules.is_empty() {
                // Collect node indices that are directly referenced by outputs.
                // These nodes must not be consumed as interior nodes by fusion.
                let mut output_nodes: Vec<usize> = Vec::new();
                for wire_ref in self.outputs.values() {
                    if let WireRef::Node(node_name, _) = wire_ref
                        && let Some(&idx) = all_name_to_idx.get(node_name) {
                            output_nodes.push(idx);
                        }
                }

                // Convert to Option<Box<dyn GkNode>> for the fusion pass.
                let mut opt_nodes: Vec<Option<Box<dyn GkNode>>> = all_nodes
                    .into_iter()
                    .map(|pn| Some(pn.node))
                    .collect();

                let fused_count = crate::fusion::apply_fusions(
                    &mut opt_nodes,
                    &mut resolved_wiring,
                    &mut all_name_to_idx,
                    &rules,
                    &output_nodes,
                );
                if fused_count > 0
                    && let Some(ref mut log) = log {
                        log.push(crate::dsl::events::CompileEvent::FusionApplied {
                            pattern: "subgraph".into(),
                            nodes_replaced: fused_count,
                        });
                    }

                // Convert back, rebuilding PendingNode wrappers.
                // Fused-away nodes (None) get placeholder names.
                all_nodes = opt_nodes
                    .into_iter()
                    .enumerate()
                    .map(|(i, opt)| PendingNode {
                        name: all_name_to_idx
                            .iter()
                            .find(|&(_, &idx)| idx == i)
                            .map(|(n, _)| n.clone())
                            .unwrap_or_else(|| format!("__removed_{i}")),
                        node: opt.unwrap_or_else(|| Box::new(crate::nodes::identity::Identity::new())),
                        inputs: vec![], // wiring is in resolved_wiring
                    })
                    .collect();
            }
        }

        // --- Dead code elimination ---
        //
        // Trace backward from output nodes to find all reachable nodes.
        // Only reachable nodes participate in the topological sort and
        // end up in the final kernel. This prunes unused binding chains
        // when the caller requests a subset of outputs.
        let node_count = all_nodes.len();
        let mut reachable = vec![false; node_count];
        {
            let mut worklist: Vec<usize> = Vec::new();
            // Seed with output nodes
            for wire_ref in self.outputs.values() {
                if let WireRef::Node(node_name, _) = wire_ref
                    && let Some(&idx) = all_name_to_idx.get(node_name) {
                        worklist.push(idx);
                    }
            }
            // Side-effecting nodes are pinned alive regardless
            // of reachability from a declared output. `log_info`
            // and friends emit one audit-log line per eval as a
            // deliberate side effect โ€” DCE-pruning them would
            // silently drop diagnostic logging the operator
            // explicitly asked for. The set is closed and
            // matched by node-meta name so the marker survives
            // any wiring shape (passthrough, captured-but-unused,
            // synthesised wrapper, etc.).
            for (idx, pn) in all_nodes.iter().enumerate() {
                if matches!(pn.node.meta().name.as_str(),
                    "log_debug" | "log_info" | "log_warn" | "log_error")
                {
                    worklist.push(idx);
                }
            }
            // Walk backward through wiring
            while let Some(idx) = worklist.pop() {
                if reachable[idx] { continue; }
                reachable[idx] = true;
                for source in &resolved_wiring[idx] {
                    if let WireSource::NodeOutput(upstream, _) = source
                        && !reachable[*upstream] {
                            worklist.push(*upstream);
                        }
                }
            }
        }
        let live_count = reachable.iter().filter(|&&r| r).count();

        // Topological sort (Kahn's algorithm) over reachable nodes only
        let mut in_degree = vec![0usize; node_count];
        let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); node_count];

        for (node_idx, wiring) in resolved_wiring.iter().enumerate() {
            if !reachable[node_idx] { continue; }
            for source in wiring {
                if let WireSource::NodeOutput(upstream, _) = source {
                    in_degree[node_idx] += 1;
                    dependents[*upstream].push(node_idx);
                }
            }
        }

        let mut queue: Vec<usize> = (0..node_count)
            .filter(|i| reachable[*i] && in_degree[*i] == 0)
            .collect();
        let mut sorted_order: Vec<usize> = Vec::with_capacity(live_count);

        while let Some(idx) = queue.pop() {
            sorted_order.push(idx);
            for &dep in &dependents[idx] {
                in_degree[dep] -= 1;
                if in_degree[dep] == 0 {
                    queue.push(dep);
                }
            }
        }

        if sorted_order.len() != live_count {
            return Err(AssemblyError::CycleDetected);
        }

        let mut old_to_new = vec![0usize; node_count];
        for (new_idx, &old_idx) in sorted_order.iter().enumerate() {
            old_to_new[old_idx] = new_idx;
        }

        let mut sorted_nodes: Vec<Option<Box<dyn GkNode>>> = all_nodes
            .into_iter()
            .map(|pn| Some(pn.node))
            .collect();

        let final_nodes: Vec<Box<dyn GkNode>> = sorted_order
            .iter()
            .map(|&old_idx| sorted_nodes[old_idx].take().unwrap())
            .collect();

        let final_wiring: Vec<Vec<WireSource>> = sorted_order
            .iter()
            .map(|&old_idx| {
                resolved_wiring[old_idx]
                    .iter()
                    .map(|source| match source {
                        WireSource::Input(c) => WireSource::Input(*c),
                        WireSource::NodeOutput(old_up, port) => {
                            WireSource::NodeOutput(old_to_new[*old_up], *port)
                        }
                    })
                    .collect()
            })
            .collect();

        let mut final_output_map: HashMap<String, (usize, usize)> = HashMap::new();
        for (name, wire_ref) in &self.outputs {
            match wire_ref {
                WireRef::Input(coord_name) => {
                    return Err(AssemblyError::UnknownWire(format!(
                        "output '{name}' references coordinate '{coord_name}' directly; \
                         wire through a node instead"
                    )));
                }
                WireRef::Node(node_name, port) => {
                    let old_idx = all_name_to_idx
                        .get(node_name)
                        .ok_or_else(|| AssemblyError::UnknownWire(node_name.clone()))?;
                    final_output_map.insert(name.clone(), (old_to_new[*old_idx], *port));
                }
            }
        }

        Ok(ResolvedDag {
            nodes: final_nodes,
            wiring: final_wiring,
            input_defs: self.input_defs,
            coord_count: self.coord_count,
            output_map: final_output_map,
            output_order: self.output_order,
            source: self.source,
            context: self.context,
            output_modifiers: self.output_modifiers,
            const_outputs: self.const_outputs,
        })
    }
}

/// Decide whether the source feeding `wire_source` already
/// guarantees the sink's value `constraint` at compile time.
/// Returns `true` if the assertion can be safely skipped.
///
/// Today we recognise two skip cases (SRD 15 ยง"Strict Wire Mode"):
///
/// 1. **Constant source.** The source node has no wire inputs and
///    its name matches the convention used by `fixed::ConstU64`
///    et al. Const sources have already been validated against
///    their `ParamSpec.constraint` at the factory layer, so any
///    further runtime check would be redundant.
/// 2. **Upstream assertion.** The source is itself an
///    `AssertValue` node (its name starts with `__assert_v_`),
///    which already enforces the same or stronger contract.
fn value_constraint_proven(
    all_nodes: &[PendingNode],
    src: &WireSource,
    _constraint: &crate::dsl::const_constraints::ConstConstraint,
) -> bool {
    match src {
        WireSource::Input(_) => false,
        WireSource::NodeOutput(idx, _) => {
            let meta = all_nodes[*idx].node.meta();
            // Const-source heuristic: a node with no wire inputs
            // is a constant. Today's `ConstU64` / `ConstF64` /
            // `ConstBool` (in `nodes::fixed`) and the synthesised
            // `ConstNode` from compile-time folding both qualify.
            let no_wire_inputs = meta.wire_inputs().is_empty();
            if no_wire_inputs {
                return true;
            }
            // Upstream assertion: skip stacking the same guard.
            // Conservative โ€” any `__assert_v_*` upstream counts as
            // proof. A fancier analysis would compare constraint
            // shapes; for now, idempotency is good enough.
            if meta.name.starts_with("__assert_v_")
                || meta.name.starts_with("assert_")
            {
                return true;
            }
            false
        }
    }
}

/// Format the reason a strict-wire assertion was skipped, for the
/// `AssertionSkipped` advisory event. Mirrors the bullets in SRD 15
/// ยง"Strict Wire Mode" so the log is grep-able.
fn assertion_skip_reason(
    strict_values: bool,
    all_nodes: &[PendingNode],
    src: &WireSource,
    _constraint: &crate::dsl::const_constraints::ConstConstraint,
) -> String {
    if !strict_values {
        return "strict_values not enabled".into();
    }
    match src {
        WireSource::Input(_) => "raw input wire".into(),
        WireSource::NodeOutput(idx, _) => {
            let meta = all_nodes[*idx].node.meta();
            if meta.wire_inputs().is_empty() {
                "constant source already validated".into()
            } else if meta.name.starts_with("__assert_v_")
                || meta.name.starts_with("assert_")
            {
                "upstream assertion".into()
            } else {
                "no skip rule matched".into()
            }
        }
    }
}

/// Return an auto-insert edge adapter for common coercions, if one exists.
fn auto_adapter(from: PortType, to: PortType) -> Option<Box<dyn GkNode>> {
    use crate::nodes::convert::{
        BoolToStr, BoolToU64,
        U32ToU64, U32ToF64, U32ToString,
        I32ToI64, I32ToF64, I32ToString,
        I64ToF64, I64ToString,
        F32ToF64, F32ToString,
    };
    match (from, to) {
        // Widening: safe, no precision loss
        (PortType::U64, PortType::F64) => Some(Box::new(U64ToF64::new())),
        // Widening: unsigned integers
        (PortType::U32, PortType::U64) => Some(Box::new(U32ToU64::new())),
        (PortType::U32, PortType::F64) => Some(Box::new(U32ToF64::new())),
        // Widening: signed integers
        (PortType::I32, PortType::I64) => Some(Box::new(I32ToI64::new())),
        (PortType::I32, PortType::F64) => Some(Box::new(I32ToF64::new())),
        (PortType::I64, PortType::F64) => Some(Box::new(I64ToF64::new())),
        // Widening: floats
        (PortType::F32, PortType::F64) => Some(Box::new(F32ToF64::new())),
        // To-string: all types render as strings
        (PortType::U64, PortType::Str) => Some(Box::new(U64ToString::new())),
        (PortType::F64, PortType::Str) => Some(Box::new(F64ToString::new())),
        (PortType::Bool, PortType::Str) => Some(Box::new(BoolToStr::new())),
        (PortType::Json, PortType::Str) => Some(Box::new(JsonToStr::new())),
        (PortType::U32, PortType::Str) => Some(Box::new(U32ToString::new())),
        (PortType::I32, PortType::Str) => Some(Box::new(I32ToString::new())),
        (PortType::I64, PortType::Str) => Some(Box::new(I64ToString::new())),
        (PortType::F32, PortType::Str) => Some(Box::new(F32ToString::new())),
        // Bool to numeric
        (PortType::Bool, PortType::U64) => Some(Box::new(BoolToU64::new())),
        _ => None,
    }
}