ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
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
//! What the tower's expansion says, read off its tokens.
//!
//! The expansion's BEHAVIOUR — that a broken chain is `E0277` on the step that broke it, that a
//! lying face word is the same refusal, that a mixed tower walks — is asserted where it can only be
//! asserted, by `ingraph`'s own corpus, which declares real towers and real breaks. What is here is
//! what a token stream can be read for: which faces the chain demands, at which types, what the
//! walk's signature is, and what its body does at every hop.

use super::{Fan, Router, Stage, StepModel, TowerModel};

/// A step, written the way the grammar hands one over.
///
/// SEGMENT-FREE, which is what every step in this file is: today's towers are the degenerate case of
/// the amendment, and the tests that are about a stage build theirs explicitly.
fn step(field: &str, ty: proc_macro2::TokenStream, answer: proc_macro2::TokenStream) -> StepModel {
  StepModel {
    field: quote::format_ident!("{field}"),
    ty: syn::parse2(ty).expect("the step's type parses"),
    answer: Some(syn::parse2(answer).expect("the step's answer parses")),
    awaited: false,
    fan: None,
    annotation: None,
  }
}

/// ⟂ A step that opens the ANNOTATION stage — no `answer` word, the front end refusing one there,
/// and the annotation's own type in the seat that carries it.
fn annotating(
  field: &str,
  ty: proc_macro2::TokenStream,
  of: proc_macro2::TokenStream,
) -> StepModel {
  StepModel {
    field: quote::format_ident!("{field}"),
    ty: syn::parse2(ty).expect("the step's type parses"),
    answer: None,
    awaited: false,
    fan: None,
    annotation: Some(syn::parse2(of).expect("the annotation's type parses")),
  }
}

/// THE MIXED TOWER: a blocking tokenizer feeding an awaited encoder, which is the shape the per-step
/// face word exists for.
fn clip_text() -> TowerModel {
  TowerModel {
    krate: syn::parse_quote!(::ingraph),
    name: syn::parse_quote!(ClipText),
    vis: syn::parse_quote!(pub),
    question: Some(syn::parse_quote!(String)),
    answer: None,
    steps: vec![
      step(
        "tokenize",
        quote::quote!(Tokenize),
        quote::quote!(Vec<String>),
      ),
      StepModel {
        awaited: true,
        ..step(
          "encode",
          quote::quote!(ClipTextTower),
          quote::quote!(Vec<f32>),
        )
      },
    ],
  }
}

/// The emitted tokens with every space taken out and the WALK'S DOC stripped.
///
/// The doc is dropped rather than tolerated because its own prose names the very types a claim here
/// is about — the chain table spells every step's server and answer — and a `split_whitespace`
/// reading glues a doc's words into the same soup a path lands in. What is asserted is the code.
fn tokens(model: &TowerModel) -> String {
  let mut file: syn::File = syn::parse2(model.emit()).expect("the expansion parses as a file");
  for item in &mut file.items {
    if let syn::Item::Impl(block) = item {
      for inner in &mut block.items {
        if let syn::ImplItem::Fn(function) = inner {
          function.attrs.retain(|attr| !attr.path().is_ident("doc"));
        }
      }
    }
  }
  quote::quote!(#file)
    .to_string()
    .split_whitespace()
    .collect()
}

/// The rendered expansion, formatted — what a failing claim prints.
fn rendered(model: &TowerModel) -> String {
  prettyplease::unparse(&syn::parse2(model.emit()).expect("the expansion parses as a file"))
}

/// The WALK's own doc line, which is where the OR law's answer is written for a reader.
///
/// Found BY NAME rather than by position: the expansion mints the options object's own roads too,
/// and every one of them carries a doc.
fn doc(model: &TowerModel) -> String {
  let file: syn::File = syn::parse2(model.emit()).expect("the expansion parses as a file");
  for item in &file.items {
    let syn::Item::Impl(block) = item else {
      continue;
    };
    for inner in &block.items {
      let syn::ImplItem::Fn(function) = inner else {
        continue;
      };
      if function.sig.ident != "walk" {
        continue;
      }
      for attr in &function.attrs {
        if !attr.path().is_ident("doc") {
          continue;
        }
        if let syn::Meta::NameValue(pair) = &attr.meta
          && let syn::Expr::Lit(literal) = &pair.value
          && let syn::Lit::Str(written) = &literal.lit
        {
          return written.value();
        }
      }
    }
  }
  String::new()
}

/// THE CHAIN IS DERIVED: one predicate per step, each at the type the chain arrived at, and the
/// second step's question is the first step's answer with nothing having declared it twice.
#[test]
fn every_adjacency_is_one_demanded_hop() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("Tokenize:::ingraph::__private::drive::Serves<String,Vec<String>>"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted
      .contains("ClipTextTower:::ingraph::__private::drive::AsyncServes<Vec<String>,Vec<f32>>"),
    "{}",
    rendered(&model)
  );
}

/// THE WORD SELECTS THE FACE, one step at a time — the fifth spend point, and the first that is per
/// field. Take the word off and the very same hop demands the blocking face.
#[test]
fn the_face_word_is_spent_per_step() {
  let mut model = clip_text();
  model.steps[1].awaited = false;
  let emitted = tokens(&model);
  assert!(
    emitted.contains("ClipTextTower:::ingraph::__private::drive::Serves<Vec<String>,Vec<f32>>"),
    "{}",
    rendered(&model)
  );
  assert!(
    !emitted.contains("AsyncServes"),
    "a wholly blocking tower demands no awaited face: {}",
    rendered(&model)
  );
}

/// The tower's two ENDS: the first step's question, and the last step's answer.
#[test]
fn the_ends_are_the_head_of_the_chain_and_its_tail() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("typeQuestion=String;"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("typeAnswer=Vec<f32>;"),
    "{}",
    rendered(&model)
  );
}

/// The declaration IS its own steps struct, which is what fields-are-steps means.
#[test]
fn the_steps_seat_names_the_declaration() {
  let model = clip_text();
  assert!(
    tokens(&model).contains("typeSteps=ClipText;"),
    "{}",
    rendered(&model)
  );
}

/// **THE IRON RULE**: the chain's `where` clause names FACES and nothing else, however the
/// declaration's type words were written.
///
/// `DefaultServe` reaches this expansion as a PROJECTION and never as a predicate, which is what
/// keeps the canonical line free of a mode: a bound would have to name one of the two faces, and
/// the word an author omits would then be omissible only for steps wearing it.
///
/// The PINNED tower is in this list for what it does not add: the head word's demand is spent on a
/// helper of its own, so the chain's own clause carries one predicate per step there too.
#[test]
fn every_demanded_bound_names_a_face() {
  for model in [
    clip_text(),
    blocking(),
    one_step(),
    canonical(),
    half(),
    pinned(),
  ] {
    let mut demanded = 0_usize;
    for bound in bounds(&model, "SearchTower") {
      let named = named(&bound);
      assert!(
        named == "Serves" || named == "AsyncServes",
        "a demanded bound named `{named}`: {}",
        rendered(&model)
      );
      demanded += 1;
    }
    assert_eq!(
      demanded,
      model.steps.len(),
      "one demand per step, whichever way the words were written: {}",
      rendered(&model)
    );
  }
}

