active-infinity 1.1.2

Active Infinity (Active ∞) — binary, zero-copy, content-addressable, graph-native, unit-aware and secret-safe data language for Active modules and AI agents
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
1381
1382
1383
1384
1385
1386
1387
1388
1389
//! Active Infinity's in-memory module model.
//!
//! This is the *canonical* IR: the encoder is a pure function of it, and the
//! decoder reproduces it exactly. It deliberately does **not** mirror the
//! `active-core` arena layout: the wire format is versioned independently of
//! any dependency's semver (see ADR-0002). Interop with the text language IR
//! lives in [`crate::interop`] behind the `active-core` feature.
//!
//! Structural invariants upheld by [`InfinityModule::validate_structure`]:
//!
//! - every referenced node id exists (no dangling references);
//! - table fields, binding names and array nodes are unique where required;
//! - the dependency graph is acyclic (Active rejects cycles before any value
//!   exists);
//! - nesting depth stays within the caller's budget.
//!
//! Secret material is held in [`SecretBytes`], which has **no** `Display`,
//! `Debug`, `Serialize` or equality path that can reveal it.

// The variant and field names in this module are the wire contract itself and
// are documented normatively in `docs/spec/layout.md`; per-variant rustdoc would
// duplicate that table without adding information.
#![allow(missing_docs)]

use std::collections::HashMap;
use std::fmt;

/// Index into the module arena.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(pub u32);

impl NodeId {
    /// Sentinel for "no node".
    pub const NONE: NodeId = NodeId(u32::MAX);

    pub fn index(self) -> usize {
        self.0 as usize
    }

    pub fn is_none(self) -> bool {
        self == NodeId::NONE
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "n{}", self.0)
    }
}

/// A secret string held structurally.
///
/// The type exposes no way to read the bytes back through a public API: the
/// wire codec and the `active-core` bridge are the only in-crate readers, and
/// both are audited. `Debug`, `Display`, `PartialEq`, `Ord` and `Hash` are all
/// deliberately absent or redacting, so a secret can never leak through
/// logging, assertion output, sorting or map keys, and can never be compared
/// for equality (the anti-oracle rule).
#[derive(Clone)]
pub struct SecretBytes(Vec<u8>);

impl SecretBytes {
    /// Wrap raw bytes as a secret.
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        SecretBytes(bytes.into())
    }

    /// Number of bytes — length is not secret material and is used by
    /// budgets and diagnostics.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Read the raw bytes. Crate-internal: only the audited codec and the
    /// `active-core` bridge call this. There is no public unlock API.
    pub(crate) fn expose(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Debug for SecretBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Secret(***)")
    }
}

impl fmt::Display for SecretBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("***SECRET***")
    }
}

impl PartialEq for SecretBytes {
    /// Anti-oracle: a secret never equals anything, including itself.
    fn eq(&self, _other: &Self) -> bool {
        false
    }
}

impl From<&str> for SecretBytes {
    fn from(value: &str) -> Self {
        SecretBytes(value.as_bytes().to_vec())
    }
}

impl From<String> for SecretBytes {
    fn from(value: String) -> Self {
        SecretBytes(value.into_bytes())
    }
}

/// Binary operators, with permanent wire codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    And,
    Or,
}

impl BinOp {
    pub const fn code(self) -> u32 {
        match self {
            BinOp::Add => 0,
            BinOp::Sub => 1,
            BinOp::Mul => 2,
            BinOp::Div => 3,
            BinOp::Eq => 4,
            BinOp::Ne => 5,
            BinOp::Lt => 6,
            BinOp::Le => 7,
            BinOp::Gt => 8,
            BinOp::Ge => 9,
            BinOp::And => 10,
            BinOp::Or => 11,
        }
    }

    pub const fn from_code(code: u32) -> Option<Self> {
        let op = match code {
            0 => BinOp::Add,
            1 => BinOp::Sub,
            2 => BinOp::Mul,
            3 => BinOp::Div,
            4 => BinOp::Eq,
            5 => BinOp::Ne,
            6 => BinOp::Lt,
            7 => BinOp::Le,
            8 => BinOp::Gt,
            9 => BinOp::Ge,
            10 => BinOp::And,
            11 => BinOp::Or,
            _ => return None,
        };
        Some(op)
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            BinOp::Add => "+",
            BinOp::Sub => "-",
            BinOp::Mul => "*",
            BinOp::Div => "/",
            BinOp::Eq => "==",
            BinOp::Ne => "!=",
            BinOp::Lt => "<",
            BinOp::Le => "<=",
            BinOp::Gt => ">",
            BinOp::Ge => ">=",
            BinOp::And => "and",
            BinOp::Or => "or",
        }
    }
}

/// Unary operators, with permanent wire codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnOp {
    Neg,
    Not,
}

impl UnOp {
    pub const fn code(self) -> u32 {
        match self {
            UnOp::Neg => 0,
            UnOp::Not => 1,
        }
    }

    pub const fn from_code(code: u32) -> Option<Self> {
        match code {
            0 => Some(UnOp::Neg),
            1 => Some(UnOp::Not),
            _ => None,
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            UnOp::Neg => "-",
            UnOp::Not => "!",
        }
    }
}

/// Semantic tag for a multi-line string block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SemanticTag {
    Prompt,
    Policy,
    Template,
}

