bat-cli 0.38.0

Blockchain Auditor Toolkit (BAT)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
//! A single HTTP client for the Miro REST API, with rate limiting and retries.
//!
//! The older helpers scattered across this module each build their own
//! `reqwest::Client`, `.unwrap()` on failures and ignore rate limiting. The
//! automatic deployment issues hundreds of calls in a row, so it needs:
//!
//! - one shared connection pool,
//! - a credit budget that matches Miro's published tiers (Level 2 = 100 credits,
//!   global budget 100_000 credits/minute per user+app),
//! - bounded concurrency,
//! - retries with backoff on `429` and `5xx`, honouring `X-RateLimit-Reset`.

use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use error_stack::{IntoReport, Report, Result, ResultExt};
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use reqwest::{multipart, StatusCode};
use serde_json::{json, Value};
use tokio::sync::{Mutex, Semaphore};

use crate::batbelt::miro::{MiroConfig, MiroError};

/// Credit cost of a Level 2 endpoint (frames, images, connectors, items).
pub const LEVEL_2_CREDITS: u32 = 100;
/// Credit cost of a Level 1 endpoint (reads).
pub const LEVEL_1_CREDITS: u32 = 50;
/// Miro's global budget, per user and application: 100 000 credits a minute, over 100 credits
/// a write, is 16.7 writes a second. Kept here as the thing [`WRITES_PER_SECOND`] is under.
#[allow(dead_code)]
const CREDITS_PER_MINUTE: u32 = 100_000;
/// Writes a second the bucket below refills at.
///
/// Miro's credit arithmetic says 16.7 a second — 100 000 credits a minute over 100 a write —
/// and the board does not behave like it. Measured on the same 2 103-request map:
///
/// - no pacing at all: the requests left in **38s**, about 55 a second, and drew 4 refusals
/// - paced at 15 a second: 1 refusal, and the work itself took **197s**
///
/// The second is slower overall (256s against 223s). So what Miro refuses is not a sustained
/// rate anywhere near its documented ceiling — it is the BURST, which is why ninety-six permits
/// hurt and forty-eight did not. Pacing at the credit ceiling pays 100 seconds to save 126 of
/// waiting, which is close to no trade at all.
///
/// 40 is above the arithmetic and far below the 55 a second that drew four refusals: the burst
/// is what [`BURST_CREDITS`] caps, and this is the rate after it.
pub const WRITES_PER_SECOND: f64 = 40.0;
/// The refill rate in credits.
const CREDITS_PER_SECOND: f64 = WRITES_PER_SECOND * LEVEL_2_CREDITS as f64;
/// How much may leave AT ONCE, after the client has been idle.
///
/// 5 000 credits is fifty writes — about one round of [`MAX_CONCURRENT_REQUESTS`] — so a burst
/// the permits already allow still goes out in one go, and everything after it is paced. The
/// pacing is the whole point: the budget used to count over a minute, so a run could spend the
/// entire minute's credits in its first second, and a burst is precisely what Miro answers
/// with a 429.
const BURST_CREDITS: f64 = 5_000.0;
/// How many requests we allow in flight at once, across the whole run — one client is
/// shared by every frame, so this counts images, connectors, markers and frames together.
///
/// It was 6, chosen with no recorded reason, and a 34-frame cluster of ~2 000 calls took
/// 16 minutes where the credit budget alone (100 000/minute at 100 per level-2 call, so
/// ~16 calls a second) allows about two. The ceiling was us, not Miro. The budget is still
/// enforced locally by the token bucket below, so a higher number cannot overrun it: it
/// just reaches the bucket sooner and waits there. 429s and 5xx retry with backoff, so if
/// the board pushes back the cost is visible in the retry warnings rather than in failures.
///
/// Raised to 48 once frames began filling 16 at a time. At 24 a 30-frame cluster showed
/// **zero** `credit budget exhausted` waits and zero retries — the bucket was never
/// reached, so the permits were what held the line, not Miro. Raising this cannot overrun
/// the board either way: the bucket below enforces the real rate locally, so a higher
/// number only arrives there sooner and waits. That warning is the signal to watch — once
/// it appears, Miro's 1 000 writes a minute is the ceiling and raising this buys nothing.
///
/// Raised to 96 when the map began drawing connectors by the hundred — a connector cannot be
/// batched, `/items/bulk` takes items only — and put straight back to 48, measured on the same
/// frame twice:
///
/// - 96 permits: 59 requests, **2 retries**, **126s**
/// - 48 permits: 59 requests, **0 retries**, **11s**
///
/// Eleven times faster with half the permits. 24 was then tried on the same map, on the
/// reasoning that 48 still drew four refusals out of 2 103 requests and sat out 185 seconds of
/// them, against maybe ten seconds of extra rounds. The reasoning was wrong: the whole map takes
/// 223s at 48 and was not past its second frame after six minutes at 24. Rounds are not ten
/// seconds here, they are most of the run.
///
/// So 48 is the measured floor as well as the measured ceiling, and the next thing to try is not
/// another permit count: it is spacing the requests out in TIME. The budget below counts credits
/// over a minute and let the minute leave at once, which is the burst Miro refuses. That is now
/// the bucket's job, below, and this is back to being only a cap on how many sockets are open.
///
/// A 429 from Miro carries a `Retry-After` of a minute, so one of them costs more than any
/// amount of parallelism buys. The signal to watch is in the run's last line, which prints the
/// retries AND what they cost — the two are not proportional, and the seconds explain the clock.
const MAX_CONCURRENT_REQUESTS: usize = 48;
const MAX_ATTEMPTS: u32 = 5;

/// How many permits a request of this cost takes.
///
/// One per write it performs, so a bulk of twenty takes twenty and a single item takes one. A
/// read is cheaper than a write and still takes one: it is a round trip like any other.
/// Capped at the whole pool, or a batch larger than the pool could never be admitted at all.
fn permits_for(credits: u32) -> u32 {
    (credits / LEVEL_2_CREDITS).clamp(1, MAX_CONCURRENT_REQUESTS as u32)
}

/// Token bucket over Miro's credit budget.
///
/// A real bucket now, refilling continuously, rather than a window that resets on the minute.
/// The window held the right average and allowed the wrong shape: 100 000 credits were
/// available the instant it opened, so 2 000 requests left as fast as the sockets allowed, the
/// board answered 429, and each of those cost a minute of `Retry-After` — 185 of the 223
/// seconds one map took.
#[derive(Debug)]
struct CreditBudget {
    /// When the bucket was last topped up.
    last: Instant,
    /// Credits in it right now, capped at [`BURST_CREDITS`].
    available: f64,
}

/// Shared, cheap to clone.
#[derive(Clone)]
pub struct MiroClient {
    http: reqwest::Client,
    access_token: String,
    board_id: String,
    board_url: String,
    budget: Arc<Mutex<CreditBudget>>,
    permits: Arc<Semaphore>,
    /// How often the board pushed back, and how often our own budget made us wait. Two
    /// numbers that turn "it took a while" into a cause: a run at the credit ceiling with no
    /// retries is Miro's floor, and a run full of retries is the board rate-limiting us.
    retries: Arc<std::sync::atomic::AtomicU32>,
    budget_waits: Arc<std::sync::atomic::AtomicU32>,
    /// Requests actually SENT, and credits actually spent.
    ///
    /// The map prints how many calls it planned, which is a number computed before the board is
    /// touched: it counts the items to create and nothing else. Every read is missing from it —
    /// listing the board, reading a frame's shapes back, asking an item its geometry — and a
    /// read costs 50 credits of the same budget the writes are paced against. A plan is not a
    /// measurement, and only one of the two can say where the budget went.
    sent: Arc<std::sync::atomic::AtomicU32>,
    credits_spent: Arc<std::sync::atomic::AtomicU32>,
    /// Seconds slept waiting out a 429 or a 5xx, across every request.
    ///
    /// The count of retries says the board pushed back; it does not say what that cost, and the
    /// two are not proportional: Miro answers a 429 with a `Retry-After` of a minute, so two
    /// retries are two minutes whatever else the run was doing. A command that drew 59 items in
    /// 126 seconds looked like a command that had become slow, and was a command that waited
    /// out two of those.
    retry_seconds: Arc<std::sync::atomic::AtomicU32>,
}

