layover-core 0.23.1

Domain types for Layover: factory configuration, route graph, itinerary accounting and rendezvous barriers.
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
//! Deciding where each node goes.
//!
//! A layered layout, which is the right shape for a route map: work flows from an entry point
//! towards a terminal agent, and putting each node one column further right than the thing that
//! wakes it makes that flow the diagram's primary axis.
//!
//! # Layers come from breadth-first distance, not longest path
//!
//! The textbook layered algorithm assigns layers by longest path from a source, which does not
//! terminate on a cyclic graph. Route maps are routinely cyclic — a developer sends to a tester
//! and the tester sends back, which is the review loop that makes the reference factory work —
//! so longest path is not available.
//!
//! Breadth-first distance is, and [`crate::graph::RouteGraph`] already computes it for the
//! load-time hop check. Reusing it means the diagram's columns and the validator's hop arithmetic
//! are derived from the same number, so a diagram can never imply a depth that validation
//! disagrees with.
//!
//! Edges that point backwards or sideways are then drawn as return paths, which is what they are.

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

use crate::agent::{Access, AgentName};
use crate::config::Config;
use crate::diagram::{Activity, Live, Scope};
use crate::graph::RouteGraph;
use crate::pipeline::PipelineName;
use crate::route::Join;

/// Width of a node box.
const NODE_W: f64 = 168.0;
/// Height of a node box.
const NODE_H: f64 = 56.0;
/// Horizontal gap between columns.
const COL_GAP: f64 = 96.0;
/// Vertical gap between nodes in a column.
const ROW_GAP: f64 = 32.0;
/// Margin around the whole drawing.
const MARGIN: f64 = 32.0;
/// Vertical spacing between the lanes that return paths are routed through.
const RETURN_GAP: f64 = 34.0;
/// How far left of a node''s column the first return path climbs.
const GUTTER_INSET: f64 = 44.0;
/// How much further left each additional return to the same node climbs.
const GUTTER_STEP: f64 = 18.0;
/// Closest to the left edge of the canvas a gutter may be.
const GUTTER_MIN: f64 = 12.0;
/// Closest to a node''s right edge that a return path may hook in.
const CORNER_MARGIN: f64 = 20.0;

/// What a node represents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeKind {
    /// A way into the mesh.
    Pipeline,
    /// A configured agent.
    Agent,
}

/// How a node is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
    /// An ordinary agent or pipeline.
    Box,
    /// An agent guarded by a rendezvous barrier. Drawn as a gate, because that is what it is.
    Gate,
}

/// A positioned node.
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
    /// Stable identifier, used to join edges to nodes and for DOM ids.
    pub id: String,
    /// The name shown on the node.
    pub label: String,
    /// A second line: a trigger for a pipeline, `read-only` for an agent that has it.
    pub subtitle: Option<String>,
    /// What this node represents.
    pub kind: NodeKind,
    /// How to draw it.
    pub shape: Shape,
    /// What it is doing, if anything.
    pub activity: Option<Activity>,
    /// Which column it sits in.
    pub layer: usize,
    /// Left edge.
    pub x: f64,
    /// Top edge.
    pub y: f64,
    /// Width.
    pub w: f64,
    /// Height.
    pub h: f64,
}

impl Node {
    /// The point an edge should leave from.
    #[must_use]
    pub fn exit(&self) -> (f64, f64) {
        (self.x + self.w, self.y + self.h / 2.0)
    }

    /// The point an edge should arrive at.
    #[must_use]
    pub fn entry(&self) -> (f64, f64) {
        (self.x, self.y + self.h / 2.0)
    }

    /// The centre.
    #[must_use]
    pub fn centre(&self) -> (f64, f64) {
        (self.x + self.w / 2.0, self.y + self.h / 2.0)
    }
}

/// How an edge is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeStyle {
    /// An ordinary permitted edge.
    Plain,
    /// A pipeline feeding its entry agent.
    Entry,
    /// One of the upstreams a barrier names.
    Joined,
    /// A permitted sender that the barrier does *not* name, and which therefore wakes the agent
    /// directly rather than parking at it.
    Bypass,
    /// Opens a new itinerary per flight rather than continuing this one.
    Spawn,
}

