ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
//! THE WIRING WALK: what the created values are connected BY, and who will be running.
//!
//! [`Creation`](super::Creation) built the values — resources, slots, node structs — and knows
//! nothing about how they reach each other. This is the stage that reads the DECLARED topology and
//! turns it into edges: a bounded channel per node, a sending half per declared channel edge, a door
//! per query arm, a clock per poll upstream, and one registered shutdown party per running body.
//! Afterwards nothing is started; the [`Assembly`] it hands on is what the ignition round spends.
//!
//! # A channel per node, or one per SOURCE
//!
//! A node is fed through ONE inbox however many producers send into it — that is fan-in, and it is
//! what nearly every node is. A node whose declaration writes a `subscribe(…)` container is fed
//! through an INTAKE OF ITS OWN: one edge per declared upstream, so a slow upstream's full channel is
//! backpressure on that upstream and on nobody else, and the consumer waits on all of them at once.
//!
//! The walk cannot tell the two apart by looking: several inbound channel edges is either shape.
//! [`NodeWiring::drawing`](super::NodeWiring::drawing) is the declaration's answer, and it is what
//! [`resident`](Wiring::resident) reads before it asks for a producer's sending half —
//! [`source_of`](Wiring::source_of) turns that producer's edge into the slot it publishes to, by the
//! same declaration-order rule a [`PollUpstream`](crate::PollUpstream) position already follows. Every
//! edge here is keyed by `(node, upstream)` and the single-inbox world is the whole map at slot zero,
//! so the per-upstream shape is a widening rather than a change.
//!
//! THE EMITTED ENTRY SPELLS THE CONTAINER, and [`upstreams`](Wiring::upstreams) is where it reads
//! one: a mount asks for the node's WHOLE upstream set rather than for an inbox, and what comes back
//! is one receiving half per declared upstream where the declaration draws through an intake of its
//! own and the single fan-in edge where it does not. The set is indexed by POSITION, so an edge's
//! place in it is the slot its channel was opened at — the same declaration-order rule a producer's
//! send already follows, read from the consumer's end.
//!
//! What that still cannot reach is the HETEROGENEOUS container. [`Upstreams`] is a set of edges
//! carrying ONE message type, so a node whose input is the derive's `<Node>In` sum — whose arms are
//! its upstreams' several payloads — is not fed through it: that wants the by-key intake the driver
//! does not build, whose contract the topology emission states where an author reads it. A container
//! whose upstreams agree on their message is the whole of what arrives here today, and it is what
//! arm separation IS: one edge per upstream, so a slow one's full channel is backpressure on itself
//! and on nobody else.
//!
//! # The walk is DRIVEN, not looped — the same division the create walk keeps
//!
//! An edge's capacity is a number, but an edge's TYPE is the producer's output and the consumer's
//! input, and a graph carries names rather than types. So this layer holds the STEPS and the party
//! that knows the types spends them, one call per declared mount and per declared edge. The
//! type-erased registries below are what let a step minted under one node's name be handed back
//! typed to the node that reaches for it: [`Resources`](super::Resources)'s shape, one layer over.
//!
//! # A DATA edge is opened at what the declaration resolved to; a DOOR at the shipped constant
//!
//! [`Wiring::SHIPPED`] is what a data edge falls back to and [`Wiring::DOOR_CAPACITY`] is what every
//! query door is opened at. Between them sits the resolution: an author declares a default
//! (`channel = bounded(512)`), a deployment overrides it (`[node.channels]`), and the validate walk
//! settles the two into one [`ChannelOptions`] per edge — kind included, config over declared over
//! shipped. This stage READS that answer ([`Wired::channel`](super::Wired::channel)) and opens the
//! edge at it; it decides nothing itself, which is what keeps the precedence in one place.
//!
//! A DOOR has no such word yet. Doors are bounded edges by ruling and their shelf row is deferred
//! until they have shelf names of their own, so the constant is the whole of their story.
//!
//! # What a node's resident is given, and where each fact comes from
//!
//! [`Wiring::resident`] reads the DECLARATION and nothing else:
//!
//! - the NAME, from the arrangement;
//! - the [`Effect`], from the node's own [`NodeWiring`] — a node that lands through a storage
//!   co-subscriber has no lane to set it, so the declaration is the only authority;
//! - the [`AckMode`], folded over the node's inbound upstreams (see the method's note);
//! - and, beside it, the [`Schedule`] its declared poll upstreams state — read by
//!   [`Wiring::schedule`] off the same edges a tick's own identity is a position in;
//! - one [`publish`](Resident::publish) per declared CHANNEL out-edge whose consumer this deployment
//!   launches. A [`Changes`](Listen::Changes) edge is the consumer reading the producer's STORE and
//!   a [`Poll`](Listen::Poll) edge carries no messages at all, so neither is a send; a
//!   [`Transient`](Listen::Transient) edge is a door and is wired as one.
//!
//! What it does NOT attach is everything that changes the resident's TYPE — the write lane, the poll
//! context, the attribution, the ledger. Those name types this layer cannot, so they stay the
//! caller's: `.land(lane)` where the node's declaration holds one, `.polling(schedule, context)`
//! where it declared poll upstreams, and so on, exactly as a hand-wired arrangement spells them today.
//!
//! # The policy seats, and what sits in them
//!
//! Runtime behaviour is a declared POLICY seam — dyn-compatible traits, fallible, assembled at
//! launch, with the shipped defaults reproducing today's behaviour exactly. The set is stated once
//! on the [`Plan`](super::Plan) and this walk is where it is SPENT: every resident it builds is
//! handed the same [`Policies`](crate::Policies), so the four concerns answer with one voice across
//! an arrangement.
//!
//! - [`TickPolicy`](crate::TickPolicy) — the missed-tick posture, reached by the resident's own
//!   clock. Today's default is [`Coalesce`](crate::Coalesce), which is what both engines already do.
//! - [`RetryPolicy`](crate::RetryPolicy) — reached at
//!   [`Station::is_settled`](crate::Station::is_settled). Today's default is
//!   [`NoRetry`](crate::NoRetry): a held item comes back when its sender re-delivers.
//! - [`OverflowPolicy`](crate::OverflowPolicy) — a full bounded edge. Today's default is
//!   [`Backpressure`](crate::Backpressure), which is [`Outbox::deliver`](crate::Outbox::deliver)'s
//!   whole posture and the reason data is never droppable.
//! - [`DeadlinePolicy`](crate::DeadlinePolicy) — the per-door ambient budget, whose explicit half is
//!   the call site's own [`take_within`](crate::Awaiting::take_within) and beats it.
//!
//! Beside them, the tap seam: [`with_taps`](Wiring::with_taps) is where a deployment's
//! [`LifecycleTap`](crate::LifecycleTap)s join, and every resident this walk builds observes through
//! the same composite — which is also where a policy's own report goes.
//!
//! # What this stage leaves to the ignition round
//!
//! Starting anything. No thread is spawned, no [`Sweeper`](crate::Sweeper) runs, no upstream produces
//! — upstreams start LAST, which is what makes launch and shutdown the same dependency graph walked in
//! opposite directions. The [`Assembly`] carries the three things that walk needs: the filled
//! context, the cadences one sweep clock will serve, and the shutdown registry with its `N` already
//! exact.

use core::{
  any::{Any, type_name},
  time::Duration,
};

use std::{collections::BTreeMap, sync::Arc};

use agnostic_lite::RuntimeLite;
use smol_bytes::Utf8Bytes;

use crate::{
  Block, Driven, Operator,
  arrange::{EdgeId, NodeId},
  drive::{
    AckMode, Attached, Attaches, Attributes, Cadence, ChannelOptions, Door, Downstream, Helm,
    Inbox, Invokes, ItemId, Listen, Outbox, Policies, Registries, Resident, Runs, Schedule, Socket,
    StreamLane, StreamOptions, Streams, Taps, Thread, Unpolled, Upstreams, door, engine,
    lane::block_on, open,
  },
};

use super::{
  Context, Declared, Enrolled, Ignition, LaunchError, Resources, Shutdown, Staging, Wired,
  resources::released, teardown::farewell,
};

#[cfg(test)]
mod tests;

/// What [`Wiring::resident`] hands over for ONE node: the body that will run it, and the shutdown
/// enrolment that pairs with it.
///
/// The two travel together because they are one fact — a body that will be running is a party the
/// shutdown waits for — and the ignition spends them together, firing the enrolment when the
/// resident's loop returns.
pub type NodeBody<O, I = Inbox<ItemId, <O as Operator>::In>, M = Block> =
  (DeclaredResident<O, I, M>, Enrolled);

/// **THE RESIDENT A DECLARED BUFFERED NODE IS WIRED INTO** — every seat filled from the plan and
/// from the node's own facts, and nothing left for a caller to name but the lane.
///
/// Written as its own name rather than spelled inside [`NodeBody`], because a BOUND has to be able
/// to say it. [`Mount`](super::Mount)'s buffered cell states `Self: Drives + Send + 'static` over
/// this type — [`Ignition::resident_declared`](super::Ignition::resident_declared)'s own one bound,
/// carried up to the door that will call it — and that is what makes an attribution seat's
/// obligations reachable at all: they are `Drives`'s, on the projection the seat names, and a
/// where-clause that tried to spell them through `<Attribution as Attributes<Out>>::Root` is a
/// projection of a projection the trait solver will not take.
pub type DeclaredResident<O, I = Inbox<ItemId, <O as Operator>::In>, M = Block> =
  Resident<O, (), NodeAttribution<O, M>, (), Unpolled, Downstream<<O as Driven<M>>::Out>, I, M>;

/// **THE PROJECTION A BUFFERED NODE ATTRIBUTES ITS OUTPUTS THROUGH** — its own
/// [`Declared::Attribution`] seat, at the product its driven face states.
///
/// [`StreamWires`]'s arrangement one axis over, and written once for its reason: three signatures
/// would otherwise spell the two projections each, and a projection spelled three times is two
/// chances for one of them to drift. It is `()` for the declaration that wrote no `attributed` —
/// which is nearly every node, and which costs the resident nothing at all — and
/// [`RootProjection<Out>`](crate::RootProjection) for the one that did.
pub type NodeAttribution<O, M> = <O as Declared>::Attribution<<O as Driven<M>>::Out>;

/// What [`Wiring::lane`] hands over for one STREAMING node: the lane that will drive it, and the
/// shutdown enrolment that pairs with it.
///
/// [`NodeBody`]'s twin one face over, and it travels as a pair for the same reason: a body that will
/// be running is a party the shutdown waits for. The downstream set is [`StreamWires`] rather than a
/// parameter because it is the DECLARATION's — the node states the set it publishes through and the
/// walk fills it from the edges, so a caller that could supply its own would be naming a topology
/// the declaration does not have.
pub type StreamBody<O, X = Thread, M = Block> = (StreamLane<O, StreamWires<O, M>, X, M>, Enrolled);

