zc2 0.0.42

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

use std::cell::RefCell;
use std::collections::HashSet;
use std::time::{Duration, Instant};

use super::expose::{self, MeshExposer};
use super::runtime::{container_name, deployment_labels, ContainerRuntime, RunSpec};
use super::state::{DeploymentRecord, LocalState};
use super::{Desired, Healthcheck};

/// One step of a reconcile plan. `plan()`/`plan_failure()` emit these; only
/// `drive()` interprets them against a real (or fake) `ContainerRuntime`.
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
    Pull {
        id: String,
    },
    Start {
        id: String,
    },
    Health {
        id: String,
    },
    /// Stop+remove THIS deployment's own superseded container (a version
    /// bump's old version) — the driver reads it from
    /// `LocalState::previous_container_id`, not from the action itself.
    StopOld {
        id: String,
    },
    /// Stop+remove `id`'s current container and report it `stopped`. Used
    /// both for an explicit `desired_state: "stopped"` and, via a handoff, to
    /// retire a DIFFERENT deployment that `previous` named (see `plan`).
    Stop {
        id: String,
    },
    Remove {
        id: String,
        container_id: String,
    },
    /// Tear down a deployment the hub no longer lists at all: stop+remove its
    /// container (if any) and DROP its local record. No status report — the
    /// hub already forgot the deployment, so there is no row to update.
    Forget {
        id: String,
    },
    Report {
        id: String,
        phase: String,
        message: Option<String>,
    },
}

impl Action {
    fn deployment_id(&self) -> &str {
        match self {
            Action::Pull { id }
            | Action::Start { id }
            | Action::Health { id }
            | Action::StopOld { id }
            | Action::Stop { id }
            | Action::Remove { id, .. }
            | Action::Forget { id }
            | Action::Report { id, .. } => id,
        }
    }
}

/// Decide what should happen for every entry in `desired`, given what
/// `local` currently believes is running. Pure: no I/O, so this is exercised
/// directly by unit tests without docker or a network.
///
/// - A deployment absent from `local` (new) → `[Pull, Start, Health]`.
/// - A known deployment whose `version` differs (rolling replace) →
///   `[Pull, Start, Health, StopOld]` — `StopOld` only runs once `Health`
///   reports success, because `drive()` aborts a deployment's remaining
///   actions the moment one fails.
/// - `desired_state: "stopped"` with a container on record → `[Stop]`.
/// - Already at the desired version and healthy → `[]` (nothing to do).
/// - A known deployment stuck mid-flight (record exists, not yet healthy,
///   same version — e.g. the broker restarted between `Start` and `Health`)
///   → `[Start, Health]`, resuming rather than re-pulling.
/// - A version whose rollout already FAILED here (`failed`/`rolled_back` at
///   the same version, or `failed_version` naming it) → `[]`. It is not
///   retried: it stays failed until the hub bumps the version (owner Retry /
///   Move / Edit health check). Retrying every tick re-pulled, re-ran and
///   re-reported forever, so the hub showed "failed" and "starting" at once.
/// - `previous` naming a DIFFERENT deployment id (slot handoff) appends a
///   `Stop` for THAT id to the deploying branch, so once this deployment is
///   healthy the one it replaced is retired locally too, ahead of the hub
///   sending an explicit `desired_state: "stopped"` for it.
/// - A record the hub no longer lists → `[Forget]`: stopped, removed and
///   forgotten. The hub serves `stopped` for only a grace period after a
///   stop/delete and then drops the deployment, so a broker that was down
///   for that window never sees the `stopped` and would otherwise run the
///   container forever. A record a listed deployment's `previous` names is
///   left to that handoff `Stop` (it must outlive the new version's
///   health check); it is swept once nothing names it any more. Callers must
///   only plan from a SUCCESSFUL fetch: `desired` empty means "the hub
///   lists nothing for this node", never "the fetch failed".
pub fn plan(desired: &[Desired], local: &LocalState) -> Vec<Action> {
    let mut actions = Vec::new();

    for d in desired {
        let record = local.deployments.get(&d.id);

        if d.desired_state == "stopped" {
            if let Some(rec) = record {
                if rec.container_id.is_some() {
                    actions.push(Action::Stop { id: d.id.clone() });
                }
            }
            continue;
        }

        // desired_state == "running"
        let deploying = match record {
            None => {
                actions.push(Action::Pull { id: d.id.clone() });
                actions.push(Action::Start { id: d.id.clone() });
                actions.push(Action::Health { id: d.id.clone() });
                true
            }
            Some(rec) if failed_at(rec, d.version) => false,
            Some(rec) if rec.version != d.version => {
                actions.push(Action::Pull { id: d.id.clone() });
                actions.push(Action::Start { id: d.id.clone() });
                actions.push(Action::Health { id: d.id.clone() });
                actions.push(Action::StopOld { id: d.id.clone() });
                true
            }
            Some(rec) if rec.phase != "healthy" || rec.container_id.is_none() => {
                actions.push(Action::Start { id: d.id.clone() });
                actions.push(Action::Health { id: d.id.clone() });
                true
            }
            Some(_) => false, // unchanged and healthy — nothing to do
        };

        if deploying {
            if let Some(prev) = &d.previous {
                if prev.id != d.id {
                    actions.push(Action::Stop {
                        id: prev.id.clone(),
                    });
                }
            }
        }
    }

    // Sweep records the hub no longer lists (sorted: a stable plan).
    let handed_off: HashSet<&str> = desired
        .iter()
        .filter_map(|d| d.previous.as_ref().map(|p| p.id.as_str()))
        .collect();
    let mut unlisted: Vec<&String> = local
        .deployments
        .keys()
        .filter(|id| !desired.iter().any(|d| &d.id == *id) && !handed_off.contains(id.as_str()))
        .collect();
    unlisted.sort();
    for id in unlisted {
        actions.push(Action::Forget { id: id.clone() });
    }

    actions
}

/// Whether `rec` already holds a failed rollout of exactly `version`. Old
/// state files have no `failed_version`, so `failed`/`rolled_back` at the same
/// version counts too.
fn failed_at(rec: &DeploymentRecord, version: u64) -> bool {
    rec.failed_version == Some(version)
        || (rec.version == version && matches!(rec.phase.as_str(), "failed" | "rolled_back"))
}

/// What to do when `Start` or `Health` fails partway through deploying `id`.
/// Pure and unit-testable on its own (no docker): `drive()` supplies
/// `failed_container_id` only when a container was actually created (a
/// `Start` failure never creates one), and `had_previous` says whether a
/// pre-existing container survives to fall back to.
pub fn plan_failure(
    id: &str,
    failed_container_id: Option<&str>,
    had_previous: bool,
) -> Vec<Action> {
    let mut actions = Vec::new();
    if let Some(cid) = failed_container_id {
        actions.push(Action::Remove {
            id: id.to_string(),
            container_id: cid.to_string(),
        });
    }
    actions.push(Action::Report {
        id: id.to_string(),
        phase: "failed".to_string(),
        message: None,
    });
    if had_previous {
        actions.push(Action::Report {
            id: id.to_string(),
            phase: "rolled_back".to_string(),
            message: None,
        });
    }
    actions
}

/// Why a rollout failed, sent with the `failed` report so the hub can show it.
/// `code` is `pull_failed`, `start_failed`, `health_failed` or `no_runtime`;
/// `message` is one human line; `logs` (the container's log tail) and
/// `probes_failed` only exist for a failure after a container was started.
/// (A `healthy` report carries the startup log tail too, via `report_healthy`.)
#[derive(Debug, Clone, PartialEq)]
pub struct FailureDetail {
    pub code: &'static str,
    pub message: String,
    pub logs: Option<String>,
    pub probes_failed: Option<u32>,
}

impl FailureDetail {
    pub fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            logs: None,
            probes_failed: None,
        }
    }
}

