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
//! The launch floor: what a validated arrangement plus its options is allowed to become.
//!
//! # The walk COLLECTS
//!
//! [`Plan::validate`]'s checks are independent and side-effect-free, so it runs all of them and
//! hands back every [`Refusal`] at once — [`LaunchError::Refused`], never a first-fail. An operator
//! reading it fixes their deployment in ONE pass, which is the whole value of checking at start-up
//! rather than discovering the same list one restart at a time. The [`Creation`] walk that follows
//! is the opposite by its own nature: its steps build things, so its failures are not independent
//! and it stops at the first one.
//!
//! [`arrange`](crate::arrange) answers the questions a topology can be wrong about on its own — a
//! cycle, an exclusive edge that is not exclusive, an endpoint that names nothing. This module
//! answers the ones it cannot, because they need facts the graph does not carry:
//!
//! - a PURE LEAF. A node that computes and lands nothing, with nobody to publish to, is work whose
//!   result cannot be observed. The graph knows it has no out-edge; only the wiring knows it lands
//!   nothing. A node with a POLL upstream is exempt, and so is one with a QUERY ARM — neither
//!   exemption is a softening of the rule, see [`Plan::validate`].
//! - a CHANNEL LISTENER ON AN UPSTREAM THIS DEPLOYMENT DOES NOT LAUNCH. An unlaunched node sends
//!   nothing, so a consumer listening to its channel would wait forever with no way to notice —
//!   and PRESENCE IS ENABLEMENT, so the upstream is dark for the one reason there is: nobody wrote
//!   it a section. A consumer listening to its
//!   STORE is the opposite case and is legal, whether it listens by [`Changes`](Listen::Changes) or
//!   by [`Poll`](Listen::Poll): the rows are there, and reaching them is the reindex posture the
//!   multi-mode design exists for. Reaping does not need the dead alive either. A
//!   [`Transient`](Listen::Transient) listener is the channel case in the query lane's terms, and
//!   gets its own refusal because the advice differs — a store cannot stand in for an embedder.
//! - a LANDING WITH NOWHERE TO LAND. A node that declares [`Effect::Lands`] reaches durability
//!   either through its own write lane or through a storage co-subscriber it publishes to. The
//!   graph knows whether it publishes; only the wiring knows whether it holds a lane. A node with
//!   neither is claiming a durability nothing performs.
//! - a DEMANDED RESOURCE NOTHING DECLARED. [`Shared<R>`](crate::Shared) needs only that `R`
//!   implements [`AsyncResource`](crate::AsyncResource), which is hand-written — so a type can be shared
//!   without ever having joined the walk. Only a plan holds both halves: the declared set the walk
//!   collected, and the demands its enabled nodes state.
//!
//! What this module does NOT do is LOOP over what it builds. Constructing a node means naming its
//! type, and a graph carries names — so [`Creation`] holds the create walk's STEPS and the emission
//! that knows the types spends them, one call per declared mount. [`Wiring`] keeps the same
//! division for the same reason: an edge's capacity is a number, but an edge's TYPE is the
//! producer's output and the consumer's input, so the checked facts live here and the party that
//! can name them turns them into edges.
//!
//! # Rows this walk does not carry YET, and what each one is waiting for
//!
//! Every check here reads a fact a [`Plan`] already carries. Two ruled refusals read facts that
//! arrive with later rounds, and they are named here rather than sketched in code — a check with no
//! input to read is a promise, not a rule. (The third, the unbounded-edge-under-a-shedding-policy
//! contradiction, HAS its inputs now: the resolution is [`Wired::channel`] and the policy half is
//! the set a [`Plan`] states, so the row is a check —
//! [`Refusal::DroppingUnbounded`].)
//!
//! - **A demanded resource whose SECTION is missing.** The section half has ARRIVED — the spine
//!   carries a `[resources.<mount>]` block beside the node ones — and the refusal it earned landed
//!   one walk later, at [`Creation::declared_resource`], rather than here. The reason is the
//!   `Default` probe the ruling puts in front of it: an absent section runs the options at their own
//!   default, and whether a type HAS one is answerable only where the type is concrete
//!   ([`BareOptions`]' own tooth), which is the emitted call site and not a walk over names. So the
//!   row reads "no section and no default", and the only place that sentence can be spoken is where
//!   the probe was spelled.
//! - **An enabled node whose type cannot be constructed.** Ruled as a validate refusal by name, and
//!   the spine made it something better: naming `<T as AsyncConstructor>::Options` per mount is a
//!   COMPILE-time demand, so a declared node without the impl never reaches a start-up at all.
//!
//! # The CONSTRUCTION contract, beside the checks
//!
//! Three organs of the launch that are not checks live here as their own modules, because they are
//! what the walk this module validates for will spend: [`AsyncConstructor`], the capability a node's type
//! implements to be built at all; [`Resources`], the type-erased map a construction reaches its shared
//! resources through — published at the crate root, since the word is now its alone; and
//! [`NodeSection`], the per-node shelf a deployment's options arrive in.
//! [`Creation`] is what spends all three: the CREATE walk, reached from a [`Wired`] and nowhere
//! else.
//!
//! # And the WIRING that follows it
//!
//! [`Wiring`] is the next walk, reached from a [`Creation`] and nowhere else: it opens the edges the
//! created values reach each other over, registers the clocks the async engine's sweep will serve,
//! and builds the [`Shutdown`] registry — which lives here rather than with the ignition because
//! this is the moment `N` is known. What it hands on is an [`Assembly`], and starting that is the
//! ignition round's.

mod app;
mod channels;
mod constructor;
mod context;
mod create;
mod declared;
mod enablement;
mod feeder;
mod habitats;
mod ignition;
mod mount;
mod origin;
mod policies;
mod refusal;
mod resources;
mod section;
mod shutdown;
mod staging;
mod teardown;
mod wiring;

pub use app::{App, Stopped};
use channels::resolve_channels;
pub use channels::{ChannelShelf, Channels, Unchanneled};
pub use constructor::AsyncConstructor;
pub use context::Context;
pub use create::{
  BareOptions, Creation, MandatoryOptionsError, MandatoryResourceOptionsError, NoDefaultOptions,
  ResourceSourceError, UncataloguedResourceError,
};
pub use declared::{Blueprint, Declared, Grant, Upstream};
pub use enablement::Enablement;
pub use habitats::{
  AsyncInitialize, Habitats, Initialize, Initializes, MakesNothing, UnboundCorpus,
  UnbuiltTargetError,
};
pub use ignition::Ignition;
pub use mount::{Autonomous, Buffered, Cell, Mount, Streaming, Worn};
pub use resources::{MissingResourceError, Resources};
// The ORIGIN LAYER's own drivers — see the module note for why an awaited origin is pinned on a
// thread rather than spawned, and why the blocking face's driver is one line.
pub use origin::{
  Bridged, Died, Lived, Mounted, Ordered, Produced, Tuned, drive_awaited_origin, drive_origin,
};
pub use policies::{PolicyShelf, Unpoliced};
pub use refusal::{
  ArrangementError, DisabledUpstreamError, DroppingUnboundedError, FeederAbsentError,
  GrantsNoStoreError, LandsNowhereError, PureLeafError, Refusal, SplitOriginError,
  UnboundSlotError, UnbridgedOriginError, UndeclaredResourceError, UnknownGrantError,
  UnknownNodeError, UnknownUpstreamError,
};
pub use section::NodeSection;
pub use shutdown::{Enrolled, Party, Shutdown};
pub use staging::Staging;
use teardown::Farewell;
pub use teardown::{AsyncTeardown, BoxedError, Goodbye, Posted, Untorn};
pub use wiring::{
  Assembly, AutonomousBody, DeclaredResident, EdgeTypeError, LaneMount, MountBody, MountedLane,
  NodeAttribution, NodeBody, ProductSeatError, StreamBody, StreamWires, TakenInboxError, Wiring,
};