/// **THE SET A STREAMING NODE PUBLISHES THROUGH** — its own [`Declared::Wires`] seat, at the product
/// its streaming face states.
///
/// Written once because six signatures would otherwise spell the two projections each, and a
/// projection spelled six times is five chances for one of them to drift. It is
/// [`Downstream<Out>`](Downstream) for the node that emits one thing — which is every streaming node
/// in this crate's own suites — and the emitted `<Node>Downstream` for a declaration that wrote
/// `emits = […]`.
pub type StreamWires<O, M> = <O as Declared>::Wires<<O as Streams<M>>::Out>;

/// **EVERYTHING THE PARTY THAT DRIVES A MOUNTED LANE IS HANDED**: the lane, the inbox its declared
/// upstreams fill, and the shutdown enrolment.
///
/// [`StreamBody`] plus the INBOX, and the third member is what makes the hand-over complete rather
/// than decorative. A lane is fed by [`admit`](crate::StreamLane::admit) and the walk cannot call it
/// — that is the loop no ignition door runs — so the half an upstream publishes into has to reach the
/// same hands, or a stream node mounted in a graph root would be a node nothing could deliver to.
///
/// The buffered pair needs no such triple: a [`Resident`] TAKES its inbox, because the loop that
/// drains one is the engine this layer does start.
pub type MountedLane<O, X = Thread, M = Block> = (
  StreamLane<O, StreamWires<O, M>, X, M>,
  Inbox<ItemId, <O as Streams<M>>::In>,
  Enrolled,
);

/// **WHAT [`Wiring::autonomous`] HANDS OVER FOR ONE AUTONOMOUS NODE**: the wheel with its three
/// seats filled, the far half of its stop line, and the shutdown enrolment.
///
/// [`NodeBody`]'s and [`MountBody`]'s shape at the third kind, with one member more — and the third
/// member is the whole of what makes an autonomous node windable-down. A body inside `run` for its
/// whole life reads no party announcement, so the world says the stop on its own line instead; the
/// [`Stopper`](crate::Stopper) therefore has to stay with the launch rather than travel onto the
/// engine inside the [`Helm`]. See [`Helm`]'s own note, which is where that division is written.
pub type AutonomousBody<O, M = Block> = (Helm<O, M>, crate::Stopper, Enrolled);

/// What [`Wiring::lane_mount`] hands over for one streaming node: the ACT of building its lane, and
/// the shutdown enrolment that pairs with it.
///
/// [`NodeBody`] and [`StreamBody`]'s shape, for their reason — a body that will be running is a
/// party the shutdown waits for — with the enrolment held BESIDE the act rather than inside it, so
/// that a world stopping while still carrying a lane nobody asked for can settle that party rather
/// than leave it unanswered.
pub type MountBody<O, X = Thread, M = Block> = (LaneMount<O, X, M>, Enrolled);

/// A mounted lane HELD AS THE ACT OF BUILDING IT — [`MountedLane`] one step before it exists.
///
/// What [`Wiring::lane_mount`] hands back and [`App::lane`](super::App::lane) spends, and the reason
/// it is the act rather than the lane is stated in full there: an awaited lane's TYPE is `!Send` by
/// the face's own design, so a launch that wanted to carry one across to the party that will drive
/// it had to carry the PARTS instead. Every one of them is `Send`, so this is — and the app that
/// holds it stays a value a spawn can take.
///
/// # The WARM SET is held beside the act rather than inside it, and that is the unwind's doing
///
/// A launch that refuses AFTER a lane was mounted has to say the goodbyes of everything it is
/// holding, and what it is holding here are the node's own instances. A closure that had swallowed
/// them would be a value the unwind could only DROP — so a `teardown` word on a streaming
/// declaration would go unsaid exactly when a deployment most wants to hear it. They sit in the open
/// instead, and [`into_instances`](Self::into_instances) is the door the unwind takes.
pub struct LaneMount<O, X = Thread, M = Block>
where
  O: Declared + Streams<M>,
{
  instances: Vec<O>,
  build: Box<dyn FnOnce(Vec<O>) -> Built<O, X, M> + Send>,
}

/// The two halves the act inside a [`LaneMount`] mints — the lane, and the inbox its declared
/// upstreams fill.
///
/// The shutdown ENROLMENT is not among them: it travels beside the mount rather than inside it, so
/// that a launch holding a lane nobody ever asks for can settle that party rather than leave it
/// unanswered — see [`App::lane`](super::App::lane), which puts the three back together for the
/// caller.
type Built<O, X, M> = (
  StreamLane<O, StreamWires<O, M>, X, M>,
  Inbox<ItemId, <O as Streams<M>>::In>,
);

/// What one lane is READ OFF THE PLAN for — the downstream set its declared out-edges make, and the
/// effect its declaration states.
type LaneParts<O> = (StreamWires<O, <O as Declared>::Mode>, crate::Effect);

/// Written rather than derived, for the reason [`Blueprint`](super::Blueprint)'s own is: what a
/// reader wants of a mount nobody has taken yet is HOW MUCH is waiting in it, and neither half
/// underneath prints anything at all.
impl<O, X, M> core::fmt::Debug for LaneMount<O, X, M>
where
  O: Declared + Streams<M>,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("LaneMount")
      .field("instances", &self.instances.len())
      .finish_non_exhaustive()
  }
}

impl<O, X, M> LaneMount<O, X, M>
where
  O: Declared + Streams<M>,
{
  /// How many warm bodies the lane will be built over.
  #[inline]
  #[must_use]
  pub fn instances(&self) -> usize {
    self.instances.len()
  }

  /// The node's own values, taken back — what a REFUSED launch stages the goodbyes of.
  #[inline]
  #[must_use]
  pub fn into_instances(self) -> Vec<O> {
    self.instances
  }

  /// Mint the lane, in the hands that will drive it — the lane, its inbox, and the `enrolled` party
  /// the caller held beside this act.
  ///
  /// The enrolment is a PARAMETER rather than a field for the reason [`MountBody`] states: a launch
  /// that has to let go of a lane nobody asked for still has to settle its party, and a party
  /// swallowed by this value would have gone with it.
  #[must_use]
  pub fn build(self, enrolled: Enrolled) -> MountedLane<O, X, M> {
    let Self { instances, build } = self;
    let (lane, intake) = build(instances);
    (lane, intake, enrolled)
  }
}

/// One node's data edge, erased: the sending half every producer clones, and the receiving half
/// until the node itself takes it.
///
/// The two are minted together and kept together, which is what makes a type mismatch answerable
/// without a downcast that could half-succeed: the sending half is asked first, and the receiving
/// half is known to match because nothing else could have put it there.
struct Wire {
  carries: &'static str,
  sender: Box<dyn Any + Send>,
  receiver: Option<Box<dyn Any + Send>>,
}

impl Wire {
  /// A data edge into a node whose input is `T`, opened at what that edge resolved to.
  fn data<T: Send + 'static>(spec: ChannelOptions) -> Self {
    let (outbox, inbox) = open::<ItemId, T>(spec);
    Self {
      carries: type_name::<Outbox<ItemId, T>>(),
      sender: Box::new(outbox),
      receiver: Some(Box::new(inbox)),
    }
  }

  /// A bounded QUERY door into a node that answers `T` with `R`.
  fn query<T: Send + 'static, R: Send + 'static>(capacity: usize) -> Self {
    let (door, invokes) = door::<T, R>(capacity);
    Self {
      carries: type_name::<Door<T, R>>(),
      sender: Box::new(door),
      receiver: Some(Box::new(invokes)),
    }
  }

  /// A clone of the sending half, or the refusal naming both types.
  fn sender<S: Clone + 'static>(&self) -> Result<S, EdgeTypeError> {
    self
      .sender
      .downcast_ref::<S>()
      .cloned()
      .ok_or_else(|| EdgeTypeError::new(self.carries, type_name::<S>()))
  }

  /// Whether the sending half is an `S`, without cloning one — what a step that wants the RECEIVER
  /// asks, so a mismatch is answered before anything is taken out.
  fn carries<S: 'static>(&self) -> Result<(), EdgeTypeError> {
    if self.sender.downcast_ref::<S>().is_some() {
      return Ok(());
    }
    Err(EdgeTypeError::new(self.carries, type_name::<S>()))
  }

  /// The receiving half, once — or the refusal saying it has already gone.
  fn receiver<R: 'static>(&mut self) -> Result<R, TakenInboxError> {
    self
      .receiver
      .take()
      .map(|receiver| {
        *receiver
          .downcast::<R>()
          .expect("both halves were minted together")
      })
      .ok_or_else(TakenInboxError::of::<R>)
  }
}

/// ONE out-edge offered to a downstream set — the walk's own [`Socket`], holding the map entry that
/// edge lives at.
///
/// It is a borrow rather than a value because the edge may not EXIST yet: the map entry is what
/// [`open`](Socket::open) mints into, and a socket that had copied a `Wire` out would be minting a
/// second one nobody could reach.
struct EdgeSocket<'w> {
  wires: &'w mut BTreeMap<(usize, usize), Wire>,
  key: (usize, usize),
  spec: ChannelOptions,
}

impl Socket for EdgeSocket<'_> {
  type Refusal = EdgeTypeError;

  #[inline]
  fn open<T>(&mut self) -> Result<Outbox<ItemId, T>, EdgeTypeError>
  where
    T: Send + 'static,
  {
    self
      .wires
      .entry(self.key)
      .or_insert_with(|| Wire::data::<T>(self.spec))
      .sender::<Outbox<ItemId, T>>()
  }

  #[inline]
  fn opened<T>(&mut self) -> Option<Outbox<ItemId, T>>
  where
    T: Send + 'static,
  {
    self
      .wires
      .get(&self.key)?
      .sender::<Outbox<ItemId, T>>()
      .ok()
  }
}