impl SemanticTag {
    pub const fn code(self) -> u32 {
        match self {
            SemanticTag::Prompt => 0,
            SemanticTag::Policy => 1,
            SemanticTag::Template => 2,
        }
    }

    pub const fn from_code(code: u32) -> Option<Self> {
        match code {
            0 => Some(SemanticTag::Prompt),
            1 => Some(SemanticTag::Policy),
            2 => Some(SemanticTag::Template),
            _ => None,
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            SemanticTag::Prompt => "prompt",
            SemanticTag::Policy => "policy",
            SemanticTag::Template => "template",
        }
    }
}

/// One interpolation part.
#[derive(Debug, Clone, PartialEq)]
pub enum InterpPart {
    Literal(String),
    Expr(NodeId),
}

/// A runtime constraint attached to a node (`@constraint` predicates and
/// schema bounds).
#[derive(Debug, Clone, PartialEq)]
pub enum Constraint {
    MinMax { min: Option<i64>, max: Option<i64> },
    Enum(Vec<String>),
    Pattern(String),
    Odd,
    Custom(String),
}

/// Declared value type of a schema field.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeSpec {
    Null,
    Bool,
    Int,
    Float,
    String,
    Duration,
    Bytes,
    Table { closed: bool },
    Enum(Vec<String>),
    Secret,
    Any,
    Blob,
}

impl TypeSpec {
    pub const fn code(&self) -> u32 {
        match self {
            TypeSpec::Null => 0,
            TypeSpec::Bool => 1,
            TypeSpec::Int => 2,
            TypeSpec::Float => 3,
            TypeSpec::String => 4,
            TypeSpec::Duration => 5,
            TypeSpec::Bytes => 6,
            TypeSpec::Table { .. } => 7,
            TypeSpec::Enum(_) => 8,
            TypeSpec::Secret => 9,
            TypeSpec::Any => 10,
            TypeSpec::Blob => 11,
        }
    }

    /// Human-readable name for diagnostics (mirrors `active-core`).
    pub fn name(&self) -> String {
        match self {
            TypeSpec::Null => "Null".into(),
            TypeSpec::Bool => "Bool".into(),
            TypeSpec::Int => "Int".into(),
            TypeSpec::Float => "Float".into(),
            TypeSpec::String => "String".into(),
            TypeSpec::Duration => "Duration".into(),
            TypeSpec::Bytes => "Bytes".into(),
            TypeSpec::Table { closed } => {
                if *closed {
                    "Table(closed)".into()
                } else {
                    "Table".into()
                }
            }
            TypeSpec::Enum(values) => format!("Enum({})", values.join(", ")),
            TypeSpec::Secret => "Secret".into(),
            TypeSpec::Any => "Any".into(),
            TypeSpec::Blob => "Blob".into(),
        }
    }
}

/// A structural patch operation.
#[derive(Debug, Clone, PartialEq)]
pub enum PatchOp {
    Set { path: String, value: NodeId },
    Remove { path: String },
    Rename { from: String, to: String },
}

/// One schema field's constraints.
#[derive(Debug, Clone, PartialEq)]
pub struct SchemaFieldSpec {
    pub typ: TypeSpec,
    pub min: Option<NodeId>,
    pub max: Option<NodeId>,
    pub min_len: Option<NodeId>,
    pub max_len: Option<NodeId>,
    pub pattern: Option<NodeId>,
    pub default: Option<NodeId>,
    pub deprecated: Option<String>,
}

impl SchemaFieldSpec {
    pub fn bare(typ: TypeSpec) -> Self {
        Self {
            typ,
            min: None,
            max: None,
            min_len: None,
            max_len: None,
            pattern: None,
            default: None,
            deprecated: None,
        }
    }
}

/// A module node.
///
/// Every variant is a value of the Active IR after name resolution; `Ident`
/// is retained only because decoded third-party modules may still contain
/// one (the encoder never emits it for canonical modules produced from
/// `active-core`).
///
/// `Debug` is written by hand (never derived): blob payloads are summarized
/// by identity and secrets render as `Secret(***)`, so logging a module can
/// never dump payload or secret bytes.
#[derive(Clone, PartialEq)]
pub enum Inode {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(String),
    DurationMs(u64),
    Quantity {
        value: NodeId,
        unit: super::UnitTag,
    },
    Array {
        elements: Vec<NodeId>,
    },
    Table {
        fields: Vec<(String, NodeId)>,
    },
    /// A structural secret literal. Never equals anything.
    Secret(SecretBytes),
    /// A secret derived from a locator node (`secret.env(NAME)`,
    /// `secret(<expr>)`).
    SecretRef {
        locator: NodeId,
    },
    Ref(NodeId),
    Env {
        name: String,
        default: Option<NodeId>,
    },
    Ident(String),
    Interpolate {
        parts: Vec<InterpPart>,
    },
    Binary {
        op: BinOp,
        lhs: NodeId,
        rhs: NodeId,
    },
    Unary {
        op: UnOp,
        expr: NodeId,
    },
    Constrained {
        target: NodeId,
        constraint: Constraint,
    },
    Patch(PatchOp),
    SchemaField(SchemaFieldSpec),
    SchemaTable {
        fields: Vec<(String, NodeId)>,
        closed: bool,
    },
    SchemaArray {
        element: NodeId,
    },
    Semantic {
        tag: SemanticTag,
        inner: NodeId,
    },
    /// `blob(media_type, data)` construction site (reserved kind 24).
    ContentAddressed {
        media_type: NodeId,
        data: NodeId,
    },
    /// A materialised content-addressed blob identity.
    ///
    /// `payload` is present only for untainted blobs that were materialised;
    /// a tainted blob never carries bytes, and the codec refuses a tainted
    /// blob entry whose payload is non-empty.
    Blob {
        hash: [u8; 32],
        size: u64,
        tainted: bool,
        media_type: String,
        payload: Option<Vec<u8>>,
    },
}

