wyrd-for-games 0.4.0

Engine-neutral signal-graph game logic for Wyrd
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
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
//! Bind: turn a validated [`Weave`] into a dense, executable [`Runtime`].
//!
//! Interns host paths and command names, builds CSR inbound edges, topo order,
//! kind-dispatch tags, delay rings, and sense seed lists so [`Runtime::loom`]
//! allocates no topology after bind. Host resolves `sense_id` / `path_id` once
//! at setup; the hot path uses only dense ids.

#![allow(clippy::result_large_err)] // Preserve contextual public BindError payloads.

use std::collections::BTreeMap;
use std::string::String;
use std::vec::Vec;

use core::sync::atomic::{AtomicUsize, Ordering};

use crate::authoring::{validate, Budget, Weave};
use crate::foundation::{
    port_slot, ports_of, CalcOp, HostTime, KnotId, KnotKind, PortDir, PortSlot, Seed, Signal, ZERO,
};

use crate::runtime_impl::error::{BindError, HandleError, RecipeEndpoint, RecipeResolveError};
use crate::runtime_impl::handles::{CmdId, HostPathId, KnotHandle, SenseId};
use crate::runtime_impl::outbox::{Emit, Outbox, PortWriter, SignalOutSample};

/// Bind-time sense seed entry — only Sense knots, so loom need not scan all knots.
#[derive(Clone, Copy, Debug)]
pub(crate) enum SenseSeed {
    Constant { kid: KnotId, value: Signal },
    SignalIn { kid: KnotId },
    OnStart { kid: KnotId },
}

/// Bind-time options (sandbox / host policy).
#[derive(Clone, Debug)]
pub struct BindOpts {
    /// Optional host PRNG seed for `Random` knots (mixed with weave id at bind).
    pub seed: Option<Seed>,
    /// Hard cap on `EmitCommand` outbox entries per frame (default 8).
    ///
    /// Further emits in the same frame are dropped without panicking. Their
    /// exact count is exposed through [`Outbox::dropped_emits`] until the next
    /// [`Runtime::begin_frame`]. A cap of zero drops every emit.
    pub max_emits_per_tick: u16,
    /// Validate budget (default matches [`Budget::default`]).
    pub budget: Budget,
}