/// **THE ASSEMBLY ROW RESTATES THE CHAIN AND ADDS ONLY CANONICAL LINES.**
///
/// The restatement is what keeps a broken tower's refusal SINGLE: a `where` clause is assumed at an
/// impl, so the assembly row that carries the chain reports none of the hops the connectivity
/// already reported. What it adds beyond the faces is one `DefaultServe` per end this declaration
/// OMITTED — the lines its own signature is spelled through, which have to be in the clause's
/// environment for the clause to be well formed.
///
/// A FULLY WRITTEN tower therefore adds nothing at all, which is the row below.
#[test]
fn the_assembly_row_carries_the_chain_and_the_lines_it_is_spelled_through() {
  for model in [clip_text(), blocking(), one_step(), pinned()] {
    let faces: Vec<String> = bounds(&model, "AssembledTower")
      .iter()
      .map(named)
      .collect::<Vec<_>>();
    assert_eq!(
      faces.iter().filter(|one| *one == "DefaultServe").count(),
      0,
      "a tower that wrote every word states no canonical line: {}",
      rendered(&model)
    );
    assert_eq!(
      faces.len(),
      model.steps.len(),
      "the chain, restated once: {}",
      rendered(&model)
    );
  }

  // THE WHOLLY CANONICAL TOWER states one line per step, plus the head's — which is the FIRST step's
  // own line a second time, because what the tower is asked and what that step is asked are one type
  // read at two seats.
  let model = canonical();
  let faces: Vec<String> = bounds(&model, "AssembledTower")
    .iter()
    .map(named)
    .collect::<Vec<_>>();
  assert_eq!(
    faces.iter().filter(|one| *one == "DefaultServe").count(),
    model.steps.len() + 1,
    "{}",
    rendered(&model)
  );
}

/// Every TRAIT the `where` clause of the impl stating `trait` demands — the bound itself, never the
/// types under it.
///
/// KEYED BY THE IMPL now, where it once read every clause in the expansion: the chain is stated at
/// two impls, and what each of them may say is a different rule.
fn bounds(model: &TowerModel, trait_name: &str) -> Vec<syn::TraitBound> {
  let file: syn::File = syn::parse2(model.emit()).expect("the expansion parses as a file");
  let mut demanded = Vec::new();
  for item in &file.items {
    let syn::Item::Impl(block) = item else {
      continue;
    };
    let stated = block
      .trait_
      .as_ref()
      .and_then(|(path, _)| path.segments.last())
      .is_some_and(|segment| segment.ident == trait_name);
    if !stated {
      continue;
    }
    let Some(clause) = &block.generics.where_clause else {
      continue;
    };
    for predicate in &clause.predicates {
      let syn::WherePredicate::Type(typed) = predicate else {
        continue;
      };
      for bound in &typed.bounds {
        if let syn::TypeParamBound::Trait(bound) = bound {
          demanded.push(bound.clone());
        }
      }
    }
  }
  demanded
}

/// The TRAIT one bound names, without the shelf path in front of it.
fn named(bound: &syn::TraitBound) -> String {
  bound
    .path
    .segments
    .last()
    .expect("a bound names a trait")
    .ident
    .to_string()
}

/// A tower that wrote every word names the canonical line NOWHERE — the omissible road costs a
/// declaration that did not take it nothing at all.
#[test]
fn a_fully_written_tower_names_no_canonical_line() {
  for model in [clip_text(), blocking(), one_step()] {
    assert!(
      !tokens(&model).contains("DefaultServe"),
      "{}",
      rendered(&model)
    );
  }
}

/// A wholly blocking tower.
fn blocking() -> TowerModel {
  let mut model = clip_text();
  model.steps[1].awaited = false;
  model
}

/// The shortest tower there is.
fn one_step() -> TowerModel {
  TowerModel {
    steps: vec![step(
      "rewrite",
      quote::quote!(Rewrite),
      quote::quote!(String),
    )],
    ..clip_text()
  }
}

/// THE WHOLLY CANONICAL TOWER: no question, no answer on any step — every type read off the steps'
/// own canonical lines.
fn canonical() -> TowerModel {
  let mut model = clip_text();
  model.question = None;
  for one in &mut model.steps {
    one.answer = None;
  }
  model
}

/// THE HALF-WRITTEN TOWER: a written question over steps that answer canonically, which is the mix
/// a tower asked something its first step is not usually asked writes.
fn half() -> TowerModel {
  let mut model = clip_text();
  for one in &mut model.steps {
    one.answer = None;
  }
  model
}

/// THE MIXED FORM: the question omitted and ONE of the two answers written, which is what
/// independence between the words means.
fn mixed() -> TowerModel {
  let mut model = clip_text();
  model.question = None;
  model.steps[0].answer = None;
  model
}

/// THE PINNED TOWER: the head naming the answer its chain must arrive at.
fn pinned() -> TowerModel {
  TowerModel {
    answer: Some(syn::parse_quote!(Vec<f32>)),
    ..clip_text()
  }
}

/// **THE HEAD PIN** — one anonymous `const`, spending the tower's own `SearchTower::Answer` against
/// the type the WORD claimed.
///
/// It demands the tower's citizenship and nothing beyond it, which is what lets the same bound check
/// a written last answer and a projected canonical line alike: the two are the same associated type
/// by the time this obligation is resolved.
#[test]
fn a_head_pin_demands_the_tower_answer_the_type_it_named() {
  let model = pinned();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "fn__ingraph_a_tower_answers_the_type_its_answer_word_named<__IgTower>()where__IgTower:\
       ::ingraph::__private::retrieve::SearchTower<Answer=Vec<f32>>,{}"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "const_:fn()=__ingraph_a_tower_answers_the_type_its_answer_word_named::<ClipText>;"
    ),
    "the bound is SPENT over the declared type: {}",
    rendered(&model)
  );
}

/// **THE PIN DECIDES NOTHING.** The tower still answers what its LAST STEP answers — the word is
/// checked against that derivation rather than put in its place.
///
/// Proven by making the two DISAGREE, which is the model a declaration whose chain has drifted hands
/// over: what the expansion does with it is state the DERIVED answer at every seat that carries one
/// and the claimed one only inside the pin, so the refusal comes from the compiler rather than from
/// a type this emitter quietly substituted.
#[test]
fn a_pinned_tower_still_answers_what_its_last_step_does() {
  let model = TowerModel {
    answer: Some(syn::parse_quote!(Vec<f64>)),
    ..clip_text()
  };
  let emitted = tokens(&model);
  assert!(
    emitted.contains("typeAnswer=Vec<f32>;"),
    "the tower's end is the chain's, not the word's: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains("->::core::result::Result<Vec<f32>,ClipTextError>"),
    "and so is what the walk hands back: {}",
    rendered(&model)
  );
  assert_eq!(
    emitted.matches("Vec<f64>").count(),
    1,
    "the claimed type appears in the pin and nowhere else: {}",
    rendered(&model)
  );
}

/// **A TOWER THAT WROTE NO HEAD WORD PAYS NOTHING** — no bound, no obligation, not one token.
///
/// The zero-burden regression, and the reason no golden that does not pin can move: every other
/// shape in this file is emitted exactly as it was before the word existed.
#[test]
fn a_tower_with_no_head_pin_emits_no_pin_at_all() {
  for model in [
    clip_text(),
    blocking(),
    one_step(),
    canonical(),
    half(),
    mixed(),
  ] {
    let emitted = tokens(&model);
    assert!(
      !emitted.contains("__ingraph_a_tower_answers"),
      "{}",
      rendered(&model)
    );
    assert!(
      !emitted.contains("SearchTower<Answer="),
      "{}",
      rendered(&model)
    );
  }
}