/// A frame as returned by the board.
#[derive(Debug, Clone)]
pub struct FrameChild {
    pub id: String,
    /// What the item was created with: a screenshot carries its function's label, a shape
    /// (link card, connector marker, border) carries nothing.
    pub title: String,
    pub kind: String,
    /// Frame-local: origin at the frame's top-left, x/y the item's centre.
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

#[derive(Debug, Clone)]
pub struct BoardFrame {
    pub id: String,
    pub title: String,
    /// Center of the frame, in board coordinates.
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl BoardFrame {
    pub fn bottom(&self) -> f64 {
        self.y + self.height / 2.0
    }
    pub fn left(&self) -> f64 {
        self.x - self.width / 2.0
    }
}

/// Where a connector attaches to an item: a relative offset in percent, where
/// `(0%, 0%)` is the item's top-left corner.
#[derive(Debug, Clone, Copy)]
pub struct RelativeAnchor {
    pub x_fraction: f64,
    pub y_fraction: f64,
}

impl RelativeAnchor {
    pub fn new(x_fraction: f64, y_fraction: f64) -> Self {
        Self {
            x_fraction: x_fraction.clamp(0.0, 1.0),
            y_fraction: y_fraction.clamp(0.0, 1.0),
        }
    }

    fn to_json(self) -> Value {
        json!({
            "x": format!("{:.2}%", self.x_fraction * 100.0),
            "y": format!("{:.2}%", self.y_fraction * 100.0),
        })
    }
}

/// How a connector's line is drawn. Three values, and each means a different thing on the
/// board, so they are never interchangeable:
///
/// - `Solid` is an ordinary call.
/// - `Dashed` is a cycle — an edge back to something already on the path.
/// - `Dotted` is a colour being reused: when a gutter holds more arrows than the palette
///   has hues, the repeats are dotted so two neighbours are still two arrows. It exists
///   because the overflow used to be dashed AND the same colour, which made two of them
///   indistinguishable from each other and from a cycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ConnectorStroke {
    #[default]
    Solid,
    Dashed,
    Dotted,
}

impl ConnectorStroke {
    fn as_miro(self) -> &'static str {
        match self {
            Self::Solid => "normal",
            Self::Dashed => "dashed",
            Self::Dotted => "dotted",
        }
    }

    /// The stroke to use when two reasons for one apply at once. A cycle outranks a
    /// repeated colour: "this goes backwards" is the more important thing to see.
    pub fn strongest(self, other: Self) -> Self {
        match (self, other) {
            (Self::Dashed, _) | (_, Self::Dashed) => Self::Dashed,
            (Self::Dotted, _) | (_, Self::Dotted) => Self::Dotted,
            _ => Self::Solid,
        }
    }
}

/// Style of one connector.
#[derive(Debug, Clone)]
pub struct ConnectorStyle {
    pub stroke_color: String,
    pub stroke_width: String,
    pub stroke: ConnectorStroke,
    pub caption: Option<String>,
    /// Which end of the connector carries the arrow head, if any.
    pub arrow: ArrowEnd,
}

/// Where a connector's arrow head goes.
///
/// [`ArrowEnd::None`] exists for the middle of a chained edge: an edge routed
/// through invisible bend points is several connectors that must read as one
/// line, so only the last of them may carry a head. Without this, the others
/// draw an arrow pointing at a bend point nobody can see.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ArrowEnd {
    /// On `startItem`. The graph is built caller → callee, but the arrow reads
    /// better pointing the other way: it lands on the exact line that makes the
    /// call, so the picture says "this dependency is used *here*" rather than
    /// restating the direction the layout already shows.
    Start,
    /// On `endItem`.
    End,
    /// Neither end.
    None,
}

impl Default for ConnectorStyle {
    fn default() -> Self {
        Self {
            stroke_color: "#2d9bf0".to_string(),
            stroke_width: "3".to_string(),
            stroke: ConnectorStroke::Solid,
            caption: None,
            arrow: ArrowEnd::Start,
        }
    }
}

impl MiroClient {
    pub fn new() -> Result<Self, MiroError> {
        let MiroConfig {
            access_token,
            board_id,
            board_url,
        } = MiroConfig::new()?;
        Ok(Self {
            http: reqwest::Client::new(),
            access_token,
            board_id,
            board_url,
            retries: Arc::new(std::sync::atomic::AtomicU32::new(0)),
            budget_waits: Arc::new(std::sync::atomic::AtomicU32::new(0)),
            retry_seconds: Arc::new(std::sync::atomic::AtomicU32::new(0)),
            sent: Arc::new(std::sync::atomic::AtomicU32::new(0)),
            credits_spent: Arc::new(std::sync::atomic::AtomicU32::new(0)),
            budget: Arc::new(Mutex::new(CreditBudget {
                last: Instant::now(),
                // Full, so the first round of a run is not paced for no reason.
                available: BURST_CREDITS,
            })),
            permits: Arc::new(Semaphore::new(MAX_CONCURRENT_REQUESTS)),
        })
    }

    /// Build a client after making sure the globally stored token is still
    /// valid, refreshing it when the app issues expiring tokens.
    pub async fn new_refreshed() -> Result<Self, MiroError> {
        crate::batbelt::miro::auth::refresh_if_needed().await?;
        Self::new()
    }

    pub fn board_url(&self) -> &str {
        &self.board_url
    }

    pub fn frame_url(&self, frame_id: &str) -> String {
        format!("{}/?moveToWidget={}", self.board_url.trim_end_matches('/'), frame_id)
    }

    fn endpoint(&self, path: &str) -> String {
        format!("https://api.miro.com/v2/boards/{}/{}", self.board_id, path)
    }

    /// Wait until `credits` are in the bucket, then take them.
    ///
    /// The wait is how long THOSE credits take to refill — 60ms for one write — rather than
    /// "until this minute is over", which is what the window version slept and is why a run
    /// that overshot paid for it in whole minutes.
    async fn reserve(&self, credits: u32) {
        let credits = credits as f64;
        loop {
            let wait = {
                let mut budget = self.budget.lock().await;
                let now = Instant::now();
                let refilled = now.duration_since(budget.last).as_secs_f64() * CREDITS_PER_SECOND;
                budget.available = (budget.available + refilled).min(BURST_CREDITS);
                budget.last = now;
                if budget.available >= credits {
                    budget.available -= credits;
                    return;
                }
                let short = credits - budget.available;
                self.budget_waits
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                Duration::from_secs_f64(short / CREDITS_PER_SECOND)
            };
            log::debug!("pacing a Miro request by {:?}", wait);
            tokio::time::sleep(wait).await;
        }
    }