/// The last non-empty line of a docker error (its stderr): the line that says
/// what went wrong, after any progress output above it.
fn last_line(text: &str) -> String {
    text.lines()
        .map(str::trim)
        .rfind(|l| !l.is_empty())
        .unwrap_or("")
        .to_string()
}

/// Where `drive()` sends phase transitions. Split out as a trait so tests
/// exercise `drive()` against a fake that just records calls, the same way
/// `runtime::ContainerRuntime` is faked — no real HTTP in the unit suite.
///
/// `endpoint` is the container's own `ip:port`; `mesh_endpoint` is where the
/// rest of the mesh reaches it (see `expose`). `drive()` always passes `None`
/// for the latter, since only `expose::sync` knows it.
pub trait StatusReporter {
    #[allow(clippy::too_many_arguments)]
    fn report(
        &self,
        id: &str,
        version: u64,
        phase: &str,
        message: &str,
        attempt: u32,
        container_id: Option<&str>,
        endpoint: Option<&str>,
        mesh_endpoint: Option<&str>,
    );

    /// A `healthy` report with the container's startup log tail (`None` when
    /// it printed nothing), sent once when the deployment turns healthy: the
    /// hub otherwise only has tails from failed attempts, which show stale
    /// output such as a dead container's access token. The default drops the
    /// logs and sends a plain `healthy` through `report`.
    fn report_healthy(
        &self,
        id: &str,
        version: u64,
        attempt: u32,
        container_id: Option<&str>,
        endpoint: Option<&str>,
        _logs: Option<&str>,
    ) {
        self.report(
            id,
            version,
            "healthy",
            "",
            attempt,
            container_id,
            endpoint,
            None,
        );
    }

    /// A `failed` report with its reason. The default drops the detail and
    /// sends a plain `failed` + message through `report`, so reporters that
    /// only record phases need not care.
    fn report_failure(
        &self,
        id: &str,
        version: u64,
        attempt: u32,
        container_id: Option<&str>,
        failure: &FailureDetail,
    ) {
        self.report(
            id,
            version,
            "failed",
            &failure.message,
            attempt,
            container_id,
            None,
            None,
        );
    }
}

/// The last probe's error and how many probes failed, once `wait_healthy`
/// gave up.
struct HealthFailure {
    last_error: String,
    probes_failed: u32,
}

/// Poll a deployment's healthcheck every 2s until it passes or `timeout_s`
/// elapses. No healthcheck configured at all → a running container is
/// considered healthy immediately (the hub asked for nothing more specific).
/// The actual probe is `rt.health_probe` — delegated to the runtime (rather
/// than done here against a real socket) specifically so this loop, and the
/// deploy flow around it, are testable with a fake runtime and no network.
/// On timeout the error carries the LAST probe's reason and the failed count.
fn wait_healthy(
    rt: &dyn ContainerRuntime,
    hc: &Option<Healthcheck>,
    container_id: &str,
) -> Result<(), HealthFailure> {
    let Some(hc) = hc else { return Ok(()) };
    let deadline = Instant::now() + Duration::from_secs(hc.timeout_s.max(1));
    let mut probes_failed = 0u32;
    loop {
        let last_error = match rt.health_probe(container_id, hc) {
            Ok(()) => return Ok(()),
            Err(e) => e,
        };
        probes_failed += 1;
        if Instant::now() >= deadline {
            return Err(HealthFailure {
                last_error,
                probes_failed,
            });
        }
        std::thread::sleep(Duration::from_secs(2));
    }
}

/// How many log lines a health failure, or a deployment turning healthy,
/// sends to the hub.
const LOG_TAIL_LINES: u32 = 50;