/// THE WIRING WALK over a created deployment: edges, clocks, and the shutdown registry.
///
/// Begun with [`Creation::wire`](super::Creation::wire), which is the only door — wiring what
/// nothing built is not a thing to spell — and ended with [`into_assembly`](Self::into_assembly),
/// which is what the ignition round starts.
///
/// # Examples
///
/// ```
/// use ingraph::{Context,
///   Delivery, DriverKind, Effect, FanoutKind, GraphBuilder, NodeWiring, Operator, Plan,
/// };
/// # use ingraph::Enablement;
///
/// struct Shout;
///
/// impl Operator for Shout {
///   type Error = core::convert::Infallible;
///   type In = String;
///   type Out = String;
///
///   fn accept(&mut self, ctx: &Context, delivery: Delivery<String>, emitter: &mut ingraph::Emitter<String>)
///     -> Result<(), Self::Error> {
///     for item in delivery.into_items() {
///       emitter.emit(item.into_value().to_uppercase());
///     }
///     Ok(())
///   }
/// }
///
/// # impl ingraph::Declared for Shout {
/// #   const EFFECT: Effect = Effect::Pure;
/// #   type Channels = ingraph::Unchanneled;
/// #   type Mode = ingraph::Block;
/// #   type Options = ();
/// #   type Pair = ingraph::Buffered;
/// #   type Wires<O> = ingraph::Downstream<O>;
/// #   type Attribution<O> = ();
/// # }
///
/// let mut builder = GraphBuilder::new();
/// let shout = builder.source::<Shout>("shout", DriverKind::Thread);
/// let titles = builder.node::<Shout>("titles", DriverKind::Thread);
/// builder.edge(&shout, &titles, FanoutKind::Broadcast);
/// # let graph = builder.validate().expect("two nodes validate");
/// # let plan = Plan::new(graph)
/// #   .with_enablement(Enablement::new().launching("shout").launching("titles"))
/// #   .wiring(titles.id(), NodeWiring::new(Effect::Lands).landing());
/// // A deployment that passed its checks and built its values.
/// let wired = plan.validate().expect("the deployment checks out");
/// let mut wiring = wired.create().wire();
///
/// // Each node's own inbox, minted at the shipped capacity.
/// let downstream = wiring
///   .inbox::<String>(titles.id())
///   .expect("nothing to refuse")
///   .expect("the deployment launches it");
/// let upstream = wiring
///   .inbox::<String>(shout.id())
///   .expect("nothing to refuse")
///   .expect("the deployment launches it");
///
/// // The producer's resident comes back already publishing over its declared edge.
/// let (resident, _enrolled) = wiring
///   .resident(shout.id(), Shout, upstream)
///   .expect("nothing to refuse")
///   .expect("the deployment launches it");
/// assert_eq!(resident.name().as_str(), "shout");
/// assert_eq!(resident.nudges().len(), 1);
///
/// // And the walk knows exactly who will be running.
/// let (_titles, _enrolled) = wiring
///   .resident(titles.id(), Shout, downstream)
///   .expect("nothing to refuse")
///   .expect("the deployment launches it");
/// let assembly = wiring.into_assembly();
/// assert_eq!(assembly.shutdown().len(), 2);
/// ```
#[derive(Debug)]
pub struct Wiring<'a> {
  wired: &'a Wired,
  ctx: Arc<Resources>,
  taps: Taps,
  // THE ROOT-KEY REGISTRIES this deployment coordinates through — built HERE, in the walk that
  // hands out everything a body needs, exactly as the taps and the policies are. Behind an `Arc`
  // because every resident gets the same one and the running world keeps it afterwards.
  registries: Arc<Registries>,
  // Keyed by `(node index, SOURCE POSITION)` and ORDERED, so what the walk hands the assembly does
  // not depend on a hash map's own order — the same reason the validate walk sorts its unknown
  // names. The position is zero for a node fed by one inbox however many producers, which is what
  // makes the per-upstream shape a widening rather than a change: fan-in is every producer at slot
  // zero, and a node with an intake of its own is one slot per declared upstream.
  wires: BTreeMap<(usize, usize), Wire>,
  doors: BTreeMap<usize, Wire>,
  cadences: Vec<Cadence>,
  shutdown: Shutdown,
}

impl<'a> Wiring<'a> {
  /// What every data edge is opened at, counted in DELIVERIES.
  ///
  /// A delivery may be a batch — [`ChangeIntake::PAGE`](crate::ChangeIntake::PAGE) is 256 items —
  /// so this is a bound on messages in flight and not on items: the memory an edge can hold is
  /// `CAPACITY × batch`, which at both shipped defaults is thousands of items rather than millions.
  /// Deep enough that an ordinary consumer hiccup does not stall its producer, shallow enough that a
  /// stalled consumer becomes backpressure while the queue is still a queue.
  ///
  /// It is the FLOOR rather than the whole story: an author's `channel = bounded(…)` and a
  /// deployment's `[node.channels]` both override it, and [`SHIPPED`](Self::SHIPPED) is this number
  /// wearing the vocabulary that resolution speaks.
  pub const CAPACITY: usize = 32;

  /// What an edge NOTHING SAID ANYTHING ABOUT is opened as — [`CAPACITY`](Self::CAPACITY), bounded.
  ///
  /// The bottom of the precedence, and the reason it is spelled as OPTIONS rather than as a number:
  /// the layers above it can change the KIND as readily as the depth, so the fallback has to be a
  /// value of the same vocabulary or the resolution would have a floor it could not express.
  pub const SHIPPED: ChannelOptions = ChannelOptions::Bounded(Self::CAPACITY);

  /// What every query door is opened at, counted in QUESTIONS.
  ///
  /// Its own constant because its pressure is the other one's opposite. A data edge's depth is a
  /// memory bound over items nobody is waiting on; a door's depth is a queue of callers who all ARE
  /// waiting, so depth there buys latency rather than throughput and a shallow door turns a
  /// question-storm into backpressure at the asker instead of a slow answer for everyone.
  pub const DOOR_CAPACITY: usize = 8;

  /// The walk over `wired`, with the context `create` filled, the taps it stated, and nothing
  /// connected yet.
  #[inline]
  pub(super) fn new(wired: &'a Wired, ctx: Resources, taps: Taps) -> Self {
    Self {
      wired,
      ctx: Arc::new(ctx),
      taps,
      // The shipped defaults, which is what a deployment that wrote no `[registry]` section runs.
      // `with_registries` is where an emitted launch hands over the one it read off its own
      // options, and it is called before any resident is wired.
      registries: Arc::new(Registries::default()),
      wires: BTreeMap::new(),
      doors: BTreeMap::new(),
      cadences: Vec::new(),
      shutdown: Shutdown::new(),
    }
  }

  /// Observe every resident this walk wires through `taps`.
  ///
  /// The one hook this stage assembles, and the shape the hook law rules for all of them: taps are
  /// composed at launch rather than implemented by a node, so the composite is built once here and
  /// each resident gets a clone of it.
  #[inline]
  #[must_use]
  pub fn with_taps(mut self, taps: Taps) -> Self {
    self.set_taps(taps);
    self
  }

  /// [`with_taps`](Self::with_taps), in place.
  #[inline]
  pub fn set_taps(&mut self, taps: Taps) -> &mut Self {
    self.taps = taps;
    self
  }

  /// The taps every resident from here on observes through.
  #[inline]
  #[must_use]
  pub const fn taps(&self) -> &Taps {
    &self.taps
  }

  /// **THE ROOT-KEY REGISTRIES** every resident this walk wires from here on coordinates through.
  ///
  /// The seam an emitted launch spends: `<Root>Options::registry()` is the document a deployment
  /// wrote, [`Registries::new`] is what turns it into the tables, and this is where those tables
  /// meet the walk that hands them out. A walk that is never told runs
  /// [`Registries::default`] — the shipped knobs, spelled out.
  ///
  /// Call it BEFORE wiring anything: a resident takes its handle as it is built, so a set made
  /// afterwards reaches only the bodies wired after it, exactly as [`with_taps`](Self::with_taps)'s
  /// does.
  #[inline]
  #[must_use]
  pub fn with_registries(mut self, registries: Arc<Registries>) -> Self {
    self.set_registries(registries);
    self
  }

  /// [`with_registries`](Self::with_registries), in place.
  #[inline]
  pub fn set_registries(&mut self, registries: Arc<Registries>) -> &mut Self {
    self.registries = registries;
    self
  }

  /// The registries every resident from here on coordinates through.
  #[inline]
  #[must_use]
  pub fn registries(&self) -> &Arc<Registries> {
    &self.registries
  }

  /// The policies every resident this walk builds runs under — the set the plan stated, read here
  /// rather than chosen here.
  ///
  /// One authority: the validate walk already refused the pairs that cannot work (an unbounded edge
  /// under a shedding policy), so what reaches this stage is a set that has been checked against
  /// the topology it is about to be wired into.
  #[inline]
  #[must_use]
  pub const fn policies(&self) -> &Policies {
    self.wired.policies()
  }

  /// `node`'s own inbox, opened at what its edge resolved to — or `None` where this deployment does
  /// not launch it.
  ///
  /// ONE inbox per node however many producers, which is what fan-in IS: several sending halves of
  /// this same edge. So it comes back once; asking twice is the refusal below.
  ///
  /// The edge is minted by whichever step reaches for it first — this one or
  /// [`outbox`](Self::outbox) — so a walk may wire a producer before its consumer or after, and
  /// neither order is the right one.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where the node's inbox has already been taken, or where `T` is not what
  /// the edge already carries — a producer's output type and its consumer's input type are ONE type,
  /// and a walk that spells them differently is naming a topology the declaration does not have.
  pub fn inbox<T>(&mut self, node: NodeId) -> Result<Option<Inbox<ItemId, T>>, LaunchError>
  where
    T: Send + 'static,
  {
    self.source_inbox(node, 0)
  }

  /// `node`'s inbox for the upstream at `upstream` — the PER-SOURCE edge a node with an intake of its
  /// own draws through.
  ///
  /// One edge per declared upstream, each with its own capacity, which is what keeps a slow upstream
  /// from stopping a fast one: a full edge is backpressure on the producer that filled it and on
  /// nobody else. The position is the upstream's place among this node's inbound CHANNEL edges —
  /// [`source_of`](Self::source_of) is what reads one off the declaration, and the same number is
  /// what a producer publishes to.
  ///
  /// [`inbox`](Self::inbox) is this at position zero, which is the whole of a single-upstream node's
  /// story and the whole of fan-in's.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`], on [`inbox`](Self::inbox)'s two conditions — asked twice, or asked
  /// for a type this edge does not carry.
  pub fn source_inbox<T>(
    &mut self,
    node: NodeId,
    upstream: usize,
  ) -> Result<Option<Inbox<ItemId, T>>, LaunchError>
  where
    T: Send + 'static,
  {
    let wired = self.wired;
    if !wired.is_enabled(node) {
      return Ok(None);
    }
    let spec = wired.channel(node, upstream);
    let wire = self
      .wires
      .entry((node.index(), upstream))
      .or_insert_with(|| Wire::data::<T>(spec));
    // The SENDING half is asked first, because it is the one that survives a mismatch: taking the
    // receiver and putting it back would be two chances to lose it.
    wire
      .carries::<Outbox<ItemId, T>>()
      .map_err(|error| LaunchError::wiring(name(wired, node), error))?;
    wire
      .receiver::<Inbox<ItemId, T>>()
      .map(Some)
      .map_err(|error| LaunchError::wiring(name(wired, node), error))
  }