impl fmt::Debug for Inode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Inode::Null => f.write_str("Null"),
            Inode::Bool(value) => write!(f, "Bool({value})"),
            Inode::Int(value) => write!(f, "Int({value})"),
            Inode::Float(value) => write!(f, "Float({value})"),
            Inode::Str(value) => write!(f, "Str({value:?})"),
            Inode::DurationMs(ms) => write!(f, "DurationMs({ms})"),
            Inode::Quantity { value, unit } => write!(f, "Quantity({value}, {unit})"),
            Inode::Array { elements } => write!(f, "Array({elements:?})"),
            Inode::Table { fields } => write!(f, "Table({fields:?})"),
            Inode::Secret(_) => f.write_str("Secret(***)"),
            Inode::SecretRef { locator } => write!(f, "SecretRef({locator})"),
            Inode::Ref(id) => write!(f, "Ref({id})"),
            Inode::Env { name, default } => write!(f, "Env({name:?}, {default:?})"),
            Inode::Ident(name) => write!(f, "Ident({name:?})"),
            Inode::Interpolate { parts } => write!(f, "Interpolate({parts:?})"),
            Inode::Binary { op, lhs, rhs } => write!(f, "Binary({}, {lhs}, {rhs})", op.as_str()),
            Inode::Unary { op, expr } => write!(f, "Unary({}, {expr})", op.as_str()),
            Inode::Constrained { target, constraint } => {
                write!(f, "Constrained({target}, {constraint:?})")
            }
            Inode::Patch(op) => write!(f, "Patch({op:?})"),
            Inode::SchemaField(spec) => write!(f, "SchemaField({spec:?})"),
            Inode::SchemaTable { fields, closed } => {
                write!(f, "SchemaTable({fields:?}, closed={closed})")
            }
            Inode::SchemaArray { element } => write!(f, "SchemaArray({element})"),
            Inode::Semantic { tag, inner } => write!(f, "Semantic({}, {inner})", tag.as_str()),
            Inode::ContentAddressed { media_type, data } => {
                write!(f, "ContentAddressed({media_type}, {data})")
            }
            Inode::Blob {
                hash,
                size,
                tainted,
                media_type,
                payload,
            } => write!(
                f,
                "Blob(blake3:{}, size={size}, media={media_type:?}, tainted={tainted}, payload={})",
                hash_hex(hash),
                match payload {
                    Some(bytes) => format!("{} bytes", bytes.len()),
                    None => "absent".to_string(),
                }
            ),
        }
    }
}

/// Lowercase hex of a 32-byte digest.
pub fn hash_hex(hash: &[u8; 32]) -> String {
    let mut out = String::with_capacity(64);
    for byte in hash {
        out.push_str(&format!("{byte:02x}"));
    }
    out
}

/// Parse a 64-character hex digest.
pub fn parse_hash_hex(text: &str) -> Option<[u8; 32]> {
    if text.len() != 64 {
        return None;
    }
    let mut out = [0u8; 32];
    for (index, pair) in text.as_bytes().chunks_exact(2).enumerate() {
        let hi = (pair[0] as char).to_digit(16)?;
        let lo = (pair[1] as char).to_digit(16)?;
        out[index] = (hi * 16 + lo) as u8;
    }
    Some(out)
}

/// Stable node-kind identity, usable without depending on wire ids.
///
/// Downstream tools (the RPC layer, projections, diagnostics) name kinds through
/// this enum; `code()` is the permanent wire discriminant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(missing_docs)]
pub enum SerializedKind {
    Null,
    Bool,
    Int,
    Float,
    Str,
    DurationMs,
    Quantity,
    Array,
    Table,
    Secret,
    SecretRef,
    Ref,
    Env,
    Ident,
    Interpolate,
    Binary,
    Unary,
    Constrained,
    Patch,
    SchemaField,
    SchemaTable,
    SchemaArray,
    Semantic,
    Blob,
    ContentAddressed,
}

impl SerializedKind {
    pub const fn code(self) -> u8 {
        match self {
            SerializedKind::Null => 0,
            SerializedKind::Bool => 1,
            SerializedKind::Int => 2,
            SerializedKind::Float => 3,
            SerializedKind::Str => 4,
            SerializedKind::DurationMs => 5,
            SerializedKind::Quantity => 6,
            SerializedKind::Array => 7,
            SerializedKind::Table => 8,
            SerializedKind::Secret => 9,
            SerializedKind::SecretRef => 10,
            SerializedKind::Ref => 11,
            SerializedKind::Env => 12,
            SerializedKind::Ident => 13,
            SerializedKind::Interpolate => 14,
            SerializedKind::Binary => 15,
            SerializedKind::Unary => 16,
            SerializedKind::Constrained => 17,
            SerializedKind::Patch => 18,
            SerializedKind::SchemaField => 19,
            SerializedKind::SchemaTable => 20,
            SerializedKind::SchemaArray => 21,
            SerializedKind::Semantic => 22,
            SerializedKind::Blob => 23,
            SerializedKind::ContentAddressed => 24,
        }
    }