// The bare-section probe takes a MODULE path for the four gates' reason, written out at
// [`gate`](crate::gate): `#[macro_export]` publishes a macro at the crate ROOT, the shelf mirrors
// MODULES, and an emitted launch entry reaches every framework name through the shelf. So the
// crate-root macro is re-exported here, where the walk that spends it lives, and
// `__private::drive::bare_options` is what an expansion writes.
pub use crate::{bare_options, bare_origin_options, bare_resource_options};

use std::collections::{BTreeMap, BTreeSet, HashSet};

use smol_bytes::Utf8Bytes;

use crate::{
  arrange::{ChannelGraph, EdgeId, NodeId},
  drive::{AckMode, ChannelOptions, Effect, Failure, Feeder, Listen, Policies, TracingLevel},
  resource::{AsyncResource, ResourceCatalog, ResourceDemand, ResourceKind, ResourceName},
};

/// ONE CORPUS whose leg named NO resource — what the sole-default law is resolved for.
///
/// # It carries a NAME and a KIND, and neither is a type
///
/// The corpus is its durable name — `<index>__<field>__<label>`, the same string the emitted
/// [`Slot`](crate::Slot) marker holds and the same one a store makes a directory out of — because
/// what the binding produces is an OPEN, and an open is by name. The kind is which seam the leg
/// needs, which is the declaration's own kind and not a request's.
///
/// There is no `R` here, and that is the whole point: a bound leg names its resource as a TYPE at
/// the word, and this states the case where no type was written. What resolves it is the catalog,
/// which holds names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlotBinding {
  slot: Utf8Bytes,
  kind: ResourceKind,
}

impl SlotBinding {
  /// The corpus `slot` needs a resource that holds `kind`.
  #[must_use]
  pub fn new(slot: impl Into<Utf8Bytes>, kind: ResourceKind) -> Self {
    Self {
      slot: slot.into(),
      kind,
    }
  }

  /// The corpus, by its durable name.
  #[inline]
  #[must_use]
  pub const fn slot(&self) -> &Utf8Bytes {
    &self.slot
  }

  /// What it needs a resource to hold.
  #[inline]
  #[must_use]
  pub const fn kind(&self) -> ResourceKind {
    self.kind
  }
}

/// What a node declares beyond its place in the graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeWiring {
  effect: Effect,
  lane: bool,
  door: bool,
  intake: bool,
  /// Whether this node is an ORIGIN rather than an operator — see [`originating`](Self::originating),
  /// which is the only thing that sets it.
  origin: bool,
  /// The level this node's framework spans open at — the `tracing(level = …)` word, or the
  /// framework's own default where the declaration wrote none.
  tracing: TracingLevel,
}

impl NodeWiring {
  /// A node with `effect`.
  #[inline]
  #[must_use]
  pub const fn new(effect: Effect) -> Self {
    Self {
      effect,
      lane: false,
      door: false,
      intake: false,
      origin: false,
      tracing: TracingLevel::Info,
    }
  }

  /// It opens its framework spans at `level` — the `tracing(level = …)` word, carried from the
  /// node's own declaration.
  ///
  /// A separate word from everything else here, and the difference is what it governs: the others
  /// change what a node DOES, and this changes only how loudly the framework says it. A build with
  /// no observation compiled in carries the level and spends it nowhere.
  #[inline]
  #[must_use]
  pub const fn tracing(mut self, level: TracingLevel) -> Self {
    self.tracing = level;
    self
  }

  /// It holds its own write LANE.
  ///
  /// It also declares [`Effect::Lands`] — set here rather than asked for, which is the same trade
  /// [`Resident::land`](super::Resident::land) makes: a node holding a write lane lands by
  /// construction, and saying so in two places would be a fact two places could disagree about.
  ///
  /// Composes with [`answering`](Self::answering), a node that stores being free to answer
  /// questions too.
  #[inline]
  #[must_use]
  pub const fn landing(mut self) -> Self {
    self.effect = Effect::Lands;
    self.lane = true;
    self
  }

  /// A node with `effect` that also ANSWERS INVOKES at a door of its own.
  ///
  /// The door is a node fact and not an edge, because the party on its other end is not a node: a
  /// wire resolver holds a [`Door`](super::Door) and sends into the query node's transient inbox,
  /// exactly as an upstream query node would. Every hop AFTER the first is an ordinary
  /// [`Transient`](Listen::Transient) edge and needs no word here.
  ///
  /// It is the same shape a poll-only node already has: something outside the graph holds the
  /// handle that reaches it, and that is what its shutdown is too.
  #[inline]
  #[must_use]
  pub const fn answering(effect: Effect) -> Self {
    Self {
      effect,
      lane: false,
      door: true,
      intake: false,
      origin: false,
      tracing: TracingLevel::Info,
    }
  }

  /// It draws its upstreams through an INTAKE OF ITS OWN — one edge per declared upstream rather than
  /// one inbox for all of them.
  ///
  /// What a `subscribe(…)` container's node carries: the per-upstream channels the select waits on,
  /// and the by-key join behind the keyed ones. It is the fact the wiring walk cannot infer from
  /// the graph, because a node with several inbound channel edges is either this or an ordinary
  /// FAN-IN — several producers of ONE message type meeting on one edge — and only the declaration
  /// says which.
  ///
  /// Composes with everything here: an intake is about where a node's input comes from, and the
  /// lane, the door and the effect are about what it does with it.
  #[inline]
  #[must_use]
  pub const fn drawing(mut self) -> Self {
    self.intake = true;
    self
  }

  /// It is an ORIGIN — a [`Source`](crate::Source) or an [`AsyncSource`](crate::AsyncSource) — and
  /// not an operator.
  ///
  /// The one fact about a node that the graph text cannot show: an origin is a HEAD, and so is an
  /// operator that subscribes to nothing, so *has no inbound edge* does not tell them apart. What
  /// tells them apart is which door mounted it — [`Blueprint::origin`] states this, and nothing else
  /// does.
  ///
  /// # What it is READ for, and it is exactly one thing today
  ///
  /// The dead edge. An origin's out-edge is in the PLAN and the ignition never opens it — the
  /// origin's [`Feed`](crate::Feed) comes back in [`Mounted`], not in a consumer's inbox — so a
  /// deployment that enables both ends is claiming an edge nothing wires, and
  /// [`Refusal::UnbridgedOrigin`] is what says so. See [`Plan::validate`], where the row is found.
  ///
  /// It composes with nothing else here on purpose: an origin lands nothing, holds no lane, answers
  /// no door and draws no intake, so this word is the whole of what an origin's row adds to
  /// [`new`](Self::new)'s pure one.
  #[inline]
  #[must_use]
  pub const fn originating(mut self) -> Self {
    self.origin = true;
    self
  }

  /// What it does with what it produces.
  #[inline]
  #[must_use]
  pub const fn effect(&self) -> Effect {
    self.effect
  }