  /// **`node`'s WHOLE UPSTREAM SET** — one receiving half per declared upstream where its
  /// declaration draws through an intake of its own, and the single fan-in edge where it does not.
  ///
  /// [`source_inbox`](Self::source_inbox)'s N-at-once door, and what the emitted container entry
  /// hands a body that owns its loop. [`Upstreams`] is indexed BY POSITION, and the position an edge
  /// lands at here is the slot its channel was opened at — [`source_of`](Self::source_of)'s
  /// declaration-order rule read from the consumer's end, so the arm a body selects on and the slot
  /// its producer publishes to are one number.
  ///
  /// The arity is the DECLARATION's and not the deployment's. An upstream this deployment leaves
  /// dark keeps its place, because the slots are counted off the graph's edges rather than off who
  /// is running — so a body armed over edge two is armed over the edge its own declaration named
  /// however many of its producers this deployment carries. A node with no inbound channel edge at
  /// all — a dataflow head — comes back holding the ONE edge its intake door publishes into, which
  /// is the edge [`inbox`](Self::inbox) would have handed over.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`], on [`inbox`](Self::inbox)'s two conditions, at whichever edge refuses.
  pub fn upstreams<T>(&mut self, node: NodeId) -> Result<Option<Upstreams<T>>, LaunchError>
  where
    T: Send + 'static,
  {
    if !self.wired.is_enabled(node) {
      return Ok(None);
    }
    // ONE edge is the FLOOR rather than a special case: a head has no inbound edge at all and is fed
    // all the same — through the slot its intake door publishes into — and a node whose declaration
    // states no intake of its own takes every producer on that same slot, which is what fan-in is.
    let arms = if self.apart(node) {
      self.arms(node).max(1)
    } else {
      1
    };
    let mut upstreams = Upstreams::new();
    for upstream in 0..arms {
      let Some(inbox) = self.source_inbox::<T>(node, upstream)? else {
        return Ok(None);
      };
      upstreams.attach(inbox);
    }
    Ok(Some(upstreams))
  }

  /// A sending half into `consumer`'s inbox — what a producer [`publish`](Resident::publish)es over,
  /// and what a change intake or a hand-held upstream delivers through.
  ///
  /// `None` where this deployment does not launch the consumer: an enabled producer with a dark
  /// consumer simply has one edge fewer, which is not a refusal — the reverse, a launched consumer
  /// listening to a dark producer, is what the validate walk already refused.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where `T` is not what the consumer's edge carries — see
  /// [`inbox`](Self::inbox).
  pub fn outbox<T>(&mut self, consumer: NodeId) -> Result<Option<Outbox<ItemId, T>>, LaunchError>
  where
    T: Send + 'static,
  {
    self.source_outbox(consumer, 0)
  }

  /// A sending half into `consumer`'s edge for the upstream at `upstream` — the other half of
  /// [`source_inbox`](Self::source_inbox).
  ///
  /// `None` where this deployment does not launch the consumer, exactly as
  /// [`outbox`](Self::outbox)'s is.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where `T` is not what that edge carries — see
  /// [`inbox`](Self::inbox).
  pub fn source_outbox<T>(
    &mut self,
    consumer: NodeId,
    upstream: usize,
  ) -> Result<Option<Outbox<ItemId, T>>, LaunchError>
  where
    T: Send + 'static,
  {
    let wired = self.wired;
    if !wired.is_enabled(consumer) {
      return Ok(None);
    }
    let spec = wired.channel(consumer, upstream);
    self
      .wires
      .entry((consumer.index(), upstream))
      .or_insert_with(|| Wire::data::<T>(spec))
      .sender::<Outbox<ItemId, T>>()
      .map(Some)
      .map_err(|error| LaunchError::wiring(name(wired, consumer), error))
  }

  /// WHICH of `consumer`'s upstreams `edge` is: its position among that node's inbound CHANNEL edges,
  /// in the graph's own edge order.
  ///
  /// The same convention a [`PollUpstream`](crate::PollUpstream) position already follows — declaration
  /// order, read off the edges rather than held anywhere — so a upstream's channel and a upstream's
  /// tick are numbered by one rule. `None` where `edge` is not one of this consumer's channel
  /// upstreams, which is a question about a topology the declaration does not have.
  ///
  /// Only CHANNEL edges are counted, for the reason the ack fold already gives: a changes listener
  /// reads the producer's store, a poll edge carries no messages, and a transient edge is a door —
  /// none of the three is a upstream anything is delivered on.
  #[must_use]
  pub fn source_of(&self, consumer: NodeId, edge: EdgeId) -> Option<usize> {
    self
      .wired
      .graph()
      .edges()
      .iter()
      .enumerate()
      .filter(|&(_, wire)| wire.to() == consumer)
      .filter(|&(index, _)| {
        self
          .wired
          .upstream(EdgeId::new(index))
          .is_some_and(|upstream| upstream.listen().is_channel())
      })
      .position(|(index, _)| EdgeId::new(index) == edge)
  }

  /// HOW MANY inbound CHANNEL edges `consumer` declared — the arity of its upstream set.
  ///
  /// [`source_of`](Self::source_of)'s own walk with the position dropped, and written beside it so
  /// the two cannot disagree: a slot that walk hands a producer is always one this count opened, and
  /// the three edge kinds it skips are skipped for the reason stated there.
  #[must_use]
  pub fn arms(&self, consumer: NodeId) -> usize {
    self
      .wired
      .graph()
      .edges()
      .iter()
      .enumerate()
      .filter(|&(_, wire)| wire.to() == consumer)
      .filter(|&(index, _)| {
        self
          .wired
          .upstream(EdgeId::new(index))
          .is_some_and(|upstream| upstream.listen().is_channel())
      })
      .count()
  }

  /// **AN ORIGIN'S ONE OUT-EDGE**, opened at what it produces — the sending half
  /// [`Ignition::origin_bridged`](super::Ignition::origin_bridged) hands the origin as its FEED.
  ///
  /// [`outbox`](Self::outbox) asks from the CONSUMER's end, which is what a walk that already knows
  /// who the consumer is spells. This asks from the ORIGIN's, because an emitted launch does not:
  /// the pairing is written in the consumer's own declaration and joined into the plan, so the walk
  /// reads the edge off the arrangement and answers under the origin's own
  /// [`Produced`](super::Produced) projection. That is the whole of what a root's one emitted line
  /// per origin field needs, and the reason there is no cell on this tier.
  ///
  /// # It reads the CHANNEL out-edges, and there is exactly one
  ///
  /// Zero, several, or an out-edge listened to by `changes`, `poll` or `transient` are all already
  /// refused at [`Plan::validate`](super::Plan) — [`PureLeaf`](super::Refusal::PureLeaf),
  /// [`SplitOrigin`](super::Refusal::SplitOrigin) and
  /// [`UnbridgedOrigin`](super::Refusal::UnbridgedOrigin) respectively — so a validated deployment
  /// reaches this door with one edge or does not reach it at all. `None` for any other count is the
  /// non-panicking floor under those three rows rather than a fourth answer.
  ///
  /// # `None` where either END is dark
  ///
  /// An origin this deployment does not launch has no feed, exactly as a node it does not launch has
  /// no inbox. So does an origin whose only CONSUMER is dark — an origin's feed IS its out-edge, so
  /// an origin with nowhere to send is an origin with nothing to be started for, and it is not
  /// mounted. Neither is a refusal: presence is enablement at both ends, and the validate walk's own
  /// rows are about the deployments that turn BOTH ends on.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where `T` is not what the consumer's edge carries — see
  /// [`inbox`](Self::inbox), whose two types this one names from the producer's side.
  pub fn bridge<T>(&mut self, origin: NodeId) -> Result<Option<Outbox<ItemId, T>>, LaunchError>
  where
    T: Send + 'static,
  {
    if !self.wired.is_enabled(origin) {
      return Ok(None);
    }
    let mut out = self
      .wired
      .graph()
      .edges()
      .iter()
      .enumerate()
      .filter(|&(_, wire)| wire.from() == origin)
      .filter(|&(index, _)| {
        self
          .wired
          .upstream(EdgeId::new(index))
          .is_some_and(|upstream| upstream.listen().is_channel())
      });
    let Some((index, wire)) = out.next() else {
      return Ok(None);
    };
    if out.next().is_some() {
      return Ok(None);
    }
    let consumer = wire.to();
    let Some(slot) = self.source_of(consumer, EdgeId::new(index)) else {
      return Ok(None);
    };
    self.source_outbox::<T>(consumer, slot)
  }

  /// `node`'s TRANSIENT inbox, minted at [`DOOR_CAPACITY`](Self::DOOR_CAPACITY) — what its query arm
  /// reads, and `None` where this deployment does not launch it.
  ///
  /// A query arm's inbox is not the node's data inbox and never becomes one: that separation is the
  /// read-path law, and it is why the two registries here are two.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`], on [`inbox`](Self::inbox)'s two conditions.
  pub fn invokes<T, R>(&mut self, node: NodeId) -> Result<Option<Invokes<T, R>>, LaunchError>
  where
    T: Send + 'static,
    R: Send + 'static,
  {
    let wired = self.wired;
    if !wired.is_enabled(node) {
      return Ok(None);
    }
    let capacity = Self::DOOR_CAPACITY;
    let gate = self
      .doors
      .entry(node.index())
      .or_insert_with(|| Wire::query::<T, R>(capacity));
    gate
      .carries::<Door<T, R>>()
      .map_err(|error| LaunchError::wiring(name(wired, node), error))?;
    gate
      .receiver::<Invokes<T, R>>()
      .map(Some)
      .map_err(|error| LaunchError::wiring(name(wired, node), error))
  }

  /// A door onto `node`'s query arm.
  ///
  /// One shape for both of its callers, which is the query lane's own point: an upstream query node
  /// holding one is doing exactly what a wire resolver outside the graph does, so the first hop of a
  /// chain and every hop after it are wired the same way.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where `T`/`R` are not what the node's door carries.
  pub fn door<T, R>(&mut self, node: NodeId) -> Result<Option<Door<T, R>>, LaunchError>
  where
    T: Send + 'static,
    R: Send + 'static,
  {
    let wired = self.wired;
    if !wired.is_enabled(node) {
      return Ok(None);
    }
    let capacity = Self::DOOR_CAPACITY;
    self
      .doors
      .entry(node.index())
      .or_insert_with(|| Wire::query::<T, R>(capacity))
      .sender::<Door<T, R>>()
      .map(Some)
      .map_err(|error| LaunchError::wiring(name(wired, node), error))
  }