    pub const fn from_code(code: u8) -> Option<Self> {
        let kind = match code {
            0 => SerializedKind::Null,
            1 => SerializedKind::Bool,
            2 => SerializedKind::Int,
            3 => SerializedKind::Float,
            4 => SerializedKind::Str,
            5 => SerializedKind::DurationMs,
            6 => SerializedKind::Quantity,
            7 => SerializedKind::Array,
            8 => SerializedKind::Table,
            9 => SerializedKind::Secret,
            10 => SerializedKind::SecretRef,
            11 => SerializedKind::Ref,
            12 => SerializedKind::Env,
            13 => SerializedKind::Ident,
            14 => SerializedKind::Interpolate,
            15 => SerializedKind::Binary,
            16 => SerializedKind::Unary,
            17 => SerializedKind::Constrained,
            18 => SerializedKind::Patch,
            19 => SerializedKind::SchemaField,
            20 => SerializedKind::SchemaTable,
            21 => SerializedKind::SchemaArray,
            22 => SerializedKind::Semantic,
            23 => SerializedKind::Blob,
            24 => SerializedKind::ContentAddressed,
            _ => return None,
        };
        Some(kind)
    }

    pub const fn name(self) -> &'static str {
        crate::view::node_kind_name(self.code())
    }
}

impl Inode {
    /// Stable kind identity of this node.
    pub const fn kind(&self) -> SerializedKind {
        match self {
            Inode::Null => SerializedKind::Null,
            Inode::Bool(_) => SerializedKind::Bool,
            Inode::Int(_) => SerializedKind::Int,
            Inode::Float(_) => SerializedKind::Float,
            Inode::Str(_) => SerializedKind::Str,
            Inode::DurationMs(_) => SerializedKind::DurationMs,
            Inode::Quantity { .. } => SerializedKind::Quantity,
            Inode::Array { .. } => SerializedKind::Array,
            Inode::Table { .. } => SerializedKind::Table,
            Inode::Secret(_) => SerializedKind::Secret,
            Inode::SecretRef { .. } => SerializedKind::SecretRef,
            Inode::Ref(_) => SerializedKind::Ref,
            Inode::Env { .. } => SerializedKind::Env,
            Inode::Ident(_) => SerializedKind::Ident,
            Inode::Interpolate { .. } => SerializedKind::Interpolate,
            Inode::Binary { .. } => SerializedKind::Binary,
            Inode::Unary { .. } => SerializedKind::Unary,
            Inode::Constrained { .. } => SerializedKind::Constrained,
            Inode::Patch(_) => SerializedKind::Patch,
            Inode::SchemaField(_) => SerializedKind::SchemaField,
            Inode::SchemaTable { .. } => SerializedKind::SchemaTable,
            Inode::SchemaArray { .. } => SerializedKind::SchemaArray,
            Inode::Semantic { .. } => SerializedKind::Semantic,
            Inode::Blob { .. } => SerializedKind::Blob,
            Inode::ContentAddressed { .. } => SerializedKind::ContentAddressed,
        }
    }
}

impl Inode {
    /// Stable kind discriminant (wire contract, `docs/spec/layout.md` §5.1).
    pub const fn kind_code(&self) -> u8 {
        match self {
            Inode::Null => 0,
            Inode::Bool(_) => 1,
            Inode::Int(_) => 2,
            Inode::Float(_) => 3,
            Inode::Str(_) => 4,
            Inode::DurationMs(_) => 5,
            Inode::Quantity { .. } => 6,
            Inode::Array { .. } => 7,
            Inode::Table { .. } => 8,
            Inode::Secret(_) => 9,
            Inode::SecretRef { .. } => 10,
            Inode::Ref(_) => 11,
            Inode::Env { .. } => 12,
            Inode::Ident(_) => 13,
            Inode::Interpolate { .. } => 14,
            Inode::Binary { .. } => 15,
            Inode::Unary { .. } => 16,
            Inode::Constrained { .. } => 17,
            Inode::Patch(_) => 18,
            Inode::SchemaField(_) => 19,
            Inode::SchemaTable { .. } => 20,
            Inode::SchemaArray { .. } => 21,
            Inode::Semantic { .. } => 22,
            Inode::Blob { .. } => 23,
            Inode::ContentAddressed { .. } => 24,
        }
    }

    /// Whether this node carries secret material or a secret locator.
    pub const fn is_secret(&self) -> bool {
        matches!(self, Inode::Secret(_) | Inode::SecretRef { .. })
    }