  /// Whether it holds a write lane of its own.
  ///
  /// The OTHER half of what [`Effect::Lands`] means. A landing node reaches durability either
  /// through its own lane or through a storage co-subscriber it publishes to, and only this says
  /// which — so a node that claims to land with neither is a claim nothing keeps.
  #[inline]
  #[must_use]
  pub const fn holds_lane(&self) -> bool {
    self.lane
  }

  /// Whether it answers invokes at a door of its own.
  #[inline]
  #[must_use]
  pub const fn answers(&self) -> bool {
    self.door
  }

  /// Whether it draws its upstreams through an intake of its own — see [`drawing`](Self::drawing).
  ///
  /// What a producer reads before it asks for a sending half: a consumer that holds one takes each
  /// producer on the EDGE THAT PRODUCER DECLARED, and a consumer that does not takes them all on
  /// one.
  #[inline]
  #[must_use]
  pub const fn holds_intake(&self) -> bool {
    self.intake
  }

  /// Whether it is an ORIGIN rather than an operator — see [`originating`](Self::originating).
  #[inline]
  #[must_use]
  pub const fn is_origin(&self) -> bool {
    self.origin
  }

  /// The level its framework spans open at — see [`tracing`](Self::tracing).
  #[inline]
  #[must_use]
  pub const fn tracing_level(&self) -> TracingLevel {
    self.tracing
  }
}

impl Default for NodeWiring {
  /// [`Pure`](Effect::Pure) and no door, which is the answer that gets CHECKED. A node that stores
  /// says so, a node that answers queries says so, and one that says neither and publishes to nobody
  /// is the refusal this default exists to produce.
  #[inline]
  fn default() -> Self {
    Self::new(Effect::Pure)
  }
}

/// What one inbound edge declares — the per-upstream words, mixable within one fan-in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UpstreamWiring {
  listen: Listen,
  ack: AckMode,
  channel: Option<ChannelOptions>,
}

impl UpstreamWiring {
  /// A upstream listened to as `listen`, released as `ack`, at whatever channel the layers around
  /// this declaration resolve to.
  #[inline]
  #[must_use]
  pub const fn new(listen: Listen, ack: AckMode) -> Self {
    Self {
      listen,
      ack,
      channel: None,
    }
  }

  /// The AUTHOR'S OWN DEFAULT for this edge — `channel = bounded(512)` as the declaration wrote it.
  ///
  /// A default rather than a law: a deployment's `[node.channels]` overrides it, kind included, and
  /// what stands where neither speaks is [`Wiring::SHIPPED`]. Unsaid is a state of its own — `None`
  /// is *this declaration said nothing*, which is what lets the layer under it be reached at all.
  #[inline]
  #[must_use]
  pub const fn with_channel(mut self, channel: ChannelOptions) -> Self {
    self.channel = Some(channel);
    self
  }

  /// What the DECLARATION said this edge should be opened as, or `None` where it said nothing.
  #[inline]
  #[must_use]
  pub const fn channel(&self) -> Option<ChannelOptions> {
    self.channel
  }

  /// How it is fed.
  #[inline]
  #[must_use]
  pub const fn listen(&self) -> Listen {
    self.listen
  }

  /// When its items are released.
  ///
  /// It is a fact about ITEMS, so a [`Poll`](Listen::Poll) upstream carries whatever it was given and
  /// nothing reads it: a poll edge moves no messages, so there is no window to hold and nothing to
  /// release. A [`Transient`](Listen::Transient) upstream is the same sentence for the opposite
  /// reason — it moves plenty, and none of it is owed an ack, the oneshot carrying the RESULT.
  /// Both are stated rather than refused: the ruled grammar puts no ack word inside either, and
  /// inventing a refusal for a combination the declaration cannot even spell would be this layer
  /// deciding a question the grammar has not been asked.
  #[inline]
  #[must_use]
  pub const fn ack(&self) -> AckMode {
    self.ack
  }
}

impl Default for UpstreamWiring {
  /// The record's two defaults: `listen(channel)` and `ack(local)`.
  #[inline]
  fn default() -> Self {
    Self::new(Listen::Channel, AckMode::Local)
  }
}

/// A validated arrangement plus the wiring and options it is to run under.
///
/// Built with the record's own defaults everywhere — every node [`Pure`](Effect::Pure), every upstream
/// [`Channel`](Listen::Channel) and [`Local`](AckMode::Local), and NOTHING LAUNCHED — and narrowed
/// from there. Defaults that get CHECKED, so a node that forgot to say it lands is refused rather
/// than quietly accepted.
///
/// The enablement default is the catalog principle rather than a cautious choice: presence is
/// enablement, so a plan nobody has named a node in is the empty deployment, which launches nothing
/// and is refused for nothing. What names them is [`with_enablement`](Self::with_enablement), fed
/// either by the emitted spine's own `enablement()` or by an [`Enablement`] assembled in code.
#[derive(Debug)]
pub struct Plan {
  graph: ChannelGraph,
  nodes: Vec<NodeWiring>,
  upstreams: Vec<UpstreamWiring>,
  enablement: Enablement,
  channels: Channels,
  policies: Policies,
  resources: ResourceCatalog,
  demands: Vec<(NodeId, ResourceDemand)>,
  mounts: Vec<ResourceDemand>,
  bindings: Vec<SlotBinding>,
}

impl Plan {
  /// A plan over `graph`, at every default.
  #[must_use]
  pub fn new(graph: ChannelGraph) -> Self {
    let nodes = vec![NodeWiring::default(); graph.nodes().len()];
    let upstreams = vec![UpstreamWiring::default(); graph.edges().len()];
    Self {
      graph,
      nodes,
      upstreams,
      enablement: Enablement::new(),
      channels: Channels::new(),
      policies: Policies::new(),
      resources: ResourceCatalog::new(),
      demands: Vec::new(),
      mounts: Vec::new(),
      bindings: Vec::new(),
    }
  }

  /// Wire the node `node`.
  ///
  /// A [`NodeId`] from another graph names nothing here and is ignored, which is the same posture
  /// [`ChannelGraph::node`] takes: a handle carries no builder identity, so the only honest answer
  /// to one that is out of range is that there is nothing to wire.
  #[must_use]
  pub fn wiring(mut self, node: NodeId, wiring: NodeWiring) -> Self {
    if let Some(slot) = self.nodes.get_mut(node.index()) {
      *slot = wiring;
    }
    self
  }

  /// Wire the inbound upstream `edge`.
  #[must_use]
  pub fn upstream(mut self, edge: EdgeId, wiring: UpstreamWiring) -> Self {
    if let Some(slot) = self.upstreams.get_mut(edge.index()) {
      *slot = wiring;
    }
    self
  }

  /// Run under `enablement`.
  #[inline]
  #[must_use]
  pub fn with_enablement(mut self, enablement: Enablement) -> Self {
    self.set_enablement(enablement);
    self
  }

  /// [`with_enablement`](Self::with_enablement), in place.
  #[inline]
  pub fn set_enablement(&mut self, enablement: Enablement) -> &mut Self {
    self.enablement = enablement;
    self
  }

  /// Which nodes this plan will run — the ones its options named, and no others.
  #[inline]
  #[must_use]
  pub const fn enablement(&self) -> &Enablement {
    &self.enablement
  }

  /// Run under `channels` — what a deployment TUNED its nodes' edges to.
  ///
  /// The config layer of the channel precedence, and the top one: what it names wins over the
  /// author's declared default and over the framework's shipped constant, kind included. Fed either
  /// by the emitted spine's own bridge or by a [`Channels`] assembled in code.
  #[inline]
  #[must_use]
  pub fn with_channels(mut self, channels: Channels) -> Self {
    self.set_channels(channels);
    self
  }