impl Default for BindOpts {
    fn default() -> Self {
        Self {
            seed: None,
            max_emits_per_tick: 8,
            budget: Budget::default(),
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct ResolvedKnot {
    pub(crate) kind: KnotKind,
    /// For SignalOut / Emit after intern
    pub(crate) path: Option<HostPathId>,
    pub(crate) cmd: Option<CmdId>,
}

/// Bound runtime: dense buffers, topo order, intern tables, stateful rune storage.
///
/// Sole executable artifact after bind. Sample senses through [`PortWriter`],
/// settle with [`Self::loom`], then read [`Self::outbox`].
pub struct Runtime {
    pub(crate) owner: usize,
    pub(crate) knots: Vec<ResolvedKnot>,
    /// Author name → KnotId
    pub(crate) name_to_id: BTreeMap<String, KnotId>,
    pub(crate) path_names: Vec<String>,
    pub(crate) cmd_names: Vec<String>,
    /// CSR inbound: edges in `inbound_edges[inbound_off[ki]..inbound_off[ki+1]]`.
    /// Each edge is (from_knot, from_slot, to_slot).
    pub(crate) inbound_off: Vec<u32>,
    pub(crate) inbound_edges: Vec<(KnotId, PortSlot, PortSlot)>,
    /// Absolute `port_vals` indices of In ports to zero each loom (flat, bind-sized).
    pub(crate) clear_port_idx: Vec<usize>,
    pub(crate) topo: Vec<KnotId>,
    /// Bind-time kind dispatch tags (one per knot; no per-tick from_kind).
    pub(crate) kind_tags: Vec<crate::runtime_impl::kind_tag::KindTag>,
    /// Only Constant / SignalIn / OnStart — loom seeds these without scanning all knots.
    pub(crate) sense_seeds: Vec<SenseSeed>,
    /// Host-fed sense outputs (SignalIn).
    pub(crate) sense_values: Vec<Signal>,
    /// Port value store: indexed by (knot_idx * MAX_PORTS + slot)
    pub(crate) port_vals: Vec<Signal>,
    pub(crate) max_ports: usize,
    /// Knot state for stateful runes
    pub(crate) prev_in: Vec<Signal>,
    pub(crate) prev_dec: Vec<Signal>,
    pub(crate) counter: Vec<i32>,
    pub(crate) flag: Vec<bool>,
    pub(crate) timer_left: Vec<u16>,
    pub(crate) on_start_done: Vec<bool>,
    /// Delay ring: flat buffer + per-knot (offset, len, head).
    pub(crate) delay_buf: Vec<Signal>,
    pub(crate) delay_off: Vec<u16>,
    pub(crate) delay_len: Vec<u16>,
    pub(crate) delay_head: Vec<u16>,
    pub(crate) out_signals: Vec<SignalOutSample>,
    pub(crate) out_emits: Vec<Emit>,
    pub(crate) dropped_emits: usize,
    pub(crate) max_emits_per_tick: u16,
    pub(crate) tick: u64,
    pub(crate) phase: u8,
    /// Deterministic xorshift state for Random knots (never zero).
    pub(crate) rng: u64,
    /// `fnv1a64(weave.id)` mixed into seeds at bind and [`Self::reseed`].
    pub(crate) seed_mix: u64,
    /// Immutable graph and bind-policy fingerprint, computed once at bind.
    pub(crate) state_fingerprint: u64,
}

const MAX_PORTS: usize = 8;
static NEXT_RUNTIME_OWNER: AtomicUsize = AtomicUsize::new(1);

fn fnv1a64(data: &[u8]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for &b in data {
        h ^= b as u64;
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    h
}

/// Convert an authoring-order index to the compact runtime knot id.
///
/// Both bind passes use this guard: the first protects name and intern tables,
/// and the second protects the dense hot-path arrays built from those tables.
fn dense_knot_id(index: usize, weave_id: &str) -> Result<KnotId, BindError> {
    KnotId::try_from(index).map_err(|_| BindError::CapacityExceeded {
        weave_id: String::from(weave_id),
        resource: "knot",
        count: index + 1,
    })
}

/// Intern a SignalOut path while preserving compact host-path ids.
fn intern_host_path(
    owner: usize,
    path: &str,
    path_index: &mut BTreeMap<String, HostPathId>,
    path_names: &mut Vec<String>,
    weave_id: &str,
) -> Result<HostPathId, BindError> {
    if let Some(id) = path_index.get(path) {
        return Ok(*id);
    }

    let index = u16::try_from(path_names.len()).map_err(|_| BindError::CapacityExceeded {
        weave_id: String::from(weave_id),
        resource: "host path",
        count: path_names.len() + 1,
    })?;
    let id = HostPathId::new(owner, index);
    path_names.push(String::from(path));
    path_index.insert(String::from(path), id);
    Ok(id)
}

/// Intern an EmitCommand name while preserving compact command ids.
fn intern_command(
    owner: usize,
    name: &str,
    cmd_index: &mut BTreeMap<String, CmdId>,
    cmd_names: &mut Vec<String>,
    weave_id: &str,
) -> Result<CmdId, BindError> {
    if let Some(id) = cmd_index.get(name) {
        return Ok(*id);
    }

    let index = u16::try_from(cmd_names.len()).map_err(|_| BindError::CapacityExceeded {
        weave_id: String::from(weave_id),
        resource: "command",
        count: cmd_names.len() + 1,
    })?;
    let id = CmdId::new(owner, index);
    cmd_names.push(String::from(name));
    cmd_index.insert(String::from(name), id);
    Ok(id)
}

/// Add a delay extent while preserving the error reported by the original bind
/// phase when the host architecture's usize capacity would overflow.
fn checked_delay_buffer_len(
    current_len: usize,
    len: usize,
    weave_id: &str,
) -> Result<usize, BindError> {
    current_len
        .checked_add(len)
        .ok_or_else(|| BindError::CapacityExceeded {
            weave_id: String::from(weave_id),
            resource: "delay buffer",
            count: usize::MAX,
        })
}

/// Calculate the next delay-ring extent before allocating the backing buffer.
///
/// `current_len` is passed separately so the compact-index guard remains
/// directly testable even though a validated weave cannot reach its impossible
/// overflow state.
fn delay_buffer_layout(
    current_len: usize,
    len: usize,
    weave_id: &str,
) -> Result<(u16, usize), BindError> {
    let offset = u16::try_from(current_len).map_err(|_| BindError::CapacityExceeded {
        weave_id: String::from(weave_id),
        resource: "delay buffer offset",
        count: current_len,
    })?;
    let new_len = checked_delay_buffer_len(current_len, len, weave_id)?;
    if new_len > u16::MAX as usize {
        return Err(BindError::CapacityExceeded {
            weave_id: String::from(weave_id),
            resource: "delay buffer",
            count: new_len,
        });
    }
    Ok((offset, new_len))
}

impl Runtime {
    /// Validate and consume a weave into dense executable state.
    ///
    /// # Errors
    ///
    /// Returns [`BindError`] when budget validation fails, dense capacity is
    /// exceeded, a port cannot be resolved, or topo order cannot be built.
    pub fn bind(weave: Weave, opts: BindOpts) -> Result<Self, BindError> {
        let weave_id = String::from(weave.id());
        validate(&weave, &opts.budget).map_err(|source| BindError::InvalidWeave {
            weave_id: weave_id.clone(),
            source,
        })?;

        Self::bind_validated(weave, opts, weave_id)
    }

    /// Build dense state from a weave that already passed structural and budget validation.
    ///
    /// Keeping this phase separate makes the defensive error handling below
    /// testable without exposing a way to bypass validation to callers.
    fn bind_validated(weave: Weave, opts: BindOpts, weave_id: String) -> Result<Self, BindError> {
        Self::bind_validated_with_preinterned_names(weave, opts, weave_id, Vec::new(), Vec::new())
    }

    /// Internal bind entrypoint with explicit preinterned names for capacity
    /// validation. Normal binding always starts with empty tables.
    ///
    /// Bind phases: intern host paths/commands → build CSR inbound edges and
    /// topo order → patch kind-dispatch tags → size delay rings and sense seeds
    /// → compute the immutable state fingerprint.
    fn bind_validated_with_preinterned_names(
        weave: Weave,
        opts: BindOpts,
        weave_id: String,
        mut path_names: Vec<String>,
        mut cmd_names: Vec<String>,
    ) -> Result<Self, BindError> {
        let owner = NEXT_RUNTIME_OWNER.fetch_add(1, Ordering::Relaxed);
        reserve_owner(owner, &weave_id)?;

        let mut name_to_id = BTreeMap::new();
        let mut path_index: BTreeMap<String, HostPathId> = BTreeMap::new();
        let mut cmd_index: BTreeMap<String, CmdId> = BTreeMap::new();

        let mut knots = Vec::with_capacity(weave.knots().len());
        for (i, k) in weave.knots().iter().enumerate() {
            let id = dense_knot_id(i, &weave_id)?;
            name_to_id.insert(k.id.clone(), id);

            let (path, cmd) = match &k.kind {
                KnotKind::SignalOut { path, .. } => (
                    Some(intern_host_path(
                        owner,
                        path,
                        &mut path_index,
                        &mut path_names,
                        &weave_id,
                    )?),
                    None,
                ),
                KnotKind::EmitCommand { name } => (
                    None,
                    Some(intern_command(
                        owner,
                        name,
                        &mut cmd_index,
                        &mut cmd_names,
                        &weave_id,
                    )?),
                ),
                _ => (None, None),
            };

            knots.push(ResolvedKnot {
                kind: k.kind.clone(),
                path,
                cmd,
            });
        }

        let mut threads = Vec::new();
        for t in weave.threads() {
            let fk = *name_to_id
                .get(&t.from.knot)
                .ok_or_else(|| BindError::InvalidReference {
                    weave_id: weave_id.clone(),
                    knot: t.from.knot.clone(),
                    port: t.from.port.clone(),
                })?;
            let tk = *name_to_id
                .get(&t.to.knot)
                .ok_or_else(|| BindError::InvalidReference {
                    weave_id: weave_id.clone(),
                    knot: t.to.knot.clone(),
                    port: t.to.port.clone(),
                })?;
            let fs = port_slot(&knots[usize::from(fk)].kind, &t.from.port).ok_or_else(|| {
                BindError::InvalidReference {
                    weave_id: weave_id.clone(),
                    knot: t.from.knot.clone(),
                    port: t.from.port.clone(),
                }
            })?;
            let ts = port_slot(&knots[usize::from(tk)].kind, &t.to.port).ok_or_else(|| {
                BindError::InvalidReference {
                    weave_id: weave_id.clone(),
                    knot: t.to.knot.clone(),
                    port: t.to.port.clone(),
                }
            })?;
            threads.push((fk, fs, tk, ts));
        }

        let topo = topo_order(knots.len(), &threads).ok_or_else(|| BindError::InvalidTopology {
            weave_id: weave_id.clone(),
        })?;

        let n = knots.len();
        let mut inbound_lists: Vec<Vec<(KnotId, PortSlot, PortSlot)>> = alloc::vec![Vec::new(); n];
        for &(f, fs, t, ts) in &threads {
            inbound_lists[usize::from(t)].push((f, fs, ts));
        }
        let mut inbound_off = Vec::with_capacity(n + 1);
        let mut inbound_edges = Vec::with_capacity(threads.len());
        inbound_off.push(0);
        for list in &inbound_lists {
            inbound_edges.extend_from_slice(list);
            inbound_off.push(inbound_edges.len() as u32);
        }

        let mut clear_port_idx = Vec::new();
        let mut act_signals = 0usize;
        let mut act_emits = 0usize;
        let mut sense_seeds = Vec::new();
        let mut kind_tags: Vec<crate::runtime_impl::kind_tag::KindTag> = knots
            .iter()
            .map(|k| crate::runtime_impl::kind_tag::KindTag::from_kind(&k.kind))
            .collect();
        for (ki, k) in knots.iter().enumerate() {
            let kid = dense_knot_id(ki, &weave_id)?;
            for p in ports_of(&k.kind) {
                if p.dir == PortDir::In {
                    // Only unwired Ins are zeroed each loom; wired Ins are gathered.
                    let wired = inbound_lists[ki].iter().any(|&(_, _, ts)| ts == p.slot);
                    if !wired {
                        clear_port_idx.push(ki * MAX_PORTS + usize::from(p.slot));
                    }
                }
            }
            match &k.kind {
                KnotKind::Constant { value, .. } => {
                    sense_seeds.push(SenseSeed::Constant { kid, value: *value });
                }
                KnotKind::SignalIn { .. } => {
                    sense_seeds.push(SenseSeed::SignalIn { kid });
                }
                KnotKind::OnStart => {
                    sense_seeds.push(SenseSeed::OnStart { kid });
                }
                KnotKind::SignalOut { .. } => act_signals += 1,
                KnotKind::EmitCommand { .. } => {
                    act_emits += 1;
                    let enable_wired = inbound_lists[ki]
                        .iter()
                        .any(|&(_, _, ts)| ts == PortSlot::new(1));
                    kind_tags[ki] =
                        crate::runtime_impl::kind_tag::KindTag::EmitCommand { enable_wired };
                }
                KnotKind::Random { .. } => {
                    let mut min_wired = false;
                    let mut max_wired = false;
                    for &(_, _, ts) in &inbound_lists[ki] {
                        if ts == PortSlot::new(0) {
                            min_wired = true;
                        } else if ts == PortSlot::new(1) {
                            max_wired = true;
                        }
                    }
                    kind_tags[ki] = kind_tags[ki].with_random_wiring(min_wired, max_wired);
                }
                KnotKind::Calc {
                    domain,
                    op: CalcOp::Div,
                } => {
                    if let Some(&(from, _, _)) = inbound_lists[ki]
                        .iter()
                        .find(|&&(_, _, ts)| ts == PortSlot::new(1))
                    {
                        if let KnotKind::Constant { value, .. } = knots[usize::from(from)].kind {
                            kind_tags[ki] = crate::runtime_impl::kind_tag::KindTag::calc_div_const(
                                *domain, value,
                            );
                        }
                    }
                }
                _ => {}
            }
        }

        let mut delay_buf = Vec::new();
        let mut delay_off = alloc::vec![0u16; n];
        let mut delay_len = alloc::vec![0u16; n];
        let delay_head = alloc::vec![0u16; n];
        for (i, k) in knots.iter().enumerate() {
            if let KnotKind::Delay { ticks } = k.kind {
                let len = ticks as usize;
                if len > 0 {
                    let (offset, new_len) = delay_buffer_layout(delay_buf.len(), len, &weave_id)?;
                    delay_off[i] = offset;
                    delay_len[i] = ticks;
                    delay_buf.resize(new_len, ZERO);
                }
            }
        }

        let out_signals = Vec::with_capacity(act_signals);
        let out_emits = Vec::with_capacity(act_emits.min(usize::from(opts.max_emits_per_tick)));

        let base = opts.seed.unwrap_or(Seed(0xC0FF_EE00_D15C_AFEDu64));
        let seed_mix = fnv1a64(weave.id().as_bytes());
        let rng = (base.0 ^ seed_mix) | 1;
        let state_fingerprint = crate::runtime_impl::runtime_state::runtime_fingerprint_for(
            &knots,
            &threads,
            &path_names,
            &cmd_names,
            opts.max_emits_per_tick,
            seed_mix,
            opts.seed,
        );

        Ok(Runtime {
            owner,
            knots,
            name_to_id,
            path_names,
            cmd_names,
            inbound_off,
            inbound_edges,
            clear_port_idx,
            topo,
            kind_tags,
            sense_seeds,
            sense_values: alloc::vec![ZERO; n],
            port_vals: alloc::vec![ZERO; n * MAX_PORTS],
            max_ports: MAX_PORTS,
            prev_in: alloc::vec![ZERO; n],
            prev_dec: alloc::vec![ZERO; n],
            counter: alloc::vec![0; n],
            flag: alloc::vec![false; n],
            timer_left: alloc::vec![0; n],
            on_start_done: alloc::vec![false; n],
            delay_buf,
            delay_off,
            delay_len,
            delay_head,
            out_signals,
            out_emits,
            dropped_emits: 0,
            max_emits_per_tick: opts.max_emits_per_tick,
            tick: 0,
            phase: 0,
            rng,
            seed_mix,
            state_fingerprint,
        })
    }

    /// Restore PRNG stream (room retry). Same mix as bind: `seed ^ fnv(weave.id) | 1`.
    pub fn reseed(&mut self, seed: Seed) {
        self.rng = (seed.0 ^ self.seed_mix) | 1;
    }

    /// Next u32 from the bind-seeded xorshift64 stream (`rng` is never zero).
    pub(crate) fn next_rng_u32(&mut self) -> u32 {
        let mut x = self.rng;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.rng = x;
        x as u32
    }

    /// Resolve a `SignalIn` author name to a dense sense id (setup only).
    pub fn sense_id(&self, name: &str) -> Option<SenseId> {
        let knot = self.name_to_id.get(name).copied()?;
        if !matches!(
            self.knots.get(usize::from(knot))?.kind,
            KnotKind::SignalIn { .. }
        ) {
            return None;
        }
        Some(SenseId::new(self.owner, knot.get()))
    }

    /// Resolve a required `SignalIn` knot for a typed recipe port.
    pub fn required_sense(&self, name: &str) -> Result<SenseId, RecipeResolveError> {
        let Some(knot) = self.name_to_id.get(name).copied() else {
            return Err(RecipeResolveError::Missing {
                endpoint: RecipeEndpoint::SignalIn,
                name: String::from(name),
            });
        };
        if !matches!(
            self.knots
                .get(usize::from(knot))
                .map(|resolved| &resolved.kind),
            Some(KnotKind::SignalIn { .. })
        ) {
            return Err(RecipeResolveError::Invalid {
                endpoint: RecipeEndpoint::SignalIn,
                name: String::from(name),
                reason: "the knot is not a SignalIn",
            });
        }
        Ok(SenseId::new(self.owner, knot.get()))
    }

    /// Resolve an author knot name for checked tooling access.
    pub fn knot_id(&self, name: &str) -> Option<KnotHandle> {
        self.name_to_id
            .get(name)
            .map(|knot| KnotHandle::new(self.owner, knot.get()))
    }

    /// Resolve a required author knot for a typed recipe port.
    pub fn required_knot(&self, name: &str) -> Result<KnotHandle, RecipeResolveError> {
        self.knot_id(name)
            .ok_or_else(|| RecipeResolveError::Missing {
                endpoint: RecipeEndpoint::Knot,
                name: String::from(name),
            })
    }

    /// Resolve a `SignalOut` path string interned at bind.
    pub fn path_id(&self, path: &str) -> Option<HostPathId> {
        self.path_names
            .iter()
            .position(|p| p == path)
            .and_then(|i| u16::try_from(i).ok())
            .map(|index| HostPathId::new(self.owner, index))
    }

    /// Resolve a required `SignalOut` path for a typed recipe port.
    pub fn required_path(&self, path: &str) -> Result<HostPathId, RecipeResolveError> {
        self.path_id(path)
            .ok_or_else(|| RecipeResolveError::Missing {
                endpoint: RecipeEndpoint::SignalOut,
                name: String::from(path),
            })
    }

    /// Resolve an `EmitCommand` name interned at bind.
    pub fn cmd_id(&self, name: &str) -> Option<CmdId> {
        self.cmd_names
            .iter()
            .position(|candidate| candidate == name)
            .and_then(|i| u16::try_from(i).ok())
            .map(|index| CmdId::new(self.owner, index))
    }

    /// Resolve a required `EmitCommand` name for a typed recipe port.
    pub fn required_command(&self, name: &str) -> Result<CmdId, RecipeResolveError> {
        self.cmd_id(name)
            .ok_or_else(|| RecipeResolveError::Missing {
                endpoint: RecipeEndpoint::EmitCommand,
                name: String::from(name),
            })
    }

    /// Interned path string for a dense host path id.
    pub fn path_name(&self, id: HostPathId) -> Result<&str, HandleError> {
        self.ensure_owner(id.owner, "host path")?;
        self.path_names
            .get(usize::from(id.index))
            .map(|s| s.as_str())
            .ok_or(HandleError::InvalidHostPath { path: id })
    }

    /// Interned emit command name for a dense command id.
    pub fn cmd_name(&self, id: CmdId) -> Result<&str, HandleError> {
        self.ensure_owner(id.owner, "command")?;
        self.cmd_names
            .get(usize::from(id.index))
            .map(|s| s.as_str())
            .ok_or(HandleError::InvalidCommand { cmd: id })
    }

    /// Start a frame: set tick and clear acts and dropped-emit telemetry.
    pub fn begin_frame(&mut self, time: HostTime) {
        self.tick = time.tick;
        self.phase = 1;
        self.out_signals.clear();
        self.out_emits.clear();
        self.dropped_emits = 0;
    }

    /// Borrow for host sense writes (`set_sense` with dense ids only).
    pub fn port_writer(&mut self) -> PortWriter<'_> {
        PortWriter { rt: self }
    }

    /// Read-only view of acts and dropped-emit telemetry for this frame.
    pub fn outbox(&self) -> Outbox<'_> {
        Outbox {
            signals: &self.out_signals,
            emits: &self.out_emits,
            dropped_emits: self.dropped_emits,
        }
    }

    /// Capacity of the SignalOut outbox buffer (reserved at bind).
    pub fn outbox_signals_capacity(&self) -> usize {
        self.out_signals.capacity()
    }

    /// Length of the flat delay ring (sized at bind).
    pub fn delay_buf_len(&self) -> usize {
        self.delay_buf.len()
    }

    #[inline]
    pub(crate) fn port_index(&self, knot: KnotId, slot: PortSlot) -> usize {
        usize::from(knot) * self.max_ports + usize::from(slot)
    }

    /// Safe OOB-tolerant read (returns ZERO past end). Used by tests and host tooling.
    #[inline]
    pub fn get_port_checked(
        &self,
        knot: KnotHandle,
        slot: PortSlot,
    ) -> Result<Signal, HandleError> {
        self.ensure_owner(knot.owner, "knot")?;
        let dense = KnotId::try_from(usize::from(knot.index))
            .map_err(|_| HandleError::InvalidKnot { knot })?;
        let Some(resolved) = self.knots.get(usize::from(dense)) else {
            return Err(HandleError::InvalidKnot { knot });
        };
        if !ports_of(&resolved.kind)
            .iter()
            .any(|info| info.slot == slot)
        {
            return Err(HandleError::InvalidPort { knot, port: slot });
        }
        let i = self.port_index(dense, slot);
        self.port_vals
            .get(i)
            .copied()
            .ok_or(HandleError::InvalidPort { knot, port: slot })
    }

    /// Safe OOB-tolerant write (no-op past end). Used by tests and host tooling.
    #[inline]
    pub fn set_port_checked(
        &mut self,
        knot: KnotHandle,
        slot: PortSlot,
        v: Signal,
    ) -> Result<(), HandleError> {
        self.ensure_owner(knot.owner, "knot")?;
        let dense = KnotId::try_from(usize::from(knot.index))
            .map_err(|_| HandleError::InvalidKnot { knot })?;
        let Some(resolved) = self.knots.get(usize::from(dense)) else {
            return Err(HandleError::InvalidKnot { knot });
        };
        if !ports_of(&resolved.kind)
            .iter()
            .any(|info| info.slot == slot)
        {
            return Err(HandleError::InvalidPort { knot, port: slot });
        }
        let i = self.port_index(dense, slot);
        let p = self
            .port_vals
            .get_mut(i)
            .ok_or(HandleError::InvalidPort { knot, port: slot })?;
        *p = v;
        Ok(())
    }

    /// Dense-id alias for [`Self::get_port_checked`] (tooling and bind-shape tests).
    #[inline]
    #[allow(dead_code)]
    pub(crate) fn get_port(&self, knot: KnotId, slot: PortSlot) -> Result<Signal, HandleError> {
        let handle = KnotHandle::new(self.owner, knot.get());
        self.get_port_checked(handle, slot)
    }

    /// Dense-id alias for [`Self::set_port_checked`] (tooling and bind-shape tests).
    #[inline]
    #[allow(dead_code)]
    pub(crate) fn set_port(
        &mut self,
        knot: KnotId,
        slot: PortSlot,
        v: Signal,
    ) -> Result<(), HandleError> {
        let handle = KnotHandle::new(self.owner, knot.get());
        self.set_port_checked(handle, slot, v)
    }

    fn ensure_owner(&self, owner: usize, handle: &'static str) -> Result<(), HandleError> {
        if owner == self.owner {
            Ok(())
        } else {
            Err(HandleError::ForeignRuntime { handle })
        }
    }

    /// Number of bind-time kind tags (equals knot count after successful bind).
    ///
    /// Bind-shape introspection for tests and tooling — not used on the settle hot path.
    pub fn kind_tag_count(&self) -> usize {
        self.kind_tags.len()
    }

    /// Flat clear-index count (all In ports across the weave).
    ///
    /// Bind-shape introspection for tests and tooling — not used on the settle hot path.
    pub fn clear_port_index_count(&self) -> usize {
        self.clear_port_idx.len()
    }

    /// CSR inbound edge count.
    ///
    /// Bind-shape introspection for tests and tooling — not used on the settle hot path.
    pub fn inbound_edge_count(&self) -> usize {
        self.inbound_edges.len()
    }

    /// Hot-path port read when `knot`/`slot` are bind-validated (in-range).
    #[inline]
    pub(crate) fn get_port_hot(&self, knot: KnotId, slot: PortSlot) -> Signal {
        let i = self.port_index(knot, slot);
        debug_assert!(i < self.port_vals.len());
        self.port_vals[i]
    }

    /// Hot-path port write when `knot`/`slot` are bind-validated.
    #[inline]
    pub(crate) fn set_port_hot(&mut self, knot: KnotId, slot: PortSlot, v: Signal) {
        let i = self.port_index(knot, slot);
        debug_assert!(i < self.port_vals.len());
        self.port_vals[i] = v;
    }

    pub(crate) fn push_signal_out(&mut self, path: HostPathId, value: Signal) {
        self.out_signals.push(SignalOutSample { path, value });
    }

    pub(crate) fn push_emit(&mut self, cmd: CmdId, payload: Signal) {
        if self.out_emits.len() >= usize::from(self.max_emits_per_tick) {
            self.dropped_emits = self.dropped_emits.saturating_add(1);
            return;
        }
        self.out_emits.push(Emit { cmd, payload });
    }
}

fn reserve_owner(owner: usize, weave_id: &str) -> Result<(), BindError> {
    if owner == usize::MAX {
        return Err(BindError::CapacityExceeded {
            weave_id: String::from(weave_id),
            resource: "runtime owner token",
            count: owner,
        });
    }
    Ok(())
}

fn topo_order(n: usize, threads: &[(KnotId, PortSlot, KnotId, PortSlot)]) -> Option<Vec<KnotId>> {
    let mut indeg = alloc::vec![0u32; n];
    let mut adj: Vec<Vec<usize>> = alloc::vec![Vec::new(); n];
    for &(f, _, t, _) in threads {
        let a = usize::from(f);
        let b = usize::from(t);
        if a != b {
            adj[a].push(b);
            indeg[b] += 1;
        }
    }
    let mut q: Vec<usize> = indeg
        .iter()
        .enumerate()
        .filter_map(|(i, d)| if *d == 0 { Some(i) } else { None })
        .collect();
    let mut order = Vec::with_capacity(n);
    while let Some(u) = q.pop() {
        order.push(KnotId::try_from(u).ok()?);
        for &v in &adj[u] {
            indeg[v] -= 1;
            if indeg[v] == 0 {
                q.push(v);
            }
        }
    }
    if order.len() != n {
        return None;
    }
    Some(order)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authoring::{KnotDef, PortRefDef, ThreadDef, Weave, WeaveDef};
    use crate::foundation::{CalcOp, FlagPriority, KnotKind, NumericPath, SignalDomain, ONE};
    use std::vec;

    fn unchecked_weave(id: &str, knots: Vec<KnotDef>, threads: Vec<ThreadDef>) -> Weave {
        Weave::from_validated(WeaveDef {
            id: String::from(id),
            numeric: NumericPath::compiled(),
            knots,
            threads,
        })
    }

    fn bind_unchecked(id: &str, knots: Vec<KnotDef>, threads: Vec<ThreadDef>) -> BindError {
        Runtime::bind_validated(
            unchecked_weave(id, knots, threads),
            BindOpts::default(),
            String::from(id),
        )
        .err()
        .expect("malformed internal weave must not bind")
    }

    fn knot(id: &str, kind: KnotKind) -> KnotDef {
        KnotDef {
            id: String::from(id),
            kind,
        }
    }

    #[test]
    fn sense_seeds_lists_only_sense_knots() {
        let mut b = Weave::builder("s").unwrap();
        let k_in = b
            .knot("in", KnotKind::signal_in(SignalDomain::Bool))
            .unwrap();
        let _k_c = b
            .knot("c", KnotKind::constant(ONE, SignalDomain::Bool))
            .unwrap();
        let k_n = b.knot("n", KnotKind::Not).unwrap();
        let k_out = b
            .knot("out", KnotKind::signal_out("y", SignalDomain::Bool))
            .unwrap();
        let from = b.output(&k_in, "out").unwrap();
        let to = b.input(&k_n, "in").unwrap();
        b.connect(from, to).unwrap();
        let from = b.output(&k_n, "out").unwrap();
        let to = b.input(&k_out, "in").unwrap();
        b.connect(from, to).unwrap();
        let weave = b.build().unwrap();
        let rt = Runtime::bind(weave.clone(), BindOpts::default()).unwrap();
        assert_eq!(rt.sense_seeds.len(), 2, "SignalIn + Constant only");
        assert!(rt
            .sense_seeds
            .iter()
            .any(|s| matches!(s, SenseSeed::SignalIn { .. })));
        assert!(rt
            .sense_seeds
            .iter()
            .any(|s| matches!(s, SenseSeed::Constant { value, .. } if *value == ONE)));
        let mut b = Weave::builder("e").unwrap();
        let k_btn = b
            .knot("btn", KnotKind::signal_in(SignalDomain::Bool))
            .unwrap();
        let k_em = b.knot("em", KnotKind::emit_command("fire")).unwrap();
        let from = b.output(&k_btn, "out").unwrap();
        let to = b.input(&k_em, "trigger").unwrap();
        b.connect(from, to).unwrap();
        let weave = b.build().unwrap();
        let rt = Runtime::bind(
            weave.clone(),
            BindOpts {
                seed: Some(Seed(1)),
                ..BindOpts::default()
            },
        )
        .unwrap();
        let em = *rt.name_to_id.get("em").expect("em knot");
        assert!(matches!(
            rt.kind_tags[usize::from(em)],
            crate::runtime_impl::kind_tag::KindTag::EmitCommand {
                enable_wired: false
            }
        ));
    }

    #[test]
    fn cmd_name_and_path_name_lookup() {
        let mut b = Weave::builder("e").unwrap();
        let k_btn = b
            .knot("btn", KnotKind::signal_in(SignalDomain::Bool))
            .unwrap();
        let k_em = b.knot("em", KnotKind::emit_command("fire")).unwrap();
        let k_out = b
            .knot("out", KnotKind::signal_out("y", SignalDomain::Bool))
            .unwrap();
        let from = b.output(&k_btn, "out").unwrap();
        let to = b.input(&k_em, "trigger").unwrap();
        b.connect(from, to).unwrap();
        let from = b.output(&k_btn, "out").unwrap();
        let to = b.input(&k_out, "in").unwrap();
        b.connect(from, to).unwrap();
        let weave = b.build().unwrap();
        let rt = Runtime::bind(
            weave.clone(),
            BindOpts {
                seed: Some(Seed(1)),
                ..BindOpts::default()
            },
        )
        .unwrap();
        let cmd = rt.knots[usize::from(*rt.name_to_id.get("em").unwrap())]
            .cmd
            .unwrap();
        assert_eq!(rt.cmd_name(cmd), Ok("fire"));
        let invalid_cmd = CmdId::new(rt.owner, 99);
        assert_eq!(
            rt.cmd_name(invalid_cmd),
            Err(HandleError::InvalidCommand { cmd: invalid_cmd })
        );
        let path = rt.path_id("y").unwrap();
        assert_eq!(rt.path_name(path), Ok("y"));
        let invalid_path = HostPathId::new(rt.owner, 99);
        assert_eq!(
            rt.path_name(invalid_path),
            Err(HandleError::InvalidHostPath { path: invalid_path })
        );
    }

    #[test]
    fn topo_order_detects_cycle() {
        let a = KnotId::try_from(0usize).unwrap();
        let b = KnotId::try_from(1usize).unwrap();
        let threads = [
            (a, PortSlot::new(1), b, PortSlot::new(0)),
            (b, PortSlot::new(1), a, PortSlot::new(0)),
        ];
        assert_eq!(topo_order(2, &threads), None);
    }

    #[test]
    fn checked_port_access_reports_oob_without_mutation() {
        let mut b = Weave::builder("x").unwrap();
        let _k_c = b
            .knot("c", KnotKind::constant(ONE, SignalDomain::Bool))
            .unwrap();
        let weave = b.build().unwrap();
        let mut rt = Runtime::bind(weave.clone(), BindOpts::default()).unwrap();
        let far = KnotId::try_from(999usize).unwrap();
        let far_handle = KnotHandle::new(rt.owner, far.get());
        assert_eq!(
            rt.get_port(far, PortSlot::new(0)),
            Err(HandleError::InvalidKnot { knot: far_handle })
        );
        assert_eq!(
            rt.set_port(far, PortSlot::new(0), ONE),
            Err(HandleError::InvalidKnot { knot: far_handle })
        );
        let _ = FlagPriority::SetWins;
    }

    #[test]
    fn dropped_emit_count_saturates() {
        let mut b = Weave::builder("emit-saturation").unwrap();
        let input = b
            .knot("input", KnotKind::signal_in(SignalDomain::Bool))
            .unwrap();
        let emit = b.knot("emit", KnotKind::emit_command("fire")).unwrap();
        let from = b.output(&input, "out").unwrap();
        let to = b.input(&emit, "trigger").unwrap();
        b.connect(from, to).unwrap();
        let mut rt = Runtime::bind(
            b.build().unwrap(),
            BindOpts {
                max_emits_per_tick: 0,
                ..BindOpts::default()
            },
        )
        .unwrap();
        let cmd = rt.cmd_id("fire").unwrap();
        rt.dropped_emits = usize::MAX;

        rt.push_emit(cmd, ONE);

        assert_eq!(rt.dropped_emits, usize::MAX);
        assert!(rt.out_emits.is_empty());
    }

    #[test]
    fn emit_outbox_reservation_respects_the_runtime_cap() {
        let mut b = Weave::builder("emit-reservation").unwrap();
        let trigger = b
            .knot("trigger", KnotKind::constant(ONE, SignalDomain::Bool))
            .unwrap();
        for i in 0..4 {
            let emit = b
                .knot(
                    alloc::format!("emit-{i}"),
                    KnotKind::emit_command(alloc::format!("command-{i}")),
                )
                .unwrap();
            let from = b.output(&trigger, "out").unwrap();
            let to = b.input(&emit, "trigger").unwrap();
            b.connect(from, to).unwrap();
        }
        let weave = b.build().unwrap();

        for (cap, expected) in [(0, 0), (2, 2), (4, 4), (8, 4)] {
            let rt = Runtime::bind(
                weave.clone(),
                BindOpts {
                    max_emits_per_tick: cap,
                    ..BindOpts::default()
                },
            )
            .unwrap();
            assert_eq!(rt.out_emits.capacity(), expected);
        }
    }

    #[test]
    fn clear_only_unwired_ins_and_div_const_specializes() {
        use crate::foundation::CalcOp;
        let mut b = Weave::builder("fl").unwrap();
        let k_f = b
            .knot("f", KnotKind::flag(FlagPriority::SetWins, false))
            .unwrap();
        let k_o = b
            .knot("o", KnotKind::signal_out("y", SignalDomain::Bool))
            .unwrap();
        let from = b.output(&k_f, "out").unwrap();
        let to = b.input(&k_o, "in").unwrap();
        b.connect(from, to).unwrap();
        let weave = b.build().unwrap();
        let rt = Runtime::bind(weave.clone(), BindOpts::default()).unwrap();
        assert_eq!(
            rt.clear_port_index_count(),
            3,
            "unwired Flag Ins must clear"
        );

        let mut b = Weave::builder("dv").unwrap();
        let k_in = b
            .knot("in", KnotKind::signal_in(SignalDomain::Level))
            .unwrap();
        let k_one = b
            .knot("one", KnotKind::constant(ONE, SignalDomain::Level))
            .unwrap();
        let k_d = b
            .knot(
                "d",
                KnotKind::Calc {
                    domain: SignalDomain::Level,
                    op: CalcOp::Div,
                },
            )
            .unwrap();
        let k_out = b
            .knot("out", KnotKind::signal_out("y", SignalDomain::Level))
            .unwrap();
        let from = b.output(&k_in, "out").unwrap();
        let to = b.input(&k_d, "a").unwrap();
        b.connect(from, to).unwrap();
        let from = b.output(&k_one, "out").unwrap();
        let to = b.input(&k_d, "b").unwrap();
        b.connect(from, to).unwrap();
        let from = b.output(&k_d, "out").unwrap();
        let to = b.input(&k_out, "in").unwrap();
        b.connect(from, to).unwrap();
        let weave = b.build().unwrap();
        let rt = Runtime::bind(weave.clone(), BindOpts::default()).unwrap();
        let d = *rt.name_to_id.get("d").expect("div knot");
        assert!(matches!(
            rt.kind_tags[usize::from(d)],
            crate::runtime_impl::kind_tag::KindTag::CalcDivLevelConst { divisor } if divisor == ONE
        ));
    }

    /// Bind builds KindTag cache, flat clear indices, and CSR inbound.
    #[test]
    fn bind_builds_hot_path_tables() {
        let mut b = Weave::builder("h").unwrap();
        let k_a = b
            .knot("a", KnotKind::signal_in(SignalDomain::Bool))
            .unwrap();
        let k_n = b.knot("n", KnotKind::not()).unwrap();
        let k_o = b
            .knot("o", KnotKind::signal_out("y", SignalDomain::Bool))
            .unwrap();
        let from = b.output(&k_a, "out").unwrap();
        let to = b.input(&k_n, "in").unwrap();
        b.connect(from, to).unwrap();
        let from = b.output(&k_n, "out").unwrap();
        let to = b.input(&k_o, "in").unwrap();
        b.connect(from, to).unwrap();
        let weave = b.build().unwrap();
        let mut rt = Runtime::bind(weave.clone(), BindOpts::default()).unwrap();
        assert_eq!(rt.kind_tag_count(), weave.knots().len());
        assert_eq!(rt.clear_port_index_count(), 0);
        assert_eq!(rt.inbound_edge_count(), 2);
        assert_eq!(rt.inbound_off.len(), weave.knots().len() + 1);
        let n_id = KnotId::try_from(1usize).unwrap();
        rt.set_port_hot(n_id, PortSlot::new(0), ONE);
        assert_eq!(rt.get_port_hot(n_id, PortSlot::new(0)), ONE);
        let n_handle = rt.knot_id("n").unwrap();
        assert_eq!(rt.get_port_checked(n_handle, PortSlot::new(0)), Ok(ONE));
    }

    #[test]
    fn defensive_bind_phase_rejects_invalid_internal_definitions() {
        let constant = || knot("constant", KnotKind::constant(ONE, SignalDomain::Bool));
        let out = || knot("out", KnotKind::signal_out("out", SignalDomain::Bool));

        let error = bind_unchecked(
            "missing-from",
            vec![constant()],
            vec![ThreadDef {
                from: PortRefDef::new("missing", "out"),
                to: PortRefDef::new("constant", "out"),
            }],
        );
        assert!(matches!(
            error,
            BindError::InvalidReference { knot, port, .. } if knot == "missing" && port == "out"
        ));

        let error = bind_unchecked(
            "missing-to",
            vec![constant()],
            vec![ThreadDef {
                from: PortRefDef::new("constant", "out"),
                to: PortRefDef::new("missing", "in"),
            }],
        );
        assert!(matches!(
            error,
            BindError::InvalidReference { knot, port, .. } if knot == "missing" && port == "in"
        ));

        let error = bind_unchecked(
            "missing-from-port",
            vec![constant(), out()],
            vec![ThreadDef {
                from: PortRefDef::new("constant", "in"),
                to: PortRefDef::new("out", "in"),
            }],
        );
        assert!(matches!(
            error,
            BindError::InvalidReference { knot, port, .. } if knot == "constant" && port == "in"
        ));

        let error = bind_unchecked(
            "missing-to-port",
            vec![constant(), out()],
            vec![ThreadDef {
                from: PortRefDef::new("constant", "out"),
                to: PortRefDef::new("out", "out"),
            }],
        );
        assert!(matches!(
            error,
            BindError::InvalidReference { knot, port, .. } if knot == "out" && port == "out"
        ));

        let error = bind_unchecked(
            "cycle",
            vec![knot("a", KnotKind::Not), knot("b", KnotKind::Not)],
            vec![
                ThreadDef {
                    from: PortRefDef::new("a", "out"),
                    to: PortRefDef::new("b", "in"),
                },
                ThreadDef {
                    from: PortRefDef::new("b", "out"),
                    to: PortRefDef::new("a", "in"),
                },
            ],
        );
        assert!(matches!(error, BindError::InvalidTopology { .. }));
    }

    #[test]
    fn defensive_bind_phase_checks_dense_capacities_before_allocation() {
        assert_eq!(
            reserve_owner(usize::MAX, "owner"),
            Err(BindError::CapacityExceeded {
                weave_id: String::from("owner"),
                resource: "runtime owner token",
                count: usize::MAX,
            })
        );
        assert_eq!(reserve_owner(1, "owner"), Ok(()));

        let excessive_knots = (0..=(usize::from(u16::MAX) + 1))
            .map(|_| knot("", KnotKind::OnStart))
            .collect();
        let error = bind_unchecked("too-many-knots", excessive_knots, Vec::new());
        assert_eq!(
            error,
            BindError::CapacityExceeded {
                weave_id: String::from("too-many-knots"),
                resource: "knot",
                count: usize::from(u16::MAX) + 2,
            }
        );

        let delay_knots = (0..256)
            .map(|_| knot("", KnotKind::Delay { ticks: 256 }))
            .collect();
        let error = bind_unchecked("delay-capacity", delay_knots, Vec::new());
        assert_eq!(
            error,
            BindError::CapacityExceeded {
                weave_id: String::from("delay-capacity"),
                resource: "delay buffer",
                count: usize::from(u16::MAX) + 1,
            }
        );
    }

    #[test]
    fn defensive_compact_capacity_guards_report_the_next_entry() {
        let overflow_index = usize::from(u16::MAX) + 1;
        let mut path_index = BTreeMap::new();
        let mut path_names = vec![String::new(); overflow_index];
        assert_eq!(
            intern_host_path(
                1,
                "overflow",
                &mut path_index,
                &mut path_names,
                "path-capacity",
            ),
            Err(BindError::CapacityExceeded {
                weave_id: String::from("path-capacity"),
                resource: "host path",
                count: overflow_index + 1,
            })
        );

        let mut cmd_index = BTreeMap::new();
        let mut cmd_names = vec![String::new(); overflow_index];
        assert_eq!(
            intern_command(
                1,
                "overflow",
                &mut cmd_index,
                &mut cmd_names,
                "command-capacity",
            ),
            Err(BindError::CapacityExceeded {
                weave_id: String::from("command-capacity"),
                resource: "command",
                count: overflow_index + 1,
            })
        );

        assert_eq!(
            delay_buffer_layout(overflow_index, 1, "delay-offset-capacity"),
            Err(BindError::CapacityExceeded {
                weave_id: String::from("delay-offset-capacity"),
                resource: "delay buffer offset",
                count: overflow_index,
            })
        );
        assert_eq!(
            checked_delay_buffer_len(usize::MAX, 1, "delay-overflow"),
            Err(BindError::CapacityExceeded {
                weave_id: String::from("delay-overflow"),
                resource: "delay buffer",
                count: usize::MAX,
            })
        );
    }

    #[test]
    fn preinterned_tables_propagate_path_and_command_capacity_errors() {
        let full_names = vec![String::new(); usize::from(u16::MAX) + 1];
        let path_error = Runtime::bind_validated_with_preinterned_names(
            unchecked_weave(
                "path-capacity",
                vec![knot(
                    "output",
                    KnotKind::signal_out("too-many-paths", SignalDomain::Bool),
                )],
                Vec::new(),
            ),
            BindOpts::default(),
            String::from("path-capacity"),
            full_names,
            Vec::new(),
        )
        .err()
        .expect("the next host path must exceed its compact id space");
        assert!(matches!(
            path_error,
            BindError::CapacityExceeded {
                resource: "host path",
                count,
                ..
            } if count == usize::from(u16::MAX) + 2
        ));

        let full_names = vec![String::new(); usize::from(u16::MAX) + 1];
        let command_error = Runtime::bind_validated_with_preinterned_names(
            unchecked_weave(
                "command-capacity",
                vec![knot("emit", KnotKind::emit_command("too-many-commands"))],
                Vec::new(),
            ),
            BindOpts::default(),
            String::from("command-capacity"),
            Vec::new(),
            full_names,
        )
        .err()
        .expect("the next command must exceed its compact id space");
        assert!(matches!(
            command_error,
            BindError::CapacityExceeded {
                resource: "command",
                count,
                ..
            } if count == usize::from(u16::MAX) + 2
        ));
    }

    #[test]
    fn div_with_a_dynamic_rhs_keeps_the_general_dispatch_tag() {
        let mut b = Weave::builder("dynamic-divisor").unwrap();
        let lhs = b
            .knot("lhs", KnotKind::signal_in(SignalDomain::Level))
            .unwrap();
        let rhs = b
            .knot("rhs", KnotKind::signal_in(SignalDomain::Level))
            .unwrap();
        let div = b
            .knot(
                "div",
                KnotKind::Calc {
                    domain: SignalDomain::Level,
                    op: CalcOp::Div,
                },
            )
            .unwrap();
        b.connect(b.output(&lhs, "out").unwrap(), b.input(&div, "a").unwrap())
            .unwrap();
        b.connect(b.output(&rhs, "out").unwrap(), b.input(&div, "b").unwrap())
            .unwrap();

        let rt = Runtime::bind(b.build().unwrap(), BindOpts::default()).unwrap();
        let div = rt.name_to_id["div"];
        assert!(matches!(
            rt.kind_tags[usize::from(div)],
            crate::runtime_impl::kind_tag::KindTag::CalcDivLevel
        ));
    }

    #[test]
    fn div_without_an_rhs_edge_keeps_the_general_dispatch_tag_defensively() {
        let weave = unchecked_weave(
            "unwired-divisor",
            vec![knot(
                "div",
                KnotKind::calc(CalcOp::Div, SignalDomain::Level),
            )],
            Vec::new(),
        );
        let runtime =
            Runtime::bind_validated(weave, BindOpts::default(), String::from("unwired-divisor"))
                .expect("the defensive bind phase can represent an unwired calc");

        assert!(matches!(
            runtime.kind_tags[0],
            crate::runtime_impl::kind_tag::KindTag::CalcDivLevel
        ));
    }

    #[test]
    fn sense_id_rejects_existing_non_sense_knots() {
        let mut b = Weave::builder("sense-id-kind").unwrap();
        b.knot("constant", KnotKind::constant(ONE, SignalDomain::Bool))
            .unwrap();
        let rt = Runtime::bind(b.build().unwrap(), BindOpts::default()).unwrap();

        assert_eq!(rt.sense_id("constant"), None);
    }
}