    /// Run a request with rate limiting, retries and error reporting.
    ///
    /// `make` is a closure rather than a prepared request because a multipart
    /// body cannot be cloned, so a retry has to rebuild it from scratch.
    async fn execute<F>(&self, credits: u32, label: &str, make: F) -> Result<Value, MiroError>
    where
        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
    {
        // A permit per WRITE this request performs, not one per request.
        //
        // A bulk call carrying twenty items took one permit and created twenty things, so 48
        // permits meant 960 items could be in flight at once — and the board defends itself
        // against items, not against sockets. It showed: the bulk wave sent 74 requests in
        // 120 seconds, 1.6s each, while the connector wave sent 760 in 40. Same client, same
        // budget, same permits; the only difference is that one request in the first wave is
        // worth twenty of the second.
        //
        // Costing the permit in writes makes a bulk take twenty of them, so the big calls
        // self-limit to a couple at a time while the small ones still go 48 wide.
        let _permit = self
            .permits
            .acquire_many(permits_for(credits))
            .await
            .into_report()
            .change_context(MiroError)?;

        let mut attempt = 0;
        loop {
            attempt += 1;
            self.reserve(credits).await;

            self.sent.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            self.credits_spent
                .fetch_add(credits, std::sync::atomic::Ordering::Relaxed);
            let response = make(&self.http)
                .header(AUTHORIZATION, format!("Bearer {}", self.access_token))
                .send()
                .await;

            let response = match response {
                Ok(response) => response,
                Err(error) => {
                    if attempt >= MAX_ATTEMPTS {
                        return Err(Report::new(MiroError)
                            .attach_printable(format!("{label}: transport error: {error}")));
                    }
                    let backoff = Duration::from_millis(400 * 2u64.pow(attempt - 1));
                    log::warn!("{label}: transport error {error}, retrying in {backoff:?}");
                    tokio::time::sleep(backoff).await;
                    continue;
                }
            };

            let status = response.status();
            if status.is_success() {
                let body = response
                    .text()
                    .await
                    .into_report()
                    .change_context(MiroError)?;
                if body.trim().is_empty() {
                    return Ok(Value::Null);
                }
                return serde_json::from_str(&body)
                    .into_report()
                    .change_context(MiroError)
                    .attach_printable_lazy(|| format!("{label}: malformed JSON: {body}"));
            }

            let retryable = status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error();
            if !retryable || attempt >= MAX_ATTEMPTS {
                let body = response.text().await.unwrap_or_default();
                return Err(Report::new(MiroError)
                    .attach_printable(format!("{label}: HTTP {status}: {body}")));
            }

            let wait = retry_after(&response).unwrap_or_else(|| {
                Duration::from_millis(500 * 2u64.pow(attempt - 1))
            });
            self.retries.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            log::warn!("{label}: HTTP {status}, retrying in {wait:?} (attempt {attempt})");
            self.retry_seconds
                .fetch_add(wait.as_secs() as u32, std::sync::atomic::Ordering::Relaxed);
            tokio::time::sleep(wait).await;
        }
    }