  /// [`with_channels`](Self::with_channels), in place.
  #[inline]
  pub fn set_channels(&mut self, channels: Channels) -> &mut Self {
    self.channels = channels;
    self
  }

  /// What this deployment tuned — the config layer, as it was handed over.
  #[inline]
  #[must_use]
  pub const fn channels(&self) -> &Channels {
    &self.channels
  }

  /// Run under `policies` — WHICH runtime behaviours this deployment chose, for all four concerns.
  ///
  /// Stated ONCE and here, which is what keeps the launch walk and the wiring walk from being able
  /// to disagree: the validate walk reads them (an unbounded edge under a shedding policy is a
  /// contradiction it refuses by name) and the wiring walk hands each resident the same set. What
  /// [`Policies::new`] holds is today's behaviour spelled out, so a plan that never calls this runs
  /// exactly as it always did.
  #[inline]
  #[must_use]
  pub fn with_policies(mut self, policies: Policies) -> Self {
    self.set_policies(policies);
    self
  }

  /// [`with_policies`](Self::with_policies), in place.
  #[inline]
  pub fn set_policies(&mut self, policies: Policies) -> &mut Self {
    self.policies = policies;
    self
  }

  /// The policies in force.
  #[inline]
  #[must_use]
  pub const fn policies(&self) -> &Policies {
    &self.policies
  }

  /// Run under `resources` — THE ROOT CATALOG, what a demand is cross-checked against and what the
  /// create walk reads a resource's declared source out of.
  ///
  /// # A deployment with an emitted root does not write this
  ///
  /// The root's own fields ARE the declared set, so `<Root>::launch` installs the catalog its
  /// declaration states, exactly as it installs the options' own enablement — and this replaces
  /// whatever the plan carried, for that same reason: two authorities for one list is one too many.
  /// What the seat is still for is a HAND-WIRED arrangement, which has no root to read a catalog
  /// off and states its own.
  #[inline]
  #[must_use]
  pub fn with_resources(mut self, resources: ResourceCatalog) -> Self {
    self.set_resources(resources);
    self
  }

  /// [`with_resources`](Self::with_resources), in place.
  #[inline]
  pub fn set_resources(&mut self, resources: ResourceCatalog) -> &mut Self {
    self.resources = resources;
    self
  }

  /// What the walk declared.
  #[inline]
  #[must_use]
  pub const fn resources(&self) -> &ResourceCatalog {
    &self.resources
  }

  /// `node` holds a `Shared<R>` field, and therefore DEMANDS `R`.
  ///
  /// Wiring rather than a value, so it APPENDS: a node reaching for two resources states two
  /// demands, exactly as a node publishing to two consumers gets two edges.
  ///
  /// A [`NodeId`] from another graph names nothing here and is kept anyway — the cross-check reads
  /// the wiring by index and an out-of-range one is unreachable, which is the same answer
  /// [`wiring`](Self::wiring) gives a handle it cannot place.
  #[must_use]
  pub fn demanding(mut self, node: NodeId, demand: ResourceDemand) -> Self {
    self.demands.push((node, demand));
    self
  }

  /// Every demand this plan carries, in the order it was wired.
  #[inline]
  pub fn demands(&self) -> impl Iterator<Item = (NodeId, ResourceDemand)> {
    self.demands.iter().copied()
  }

  /// A DECLARATION points at this resource, so THIS DEPLOYMENT MOUNTS IT — a demand with no node
  /// behind it.
  ///
  /// # Why a mount is a demand
  ///
  /// A resource is built for whoever will hold a [`Shared<R>`](crate::Shared), and a node's field is
  /// only the holder the graph can see. The other one is a search resolver: the application takes
  /// the handle out of the launched world and hands it to its wire layer, which no list the launch
  /// reads has any record of. So a deployment whose corpora are only READ had no way to ask for its
  /// own store, and what it got was a walk that made no homes and a first query that opened an index
  /// nobody had created.
  ///
  /// This is the ask, stated by the party that knows: the declaration that owns the corpora names
  /// the target in [`Habitats::TARGETS`], and an emitted launch spends one call here per row before
  /// the validate walk. A write mount and a read-only mount state it identically, which is the whole
  /// point — whether a node happens to land into the target is not a fact about whether the target
  /// has to exist.
  ///
  /// # What stays lazy
  ///
  /// Exactly one thing, and it is the one worth keeping: a resource NOTHING points at and no ENABLED
  /// node demands is never built. A catalog's unused models stay unloaded, and a deployment that
  /// switched an arm off owes neither its model nor its options section.
  ///
  /// Wiring rather than a value, so it APPENDS, on [`demanding`](Self::demanding)'s reason: one
  /// declaration may point at as many targets as it has legs.
  #[must_use]
  pub fn mounting(mut self, mount: ResourceDemand) -> Self {
    self.mounts.push(mount);
    self
  }

  /// Every MOUNT this plan carries — the targets its declarations point at, in the order they were
  /// stated.
  #[inline]
  pub fn mounts(&self) -> impl Iterator<Item = ResourceDemand> {
    self.mounts.iter().copied()
  }

  /// A CORPUS whose leg named no resource, to be bound by the SOLE-DEFAULT law.
  ///
  /// # What the plan is being told, and what it is not
  ///
  /// A leg that WROTE `resource = "…"` states nothing here: it is already bound, and the kind check
  /// that verifies it is a compile-time one at the word. What this states is the other case — a
  /// corpus that needs a resource of a KIND and named none — and the walk below resolves it against
  /// the deployment's own catalog: exactly one candidate binds, and zero or several is
  /// [`Refusal::UnboundSlot`].
  ///
  /// Wiring rather than a value, so it APPENDS, on [`demanding`](Self::demanding)'s reason: one
  /// declaration owns as many corpora as it has elections.
  #[must_use]
  pub fn binding(mut self, binding: SlotBinding) -> Self {
    self.bindings.push(binding);
    self
  }

  /// Every unbound corpus this plan carries, in the order it was wired.
  #[inline]
  pub fn bindings(&self) -> impl Iterator<Item = &SlotBinding> {
    self.bindings.iter()
  }