/// Execute one reconcile pass: plan, then walk the plan against `rt`,
/// updating `local` and calling `reporter` on every phase transition. A
/// deployment whose `Pull`/`Start`/`Health` step fails has its remaining
/// actions skipped (no `StopOld`/handoff `Stop` for a deployment that never
/// went healthy) and is rolled back in place.
pub fn drive(
    rt: &dyn ContainerRuntime,
    reporter: &dyn StatusReporter,
    desired: &[Desired],
    local: &mut LocalState,
) {
    let actions = plan(desired, local);
    let mut failed: std::collections::HashSet<String> = Default::default();
    // Every phase reported within one `drive()` pass belongs to the same
    // deploy attempt (a retry only happens on the NEXT tick's `drive()`
    // call, driven by `plan()` resuming a non-healthy record) — so attempt
    // number is constant here, not incremented per action.
    let attempt: u32 = 1;

    for action in actions {
        let id = action.deployment_id().to_string();
        if failed.contains(&id) {
            continue;
        }
        let Some(d) = desired.iter().find(|d| d.id == id) else {
            // Referenced by a Stop{other_id} handoff for a deployment the
            // hub no longer even lists — still valid, just has no `Desired`,
            // so the local record's version is the only one there is.
            match &action {
                Action::Stop { id } => {
                    let version = local.deployments.get(id).map(|r| r.version).unwrap_or(0);
                    do_stop(rt, reporter, local, id, version);
                }
                Action::Forget { id } => do_forget(rt, local, id),
                _ => {}
            }
            continue;
        };

        match action {
            Action::Pull { id } => {
                reporter.report(&id, d.version, "pulling", "", attempt, None, None, None);
                if let Err(e) = rt.pull(&d.image) {
                    // Nothing was ever touched: whatever this deployment was
                    // running before (if anything) is still exactly as it
                    // was, so this is a plain failure report, not a rollback
                    // (see `run_failure`'s doc comment).
                    let failure = FailureDetail::new("pull_failed", last_line(&e));
                    run_failure(reporter, local, &id, d.version, attempt, None, &failure);
                    failed.insert(id);
                }
            }
            Action::Start { id } => {
                reporter.report(&id, d.version, "starting", "", attempt, None, None, None);
                if !d.warm {
                    // Cold-start-on-demand isn't built yet — see
                    // `Desired::warm`'s doc comment. Logged once per Start
                    // (not every tick: a healthy, unchanged deployment never
                    // re-enters this branch) so it doesn't drown other
                    // `[DEPLOY]` lines.
                    println!("  [DEPLOY] warm=false not implemented, keeping warm ({id})");
                }
                let name = container_name(&id, d.version);
                let labels = deployment_labels(&id, d.version);
                // The grants are handed to the environment's own process;
                // the policy's network statements are enforced here by
                // choosing the container's docker network (see `policy`).
                let mut env = d.env.clone();
                if let Some(sa) = &d.service_account {
                    env.insert("ZAKURO_SERVICE_ACCOUNT".to_string(), sa.name.clone());
                    env.insert("ZAKURO_GRANTS".to_string(), sa.grants.join(","));
                }
                let net = super::policy::network_access(d.service_account.as_ref());
                let network = if net.isolated() {
                    println!(
                        "  [DEPLOY] service-account policy denies network (mesh={}, internet={}): \
                         isolating {id}",
                        net.mesh, net.internet
                    );
                    Some(super::runtime::isolated_network())
                } else {
                    None
                };
                // The healthcheck port joins `ports` so a runtime that
                // publishes ports (Docker Desktop) maps it too.
                let mut ports = d.ports.clone();
                if let Some(hc) = &d.healthcheck {
                    if !ports.iter().any(|p| p.container == hc.port) {
                        ports.push(super::Port {
                            container: hc.port,
                            protocol: hc.kind.clone(),
                        });
                    }
                }
                let spec = RunSpec {
                    name,
                    image: &d.image,
                    cmd: d.cmd.as_deref(),
                    ports: &ports,
                    env: &env,
                    labels,
                    mounts: Vec::new(),
                    cpus: None,
                    memory_gb: None,
                    gpus: None,
                    network,
                    hardened: false,
                };
                match rt.run(&spec) {
                    Ok(container_id) => {
                        let rec = local.deployments.entry(id.clone()).or_default();
                        rec.previous_container_id = rec.container_id.take();
                        rec.container_id = Some(container_id);
                        rec.image = d.image.clone();
                        rec.version = d.version;
                        rec.price_per_second = d.price_per_second;
                        rec.service_account = d.service_account.clone();
                        rec.warm = d.warm;
                        rec.phase = "starting".to_string();
                        let _ = local.save();
                    }
                    Err(e) => {
                        // `rt.run` failed before creating anything: same as
                        // the `Pull` case above, whatever was running before
                        // is untouched — a plain failure, not a rollback.
                        let failure = FailureDetail::new("start_failed", last_line(&e));
                        run_failure(reporter, local, &id, d.version, attempt, None, &failure);
                        failed.insert(id);
                    }
                }
            }
            Action::Health { id } => {
                let container_id = local
                    .deployments
                    .get(&id)
                    .and_then(|r| r.container_id.clone());
                let Some(container_id) = container_id else {
                    failed.insert(id);
                    continue;
                };
                // Before the first probe, so the hub can tell "started, now
                // probing" from "still starting".
                reporter.report(
                    &id,
                    d.version,
                    "health_check",
                    "",
                    attempt,
                    Some(&container_id),
                    None,
                    None,
                );
                let health = wait_healthy(rt, &d.healthcheck, &container_id);
                if health.is_ok() {
                    // The container's own port (not a host-published one —
                    // see `runtime`'s module doc comment for why `run` no
                    // longer publishes anything) paired with its network
                    // address, resolved fresh here rather than reused from
                    // whatever `wait_healthy` last saw internally.
                    let container_port = d
                        .healthcheck
                        .as_ref()
                        .map(|hc| hc.port)
                        .or_else(|| d.ports.first().map(|p| p.container));
                    // Where to dial it: the container IP and port, or a
                    // published loopback port on Docker Desktop.
                    let addr = match container_port {
                        Some(port) => rt.container_addr(&container_id, port).ok(),
                        None => None,
                    };
                    let endpoint = addr.as_ref().map(|(ip, port)| format!("{ip}:{port}"));
                    let (ip, port) = match addr {
                        Some((ip, port)) => (Some(ip), Some(port)),
                        None => (rt.container_ip(&container_id).ok(), container_port),
                    };
                    if let Some(rec) = local.deployments.get_mut(&id) {
                        rec.phase = "healthy".to_string();
                        rec.failed_version = None;
                        rec.ip = ip;
                        rec.port = port;
                        rec.endpoint = endpoint.clone();
                    }
                    let _ = local.save();
                    // The startup output (e.g. Jupyter's access token) of the
                    // container that is actually serving, not a failed one.
                    let logs = rt.logs_tail(&container_id, LOG_TAIL_LINES);
                    reporter.report_healthy(
                        &id,
                        d.version,
                        attempt,
                        Some(&container_id),
                        endpoint.as_deref(),
                        Some(logs.as_str()).filter(|l| !l.is_empty()),
                    );
                } else if let Err(h) = health {
                    // Read the logs before the container is removed.
                    let mut failure = FailureDetail::new("health_failed", h.last_error);
                    failure.logs = Some(rt.logs_tail(&container_id, LOG_TAIL_LINES));
                    failure.probes_failed = Some(h.probes_failed);
                    // Unlike the Pull/Start failure branches: a container WAS
                    // created and needs cleaning up, and if a previous
                    // version's container is still on record, this is a real
                    // rollback — restore it and say so.
                    let _ = rt.stop(&container_id);
                    let _ = rt.rm(&container_id);
                    let previous = local
                        .deployments
                        .get_mut(&id)
                        .and_then(|rec| rec.previous_container_id.take());
                    run_failure(
                        reporter,
                        local,
                        &id,
                        d.version,
                        attempt,
                        Some(&container_id),
                        &failure,
                    );
                    if let Some(prev) = previous {
                        let _ = rt.restart(&prev);
                        restore_previous_container(reporter, local, &id, d.version, attempt, prev);
                    }
                    failed.insert(id);
                }
            }
            Action::StopOld { id } => {
                if let Some(rec) = local.deployments.get_mut(&id) {
                    if let Some(old) = rec.previous_container_id.take() {
                        let _ = rt.stop(&old);
                        let _ = rt.rm(&old);
                    }
                }
                let _ = local.save();
            }
            Action::Stop { id } => do_stop(rt, reporter, local, &id, d.version),
            // Only planned for ids absent from `desired`, handled above.
            Action::Forget { .. } => {}
            Action::Remove { container_id, .. } => {
                let _ = rt.stop(&container_id);
                let _ = rt.rm(&container_id);
            }
            Action::Report { id, phase, message } => {
                reporter.report(
                    &id,
                    d.version,
                    &phase,
                    message.as_deref().unwrap_or(""),
                    attempt,
                    None,
                    None,
                    None,
                );
            }
        }
    }
}

/// One reconcile pass followed by `expose::sync`, which is what
/// `deploy::tick` runs. Every report `drive()` sends replaces the hub's row
/// with one that carries no mesh endpoint (`drive()` knows nothing about
/// exposure), so each record it reported on has its `mesh_endpoint` cleared
/// before `sync` compares. Otherwise a version bump that re-exposes on the
/// same port would look unchanged, and the hub would keep showing no address.
pub fn drive_and_expose(
    rt: &dyn ContainerRuntime,
    reporter: &dyn StatusReporter,
    exposer: &dyn MeshExposer,
    mesh_ip: Option<&str>,
    desired: &[Desired],
    local: &mut LocalState,
) {
    let tracked = ReportedIds {
        inner: reporter,
        ids: RefCell::default(),
    };
    drive(rt, &tracked, desired, local);
    let mut changed = false;
    for id in tracked.ids.into_inner() {
        if let Some(rec) = local.deployments.get_mut(&id) {
            changed |= rec.mesh_endpoint.take().is_some();
        }
    }
    let synced = expose::sync(local, exposer, mesh_ip, reporter);
    if synced || changed {
        let _ = local.save();
    }
}

/// A `StatusReporter` that notes which deployments were reported on, for
/// `drive_and_expose`.
struct ReportedIds<'a> {
    inner: &'a dyn StatusReporter,
    ids: RefCell<HashSet<String>>,
}

impl StatusReporter for ReportedIds<'_> {
    fn report(
        &self,
        id: &str,
        version: u64,
        phase: &str,
        message: &str,
        attempt: u32,
        container_id: Option<&str>,
        endpoint: Option<&str>,
        mesh_endpoint: Option<&str>,
    ) {
        self.ids.borrow_mut().insert(id.to_string());
        self.inner.report(
            id,
            version,
            phase,
            message,
            attempt,
            container_id,
            endpoint,
            mesh_endpoint,
        );
    }

    fn report_healthy(
        &self,
        id: &str,
        version: u64,
        attempt: u32,
        container_id: Option<&str>,
        endpoint: Option<&str>,
        logs: Option<&str>,
    ) {
        self.ids.borrow_mut().insert(id.to_string());
        self.inner
            .report_healthy(id, version, attempt, container_id, endpoint, logs);
    }

    fn report_failure(
        &self,
        id: &str,
        version: u64,
        attempt: u32,
        container_id: Option<&str>,
        failure: &FailureDetail,
    ) {
        self.ids.borrow_mut().insert(id.to_string());
        self.inner
            .report_failure(id, version, attempt, container_id, failure);
    }
}