    /// Node references in canonical child order.
    ///
    /// This is the single source of truth for the dependency edges, the
    /// canonical numbering traversal, cycle detection and graph queries. It
    /// must list *every* node reference the variant holds.
    pub fn children(&self) -> Vec<NodeId> {
        match self {
            Inode::Quantity { value, .. } => vec![*value],
            Inode::Array { elements } => elements.clone(),
            Inode::Table { fields } => fields.iter().map(|(_, id)| *id).collect(),
            Inode::SecretRef { locator } => vec![*locator],
            Inode::Ref(id) => vec![*id],
            Inode::Env { default, .. } => default.iter().copied().collect(),
            Inode::Interpolate { parts } => parts
                .iter()
                .filter_map(|part| match part {
                    InterpPart::Expr(id) => Some(*id),
                    InterpPart::Literal(_) => None,
                })
                .collect(),
            Inode::Binary { lhs, rhs, .. } => vec![*lhs, *rhs],
            Inode::Unary { expr, .. } => vec![*expr],
            Inode::Constrained { target, .. } => vec![*target],
            Inode::Patch(op) => match op {
                PatchOp::Set { value, .. } => vec![*value],
                PatchOp::Remove { .. } | PatchOp::Rename { .. } => Vec::new(),
            },
            Inode::SchemaField(spec) => {
                let mut out = Vec::new();
                for id in [
                    spec.min,
                    spec.max,
                    spec.min_len,
                    spec.max_len,
                    spec.pattern,
                    spec.default,
                ]
                .into_iter()
                .flatten()
                {
                    out.push(id);
                }
                out
            }
            Inode::SchemaTable { fields, .. } => fields.iter().map(|(_, id)| *id).collect(),
            Inode::SchemaArray { element } => vec![*element],
            Inode::Semantic { inner, .. } => vec![*inner],
            Inode::ContentAddressed { media_type, data } => vec![*media_type, *data],
            Inode::Null
            | Inode::Bool(_)
            | Inode::Int(_)
            | Inode::Float(_)
            | Inode::Str(_)
            | Inode::DurationMs(_)
            | Inode::Secret(_)
            | Inode::Ident(_)
            | Inode::Blob { .. } => Vec::new(),
        }
    }

    /// Every string this node owns, for heap construction.
    pub fn strings(&self, out: &mut Vec<String>) {
        match self {
            Inode::Str(s) | Inode::Ident(s) => out.push(s.clone()),
            Inode::Table { fields } => {
                for (name, _) in fields {
                    out.push(name.clone());
                }
            }
            Inode::Env { name, .. } => out.push(name.clone()),
            Inode::Interpolate { parts } => {
                for part in parts {
                    if let InterpPart::Literal(s) = part {
                        out.push(s.clone());
                    }
                }
            }
            Inode::Constrained { constraint, .. } => match constraint {
                Constraint::Enum(items) => out.extend(items.iter().cloned()),
                Constraint::Pattern(s) | Constraint::Custom(s) => out.push(s.clone()),
                Constraint::MinMax { .. } | Constraint::Odd => {}
            },
            Inode::Patch(op) => match op {
                PatchOp::Set { path, .. } | PatchOp::Remove { path } => out.push(path.clone()),
                PatchOp::Rename { from, to } => {
                    out.push(from.clone());
                    out.push(to.clone());
                }
            },
            Inode::SchemaField(spec) => {
                if let TypeSpec::Enum(items) = &spec.typ {
                    out.extend(items.iter().cloned());
                }
                if let Some(deprecated) = &spec.deprecated {
                    out.push(deprecated.clone());
                }
            }
            Inode::SchemaTable { fields, .. } => {
                for (name, _) in fields {
                    out.push(name.clone());
                }
            }
            Inode::Blob { media_type, .. } => out.push(media_type.clone()),
            Inode::Null
            | Inode::Bool(_)
            | Inode::Int(_)
            | Inode::Float(_)
            | Inode::DurationMs(_)
            | Inode::Quantity { .. }
            | Inode::Array { .. }
            | Inode::Secret(_)
            | Inode::SecretRef { .. }
            | Inode::Ref(_)
            | Inode::Unary { .. }
            | Inode::Binary { .. }
            | Inode::SchemaArray { .. }
            | Inode::Semantic { .. }
            | Inode::ContentAddressed { .. } => {}
        }
    }
}

/// Annotation kinds (spec/annotations.md §2–§4).
#[derive(Debug, Clone, PartialEq)]
pub enum AnnotationKind {
    /// Documentation only, never enforced.
    Intent(String),
    /// A constraint predicate attached to a node.
    Constraint { source: String, expr: NodeId },
    /// Agent-immutable flag.
    AiImmutable(bool),
}

/// One annotation attached to a node.
#[derive(Debug, Clone, PartialEq)]
pub struct Annotation {
    pub node: NodeId,
    pub kind: AnnotationKind,
}

/// Kinds of provenance entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProvKind {
    Text,
    Int,
    Flag,
    Hash,
    /// Input module content hash (delta/derivation lineage).
    Input,
}

impl ProvKind {
    pub const fn code(self) -> u32 {
        match self {
            ProvKind::Text => 0,
            ProvKind::Int => 1,
            ProvKind::Flag => 2,
            ProvKind::Hash => 3,
            ProvKind::Input => 4,
        }
    }

    pub const fn from_code(code: u32) -> Option<Self> {
        match code {
            0 => Some(ProvKind::Text),
            1 => Some(ProvKind::Int),
            2 => Some(ProvKind::Flag),
            3 => Some(ProvKind::Hash),
            4 => Some(ProvKind::Input),
            _ => None,
        }
    }
}