  /// Check the plan and freeze it.
  ///
  /// # The pure-leaf rule and the two things that are exempt from it
  ///
  /// The rule is about OBSERVABILITY, not about outputs: a node whose work leaves no trace anywhere
  /// is a node nobody can ask anything about, and that is what makes it a start-up refusal rather
  /// than a wasted cycle. A node with at least one POLL upstream leaves a trace by construction, and
  /// two of them: its declared schedule and grants say what it touches and on whose authority, and
  /// what it does with them reaches the same [`LifecycleTap`](super::LifecycleTap)s every other
  /// node's work does. A reaper writes stores it does not own; a watchdog writes nothing at all and
  /// exists to be observed. Refusing either would refuse the whole maintenance mode.
  ///
  /// # The landing rule is the pure-leaf rule from the other side
  ///
  /// [`Effect::Lands`] is reached by two postures, and the difference is WHOSE write: a node with
  /// its own lane writes, and a node without one is durable because a storage co-subscriber it
  /// publishes to writes. A node that declares the effect and has neither has said its outputs
  /// become durable and left nothing to make them so — and unlike a pure leaf, whose work is merely
  /// unobservable, this one's ack answers *persisted* for a write that never happens.
  ///
  /// The edge half is the graph's own out-edge, exactly the fact the pure-leaf rule reads. It is
  /// not followed to see whether the consumer really lands: [`Chained`](AckMode::Chained) composes
  /// hop by hop, so durability may be several hops away, and the ruled sentence is the one this
  /// walk can answer — no lane and no edge.
  ///
  /// # A QUERY ARM is the second exemption, and it is the same sentence
  ///
  /// A query-only node lands nothing, publishes to no durable consumer, and polls nothing — and
  /// its work is the most directly observed work in the arrangement, because somebody is HOLDING
  /// the other half of the oneshot it answers on. So a node with a transient arm leaves a trace by
  /// construction exactly as a polling one does: at the caller, and at the
  /// [`LifecycleTap`](super::LifecycleTap)s the [`QueryArm`](super::QueryArm) observes each answer
  /// through.
  ///
  /// It has two spellings because a query chain has two shapes of hop. A hop AFTER the first is fed
  /// by a [`Transient`](Listen::Transient) edge, which the graph carries. The FIRST hop is fed by a
  /// door whose other end is a wire resolver rather than a node, so the graph cannot carry it and
  /// [`NodeWiring::answering`] is what says it is there.
  ///
  /// Both are narrow on purpose. A pure leaf with no poll upstream, no transient inbound and no door
  /// is refused exactly as before — the exemptions are the schedule and the arm, so a node that
  /// declared neither has nothing to claim one by.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Refused`], carrying EVERY [`Refusal`] the walk found — see the module note for
  /// why the walk collects and the create walk after it does not, and [`Refusal`] itself for the
  /// rows and the order they come out in.
  pub fn validate(self) -> Result<Wired, LaunchError> {
    let Self {
      graph,
      nodes,
      upstreams,
      enablement,
      channels,
      policies,
      resources,
      demands,
      mounts,
      bindings,
    } = self;

    let mut refusals = Vec::new();

    // A name the arrangement does not have. Reported first, because everything after it describes
    // the deployment as literally written, in which the node a typo meant to name is ABSENT — and
    // an absent node is one that does not launch, which the rows below may well have something to
    // say about. SORTED, because a report's order may not be a hash map's.
    let declared: HashSet<&str> = graph.nodes().iter().map(crate::Node::name).collect();
    let mut unknown: Vec<&str> = enablement
      .names()
      .filter(|name| !declared.contains(name))
      .collect();
    unknown.sort_unstable();
    refusals.extend(
      unknown
        .into_iter()
        .map(|name| Refusal::UnknownNode(UnknownNodeError::new(Utf8Bytes::from(name.to_owned())))),
    );

    let enabled: Vec<bool> = graph
      .nodes()
      .iter()
      .map(|node| enablement.is_enabled(node.name()))
      .collect();

    // THE MOUNTS, first: a target a DECLARATION points at is one this deployment mounts, and a
    // mount is a demand with no node behind it — see `Plan::mounting` for the holder the graph
    // cannot see. Nothing cross-checks them against the catalog, and that is deliberate: a leg names
    // a TYPE where the catalog lists FIELDS, so the only walk that can tell whether the two met is
    // the create walk, which either has the mount in hand or refuses by name (`UnbuiltTargetError`).
    //
    // THE LAZY RULE, for the rest: a resource is relevant iff at least one ENABLED node demands it,
    // so a demand from a node this deployment does not launch asks for nothing and is checked
    // against nothing. Before the pure-leaf rule, because a node that cannot get its resource cannot
    // run at all, and a reader wants to be told that before being told what its output would not
    // have reached.
    //
    // The SAME pass answers the create walk's first question — which resources to build — because it
    // is the same question: what this deployment mounts and what its enabled nodes demand.
    // Collecting it here rather than deriving it a second time from the same rows is what keeps the
    // two from disagreeing.
    let mut demanded: BTreeSet<&str> = mounts
      .into_iter()
      .map(|mount| mount.resource().as_str())
      .collect();
    for (node, demand) in demands {
      if !enabled.get(node.index()).copied().unwrap_or(false) {
        continue;
      }
      demanded.insert(demand.resource().as_str());
      if !resources.declares(demand.resource()) {
        refusals.push(Refusal::UndeclaredResource(Box::new(
          UndeclaredResourceError::new(
            node,
            graph.nodes()[node.index()].name().into(),
            demand.resource(),
          ),
        )));
      }
    }

    // THE SOLE-DEFAULT LAW, resolved here because here is where the catalog is. A leg is written in
    // a library that cannot know which resources an application declared, so an unwritten binding
    // can only be decided where the deployment's own list exists — and the two failures are one
    // refusal with two sentences, because *nothing to bind* and *a choice that is yours* have
    // different fixes.
    //
    // AFTER the demand cross-check and before everything else, for the reading order this walk
    // keeps throughout: a corpus that cannot be bound is a corpus nothing can be written to or read
    // from, and the rows below describe a deployment in which that is already true.
    let mut bound: BTreeMap<Utf8Bytes, &'static ResourceName> = BTreeMap::new();
    for binding in bindings {
      match resources.sole(binding.kind()) {
        Some(resource) => {
          bound.insert(binding.slot().clone(), resource);
        }
        None => refusals.push(Refusal::UnboundSlot(Box::new(UnboundSlotError::new(
          binding.slot().clone(),
          binding.kind(),
          resources.candidates(binding.kind()).collect(),
        )))),
      }
    }

    let mut publishes = vec![false; graph.nodes().len()];
    let mut polls = vec![false; graph.nodes().len()];
    // A query arm, by either of its two spellings — see the doc comment for why the first hop of a
    // chain cannot be an edge. The DOOR half is read first because it is a node fact; the edge half
    // joins it below.
    let mut answers: Vec<bool> = nodes.iter().map(NodeWiring::answers).collect();
    for (index, edge) in graph.edges().iter().enumerate() {
      publishes[edge.from().index()] = true;
      if upstreams[index].listen().is_poll() {
        polls[edge.to().index()] = true;
      }
      if upstreams[index].listen().is_transient() {
        answers[edge.to().index()] = true;
      }
    }

    for (index, node) in graph.nodes().iter().enumerate() {
      if !enabled[index] {
        continue;
      }
      let wiring = nodes[index];
      if wiring.effect().is_pure() && !publishes[index] && !polls[index] && !answers[index] {
        refusals.push(Refusal::PureLeaf(PureLeafError::new(
          NodeId::new(index),
          node.name().into(),
        )));
      }
      // The same question from the other side — see the doc comment. A landing node reaches
      // durability through its own lane or through a storage co-subscriber, and this is a node that
      // declared neither.
      if wiring.effect().is_lands() && !wiring.holds_lane() && !publishes[index] {
        refusals.push(Refusal::LandsNowhere(LandsNowhereError::new(
          NodeId::new(index),
          node.name().into(),
        )));
      }
    }

    // THE FEEDER, for every DEFAULT change-feed edge. A feed reports what arrived and never who put
    // it there, so *somebody lands into that store* is the one fact the runtime cannot discover and
    // the declaration therefore states: absent the `external` word it is a claim about THIS graph,
    // and this is the walk that holds it to it.
    //
    // The test is the WATCHED node's own effect rather than its enablement, and deliberately: a
    // changes listener over an UNLAUNCHED lander is the reindex posture and is legal — the store
    // still holds everything that node wrote. What is refused is the store nothing in the graph ever
    // writes, which no restart fixes.
    for (index, edge) in graph.edges().iter().enumerate() {
      let consumer = edge.to().index();
      if !enabled[consumer] {
        continue;
      }
      let Listen::Changes(Feeder::InGraph) = upstreams[index].listen() else {
        continue;
      };
      let watched = edge.from().index();
      if nodes[watched].effect().is_lands() {
        continue;
      }
      refusals.push(Refusal::FeederAbsent(Box::new(FeederAbsentError::new(
        EdgeId::new(index),
        edge.to(),
        graph.nodes()[consumer].name().into(),
        edge.from(),
        graph.nodes()[watched].name().into(),
      ))));
    }

    for (index, edge) in graph.edges().iter().enumerate() {
      let consumer = edge.to().index();
      let producer = edge.from().index();
      if !enabled[consumer] || enabled[producer] {
        continue;
      }
      // A CHANGES or POLL listener over an unlaunched upstream is the intended case rather than an
      // oversight: the store still holds everything the upstream wrote, and draining it is what a
      // reindex is.
      // A reaper's case is the same sentence with nothing left to drain — collecting a dead node's
      // garbage is precisely the work that outlives the node.
      //
      // The two refusals below are ONE fact with two sentences, and the sentences differ because
      // the escape does. A starved channel listener has a store to fall back on; a starved query
      // edge has nothing — the dark node is an EMBEDDER, and there is no store holding the vectors
      // it would have made for a query nobody has asked yet.
      let starved = upstreams[index].listen();
      if starved.is_channel() || starved.is_transient() {
        let producer_name = graph.nodes()[producer].name();
        let refusal = Box::new(DisabledUpstreamError::new(
          EdgeId::new(index),
          edge.to(),
          graph.nodes()[consumer].name().into(),
          edge.from(),
          producer_name.into(),
        ));
        refusals.push(if starved.is_transient() {
          Refusal::DisabledQueryUpstream(refusal)
        } else {
          Refusal::DisabledUpstream(refusal)
        });
      }
    }

    // AN ORIGIN'S OUT-EDGES: the one shape the bridge opens, and the two it cannot.
    //
    // A CHANNEL edge from a launched origin to a launched consumer is opened — the origin's feed IS
    // that edge, so the items flow, the bound is the edge's own and the consumer's stream ends when
    // the origin's life does. That is the whole of the bridge, and this walk's job is now what is
    // LEFT: the deployments no bridge can serve.
    //
    // Both reads take the PRODUCER's own row rather than the graph's shape, and they have to: an
    // origin and an operator that subscribes to nothing are both heads, and only the door that
    // mounted one says which it was — see `NodeWiring::originating`. Neither edge is the mistake and
    // neither is refused in the arrangement: an origin with a consumer is exactly what keeps it from
    // being a leaf that computes into nothing. What is refused is a DEPLOYMENT that turns both ends
    // on.
    //
    // The word first, per edge. `changes`, `poll` and `transient` ask a producer for a store or a
    // door, and an origin's effect is the PURE one — it has neither.
    let mut listeners: Vec<Vec<Utf8Bytes>> = vec![Vec::new(); graph.nodes().len()];
    for (index, edge) in graph.edges().iter().enumerate() {
      let producer = edge.from().index();
      let consumer = edge.to().index();
      if !nodes[producer].is_origin() || !enabled[producer] || !enabled[consumer] {
        continue;
      }
      let listen = upstreams[index].listen();
      if listen.is_channel() {
        listeners[producer].push(graph.nodes()[consumer].name().into());
        continue;
      }
      refusals.push(Refusal::UnbridgedOrigin(Box::new(
        UnbridgedOriginError::new(
          EdgeId::new(index),
          edge.from(),
          graph.nodes()[producer].name().into(),
          edge.to(),
          graph.nodes()[consumer].name().into(),
          listen.as_str(),
        ),
      )));
    }
    // Then the ARITY, per origin. One feed becomes one edge, and copying a yield onto a second one
    // is the `Downstream` set's road, which demands a `Clone` the origin face declines to bound —
    // see `SplitOriginError`. Collected per producer rather than per edge, because the mistake is a
    // node's whole fan-out and not any one of the edges in it: a row per edge would tell the same
    // reader the same thing twice and name a different innocent consumer each time.
    for (index, consumers) in listeners.into_iter().enumerate() {
      if consumers.len() < 2 {
        continue;
      }
      refusals.push(Refusal::SplitOrigin(Box::new(SplitOriginError::new(
        NodeId::new(index),
        graph.nodes()[index].name().into(),
        consumers,
      ))));
    }

    // RESOLVED BEFORE THE ANSWER, because one row reads the resolution rather than any one layer's
    // word: an edge is unbounded because config said so, or because the declaration did, or because
    // both were silent and the shipped constant is — and the contradiction is about the edge that
    // results, not about who spelled it.
    let resolved = resolve_channels(&graph, &upstreams, &channels);

    // THE CONTRADICTION: an edge nothing bounds, under a policy that sheds. Nothing can overflow a
    // queue nothing bounds, so the shedding word would never fire — and a word that never fires is
    // worse than a refused one, because the deployment believes it is shedding and it is not. The
    // row is collected with the rest rather than thrown, so an operator sees it beside whatever
    // else is wrong.
    if policies.overflow_policy().sheds() {
      for (index, node) in graph.nodes().iter().enumerate() {
        if !enabled[index] {
          continue;
        }
        let Some(table) = resolved.get(index) else {
          continue;
        };
        refusals.extend(
          table
            .iter()
            .enumerate()
            .filter(|(_, spec)| spec.is_unbounded())
            .map(|(upstream, _)| {
              Refusal::DroppingUnbounded(Box::new(DroppingUnboundedError::new(
                NodeId::new(index),
                node.name().into(),
                upstream,
              )))
            }),
        );
      }
    }

    if !refusals.is_empty() {
      return Err(LaunchError::Refused(refusals));
    }

    Ok(Wired {
      graph,
      nodes,
      upstreams,
      enabled,
      channels: resolved,
      policies,
      resources,
      demanded,
      bound,
    })
  }
}