/// The pin rides the CANONICAL road too: a tower that wrote no type anywhere else states its intent
/// once at the head, and every step's line is checked against it through the chain.
#[test]
fn a_canonical_tower_may_still_pin_its_head() {
  let model = TowerModel {
    answer: Some(syn::parse_quote!(Vec<f32>)),
    ..canonical()
  };
  let emitted = tokens(&model);
  assert!(
    emitted
      .contains("typeAnswer=<ClipTextToweras::ingraph::__private::drive::DefaultServe>::Answer;"),
    "the derivation is untouched: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains("SearchTower<Answer=Vec<f32>>"),
    "and the word is what it is demanded to be: {}",
    rendered(&model)
  );
}

/// THE OR LAW, one way: one awaited step makes the whole walk awaited.
#[test]
fn one_awaited_step_makes_the_whole_walk_awaited() {
  let model = clip_text();
  assert!(model.awaited());
  assert!(
    tokens(&model).contains("pubasyncfnwalk("),
    "{}",
    rendered(&model)
  );
  assert!(
    doc(&model).contains("at least one step is awaited"),
    "{}",
    doc(&model)
  );
}

/// THE OR LAW, the other way: a wholly blocking tower needs no runtime to be walked.
#[test]
fn a_wholly_blocking_tower_walks_in_a_blocking_function() {
  let model = blocking();
  assert!(!model.awaited());
  let emitted = tokens(&model);
  assert!(emitted.contains("pubfnwalk("), "{}", rendered(&model));
  assert!(
    !emitted.contains("asyncfnwalk("),
    "nothing awaits, so nothing is awaited: {}",
    rendered(&model)
  );
  assert!(
    !emitted.contains(".await"),
    "a blocking hop is CALLED: {}",
    rendered(&model)
  );
  assert!(
    doc(&model).contains("every step is blocking"),
    "{}",
    doc(&model)
  );
}

/// THE SIGNATURE: the question first, one `&mut` borrow per step in declaration order, the options
/// seat last.
#[test]
fn the_walk_takes_the_question_then_the_steps_then_the_seat() {
  let model = clip_text();
  assert!(
    tokens(&model).contains(
      "fnwalk(question:String,__ingraph_step0__:&mutTokenize,__ingraph_step1__:&mut\
       ClipTextTower,options:::core::option::Option<&ClipTextStepOptions>,)"
    ),
    "{}",
    rendered(&model)
  );
}

/// The walk answers the tower's own answer, or the TOWER'S OWN SUM.
#[test]
fn the_walk_answers_the_tower_or_its_own_refusal_sum() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("->::core::result::Result<Vec<f32>,ClipTextError>"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted
      .contains("return::core::result::Result::Err(ClipTextError::Tokenize(__ingraph_refused__));"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted
      .contains("return::core::result::Result::Err(ClipTextError::Encode(__ingraph_refused__));"),
    "{}",
    rendered(&model)
  );
  // THE ERASURE ROAD IS GONE, and the assertion is the POSITIVE one now: `AskRefusal` was deleted
  // from the tree on 2026-08-19, so a pin naming the absent type would pass over any emission at
  // all — including one that had stopped naming the sum. What the walk must carry is a `Box<dyn
  // Error>` nowhere and a typed arm at every early return, which the three assertions above are.
  assert!(
    !emitted.contains("Box<dynError"),
    "a refusal was boxed rather than named: {}",
    rendered(&model)
  );
}

/// **THE REFUSAL SUM**: one arm per step, named after the step's own field, carrying that step's
/// own error as a PROJECTION at the face its word chose.
#[test]
fn the_refusal_sum_has_one_arm_per_step_carrying_that_steps_error() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pubenumClipTextError{"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "Tokenize(<Tokenizeas::ingraph::__private::drive::Serves<String,Vec<String>>>::Error)"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "Encode(<ClipTextToweras::ingraph::__private::drive::AsyncServes<Vec<String>,Vec<f32>>>\
       ::Error)"
    ),
    "{}",
    rendered(&model)
  );
}

/// The sum's ARM NAME is the field's, translated — a snake-cased field is a camel-cased variant,
/// and a raw one loses only its `r#`.
#[test]
fn an_arm_is_the_step_fields_own_name() {
  let mut model = one_step();
  model.steps[0].field = quote::format_ident!("second_pass");
  assert!(
    tokens(&model).contains("SecondPass(<"),
    "{}",
    rendered(&model)
  );

  let mut raw = one_step();
  raw.steps[0].field = quote::format_ident!("r#type");
  assert!(tokens(&raw).contains("Type(<"), "{}", rendered(&raw));
}

/// The sum's three faces: the SENTENCE, the ARM WITH ITS PAYLOAD, and the CAUSE.
///
/// `Display` takes only the arm's name, being a sentence about which step refused. `Debug` prints
/// the arm AND what it holds, which is the shape a derived one has and the shape a caller
/// `.unwrap()`ing a walk expects — and it costs nothing to demand, `source`'s own coercion having
/// already required every payload to be an `Error`, whose supertrait is `Debug`.
#[test]
fn the_refusal_sums_faces_name_the_step_and_what_it_refused_with() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("Self::Tokenize(_)=>::core::fmt::Formatter::write_str(__ingraph_f,\"thestep`tokenize`refusedthequestion\")"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "Self::Tokenize(__ingraph_refused__)=>::core::fmt::DebugTuple::finish(\
       ::core::fmt::DebugTuple::field(&mut::core::fmt::Formatter::debug_tuple(__ingraph_f,\
       \"Tokenize\"),__ingraph_refused__,),)"
    ),
    "the arm names the step and carries what it refused with: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "fnsource(&self)->::core::option::Option<&(dyn::core::error::Error+'static)>{matchself{\
       Self::Tokenize(__ingraph_refused__)=>::core::option::Option::Some(__ingraph_refused__),"
    ),
    "{}",
    rendered(&model)
  );
  // THE REFUSAL SUM ITSELF carries no derive, which is what makes each of the three faces a
  // sentence. Read off the sum's OWN ITEM rather than off the whole expansion: the options object
  // beside it joined the package family's three derives when a recipe first bound a tower, and a
  // claim about one type must not be spelled as a claim about every type the model mints.
  let file: syn::File = syn::parse2(model.emit()).expect("the expansion parses");
  let sum = file
    .items
    .iter()
    .find_map(|item| match item {
      syn::Item::Enum(declared) if declared.ident == "ClipTextError" => Some(declared),
      _ => None,
    })
    .expect("the expansion holds the sum");
  assert!(
    !sum
      .attrs
      .iter()
      .any(|attribute| attribute.path().is_ident("derive")),
    "the three faces are written rather than derived, so each says what this sum means: {}",
    rendered(&model)
  );
}

/// The sum takes the DECLARATION's visibility, as the walk does: a refusal nobody outside the crate
/// can name is one nobody outside it could match.
#[test]
fn the_refusal_sum_takes_the_declarations_visibility() {
  let model = TowerModel {
    vis: syn::parse_quote!(pub(crate)),
    ..clip_text()
  };
  assert!(
    tokens(&model).contains("pub(crate)enumClipTextError{"),
    "{}",
    rendered(&model)
  );
}