  /// The resident for `node`, wired to the declared topology — and the shutdown enrolment that
  /// pairs with it.
  ///
  /// The two come back together because they are one fact: a body that will be running is a party
  /// the shutdown waits for, and registering it in a second call is a step somebody can forget. The
  /// ignition holds the [`Enrolled`] beside the engine it starts and fires it when the loop returns.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # What the caller still owes it
  ///
  /// Everything that changes the resident's TYPE, which is everything this layer cannot name: a
  /// node whose declaration [`holds_lane`](super::NodeWiring::holds_lane) is handed back declaring
  /// [`Effect::Lands`] and carrying no lane, and `.land(lane)` is what makes that declaration true.
  /// The walk cannot attach one — a lane is the author's type — so the honest thing it can do is
  /// say so here.
  ///
  /// # The ATTRIBUTION is no longer among them, because the declaration now names one
  ///
  /// A root projection is a type rather than a value, so a walk that has the type can build it: the
  /// seat is [`Declared::Attribution`] and the install below is UNCONDITIONAL, because `()` — what
  /// a declaration that wrote no `attributed` seats — satisfies the same bound the projection does
  /// and costs the resident a zero-sized field. That is the whole of what separates it from the
  /// lane: a lane is a VALUE only the author holds, and a projection is a FACT the declaration
  /// states.
  ///
  /// [`attributing`](Resident::attributing) stays public and stays the seat for the other road: an
  /// attribution that carries state — a journal writer, a queue, a handle — is a value no walk can
  /// mint, so a deployment with one seats `()` on the declaration and attaches its own here.
  /// Calling it after this door replaces what the seat installed, which is what makes the two roads
  /// compose rather than compete.
  ///
  /// # The ack mode is FOLDED, and toward the stronger of the two
  ///
  /// [`AckMode`] is ruled per SOURCE and a [`Resident`] carries one, so a node whose inbound upstreams
  /// disagree has to be given an answer. It is given [`Chained`](AckMode::Chained) if ANY of its
  /// message-carrying upstreams declared it: releasing early where a upstream asked to be chained would
  /// break a guarantee that upstream was promised, and holding longer than a
  /// [`Local`](AckMode::Local) upstream needed costs a window and breaks nothing.
  /// [`Poll`](Listen::Poll) and [`Transient`](Listen::Transient) upstreams are not read, for the
  /// reason [`UpstreamWiring::ack`](super::UpstreamWiring::ack) already states: neither carries items to
  /// release.
  ///
  /// # The MODE is the DECLARATION's, and this door takes no parameter for it
  ///
  /// [`Ignition::feeder`](super::Ignition::feeder)'s arrangement, at the other end of the same
  /// wiring: the face is read off `<O as Declared>::Mode` rather than inferred from whichever
  /// `Driven` row the caller's turbofish named. A free mode parameter here was a parameter nobody
  /// chose — inference had to guess it, and a type wearing BOTH faces gave it nothing to guess
  /// with, so a two-faced operator was `E0283` at a call that had already said which mode it meant
  /// on its own declaration.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where a declared consumer's edge does not carry this node's output —
  /// see [`inbox`](Self::inbox).
  pub fn resident<O, I>(
    &mut self,
    node: NodeId,
    operator: O,
    intake: I,
  ) -> Result<Option<NodeBody<O, I, <O as Declared>::Mode>>, LaunchError>
  where
    O: Declared + Driven<<O as Declared>::Mode>,
    <O as Driven<<O as Declared>::Mode>>::Out: Send + 'static,
    // THE SEAT, CASHED. A declaration that seats `()` pays this with the empty program; one that
    // wrote `attributed` pays it with the impl its own record emitted, and one that wrote the word
    // over an output no record declared is refused HERE, naming the payload the projection cannot
    // take a root out of.
    NodeAttribution<O, <O as Declared>::Mode>:
      Attributes<<O as Driven<<O as Declared>::Mode>>::Out>,
  {
    let Some(declared) = self
      .wired
      .node(node)
      .filter(|_| self.wired.is_enabled(node))
    else {
      return Ok(None);
    };
    // A second `&Wired`, so the loop below may borrow `self` mutably: the plan is behind a shared
    // reference this walk only reads through.
    let wired = self.wired;
    let mount = name(wired, node);
    let mut resident = Resident::new(mount, operator, intake)
      .with_effect(declared.effect())
      .with_ack(fold_ack(wired, node))
      .with_taps(self.taps.clone())
      // THE POLICY SET, wired here for the taps' reason: it is chosen once for the deployment and
      // spent per node, so the walk that holds it is the one that hands it out.
      .with_policies(wired.policies().clone())
      // THE ROOT-KEY REGISTRIES, wired here for the policies' reason and the taps': one object is
      // chosen for the deployment and a handle is spent per node, so the walk that holds it is the
      // one that hands it out.
      .with_registries(Arc::clone(&self.registries))
      // THE RUNTIME DOOR, wired here because this is the walk that holds the map: every node gets
      // the same one, so `ctx.shared::<R>()` inside `accept` reaches what the create walk built.
      .with_resources(Arc::clone(&self.ctx))
      // THE OBSERVATION LEVEL, which is the one thing here that is the NODE's rather than the
      // deployment's: the taps and the policies are chosen once for the whole arrangement, and this
      // came off `Declared::TRACING` — the declaration's own `tracing(level = …)` word.
      .with_tracing_level(declared.tracing_level())
      // THE ROOT PROJECTION, off the declaration's own `Declared::Attribution` seat and installed
      // for EVERY node. It is the observation level's own arrangement one seat over — a fact the
      // node states and this walk spends — and it is unconditional because the absence has a type:
      // a declaration that wrote no `attributed` seats `()`, whose `Attributes` impl is the empty
      // program and whose value is zero-sized, so the line below compiles and costs nothing for
      // every node that attributes nothing.
      .attributing(<NodeAttribution<O, <O as Declared>::Mode> as Default>::default());

    for (index, edge) in wired.graph().edges().iter().enumerate() {
      if edge.from() != node {
        continue;
      }
      // A CHANNEL edge is the only one a producer sends over. A changes listener reads this node's
      // STORE, a poll edge carries no messages at all, and a transient edge is a door — none of the
      // three is a message this resident dispatches.
      let sends = wired
        .upstream(EdgeId::new(index))
        .is_some_and(|upstream| upstream.listen().is_channel());
      if !sends {
        continue;
      }
      // WHICH of the consumer's edges this producer sends on. A consumer that draws through an
      // INTAKE OF ITS OWN takes each producer on the edge that producer declared, so a slow
      // upstream's full channel is backpressure on itself and on nobody else; a consumer without
      // one takes them all on its single inbox, which is fan-in and is what nearly every node is.
      // The declaration is the only authority — see [`NodeWiring::drawing`].
      let slot = self
        .apart(edge.to())
        .then(|| self.source_of(edge.to(), EdgeId::new(index)))
        .flatten()
        .unwrap_or(0);
      if let Some(outbox) =
        self.source_outbox::<<O as Driven<<O as Declared>::Mode>>::Out>(edge.to(), slot)?
      {
        resident = resident.publish(outbox);
      }
    }

    let enrolled = self.shutdown.register(mount);
    Ok(Some((resident, enrolled)))
  }

  /// **THE STREAM LANE for `node`**, wired to the declared topology — and the shutdown enrolment
  /// that pairs with it.
  ///
  /// [`resident`](Self::resident)'s twin for a node whose declaration wrote `stream`, and the
  /// answer to *what mounts a [`StreamOperator`](crate::StreamOperator)*: the name, the
  /// [`Effect`](crate::Effect), the downstream set and the taps are read off the declaration and the
  /// plan exactly as a resident's are, so the by-hand lane a deployment used to build becomes a lane
  /// the walk builds.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # What the CALLER supplies, and why each of the three is not the walk's
  ///
  /// * **the instances.** A lane holds N warm bodies and the create walk builds ONE value per mount,
  ///   because a construction is a fallible async call against a deployment's own options — so how
  ///   many of them there are is a question only the party holding the constructor can answer. The
  ///   honest count is the node's own [`in_flight`](StreamOptions::in_flight), which is what
  ///   [`StreamLane::width`] then reads back.
  /// * **the seats.** [`StreamOptions`] carries a [`FeedPolicy`](crate::FeedPolicy) and a
  ///   [`MemoryProbe`](crate::MemoryProbe), and both are framework-open trait objects a deployment
  ///   installs — there is no word for either and there is deliberately not going to be one, because
  ///   an attribute constant cannot name a policy. So the seats arrive HERE, at the runtime builder,
  ///   which is where every other trait-object seam in this stage arrives too.
  /// * **the spawner.** [`Spawn`](crate::Spawn) is the executor a BLOCKING run is placed on and it
  ///   is a seam for the same reason the poll words' executors are: a deployment's own pool is not
  ///   nameable from a declaration. The awaited face reads it not at all.
  ///
  /// # The MODE is the DECLARATION's, exactly as it is at [`resident`](Self::resident)
  ///
  /// The face is read off `<O as Declared>::Mode` rather than inferred from whichever
  /// [`Streams`](crate::Streams) row a turbofish named, so a body wearing BOTH streaming faces is
  /// mounted at the one its own word chose rather than being `E0283` at a call that had already
  /// said.
  ///
  /// # A STREAM NODE LANDS NOTHING, and the word is what keeps that true
  ///
  /// [`resident`](Self::resident) hands a node back declaring [`Effect::Lands`](crate::Effect) and
  /// carrying no lane, because `.land(lane)` is the caller's. There is no such door HERE: a
  /// [`StreamLane`] has no write-lane seat, which is exactly why the `stream` word is refused at the
  /// declaration on every kind that stores. What this door cannot check for you is the one shape a
  /// declaration cannot reach — a HAND-WRITTEN [`Declared`] stating `Lands` and mounted here, whose
  /// effect nothing would perform.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where a declared consumer's edge does not carry this node's output —
  /// see [`inbox`](Self::inbox).
  pub fn lane<O, I, X>(
    &mut self,
    node: NodeId,
    instances: I,
    options: StreamOptions,
    spawner: X,
  ) -> Result<Option<StreamBody<O, X, <O as Declared>::Mode>>, LaunchError>
  where
    O: Declared + Streams<<O as Declared>::Mode>,
    I: IntoIterator<Item = O>,
    <O as Streams<<O as Declared>::Mode>>::Out: Send + 'static,
    StreamWires<O, <O as Declared>::Mode>: Attaches,
  {
    let Some((downstream, effect)) = self.lane_parts::<O>(node)? else {
      return Ok(None);
    };
    let mount = name(self.wired, node);
    let lane = StreamLane::new(self.window(mount), options, instances, downstream, spawner)
      .with_effect(effect)
      .with_taps(self.taps.clone());
    let enrolled = self.shutdown.register(mount);
    Ok(Some((lane, enrolled)))
  }