/// A checked plan: what runs, and how.
///
/// It carries no residents. Building one names an operator's input and output types, which only the
/// declaration knows — so this is what the emission reads to wire them, and what a hand-written
/// arrangement reads to wire them by hand.
#[derive(Debug)]
pub struct Wired {
  graph: ChannelGraph,
  nodes: Vec<NodeWiring>,
  upstreams: Vec<UpstreamWiring>,
  enabled: Vec<bool>,
  // RESOLVED at the validate walk and never again: one row per node, one entry per inbound CHANNEL
  // upstream in the graph's own edge order — which is the declaration order the shelf's fields and a
  // `PollUpstream`'s position both follow.
  channels: Vec<Vec<ChannelOptions>>,
  policies: Policies,
  resources: ResourceCatalog,
  demanded: BTreeSet<&'static str>,
  bound: BTreeMap<Utf8Bytes, &'static ResourceName>,
}

impl Wired {
  /// THE ROOT CATALOG this deployment was checked against — every declared resource, its mount and
  /// the ONE upstream its declaration named.
  ///
  /// Carried forward from the plan rather than re-collected, which is what keeps the walk that
  /// BUILDS a resource and the walk that cross-checked the demand for it reading one list.
  #[inline]
  #[must_use]
  pub const fn resources(&self) -> &ResourceCatalog {
    &self.resources
  }