/// EVERY HOP IS DOUBLE-PINNED: the call goes through the trait path the word chose, and both of the
/// hop's ends are ascribed beside it.
#[test]
fn each_hop_is_pinned_twice() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "::ingraph::__private::drive::Serves::serve(__ingraph_step0__,__ingraph_asked__,\
       ::core::option::Option::and_then(options,|__ingraph_options__|{\
       ::core::option::Option::as_ref(&__ingraph_options__.tokenize)}),)"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("let__ingraph_asked__:String=question;"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("let__ingraph_answered__:Vec<String>="),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("let__ingraph_asked__:Vec<String>=__ingraph_answered__;"),
    "{}",
    rendered(&model)
  );
}

/// AN AWAITED HOP IS AWAITED, and a blocking one in the same tower is not.
#[test]
fn the_awaited_hop_is_the_one_that_wore_the_word() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "::ingraph::__private::drive::AsyncServes::serve(__ingraph_step1__,__ingraph_asked__,\
       ::core::option::Option::and_then(options,|__ingraph_options__|{\
       ::core::option::Option::as_ref(&__ingraph_options__.encode)}),).await"
    ),
    "{}",
    rendered(&model)
  );
  // `.await{` and not `.await`: the RECORD spells the same step's face as `Step::of("encode")
  // .awaited()`, which is a word ABOUT a hop rather than one, and a bare prefix match would count
  // it.
  assert_eq!(
    emitted.matches(".await{").count(),
    1,
    "one awaited step, one await: {}",
    rendered(&model)
  );
}

/// **EVERY HOP IS HANDED ITS OWN FIELD AND NOTHING ELSE** — the projection, one hop's worth.
///
/// The two absences fold into one: options that were never handed over, and options that named
/// nothing for THIS step, are the same fact from the step's side — *this call named nothing*, under
/// which it runs at its own floor.
#[test]
fn every_hop_is_handed_the_field_that_is_its_own() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert_eq!(
    emitted
      .matches("::core::option::Option::and_then(options,|__ingraph_options__|{")
      .count(),
    model.steps.len(),
    "one projection per hop: {}",
    rendered(&model)
  );
  for field in ["tokenize", "encode"] {
    assert!(
      emitted.contains(&format!(
        "::core::option::Option::as_ref(&__ingraph_options__.{field})"
      )),
      "the `{field}` hop reads the `{field}` field: {}",
      rendered(&model)
    );
  }
  assert!(
    !emitted.contains("::core::option::Option::None,)"),
    "no hop is served under a hard-coded nothing any more: {}",
    rendered(&model)
  );
}

/// **THE TOWER'S OWN OPTIONS**: one field per step, each the PROJECTION of that step's own base
/// seat — never a face, which is what keeps the object free of a mode.
#[test]
fn the_options_object_has_one_field_per_step() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pubstructClipTextStepOptions{"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "tokenize:::core::option::Option<<Tokenizeas::ingraph::__private::drive::Serve>::Options>"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "encode:::core::option::Option<<ClipTextToweras::ingraph::__private::drive::Serve>::Options>"
    ),
    "{}",
    rendered(&model)
  );
}

/// **THE `()`-SEAT IS NOT A MACRO-TIME FACT**, so a step gets its row whatever its server seats.
///
/// This emission sees a TYPE and never resolves one, so whether `<Ty as Serve>::Options` is `()` is
/// the compiler's knowledge and not this pass's. The half-row law is therefore stated where it CAN
/// be enforced — on the wire, where a seat crosses only if it can — and the Rust struct carries a
/// row per step, the `()` ones zero-sized and read by nothing.
#[test]
fn a_step_gets_its_row_whatever_its_server_seats() {
  let model = one_step();
  let emitted = tokens(&model);
  assert_eq!(
    emitted
      .matches("::ingraph::__private::drive::Serve>::Options")
      .count(),
    // the field, `with_…`'s parameter, `set_…`'s parameter, and the getter's answer
    4,
    "{}",
    rendered(&model)
  );
}

/// The three roads to a step's knobs, and the division between the two that WRITE.
///
/// `with_…` takes the SEAT and `set_…` takes the option, which is `Flow`'s own division one layer
/// down: *this call names nothing* has to stay sayable after construction.
#[test]
fn a_step_is_named_by_its_own_three_roads() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "pubfnwith_tokenize(mutself,tokenize:<Tokenizeas::ingraph::__private::drive::Serve>\
       ::Options)->Self{self.tokenize=::core::option::Option::Some(tokenize);self}"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "pubfnset_tokenize(&mutself,tokenize:::core::option::Option<<Tokenizeas\
       ::ingraph::__private::drive::Serve>::Options>)->&mutSelf{self.tokenize=tokenize;self}"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "pubfntokenize(&self)->::core::option::Option<&<Tokenizeas::ingraph::__private::drive::\
       Serve>::Options>{::core::option::Option::as_ref(&self.tokenize)}"
    ),
    "{}",
    rendered(&model)
  );
}

/// NOTHING IS THE FLOOR, and it is one source of truth: `Default` delegates to `new`, which names no
/// step at all.
#[test]
fn the_unnamed_options_are_one_value_reached_two_ways() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "pubconstfnnew()->Self{Self{tokenize:::core::option::Option::None,encode:\
       ::core::option::Option::None,}}"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "impl::core::default::DefaultforClipTextStepOptions{#[inline]fndefault()->Self{Self::new()}}"
    ),
    "{}",
    rendered(&model)
  );
}