/// Stop+remove `id`'s current container (if any), clear it from local state,
/// and report it `stopped`. Shared by the explicit `desired_state: "stopped"`
/// path and the cross-deployment handoff path — both mean the same thing to
/// the hub: this node no longer runs anything for `id`.
///
/// `version` is the one the `stopped` report carries: the desired entry's
/// when the hub lists `id`, else the local record's. It must not be the local
/// one when the hub has a newer version: the hub's stop route bumps the version
/// and ignores older reports, so a stale one would never be recorded (zc#213).
fn do_stop(
    rt: &dyn ContainerRuntime,
    reporter: &dyn StatusReporter,
    local: &mut LocalState,
    id: &str,
    version: u64,
) {
    if let Some(rec) = local.deployments.get_mut(id) {
        if let Some(cid) = rec.container_id.take() {
            let _ = rt.stop(&cid);
            let _ = rt.rm(&cid);
        }
        rec.phase = "stopped".to_string();
        rec.endpoint = None;
        rec.port = None;
    }
    let _ = local.save();
    reporter.report(id, version, "stopped", "", 1, None, None, None);
}

/// Stop+remove `id`'s container (if any) and drop its record, for a
/// deployment the hub no longer lists. Unlike `do_stop` it sends no report:
/// the hub has no row left to update, and a `stopped` for a deleted
/// deployment would only 404 every tick until the record is gone.
fn do_forget(rt: &dyn ContainerRuntime, local: &mut LocalState, id: &str) {
    if let Some(rec) = local.deployments.remove(id) {
        for cid in rec
            .container_id
            .iter()
            .chain(rec.previous_container_id.iter())
        {
            let _ = rt.stop(cid);
            let _ = rt.rm(cid);
        }
    }
    let _ = local.save();
}

/// Report `id` `failed`. Two shapes share this, distinguished by
/// `failed_container_id`:
///
/// - `None` (a `Pull` or `docker run` failure): nothing was ever touched —
///   an existing, still-running container from a previous version (if any)
///   is untouched and left exactly as it was, so local state/phase is only
///   overwritten to `failed` when there was NOTHING running to begin with.
/// - `Some(cid)` (a `Health` failure): the caller has already stopped+
///   removed `cid` before calling here, so the record's stale `container_id`
///   is always cleared. The caller separately restores a previous version's
///   container, if one was saved, via `restore_previous_container` — this
///   function only ever reports/records `failed`, never `rolled_back`.
fn run_failure(
    reporter: &dyn StatusReporter,
    local: &mut LocalState,
    id: &str,
    version: u64,
    attempt: u32,
    failed_container_id: Option<&str>,
    failure: &FailureDetail,
) {
    reporter.report_failure(id, version, attempt, failed_container_id, failure);
    // `.entry().or_default()`, not `get_mut`: a brand-new deployment whose
    // very first `Pull`/`Start` fails has no record yet, and the hub's
    // `failed` report above should be reflected locally too (`zc
    // deployments` and the next `plan()` both read this).
    let rec = local.deployments.entry(id.to_string()).or_default();
    // Whatever else is on record, `plan()` must not retry this version.
    rec.failed_version = Some(version);
    if failed_container_id.is_some() || rec.container_id.is_none() {
        rec.container_id = None;
        rec.phase = "failed".to_string();
        rec.version = version;
    }
    let _ = local.save();
}