  /// WHICH RESOURCE a corpus was bound to by the SOLE-DEFAULT law — `None` for a corpus this plan
  /// never stated, or one whose binding was refused.
  ///
  /// The answer the create walk opens a slot through: a leg that wrote `resource = "…"` is bound at
  /// the word and never reaches this map, so what is here is exactly what the deployment's catalog
  /// decided.
  #[inline]
  #[must_use]
  pub fn bound(&self, slot: &str) -> Option<&'static ResourceName> {
    self.bound.get(slot).copied()
  }

  /// Every corpus the sole-default law bound, in slot-name order.
  #[inline]
  pub fn bindings(&self) -> impl Iterator<Item = (&str, &'static ResourceName)> {
    self
      .bound
      .iter()
      .map(|(slot, resource)| (slot.as_str(), *resource))
  }

  /// Begin the CREATE walk — resources, then slots, then nodes.
  ///
  /// The only door onto [`Creation`], which is what keeps a walk that BUILDS reachable only from a
  /// deployment whose refusals have already been read.
  #[inline]
  #[must_use]
  pub fn create(&self) -> Creation<'_> {
    Creation::new(self)
  }

  /// The arrangement.
  #[inline]
  #[must_use]
  pub const fn graph(&self) -> &ChannelGraph {
    &self.graph
  }

  /// Whether this deployment builds `resource` — because a declaration MOUNTS it, or because an
  /// ENABLED node demands it.
  ///
  /// Carried forward from the pass that collected both rather than derived from them a second time,
  /// where the two could disagree.
  #[inline]
  #[must_use]
  pub fn demands(&self, resource: &ResourceName) -> bool {
    self.demanded.contains(resource.as_str())
  }

  /// Every resource this deployment will build, in name order.
  ///
  /// Two roads reach it and they are one list. A MOUNT is a target some declaration points at, and
  /// it is built whether or not any node writes into it — a read-only deployment's store is a store
  /// all the same. A DEMAND is a `Shared<R>` field on a node this deployment LAUNCHES; one on a node
  /// nobody named asks for nothing, which is the lazy law that keeps a catalog's unused models
  /// unloaded.
  #[inline]
  pub fn demanded(&self) -> impl Iterator<Item = &ResourceName> {
    self.demanded.iter().copied().map(ResourceName::new)
  }

  /// Every resource this deployment will build, UNDER THE MOUNT THE ROOT WROTE IT AT — and under
  /// its own name where nothing in the catalog declares it.
  ///
  /// **The type→mount join.** A demand is minted inside a member's own declaration
  /// ([`ResourceDemand::of`](crate::ResourceDemand::of)), which cannot see the root's field list, so
  /// the demand side has always been keyed by the compiler's path for the type while the declaration
  /// side has a mount. Both keys meet HERE, on a plan that carries the root's catalog, and this is
  /// the reading that spends the meeting: a report, a log line or a refusal that has this walk in
  /// hand names a resource the way the deployment's own document spells it.
  ///
  /// What it does NOT do is move the KEY. [`ResourceCatalog`] is still keyed by the type's path, and the
  /// swap to the mount is a mechanical one that changes no behaviour — it belongs to whichever round
  /// wants `type_name`'s unpromised spelling out of the enumeration, and it now has both halves it
  /// was waiting for.
  #[inline]
  pub fn demanded_at(&self) -> impl Iterator<Item = (&'static str, &ResourceName)> {
    self.demanded.iter().copied().map(|name| {
      let resource = ResourceName::new(name);
      (self.resources.mount(resource).unwrap_or(name), resource)
    })
  }

  /// Whether `node` runs.
  #[inline]
  #[must_use]
  pub fn is_enabled(&self, node: NodeId) -> bool {
    self.enabled.get(node.index()).copied().unwrap_or(false)
  }

  /// How `node` is wired.
  #[inline]
  #[must_use]
  pub fn node(&self, node: NodeId) -> Option<NodeWiring> {
    self.nodes.get(node.index()).copied()
  }

  /// How the inbound upstream `edge` is wired.
  #[inline]
  #[must_use]
  pub fn upstream(&self, edge: EdgeId) -> Option<UpstreamWiring> {
    self.upstreams.get(edge.index()).copied()
  }

  /// WHAT `node`'s edge at `upstream` RESOLVED TO — the answer the wiring walk opens it at.
  ///
  /// Post-precedence and total: config over the declaration over [`Wiring::SHIPPED`], so a position
  /// nobody said anything about answers the shipped constant rather than nothing. A position beyond
  /// this node's inbound channel upstreams answers the same, an edge that does not exist having
  /// nothing to have been declared about.
  ///
  /// This is the fact the contradiction row reads: an edge that resolved to
  /// [`Unbounded`](ChannelOptions::Unbounded) under a shedding
  /// [`OverflowPolicy`](crate::OverflowPolicy) is refused by name at the validate walk.
  #[must_use]
  pub fn channel(&self, node: NodeId, upstream: usize) -> ChannelOptions {
    self
      .channels
      .get(node.index())
      .and_then(|table| table.get(upstream))
      .copied()
      .unwrap_or(Wiring::SHIPPED)
  }

  /// The policies this deployment runs under — what the wiring walk hands every resident.
  #[inline]
  #[must_use]
  pub const fn policies(&self) -> &Policies {
    &self.policies
  }

  /// Every node that runs, in declaration order.
  #[inline]
  pub fn running(&self) -> impl Iterator<Item = NodeId> {
    self
      .enabled
      .iter()
      .enumerate()
      .filter(|&(_, on)| *on)
      .map(|(index, _)| NodeId::new(index))
  }
}