/// A step's ONE NAME reaches its options roads unraw'd, and the field itself keeps its `r#`.
#[test]
fn a_raw_step_name_is_unrawed_where_it_is_glued() {
  let mut model = one_step();
  model.steps[0].field = quote::format_ident!("r#type");
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pubfnwith_type(mutself,"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("pubfnset_type(&mutself,"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("pubfnr#type(&self)"),
    "{}",
    rendered(&model)
  );
}

/// The options object takes the DECLARATION's visibility, and so does every road into it.
#[test]
fn the_options_object_takes_the_declarations_visibility() {
  let model = TowerModel {
    vis: syn::parse_quote!(pub(crate)),
    ..clip_text()
  };
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pub(crate)structClipTextStepOptions{"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("pub(crate)constfnnew()->Self"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("pub(crate)fnwith_tokenize("),
    "{}",
    rendered(&model)
  );
}

/// **THE RECORD**: the three facts a reader that cannot see these tokens needs, and no fourth.
#[test]
fn the_record_states_the_face_the_options_and_the_roster() {
  let model = clip_text();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("impl::ingraph::__private::retrieve::DeclaredTowerforClipText{"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("typeStepOptions=ClipTextStepOptions;"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("constALL_SYNC:bool=false;"),
    "one awaited step, so the tower is not blocking end to end: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "constSTEPS:&'static[::ingraph::__private::retrieve::Step]=&[\
       ::ingraph::__private::retrieve::Step::of(\"tokenize\"),\
       ::ingraph::__private::retrieve::Step::of(\"encode\").awaited()];"
    ),
    "{}",
    rendered(&model)
  );
}

/// The record's `ALL_SYNC` is the OR law read the other way round — and the record restates NO
/// predicate, so a broken chain is reported by the connectivity alone.
#[test]
fn a_wholly_blocking_tower_records_itself_as_one() {
  let model = blocking();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("constALL_SYNC:bool=true;"),
    "{}",
    rendered(&model)
  );
  assert!(
    !emitted.contains("DeclaredTowerforClipTextwhere"),
    "the record restates no predicate: {}",
    rendered(&model)
  );
}

/// The RECORD names no end, and that is the one-landing law: the supertrait already carries both.
#[test]
fn the_record_restates_neither_end() {
  let model = clip_text();
  let emitted = tokens(&model);
  let record = emitted
    .split("DeclaredTowerforClipText{")
    .nth(1)
    .expect("the record is emitted");
  let record = record.split("}").next().expect("the record closes");
  assert!(
    !record.contains("typeQuestion") && !record.contains("typeAnswer"),
    "{}",
    rendered(&model)
  );
}

/// The declaration's own visibility is the walk's: a tower nobody outside the crate can name has no
/// walk anybody outside it could call.
#[test]
fn the_walk_takes_the_declarations_visibility() {
  let model = TowerModel {
    vis: syn::parse_quote!(pub(crate)),
    ..clip_text()
  };
  assert!(
    tokens(&model).contains("pub(crate)asyncfnwalk("),
    "{}",
    rendered(&model)
  );
}

/// The argument-count allow rides the walk, whose parameter count is a DECLARATION's rather than
/// this emitter's — a six-step tower has eight parameters, in a crate that cannot edit the
/// expansion.
#[test]
fn the_argument_count_allow_rides_the_walk() {
  assert!(
    tokens(&clip_text()).contains("#[allow(clippy::too_many_arguments)]"),
    "{}",
    rendered(&clip_text())
  );
}

/// **THE OMISSION ROAD, whole**: no question and no answer anywhere, so every type in the
/// expansion is a projection off a step's own canonical line.
#[test]
fn a_wholly_canonical_tower_projects_every_type() {
  let model = canonical();
  let emitted = tokens(&model);
  const LINE: &str = "::ingraph::__private::drive::DefaultServe";

  assert!(
    emitted.contains(&format!("typeQuestion=<Tokenizeas{LINE}>::Question;")),
    "the tower is asked what its FIRST step is: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(&format!("typeAnswer=<ClipTextToweras{LINE}>::Answer;")),
    "the tower answers what its LAST step does: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(&format!(
      "Tokenize:::ingraph::__private::drive::Serves<<Tokenizeas{LINE}>::Question,<Tokenizeas\
       {LINE}>::Answer>"
    )),
    "the canonical line is proven honest by the chain's own predicate: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(&format!(
      "ClipTextTower:::ingraph::__private::drive::AsyncServes<<Tokenizeas{LINE}>::Answer,\
       <ClipTextToweras{LINE}>::Answer>"
    )),
    "the hop between them is still DERIVED: {}",
    rendered(&model)
  );
}

/// **THE HALF FORM**: a written question over canonically-answering steps — the tower says what IT
/// is asked and lets each step say what it gives back.
#[test]
fn a_written_question_over_canonical_answers() {
  let model = half();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("typeQuestion=String;"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "Tokenize:::ingraph::__private::drive::Serves<String,<Tokenizeas\
       ::ingraph::__private::drive::DefaultServe>::Answer>"
    ),
    "the head of the chain is the WORD, and what it answers is the line: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains("fnwalk(question:String,"),
    "{}",
    rendered(&model)
  );
}

/// **THE MIXED FORM**: the words are independent, so one step writes its answer beside another that
/// omits it, under a question that was omitted too.
#[test]
fn the_two_words_are_omitted_and_written_independently() {
  let model = mixed();
  let emitted = tokens(&model);
  const LINE: &str = "::ingraph::__private::drive::DefaultServe";

  assert!(
    emitted.contains(&format!("typeQuestion=<Tokenizeas{LINE}>::Question;")),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("typeAnswer=Vec<f32>;"),
    "the last step WROTE its answer, so the tower's is that word: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(&format!(
      "ClipTextTower:::ingraph::__private::drive::AsyncServes<<Tokenizeas{LINE}>::Answer,\
       Vec<f32>>"
    )),
    "one hop with a projected question and a written answer: {}",
    rendered(&model)
  );
}

/// The doc line reads a canonical type back in the SHORT form — `__private` is a shelf path, not a
/// sentence.
#[test]
fn the_doc_spells_a_canonical_type_the_way_a_reader_would() {
  let written = doc(&canonical());
  assert!(
    written.contains("from `<Tokenize as DefaultServe>::Question`"),
    "{written}"
  );
  assert!(
    written
      .contains("| `tokenize` | `Tokenize` | blocking | `<Tokenize as DefaultServe>::Answer` |"),
    "{written}"
  );
  assert!(!written.contains("__private"), "{written}");
}

/// The doc table names every step, its server, its face and what it answers — the four facts a
/// caller needs to know which borrow goes where.
#[test]
fn the_walk_doc_names_every_step_and_its_face() {
  let written = doc(&clip_text());
  assert!(
    written.contains("| `tokenize` | `Tokenize` | blocking | `Vec<String>` |"),
    "{written}"
  );
  assert!(
    written.contains("| `encode` | `ClipTextTower` | awaited | `Vec<f32>` |"),
    "{written}"
  );
  assert!(written.contains("# Errors"), "{written}");
}

// ── THE FAN-SEGMENT MODEL ─────────────────────────────────────────────────────────────────────
//
// The amendment's rows: which segments a declaration opened, what mounts each, where each sits —
// and the one thing the emission does with them today, which is nothing.

/// A widening, as the grammar hands one over.
fn widening() -> Fan {
  Fan::Expand {
    expander: syn::parse_quote!(app::Synonyms),
  }
}

/// A crossing, as the grammar hands one over.
fn crossing(router: Router) -> Fan {
  Fan::Route {
    router,
    slot: syn::parse_quote!(app::BodySlot),
  }
}

/// The mixed tower with a segment opened at each of its two steps.
fn fanned() -> TowerModel {
  let mut model = clip_text();
  model.steps[0].fan = Some(widening());
  model.steps[1].fan = Some(crossing(Router::ScriptWeightedFan));
  model
}

// ── THE ASSEMBLY ROW ──────────────────────────────────────────────────────────────────────────
//
// The gate over a deployment's filled seats, and the uniform run a resolver calls.

/// **THE RUN IS THE WALK AT A FIXED ARITY** — the steps as ONE value, and every step borrowed out of
/// it in declaration order.
#[test]
fn the_run_hands_the_walk_one_borrow_per_step_out_of_one_value() {
  let emitted = tokens(&clip_text());
  assert!(
    emitted.contains(
      "asyncfnrun(__ingraph_steps__:&mutClipText,question:String,options:::core::option::Option<&\
       ClipTextStepOptions>,asked:::core::option::Option<ClipTextSearchOptions>,)->::core::result::\
       Result<Vec<f32>,ClipTextError>"
    ),
    "{}",
    rendered(&clip_text())
  );
  assert!(
    emitted.contains(
      "ClipText::walk(question,&mut__ingraph_steps__.tokenize,&mut__ingraph_steps__.encode,options)\
       .await"
    ),
    "{}",
    rendered(&clip_text())
  );
}