/// A positioned edge.
#[derive(Debug, Clone, PartialEq)]
pub struct Edge {
    /// Identifier of the node it leaves.
    pub from: String,
    /// Identifier of the node it arrives at.
    pub to: String,
    /// `all` or `any`, for an edge into a barrier.
    pub label: Option<String>,
    /// How to draw it.
    pub style: EdgeStyle,
    /// True when the edge points back towards the entry, which makes it a return path.
    pub back: bool,
    /// Where on the source''s right edge this leaves, as an absolute y.
    ///
    /// Edges all left from the node''s centre, so several going to different places overlapped
    /// for their first stretch and only separated once they had already crossed each other.
    /// Spreading them down the edge, ordered by where they are going, means they never cross at
    /// the node they share.
    pub from_y: f64,
    /// Where on the target''s left edge this arrives, as an absolute y.
    pub to_y: f64,
    /// For a return path, the x it climbs at. `None` for a forward edge.
    ///
    /// Distinct per edge even when several return to the same agent. Sharing one gutter put four
    /// curves on the same vertical line with their labels stacked on top of each other.
    pub gutter: Option<f64>,
    /// For a return path, where it hooks into the target''s underside.
    pub hook_x: Option<f64>,
    /// For a return path, the depth it dips to. `None` for a forward edge.
    ///
    /// Computed here rather than in the renderer because it decides how tall the drawing is, and
    /// a renderer that invented its own geometry would draw outside the reported extent — which
    /// is exactly how a review loop ends up clipped off the bottom of the diagram.
    pub floor: Option<f64>,
}

/// A laid-out diagram.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Layout {
    /// Every node, in reading order.
    pub nodes: Vec<Node>,
    /// Every edge.
    pub edges: Vec<Edge>,
    /// Total width, including margins.
    pub width: f64,
    /// Total height, including margins.
    pub height: f64,
}

impl Layout {
    /// Finds a node by identifier.
    #[must_use]
    pub fn node(&self, id: &str) -> Option<&Node> {
        self.nodes.iter().find(|node| node.id == id)
    }

    /// Lays out a whole factory.
    #[must_use]
    pub fn build(config: &Config, live: &Live) -> Self {
        Self::scoped(config, live, &Scope::Everything)
    }

    /// Lays out one workflow, or the whole factory.
    #[must_use]
    pub fn scoped(config: &Config, live: &Live, scope: &Scope) -> Self {
        let graph = RouteGraph::from_config(config);
        let members = scope.pipeline().and_then(|name| {
            config
                .pipelines
                .get(name)
                .map(|pipeline| graph.workflow_from(&pipeline.entry))
        });
        let layers = assign_layers(config, &graph, scope);

        let mut layout = Self::default();
        layout.place(config, live, &graph, &layers, scope, members.as_ref());
        layout.connect(config, &graph, members.as_ref());
        layout.order_by_barycentre();
        layout.size();
        layout
    }

    /// Creates a node for every pipeline and agent, and puts it in its column.
    fn place(
        &mut self,
        config: &Config,
        live: &Live,
        graph: &RouteGraph,
        layers: &BTreeMap<AgentName, usize>,
        scope: &Scope,
        members: Option<&BTreeSet<AgentName>>,
    ) {
        let mut columns: BTreeMap<usize, Vec<Node>> = BTreeMap::new();

        for (name, pipeline) in &config.pipelines {
            if scope.pipeline().is_some_and(|wanted| wanted != name) {
                continue;
            }
            columns.entry(0).or_default().push(Node {
                id: pipeline_id(name),
                label: name.as_str().to_owned(),
                subtitle: Some(pipeline.trigger.to_string()),
                kind: NodeKind::Pipeline,
                shape: Shape::Box,
                activity: None,
                layer: 0,
                x: 0.0,
                y: 0.0,
                w: NODE_W,
                h: NODE_H,
            });
        }

        for (name, agent) in &config.agents {
            if members.is_some_and(|members| !members.contains(name)) {
                continue;
            }
            // Agents no pipeline can reach still have to appear — an unreachable agent is
            // precisely the thing somebody opened the diagram to find.
            let layer = layers.get(name).copied().unwrap_or(0) + 1;
            columns.entry(layer).or_default().push(Node {
                id: agent_id(name),
                label: name.as_str().to_owned(),
                subtitle: (agent.access == Access::ReadOnly).then(|| "read-only".to_owned()),
                kind: NodeKind::Agent,
                shape: if graph.join_for(name).is_some() {
                    Shape::Gate
                } else {
                    Shape::Box
                },
                activity: live.activity.get(name).copied(),
                layer,
                x: 0.0,
                y: 0.0,
                w: NODE_W,
                h: NODE_H,
            });
        }

        for (layer, mut nodes) in columns {
            let x = MARGIN + precise(layer) * (NODE_W + COL_GAP);
            for (row, node) in nodes.iter_mut().enumerate() {
                node.x = x;
                node.y = MARGIN + precise(row) * (NODE_H + ROW_GAP);
            }
            self.nodes.append(&mut nodes);
        }
    }