  /// **THE LANE FOR `node`, HELD AS THE ACT OF BUILDING IT** — what a launch puts in the app's
  /// cupboard for the party that will drive it.
  ///
  /// [`lane`](Self::lane)'s walk to the last line, where it stops: the downstream set is read off the
  /// declaration HERE, at the wiring, because that is the only stage that holds the plan — and the
  /// [`StreamLane`] itself is minted LATER, in the hands of whoever takes it. Everything the mint
  /// needs travels in the closure, and [`App::lane`](super::App::lane) is where it is spent.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # Why the LANE cannot travel and the ACT can, and it is the awaited face's own doing
  ///
  /// A `StreamLane<…, Async>` holds its live runs as `Pin<Box<dyn Future>>` with no `Send` on it —
  /// which is the whole of what
  /// [`AsyncStreamOperator`](crate::AsyncStreamOperator) buys, a `!Send` body being an ordinary
  /// citizen at that face. So the TYPE is `!Send` even while the lane is empty, and an app that held
  /// one would be an app no `tokio::spawn` could take. What this door holds instead is the PARTS —
  /// the name, the seats, the warm set, the downstream set, the spawner — every one of which is
  /// `Send`, and the act that will put them together.
  ///
  /// # Errors
  ///
  /// [`lane`](Self::lane)'s, for its reason.
  pub fn lane_mount<O, I, X>(
    &mut self,
    node: NodeId,
    instances: I,
    options: StreamOptions,
    spawner: X,
    intake: Inbox<ItemId, <O as Streams<<O as Declared>::Mode>>::In>,
  ) -> Result<Option<MountBody<O, X, <O as Declared>::Mode>>, LaunchError>
  where
    O: Declared + Streams<<O as Declared>::Mode> + Send + 'static,
    I: IntoIterator<Item = O>,
    X: Send + 'static,
    <O as Streams<<O as Declared>::Mode>>::In: Send + 'static,
    <O as Streams<<O as Declared>::Mode>>::Out: Send + 'static,
    // The SET travels inside the act, and the act is `Send` for the reason this door exists at all
    // — so the set is too, and `'static` because the act outlives the walk that built it.
    StreamWires<O, <O as Declared>::Mode>: Attaches + Send + 'static,
  {
    let Some((downstream, effect)) = self.lane_parts::<O>(node)? else {
      return Ok(None);
    };
    // OWNED, unlike the sibling door's: the mount name is borrowed out of the plan and the act this
    // builds outlives the walk that holds it.
    let mount = Utf8Bytes::from(name(self.wired, node).to_owned());
    let taps = self.taps.clone();
    let enrolled = self.shutdown.register(mount.clone());
    let window = self.window(mount);
    Ok(Some((
      LaneMount {
        instances: instances.into_iter().collect(),
        build: Box::new(move |warm| {
          let lane = StreamLane::new(window, options, warm, downstream, spawner)
            .with_effect(effect)
            .with_taps(taps);
          (lane, intake)
        }),
      },
      enrolled,
    )))
  }

  /// **THE AUTONOMOUS BODY for `node`**, with its three seats filled — and the shutdown enrolment
  /// that pairs with it.
  ///
  /// [`resident`](Self::resident)'s and [`lane_mount`](Self::lane_mount)'s twin at the third kind,
  /// and the answer to *what mounts an [`AutonomousOperator`](crate::AutonomousOperator)*: the name,
  /// the downstream set and the taps are read off the declaration and the plan exactly as the other
  /// two read them, and the node's own [`ShutdownSignal`] line is minted here.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # What the CALLER supplies, and where a MOUNT gets it
  ///
  /// THE UPSTREAMS. [`Upstreams`] is a set of receiving halves, and which halves belong in it is a
  /// question about the node's declared edges — so it is a PARAMETER here, exactly as a lane's warm
  /// set is: a hand-wired arrangement attaches whichever edges it opened, and nothing about this
  /// door has to guess. [`upstreams`](Self::upstreams) is the walk that answers the question off the
  /// declaration, and it is what the emitted container entry hands in: one edge per declared
  /// upstream where the node draws through an intake of its own, the single fan-in edge where it
  /// does not.
  ///
  /// # THE STOPPER TRAVELS BESIDE THE BODY, and the launch is what keeps it
  ///
  /// A body inside `run` for its whole life reads no party announcement, so the wind-down reaches it
  /// on its [`ShutdownSignal`] — and the far half of that line must stay with the world rather than move onto
  /// the engine with the value. [`Ignition::autonomous_declared`](super::Ignition::autonomous_declared)
  /// is where it is joined to the shutdown.
  ///
  /// # A HAND-WRITTEN NODE CLAIMING `Lands` IS THE ONE SHAPE THIS DOOR CANNOT CHECK
  ///
  /// [`lane_mount`](Self::lane_mount)'s gap verbatim, for its reason: there is no write-lane seat
  /// here — an autonomous node publishes through its own downstream set and lands nothing of its own
  /// — which is why the `autonomous` word is refused at the declaration on every kind that stores.
  /// What survives that gate is a hand-written [`Declared`] stating
  /// [`Effect::Lands`](crate::Effect::Lands) and mounted here, whose effect nothing would perform.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where a declared consumer's edge does not carry this node's output —
  /// see [`inbox`](Self::inbox).
  pub fn autonomous<O>(
    &mut self,
    node: NodeId,
    operator: O,
    upstreams: Upstreams<<O as Runs<<O as Declared>::Mode>>::In>,
  ) -> Result<Option<AutonomousBody<O, <O as Declared>::Mode>>, LaunchError>
  where
    O: Declared + Runs<<O as Declared>::Mode>,
    <O as Runs<<O as Declared>::Mode>>::Out: Send + 'static,
  {
    // THE FRAMEWORK'S OWN SET, named in as many words rather than read off
    // [`Declared::Wires`](super::Declared::Wires) — the ruled narrowing, and the reason is that
    // [`Helm`] holds a `Downstream<Out>` in its own seat. No multi-product autonomous resident
    // exists in the plan, so the face keeps the one-product set it was built at; the door opens the
    // day a real one arrives, and what it opens is this line plus the seat on `Helm`.
    let Some((downstream, _effect)) =
      self.publishing::<Downstream<<O as Runs<<O as Declared>::Mode>>::Out>>(node)?
    else {
      return Ok(None);
    };
    // OWNED, for [`lane_mount`](Self::lane_mount)'s reason: the mount name is borrowed out of the
    // plan and the body this builds outlives the walk that holds it.
    let mount = Utf8Bytes::from(name(self.wired, node).to_owned());
    let enrolled = self.shutdown.register(mount.clone());
    let (stopper, halt) = crate::shutdown_signal();
    let helm = Helm::new(
      self.window(mount).halting(halt),
      operator,
      upstreams,
      downstream,
    );
    Ok(Some((helm, stopper, enrolled)))
  }

  /// **ONE NODE's WINDOW**, minted at its mount: the map this walk holds and the name the plan gave
  /// it, on a wind-down line of its own.
  ///
  /// The line is the private one [`Context::new`] mints, and a caller that has a REAL one puts it
  /// on with [`Context::halting`] — which is what the autonomous door does, and what a lane's every
  /// admission does per delivery. A window nobody replaces the line of simply never reads as
  /// stopping, which is the honest answer for a node the deployment winds down by closing its edges.
  fn window(&self, mount: impl Into<Utf8Bytes>) -> Context {
    Context::new(mount).sharing(Arc::clone(&self.ctx))
  }

  /// The two things a lane is READ OFF THE PLAN FOR: the downstream set its declared out-edges make,
  /// and the effect its declaration states.
  ///
  /// Written once because [`lane`](Self::lane) and [`lane_mount`](Self::lane_mount) differ in exactly
  /// when the lane is minted and in nothing else — a walk spelled at each would be two chances for
  /// the edge rules to drift between a lane built now and one built later.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # It builds the NODE'S OWN set, which is what the [`Declared::Wires`] seat bought
  ///
  /// The set is `<O as Declared>::Wires<Out>` and not [`Downstream`] in as many words, so a
  /// declaration that emits SEVERAL products is published through the set its own expansion minted —
  /// one edge LIST per product, each consumer on the edge it opened, and as many of them per product
  /// as the declaration's subscribers asked for. That set asks
  /// [`Sink::duplicate`](crate::Sink) PER PRODUCT, so a product with one subscriber is asked for no
  /// copy at all — which is why a mounted stream node's payload is no longer asked to [`Clone`]:
  /// [`Mount`](super::Mount)'s streaming cell states the relax and this walk is what earned it.
  ///
  /// A node that emits ONE thing seats `Downstream<Out>` and nothing about it moves: one product
  /// over N edges IS the fan-out, the copy is taken at the set, and the `Clone` is that set's own
  /// [`Sink`](crate::Sink) impl's rather than any cell's.
  fn lane_parts<O>(&mut self, node: NodeId) -> Result<Option<LaneParts<O>>, LaunchError>
  where
    O: Declared + Streams<<O as Declared>::Mode>,
    <O as Streams<<O as Declared>::Mode>>::Out: Send + 'static,
    StreamWires<O, <O as Declared>::Mode>: Attaches,
  {
    self.publishing::<StreamWires<O, <O as Declared>::Mode>>(node)
  }