/// Bring a deployment's previous-version container back to being THE
/// container on record after a failed rollout, and tell the hub. Always
/// follows a `run_failure(..., Some(cid), ...)` call for the same
/// deployment (see its doc comment) — together they produce the `failed`
/// then `rolled_back` pair the hub contract expects.
fn restore_previous_container(
    reporter: &dyn StatusReporter,
    local: &mut LocalState,
    id: &str,
    version: u64,
    attempt: u32,
    previous_container_id: String,
) {
    let endpoint = local.deployments.get(id).and_then(|r| r.endpoint.clone());
    if let Some(rec) = local.deployments.get_mut(id) {
        rec.container_id = Some(previous_container_id.clone());
        rec.phase = "rolled_back".to_string();
    }
    let _ = local.save();
    reporter.report(
        id,
        version,
        "rolled_back",
        "",
        attempt,
        Some(&previous_container_id),
        endpoint.as_deref(),
        None,
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::broker::deploy::state::DeploymentRecord;
    use std::collections::HashMap;

    fn desired(id: &str, version: u64, desired_state: &str) -> Desired {
        Desired {
            id: id.to_string(),
            version,
            name: format!("name-{id}"),
            image: "python:3.12-slim".to_string(),
            cmd: None,
            ports: vec![super::super::Port {
                container: 8000,
                protocol: "http".to_string(),
            }],
            env: HashMap::new(),
            healthcheck: None,
            price_per_second: 0.0001,
            desired_state: desired_state.to_string(),
            service_account: None,
            warm: true,
            previous: None,
        }
    }

    fn record(version: u64, phase: &str, container_id: Option<&str>) -> DeploymentRecord {
        DeploymentRecord {
            version,
            container_id: container_id.map(|s| s.to_string()),
            image: "python:3.12-slim".to_string(),
            endpoint: None,
            ip: None,
            port: None,
            price_per_second: 0.0001,
            service_account: None,
            warm: true,
            phase: phase.to_string(),
            previous_container_id: None,
            mesh_endpoint: None,
            mesh_port: None,
            failed_version: None,
        }
    }

    #[test]
    fn plan_new_deployment_pulls_starts_and_checks_health() {
        let d = desired("dep_1", 1, "running");
        let local = LocalState::default();
        let actions = plan(&[d], &local);
        assert_eq!(
            actions,
            vec![
                Action::Pull { id: "dep_1".into() },
                Action::Start { id: "dep_1".into() },
                Action::Health { id: "dep_1".into() },
            ]
        );
    }

    #[test]
    fn plan_version_bump_appends_stop_old_after_health() {
        let d = desired("dep_1", 2, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("old-container")));
        let actions = plan(&[d], &local);
        assert_eq!(
            actions,
            vec![
                Action::Pull { id: "dep_1".into() },
                Action::Start { id: "dep_1".into() },
                Action::Health { id: "dep_1".into() },
                Action::StopOld { id: "dep_1".into() },
            ]
        );
    }

    #[test]
    fn plan_stopped_desired_state_stops_running_container() {
        let d = desired("dep_1", 1, "stopped");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("c1")));
        let actions = plan(&[d], &local);
        assert_eq!(actions, vec![Action::Stop { id: "dep_1".into() }]);
    }

    #[test]
    fn plan_stopped_desired_state_with_nothing_running_is_a_noop() {
        let d = desired("dep_1", 1, "stopped");
        let local = LocalState::default();
        assert_eq!(plan(&[d], &local), vec![]);
    }

    #[test]
    fn plan_unchanged_and_healthy_is_a_noop() {
        let d = desired("dep_1", 1, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("c1")));
        assert_eq!(plan(&[d], &local), vec![]);
    }

    #[test]
    fn plan_resumes_a_stuck_mid_flight_deployment() {
        // Same version already on record, but not healthy (e.g. broker
        // restarted between Start and Health) — resume, don't re-pull.
        let d = desired("dep_1", 1, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "starting", Some("c1")));
        let actions = plan(&[d], &local);
        assert_eq!(
            actions,
            vec![
                Action::Start { id: "dep_1".into() },
                Action::Health { id: "dep_1".into() },
            ]
        );
    }

    #[test]
    fn plan_does_not_retry_a_failed_record_at_the_same_version() {
        let d = desired("dep_1", 1, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "failed", None));
        assert_eq!(plan(std::slice::from_ref(&d), &local), vec![]);

        // A rollback at the same version is just as final.
        local
            .deployments
            .insert("dep_1".into(), record(1, "rolled_back", Some("old")));
        assert_eq!(plan(&[d], &local), vec![]);
    }

    #[test]
    fn plan_retries_a_failed_record_once_the_version_is_bumped() {
        let d = desired("dep_1", 2, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "failed", None));
        assert_eq!(
            plan(&[d], &local),
            vec![
                Action::Pull { id: "dep_1".into() },
                Action::Start { id: "dep_1".into() },
                Action::Health { id: "dep_1".into() },
                Action::StopOld { id: "dep_1".into() },
            ]
        );
    }

    #[test]
    fn plan_does_not_retry_a_failed_version_whose_record_is_the_old_healthy_one() {
        // `docker run` for v2 failed while v1 kept running: the record still
        // says v1 healthy, so only `failed_version` tells plan() not to retry.
        let d = desired("dep_1", 2, "running");
        let mut rec = record(1, "healthy", Some("old"));
        rec.failed_version = Some(2);
        let mut local = LocalState::default();
        local.deployments.insert("dep_1".into(), rec);
        assert_eq!(plan(&[d], &local), vec![]);
    }

    #[test]
    fn plan_still_resumes_records_stuck_in_every_in_flight_phase() {
        for phase in ["pulling", "starting", "health_check"] {
            let mut local = LocalState::default();
            local
                .deployments
                .insert("dep_1".into(), record(1, phase, Some("c1")));
            assert_eq!(
                plan(&[desired("dep_1", 1, "running")], &local),
                vec![
                    Action::Start { id: "dep_1".into() },
                    Action::Health { id: "dep_1".into() },
                ],
                "{phase}"
            );
        }
    }

    #[test]
    fn last_line_skips_trailing_blank_lines() {
        assert_eq!(last_line("a\nb\n\n"), "b");
        assert_eq!(last_line(""), "");
    }

    #[test]
    fn plan_previous_naming_another_deployment_stops_it_on_handoff() {
        let mut d = desired("dep_2", 1, "running");
        d.previous = Some(Box::new(super::super::PreviousDeployment {
            id: "dep_1".into(),
            image: "old-image".into(),
            cmd: None,
            ports: vec![],
            env: HashMap::new(),
            healthcheck: None,
        }));
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("old-container")));
        let actions = plan(&[d], &local);
        assert_eq!(
            actions,
            vec![
                Action::Pull { id: "dep_2".into() },
                Action::Start { id: "dep_2".into() },
                Action::Health { id: "dep_2".into() },
                Action::Stop { id: "dep_1".into() },
            ]
        );
    }

    #[test]
    fn plan_previous_naming_the_same_deployment_does_not_double_stop() {
        // previous.id == this deployment's own id is the ordinary
        // version-bump case, already covered by StopOld — must not ALSO
        // produce a handoff Stop for itself.
        let mut d = desired("dep_1", 2, "running");
        d.previous = Some(Box::new(super::super::PreviousDeployment {
            id: "dep_1".into(),
            image: "python:3.12-slim".into(),
            cmd: None,
            ports: vec![],
            env: HashMap::new(),
            healthcheck: None,
        }));
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("old-container")));
        let actions = plan(&[d], &local);
        assert_eq!(
            actions,
            vec![
                Action::Pull { id: "dep_1".into() },
                Action::Start { id: "dep_1".into() },
                Action::Health { id: "dep_1".into() },
                Action::StopOld { id: "dep_1".into() },
            ]
        );
    }

    #[test]
    fn plan_failure_with_container_and_previous_removes_reports_failed_then_rolled_back() {
        let actions = plan_failure("dep_1", Some("new-c"), true);
        assert_eq!(
            actions,
            vec![
                Action::Remove {
                    id: "dep_1".into(),
                    container_id: "new-c".into(),
                },
                Action::Report {
                    id: "dep_1".into(),
                    phase: "failed".into(),
                    message: None,
                },
                Action::Report {
                    id: "dep_1".into(),
                    phase: "rolled_back".into(),
                    message: None,
                },
            ]
        );
    }

    #[test]
    fn plan_failure_without_container_or_previous_is_just_a_failed_report() {
        // A `Pull` failure never created a container, and there was nothing
        // previously running to fall back to.
        let actions = plan_failure("dep_1", None, false);
        assert_eq!(
            actions,
            vec![Action::Report {
                id: "dep_1".into(),
                phase: "failed".into(),
                message: None,
            }]
        );
    }

    // `health_http_url` moved to `runtime.rs` (it's tested there) once
    // health probing became a `ContainerRuntime` method (`health_check`) —
    // see that module's tests.

    // --- driver tests: a fake ContainerRuntime + a recording StatusReporter --

    use std::sync::Mutex;

    #[derive(Default)]
    struct FakeRuntime {
        next_container_id: Mutex<u32>,
        run_should_fail: Mutex<bool>,
        pull_error: Mutex<Option<String>>,
        health_should_fail: Mutex<bool>,
        stopped: Mutex<Vec<String>>,
        removed: Mutex<Vec<String>>,
        restarted: Mutex<Vec<String>>,
        last_run_env: Mutex<HashMap<String, String>>,
        last_run_network: Mutex<Option<String>>,
        last_run_ports: Mutex<Vec<u16>>,
        /// When set, `container_addr` answers this instead of
        /// `container_ip` + the container port (a Docker Desktop host).
        published: Mutex<Option<(String, u16)>>,
    }

    impl ContainerRuntime for FakeRuntime {
        fn available(&self) -> bool {
            true
        }
        fn pull(&self, _image: &str) -> Result<(), String> {
            match self.pull_error.lock().unwrap().clone() {
                Some(e) => Err(e),
                None => Ok(()),
            }
        }
        fn run(&self, spec: &RunSpec) -> Result<String, String> {
            *self.last_run_env.lock().unwrap() = spec.env.clone();
            *self.last_run_network.lock().unwrap() = spec.network.clone();
            *self.last_run_ports.lock().unwrap() = spec.ports.iter().map(|p| p.container).collect();
            if *self.run_should_fail.lock().unwrap() {
                return Err(
                    "docker: Error response from daemon\nno space left on device\n".to_string(),
                );
            }
            let mut n = self.next_container_id.lock().unwrap();
            *n += 1;
            Ok(format!("c{n}"))
        }
        fn stop(&self, container_id: &str) -> Result<(), String> {
            self.stopped.lock().unwrap().push(container_id.to_string());
            Ok(())
        }
        fn rm(&self, container_id: &str) -> Result<(), String> {
            self.removed.lock().unwrap().push(container_id.to_string());
            Ok(())
        }
        fn restart(&self, container_id: &str) -> Result<(), String> {
            self.restarted
                .lock()
                .unwrap()
                .push(container_id.to_string());
            Ok(())
        }
        fn is_running(&self, _container_id: &str) -> bool {
            true
        }
        fn container_ip(&self, _container_id: &str) -> Result<String, String> {
            Ok("172.17.0.5".to_string())
        }
        fn container_addr(&self, container_id: &str, port: u16) -> Result<(String, u16), String> {
            match self.published.lock().unwrap().clone() {
                Some(addr) => Ok(addr),
                None => self.container_ip(container_id).map(|ip| (ip, port)),
            }
        }
        fn health_check(&self, _container_id: &str, _hc: &Healthcheck) -> bool {
            !*self.health_should_fail.lock().unwrap()
        }
        fn health_probe(&self, _container_id: &str, _hc: &Healthcheck) -> Result<(), String> {
            if *self.health_should_fail.lock().unwrap() {
                Err("GET http://172.17.0.5:8000/ → connection refused".to_string())
            } else {
                Ok(())
            }
        }
        fn logs_tail(&self, _container_id: &str, lines: u32) -> String {
            format!("boom (tail {lines})")
        }
        fn list_by_label(&self, _id: &str) -> Vec<String> {
            vec![]
        }
    }

    #[derive(Default)]
    struct RecordingReporter {
        calls: Mutex<Vec<(String, u64, String)>>, // (id, version, phase)
        meshes: Mutex<Vec<Option<String>>>,       // mesh_endpoint, same order as calls
        failures: Mutex<Vec<(Option<String>, FailureDetail)>>, // (container_id, detail)
        healthy_logs: Mutex<Vec<Option<String>>>, // logs of each healthy report
    }

    impl StatusReporter for RecordingReporter {
        fn report(
            &self,
            id: &str,
            version: u64,
            phase: &str,
            _message: &str,
            _attempt: u32,
            _container_id: Option<&str>,
            _endpoint: Option<&str>,
            mesh_endpoint: Option<&str>,
        ) {
            self.calls
                .lock()
                .unwrap()
                .push((id.to_string(), version, phase.to_string()));
            self.meshes
                .lock()
                .unwrap()
                .push(mesh_endpoint.map(str::to_string));
        }

        fn report_healthy(
            &self,
            id: &str,
            version: u64,
            attempt: u32,
            container_id: Option<&str>,
            endpoint: Option<&str>,
            logs: Option<&str>,
        ) {
            self.healthy_logs
                .lock()
                .unwrap()
                .push(logs.map(str::to_string));
            self.report(
                id,
                version,
                "healthy",
                "",
                attempt,
                container_id,
                endpoint,
                None,
            );
        }

        fn report_failure(
            &self,
            id: &str,
            version: u64,
            attempt: u32,
            container_id: Option<&str>,
            failure: &FailureDetail,
        ) {
            self.failures
                .lock()
                .unwrap()
                .push((container_id.map(str::to_string), failure.clone()));
            self.report(
                id,
                version,
                "failed",
                &failure.message,
                attempt,
                container_id,
                None,
                None,
            );
        }
    }

    // No healthcheck configured => wait_healthy returns true immediately,
    // so the driver tests below don't sleep on the 2s poll loop.

    #[test]
    fn drive_new_deployment_goes_healthy_and_persists_endpoint() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let d = desired("dep_1", 1, "running");
        let mut local = LocalState::default();

        drive(&rt, &reporter, &[d], &mut local);

        let rec = local.deployments.get("dep_1").expect("recorded");
        assert_eq!(rec.phase, "healthy");
        assert_eq!(rec.container_id.as_deref(), Some("c1"));
        assert_eq!(rec.endpoint.as_deref(), Some("172.17.0.5:8000"));
        assert_eq!(rec.ip.as_deref(), Some("172.17.0.5"));

        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(
            phases,
            vec!["pulling", "starting", "health_check", "healthy"]
        );
    }

    #[test]
    fn drive_passes_service_account_to_the_container_as_env_and_persists_it() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let mut d = desired("dep_1", 1, "running");
        d.service_account = Some(super::super::ServiceAccount {
            name: "billing-svc".to_string(),
            grants: vec!["kv:read".to_string(), "queue:publish".to_string()],
            policy: None,
        });
        let mut local = LocalState::default();

        drive(&rt, &reporter, &[d], &mut local);

        let env = rt.last_run_env.lock().unwrap();
        assert_eq!(
            env.get("ZAKURO_SERVICE_ACCOUNT").map(String::as_str),
            Some("billing-svc")
        );
        assert_eq!(
            env.get("ZAKURO_GRANTS").map(String::as_str),
            Some("kv:read,queue:publish")
        );

        let rec = local.deployments.get("dep_1").unwrap();
        assert_eq!(
            rec.service_account.as_ref().map(|sa| sa.name.as_str()),
            Some("billing-svc")
        );
    }

    fn run_with_policy(grants: &[&str], policy: Option<serde_json::Value>) -> Option<String> {
        let rt = FakeRuntime::default();
        let mut d = desired("dep_1", 1, "running");
        d.service_account = Some(super::super::ServiceAccount {
            name: "svc".to_string(),
            grants: grants.iter().map(|s| s.to_string()).collect(),
            policy,
        });
        drive(
            &rt,
            &RecordingReporter::default(),
            &[d],
            &mut LocalState::default(),
        );
        let n = rt.last_run_network.lock().unwrap().clone();
        n
    }

    #[test]
    fn drive_isolates_a_workload_whose_policy_denies_network() {
        let _home = expose::TempZakuroHome::new();
        let deny = serde_json::json!({"Statement":[
            {"Effect":"Allow","Action":"datasets:*","Resource":"arn:zakuro:datasets:::*"}]});
        assert_eq!(
            run_with_policy(&["network:mesh"], Some(deny)),
            Some(crate::broker::deploy::runtime::isolated_network())
        );
        // Unparseable policy fails closed.
        assert!(run_with_policy(&[], Some(serde_json::json!("garbage"))).is_some());
        // An explicit Deny wins over a broad Allow.
        let p = serde_json::json!({"Statement":[
            {"Effect":"Allow","Action":"*:*","Resource":"arn:zakuro:*:::*"},
            {"Effect":"Deny","Action":"network:*","Resource":"arn:zakuro:network:::*"}]});
        assert!(run_with_policy(&[], Some(p)).is_some());
    }

    #[test]
    fn drive_keeps_the_default_network_without_an_enforced_policy() {
        let _home = expose::TempZakuroHome::new();
        // No policy, the V025 legacy backfill, and an allowing policy.
        assert_eq!(run_with_policy(&["network:mesh"], None), None);
        let legacy = serde_json::json!({"Version":"2026-01-01","Statement":[
            {"Sid":"LegacyGrant0","Effect":"Allow","Action":"network:mesh",
             "Resource":"arn:zakuro:network:::*"}]});
        assert_eq!(run_with_policy(&["network:mesh"], Some(legacy)), None);
        let allow = serde_json::json!({"Statement":[
            {"Effect":"Allow","Action":"network:Connect","Resource":"arn:zakuro:network:::*"}]});
        assert_eq!(run_with_policy(&[], Some(allow)), None);
    }

    #[test]
    fn desired_without_policy_still_parses_and_policy_round_trips() {
        let old: super::super::ServiceAccount =
            serde_json::from_str(r#"{"name":"default","grants":["network:mesh"]}"#).unwrap();
        assert!(old.policy.is_none());
        let new: super::super::ServiceAccount = serde_json::from_str(
            r#"{"name":"a","grants":[],"policy":{"Statement":"not even valid"}}"#,
        )
        .unwrap();
        assert!(new.policy.is_some());
    }

    #[test]
    fn drive_records_the_published_loopback_address_when_the_runtime_has_one() {
        let _home = expose::TempZakuroHome::new();
        // Docker Desktop (macOS): the container's bridge IP has no route from
        // the host, so the runtime answers a published 127.0.0.1 port and
        // that is what /serve and mesh exposure must dial.
        let rt = FakeRuntime::default();
        *rt.published.lock().unwrap() = Some(("127.0.0.1".to_string(), 49153));
        let reporter = RecordingReporter::default();
        let mut local = LocalState::default();

        drive(
            &rt,
            &reporter,
            &[desired("dep_1", 1, "running")],
            &mut local,
        );

        let rec = local.deployments.get("dep_1").expect("recorded");
        assert_eq!(rec.phase, "healthy");
        assert_eq!(rec.endpoint.as_deref(), Some("127.0.0.1:49153"));
        assert_eq!(rec.ip.as_deref(), Some("127.0.0.1"));
        assert_eq!(rec.port, Some(49153));
    }

    #[test]
    fn drive_runs_with_the_healthcheck_port_even_when_ports_omit_it() {
        let _home = expose::TempZakuroHome::new();
        // A published-port runtime only maps the ports it is given, so the
        // healthcheck port must be among them.
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let mut d = desired("dep_1", 1, "running");
        d.healthcheck = Some(Healthcheck {
            kind: "http".to_string(),
            port: 8888,
            path: Some("/api".to_string()),
            timeout_s: 5,
        });
        let mut local = LocalState::default();

        drive(&rt, &reporter, &[d], &mut local);

        assert_eq!(*rt.last_run_ports.lock().unwrap(), vec![8000, 8888]);
    }

    #[test]
    fn drive_version_bump_stops_old_container_after_healthy() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let d = desired("dep_1", 2, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("old-container")));

        drive(&rt, &reporter, &[d], &mut local);

        assert!(rt
            .stopped
            .lock()
            .unwrap()
            .contains(&"old-container".to_string()));
        assert!(rt
            .removed
            .lock()
            .unwrap()
            .contains(&"old-container".to_string()));
        let rec = local.deployments.get("dep_1").unwrap();
        assert_eq!(rec.phase, "healthy");
        assert_eq!(rec.version, 2);
        assert!(rec.previous_container_id.is_none());
    }

    #[test]
    fn drive_start_failure_leaves_existing_container_untouched() {
        let _home = expose::TempZakuroHome::new();
        // `docker run` itself failing (before any new container exists) is
        // NOT a rollback: the old version was never stopped or replaced, so
        // there's nothing to restore — just a `failed` report, and local
        // state keeps recording the old (still-running, still-healthy)
        // container exactly as it was.
        let rt = FakeRuntime::default();
        *rt.run_should_fail.lock().unwrap() = true;
        let reporter = RecordingReporter::default();
        let d = desired("dep_1", 2, "running");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("old-container")));

        drive(&rt, &reporter, &[d], &mut local);

        let rec = local.deployments.get("dep_1").unwrap();
        assert_eq!(rec.phase, "healthy");
        assert_eq!(rec.version, 1);
        assert_eq!(rec.container_id.as_deref(), Some("old-container"));
        assert!(rt.restarted.lock().unwrap().is_empty());
        assert!(rt.stopped.lock().unwrap().is_empty());
        assert!(rt.removed.lock().unwrap().is_empty());

        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(phases, vec!["pulling", "starting", "failed"]);
    }

    #[test]
    fn drive_health_failure_rolls_back_to_previous_container() {
        let _home = expose::TempZakuroHome::new();
        // Unlike a `Start` failure, a `Health` failure DID create a new
        // container that superseded the old one in local state (see
        // `Action::Start`'s success branch) — so this is the real rollback
        // path: stop+remove the failed new container, restart the old one,
        // and report `failed` then `rolled_back`.
        let rt = FakeRuntime::default();
        *rt.health_should_fail.lock().unwrap() = true;
        let reporter = RecordingReporter::default();
        let mut d = desired("dep_1", 2, "running");
        d.healthcheck = Some(Healthcheck {
            kind: "http".to_string(),
            port: 8000,
            path: None,
            timeout_s: 1,
        });
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("old-container")));

        drive(&rt, &reporter, &[d], &mut local);

        let rec = local.deployments.get("dep_1").unwrap();
        assert_eq!(rec.phase, "rolled_back");
        assert_eq!(rec.container_id.as_deref(), Some("old-container"));
        assert!(rt
            .restarted
            .lock()
            .unwrap()
            .contains(&"old-container".to_string()));
        // The failed NEW attempt (c1) was stopped+removed; the old container
        // was never stopped, only restarted (belt-and-braces).
        assert!(rt.stopped.lock().unwrap().contains(&"c1".to_string()));
        assert!(rt.removed.lock().unwrap().contains(&"c1".to_string()));
        assert!(!rt
            .removed
            .lock()
            .unwrap()
            .contains(&"old-container".to_string()));

        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(
            phases,
            vec![
                "pulling",
                "starting",
                "health_check",
                "failed",
                "rolled_back"
            ]
        );
        drop(calls);

        // The failed report says why: the last probe, the log tail (read
        // before the container was removed) and how many probes failed.
        let failures = reporter.failures.lock().unwrap();
        assert_eq!(failures.len(), 1);
        let (cid, f) = &failures[0];
        assert_eq!(cid.as_deref(), Some("c1"));
        assert_eq!(f.code, "health_failed");
        assert_eq!(
            f.message,
            "GET http://172.17.0.5:8000/ → connection refused"
        );
        assert_eq!(f.logs.as_deref(), Some("boom (tail 50)"));
        assert!(f.probes_failed.unwrap() >= 1);
    }

    #[test]
    fn drive_run_failure_with_no_previous_leaves_deployment_failed() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        *rt.run_should_fail.lock().unwrap() = true;
        let reporter = RecordingReporter::default();
        let d = desired("dep_1", 1, "running");
        let mut local = LocalState::default();

        drive(&rt, &reporter, &[d], &mut local);

        let rec = local.deployments.get("dep_1").unwrap();
        assert_eq!(rec.phase, "failed");
        assert_eq!(rec.version, 1);
        assert!(rec.container_id.is_none());

        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(phases, vec!["pulling", "starting", "failed"]);
        drop(calls);

        // The message is docker's last stderr line; no container, so no logs.
        let failures = reporter.failures.lock().unwrap();
        let (cid, f) = &failures[0];
        assert!(cid.is_none());
        assert_eq!(f.code, "start_failed");
        assert_eq!(f.message, "no space left on device");
        assert!(f.logs.is_none() && f.probes_failed.is_none());
    }

    #[test]
    fn drive_pull_failure_reports_pull_failed_and_stops_the_pass() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        *rt.pull_error.lock().unwrap() =
            Some("Pulling from x\n\ndenied: requested access is denied\n".to_string());
        let reporter = RecordingReporter::default();
        let mut local = LocalState::default();

        drive(
            &rt,
            &reporter,
            &[desired("dep_1", 1, "running")],
            &mut local,
        );

        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(phases, vec!["pulling", "failed"]);
        drop(calls);
        let failures = reporter.failures.lock().unwrap();
        assert_eq!(failures[0].1.code, "pull_failed");
        assert_eq!(failures[0].1.message, "denied: requested access is denied");
        assert_eq!(local.deployments["dep_1"].phase, "failed");
    }

    #[test]
    fn drive_does_not_retry_a_failed_version_on_the_next_tick() {
        let _home = expose::TempZakuroHome::new();
        // The staging bug: a failed rollout was re-run (starting -> failed)
        // every tick. Now the second pass reports and runs nothing.
        let rt = FakeRuntime::default();
        *rt.run_should_fail.lock().unwrap() = true;
        let reporter = RecordingReporter::default();
        let d = desired("dep_1", 1, "running");
        let mut local = LocalState::default();

        drive(&rt, &reporter, std::slice::from_ref(&d), &mut local);
        let first = reporter.calls.lock().unwrap().len();
        drive(&rt, &reporter, &[d], &mut local);

        assert_eq!(reporter.calls.lock().unwrap().len(), first);
    }

    #[test]
    fn drive_retries_once_the_hub_bumps_the_version() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        *rt.run_should_fail.lock().unwrap() = true;
        let reporter = RecordingReporter::default();
        let mut local = LocalState::default();
        drive(
            &rt,
            &reporter,
            &[desired("dep_1", 1, "running")],
            &mut local,
        );

        *rt.run_should_fail.lock().unwrap() = false;
        drive(
            &rt,
            &reporter,
            &[desired("dep_1", 2, "running")],
            &mut local,
        );

        let rec = &local.deployments["dep_1"];
        assert_eq!(rec.phase, "healthy");
        assert_eq!(rec.version, 2);
        assert_eq!(rec.failed_version, None);
    }

    #[test]
    fn drive_stopped_desired_state_stops_and_reports() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let d = desired("dep_1", 1, "stopped");
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("c1")));

        drive(&rt, &reporter, &[d], &mut local);

        assert!(rt.stopped.lock().unwrap().contains(&"c1".to_string()));
        let rec = local.deployments.get("dep_1").unwrap();
        assert_eq!(rec.phase, "stopped");
        assert!(rec.container_id.is_none());
        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(phases, vec!["stopped"]);
    }

    // --- drive_and_expose: drive() plus mesh exposure (zc#209) --------------

    /// A v1 deployment on `ip`, already exposed at 10.13.13.22:8000.
    fn exposed_record(ip: &str, container_id: &str) -> DeploymentRecord {
        let mut rec = record(1, "healthy", Some(container_id));
        rec.ip = Some(ip.to_string());
        rec.port = Some(8000);
        rec.endpoint = Some(format!("{ip}:8000"));
        rec.mesh_endpoint = Some("10.13.13.22:8000".to_string());
        rec.mesh_port = Some(8000);
        rec
    }

    #[test]
    fn drive_and_expose_reports_a_new_deployment_healthy_then_its_mesh_endpoint() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let exposer = expose::FakeExposer::default();
        let mut local = LocalState::default();

        drive_and_expose(
            &rt,
            &reporter,
            &exposer,
            Some("10.13.13.22"),
            &[desired("dep_1", 1, "running")],
            &mut local,
        );

        let calls = reporter.calls.lock().unwrap();
        let phases: Vec<&str> = calls.iter().map(|(_, _, p)| p.as_str()).collect();
        assert_eq!(
            phases,
            vec!["pulling", "starting", "health_check", "healthy", "healthy"]
        );
        assert_eq!(
            *reporter.meshes.lock().unwrap(),
            vec![None, None, None, None, Some("10.13.13.22:8000".to_string())]
        );
        assert_eq!(
            exposer.target_of("dep_1").as_deref(),
            Some("172.17.0.5:8000")
        );
        assert_eq!(
            local.deployments["dep_1"].mesh_endpoint.as_deref(),
            Some("10.13.13.22:8000")
        );
    }

    #[test]
    fn drive_and_expose_re_reports_the_mesh_endpoint_after_a_version_bump() {
        // v1 was exposed at 10.13.13.22:8000; v2 comes up on a new container
        // IP. drive()'s own `healthy` report carries no mesh endpoint, so the
        // hub has to be told again even though the port stays the same.
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let exposer = expose::FakeExposer::default();
        exposer.expose("dep_1", "10.13.13.22", "172.17.0.4:8000", 8000);
        let mut local = LocalState::default();
        local.deployments.insert(
            "dep_1".into(),
            exposed_record("172.17.0.4", "old-container"),
        );

        drive_and_expose(
            &rt,
            &reporter,
            &exposer,
            Some("10.13.13.22"),
            &[desired("dep_1", 2, "running")],
            &mut local,
        );

        let last = reporter.calls.lock().unwrap().last().cloned();
        assert_eq!(last, Some(("dep_1".to_string(), 2, "healthy".to_string())));
        let last_mesh = reporter.meshes.lock().unwrap().last().cloned().flatten();
        assert_eq!(last_mesh.as_deref(), Some("10.13.13.22:8000"));
        assert_eq!(
            exposer.target_of("dep_1").as_deref(),
            Some("172.17.0.5:8000")
        );
    }

    #[test]
    fn drive_and_expose_releases_a_stopped_deployment() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let exposer = expose::FakeExposer::default();
        exposer.expose("dep_1", "10.13.13.22", "172.17.0.4:8000", 8000);
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), exposed_record("172.17.0.4", "c1"));

        drive_and_expose(
            &rt,
            &reporter,
            &exposer,
            Some("10.13.13.22"),
            &[desired("dep_1", 1, "stopped")],
            &mut local,
        );

        assert!(exposer.exposed_ids().is_empty());
        assert_eq!(local.deployments["dep_1"].mesh_endpoint, None);
        // Only drive()'s own `stopped` report, which carries no mesh endpoint.
        assert_eq!(*reporter.meshes.lock().unwrap(), vec![None]);
    }

    // --- zc#213: a `stopped` report carries the version the hub asked for --

    #[test]
    fn drive_stop_reports_the_desired_version_not_the_local_one() {
        // The hub's stop route bumps the deployment to v2 and ignores any
        // report older than that, so a `stopped` report carrying the local
        // v1 would be dropped and the console would keep showing healthy.
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("c1")));

        drive(
            &rt,
            &reporter,
            &[desired("dep_1", 2, "stopped")],
            &mut local,
        );

        assert_eq!(
            *reporter.calls.lock().unwrap(),
            vec![("dep_1".to_string(), 2, "stopped".to_string())]
        );
    }

    #[test]
    fn drive_handoff_stop_of_an_unlisted_deployment_reports_its_local_version() {
        // `previous` names dep_1, which the hub no longer lists at all: there
        // is no desired version for it, so the local record's is reported.
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let mut d = desired("dep_2", 1, "running");
        d.previous = Some(Box::new(super::super::PreviousDeployment {
            id: "dep_1".into(),
            image: "old-image".into(),
            cmd: None,
            ports: vec![],
            env: HashMap::new(),
            healthcheck: None,
        }));
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(3, "healthy", Some("old-container")));

        drive(&rt, &reporter, &[d], &mut local);

        let calls = reporter.calls.lock().unwrap();
        assert!(
            calls.contains(&("dep_1".to_string(), 3, "stopped".to_string())),
            "{calls:?}"
        );
    }

    // --- unlisted deployments: the hub dropped them, the node must too -----

    #[test]
    fn plan_empty_desired_forgets_every_local_record() {
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("c1")));
        assert_eq!(
            plan(&[], &local),
            vec![Action::Forget { id: "dep_1".into() }]
        );
    }

    #[test]
    fn plan_only_forgets_the_unlisted_record() {
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_a".into(), record(1, "healthy", Some("ca")));
        local
            .deployments
            .insert("dep_b".into(), record(1, "healthy", Some("cb")));
        let actions = plan(&[desired("dep_a", 1, "running")], &local);
        assert_eq!(actions, vec![Action::Forget { id: "dep_b".into() }]);
    }

    #[test]
    fn plan_forgets_an_unlisted_record_that_is_already_stopped() {
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "stopped", None));
        assert_eq!(
            plan(&[], &local),
            vec![Action::Forget { id: "dep_1".into() }]
        );
    }

    #[test]
    fn plan_leaves_a_handoff_previous_to_the_handoff_stop() {
        let mut d = desired("dep_2", 1, "running");
        d.previous = Some(Box::new(super::super::PreviousDeployment {
            id: "dep_1".into(),
            image: "old-image".into(),
            cmd: None,
            ports: vec![],
            env: HashMap::new(),
            healthcheck: None,
        }));
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "healthy", Some("c1")));
        let actions = plan(&[d], &local);
        assert!(!actions.iter().any(|a| matches!(a, Action::Forget { .. })));
        assert!(actions.contains(&Action::Stop { id: "dep_1".into() }));
    }

    #[test]
    fn drive_unlisted_record_is_stopped_removed_and_forgotten_silently() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_a".into(), record(1, "healthy", Some("ca")));
        local
            .deployments
            .insert("dep_b".into(), record(1, "healthy", Some("cb")));

        drive(
            &rt,
            &reporter,
            &[desired("dep_a", 1, "running")],
            &mut local,
        );

        assert_eq!(*rt.stopped.lock().unwrap(), vec!["cb".to_string()]);
        assert_eq!(*rt.removed.lock().unwrap(), vec!["cb".to_string()]);
        assert!(!local.deployments.contains_key("dep_b"));
        assert!(local.deployments.contains_key("dep_a"));
        assert!(reporter.calls.lock().unwrap().is_empty());
    }

    #[test]
    fn drive_unlisted_stopped_record_is_just_forgotten() {
        let _home = expose::TempZakuroHome::new();
        let rt = FakeRuntime::default();
        let reporter = RecordingReporter::default();
        let mut local = LocalState::default();
        local
            .deployments
            .insert("dep_1".into(), record(1, "stopped", None));

        drive(&rt, &reporter, &[], &mut local);

        assert!(local.deployments.is_empty());
        assert!(rt.stopped.lock().unwrap().is_empty());
        assert!(rt.removed.lock().unwrap().is_empty());
    }
}