    /// Adds the edges, classifying each one.
    fn connect(
        &mut self,
        config: &Config,
        graph: &RouteGraph,
        members: Option<&BTreeSet<AgentName>>,
    ) {
        for (name, pipeline) in &config.pipelines {
            if self.node(&pipeline_id(name)).is_none() {
                continue;
            }
            self.edges.push(Edge {
                from: pipeline_id(name),
                to: agent_id(&pipeline.entry),
                label: None,
                style: EdgeStyle::Entry,
                back: false,
                from_y: 0.0,
                to_y: 0.0,
                gutter: None,
                hook_x: None,
                floor: None,
            });
        }

        let mut drawn = Vec::new();
        for route in &config.routes {
            for from in &route.from {
                for to in &route.to {
                    if members
                        .is_some_and(|members| !members.contains(from) || !members.contains(to))
                    {
                        continue;
                    }
                    let pair = (agent_id(from), agent_id(to));
                    if drawn.contains(&pair) {
                        continue;
                    }
                    drawn.push(pair.clone());

                    // A barrier constrains only the upstreams it names. Any other permitted
                    // sender wakes the agent directly, leaving parked flights untouched, so
                    // labelling that edge with the join condition would state the opposite of
                    // what happens.
                    // A spawn is checked first: it opens a new itinerary, so a barrier on the
                    // receiver cannot apply to it -- validation rejects that combination outright.
                    let (style, label) = if route.is_spawn() {
                        (EdgeStyle::Spawn, Some("spawn".to_owned()))
                    } else {
                        match graph.join_for(to) {
                            Some(spec) if spec.upstreams.contains(from) => (
                                EdgeStyle::Joined,
                                Some(
                                    match spec.join {
                                        Join::All => "all",
                                        Join::Any => "any",
                                    }
                                    .to_owned(),
                                ),
                            ),
                            Some(_) => (EdgeStyle::Bypass, None),
                            None => (EdgeStyle::Plain, None),
                        }
                    };

                    let back = self.layer_of(&pair.0) >= self.layer_of(&pair.1);
                    self.edges.push(Edge {
                        from: pair.0,
                        to: pair.1,
                        label,
                        style,
                        back,
                        from_y: 0.0,
                        to_y: 0.0,
                        gutter: None,
                        hook_x: None,
                        floor: None,
                    });
                }
            }
        }
    }

    /// Which column a node is in, or zero if it is not placed.
    fn layer_of(&self, id: &str) -> usize {
        self.node(id).map_or(0, |node| node.layer)
    }

    /// Reorders each column to sit near the things that point at it.
    ///
    /// One pass of the barycentre heuristic. It is not optimal — crossing minimisation is
    /// NP-hard — but on a graph of this size one pass removes most of the obvious tangles, and a
    /// second pass tends to shuffle nodes without improving anything a human would notice.
    fn order_by_barycentre(&mut self) {
        let positions: BTreeMap<String, f64> = self
            .nodes
            .iter()
            .map(|node| (node.id.clone(), node.centre().1))
            .collect();

        let mut keys: BTreeMap<String, (f64, String)> = BTreeMap::new();
        for node in &self.nodes {
            let incoming: Vec<f64> = self
                .edges
                .iter()
                .filter(|edge| edge.to == node.id && !edge.back)
                .filter_map(|edge| positions.get(&edge.from).copied())
                .collect();

            // No incoming edges leaves the node where it was: its own position is the only
            // information available, and inventing an order would be churn.
            let bary = if incoming.is_empty() {
                node.centre().1
            } else {
                incoming.iter().sum::<f64>() / precise(incoming.len())
            };
            keys.insert(node.id.clone(), (bary, node.label.clone()));
        }

        let mut by_layer: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
        for (index, node) in self.nodes.iter().enumerate() {
            by_layer.entry(node.layer).or_default().push(index);
        }

        for indices in by_layer.into_values() {
            let mut ordered = indices.clone();
            ordered.sort_by(|left, right| {
                let a = &keys[&self.nodes[*left].id];
                let b = &keys[&self.nodes[*right].id];
                a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1))
            });