    /// Every frame currently on the board, following cursor pagination.
    /// Every LOOSE shape on the board — one that is not inside a frame — with its text.
    ///
    /// Used to find this tool's own cards again when the registry cannot say where they are.
    /// A registry is a convenience; the board is the truth, and a card that outlives its record
    /// is a card nobody can clean up. It happened: a binary that did not know the `miro.map`
    /// field rewrote `BatMetadata.json` without it, and the next run drew a second set of cards
    /// on top of the first.
    pub async fn list_loose_shapes(&self) -> Result<Vec<(String, String)>, MiroError> {
        let mut shapes = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let cursor_for_request = cursor.clone();
            let url = self.endpoint("items");
            let value = self
                .execute(LEVEL_1_CREDITS, "list_loose_shapes", move |http| {
                    let mut request = http.get(&url).query(&[("type", "shape"), ("limit", "50")]);
                    if let Some(ref cursor) = cursor_for_request {
                        request = request.query(&[("cursor", cursor.as_str())]);
                    }
                    request
                })
                .await?;

            if let Some(items) = value["data"].as_array() {
                for item in items {
                    // Inside a frame it belongs to a diagram, not to the open board.
                    if !item["parent"].is_null() {
                        continue;
                    }
                    shapes.push((
                        item["id"].as_str().unwrap_or_default().to_string(),
                        item["data"]["content"].as_str().unwrap_or_default().to_string(),
                    ));
                }
            }

            match value["cursor"].as_str() {
                Some(next) if !next.is_empty() => cursor = Some(next.to_string()),
                _ => break,
            }
        }
        Ok(shapes)
    }

    pub async fn list_frames(&self) -> Result<Vec<BoardFrame>, MiroError> {
        let mut frames = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let cursor_for_request = cursor.clone();
            let url = self.endpoint("items");
            let value = self
                .execute(LEVEL_1_CREDITS, "list_frames", move |http| {
                    let mut request = http.get(&url).query(&[("type", "frame"), ("limit", "50")]);
                    if let Some(ref cursor) = cursor_for_request {
                        request = request.query(&[("cursor", cursor.as_str())]);
                    }
                    request
                })
                .await?;

            if let Some(items) = value["data"].as_array() {
                for item in items {
                    frames.push(BoardFrame {
                        id: item["id"].as_str().unwrap_or_default().to_string(),
                        title: item["data"]["title"].as_str().unwrap_or_default().to_string(),
                        x: item["position"]["x"].as_f64().unwrap_or(0.0),
                        y: item["position"]["y"].as_f64().unwrap_or(0.0),
                        width: item["geometry"]["width"].as_f64().unwrap_or(0.0),
                        height: item["geometry"]["height"].as_f64().unwrap_or(0.0),
                    });
                }
            }

            match value["cursor"].as_str() {
                Some(next) if !next.is_empty() => cursor = Some(next.to_string()),
                _ => break,
            }
        }
        Ok(frames)
    }

    /// Create a frame sized to the computed layout. `x`/`y` are the center, in
    /// board coordinates.
    /// `fill` tints the frame's own background — the API offers no border on a frame,
    /// and a shape laid over one is an extra item to create, track and delete.
    pub async fn create_frame(
        &self,
        title: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        fill: Option<&str>,
    ) -> Result<String, MiroError> {
        let url = self.endpoint("frames");
        let mut data = json!({ "title": title, "format": "custom", "type": "freeform" });
        let mut body = json!({
            "data": data.take(),
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
        });
        if let Some(fill) = fill {
            body["style"] = json!({ "fillColor": fill });
        }
        let body = body.to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_frame", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;

        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// A translucent red band over a single code line, marking the exact
    /// statement that writes contract storage. `y` is the line centre and
    /// `height` one line tall; the fill is semi-transparent so the code stays
    /// readable underneath.
    pub async fn create_line_highlight(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        self.create_colored_line_band(frame_id, x, y, width, height, "#f24726").await
    }

    /// The same band in any colour. Blue is what `bat-cli highlight` draws: a mark the
    /// assistant puts on a line for the auditor to find, which must not be mistaken for the
    /// red one the deploy puts on a state change — those mean something about the code.
    pub async fn create_colored_line_band(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        color: &str,
    ) -> Result<String, MiroError> {
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": {
                "fillColor": color,
                "fillOpacity": "0.30",
                "borderColor": color,
                "borderWidth": "2",
                "borderOpacity": "0.9",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_line_band", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// A hollow rectangle at the FRAME's own bounds, so a frame carrying a highlight is
    /// recognisable from the zoom where a whole cluster fits on screen.
    ///
    /// Not the frame's border: Miro's REST API does not set one (see §19 of
    /// docs/diagram-deploy-design.md, where the state tint had to become the frame's FILL
    /// for the same reason). The fill is spoken for — pale red and amber already say
    /// whether the frame changes state — so an outline it is. It costs one item, which is
    /// the objection that ruled it out for the tint, and here it does not apply: this mark
    /// is temporary and `--clear` already deletes what it created.
    /// A heading on the board itself: one contract's name above its column of deployments.
    ///
    /// A shape rather than a sticky note, and not a frame: `list_frames` only ever returns
    /// frames, so anything else is invisible to every placement scan this tool does — which
    /// is what you want for a label (it must not push a column around) and exactly what you
    /// do not want for a frame. Drawn at board level, with no parent, because a column is not
    /// an item and has nothing to be a child of.
    ///
    /// `x`/`y` are the centre, in board coordinates.
    pub async fn create_board_label(
        &self,
        text: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        font_size: usize,
    ) -> Result<String, MiroError> {
        self.create_label(text, x, y, width, height, font_size, "#ffffff", None)
            .await
    }

    /// The same, with a fill colour and an optional parent frame — a box on a diagram rather
    /// than a heading on the board.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_label(
        &self,
        text: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        font_size: usize,
        fill: &str,
        parent: Option<&str>,
    ) -> Result<String, MiroError> {
        self.create_label_bordered(text, x, y, width, height, font_size, fill, "#1a1a1a", parent)
            .await
    }

    /// The same again, with the border colour chosen too. The map uses the border to say
    /// what a box DOES — amber for a contract that calls past the repository — because the
    /// fill is already taken by what a box IS, and a colour that means two things means none.
    #[allow(clippy::too_many_arguments)]
    /// Create up to 20 items in ONE call: Miro's bulk endpoint.
    ///
    /// The map's boxes, badges and markers are hundreds of items that depend on nothing but
    /// their frame, and sending them one by one is hundreds of round trips. Concurrency does
    /// not fix that on its own — 226 calls at 48 in flight still took 75 seconds against a
    /// budget that allows 16.7 writes a second, because the wall is per-request latency and
    /// not the budget. Twenty items a call is twenty times fewer waits on the same wire.
    ///
    /// Connectors are NOT bulk-createable (the endpoint takes items only), so an arrow's legs
    /// still go one by one; its markers do not.
    ///
    /// Returns the created items' ids, in the order they were sent, which is what lets a
    /// marker be found again by the leg that lands on it.
    /// Create ONE item, through `/items` rather than `/items/bulk`.
    ///
    /// Worth having beside the bulk call because the two have different shapes of cost. A bulk
    /// of twenty takes about 1.6s to come back, so 68 of them — every box and marker of a map —
    /// take 110 seconds however many are in flight. The 760 connectors of the same map, sent one
    /// at a time, took 39 seconds: nineteen a second. Latency per call dominates, and a call
    /// that carries one item has the same latency as a call that carries twenty.
    pub async fn create_item(&self, mut item: Value) -> Result<String, MiroError> {
        // By TYPE, because `/items` only answers GET: Miro creates through one endpoint per
        // kind, and the `type` field the bulk endpoint needs is what names the endpoint here —
        // so it is read off and then removed, since the typed endpoint rejects it.
        let kind = item
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("shape")
            .to_string();
        if let Some(object) = item.as_object_mut() {
            object.remove("type");
        }
        let url = self.endpoint(&format!("{kind}s"));
        let body = item.to_string();
        let value = self
            .execute(LEVEL_2_CREDITS, "create_item", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        value["id"]
            .as_str()
            .map(str::to_string)
            .ok_or_else(|| {
                Report::new(MiroError)
                    .attach_printable(format!("create_item: no id in the answer: {value}"))
            })
    }

    pub async fn create_items_bulk(&self, items: Vec<Value>) -> Result<Vec<String>, MiroError> {
        if items.is_empty() {
            return Ok(Vec::new());
        }
        // ONE item is not a bulk: `/items` takes it directly, and the bulk endpoint's two
        // behaviours — collapsing identical items, and answering in the order it was sent —
        // are only worth working around when there is a batch to gain from them.
        if items.len() == 1 {
            let item = items.into_iter().next().expect("checked");
            return self.create_item(item).await.map(|id| vec![id]);
        }
        let url = self.endpoint("items/bulk");
        // Priced as what it creates: the budget is about items, not about TCP connections, and
        // pretending a bulk call costs one level-2 write is how a budget stops protecting
        // anything.
        let credits = LEVEL_2_CREDITS * items.len() as u32;
        let body = Value::Array(items).to_string();
        let value = self
            .execute(credits, "create_items_bulk", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        let created = value
            .get("data")
            .and_then(Value::as_array)
            .cloned()
            .or_else(|| value.as_array().cloned())
            .ok_or_else(|| {
                Report::new(MiroError)
                    .attach_printable(format!("create_items_bulk: no items in the answer: {value}"))
            })?;
        Ok(created
            .iter()
            .map(|item| item["id"].as_str().unwrap_or_default().to_string())
            .collect())
    }

    /// A card that points at a frame, as the bulk endpoint wants it, and with NO parent: these
    /// sit on the open board above a cluster's shape, not inside any frame.
    ///
    /// The link is an `<a href>` inside the text because Miro's REST API rejects `linkedTo`
    /// outright (see CLAUDE.md). That is also why the words have to carry the fact: if the
    /// frame is deleted the card still says which one it was.
    #[allow(clippy::too_many_arguments)]
    pub fn link_card_item(
        text: &str,
        target_url: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        font_size: usize,
        fill: &str,
        border: &str,
    ) -> Value {
        json!({
            "type": "shape",
            "data": {
                "shape": "round_rectangle",
                "content": format!(
                    "<p><a href=\"{}\">{}</a></p>",
                    html_escape(target_url),
                    html_escape(text)
                ),
            },
            "style": {
                "fillColor": fill,
                "fillOpacity": "1.0",
                "borderColor": border,
                "borderWidth": "4",
                "borderOpacity": "1.0",
                "color": border,
                "fontSize": font_size.to_string(),
                "textAlign": "center",
                "textAlignVertical": "middle",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
        })
    }

    /// One invisible anchor marker, as the bulk endpoint wants it.
    pub fn marker_item(x: f64, y: f64, size: f64, parent: &str) -> Value {
        json!({
            "type": "shape",
            "data": { "shape": "rectangle" },
            "style": { "fillOpacity": "0.0", "borderOpacity": "0.0" },
            "position": { "x": x, "y": y },
            "geometry": { "width": size, "height": size },
            "parent": { "id": parent },
        })
    }

    /// One box of the map, as the bulk endpoint wants it. Same shape as `create_label_bordered`
    /// writes, so the two cannot drift.
    #[allow(clippy::too_many_arguments)]
    pub fn label_item(
        text: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        font_size: usize,
        fill: &str,
        border: &str,
        // Miro refuses anything from 24 up, so that is the ceiling a caller can ask for.
        border_width: usize,
        // The text's own colour. A border is a hairline at the zoom where a whole frame fits;
        // the name is 120pt, so colouring the glyphs is what actually carries at a distance.
        text_colour: &str,
        // `"normal"` or `"dotted"`: the third channel a box has, after its fill and the colour
        // of its border.
        border_style: &str,
        parent: &str,
    ) -> Value {
        json!({
            "type": "shape",
            // One `<p>` per line: a box whose name was too wide to fit its column wraps, and a
            // `\n` in HTML is whitespace. Each line escaped on its own, so the escaping cannot
            // eat the break.
            "data": {
                "shape": "rectangle",
                "content": text
                    .split('\n')
                    .map(|line| format!("<p><b>{}</b></p>", html_escape(line)))
                    .collect::<Vec<_>>()
                    .join(""),
            },
            "style": {
                "fillColor": fill,
                "fillOpacity": "1.0",
                "borderColor": border,
                "borderWidth": border_width.min(23).to_string(),
                "borderStyle": border_style,
                "borderOpacity": "1.0",
                "color": text_colour,
                "fontSize": font_size.to_string(),
                "textAlign": "center",
                "textAlignVertical": "middle",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
            "parent": { "id": parent },
        })
    }

    pub async fn create_label_bordered(
        &self,
        text: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        font_size: usize,
        fill: &str,
        border: &str,
        parent: Option<&str>,
    ) -> Result<String, MiroError> {
        let url = self.endpoint("shapes");
        let mut body = json!({
            "data": {
                "shape": "rectangle",
                "content": format!("<p><b>{}</b></p>", html_escape(text)),
            },
            "style": {
                "fillColor": fill,
                "fillOpacity": "1.0",
                "borderColor": border,
                "borderWidth": "4",
                "borderOpacity": "1.0",
                "color": "#1a1a1a",
                "fontSize": font_size.to_string(),
                "textAlign": "center",
                "textAlignVertical": "middle",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
        });
        if let Some(frame_id) = parent {
            body["parent"] = json!({ "id": frame_id });
        }
        let body = body.to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_board_label", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    pub async fn create_frame_outline(
        &self,
        frame_id: &str,
        frame_width: f64,
        frame_height: f64,
        color: &str,
    ) -> Result<String, MiroError> {
        // Flush with the frame's edge, on the outside of it. The stroke is centred on the
        // rectangle's path, so a rectangle one stroke wider than the frame puts the inner
        // half of the line exactly on the edge and the outer half beyond it — against the
        // board, where nothing else is, and clear of the frame's title.
        let outset = 24.0;
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": {
                "fillOpacity": "0.0",
                "borderColor": color,
                // 24 is Miro's ceiling: anything above it is refused with
                // `style.borderWidth: Expected valid decimal number: must be less than 24.0`.
                // So "thicker" is bought with the outset, not the stroke.
                "borderWidth": "24",
                "borderOpacity": "1.0",
            },
            "position": { "x": frame_width / 2.0, "y": frame_height / 2.0 },
            "geometry": { "width": frame_width + outset, "height": frame_height + outset },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_frame_outline", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// A hollow BLUE rectangle around a screenshot that carries a highlight, so the box
    /// holding the marked line is findable from across the frame.
    ///
    /// Drawn thinner and tighter than the red and amber borders on purpose: those say
    /// something about the code and this only says "look here", so when a screenshot
    /// carries both, the claim stays legible and the pointer sits inside it.
    pub async fn create_highlight_border(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        color: &str,
    ) -> Result<String, MiroError> {
        let pad = 16.0;
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": {
                "fillOpacity": "0.0",
                "borderColor": color,
                "borderWidth": "8",
                "borderOpacity": "1.0",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width + pad, "height": height + pad },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_highlight_border", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// A hollow SOLID amber rectangle around a whole node whose function makes a
    /// non-view call to an external contract with no in-scope source but writes no
    /// storage of its own — so at a glance the board says "a state change PROBABLY
    /// happens here", the amber counterpart of the solid-red storage border.
    pub async fn create_external_border(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        let pad = 60.0;
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": {
                "fillOpacity": "0.0",
                "borderColor": "#ff9900",
                "borderWidth": "24",
                "borderOpacity": "1.0",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width + pad, "height": height + pad },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_external_border", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// A dashed amber band over a code line that calls an external contract with
    /// no in-scope source. Distinct from the solid-red proven-write highlight: this
    /// marks an UNVERIFIED external state-change boundary (a non-view call whose
    /// concrete target — and its storage effect — is unknown).
    pub async fn create_external_marker(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": {
                "fillColor": "#ffcc00",
                "fillOpacity": "0.18",
                "borderColor": "#ff9900",
                "borderWidth": "2",
                "borderOpacity": "0.9",
                "borderStyle": "dashed",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_external_marker", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// Move an existing item (an image, say) to a new position inside its parent
    /// frame — used by `deploy --refresh-links` to re-lay-out reused screenshots
    /// without re-uploading them. Position is the item CENTER, relative to the
    /// parent, matching how the items were created.
    /// Every shape INSIDE a frame, with its text: what the frame is made of.
    pub async fn shapes_in_frame(&self, frame_id: &str) -> Result<Vec<(String, String)>, MiroError> {
        let mut shapes = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let cursor_for_request = cursor.clone();
            // `/items?parent_item_id=`, not `/frames/{id}/items`, which Miro answers with
            // `404 No endpoint`. It had been failing on every call, and the one place that
            // reads it treated a failed read as "nothing to repaint" — so `mark --apply` said
            // `0 of 0` and nobody could see that the request had never worked at all.
            let url = self.endpoint("items");
            let parent = frame_id.to_string();
            let value = self
                .execute(LEVEL_1_CREDITS, "shapes_in_frame", move |http| {
                    let mut request = http.get(&url).query(&[
                        ("parent_item_id", parent.as_str()),
                        ("type", "shape"),
                        ("limit", "50"),
                    ]);
                    if let Some(ref cursor) = cursor_for_request {
                        request = request.query(&[("cursor", cursor.as_str())]);
                    }
                    request
                })
                .await?;
            if let Some(items) = value["data"].as_array() {
                for item in items {
                    shapes.push((
                        item["id"].as_str().unwrap_or_default().to_string(),
                        item["data"]["content"].as_str().unwrap_or_default().to_string(),
                    ));
                }
            }
            match value["cursor"].as_str() {
                Some(next) if !next.is_empty() => cursor = Some(next.to_string()),
                _ => break,
            }
        }
        Ok(shapes)
    }

    /// Repaint one shape: its fill, nothing else.
    ///
    /// A PATCH rather than a redraw, because changing which contracts stand out must not cost a
    /// map: `bat-cli map` never replaces, so a redraw leaves another generation of frames on the
    /// board for the auditor to clean up.
    pub async fn recolour_shape(&self, item_id: &str, fill: &str) -> Result<(), MiroError> {
        let url = format!("{}/{}", self.endpoint("shapes"), item_id);
        let body = json!({ "style": { "fillColor": fill } }).to_string();
        self.execute(LEVEL_2_CREDITS, "recolour_shape", move |http| {
            http.patch(&url)
                .header(CONTENT_TYPE, "application/json")
                .body(body.clone())
        })
        .await?;
        Ok(())
    }

    pub async fn update_item_position(
        &self,
        item_id: &str,
        x: f64,
        y: f64,
    ) -> Result<(), MiroError> {
        let url = self.endpoint(&format!("items/{item_id}"));
        let body = json!({ "position": { "x": x, "y": y } }).to_string();
        self.execute(LEVEL_1_CREDITS, "update_item_position", move |http| {
            http.patch(&url)
                .header(CONTENT_TYPE, "application/json")
                .body(body.clone())
        })
        .await?;
        Ok(())
    }

    /// Reposition and resize an existing frame in place, keeping its id.
    ///
    /// Redeploying a function recycles its frame instead of deleting it, because
    /// other diagrams may link to that frame by URL (`?moveToWidget=<frame_id>`)
    /// and a fresh frame would break those links. We wipe the contents and reflow
    /// them into the same frame, resized to the new layout.
    pub async fn update_frame(
        &self,
        frame_id: &str,
        title: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<(), MiroError> {
        let url = self.endpoint(&format!("frames/{frame_id}"));
        let body = json!({
            "data": { "title": title },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
        })
        .to_string();

        self.execute(LEVEL_2_CREDITS, "update_frame", move |http| {
            http.patch(&url)
                .header(CONTENT_TYPE, "application/json")
                .body(body.clone())
        })
        .await?;
        Ok(())
    }

    /// Upload a PNG **already positioned, sized and parented**.
    ///
    /// This is the call the previous implementation was missing: without the
    /// `data` part the image lands at the board origin with no parent, which is
    /// why screenshots had to be dragged into place by hand afterwards.
    ///
    /// `x`/`y` are the center of the image relative to the **top-left corner of
    /// the parent frame**. Only `width` is sent: image geometry keeps a fixed
    /// aspect ratio, so setting both width and height is rejected.
    pub async fn create_image_in_frame(
        &self,
        png_path: &str,
        frame_id: &str,
        title: &str,
        x: f64,
        y: f64,
        width: f64,
    ) -> Result<String, MiroError> {
        let bytes = std::fs::read(png_path)
            .into_report()
            .change_context(MiroError)
            .attach_printable_lazy(|| format!("cannot read screenshot {png_path}"))?;

        if bytes.len() > 6 * 1024 * 1024 {
            return Err(Report::new(MiroError).attach_printable(format!(
                "{png_path} is {} MB; Miro rejects images over 6 MB",
                bytes.len() / (1024 * 1024)
            )));
        }

        let file_name = png_path
            .rsplit('/')
            .next()
            .unwrap_or("screenshot.png")
            .to_string();

        let metadata = json!({
            "title": title,
            "position": { "x": x, "y": y },
            "geometry": { "width": width },
            "parent": { "id": frame_id },
        })
        .to_string();

        let url = self.endpoint("images");
        let value = self
            .execute(LEVEL_2_CREDITS, "create_image", move |http| {
                let part = multipart::Part::bytes(bytes.clone())
                    .file_name(file_name.clone())
                    .mime_str("image/png")
                    .expect("image/png is a valid mime type");
                let data = multipart::Part::text(metadata.clone())
                    .mime_str("application/json")
                    .expect("application/json is a valid mime type");
                let form = multipart::Form::new()
                    .part("resource", part)
                    .part("data", data);
                http.post(&url).multipart(form)
            })
            .await?;

        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// Create an invisible square used as a connector endpoint.
    ///
    /// Miro clips a connector at the boundary of the item it attaches to, so an
    /// anchor placed inside a screenshot is pushed out to that screenshot's
    /// border — the arrow ends up under the token instead of on it. Attaching to
    /// a tiny transparent shape sitting on the token sidesteps that: the border
    /// it gets clipped to *is* the token.
    ///
    /// `x`/`y` are the center, relative to the parent frame's top-left corner.
    pub async fn create_anchor_marker(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        size: f64,
    ) -> Result<String, MiroError> {
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": { "fillOpacity": "0.0", "borderOpacity": "0.0" },
            "position": { "x": x, "y": y },
            "geometry": { "width": size, "height": size },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_anchor_marker", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// Draw a hollow rectangle (colored border, transparent fill) framing an item,
    /// used to flag a node that writes contract storage. `x`/`y` are the center and
    /// `width`/`height` the size of the item being framed, relative to the parent
    /// frame's top-left; the border is drawn a touch larger so it reads as an outline
    /// around the screenshot rather than over it.
    pub async fn create_storage_border(
        &self,
        frame_id: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        let pad = 60.0;
        let url = self.endpoint("shapes");
        let body = json!({
            "data": { "shape": "rectangle" },
            "style": {
                "fillOpacity": "0.0",
                "borderColor": "#f24726",
                "borderWidth": "24",
                "borderOpacity": "1.0",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width + pad, "height": height + pad },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_storage_border", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// Whether an item is still on the board.
    ///
    /// The registry records what was deployed, but a board is edited by hand:
    /// a frame deleted in Miro leaves an entry behind that points at nothing.
    /// Trusting the registry alone means refusing to redeploy something that is
    /// no longer there.
    /// The items inside a frame, as `(x, y, width, height)` in FRAME-LOCAL coordinates
    /// (origin at the frame's top-left, x/y the item's centre — what `create_image_in_frame`
    /// expects).
    ///
    /// The registry knows where the deploy PUT each screenshot and how big its PNG was, but
    /// not how big it ended up: a deep node is drawn scaled down, and the auditor moves
    /// things. Asking the board is the only way to know what space is actually taken.
    pub async fn frame_children(
        &self,
        frame_id: &str,
        frame: (f64, f64, f64, f64),
    ) -> Result<Vec<FrameChild>, MiroError> {
        let (frame_x, frame_y, frame_width, frame_height) = frame;
        let mut children = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let cursor_for_request = cursor.clone();
            let url = self.endpoint("items");
            let parent = frame_id.to_string();
            let value = self
                .execute(LEVEL_1_CREDITS, "frame_children", move |http| {
                    let mut request = http
                        .get(&url)
                        .query(&[("parent_item_id", parent.as_str()), ("limit", "50")]);
                    if let Some(ref cursor) = cursor_for_request {
                        request = request.query(&[("cursor", cursor.as_str())]);
                    }
                    request
                })
                .await?;

            if let Some(items) = value["data"].as_array() {
                for item in items {
                    let width = item["geometry"]["width"].as_f64().unwrap_or(0.0);
                    let height = item["geometry"]["height"].as_f64().unwrap_or(0.0);
                    if width <= 0.0 || height <= 0.0 {
                        continue;
                    }
                    let x = item["position"]["x"].as_f64().unwrap_or(0.0);
                    let y = item["position"]["y"].as_f64().unwrap_or(0.0);
                    // A child is normally reported relative to the frame's top-left; when
                    // the board reports canvas coordinates instead, bring them back.
                    let relative_to = item["position"]["relativeTo"].as_str().unwrap_or("");
                    let (x, y) = if relative_to == "parent_top_left" {
                        (x, y)
                    } else {
                        (
                            x - (frame_x - frame_width / 2.0),
                            y - (frame_y - frame_height / 2.0),
                        )
                    };
                    children.push(FrameChild {
                        id: item["id"].as_str().unwrap_or_default().to_string(),
                        title: item["data"]["title"].as_str().unwrap_or_default().to_string(),
                        kind: item["type"].as_str().unwrap_or_default().to_string(),
                        x,
                        y,
                        width,
                        height,
                    });
                }
            }

            match value["cursor"].as_str() {
                Some(next) if !next.is_empty() => cursor = Some(next.to_string()),
                _ => break,
            }
        }
        Ok(children)
    }

    /// How often this client was pushed back, as `(retries, budget waits, seconds waited)`.
    ///
    /// Printed at the end of a long drawing so the next question is about a cause rather than
    /// a feeling, and the three are three different things: a RETRY is a request the board
    /// refused and we sent again; a BUDGET wait is our own bucket saying the minute's credits
    /// are spent, which is arithmetic over the work's size and not a sign of anything wrong;
    /// and the SECONDS are what the refusals cost, which is the number that explains the clock.
    pub fn stats(&self) -> (u32, u32, u32) {
        use std::sync::atomic::Ordering::Relaxed;
        (
            self.retries.load(Relaxed),
            self.budget_waits.load(Relaxed),
            self.retry_seconds.load(Relaxed),
        )
    }

    /// What was really sent: `(requests, credits)`. Includes the reads and every retry.
    pub fn sent(&self) -> (u32, u32) {
        use std::sync::atomic::Ordering::Relaxed;
        (self.sent.load(Relaxed), self.credits_spent.load(Relaxed))
    }

    /// Where an item is RIGHT NOW: `(x, y, width, height)`, with x/y its centre.
    ///
    /// The registry records where a frame was put at deploy time, and the auditor drags
    /// frames around afterwards — arranging the board is half of reading it. Anything that
    /// resizes a frame has to start from the live geometry, or it teleports the frame back
    /// to where it was born.
    pub async fn item_geometry(&self, item_id: &str) -> Option<(f64, f64, f64, f64)> {
        let url = format!("{}/{}", self.endpoint("items"), item_id);
        let value = self
            .execute(LEVEL_1_CREDITS, "item_geometry", move |http| http.get(&url))
            .await
            .ok()?;
        let number = |parent: &str, key: &str| -> Option<f64> { value[parent][key].as_f64() };
        Some((
            number("position", "x")?,
            number("position", "y")?,
            number("geometry", "width")?,
            number("geometry", "height")?,
        ))
    }

    /// Is this item on the board? `None` when the board could not answer.
    ///
    /// The difference matters because a caller acts on the answer by FORGETTING the item:
    /// a record whose frame is really gone is dropped. Collapsing every failure into
    /// "gone" — which `is_ok()` did — meant one rate-limited or 500ing request silently
    /// deleted a deployment's registry entry, and the frames it named became unreachable
    /// although they were still sitting on the board. A 404 is an answer; everything else
    /// is the absence of one.
    pub async fn item_status(&self, item_id: &str) -> Option<bool> {
        let url = format!("{}/{}", self.endpoint("items"), item_id);
        match self
            .execute(LEVEL_1_CREDITS, "item_exists", move |http| http.get(&url))
            .await
        {
            Ok(_) => Some(true),
            Err(report) => {
                let said = format!("{report:?}");
                if said.contains("HTTP 404") {
                    Some(false)
                } else {
                    log::warn!("could not check whether {item_id} is on the board: {said}");
                    None
                }
            }
        }
    }

    /// Convenience for callers that only skip work when an item is missing and never
    /// delete anything on the answer. Treats "could not tell" as still there.
    pub async fn item_exists(&self, item_id: &str) -> bool {
        self.item_status(item_id).await.unwrap_or(true)
    }

    /// Delete an item (frame, image, shape, card) by id. Best-effort: a 404 (already
    /// gone) is treated as success so recycling a partially hand-edited frame works.
    pub async fn delete_item(&self, item_id: &str) -> Result<(), MiroError> {
        let url = format!("{}/{}", self.endpoint("items"), item_id);
        let _ = self
            .execute(LEVEL_1_CREDITS, "delete_item", move |http| http.delete(&url))
            .await;
        Ok(())
    }

    /// Delete a connector by id. Best-effort, like `delete_item`.
    pub async fn delete_connector(&self, connector_id: &str) -> Result<(), MiroError> {
        let url = format!("{}/{}", self.endpoint("connectors"), connector_id);
        let _ = self
            .execute(LEVEL_1_CREDITS, "delete_connector", move |http| {
                http.delete(&url)
            })
            .await;
        Ok(())
    }

    /// Create a card standing in for a function drawn elsewhere on the board.
    ///
    /// The link goes in the shape's `content` as an `<a href>`, because the REST
    /// API rejects Miro's own `linkedTo` field outright — it answers
    /// `Field [linkedTo] is not supported`. An anchor pointing at a
    /// `?moveToWidget=` URL on the same board navigates there instead of opening
    /// a tab, which is what makes this usable at all.
    pub async fn create_link_card(
        &self,
        frame_id: &str,
        title: &str,
        target_url: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        self.create_card(frame_id, title, "see dependencies →", target_url, x, y, width, height,
                         "#fff9b1", "#f24726").await
    }

    /// The way back: a card in the destination frame pointing at a frame that links TO it.
    ///
    /// A card takes the reader deeper and leaves no trail, and a frame can be reached from
    /// several — `FLAMMGateLib.priced` is carded from three frames of one deployment — so
    /// the destination carries one of these per origin. Blue, because yellow already means
    /// "a call goes out here" and purple "a type lives there"; this one is the only arrow
    /// that points back.
    pub async fn create_back_card(
        &self,
        frame_id: &str,
        title: &str,
        target_url: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        self.create_card(frame_id, title, "↑ back to", target_url, x, y, width, height,
                         "#e6f2ff", "#2d9bf0").await
    }

    /// The same card in the colours a struct gets: a type is not a call, and the two
    /// should not read as the same thing on a board where colour already means something.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_struct_card(
        &self,
        frame_id: &str,
        title: &str,
        target_url: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<String, MiroError> {
        self.create_card(frame_id, title, "see its fields →", target_url, x, y, width, height,
                         "#f0e6ff", "#a259ff").await
    }

    #[allow(clippy::too_many_arguments)]
    async fn create_card(
        &self,
        frame_id: &str,
        title: &str,
        action: &str,
        target_url: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        fill: &str,
        border: &str,
    ) -> Result<String, MiroError> {
        let url = self.endpoint("shapes");
        let body = json!({
            "data": {
                "content": format!(
                    "<p><a href=\"{target_url}\">{title}</a></p><p>{action}</p>"
                ),
                "shape": "round_rectangle",
            },
            "style": {
                "fillColor": fill,
                "borderColor": border,
                "borderWidth": "2",
                "fontSize": "36",
                "textAlign": "center",
                "textAlignVertical": "middle",
            },
            "position": { "x": x, "y": y },
            "geometry": { "width": width, "height": height },
            "parent": { "id": frame_id },
        })
        .to_string();

        let value = self
            .execute(LEVEL_2_CREDITS, "create_link_card", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;
        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }

    /// Connect two items, anchoring each end at an exact point of the item.
    ///
    /// Note that frames cannot be connector endpoints — the API only accepts
    /// regular items — which is why we always connect image to image.
    pub async fn create_connector(
        &self,
        start_item_id: &str,
        start_anchor: RelativeAnchor,
        end_item_id: &str,
        end_anchor: RelativeAnchor,
        style: ConnectorStyle,
    ) -> Result<String, MiroError> {
        self.create_connector_shaped(
            start_item_id,
            start_anchor,
            end_item_id,
            end_anchor,
            style,
            "elbowed",
        )
        .await
    }

    /// The same connector, drawn with a shape of your choosing.
    ///
    /// `elbowed` is right for a call graph, where arrows run between columns and orthogonal
    /// segments are what keeps them legible. It is wrong wherever two points simply have to
    /// be joined — a row of a table and the line it describes — because an elbow between two
    /// far-apart points is a bracket around everything in between, and four of those nest
    /// into a shape that hides what it is pointing at. There `straight` is one diagonal.
    pub async fn create_connector_shaped(
        &self,
        start_item_id: &str,
        start_anchor: RelativeAnchor,
        end_item_id: &str,
        end_anchor: RelativeAnchor,
        style: ConnectorStyle,
        shape: &str,
    ) -> Result<String, MiroError> {
        let mut body = json!({
            "startItem": { "id": start_item_id, "position": start_anchor.to_json() },
            "endItem": { "id": end_item_id, "position": end_anchor.to_json() },
            // Whatever the shape, Miro clips a connector at the item's boundary — that was
            // tried when the anchors were first pushed out to the border, and the shape is
            // not what causes it. The marker shapes are.
            "shape": shape,
            "style": {
                "strokeColor": style.stroke_color,
                "strokeWidth": style.stroke_width,
                "strokeStyle": style.stroke.as_miro(),
                "startStrokeCap": if style.arrow == ArrowEnd::Start { "stealth" } else { "none" },
                "endStrokeCap": if style.arrow == ArrowEnd::End { "stealth" } else { "none" },
            },
        });
        if let Some(caption) = style.caption {
            body["captions"] = json!([{ "content": caption, "position": "15%" }]);
        }
        let body = body.to_string();

        let url = self.endpoint("connectors");
        let value = self
            .execute(LEVEL_2_CREDITS, "create_connector", move |http| {
                http.post(&url)
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone())
            })
            .await?;

        Ok(value["id"].as_str().unwrap_or_default().to_string())
    }
}

/// Prefer `Retry-After`, fall back to `X-RateLimit-Reset` (a UNIX timestamp).
fn retry_after(response: &reqwest::Response) -> Option<Duration> {
    let headers = response.headers();
    if let Some(value) = headers.get("retry-after").and_then(|v| v.to_str().ok()) {
        if let Ok(seconds) = value.parse::<u64>() {
            return Some(Duration::from_secs(seconds));
        }
    }
    let reset = headers
        .get("x-ratelimit-reset")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<u64>().ok())?;
    let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
    Some(Duration::from_secs(reset.saturating_sub(now).min(120)))
}

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

    #[test]
    fn test_relative_anchor_is_clamped_and_formatted() {
        let anchor = RelativeAnchor::new(0.6823, 0.374);
        assert_eq!(anchor.to_json()["x"], "68.23%");
        assert_eq!(anchor.to_json()["y"], "37.40%");

        let out_of_range = RelativeAnchor::new(-0.5, 1.9);
        assert_eq!(out_of_range.to_json()["x"], "0.00%");
        assert_eq!(out_of_range.to_json()["y"], "100.00%");
    }
}

/// The three characters that would otherwise close Miro's own markup. A contract name has no
/// business containing them, and a label that silently swallowed one would be worse than an
/// escaped one.
fn html_escape(text: &str) -> String {
    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}

#[cfg(test)]
mod bulk_test {
    use super::MiroClient;

    /// Every item of a bulk call carries its `type` and its parent frame: the bulk endpoint
    /// takes one list of mixed items, so an item that does not say what it is is rejected and
    /// one that does not say whose it is lands loose on the board.
    #[test]
    fn a_bulk_item_names_its_kind_and_its_frame() {
        let items = [
            MiroClient::label_item("Treasury", 100.0, 200.0, 900.0, 320.0, 120, "#ffffff", "#1a1a1a", 4, "#1a1a1a", "normal", "frame-1"),
            MiroClient::marker_item(100.0, 500.0, 8.0, "frame-1"),
        ];
        for item in &items {
            assert_eq!(item["type"], "shape");
            assert_eq!(item["parent"]["id"], "frame-1");
            assert!(item["position"]["x"].is_number());
        }
        assert!(items[0]["data"]["content"].as_str().expect("text").contains("Treasury"));
        // The marker is the one that must not be seen: it exists to give a connector an exact
        // point to land on.
        // The ceiling is Miro's: a border thicker than 23 is refused outright.
        assert_eq!(
            MiroClient::label_item("x", 0.0, 0.0, 1.0, 1.0, 1, "#fff", "#000", 99, "#000", "normal", "f")["style"]["borderWidth"],
            "23"
        );
        assert_eq!(items[1]["style"]["fillOpacity"], "0.0");
        assert_eq!(items[1]["style"]["borderOpacity"], "0.0");
    }

    /// A bulk item's text is escaped exactly as the single-item call escapes it — the two write
    /// the same shape, and a name with an angle bracket must not become markup in one of them.
    #[test]
    fn a_bulk_item_escapes_its_text() {
        let item = MiroClient::label_item("A<B>", 0.0, 0.0, 10.0, 10.0, 12, "#fff", "#000", 4, "#000", "normal", "f");
        let content = item["data"]["content"].as_str().expect("text");
        assert!(!content.contains("<B>"), "unescaped: {content}");
        assert!(content.contains("&lt;B&gt;"), "{content}");
    }
}

#[cfg(test)]
mod permit_test {
    use super::{permits_for, LEVEL_1_CREDITS, LEVEL_2_CREDITS, MAX_CONCURRENT_REQUESTS};

    /// A permit is a write in flight, not a request in flight.
    ///
    /// The board defends itself against items created, and a bulk call creates twenty of them
    /// through one socket. Counting sockets let 48 of those run at once — 960 items — and the
    /// wave that sent 74 bulk requests took 120 seconds where 760 connectors took 40.
    #[test]
    fn a_bulk_costs_what_it_creates() {
        assert_eq!(permits_for(LEVEL_2_CREDITS), 1, "one item, one permit");
        assert_eq!(permits_for(LEVEL_2_CREDITS * 20), 20, "twenty items, twenty");
        // A read is cheaper than a write and still a round trip.
        assert_eq!(permits_for(LEVEL_1_CREDITS), 1);
        // And nothing may ask for more than exists, or it would wait for ever.
        assert_eq!(
            permits_for(LEVEL_2_CREDITS * 1_000),
            MAX_CONCURRENT_REQUESTS as u32
        );
    }
}

#[cfg(test)]
mod budget_test {
    use super::{CreditBudget, BURST_CREDITS, CREDITS_PER_SECOND, LEVEL_2_CREDITS};
    use std::time::{Duration, Instant};

    /// The bucket's arithmetic, without a clock to wait on: refill, take, and what is left to
    /// wait for when there is not enough.
    ///
    /// `reserve` itself is `async` and sleeps, so what is checked here is the sum it sleeps on.
    /// The thing that matters is the SHAPE of that number: a write short of credit waits for
    /// that write's worth of refill — tens of milliseconds — where the window version this
    /// replaced slept until the minute was over, which is why one map spent 185 of its 223
    /// seconds waiting.
    fn take(budget: &mut CreditBudget, credits: f64, at: Instant) -> Option<Duration> {
        let refilled = at.duration_since(budget.last).as_secs_f64() * CREDITS_PER_SECOND;
        budget.available = (budget.available + refilled).min(BURST_CREDITS);
        budget.last = at;
        if budget.available >= credits {
            budget.available -= credits;
            return None;
        }
        Some(Duration::from_secs_f64(
            (credits - budget.available) / CREDITS_PER_SECOND,
        ))
    }

    #[test]
    fn a_burst_leaves_at_once_and_the_rest_is_paced() {
        let start = Instant::now();
        let mut budget = CreditBudget { last: start, available: BURST_CREDITS };
        let write = LEVEL_2_CREDITS as f64;

        // Fifty writes — one round of the permits — go out with no wait at all.
        for at in 0..50 {
            assert_eq!(take(&mut budget, write, start), None, "write {at} waited");
        }
        // The fifty-first does not, and waits one write's worth of refill — tens of
        // milliseconds. Not a minute, which is what the window version slept.
        let waited = take(&mut budget, write, start).expect("the bucket is empty");
        assert!(
            waited < Duration::from_millis(100),
            "paced, not stalled: {waited:?}"
        );

        // And the rate holds: a second of refill is exactly `WRITES_PER_SECOND` more writes.
        // Read off the constant rather than written out here, so tuning the rate does not need
        // the test edited to agree with it — which is how a test stops checking anything.
        let mut budget = CreditBudget { last: start, available: 0.0 };
        let later = start + Duration::from_secs(1);
        for at in 0..super::WRITES_PER_SECOND as usize {
            assert_eq!(take(&mut budget, write, later), None, "write {at} of the second");
        }
        assert!(
            take(&mut budget, write, later).is_some(),
            "one more than a second's worth waits"
        );
    }

    /// Idle time does not bank a minute's credit: the bucket stops at its burst, so coming back
    /// after a pause cannot replay the burst that gets a run refused.
    #[test]
    fn the_bucket_does_not_bank_a_minute() {
        let start = Instant::now();
        let mut budget = CreditBudget { last: start, available: 0.0 };
        let write = LEVEL_2_CREDITS as f64;
        let much_later = start + Duration::from_secs(600);
        for at in 0..(BURST_CREDITS / write) as usize {
            assert_eq!(take(&mut budget, write, much_later), None, "write {at}");
        }
        assert!(
            take(&mut budget, write, much_later).is_some(),
            "ten idle minutes are still only one burst"
        );
    }
}