/// A provenance value.
#[derive(Debug, Clone, PartialEq)]
pub enum ProvValue {
    Text(String),
    Int(i64),
    Flag(bool),
    Hash([u8; 32]),
}

/// One provenance entry: a typed key/value pair.
#[derive(Debug, Clone, PartialEq)]
pub struct ProvEntry {
    pub key: String,
    pub value: ProvValue,
}

impl ProvEntry {
    pub fn kind(&self) -> ProvKind {
        match self.value {
            ProvValue::Text(_) => ProvKind::Text,
            ProvValue::Int(_) => ProvKind::Int,
            ProvValue::Flag(_) => ProvKind::Flag,
            ProvValue::Hash(_) => ProvKind::Hash,
        }
    }
}

/// Module provenance: who produced this module, when, with what, from what.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Provenance {
    /// Producer identity (agent, tool, human, pipeline).
    pub producer: Option<String>,
    /// Unix epoch milliseconds; `0` means "unrecorded".
    pub timestamp_ms: u64,
    /// Model identity when an AI produced the module.
    pub model: Option<String>,
    /// Tool identity.
    pub tool: Option<String>,
    /// Content hash of the parent module this one derives from.
    pub parent: Option<[u8; 32]>,
    /// Free-form typed entries, sorted by key in canonical form.
    pub entries: Vec<ProvEntry>,
}

/// A canonical Active Infinity module.
///
/// The struct is an arena of [`Inode`] plus roots, bindings, annotations and
/// provenance. Edges are *derived* from node children, so a module can never
/// hold an edge table inconsistent with its nodes.
#[derive(Debug, Clone, Default)]
pub struct InfinityModule {
    nodes: Vec<Inode>,
    root: Option<NodeId>,
    bindings: Vec<(String, NodeId)>,
    annotations: Vec<Annotation>,
    provenance: Option<Provenance>,
}

impl PartialEq for InfinityModule {
    /// Canonical structural equality: two modules are equal when their
    /// canonical forms match, so arena order, table field order and blob
    /// numbering are irrelevant.
    ///
    /// Secret *contents* are never compared — only the fact that a secret is
    /// there — so equality can never become a guessing oracle, and a module
    /// holding a secret is equal to a structurally identical copy of itself.
    /// Use [`SecretBytes`] directly when you need the anti-oracle behaviour of
    /// two secret values.
    fn eq(&self, other: &Self) -> bool {
        self.structurally_eq(other)
    }
}

/// Compare two canonical nodes, blinding secret payloads.
fn node_eq(left: &Inode, right: &Inode) -> bool {
    match (left, right) {
        (Inode::Secret(_), Inode::Secret(_)) => true,
        (Inode::Secret(_), _) | (_, Inode::Secret(_)) => false,
        // Canonicalization normalizes floats; compare their bits so a NaN is
        // equal to itself.
        (Inode::Float(a), Inode::Float(b)) => a.to_bits() == b.to_bits(),
        _ => left == right,
    }
}

impl InfinityModule {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a node, returning its id.
    pub fn push(&mut self, node: Inode) -> NodeId {
        let id = NodeId(u32::try_from(self.nodes.len()).expect("arena exceeds u32 ids"));
        self.nodes.push(node);
        id
    }

    /// Alias for [`InfinityModule::push`], mirroring `Module::add_node`.
    pub fn add_node(&mut self, node: Inode) -> NodeId {
        self.push(node)
    }

    pub fn get(&self, id: NodeId) -> Option<&Inode> {
        self.nodes.get(id.index())
    }

    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut Inode> {
        self.nodes.get_mut(id.index())
    }

    pub fn node_mut(&mut self, id: NodeId) -> Result<&mut Inode, super::Error> {
        self.nodes
            .get_mut(id.index())
            .ok_or(super::Error::NodeRef(id.0))
    }

    pub fn nodes(&self) -> &[Inode] {
        &self.nodes
    }

    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    pub fn root(&self) -> Option<NodeId> {
        self.root
    }

    pub fn set_root(&mut self, root: Option<NodeId>) {
        self.root = root;
    }

    pub fn bindings(&self) -> &[(String, NodeId)] {
        &self.bindings
    }

    /// Bind a name to a node. Replaces an existing binding with the same name.
    pub fn bind(&mut self, name: impl Into<String>, id: NodeId) {
        let name = name.into();
        if let Some(slot) = self.bindings.iter_mut().find(|(n, _)| *n == name) {
            slot.1 = id;
        } else {
            self.bindings.push((name, id));
        }
    }

    pub fn annotations(&self) -> &[Annotation] {
        &self.annotations
    }

    pub fn annotate(&mut self, node: NodeId, kind: AnnotationKind) {
        self.annotations.push(Annotation { node, kind });
    }

    /// Drop every annotation.
    pub fn clear_annotations(&mut self) {
        self.annotations.clear();
    }

    /// Remove a binding by name; returns the old target when present.
    pub fn remove_binding(&mut self, name: &str) -> Option<NodeId> {
        let position = self.bindings.iter().position(|(key, _)| key == name)?;
        Some(self.bindings.remove(position).1)
    }

    pub fn provenance(&self) -> Option<&Provenance> {
        self.provenance.as_ref()
    }