/// **A BLOCKING TOWER'S RUN IS AWAITED AND ITS WALK IS NOT.** The caller is a resolver, so the run
/// wraps rather than branching — and the `.await` the fanned road writes is absent here.
#[test]
fn a_blocking_towers_run_wraps_its_blocking_walk() {
  let emitted = tokens(&blocking());
  assert!(emitted.contains("asyncfnrun("), "{}", rendered(&blocking()));
  assert!(
    emitted.contains(
      "ClipText::walk(question,&mut__ingraph_steps__.tokenize,&mut__ingraph_steps__\
                      .encode,options)}"
    ),
    "{}",
    rendered(&blocking())
  );
}

/// **ABSENCE-IDENTITY AT THE GATE**: a tower that opened no segment emits NO `check` at all and
/// inherits the row that refuses nothing.
#[test]
fn an_unfanned_tower_emits_no_gate() {
  for model in [clip_text(), blocking(), one_step(), canonical()] {
    assert!(!tokens(&model).contains("fncheck("), "{}", rendered(&model));
  }
}

/// **THE GATE READS ONE SEAT PER DECLARED WORD**, ascribing each before it reads it — so the gate
/// and the walk agree about what a fan step's field holds by construction.
#[test]
fn the_gate_reads_every_declared_fan_word_at_its_own_seat() {
  let model = fanned();
  let emitted = tokens(&model);

  assert!(
    emitted.contains(
      "fncheck(__ingraph_steps__:&ClipText,)->::core::result::Result<(),::ingraph::__private::\
       retrieve::SeatsUnfilled>"
    ),
    "{}",
    rendered(&model)
  );
  // ② the seat ASCRIBED, then asked whether anything is mounted, and the DECLARED expander named.
  assert!(
    emitted.contains(
      "let__ingraph_road__:&::ingraph::__private::retrieve::Expansion<String>=&__ingraph_steps__.\
       tokenize;"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("::widening(\"tokenize\",\"app::Synonyms\")"),
    "{}",
    rendered(&model)
  );
  // ④ the fan's OWN check, carried whole rather than restated.
  assert!(
    emitted.contains("::route::LaneFan::check(__ingraph_fan__)"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("::crossing(\"encode\",__ingraph_missing__)"),
    "{}",
    rendered(&model)
  );
  // ONE AUTHORITY for *nothing unfilled is not a refusal*.
  assert!(
    emitted.contains("SeatsUnfilled::checked(\"ClipText\",__ingraph_unfilled__)"),
    "{}",
    rendered(&model)
  );
}

/// **THE STAGES ARE ORDERED BY THE PIPELINE**, and the order is the enum's own.
#[test]
fn the_stage_order_is_the_pipelines() {
  assert!(
    Stage::Annotate < Stage::Expand,
    "a question is annotated before anything reads the annotation",
  );
  assert!(
    Stage::Expand < Stage::Route,
    "a question is widened before it is crossed",
  );
  assert_eq!(Stage::Annotate.word(), "annotate");
  assert_eq!(Stage::Expand.word(), "expand");
  assert_eq!(Stage::Route.word(), "route");
}

/// **EVERY STAGE ANSWERS WHY IT RUNS WHERE IT DOES**, which is what an out-of-order refusal quotes —
/// one row per stage rather than one per pair, and none by silence.
#[test]
fn every_stage_says_why_it_is_where_it_is() {
  assert!(Stage::Annotate.why_first().contains("READ what it wrote"));
  assert!(Stage::Expand.why_first().contains("endomorphism"));
  assert!(Stage::Route.why_first().contains("one probe per lane"));
}

/// A fan answers WHICH STAGE it is and WHICH WORD wrote it, and the two cannot disagree.
#[test]
fn a_fan_names_its_stage_and_its_word() {
  assert_eq!(widening().stage(), Stage::Expand);
  assert_eq!(widening().word(), Stage::Expand.word());
  assert_eq!(crossing(Router::FanAll).stage(), Stage::Route);
  assert_eq!(crossing(Router::FanAll).word(), Stage::Route.word());
}

/// **THE SHIPPED ROSTER ROUND-TRIPS**, so the words a refusal prints are the words that bind.
#[test]
fn every_shipped_word_names_the_router_it_spells() {
  for word in Router::SHIPPED {
    let shipped = Router::shipped(word).expect("a word in the roster names a shipped router");
    assert_eq!(shipped.as_written(), word);
  }
  assert!(Router::shipped("script_weighted").is_none());
  assert!(Router::shipped("").is_none());

  let declared = Router::Declared(syn::parse_quote!(app::MyRouter));
  assert_eq!(declared.as_written().replace(' ', ""), "app::MyRouter");
}

/// The roster's positions are the ones the refusals read off, named rather than counted by hand.
#[test]
fn the_shipped_roster_is_the_three_routers_this_framework_has() {
  assert_eq!(
    Router::SHIPPED,
    ["fan_all", "script_router", "script_weighted_fan"],
  );
}

/// **THE SEGMENTS ARE READ OFF THE STEPS**, so a position is a step's own index and never a second
/// seat that could disagree with it.
#[test]
fn a_towers_fans_are_its_steps_own_positions() {
  let model = fanned();
  assert!(model.fanned());
  let opened: Vec<_> = model
    .fans()
    .map(|(at, step, fan)| (at, step.field.to_string(), fan.stage()))
    .collect();
  assert_eq!(
    opened,
    vec![
      (0, "tokenize".to_owned(), Stage::Expand),
      (1, "encode".to_owned(), Stage::Route),
    ],
  );
}

/// **TODAY'S TOWERS ARE THE DEGENERATE CASE**, read off the model rather than assumed.
#[test]
fn a_tower_with_no_fan_word_opens_no_segment() {
  let model = clip_text();
  assert!(!model.fanned());
  assert_eq!(model.fans().count(), 0);
}

/// **THE BYTE PIN, RE-POINTED AT WHAT IT CAN STILL HONESTLY PIN.**
///
/// The task that built the grammar pinned *a fan segment costs the expansion nothing* by COMPARING
/// the two renderings, and that pin was written to go red the day a walk spent one. It did, and this
/// is what stands in its place: the premise moved, so the comparison moved with it.
///
/// What is no longer true is that the two expansions are equal — a fanned tower now walks a grid and
/// folds at its mouth, so of course it does not emit what a 1 → 1 chain emits. What IS still true,
/// and is the thing the original pin existed to protect, is that **a tower which opens no segment
/// pays for the amendment in nothing at all**: not one token of the fan machinery reaches its
/// expansion, and its walk is the same straight chain it has always been.
///
/// That is what is compared here — against the NAMES, which is the strongest statement available
/// once the two sides legitimately differ. The unfanned expansion's exact shape is pinned by the
/// hundred-odd token claims above it, none of which moved this round.
#[test]
fn a_fan_free_tower_pays_for_the_amendment_in_nothing() {
  let bare = tokens(&clip_text());
  for machinery in [
    "Expansion",
    "LaneFan",
    "FanStream",
    "RankedStream",
    "fuse_fanned",
    "ArmWeights",
    "__ingraph_grid__",
    "__ingraph_arm__",
    "__ingraph_probe__",
  ] {
    assert!(
      !bare.contains(machinery),
      "a fan-free tower's expansion names `{machinery}`:\n{}",
      rendered(&clip_text()),
    );
  }
  // And its walk is the straight chain, ending where it always ended — no grid, no fold, no loop.
  assert!(
    bare.contains("Ok(__ingraph_answered__)"),
    "{}",
    rendered(&clip_text()),
  );
  assert!(!bare.contains("for("), "{}", rendered(&clip_text()));
}

/// **THE STEPS BEFORE A FAN RUN EXACTLY AS THEY ALWAYS DID** — the surviving half, as a comparison.
///
/// A pre-fan hop is emitted by the same call the unfanned walk emits, with the reborrow left off,
/// so the tokens are the same tokens. Read off both renderings rather than asserted about one:
/// whatever the fan does after it, the chain in front of it is untouched.
#[test]
fn the_hops_before_a_fan_are_the_hops_they_always_were() {
  let mut model = clip_text();
  let mut widen = step("widen", quote::quote!(Widen), quote::quote!(Vec<String>));
  widen.fan = Some(widening());
  model.steps.insert(1, widen);

  let lead = "let__ingraph_asked__:String=question;let__ingraph_answered__:Vec<String>=match";
  assert!(
    tokens(&clip_text()).contains(lead),
    "{}",
    rendered(&clip_text()),
  );
  assert!(tokens(&model).contains(lead), "{}", rendered(&model));
  // And the hops AFTER it are reborrowed, which is what a loop costs and what nothing before it
  // pays.
  assert!(
    tokens(&model).contains("serve(&mut*__ingraph_step2__"),
    "{}",
    rendered(&model),
  );
}

/// **AN OMITTED END IS LEFT UNBOUND**, because a predicate that named it would name itself.
///
/// A fan step whose `answer` word is absent has `<Ty as DefaultServe>::Answer` for an answer, so
/// binding `Answer =` to it would state `Ty: DefaultServe<Answer = <Ty as DefaultServe>::Answer>` —
/// which rustc reports as `E0275`, at the attribute, on a declaration that did nothing wrong. It was
/// MEASURED rather than reasoned about: the tree's first fanned tower earned that overflow.
#[test]
fn a_fan_step_that_omits_its_ends_binds_neither() {
  let mut model = clip_text();
  model.question = None;
  model.steps[0].answer = None;
  model.steps[0].fan = Some(widening());

  let written = tokens(&model);
  assert!(
    written.contains("Tokenize:::ingraph::__private::drive::DefaultServe,"),
    "{}",
    rendered(&model),
  );
  assert!(
    !written.contains("DefaultServe<Question"),
    "{}",
    rendered(&model),
  );
}

/// **THE FANNED WALK IS AWAITED, AND ITS ANSWER IS THE FUSED LIST.**
#[test]
fn a_fanned_tower_answers_one_fused_list_from_an_awaited_walk() {
  let written = tokens(&fanned());

  assert!(
    written.contains("pubasyncfnwalk"),
    "{}",
    rendered(&fanned())
  );
  assert!(
    written.contains("constALL_SYNC:bool=false"),
    "{}",
    rendered(&fanned()),
  );
  // ONE value out, and it is the fold's — the two parameters projected off the tail's own answer.
  assert!(
    written.contains(
      "typeAnswer=::std::vec::Vec<::ingraph::__private::retrieve::Fused<<Vec<f32>as::ingraph::\
       __private::retrieve::RankedStream>::Root,<Vec<f32>as::ingraph::__private::retrieve::\
       RankedStream>::Evidence,>>"
    ),
    "{}",
    rendered(&fanned()),
  );
}

/// **THE TWO SEGMENTS ARE SPENT AT THEIR OWN FIELDS** — the seat, the family, the dispatches.
#[test]
fn the_fan_walk_widens_then_crosses_then_folds() {
  let written = tokens(&fanned());

  // ② — the seat is ASCRIBED, the call is awaited, and the family's element type is pinned.
  assert!(
    written.contains("let__ingraph_road__:&::ingraph::__private::retrieve::Expansion<String>="),
    "{}",
    rendered(&fanned()),
  );
  assert!(
    written.contains("::expand(__ingraph_road__,__ingraph_asked__).await"),
    "{}",
    rendered(&fanned()),
  );
  // ④ — the seat is ascribed at the ROUTER the word named, and the question crosses as a borrow.
  assert!(
    written.contains(
      "let__ingraph_fan__:&::ingraph::__private::route::LaneFan<::ingraph::__private::route::\
       ScriptWeightedFan<Vec<String>>>="
    ),
    "{}",
    rendered(&fanned()),
  );
  assert!(
    written.contains("::route(__ingraph_fan__,&__ingraph_asked__)"),
    "{}",
    rendered(&fanned()),
  );
  // THE FOLD, at the mouth, over the grid the two loops filled.
  assert!(
    written.contains("::fuse_fanned::<"),
    "{}",
    rendered(&fanned()),
  );
  assert!(
    written.contains("__ingraph_grid__,::ingraph::__private::retrieve::Fusion::rrf(),"),
    "{}",
    rendered(&fanned()),
  );
}

/// **(D) THE TWO NUMBERS REACH THE CELL SEPARATELY**, which is what makes the multiply structural.
#[test]
fn a_cell_is_built_from_the_arm_and_the_lane_and_never_from_a_product() {
  let written = tokens(&fanned());

  assert!(
    written.contains(
      "::ingraph::__private::retrieve::FanStream::new(__ingraph_lane__,__ingraph_arm__,\
       __ingraph_arm_weight__,__ingraph_lane_weight__,"
    ),
    "{}",
    rendered(&fanned()),
  );
  // The arm's number is read off the ② step's OWN options row, through the projection every step
  // already had.
  assert!(
    written.contains("::ingraph::__private::retrieve::ArmWeights::weight("),
    "{}",
    rendered(&fanned()),
  );
  assert!(
    written.contains("&__ingraph_options__.tokenize"),
    "{}",
    rendered(&fanned()),
  );
  // And the lane's is read off the dispatch the router answered with.
  assert!(
    written.contains("::weight(&__ingraph_probe__)"),
    "{}",
    rendered(&fanned()),
  );
}

/// **THE CHAIN'S PREDICATES AT A FAN STEP** — the seat's line, the declared expander, and the
/// wiring's own equality.
#[test]
fn a_fan_steps_predicates_are_the_seat_the_default_and_the_wiring() {
  let written = tokens(&fanned());

  // ② — the seat states a canonical line at BOTH ends this declaration wrote, and the DECLARED
  // DEFAULT must be able to widen the question the chain is carrying.
  assert!(
    written.contains(
      "Tokenize:::ingraph::__private::drive::DefaultServe<Question=String,Answer=Vec<String>>"
    ),
    "{}",
    rendered(&fanned()),
  );
  assert!(
    written.contains("app::Synonyms:::ingraph::__private::retrieve::AsyncQueryExpander<String>"),
    "{}",
    rendered(&fanned()),
  );
  // ④ — THE SLOT EQUALITY, which is the whole reason the crossing names two things.
  assert!(
    written.contains(
      "::ingraph::__private::route::LaneRouter<Routed=<app::BodySlotas::ingraph::__private::lane::\
       LanedStore>::Probe>"
    ),
    "{}",
    rendered(&fanned()),
  );
}

/// **A WIDENING HAS NO ARM IN THE REFUSAL SUM**, and a crossing's arm carries the fan's own.
#[test]
fn the_refusal_sum_names_only_the_steps_that_can_refuse() {
  let written = tokens(&fanned());

  assert!(
    !written.contains("Tokenize(<"),
    "a widening cannot fail, so it has no arm:\n{}",
    rendered(&fanned()),
  );
  assert!(
    written.contains(
      "Encode(::ingraph::__private::route::FanError<<::ingraph::__private::route::\
       ScriptWeightedFan<Vec<String>>as::ingraph::__private::route::LaneRouter>::Error>)"
    ),
    "{}",
    rendered(&fanned()),
  );
  // And the three faces beneath it match on the same set — one arm, not two.
  assert_eq!(
    written.matches("Self::Encode(__ingraph_refused__)").count(),
    2,
    "`Debug` and `source` each match the crossing's arm once:\n{}",
    rendered(&fanned()),
  );
  assert!(
    !written.contains("Self::Tokenize(_)"),
    "{}",
    rendered(&fanned()),
  );
}

/// **THE TWO DEGENERATE FANS ARE SPELLED**, so neither is a branch a reader has to find.
#[test]
fn a_tower_that_opens_one_segment_names_the_axis_it_did_not() {
  let mut widening_only = clip_text();
  widening_only.steps[0].fan = Some(widening());
  assert!(
    tokens(&widening_only).contains("FanStream::uncut(__ingraph_arm__,__ingraph_arm_weight__,"),
    "{}",
    rendered(&widening_only),
  );

  let mut crossing_only = clip_text();
  crossing_only.steps[0].fan = Some(crossing(Router::FanAll));
  let written = tokens(&crossing_only);
  assert!(
    written.contains("FanStream::unwidened(__ingraph_lane__,__ingraph_lane_weight__,"),
    "{}",
    rendered(&crossing_only),
  );
  // A tower that only crosses does not widen, so its walk is awaited only if a STEP said so — and
  // this one's second step did.
  assert!(
    !written.contains("__ingraph_arm__"),
    "{}",
    rendered(&crossing_only)
  );
}

// ── ⟂ THE ANNOTATION STAGE ────────────────────────────────────────────────────────────────────
//
// The stage whose ends are the same type: what the chain does across it, what the walk asks before
// it spends the operator, and the two predicates the step raises.

/// The mixed tower with an annotation stage in front of it.
///
/// The stage is at step `0`, which is where the order law puts it, and the tower's own question is
/// what it is handed.
fn annotated() -> TowerModel {
  let mut model = clip_text();
  model.steps.insert(
    0,
    annotating(
      "detect",
      quote::quote!(Lid),
      quote::quote!(app::LanguageTag),
    ),
  );
  model
}

/// **A STEP NAMES ITS STAGE OFF WHICHEVER SEAT IS FILLED**, so the order law reads one roster
/// however many words open a stage.
#[test]
fn a_step_names_its_stage_off_either_seat() {
  let model = annotated();
  assert_eq!(model.steps[0].stage(), Some(Stage::Annotate));
  assert_eq!(model.annotate_at(), Some(0));
  assert!(
    model.steps[0].fan.is_none(),
    "an annotation opens no FAN, and the model does not pretend it does",
  );
  assert!(
    !model.fanned(),
    "and it does not make the tower a fanned one"
  );

  let mut widened = annotated();
  widened.steps[1].fan = Some(widening());
  assert_eq!(widened.steps[1].stage(), Some(Stage::Expand));
  assert!(clip_text().steps[0].stage().is_none());
}

/// **THE CHAIN'S TYPE DOES NOT MOVE ACROSS THE STAGE** — the step after it is handed the tower's own
/// question, and the stage's own hop is ascribed at that type on both sides.
#[test]
fn an_annotation_hands_on_what_it_was_handed() {
  let written = tokens(&annotated());

  // BOTH ENDS OF THE HOP are the tower's question, and the step after it takes the same type.
  assert!(
    written.contains("Lid:::ingraph::__private::drive::Serves<String,String>"),
    "{}",
    rendered(&annotated()),
  );
  assert!(
    written.contains("Tokenize:::ingraph::__private::drive::Serves<String,Vec<String>>"),
    "the chain resumes at the type it arrived with:\n{}",
    rendered(&annotated()),
  );
  // AND THE SEAM IS DEMANDED OF THE QUESTION, which is what makes fill-if-absent real.
  assert!(
    written.contains("String:::ingraph::__private::retrieve::AnnotatedQuestion<app::LanguageTag>"),
    "{}",
    rendered(&annotated()),
  );
}

/// **FILL-IF-ABSENT IS A BRANCH AND THE OPERATOR IS NOT CONSULTED** on the road that skips it.
#[test]
fn the_walk_asks_the_question_before_it_spends_the_operator() {
  let written = tokens(&annotated());

  assert!(
    written.contains(
      "let__ingraph_told__=::core::option::Option::is_some(&<Stringas::ingraph::__private::\
       retrieve::AnnotatedQuestion<app::LanguageTag>>::carried(&__ingraph_asked__),);"
    ),
    "{}",
    rendered(&annotated()),
  );
  // THE UNTOUCHED ROAD hands the very value on — no call, no rebuild, no merge.
  assert!(
    written.contains("if__ingraph_told__{__ingraph_asked__}else{match"),
    "{}",
    rendered(&annotated()),
  );
  // THE SERVE IS ON THE OTHER ROAD ONLY, and there is exactly one of it.
  assert_eq!(
    written
      .matches("::ingraph::__private::drive::Serves::serve(__ingraph_step0__,__ingraph_asked__,")
      .count(),
    1,
    "{}",
    rendered(&annotated()),
  );
}

/// **THE STAGE HAS AN ARM IN THE REFUSAL SUM**, unlike a widening: an operator can fail.
#[test]
fn the_annotation_stage_refuses_under_its_own_arm() {
  let written = tokens(&annotated());

  assert!(
    written.contains("Detect(<Lidas::ingraph::__private::drive::Serves<String,String>>::Error)"),
    "{}",
    rendered(&annotated()),
  );
}

/// **THE FACE IS THE STEP'S OWN WORD** — a `Door` onto a resident wears the awaited one, and the
/// stage does not choose for it.
#[test]
fn an_annotation_step_wears_the_face_its_word_named() {
  let mut awaited = annotated();
  awaited.steps[0].awaited = true;
  let written = tokens(&awaited);

  assert!(
    written.contains("Lid:::ingraph::__private::drive::AsyncServes<String,String>"),
    "{}",
    rendered(&awaited),
  );
  assert!(
    written.contains(
      "::ingraph::__private::drive::AsyncServes::serve(__ingraph_step0__,__ingraph_asked__,"
    ),
    "{}",
    rendered(&awaited),
  );
  assert!(
    written.contains(".await{::core::result::Result::Ok(__ingraph_answered__)"),
    "the awaited face's call is awaited:\n{}",
    rendered(&awaited),
  );
}

/// **A TOWER WITHOUT THE WORD PAYS FOR THE STAGE IN NOTHING** — not one name of the machinery
/// appears in a rendering that opened no annotation.
#[test]
fn a_tower_with_no_annotate_word_names_none_of_the_stage() {
  let written = tokens(&clip_text());

  for name in ["AnnotatedQuestion", "__ingraph_told__", "carried"] {
    assert!(
      !written.contains(name),
      "an unannotated tower names `{name}`:\n{}",
      rendered(&clip_text()),
    );
  }
}