  /// **WHAT A NODE PUBLISHES THROUGH**: the downstream set its declared out-edges make, and the
  /// effect its declaration states.
  ///
  /// The one walk every kind that carries a downstream set reads the plan through —
  /// [`lane_parts`](Self::lane_parts) at the streaming pair and
  /// [`autonomous`](Self::autonomous) at the third kind — because the three edge rules it keeps are
  /// the arrangement's rather than any driver's: only a CHANNEL edge is a send, a consumer with an
  /// intake of its own is published to at the slot its declaration numbered, and a dark consumer is
  /// one edge fewer rather than a refusal. A copy per kind would be as many chances for those to
  /// drift.
  ///
  /// It is generic over the SET rather than over the product, and that is the whole of what the
  /// [`Declared::Wires`] seat changed here. The walk cannot name a node's products — the set is an
  /// emitted type and this stage holds names rather than types — so it offers the set one SEAT per
  /// declared out-edge through [`Attaches`] and the set answers which product each one is. What
  /// used to be `Downstream<Out>` in as many words is now the one-product ANSWER to that question.
  ///
  /// `None` where this deployment does not launch the node.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] carrying an [`EdgeTypeError`] where a ONE-product set opened an edge
  /// that already carried another type, and a [`ProductSeatError`] where a SEVERAL-product set could
  /// not seat one: no product of it carries what the edge carries, the product it carries already
  /// has a consumer, or the edge has not been opened at all — see that type for what each means.
  fn publishing<W>(&mut self, node: NodeId) -> Result<Option<(W, crate::Effect)>, LaunchError>
  where
    W: Attaches,
  {
    let Some(declared) = self
      .wired
      .node(node)
      .filter(|_| self.wired.is_enabled(node))
    else {
      return Ok(None);
    };
    let effect = declared.effect();
    // A second `&Wired`, so the loop below may borrow `self` mutably — [`resident`](Self::resident)'s
    // own arrangement, for its reason.
    let wired = self.wired;
    let mut wires = W::default();
    for (index, edge) in wired.graph().edges().iter().enumerate() {
      if edge.from() != node {
        continue;
      }
      // A CHANNEL edge is the only one a producer sends over — [`resident`](Self::resident)'s walk
      // verbatim, because what any node puts on the wire is routed by the same three rules.
      let sends = wired
        .upstream(EdgeId::new(index))
        .is_some_and(|upstream| upstream.listen().is_channel());
      if !sends {
        continue;
      }
      // A DARK CONSUMER is one edge fewer rather than a refusal, and it is answered HERE rather
      // than inside the seat: a set that probed a consumer this deployment does not launch would
      // read the same `None` an unmatched product reads, and the two are not the same fact.
      let consumer = edge.to();
      if !wired.is_enabled(consumer) {
        continue;
      }
      let slot = self
        .apart(consumer)
        .then(|| self.source_of(consumer, EdgeId::new(index)))
        .flatten()
        .unwrap_or(0);
      let key = (consumer.index(), slot);
      // WAS IT ALREADY OPEN? Read before the seat is offered, because it is what tells a set's
      // *no product of mine carries this* from *nobody has opened this edge yet* — and the second
      // is a walk order rather than a topology, so it gets its own sentence.
      let opened = self.wires.get(&key).map(|wire| wire.carries);
      let mut socket = EdgeSocket {
        wires: &mut self.wires,
        key,
        spec: wired.channel(consumer, slot),
      };
      let seated = wires
        .attach(&mut socket)
        .map_err(|error| LaunchError::wiring(name(wired, node), error))?;
      match seated {
        Attached::Seated(_) => {}
        Attached::Occupied(product) => {
          return Err(LaunchError::wiring(
            name(wired, node),
            ProductSeatError::Occupied {
              set: type_name::<W>(),
              product,
            },
          ));
        }
        Attached::Foreign => {
          return Err(LaunchError::wiring(
            name(wired, node),
            match opened {
              Some(carries) => ProductSeatError::Foreign {
                set: type_name::<W>(),
                carries,
              },
              None => ProductSeatError::Unopened {
                set: type_name::<W>(),
                consumer: name(wired, consumer).to_owned().into(),
              },
            },
          ));
        }
      }
    }
    Ok(Some((wires, effect)))
  }

  /// Whether `consumer` draws its upstreams through an intake of its own — the declaration's own
  /// answer, and `false` for a node this deployment does not carry at all.
  fn apart(&self, consumer: NodeId) -> bool {
    self
      .wired
      .node(consumer)
      .is_some_and(|node| node.holds_intake())
  }

  /// The poll schedule `node` DECLARED: one interval per inbound
  /// [`Poll`](Listen::Poll) upstream, in the graph's own edge order.
  ///
  /// That order is what a [`PollUpstream`](crate::PollUpstream) position means, so reading the schedule
  /// off the same declaration the tick's identity comes from is what keeps a upstream from running at
  /// a cadence nobody asked for. It is what a caller hands
  /// [`Resident::polling`](crate::Resident::polling), and what [`clock`](Self::clock) rings the
  /// async engine's tickers on.
  ///
  /// It is a read of the DECLARATION and not of the deployment: a poll upstream over an upstream this
  /// deployment leaves dark is legal and keeps its place, because reaping does not need the dead
  /// alive.
  #[must_use]
  pub fn schedule(&self, node: NodeId) -> Schedule {
    self
      .wired
      .graph()
      .edges()
      .iter()
      .enumerate()
      .filter(|&(_, edge)| edge.to() == node)
      .filter_map(
        |(index, _)| match self.wired.upstream(EdgeId::new(index))?.listen() {
          Listen::Poll(every) => Some(every),
          Listen::Channel | Listen::Changes(_) | Listen::Transient => None,
        },
      )
      .fold(Schedule::new(), Schedule::every)
  }

  /// Register the ASYNC engine's clock for `node`: one ticker per declared poll upstream, plus the
  /// sweep.
  ///
  /// Answers how many cadences it added, which is `0` for a THREAD node and not an omission — a
  /// resident thread times itself, folding its own schedule into the timeout it was already
  /// computing, so a cadence for it would be a second clock saying what the first one says.
  ///
  /// The intervals come from [`schedule`](Self::schedule), so the clock this rings is the one the
  /// node's own resident was given. `sweep` does not: the liveness floor is the resident's own knob
  /// rather than anything the declaration states, so it is read off the value that carries it —
  /// [`Resident::sweep`].
  ///
  /// # Errors
  ///
  /// [`LaunchError::Wiring`] where `T` is not what the node's edge carries — the cadences ring the
  /// node's OWN inbox, so they are minted from its own sending half.
  pub fn clock<T>(&mut self, node: NodeId, sweep: Duration) -> Result<usize, LaunchError>
  where
    T: Send + 'static,
  {
    if !self.wired.is_enabled(node)
      || self.wired.graph().nodes()[node.index()]
        .driver()
        .is_thread()
    {
      return Ok(0);
    }
    let schedule = self.schedule(node);
    let Some(outbox) = self.outbox::<T>(node)? else {
      return Ok(0);
    };
    let before = self.cadences.len();
    self.cadences.extend(schedule.cadences(&outbox));
    // The liveness floor rides the same clock. An async task cannot time itself — flume has no async
    // deadline receive — so its sweep has to arrive as a message, and ONE clock serving every
    // registered cadence is what keeps that from becoming a clock per node.
    self
      .cadences
      .push(Cadence::new(sweep, Box::new(outbox.nudge())));
    Ok(self.cadences.len() - before)
  }

  /// Enrol a party called `name` in the shutdown registry, and hand back its own half.
  ///
  /// [`resident`](Self::resident) enrols the bodies it builds. This is the door for everything else
  /// that will be running when the launch returns and has to be waited for: a change intake, a query
  /// arm, a upstream the app itself holds.
  #[inline]
  pub fn enrol(&mut self, name: &str) -> Enrolled {
    self.shutdown.register(name)
  }

  /// The shared resources the create walk built.
  #[inline]
  #[must_use]
  pub fn context(&self) -> &Resources {
    &self.ctx
  }

  /// Who will be running, so far.
  #[inline]
  #[must_use]
  pub const fn shutdown(&self) -> &Shutdown {
    &self.shutdown
  }

  /// Freeze the wiring: the [`Assembly`] the ignition round starts.
  ///
  /// It keeps the sending half of every edge whose RECEIVER was taken, and drops whole the edges
  /// nobody took a receiver from — a channel with no reader is an edge this deployment does not
  /// have. Those kept halves are why an intake-less node stays alive to be started at all: a
  /// poll-only body has no producer, and a channel whose senders are all gone is a resident that
  /// stops before it runs. Closing them is the wave's first domino — see [`Assembly::close`].
  #[must_use]
  pub fn into_assembly(self) -> Assembly {
    let senders = self
      .wires
      .into_values()
      .chain(self.doors.into_values())
      .filter(|wire| wire.receiver.is_none())
      .map(|wire| wire.sender)
      .collect();
    Assembly {
      ctx: self.ctx,
      cadences: self.cadences,
      shutdown: self.shutdown,
      taps: self.taps,
      policies: self.wired.policies().clone(),
      registries: self.registries,
      senders,
    }
  }

  /// **THE PRE-IGNITION UNWIND**, this walk's half: say the goodbyes of everything the launch is
  /// holding, and hand `error` back UNCHANGED.
  ///
  /// [`Creation::unwind`](super::Creation::unwind)'s twin one stage on, and the values it says are
  /// the ones this stage has: a party that was WIRED and never ignited — staged as
  /// [`Resident::into_operator`](crate::Resident::into_operator) — beside whatever the create walk
  /// built and the wiring never reached. Nothing has an engine yet, so nothing has to be told to
  /// stop and no party is waited for; the chain simply consumes what the walk still owns.
  ///
  /// Order is the launch's own, backwards: the staged values last-staged first, then the RESOURCES,
  /// which were built before any of them. The enrolments this stage registered are dropped with it —
  /// a party that never ignited is a body that never ran, and there is nothing for a report to say
  /// about it.
  ///
  /// It is synchronous for [`Creation::unwind`](super::Creation::unwind)'s reason, which is the
  /// mobility of a goodbye rather than a preference.
  #[must_use]
  pub fn unwind(self, staged: Staging, error: LaunchError) -> LaunchError {
    let Self { ctx, taps, .. } = self;
    block_on(async {
      drop(farewell(staged.into_farewells(), &taps).await);
      drop(released(ctx, &taps).await);
    });
    error
  }
}

/// A wired deployment, ready to be started.
///
/// What the ignition round spends: the context that owns the resources, the cadences one sweep clock
/// serves, the shutdown registry whose `N` is already exact, and the sending halves the framework
/// holds so that nothing stops before it starts.
pub struct Assembly {
  ctx: Arc<Resources>,
  cadences: Vec<Cadence>,
  shutdown: Shutdown,
  taps: Taps,
  policies: Policies,
  /// The root-key registries every resident this walk built coordinates through, carried on so the
  /// running world can hand them out — see [`App::registries`](super::App::registries).
  registries: Arc<Registries>,
  senders: Vec<Box<dyn Any + Send>>,
}

impl Assembly {
  /// Begin the IGNITION with NO RUNTIME — put thread engines under the bodies, and start the upstreams
  /// last.
  ///
  /// One of the two doors onto [`Ignition`], which is what keeps a walk that STARTS reachable only
  /// from a deployment that has actually been wired.
  ///
  /// This is the door a THREAD-ONLY graph takes, and it names nothing: what it hands back is an
  /// `Ignition<Unruntimed>`, which puts thread engines under bodies, hands async bodies to whoever
  /// holds a runtime through [`Ignition::task`], and rings its cadences on a
  /// [`Sweeper`](crate::Sweeper) thread of the framework's own. A deployment that wants the framework
  /// to spawn its async bodies takes [`ignite_on`](Self::ignite_on) instead.
  #[inline]
  #[must_use]
  pub fn ignite(self) -> Ignition {
    Ignition::new(
      self.ctx,
      self.cadences,
      engine::hand_timer,
      self.shutdown,
      self.taps,
      self.registries,
      self.senders,
    )
  }