            let ys: Vec<f64> = indices.iter().map(|i| self.nodes[*i].y).collect();
            for (slot, index) in ordered.into_iter().enumerate() {
                self.nodes[index].y = ys[slot];
            }
        }
    }

    /// Computes the overall extent, centres each column vertically, and routes the return paths.
    fn size(&mut self) {
        let tallest = self
            .nodes
            .iter()
            .map(|node| node.y + node.h)
            .fold(0.0_f64, f64::max);

        let mut bottoms: BTreeMap<usize, f64> = BTreeMap::new();
        for node in &self.nodes {
            let bottom = bottoms.entry(node.layer).or_insert(0.0);
            *bottom = bottom.max(node.y + node.h);
        }
        for node in &mut self.nodes {
            node.y += (tallest - bottoms[&node.layer]) / 2.0;
        }

        let deepest = self.route_returns(tallest);
        self.assign_ports();

        self.width = self
            .nodes
            .iter()
            .map(|node| node.x + node.w)
            .fold(0.0_f64, f64::max)
            + MARGIN;
        self.height = tallest.max(deepest) + MARGIN;
    }

    /// Spreads each node''s edges along its sides instead of bunching them at the centre.
    ///
    /// Ordered by where the other end sits, so two edges leaving the same node never cross each
    /// other before they have gone anywhere. Only forward edges: a return path leaves from the
    /// underside and is routed through its own lane already.
    fn assign_ports(&mut self) {
        let centres: BTreeMap<String, f64> = self
            .nodes
            .iter()
            .map(|node| (node.id.clone(), node.centre().1))
            .collect();
        let boxes: BTreeMap<String, (f64, f64)> = self
            .nodes
            .iter()
            .map(|node| (node.id.clone(), (node.y, node.h)))
            .collect();

        let mut leaving: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        let mut arriving: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        for (index, edge) in self.edges.iter().enumerate() {
            if edge.back {
                continue;
            }
            leaving.entry(edge.from.clone()).or_default().push(index);
            arriving.entry(edge.to.clone()).or_default().push(index);
        }

        for (id, mut indices) in leaving {
            indices.sort_by(|left, right| {
                let a = centres.get(&self.edges[*left].to).copied().unwrap_or(0.0);
                let b = centres.get(&self.edges[*right].to).copied().unwrap_or(0.0);
                a.total_cmp(&b)
            });
            let Some(&(top, height)) = boxes.get(&id) else {
                continue;
            };
            let count = indices.len();
            for (slot, index) in indices.into_iter().enumerate() {
                self.edges[index].from_y = port(top, height, slot, count);
            }
        }

        for (id, mut indices) in arriving {
            indices.sort_by(|left, right| {
                let a = centres.get(&self.edges[*left].from).copied().unwrap_or(0.0);
                let b = centres
                    .get(&self.edges[*right].from)
                    .copied()
                    .unwrap_or(0.0);
                a.total_cmp(&b)
            });
            let Some(&(top, height)) = boxes.get(&id) else {
                continue;
            };
            let count = indices.len();
            for (slot, index) in indices.into_iter().enumerate() {
                self.edges[index].to_y = port(top, height, slot, count);
            }
        }
    }

    /// Gives each return path its own lane below the drawing, and reports the deepest one.
    ///
    /// Lanes rather than one shared depth: two loops at the same height would be drawn on top of
    /// each other, and a review loop is the structure on a route map most worth being able to
    /// follow with a finger.
    fn route_returns(&mut self, floor_start: f64) -> f64 {
        let mut lanes: Vec<(String, String)> = self
            .edges
            .iter()
            .filter(|edge| edge.back)
            .map(|edge| (edge.from.clone(), edge.to.clone()))
            .collect();
        // Shortest loops innermost, so a long return path never has to cross a short one.
        lanes.sort_by_key(|(from, to)| {
            let span = self
                .node(from)
                .zip(self.node(to))
                .map_or(0, |(f, t)| f.layer.abs_diff(t.layer));
            (span, from.clone(), to.clone())
        });

        let boxes: BTreeMap<String, (f64, f64)> = self
            .nodes
            .iter()
            .map(|node| (node.id.clone(), (node.x, node.w)))
            .collect();

        // How many returns already aim at each target, so edges sharing one can be fanned apart
        // rather than stacked on a single vertical line.
        let mut per_target: BTreeMap<String, usize> = BTreeMap::new();

        let mut deepest = floor_start;
        for (index, key) in lanes.iter().enumerate() {
            let depth = floor_start + RETURN_GAP * (precise(index) + 1.0);
            deepest = deepest.max(depth);

            let seen = per_target.entry(key.1.clone()).or_insert(0);
            let nth = *seen;
            *seen += 1;

            let (left, width) = boxes.get(&key.1).copied().unwrap_or((0.0, NODE_W));
            let gutter = (left - GUTTER_INSET - GUTTER_STEP * precise(nth)).max(GUTTER_MIN);
            let hook = left + width * 0.25 + width * 0.2 * precise(nth);

            if let Some(edge) = self
                .edges
                .iter_mut()
                .find(|edge| edge.back && (edge.from.clone(), edge.to.clone()) == *key)
            {
                edge.floor = Some(depth);
                edge.gutter = Some(gutter);
                edge.hook_x = Some(hook.min(left + width - CORNER_MARGIN));
            }
        }
        deepest
    }
}