/// Why a launch did not happen — the validate walk's WHOLE answer, or the create walk's FIRST.
///
/// The two halves refuse differently because they are different kinds of walk. Validate's checks are
/// independent and side-effect-free, so it collects and an operator fixes their deployment in one
/// pass instead of restarting into the next refusal; what one of its rows says is a [`Refusal`].
/// Create BUILDS, so its second step runs in a world its first one made, and it stops where it
/// stands — carrying the typed refusal, erased through [`Failure`](crate::Failure), under the name
/// of whatever could not be built.
///
/// It is `non_exhaustive`: the ignition round is still to come and may have a sentence of its own,
/// exactly as the wiring one turned out to.
///
/// Neither `Clone` nor `PartialEq`, and the create half is why: an author's construction error is
/// held erased, and a boxed `dyn Error` neither copies nor compares. What a test reads instead is
/// the variant, the name it carries and the rendering — which is what an operator reads too.
#[derive(Debug, derive_more::IsVariant)]
#[non_exhaustive]
pub enum LaunchError {
  /// The validate walk's whole answer: every independent, side-effect-free check that refused.
  Refused(Vec<Refusal>),
  /// A demanded resource could not be loaded, so nothing that reaches for it can be constructed.
  ///
  /// Three refusals wear it, and the erased error says which: the resource's own
  /// [`build`](AsyncResource::build) refused; its options had no source to come from; or a door was
  /// spent that its declaration did not name, which is the single-source law's own sentence.
  ///
  /// Its own variant rather than a node's, because a resource is loaded for whoever demanded it and
  /// naming one of them would be naming a party that is not the one that failed. The record spells
  /// the NODE sentence; this is the neighbouring one the ruled sequence needs, spelled the same
  /// way.
  ///
  /// It is named for the ACT and not for the thing, and that is measured rather than stylistic: a
  /// variant called `AsyncResource` shares its last segment with the [`AsyncResource`](crate::AsyncResource)
  /// TRAIT, which drops the name out of rustc's trimmed-path map — so every diagnostic anywhere
  /// mentioning the trait starts printing `ingraph::AsyncResource` instead of `AsyncResource`.
  /// `tests/shared_resources`' committed fixtures are where that showed up, and they are what pins
  /// it.
  Loading {
    /// The resource that could not be loaded.
    resource: &'static ResourceName,
    /// Its own refusal, erased.
    error: Failure,
  },
  /// A resource's LAYER-TWO WALK refused — the homes its declarations describe could not be made.
  ///
  /// The initialization round's own sentence, and it is the [`Loading`](Self::Loading) family's
  /// neighbour rather than a node's: what failed is a TARGET's own machine — a corpus that would not
  /// be created, an index the engine refused to shape — and naming one of the declarations it was
  /// shown would name a party that is not the one that failed.
  ///
  /// It is raised INSIDE the create walk's own fallible phase, so everything the launch had already
  /// built says its goodbyes on the way out: the pre-ignition unwind, unchanged.
  Initializing {
    /// The resource whose walk refused.
    resource: &'static ResourceName,
    /// Its machine's own refusal, erased.
    error: Failure,
  },
  /// A node's own construction refused, or its section left mandatory knobs unwritten.
  ///
  /// The create walk stops here. Everything it had already built DROPS as this propagates, which is
  /// the failed launch's teardown for every declaration that does not enrol in an explicit one.
  Construction {
    /// The mount whose node could not be built.
    node: Utf8Bytes,
    /// The node's own refusal, erased.
    error: Failure,
  },
  /// An edge could not be connected the way the walk spelled it.
  ///
  /// The wiring walk's own fail-fast, for [`Construction`](Self::Construction)'s reason: its steps
  /// mint things, so the ones after a failure would be describing a topology that was never built.
  /// What it carries is an [`EdgeTypeError`] or a [`TakenInboxError`] — a walk naming a topology the
  /// declaration does not have, which an emission cannot spell and a hand-wired arrangement can.
  Wiring {
    /// The mount whose edge could not be connected.
    node: Utf8Bytes,
    /// Which way it did not fit, erased.
    error: Failure,
  },
  /// A body could not be STARTED — the machine refused its engine.
  ///
  /// The ignition's own fail-fast, and the last of the four. What it carries is a
  /// [`std::io::Error`](std::io::Error) from the spawn, under the name of the node whose engine it
  /// was — nothing about it is the deployment's mistake, which is why the sentence reports what the
  /// machine said rather than advising a fix.
  ///
  /// It is the one refusal that can be raised with part of the deployment already RUNNING, and it
  /// arrives having dealt with that: [`Ignition::unwind`] winds the already-ignited parties down and
  /// waits for them before this error is handed back, so a caller holding one holds a deployment
  /// that has stopped. How the unwind itself went is on the taps, not in here — the error a failed
  /// launch reports is the failure, never the tidying after it.
  Ignition {
    /// The mount whose engine did not start.
    node: Utf8Bytes,
    /// What the machine said, erased.
    error: Failure,
  },
}

impl LaunchError {
  /// Every refusal this carries, in the walk's own order — empty for a CREATE failure, which
  /// refuses with one thing rather than a list.
  #[inline]
  #[must_use]
  pub fn refusals(&self) -> &[Refusal] {
    match self {
      Self::Refused(refusals) => refusals,
      Self::Loading { .. }
      | Self::Initializing { .. }
      | Self::Construction { .. }
      | Self::Wiring { .. }
      | Self::Ignition { .. } => &[],
    }
  }

  /// The create walk's refusal for `R`.
  ///
  /// The error is its OWN parameter rather than `R::Error`, because the resource step refuses for
  /// three reasons and only one of them is the author's: a build that failed, options with no
  /// source to come from, and a door the declaration did not name. All three are the same sentence
  /// — this resource could not be loaded, and here is why — so they are one variant with the
  /// framework's own errors erased through it exactly as the author's is.
  #[inline]
  pub(super) fn loading<R, E>(error: E) -> Self
  where
    R: AsyncResource,
    E: core::error::Error + Send + Sync + 'static,
  {
    Self::Loading {
      resource: ResourceName::of::<R>(),
      error: Failure::new(error),
    }
  }

  /// LAYER TWO's refusal for the target `R`.
  ///
  /// The error is its own parameter for [`loading`](Self::loading)'s reason: what refused is the
  /// AUTHOR's slot maker, reporting in its own currency, and the launch family erases it exactly as
  /// it erases a resource's own `build`.
  #[inline]
  pub(super) fn initializing<R, E>(error: E) -> Self
  where
    R: AsyncResource,
    E: core::error::Error + Send + Sync + 'static,
  {
    Self::Initializing {
      resource: ResourceName::of::<R>(),
      error: Failure::new(error),
    }
  }

  /// The create walk's refusal for the node mounted at `node`.
  #[inline]
  pub(super) fn construction<E>(node: &str, error: E) -> Self
  where
    E: core::error::Error + Send + Sync + 'static,
  {
    Self::Construction {
      node: Utf8Bytes::from(node.to_owned()),
      error: Failure::new(error),
    }
  }

  /// The wiring walk's refusal for the node mounted at `node`.
  #[inline]
  pub(super) fn wiring<E>(node: &str, error: E) -> Self
  where
    E: core::error::Error + Send + Sync + 'static,
  {
    Self::Wiring {
      node: Utf8Bytes::from(node.to_owned()),
      error: Failure::new(error),
    }
  }

  /// The ignition's refusal for the node mounted at `node`.
  #[inline]
  pub(super) fn ignition<E>(node: &str, error: E) -> Self
  where
    E: core::error::Error + Send + Sync + 'static,
  {
    Self::Ignition {
      node: Utf8Bytes::from(node.to_owned()),
      error: Failure::new(error),
    }
  }
}

/// Written rather than derived per variant, which is the idiom [`Refusal`] itself keeps: a variant
/// whose payload is a LIST has no one-line sentence, and rendering it as one would bury the rows
/// under commas. One row per line, each already carrying its own advice.
///
/// The create half is one line for the opposite reason — there is one thing wrong, and the sentence
/// is the name plus what the author's own error said.
impl core::fmt::Display for LaunchError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Refused(refusals) => {
        write!(f, "launch refused: {} thing(s) to fix", refusals.len())?;
        for refusal in refusals {
          write!(f, "\n  - {refusal}")?;
        }
        Ok(())
      }
      Self::Loading { resource, error } => write!(
        f,
        "the resource `{}` could not be loaded: {error}",
        resource.as_str()
      ),
      Self::Initializing { resource, error } => write!(
        f,
        "the resource `{}` could not make the homes its declarations describe: {error}",
        resource.as_str()
      ),
      Self::Construction { node, error } => {
        write!(
          f,
          "the node `{}` could not be built: {error}",
          node.as_str()
        )
      }
      Self::Wiring { node, error } => {
        write!(
          f,
          "the node `{}` could not be wired: {error}",
          node.as_str()
        )
      }
      Self::Ignition { node, error } => {
        write!(
          f,
          "the node `{}` could not be started: {error}",
          node.as_str()
        )
      }
    }
  }
}

impl core::error::Error for LaunchError {
  /// The create half's typed source, kept walkable: [`Failure`](crate::Failure) preserves the
  /// author's own error under its erasure, so a caller that knows the type can still reach it.
  #[inline]
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Refused(_) => None,
      Self::Loading { error, .. }
      | Self::Initializing { error, .. }
      | Self::Construction { error, .. }
      | Self::Wiring { error, .. }
      | Self::Ignition { error, .. } => Some(error),
    }
  }
}

#[cfg(test)]
mod honesty_tests;
#[cfg(test)]
mod tests;