    /// True when the module holds a structural secret literal.
    pub fn has_secret(&self) -> bool {
        self.nodes
            .iter()
            .any(|node| matches!(node, Inode::Secret(_)))
    }

    /// Canonical structural equality, blinding secret payloads.
    ///
    /// This is what [`PartialEq`] implements; it is also available by name for
    /// readers who want the intent spelled out.
    pub fn structurally_eq(&self, other: &Self) -> bool {
        let (Ok(left), Ok(right)) = (
            crate::canonical::prepare(self),
            crate::canonical::prepare(other),
        ) else {
            return false;
        };
        left.root == right.root
            && left.bindings == right.bindings
            && left.annotations == right.annotations
            && left.provenance == right.provenance
            && left.strings == right.strings
            && left.units == right.units
            && left.blobs == right.blobs
            && left.hashes == right.hashes
            && left.numbers == right.numbers
            && left.secrets.len() == right.secrets.len()
            && left.types.len() == right.types.len()
            && left
                .types
                .iter()
                .zip(right.types.iter())
                .all(|(a, b)| a.spec == b.spec && a.aux == b.aux)
            && left.nodes.len() == right.nodes.len()
            && left
                .nodes
                .iter()
                .zip(right.nodes.iter())
                .all(|(a, b)| node_eq(a, b))
    }

    pub fn set_provenance(&mut self, provenance: Option<Provenance>) {
        // Provenance is a map keyed by name: the last value for a key wins, so
        // the stored form can never contain the duplicate keys that validation
        // (correctly) rejects. Entries stay sorted for canonical equality.
        self.provenance = provenance.map(|prov| {
            let mut by_key: std::collections::BTreeMap<String, ProvValue> =
                std::collections::BTreeMap::new();
            for entry in prov.entries {
                by_key.insert(entry.key, entry.value);
            }
            let entries: Vec<ProvEntry> = by_key
                .into_iter()
                .map(|(key, value)| ProvEntry { key, value })
                .collect();
            Provenance { entries, ..prov }
        });
    }

    /// Roots used to define the reachable graph: the module root, every
    /// binding, every annotation subject, and provenance-only references.
    pub fn roots(&self) -> Vec<NodeId> {
        let mut roots = Vec::new();
        if let Some(root) = self.root {
            roots.push(root);
        }
        let mut bindings: Vec<&(String, NodeId)> = self.bindings.iter().collect();
        bindings.sort_by(|a, b| a.0.cmp(&b.0));
        roots.extend(bindings.into_iter().map(|(_, id)| *id));
        for annotation in &self.annotations {
            roots.push(annotation.node);
            if let AnnotationKind::Constraint { expr, .. } = &annotation.kind {
                roots.push(*expr);
            }
        }
        roots
    }

    /// Derived dependency edges, direction dependency → dependent, sorted and
    /// deduplicated. Nodes that reference where they are referenced from are
    /// normal; the graph is a DAG after [`Self::validate_structure`].
    pub fn edges(&self) -> Vec<(NodeId, NodeId)> {
        let mut edges = Vec::new();
        for (index, node) in self.nodes.iter().enumerate() {
            let dependent = NodeId(index as u32);
            for child in node.children() {
                edges.push((child, dependent));
            }
        }
        edges.sort_unstable();
        edges.dedup();
        edges
    }

    /// Reverse adjacency (dependent → dependencies).
    pub fn dependency_map(&self) -> HashMap<NodeId, Vec<NodeId>> {
        let mut map: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
        for (index, node) in self.nodes.iter().enumerate() {
            map.insert(NodeId(index as u32), node.children());
        }
        map
    }

    /// Check every structural invariant the wire format also enforces.
    ///
    /// `max_nodes` and `max_depth` bound the work so a hostile module cannot
    /// make this function hang or recurse without limit.
    pub fn validate_structure(&self, max_nodes: u64, max_depth: u32) -> Result<(), super::Error> {
        use super::Error;
        if self.nodes.len() as u64 > max_nodes {
            return Err(Error::Limit {
                kind: "nodes",
                limit: max_nodes,
            });
        }
        let count = self.nodes.len() as u32;
        let check = |id: NodeId| -> Result<(), Error> {
            if id.0 >= count {
                return Err(Error::NodeRef(id.0));
            }
            Ok(())
        };
        for (index, node) in self.nodes.iter().enumerate() {
            let id = NodeId(index as u32);
            for child in node.children() {
                check(child)?;
            }
            match node {
                Inode::Table { fields } | Inode::SchemaTable { fields, .. } => {
                    // O(k) duplicate detection: a 256-field table is common and
                    // the quadratic form dominated encoding time.
                    let mut seen = std::collections::HashSet::with_capacity(fields.len());
                    for (name, _) in fields {
                        if !seen.insert(name.as_str()) {
                            return Err(Error::DuplicateField { node: id.0 });
                        }
                    }
                }
                Inode::Float(value)
                    if value.is_nan() && !crate::canonical::is_canonical_nan(*value) =>
                {
                    return Err(Error::Node {
                        id: id.0,
                        reason: "non-canonical NaN",
                    });
                }
                Inode::Constrained { constraint, .. } => match constraint {
                    Constraint::MinMax {
                        min: Some(min),
                        max: Some(max),
                    } if min > max => {
                        return Err(Error::Node {
                            id: id.0,
                            reason: "constraint min exceeds max",
                        });
                    }
                    Constraint::Enum(items) if items.is_empty() => {
                        return Err(Error::Node {
                            id: id.0,
                            reason: "empty enum constraint",
                        });
                    }
                    _ => {}
                },
                _ => {}
            }
        }
        if let Some(root) = self.root {
            check(root)?;
        }
        let mut seen = std::collections::HashSet::new();
        for (name, id) in &self.bindings {
            check(*id)?;
            if !seen.insert(name.as_str()) {
                return Err(Error::DuplicateBinding);
            }
        }
        for annotation in &self.annotations {
            check(annotation.node)?;
            if let AnnotationKind::Constraint { expr, .. } = &annotation.kind {
                check(*expr)?;
            }
        }
        self.check_acyclic(count)?;
        self.check_depth(max_depth)?;
        Ok(())
    }