  /// Begin the IGNITION ON `R` — the deployment's runtime, named ONCE, here.
  ///
  /// The other door, and the whole of what a deployment writes to put its async nodes on its own
  /// runtime. What it changes is two things, both downstream of this one name:
  ///
  /// - [`Ignition::spawn`] exists, so the framework spawns an async body itself and HOLDS
  ///   its join for the shutdown, where the R-less walk can only hand the body back;
  /// - the cadence clock becomes an [`AfterClock`](crate::AfterClock) on `R`'s own timers, so an
  ///   async node's sweep and poll ticks are that runtime's business rather than a thread this crate
  ///   spawns to keep a timer wheel.
  ///
  /// Nothing else in a deployment mentions a runtime. That is the ruled shape — bundle at the door,
  /// narrow inside — and it is why the bound here is the whole [`RuntimeLite`] while the organs
  /// below it ask for the spawner and the After family alone.
  #[inline]
  #[must_use]
  pub fn ignite_on<R>(self) -> Ignition<R>
  where
    R: RuntimeLite,
  {
    Ignition::new(
      self.ctx,
      self.cadences,
      engine::after_clock::<R::AfterSpawner>,
      self.shutdown,
      self.taps,
      self.registries,
      self.senders,
    )
  }

  /// The shared resources, which this value keeps alive for as long as the deployment runs.
  #[inline]
  #[must_use]
  pub fn context(&self) -> &Resources {
    &self.ctx
  }

  /// The taps every resident this walk built observes through — and the ones the shutdown's own
  /// observations go to, so a deployment watching its nodes is watching their goodbyes too.
  #[inline]
  #[must_use]
  pub const fn taps(&self) -> &Taps {
    &self.taps
  }

  /// The policies this deployment runs under — carried on so the ignition round's own organs answer
  /// with the same voice the residents do.
  #[inline]
  #[must_use]
  pub const fn policies(&self) -> &Policies {
    &self.policies
  }

  /// The root-key registries this deployment coordinates through — the same object every resident
  /// this walk built is holding, and the one the running world hands out.
  #[inline]
  #[must_use]
  pub fn registries(&self) -> &Arc<Registries> {
    &self.registries
  }

  /// The cadences ONE clock will serve — an [`AfterClock`](crate::AfterClock) on the runtime where
  /// [`ignite_on`](Self::ignite_on) named one, a [`Sweeper`](crate::Sweeper) thread where
  /// [`ignite`](Self::ignite) named none.
  #[inline]
  #[must_use]
  pub fn cadences(&self) -> &[Cadence] {
    &self.cadences
  }

  /// Take them, for the clock the ignition starts.
  #[inline]
  #[must_use]
  pub fn take_cadences(&mut self) -> Vec<Cadence> {
    core::mem::take(&mut self.cadences)
  }

  /// Who the shutdown waits for.
  #[inline]
  #[must_use]
  pub const fn shutdown(&self) -> &Shutdown {
    &self.shutdown
  }

  /// The registry, for the ignition steps that enrol what they start.
  #[inline]
  pub const fn shutdown_mut(&mut self) -> &mut Shutdown {
    &mut self.shutdown
  }

  /// How many sending halves the framework still holds.
  #[inline]
  #[must_use]
  pub fn senders(&self) -> usize {
    self.senders.len()
  }

  /// Drop every one of them — the first domino of the shutdown wave.
  ///
  /// The ORDER of the wave is not orchestrated and does not need to be: a closed and drained inbox
  /// is what tells a resident there is nothing more coming, so releasing the framework's own halves
  /// lets the arrangement's real producers be the only thing holding anything open, and the wave
  /// propagates by data-flow causality from there. WHEN this is called relative to the wind-down
  /// announcement is the ignition round's sentence, not this value's.
  #[inline]
  pub fn close(&mut self) {
    self.senders.clear();
  }
}

impl core::fmt::Debug for Assembly {
  /// Arities, for [`Taps`]' own reason: what it holds is erased handles and somebody else's
  /// resources, neither of which has a [`Debug`](core::fmt::Debug) worth demanding.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Assembly")
      .field("resources", &self.ctx.len())
      .field("cadences", &self.cadences.len())
      .field("parties", &self.shutdown.len())
      .field("senders", &self.senders.len())
      .finish()
  }
}

/// An edge asked for under a type it does not carry.
///
/// A producer's output type and its consumer's input type are ONE type, so this is a walk naming a
/// topology the declaration does not have — impossible in an emission, which reads both ends off the
/// same declarations, and the reason a hand-wired arrangement gets a named refusal rather than a
/// panic. It serves both edge kinds: the types it prints are the whole handle, so a data edge names
/// its item and a door names its question and its answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display(
  "its edge is `{carries}` and this wiring asked for `{wanted}`; a producer's output type and its \
   consumer's input type are one type"
)]
pub struct EdgeTypeError {
  carries: &'static str,
  wanted: &'static str,
}

impl EdgeTypeError {
  /// The refusal an edge carrying `carries` gives a caller that asked for `wanted`.
  #[inline]
  const fn new(carries: &'static str, wanted: &'static str) -> Self {
    Self { carries, wanted }
  }

  /// What the edge carries — the compiler's own path for the handle.
  #[inline]
  #[must_use]
  pub const fn carries(&self) -> &'static str {
    self.carries
  }

  /// What the caller asked for.
  #[inline]
  #[must_use]
  pub const fn wanted(&self) -> &'static str {
    self.wanted
  }
}

impl core::error::Error for EdgeTypeError {}

/// A node's OWN downstream set could not seat one of its declared out-edges.
///
/// [`EdgeTypeError`]'s sibling at the SEVERAL-PRODUCT road, and it is a separate sentence because
/// the mistakes are separate. A one-product set OPENS the edges it is offered, so the only way it
/// can refuse is a type that disagrees with one already open. A node's own set — the emitted
/// `<Node>Downstream`, one edge list per declared product — takes the edge its CONSUMER opened, and
/// there are three ways that can fail to happen.
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::IsVariant)]
pub enum ProductSeatError {
  /// The edge carries something no product of this set does.
  ///
  /// A consumer subscribing to a product it named, whose own input type is not that product — the
  /// `out = "…"` word and the `In` beside it disagreeing, which is a topology the declaration does
  /// not have.
  #[display(
    "its edge is `{carries}` and no product of `{set}` carries it; an edge is a subscription to ONE \
     product, so a consumer's input type is the product its `out` word named"
  )]
  Foreign {
    /// The set that was offered the edge — the node's own, by the compiler's path for it.
    set: &'static str,
    /// What the edge carries — the compiler's own path for the sending half.
    carries: &'static str,
  },
  /// The product this edge carries already has a subscriber, and its PAYLOAD DOES NOT COPY.
  ///
  /// SEVERAL subscribers to one product is the ordinary topology — an A/B split, a canary beside the
  /// incumbent, a thumbnailer beside an embedder on one frame stream — and the fan serves it with no
  /// ceremony at all: the driver moves the output into the last edge that carries it and asks the
  /// product's own copy door for the ones before.
  ///
  /// This is the one corner the fan cannot reach. A product whose payload holds a decoded buffer or
  /// an open handle has no copy to give, so its door answers `None` and the SECOND subscriber has
  /// nothing to receive. It is refused by name here rather than served by dropping one of them, and
  /// the fix is the payload rather than the topology.
  #[display(
    "its product at {product} of `{set}` already has a subscriber and that product's payload does \
     not copy, so a second one would have nothing to receive; several subscribers to one product is \
     the ordinary road and each one past the first is served a COPY — make that payload `Clone`, \
     which for a decoded buffer or an open handle usually means an `Arc` or another refcounted \
     carrier"
  )]
  Occupied {
    /// The set that was offered the edge.
    set: &'static str,
    /// WHICH product, counting from zero in declaration order.
    product: usize,
  },
  /// The edge has not been opened at all, so there is nothing for the set to recognise.
  ///
  /// A WALK ORDER rather than a topology, and the one refusal here that a caller fixes by moving a
  /// line: a several-product set seats the product its consumer's own inbox named, so the consumer's
  /// receiving half has to have been taken first. Emitted arrangements take every mounted node's
  /// intake before any of them is wired, so this is a HAND-WIRED walk's sentence.
  #[display(
    "its edge into `{consumer}` has not been opened, and `{set}` seats the product that \
     consumer's own inbox names — take the consumer's receiving half before wiring this node"
  )]
  Unopened {
    /// The set that was offered the edge.
    set: &'static str,
    /// The mount whose edge was never opened.
    consumer: Utf8Bytes,
  },
}

impl core::error::Error for ProductSeatError {}

/// A node's receiving half, asked for twice.
///
/// A node has ONE inbox however many producers — fan-in is several SENDING halves of the same edge —
/// and one transient inbox for the same reason. So the receiving half comes back once, and a second
/// ask is a walk that has wired two bodies onto one node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display(
  "its `{inbox}` has already been taken; a node has one receiving half however many producers, and \
   fan-in is several sending halves of it"
)]
pub struct TakenInboxError {
  inbox: &'static str,
}

impl TakenInboxError {
  /// The refusal a second ask for `R` earns.
  #[inline]
  fn of<R>() -> Self {
    Self {
      inbox: type_name::<R>(),
    }
  }

  /// The receiving half that was already taken — the compiler's own path for it, so a reader can
  /// tell a data inbox from a transient one.
  #[inline]
  #[must_use]
  pub const fn inbox(&self) -> &'static str {
    self.inbox
  }
}

impl core::error::Error for TakenInboxError {}

/// `node`'s ack mode: [`Chained`](AckMode::Chained) if any message-carrying inbound upstream declared
/// it — see [`Wiring::resident`].
fn fold_ack(wired: &Wired, node: NodeId) -> AckMode {
  for (index, edge) in wired.graph().edges().iter().enumerate() {
    if edge.to() != node {
      continue;
    }
    let Some(upstream) = wired.upstream(EdgeId::new(index)) else {
      continue;
    };
    if matches!(upstream.listen(), Listen::Channel | Listen::Changes(_))
      && upstream.ack().is_chained()
    {
      return AckMode::Chained;
    }
  }
  AckMode::Local
}

impl core::fmt::Debug for Wire {
  /// What it carries and whether its reader has been taken — the two facts a walk's own debug output
  /// is after. The halves themselves are erased handles with no [`Debug`](core::fmt::Debug) to
  /// print, which is [`Taps`]' trade made one layer over.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Wire")
      .field("carries", &self.carries)
      .field("taken", &self.receiver.is_none())
      .finish()
  }
}

/// `node`'s declared name.
///
/// Reached only where [`Wired::is_enabled`] has already answered `true`, which is what makes the
/// index in range: a plan's enablement has exactly one entry per declared node.
fn name(wired: &Wired, node: NodeId) -> &str {
  wired.graph().nodes()[node.index()].name()
}