/// Assigns each agent a column by breadth-first distance from the ways in.
///
/// Agents nothing can reach are absent from the result, and the caller places them in the first
/// column rather than dropping them: an unreachable agent is exactly what somebody opened the
/// diagram to find, so hiding it would defeat the purpose.
///
/// When one workflow is being drawn, distance is measured from *that* pipeline's entry and no
/// other. Seeding every entry regardless of scope put agents that happen to be another pipeline's
/// way in near the left edge of a diagram they are late in — the reference factory''s follower is
/// reached through the publisher, but is also the follow-up pipeline''s entry, so it landed in
/// column two with an edge sweeping back across the whole drawing.
fn assign_layers(config: &Config, graph: &RouteGraph, scope: &Scope) -> BTreeMap<AgentName, usize> {
    let sources: Vec<AgentName> = match scope.pipeline() {
        Some(name) => config
            .pipelines
            .get(name)
            .map(|pipeline| vec![pipeline.entry.clone()])
            .unwrap_or_default(),
        None => config
            .pipelines
            .values()
            .map(|pipeline| pipeline.entry.clone())
            .chain(
                config
                    .agents
                    .iter()
                    .filter(|(_, agent)| agent.entry)
                    .map(|(name, _)| name.clone()),
            )
            .collect(),
    };

    let mut layers: BTreeMap<AgentName, usize> = graph
        .distances_from(sources.iter())
        .into_iter()
        .map(|(name, distance)| (name, distance as usize))
        .collect();

    // Spawn targets are absent from the distances above, because breadth-first traversal stops at
    // a spawn edge — correctly, since the receiver starts a fresh chain with fresh Hops and hop
    // depth across chains is not a real distance.
    //
    // For *drawing*, though, that leaves them at column zero, sitting beside the agent that
    // spawns them, and the edge between becomes a same-column loop that reads as a stray squiggle
    // rather than a hand-off. Placing each one right of its spawner keeps the left-to-right flow
    // that makes the diagram legible. Only the picture is affected: the hop check does its own
    // seeding and still treats them as entry points.
    for (from, to) in graph.spawn_edges() {
        let placed = layers.get(from).copied().unwrap_or(0) + 1;
        let entry = layers.entry(to.clone()).or_insert(placed);
        *entry = (*entry).max(placed);
    }

    layers
}

/// Where the `slot`-th of `count` edges should meet a node''s side.
///
/// Evenly spaced across the middle 70% of the height, so a single edge still meets the centre and
/// several never reach the rounded corners.
fn port(top: f64, height: f64, slot: usize, count: usize) -> f64 {
    if count <= 1 {
        return top + height / 2.0;
    }
    let usable = height * 0.7;
    let step = usable / precise(count - 1);
    top + (height - usable) / 2.0 + step * precise(slot)
}

/// Widens a count to a float for geometry.
///
/// Diagrams have tens of nodes, not quadrillions, so the lossy cast clippy warns about cannot
/// happen here. Saying so once in a named function is better than scattering allow attributes
/// through the arithmetic.
fn precise(count: usize) -> f64 {
    u32::try_from(count).map_or(f64::from(u32::MAX), f64::from)
}

/// A stable identifier for an agent node.
fn agent_id(name: &AgentName) -> String {
    format!("a_{name}")
}