    /// Iterative cycle detection over the derived dependency graph.
    ///
    /// Explicit stack: a hostile 4M-node chain must not overflow the thread
    /// stack (`active-core` treats cycles as fatal, so this is a hard
    /// invariant, not a hint).
    pub fn check_acyclic(&self, count: u32) -> Result<(), super::Error> {
        use super::Error;
        // 0 = unvisited, 1 = on stack, 2 = done.
        let mut state = vec![0u8; count as usize];
        let mut stack: Vec<(u32, usize)> = Vec::new();
        for start in 0..count {
            if state[start as usize] != 0 {
                continue;
            }
            stack.push((start, 0));
            state[start as usize] = 1;
            while let Some((node, child_index)) = stack.pop() {
                let children = self.nodes[node as usize].children();
                if child_index < children.len() {
                    stack.push((node, child_index + 1));
                    let next = children[child_index].0;
                    match state[next as usize] {
                        0 => {
                            state[next as usize] = 1;
                            stack.push((next, 0));
                        }
                        1 => return Err(Error::Cycle { node: next }),
                        _ => {}
                    }
                } else {
                    state[node as usize] = 2;
                }
            }
        }
        Ok(())
    }

    /// Depth check over the derived dependency graph (iterative).
    pub fn check_depth(&self, max_depth: u32) -> Result<(), super::Error> {
        use super::Error;
        if max_depth == 0 {
            return Ok(());
        }
        let count = self.nodes.len();
        let mut depth = vec![0u32; count];
        let mut stack: Vec<(usize, usize)> = Vec::new();
        for start in 0..count {
            if depth[start] != 0 {
                continue;
            }
            stack.push((start, 0));
            depth[start] = 1;
            while let Some((node, child_index)) = stack.pop() {
                let children = self.nodes[node].children();
                if child_index < children.len() {
                    stack.push((node, child_index + 1));
                    let next = children[child_index].index();
                    let candidate = depth[node].saturating_add(1);
                    if candidate > max_depth {
                        return Err(Error::Depth { limit: max_depth });
                    }
                    if candidate > depth[next] {
                        depth[next] = candidate;
                        stack.push((next, 0));
                    }
                }
            }
        }
        Ok(())
    }

    /// Total string payload bytes (heap size before deduplication).
    pub fn string_bytes(&self) -> u64 {
        let mut strings = Vec::new();
        for node in &self.nodes {
            node.strings(&mut strings);
        }
        strings.iter().map(|s| s.len() as u64).sum()
    }

    /// Rebuild a module from decoded parts (used by the decoder and the
    /// stream reassembler).
    pub fn from_parts(
        nodes: Vec<Inode>,
        root: Option<NodeId>,
        bindings: Vec<(String, NodeId)>,
        mut annotations: Vec<Annotation>,
        provenance: Option<Provenance>,
    ) -> Self {
        annotations.sort_by(|a, b| {
            (a.node.0, annotation_order(&a.kind)).cmp(&(b.node.0, annotation_order(&b.kind)))
        });
        InfinityModule {
            nodes,
            root,
            bindings,
            annotations,
            provenance,
        }
    }
}

fn annotation_order(kind: &AnnotationKind) -> u32 {
    match kind {
        AnnotationKind::Intent(_) => 0,
        AnnotationKind::Constraint { .. } => 1,
        AnnotationKind::AiImmutable(_) => 2,
    }
}

/// Builder helpers that keep the node graph consistent while constructing a
/// module by hand or from another IR.
#[derive(Debug, Default)]
pub struct ModuleBuilder {
    module: InfinityModule,
}

impl ModuleBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn push(&mut self, node: Inode) -> NodeId {
        self.module.push(node)
    }

    pub fn root(&mut self, id: NodeId) -> &mut Self {
        self.module.set_root(Some(id));
        self
    }

    pub fn bind(&mut self, name: impl Into<String>, id: NodeId) -> &mut Self {
        self.module.bind(name, id);
        self
    }

    pub fn annotate(&mut self, node: NodeId, kind: AnnotationKind) -> &mut Self {
        self.module.annotate(node, kind);
        self
    }

    pub fn provenance(&mut self, provenance: Provenance) -> &mut Self {
        self.module.set_provenance(Some(provenance));
        self
    }

    pub fn build(self) -> InfinityModule {
        self.module
    }
}