/// A stable identifier for a pipeline node.
fn pipeline_id(name: &PipelineName) -> String {
    format!("p_{name}")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config(body: &str) -> Config {
        Config::from_toml(body, "layout-test.toml").expect("config parses")
    }

    fn factory() -> Config {
        config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.analyst]
            prompt = "analyse"

            [agents.developer]
            prompt = "develop"

            [agents.tester]
            prompt = "test"
            access = "read-only"

            [agents.publisher]
            prompt = "publish"

            [pipelines.triage]
            entry = "analyst"

            [[routes]]
            from = "analyst"
            to = "developer"

            [[routes]]
            from = "developer"
            to = "tester"

            [[routes]]
            from = "tester"
            to = "developer"
            join = "all"

            [[routes]]
            from = "developer"
            to = "publisher"
            "#,
        )
    }

    #[test]
    fn work_flows_left_to_right_one_column_per_hop() {
        let layout = Layout::build(&factory(), &Live::default());

        assert_eq!(layout.node("p_triage").expect("pipeline").layer, 0);
        assert_eq!(layout.node("a_analyst").expect("analyst").layer, 1);
        assert_eq!(layout.node("a_developer").expect("developer").layer, 2);
        assert_eq!(layout.node("a_tester").expect("tester").layer, 3);
    }

    #[test]
    fn a_loop_does_not_hang_the_layout() {
        // Longest-path layering, the textbook approach, does not terminate here: the developer
        // and the tester point at each other, which is the review loop the reference factory is
        // built around. Breadth-first distance is what makes cyclic route maps drawable at all.
        let layout = Layout::build(&factory(), &Live::default());

        assert_eq!(layout.nodes.len(), 5);
        assert!(layout.width > 0.0 && layout.height > 0.0);
    }

    #[test]
    fn an_edge_pointing_back_towards_the_entry_is_marked_as_a_return_path() {
        let layout = Layout::build(&factory(), &Live::default());

        let back = layout
            .edges
            .iter()
            .find(|edge| edge.from == "a_tester" && edge.to == "a_developer")
            .expect("the review loop exists");

        assert!(back.back, "tester sits right of developer, so this returns");
        assert_eq!(back.style, EdgeStyle::Joined);
        assert_eq!(back.label.as_deref(), Some("all"));
    }

    #[test]
    fn a_sender_the_barrier_does_not_name_is_marked_as_bypassing_it() {
        let config = config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.scanner]
            prompt = "scan"

            [agents.left]
            prompt = "left"

            [agents.right]
            prompt = "right"

            [agents.collector]
            prompt = "collect"

            [pipelines.go]
            entry = "scanner"

            [[routes]]
            from = ["left", "right"]
            to = "collector"
            join = "all"

            [[routes]]
            from = "scanner"
            to = "collector"
            "#,
        );

        let layout = Layout::build(&config, &Live::default());
        let bypass = layout
            .edges
            .iter()
            .find(|edge| edge.from == "a_scanner" && edge.to == "a_collector")
            .expect("scanner may send to collector");

        assert_eq!(bypass.style, EdgeStyle::Bypass);
        assert_eq!(
            bypass.label, None,
            "it does not wait, so it has no condition"
        );
    }

    #[test]
    fn a_joined_agent_is_drawn_as_a_gate() {
        let layout = Layout::build(&factory(), &Live::default());

        assert_eq!(
            layout.node("a_developer").expect("developer").shape,
            Shape::Gate
        );
        assert_eq!(layout.node("a_analyst").expect("analyst").shape, Shape::Box);
    }

    #[test]
    fn nodes_in_a_column_never_overlap() {
        let layout = Layout::build(&factory(), &Live::default());

        for layer in 0..4 {
            let mut boxes: Vec<(f64, f64)> = layout
                .nodes
                .iter()
                .filter(|node| node.layer == layer)
                .map(|node| (node.y, node.y + node.h))
                .collect();
            boxes.sort_by(|a, b| a.0.total_cmp(&b.0));

            for pair in boxes.windows(2) {
                assert!(
                    pair[1].0 >= pair[0].1,
                    "layer {layer} has overlapping nodes: {pair:?}"
                );
            }
        }
    }

    #[test]
    fn every_node_sits_inside_the_reported_extent() {
        // The extent becomes the SVG viewBox. A node outside it is a node nobody can see.
        let layout = Layout::build(&factory(), &Live::default());

        for node in &layout.nodes {
            assert!(node.x >= 0.0 && node.y >= 0.0, "{} is off-canvas", node.id);
            assert!(node.x + node.w <= layout.width, "{} overflows", node.id);
            assert!(node.y + node.h <= layout.height, "{} overflows", node.id);
        }
    }

    #[test]
    fn return_paths_sit_inside_the_reported_extent_too() {
        // The first version of this reserved height for nodes only, and every review loop in the
        // reference factory was drawn below the viewBox and clipped away. Found by rendering it
        // and looking, which is the only way that class of bug ever shows up.
        let layout = Layout::build(&factory(), &Live::default());

        let returns: Vec<&Edge> = layout.edges.iter().filter(|edge| edge.back).collect();
        assert!(!returns.is_empty(), "the factory has a review loop to test");

        for edge in returns {
            let floor = edge.floor.expect("a return path is given a lane");
            assert!(
                floor <= layout.height,
                "{} -> {} dips to {floor} but the drawing is only {} tall",
                edge.from,
                edge.to,
                layout.height
            );
        }
    }

    #[test]
    fn several_returns_to_one_agent_climb_at_different_points() {
        // The normal shape of a review loop: a tester and a reviewer both report back to the
        // developer. Sharing one gutter put both curves on the same vertical line and stacked
        // their labels on top of each other, which is what the whole diagram looked like.
        let layout = Layout::build(&review_loop(), &Live::default());
        let returns: Vec<f64> = layout
            .edges
            .iter()
            .filter(|edge| edge.back && edge.to == "a_dev")
            .filter_map(|edge| edge.gutter)
            .collect();

        assert!(returns.len() >= 2, "the factory has a review loop");
        for pair in returns.windows(2) {
            assert!(
                (pair[0] - pair[1]).abs() > 1.0,
                "two returns share a gutter: {returns:?}"
            );
        }

        let hooks: Vec<f64> = layout
            .edges
            .iter()
            .filter(|edge| edge.back && edge.to == "a_dev")
            .filter_map(|edge| edge.hook_x)
            .collect();
        for pair in hooks.windows(2) {
            assert!(
                (pair[0] - pair[1]).abs() > 1.0,
                "two returns hook in at the same point: {hooks:?}"
            );
        }
    }

    #[test]
    fn a_return_path_hooks_inside_the_agent_it_returns_to() {
        let layout = Layout::build(&review_loop(), &Live::default());
        let developer = layout.node("a_dev").expect("dev");

        for edge in layout.edges.iter().filter(|edge| edge.back) {
            let hook = edge.hook_x.expect("a return path is given a hook");
            assert!(
                hook > developer.x && hook < developer.x + developer.w,
                "the hook must land on the node, not beside it: {hook}"
            );
        }
    }

    /// A developer fanning out to a tester and a reviewer, both reporting back. The commonest
    /// shape in a real factory and the one that exposed the shared-gutter problem.
    fn review_loop() -> Config {
        config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.dev]
            prompt = "develop"

            [agents.tester]
            prompt = "test"

            [agents.reviewer]
            prompt = "review"

            [pipelines.go]
            entry = "dev"

            [[routes]]
            from = "dev"
            to = ["tester", "reviewer"]

            [[routes]]
            from = ["tester", "reviewer"]
            to = "dev"
            join = "all"
            "#,
        )
    }

    #[test]
    fn two_return_paths_are_given_lanes_of_their_own() {
        // Drawn at the same depth they would overlap, and a review loop is the structure on a
        // route map most worth being able to follow with a finger.
        let config = config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.dev]
            prompt = "develop"

            [agents.tester]
            prompt = "test"

            [agents.reviewer]
            prompt = "review"

            [pipelines.go]
            entry = "dev"

            [[routes]]
            from = "dev"
            to = ["tester", "reviewer"]

            [[routes]]
            from = ["tester", "reviewer"]
            to = "dev"
            join = "all"
            "#,
        );

        let layout = Layout::build(&config, &Live::default());
        let mut floors: Vec<f64> = layout
            .edges
            .iter()
            .filter(|edge| edge.back)
            .filter_map(|edge| edge.floor)
            .collect();
        floors.sort_by(f64::total_cmp);

        assert_eq!(floors.len(), 2);
        assert!(
            (floors[1] - floors[0]).abs() > 1.0,
            "the two loops share a lane: {floors:?}"
        );
    }

    #[test]
    fn a_workflow_is_laid_out_from_its_own_entry_only() {
        // Seeding every pipeline entry regardless of scope put agents that happen to be another
        // pipeline's way in near the left edge of a diagram they are late in. In the reference
        // factory the follower is reached through the publisher but is also the follow-up
        // pipeline's entry, so it landed in column two with an edge sweeping back across the
        // whole drawing.
        let config = config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.analyst]
            prompt = "analyse"

            [agents.publisher]
            prompt = "publish"

            [agents.follower]
            prompt = "follow"

            [pipelines.triage]
            entry = "analyst"

            [pipelines.follow_up]
            entry = "follower"

            [[routes]]
            from = "analyst"
            to = "publisher"

            [[routes]]
            from = "publisher"
            to = "follower"
            "#,
        );

        let triage = Layout::scoped(&config, &Live::default(), &Scope::Pipeline("triage".into()));
        let publisher = triage.node("a_publisher").expect("publisher");
        let follower = triage.node("a_follower").expect("follower");

        assert!(
            follower.layer > publisher.layer,
            "the follower is reached through the publisher here, so it must come after it: \
             publisher at {}, follower at {}",
            publisher.layer,
            follower.layer
        );
    }

    #[test]
    fn edges_leaving_one_node_meet_it_at_different_points() {
        // They all left from the centre, so several going to different places overlapped for
        // their first stretch and only separated after they had already crossed.
        let layout = Layout::build(&factory(), &Live::default());
        let leaving: Vec<f64> = layout
            .edges
            .iter()
            .filter(|edge| edge.from == "a_developer" && !edge.back)
            .map(|edge| edge.from_y)
            .collect();

        assert!(leaving.len() >= 2, "the developer fans out");
        for pair in leaving.windows(2) {
            assert!(
                (pair[0] - pair[1]).abs() > 1.0,
                "two edges share an exit point: {leaving:?}"
            );
        }
    }

    #[test]
    fn a_node_with_one_edge_still_meets_it_in_the_middle() {
        let layout = Layout::build(&factory(), &Live::default());
        let analyst = layout.node("a_analyst").expect("analyst");
        let only = layout
            .edges
            .iter()
            .find(|edge| edge.from == "a_analyst" && !edge.back)
            .expect("analyst sends somewhere");

        assert!((only.from_y - analyst.centre().1).abs() < 0.001);
    }

    #[test]
    fn a_workflow_can_be_drawn_on_its_own() {
        // A factory holds several pipelines and they are genuinely separate workflows. Drawing
        // them together produces one tangle that reads as a single very confused process, which
        // is exactly what a reader concludes from it.
        let config = two_workflows();
        let sweep = Layout::scoped(&config, &Live::default(), &Scope::Pipeline("sweep".into()));

        assert!(sweep.node("p_sweep").is_some());
        assert!(sweep.node("a_sweeper").is_some());
        assert!(
            sweep.node("a_pr_reviewer").is_some(),
            "a spawned reviewer is part of the sweep"
        );
        assert!(sweep.node("p_build").is_none(), "the other way in is not");
        assert!(sweep.node("a_developer").is_none());
    }

    #[test]
    fn an_agent_in_two_workflows_appears_in_both() {
        // The honest answer. The developer really is in both pipelines, and hiding it from one
        // would misrepresent the factory to make a tidier picture.
        let config = two_workflows();

        for pipeline in ["build", "release"] {
            let drawn =
                Layout::scoped(&config, &Live::default(), &Scope::Pipeline(pipeline.into()));
            assert!(
                drawn.node("a_developer").is_some(),
                "developer missing from {pipeline}"
            );
        }
    }

    #[test]
    fn drawing_everything_is_still_the_default() {
        let config = two_workflows();
        let all = Layout::build(&config, &Live::default());

        assert!(all.node("p_sweep").is_some());
        assert!(all.node("p_build").is_some());
        assert!(all.node("a_pr_reviewer").is_some());
    }

    fn two_workflows() -> Config {
        config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.sweeper]
            prompt = "sweep"

            [agents.pr_reviewer]
            prompt = "review one"

            [agents.developer]
            prompt = "develop"

            [agents.publisher]
            prompt = "publish"

            [pipelines.sweep]
            entry = "sweeper"

            [pipelines.build]
            entry = "developer"

            [pipelines.release]
            entry = "developer"

            [[routes]]
            from = "sweeper"
            to = "pr_reviewer"
            mode = "spawn"

            [[routes]]
            from = "developer"
            to = "publisher"
            "#,
        )
    }

    #[test]
    fn a_spawn_target_is_drawn_right_of_the_agent_that_spawns_it() {
        // Breadth-first distance stops at a spawn edge, which is right for hop arithmetic and
        // wrong for a picture: it left the target at column zero beside its spawner, and the edge
        // between them became a same-column loop that read as a stray squiggle. Found by standing
        // up a real factory and looking at the dashboard.
        let config = config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.sweeper]
            prompt = "sweep"

            [agents.pr_reviewer]
            prompt = "review one"

            [pipelines.sweep]
            entry = "sweeper"

            [[routes]]
            from = "sweeper"
            to = "pr_reviewer"
            mode = "spawn"
            "#,
        );

        let layout = Layout::build(&config, &Live::default());
        let sweeper = layout.node("a_sweeper").expect("sweeper");
        let reviewer = layout.node("a_pr_reviewer").expect("reviewer");

        assert!(
            reviewer.layer > sweeper.layer,
            "a spawn should still flow rightwards: sweeper at {}, reviewer at {}",
            sweeper.layer,
            reviewer.layer
        );

        let edge = layout
            .edges
            .iter()
            .find(|edge| edge.to == "a_pr_reviewer")
            .expect("the spawn edge exists");
        assert!(!edge.back, "and must not be drawn as a return path");
    }

    #[test]
    fn an_agent_no_pipeline_can_reach_is_still_drawn() {
        // An unreachable agent is exactly what somebody opens the diagram to find, so dropping
        // it would defeat the purpose of drawing one.
        let config = config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.reachable]
            prompt = "work"

            [agents.orphan]
            prompt = "nobody routes here"

            [pipelines.go]
            entry = "reachable"
            "#,
        );

        let layout = Layout::build(&config, &Live::default());

        assert!(layout.node("a_orphan").is_some());
    }

    #[test]
    fn live_state_lands_on_the_right_node() {
        let live = Live::default().with("developer", Activity::Running);
        let layout = Layout::build(&factory(), &live);

        assert_eq!(
            layout.node("a_developer").expect("developer").activity,
            Some(Activity::Running)
        );
        assert_eq!(layout.node("a_analyst").expect("analyst").activity, None);
    }

    #[test]
    fn an_empty_factory_lays_out_without_panicking() {
        let config = config(
            r#"
            [layover]
            work_dir = "work"

            [defaults]
            runner = "claude"

            [runners.claude]
            command = ["claude", "-p"]

            [agents.only]
            prompt = "think"
            entry = true
            "#,
        );

        let layout = Layout::build(&config, &Live::default());

        assert_eq!(layout.nodes.len(), 1);
        assert!(layout.edges.is_empty());
    }
}