openlatch-client 0.5.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! `openlatch system model-relay <status|enable|disable|explain>` — inspect and switch
//! the model-relay listener.
//!
//! **`enable` / `disable` write config, and only config.** The agent's
//! `ANTHROPIC_BASE_URL` stays owned by the daemon: it writes the value after it
//! binds the pinned port and removes it when it lets go, which is what keeps
//! the agent config from ever naming a listener that does not exist. A command
//! that wrote that value by hand would be a second owner of the invariant, and
//! two owners is how the config came to point at a port nobody held.
//!
//! These commands existed as a documented non-feature until an operator with
//! `[model_relay] enabled = false` in `config.toml` had no supported way back:
//! `init` never writes `true`, so the opt-out was a one-way door out of the
//! product's main capability, undone only by hand-editing TOML. Writing the
//! flag is not the same job as owning the wiring, and the second job stays
//! where it was.

use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::{ModelRelayCommands, ModelRelayToggleArgs};
use crate::error::{OlError, ERR_MODEL_RELAY_FINDING_NOT_FOUND};

/// Dispatch `openlatch system model-relay <sub>`.
pub fn run(cmd: &ModelRelayCommands, output: &OutputConfig) -> Result<(), OlError> {
    match cmd {
        ModelRelayCommands::Status => status(output),
        ModelRelayCommands::Enable(args) => toggle(true, args, output),
        ModelRelayCommands::Disable(args) => toggle(false, args, output),
        ModelRelayCommands::Explain { finding_id } => explain(finding_id, output),
    }
}

/// `openlatch system model-relay enable|disable` — write `[model_relay] enabled`, then offer
/// the restart that makes it real.
///
/// There is no hot switch on purpose. Binding 7600 and writing
/// `ANTHROPIC_BASE_URL` are startup invariants of the daemon
/// (`daemon::serve_with_listener`), so a running daemon cannot adopt the new
/// value without coming back up. Claiming otherwise would produce exactly the
/// divergence this whole area is being repaired for: a config that says one
/// thing and a process doing another.
fn toggle(enable: bool, args: &ModelRelayToggleArgs, output: &OutputConfig) -> Result<(), OlError> {
    use std::io::{BufRead, IsTerminal, Write};

    let config_path = crate::config::openlatch_dir().join("config.toml");
    if !config_path.exists() {
        crate::config::ensure_config(crate::config::Config::defaults().port)?;
    }

    let before = crate::config::Config::load(None, None, false)
        .map(|c| c.model_relay.enabled)
        .unwrap_or(true);
    let verb = if enable { "enabled" } else { "disabled" };

    crate::cli::header::print(
        output,
        &[
            "system",
            "model-relay",
            if enable { "enable" } else { "disable" },
        ],
    );

    if before == enable {
        // Idempotent, and deliberately not an early return: config and runtime
        // can disagree, and that disagreement is the thing worth fixing.
        output.print_substep(&format!("Model relay already {verb} in config"));
    } else {
        crate::config::persist_model_relay_enabled(&config_path, enable)?;
        output.print_step(&format!("Model relay {verb} in {}", config_path.display()));
    }

    // Nothing to restart, nothing to reconcile.
    let daemon_up = crate::cli::commands::lifecycle::read_pid_file()
        .map(crate::cli::commands::lifecycle::is_process_alive)
        .unwrap_or(false);
    if !daemon_up {
        output.print_step("No daemon running — the change applies at the next start");
        emit_toggle_json(enable, true, false, true, output);
        return Ok(());
    }

    // Prompting requires someone to answer. A non-TTY that passed neither flag
    // gets the same treatment as `--no-restart`: the config is written, the
    // exit code says it is not in effect, and nothing hangs waiting on a stdin
    // that will never carry a keystroke.
    let interactive =
        std::io::stdin().is_terminal() && output.format == OutputFormat::Human && !output.quiet;
    let restart = if args.yes {
        true
    } else if args.no_restart || !interactive {
        false
    } else {
        eprint!("Restart the daemon now to apply? [y/N] ");
        let _ = std::io::stderr().flush();
        let mut answer = String::new();
        let _ = std::io::stdin().lock().read_line(&mut answer);
        matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
    };

    if !restart {
        output.print_substep(
            "Config updated — not in effect until the daemon restarts (run `openlatch restart`)",
        );
        emit_toggle_json(enable, true, false, false, output);
        // Config and runtime disagree. That is the definition of degraded, and
        // a script must be able to see it.
        crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
        return Ok(());
    }

    crate::cli::commands::lifecycle::run_restart(output)?;

    // Measured, not assumed: the restart is only "applied" if the listener
    // state now matches what was just written.
    let cfg = crate::config::Config::load(None, None, false)?;
    // EVERY request plane, not the first one: a two-agent host where only
    // Claude Code came back up has not applied the change, and saying it has is
    // the "off is never a pass" failure in its most literal form.
    let in_effect = model_relay_rows(&cfg).iter().all(|row| match row.state {
        ModelRelayState::Disabled => !enable,
        ModelRelayState::Wired | ModelRelayState::Isolated => enable,
        _ => false,
    });
    if in_effect {
        output.print_step(&format!("Model relay {verb} and in effect"));
    } else {
        output.print_substep(
            "Daemon restarted, but the model relay is not in the requested state — run \
             `openlatch doctor` for the reason",
        );
        crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
    }
    emit_toggle_json(enable, true, true, in_effect, output);
    Ok(())
}

fn emit_toggle_json(
    enabled: bool,
    config_written: bool,
    restarted: bool,
    in_effect: bool,
    output: &OutputConfig,
) {
    if output.format != OutputFormat::Json {
        return;
    }
    output.print_json(&serde_json::json!({
        "enabled": enabled,
        "config_written": config_written,
        "restarted": restarted,
        "in_effect": in_effect,
        "exit_code": if in_effect { 0 } else { crate::cli::report::EXIT_DEGRADED },
    }));
}

/// Who owns the pinned model relay port right now. Read by `openlatch status` and
/// by `openlatch doctor`'s wiring-coherence check, which classify model relay
/// liveness from this signature probe rather than from any disk marker.
#[derive(Debug, PartialEq)]
pub(crate) enum PortOwnership {
    /// A live OpenLatch model relay answered with our status signature — safe.
    Owned,
    /// Something is listening but it is NOT our model relay (wrong/missing
    /// signature). Wiring the agent here would leak its provider credential.
    Foreign,
    /// Nothing is holding the port — the daemon isn't up yet. Covers both a
    /// refused connection and one that never got answered, because which of
    /// the two a closed loopback port produces is a property of the host; see
    /// `verify_port_ownership`.
    Unreachable,
}

/// Budget for the TCP connect leg alone. Deliberately far shorter than
/// `PROBE_TIMEOUT`: a live listener on loopback accepts in microseconds, so
/// 100ms is three orders of magnitude of headroom for the only question this
/// leg asks — is anything there. Keeping it separate is what stops the two
/// legs from stacking into a ~1s worst case on a listener that accepts and
/// then stalls. Same split, same values, as `openlatch-hook`'s
/// `CONNECT_TIMEOUT` / `TOTAL_TIMEOUT`.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);

/// Budget for the HTTP round-trip against the admin status endpoint.
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);

/// GET the model relay's admin status endpoint.
///
/// The single place that knows the URL and the client configuration, because
/// `verify_port_ownership` and `probe_model_relay` both need it and had already
/// drifted: the timeout was a named constant in one and a bare `500` literal
/// in the other. `None` is "no answer" — both callers treat a build failure
/// and a transport failure the same way, and neither can act on the
/// distinction.
fn get_admin_status(port: u16) -> Option<reqwest::blocking::Response> {
    let url = format!("http://127.0.0.1:{port}/admin/model-relay/status");
    crate::egress::blocking_client_builder()
        .timeout(PROBE_TIMEOUT)
        .build()
        .ok()?
        .get(&url)
        .send()
        .ok()
}

/// Probe `http://127.0.0.1:{port}/admin/model-relay/status` and classify who owns
/// the port. Ownership is proven by our JSON signature (`status` + `upstream`
/// keys) — reused from `model_relay_status` so a foreign listener cannot forge it
/// by chance.
pub(crate) fn verify_port_ownership(port: u16) -> PortOwnership {
    // Liveness is decided by a raw TCP connect, deliberately BEFORE any HTTP,
    // and "could not connect" is `Unreachable` regardless of *why*.
    //
    // The previous version classified on reqwest's `is_connect()`, which is not
    // portable, for a reason worth recording because it is counter-intuitive:
    // the time a closed loopback port takes to report refused is a property of
    // the host, not of the protocol. Measured on Windows 11 with the firewall's
    // filter driver in the path, a closed 127.0.0.1 port answers
    // `ConnectionRefused` (WSAECONNREFUSED, os error 10061) only after ~2s of
    // SYN retries. Any probe on a sub-2s budget therefore never sees the
    // refusal — it sees its own timeout. reqwest surfaced that as
    // `is_connect() == false` / `is_timeout() == true`, so the closed port fell
    // through to the catch-all "no answer" case and was called `Foreign`.
    //
    // The user-visible result was not subtle: on every Windows host with the
    // daemon simply not running — the normal idle state — `openlatch status`
    // printed the model relay as "failed" rather than "down"
    // (`status.rs::model_relay_state_from_ownership`) and `doctor` diagnosed a
    // port conflict that did not exist. It passed CI throughout because Linux
    // runners refuse instantly and stay inside the budget.
    //
    // Collapsing refused and timed-out into one verdict is what makes this
    // robust rather than merely re-tuned: the target is loopback, where a live
    // listener accepts in microseconds, so a connect that has neither been
    // accepted nor refused within the budget is not holding the port. The one
    // counter-case is a local listener with a saturated backlog, which is
    // pathological and still a refusal — "down" instead of "failed", both of
    // which decline. Only `Owned`, which requires our JSON signature below,
    // ever permits anything.
    match relay_status_on(port) {
        Ok(_) => PortOwnership::Owned,
        Err(ownership) => ownership,
    }
}

/// Who holds endpoint `port`, as the slot recorded under `key` sees it.
///
/// Our status signature is not enough here. Every endpoint listener IS the
/// relay, so the main port and a sibling slot's port both answer it — and an
/// agent config naming the wrong one of our own ports sends that provider's
/// traffic, and its credential, to a different provider's origin. The listener
/// must also answer with THIS slot's key.
pub(crate) fn verify_endpoint_ownership(port: u16, key: &str) -> PortOwnership {
    match relay_status_on(port) {
        Ok(v) if v["endpoint"]["key"].as_str() == Some(key) => PortOwnership::Owned,
        Ok(_) => PortOwnership::Foreign,
        Err(ownership) => ownership,
    }
}

/// The status JSON of the model relay listening on `port`, or why there is
/// none: nothing listening (`Unreachable`) or something that does not speak
/// our protocol (`Foreign`). The one implementation of the TCP-then-signature
/// check both ownership questions are built on.
fn relay_status_on(port: u16) -> Result<serde_json::Value, PortOwnership> {
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    if std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_err() {
        return Err(PortOwnership::Unreachable);
    }

    // Something is listening (proven above), so no answer here means it did
    // not answer *our* protocol.
    let Some(resp) = get_admin_status(port) else {
        return Err(PortOwnership::Foreign);
    };
    if !resp.status().is_success() {
        return Err(PortOwnership::Foreign);
    }
    match resp.json::<serde_json::Value>() {
        Ok(v) if v.get("status").is_some() && v.get("upstream").is_some() => Ok(v),
        _ => Err(PortOwnership::Foreign),
    }
}

/// `openlatch system model-relay status` — say what the model relay is actually doing.
///
/// Classified, not probed. This used to call `probe_model_relay` alone, so a host
/// with `[model_relay] enabled = false` was told `Model relay: down (pinned port
/// 7600)` and advised to `openlatch start` — a command that will not bind a
/// listener the config has switched off. The operator runs it, nothing changes,
/// and the one command named after the subsystem is the one that cannot explain
/// it. [`classify_model_relay`] is the same predicate `doctor` and `status` use;
/// three commands answering one question now answer it identically.
pub fn status(output: &OutputConfig) -> Result<(), OlError> {
    let cfg = crate::config::Config::load(None, None, false)?;
    let port = cfg.model_relay.port;
    // One row per request plane. The command answers for the HOST, so the exit
    // code and the headline come from the worst of them — a broken Codex plane
    // must not hide behind a green Claude one.
    let rows = model_relay_rows(&cfg);
    let probe = probe_model_relay(port);
    // Provider slots, through doctor's own check for each: the two commands
    // cannot disagree about a slot, and a failed slot fails this command too.
    let (endpoints, endpoint_checks) = endpoint_status(
        &endpoint_rows_for(
            &cfg,
            &crate::hooks::detect_agents(),
            &verify_endpoint_ownership,
        ),
        probe.as_ref(),
    );

    // Same three tiers as every other diagnostic: switched off warns, broken
    // fails, working is silent about itself.
    let severity =
        model_relay_severity(&worst_row(&rows).state).max(endpoint_severity(&endpoint_checks));
    let exit = match severity {
        0 => 0,
        2 => 1,
        _ => crate::cli::report::EXIT_DEGRADED,
    };
    crate::cli::report::record_exit_code(exit);

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "port": port,
            "state": worst_row(&rows).state.label(),
            // The RESOLVED per-format map, rendered from CONFIG so it answers
            // with no daemon running — a stock host's map is empty and printing
            // the raw one would print nothing where a host today prints its
            // upstream. One entry per `WireFormat::ALL` — five now, not three —
            // and each value IS the three-step precedence for its format.
            "upstream": crate::model_relay::wire_format::WireFormat::ALL
                .iter()
                .map(|f| (f.as_str().to_string(), serde_json::json!(cfg.model_relay.upstream_for(*f))))
                .collect::<serde_json::Map<_, _>>(),
            "classification": format!("{:?}", worst_row(&rows).state),
            "enabled": cfg.model_relay.enabled,
            "owns_agent_wiring": cfg.model_relay.owns_agent_wiring(),
            "wired_to": worst_row(&rows).wired,
            // The per-agent breakdown the top-level fields summarise. Wiring is
            // per agent now, and a script that has to know WHICH plane is down
            // reads this rather than re-deriving it.
            "agents": rows
                .iter()
                .filter(|r| !r.agent.is_empty())
                .map(agent_row_json)
                .collect::<Vec<_>>(),
            // One entry per provider slot (Cline's providers), each with the
            // state, code and remedy `doctor` reports for it.
            "endpoints": endpoints,
            "up": probe.is_some(),
            "detail": probe,
            "exit_code": exit,
        }));
        return Ok(());
    }

    crate::cli::header::print(output, &["model-relay status"]);

    // The remedy follows the classification. Sending every non-working state to
    // `openlatch start` is what made this command useless on the one config it
    // was most often run against.
    //
    // One block per request plane: on a two-agent host the states genuinely
    // differ, and collapsing them prints one agent's remedy at the other's
    // problem.
    let multi = rows.len() > 1;
    for row in &rows {
        let wired = row.wired.clone();
        let (line, remedy): (String, Option<String>) = match &row.state {
            ModelRelayState::Disabled => (
                "Model relay: disabled in config — model calls bypass OpenLatch".to_string(),
                Some("Run `openlatch system model-relay enable` to turn it back on.".to_string()),
            ),
            ModelRelayState::Isolated => (
                format!("Model relay: isolated instance on port {port}"),
                Some(format!(
                    "This instance does not touch the machine-global agent config. Route a \
                     session through it with:\n    {}",
                    row.route_hint
                )),
            ),
            ModelRelayState::Wired => (
                format!(
                    "Model relay: up on port {port}, agent wired to {}",
                    wired.as_deref().unwrap_or("it")
                ),
                None,
            ),
            ModelRelayState::WiredButDown => (
                format!("Model relay: agent is wired to 127.0.0.1:{port} but nothing is listening"),
                Some(
                    "Model calls fail with ECONNREFUSED. Run `openlatch start` to bring the \
                     listener up, or `openlatch stop` to clear the wiring and go direct."
                        .to_string(),
                ),
            ),
            ModelRelayState::WiredToForeign => (
                format!("Model relay: 127.0.0.1:{port} is held by a process that is NOT OpenLatch"),
                Some(format!(
                    "The agent is wired to it, so your provider API key is going to that process. \
                     Identify it (lsof -i :{port}), stop it, then run `openlatch restart`."
                )),
            ),
            ModelRelayState::PreflightFailed(why) => (
                format!("Model relay: up on port {port}, preflight FAILED — {why}"),
                Some(
                    "The agent was left unwired on purpose: model calls go direct and keep \
                     working, but nothing is captured. Fix reachability to the provider; the \
                     daemon re-wires itself as soon as the check passes."
                        .to_string(),
                ),
            ),
            ModelRelayState::PreflightPending => (
                format!("Model relay: up on port {port}, preflight still running"),
                Some("The agent is wired once it passes. Re-run this in a moment.".to_string()),
            ),
            ModelRelayState::UpUnwired => (
                format!("Model relay: up on port {port} but the agent is not wired to it"),
                Some("Run `openlatch restart` to re-wire.".to_string()),
            ),
            ModelRelayState::Down => (
                format!("Model relay: enabled in config, nothing listening on port {port}"),
                Some("Run `openlatch start`.".to_string()),
            ),
            ModelRelayState::ForeignIdle => (
                format!("Model relay: 127.0.0.1:{port} is held by another process"),
                Some(format!(
                    "The agent is not wired to it, but the next `openlatch start` will refuse to \
                     bind. Identify it with `lsof -i :{port}`."
                )),
            ),
        };
        if multi {
            eprintln!("  [{}]", row.display_name);
        }
        eprintln!("  {line}");
        if let Some(remedy) = remedy {
            eprintln!("  {remedy}");
        }
    }
    for check in &endpoint_checks {
        eprintln!("  {}", check.headline);
        if check.state != crate::cli::report::State::Ok {
            if let Some(remedy) = &check.remedy {
                eprintln!("    {remedy}");
            }
        }
    }

    if let Some(v) = probe.as_ref() {
        // The daemon reports an OBJECT now, one entry per wire format. A
        // `.as_str()` read here would silently print nothing — a diagnostic
        // going quiet is exactly the failure this line exists to prevent.
        if let Some(up) = v.get("upstream").and_then(|x| x.as_object()) {
            for (fmt, base) in up {
                if let Some(base) = base.as_str() {
                    eprintln!("  Upstream ({fmt}): {base}");
                }
            }
        }
        // Printed only when the pair is in force. A ChatGPT-plan Codex turn
        // goes here and to none of the bases above, so leaving it out would
        // make this diagnostic name every destination but the one in use.
        if let Some(base) = v.get("upstream_chatgpt").and_then(|x| x.as_str()) {
            eprintln!("  Upstream (openai-responses, ChatGPT plan): {base}");
        }
        if let Some(f) = v.get("pass_through_failures").and_then(|x| x.as_u64()) {
            eprintln!("  Pass-through failures: {f}");
        }
    }
    Ok(())
}

/// `openlatch system model-relay explain <finding_id>` — print a churning prefix block
/// LOCALLY (C-10b). The block content lives only in the on-disk retention store
/// on the originating host and is **never** emitted on the wire; this is the one
/// path that resolves a `finding_id` back to its content.
pub fn explain(finding_id: &str, output: &OutputConfig) -> Result<(), OlError> {
    let record = crate::model_relay::retention::load(finding_id).ok_or_else(|| {
        OlError::new(
            ERR_MODEL_RELAY_FINDING_NOT_FOUND,
            format!("no local churn finding '{finding_id}'"),
        )
        .with_suggestion(
            "Findings resolve only on the host that produced them, and expire from the bounded \
             local store. Check the id from the `ai.openlatch.prefix.finding_id` field.",
        )
    })?;

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "finding_id": record.finding_id,
            "captured_at": record.captured_at,
            "churn_layer": record.churn_layer,
            "churn_class": record.churn_class,
            "divergence_offset": record.divergence_offset,
            "churn_byte_len": record.churn_byte_len,
            "churn_block_index": record.churn_block_index,
            "block": record.block,
        }));
    } else {
        crate::cli::header::print(output, &["model-relay explain"]);
        eprintln!("  finding      : {}", record.finding_id);
        eprintln!("  captured     : {}", record.captured_at);
        eprintln!("  layer        : {}", record.churn_layer);
        eprintln!("  class        : {}", record.churn_class);
        eprintln!(
            "  offset/len   : {} / {} (block #{})",
            record.divergence_offset, record.churn_byte_len, record.churn_block_index
        );
        eprintln!("  block (local, never emitted):");
        println!("{}", record.block);
    }
    Ok(())
}

/// Blocking GET of the model relay's admin status endpoint. `None` when the
/// listener is not up.
pub fn probe_model_relay(port: u16) -> Option<serde_json::Value> {
    let resp = get_admin_status(port)?;
    if !resp.status().is_success() {
        return None;
    }
    resp.json().ok()
}

/// What the model relay is actually doing, as one classification.
///
/// `status` and `doctor` used to answer this question separately: `doctor`
/// combined config, agent wiring and a live probe, while `status` classified on
/// port ownership alone and never read `model_relay.enabled`. With the model relay
/// switched off in config and an unrelated process on 7600, `status` printed
///
/// ```text
/// Model relay:    FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed) (port 7600)
/// ```
///
/// seconds after the daemon logged `agent model relay wiring removed — agents
/// connect to the provider directly`. No agent was wired to that port: a
/// security-shaped alarm raised on a configuration that was deliberately, and
/// verifiably, safe. One classifier, consumed by both commands, is what makes
/// that disagreement impossible.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ModelRelayState {
    /// `[model_relay] enabled = false`. Agents talk to the provider directly by
    /// design; whoever holds the port is not our business.
    Disabled,
    /// A non-default model relay port: this instance deliberately does not touch
    /// the machine-global agent config, so wiring and listening are not
    /// supposed to line up.
    Isolated,
    /// Agent wired to our listener, and our listener answered. The good state.
    Wired,
    /// Agent wired, nothing listening — model calls fail with ECONNREFUSED.
    WiredButDown,
    /// Agent wired to a port held by someone else. The provider credential is
    /// going to that process. The real security alarm.
    WiredToForeign,
    /// Listener up, agent unwired because the preflight round trip failed. Not
    /// broken for the user (calls go direct) but nothing is captured.
    PreflightFailed(String),
    /// Listener up, preflight still running — the wiring lands when it passes.
    PreflightPending,
    /// Listener up, agent unwired for some other reason.
    UpUnwired,
    /// Not wired, nothing listening — consistent, and what `stop` leaves.
    Down,
    /// Not wired, and the port belongs to another process. Consistent for us,
    /// but it is why the next `start` will refuse to bind.
    ForeignIdle,
}

impl ModelRelayState {
    /// The one-word label the `status` dashboard prints.
    pub(crate) fn label(&self) -> &'static str {
        match self {
            ModelRelayState::Disabled => "disabled",
            ModelRelayState::Isolated => "isolated",
            ModelRelayState::Wired => "up",
            ModelRelayState::WiredButDown => "down",
            ModelRelayState::WiredToForeign => "failed",
            ModelRelayState::PreflightFailed(_) => "preflight-failed",
            ModelRelayState::PreflightPending => "preflight-pending",
            ModelRelayState::UpUnwired => "unwired",
            ModelRelayState::Down => "down",
            ModelRelayState::ForeignIdle => "down",
        }
    }
}

/// One agent's object in the `--json` status document.
///
/// A named function rather than an inline closure so the shape can be asserted
/// directly: `status()` itself needs a loaded config, a detected host and a
/// live probe, and a test that stood all three up would be testing the host it
/// happens to run on.
pub(crate) fn agent_row_json(row: &AgentRelay) -> serde_json::Value {
    serde_json::json!({
        "agent": row.agent,
        "state": row.state.label(),
        "classification": format!("{:?}", row.state),
        "wired_to": row.wired,
        // The NEW per-agent field. `wired_to` says a base URL is on disk; this
        // says which protocol that plane resolves to, and only the second
        // distinguishes a captured turn from one forwarded opaquely to another
        // vendor. A `"unknown"` here on a wired agent is a misroute, not a shrug.
        //
        // `up` is NOT here: it is a TOP-LEVEL sibling of `agents`, because it is
        // one fact about our own listener rather than one per agent.
        "wireformat": row.wire_format.map(|f| f.as_str()),
    })
}

/// One request plane's model relay picture: what the agent points at, and what
/// that means.
pub(crate) struct AgentRelay {
    /// The agent's wire type, `""` on the no-agent row below.
    pub agent: &'static str,
    /// The human label a multi-agent rendering prefixes its line with.
    pub display_name: &'static str,
    /// The endpoint it names, when that endpoint is ours.
    pub wired: Option<String>,
    /// What that adds up to.
    pub state: ModelRelayState,
    /// The protocol this agent's request plane speaks, from its own
    /// [`ModelRelayWiring`](crate::hooks::binding::ModelRelayWiring).
    ///
    /// **A field rather than something the renderer derives.** The map closure
    /// that builds the status JSON sees only this struct, and the binding —
    /// the only thing that knows the format — is out of scope by then. It is
    /// carried for the same reason `route_hint` is: computed while the binding
    /// is still in scope, because the row outlives it.
    ///
    /// This is what proves a resolved format rather than `Unknown`, which is
    /// the difference between a captured turn and one forwarded opaquely to
    /// the wrong vendor.
    ///
    /// `None` when no configuration we read declares one: a Cline row read from
    /// its editor's lane names a PROVIDER, and the relay resolves each of that
    /// editor's requests from its route. Mapping the provider id through the
    /// `providers.json` table would answer chat-completions for an editor that
    /// speaks Ollama's native API — a resolved-looking format that is false.
    pub wire_format: Option<crate::model_relay::wire_format::WireFormat>,
    /// How an operator points one session here by hand, in THIS agent's own
    /// vocabulary — computed while the binding is still in scope, because the
    /// row outlives it. See [`crate::hooks::isolated_wiring_hint`].
    pub route_hint: String,
}

/// Every request plane on this host, classified — in detection order.
///
/// One row per detected agent that HAS a request plane, because wiring is per
/// agent: one plane can be wired and green while another's round trip fails,
/// and a single row would report one of them for both.
///
/// **A host with no request plane still gets exactly one row.** The model relay's
/// own state — switched off in config, nothing listening, the port held by
/// somebody else — is worth reporting on a host with no agent installed at all,
/// and it is the state `model-relay status` is most often run against. Returning
/// an empty list there is how the one command named after the subsystem goes
/// silent about it.
pub(crate) fn model_relay_rows(cfg: &crate::config::Config) -> Vec<AgentRelay> {
    model_relay_rows_for(cfg, &crate::hooks::detect_agents())
}

/// [`model_relay_rows`] over agents the caller detected — the seam a test hands
/// a fixture host through.
pub(crate) fn model_relay_rows_for(
    cfg: &crate::config::Config,
    agents: &[crate::hooks::DetectedAgent],
) -> Vec<AgentRelay> {
    let port = cfg.model_relay.port;
    let mut rows: Vec<AgentRelay> = agents
        .iter()
        .filter_map(|a| {
            let wire_format = Some(a.binding.model_relay_wiring()?.wire_format);
            let wired = read_agent_wiring(&*a.binding);
            let state = classify_model_relay(cfg, a.agent_type(), wired.as_deref());
            Some(AgentRelay {
                agent: a.agent_type(),
                display_name: a.binding.display_name(),
                wired,
                state,
                wire_format,
                route_hint: crate::hooks::isolated_wiring_hint(&*a.binding, port),
            })
        })
        .collect();
    if rows.is_empty() {
        rows.push(AgentRelay {
            // Matches no key in the listener's per-agent maps by construction,
            // which is the honest answer: there is no agent to have a verdict.
            agent: "",
            display_name: "The agent",
            wired: None,
            state: classify_model_relay(cfg, "", None),
            // No agent, so no protocol — and this row is filtered out of the
            // per-agent JSON anyway.
            wire_format: None,
            // No agent, so no vocabulary to borrow. Naming one agent's variable
            // here would be the very guess this field exists to stop.
            route_hint: "the base URL your agent reads".to_string(),
        });
    }
    rows
}

/// How bad a state is, on the three-tier scale every diagnostic here uses:
/// 0 working, 1 switched off / not doing anything, 2 broken.
///
/// A host is only as healthy as its worst plane. Reporting the first agent's
/// state would let a broken Codex plane hide behind a green Claude one.
pub(crate) fn model_relay_severity(state: &ModelRelayState) -> u8 {
    match state {
        ModelRelayState::Wired | ModelRelayState::Isolated => 0,
        ModelRelayState::Disabled
        | ModelRelayState::PreflightPending
        | ModelRelayState::UpUnwired
        | ModelRelayState::Down => 1,
        ModelRelayState::WiredButDown
        | ModelRelayState::WiredToForeign
        | ModelRelayState::PreflightFailed(_)
        | ModelRelayState::ForeignIdle => 2,
    }
}

/// The worst row, which is the host's answer.
pub(crate) fn worst_row(rows: &[AgentRelay]) -> &AgentRelay {
    rows.iter()
        .max_by_key(|r| model_relay_severity(&r.state))
        .expect("model_relay_rows never returns an empty list")
}

/// Classify the model relay for ONE agent, from config, that agent's wiring, and a
/// live probe.
///
/// `wired` is the endpoint the agent names when — and only when — it points at
/// our loopback; a customer's corporate gateway is not our wiring. Read it with
/// [`read_agent_wiring`], never by reaching for one convention's key.
///
/// **`agent` is not decoration.** The listener reports `preflight` and
/// `preflight_error` as objects keyed by agent type, because two agents share
/// one listener and are probed in two different formats. Reading them without
/// the key returns `None` on every host, the match falls to
/// [`ModelRelayState::UpUnwired`], and every `PreflightFailed` / `PreflightPending`
/// host renders as merely unwired — with no compile error anywhere.
pub(crate) fn classify_model_relay(
    cfg: &crate::config::Config,
    agent: &'static str,
    wired: Option<&str>,
) -> ModelRelayState {
    if !cfg.model_relay.enabled {
        return ModelRelayState::Disabled;
    }
    if !cfg.model_relay.owns_agent_wiring() {
        return ModelRelayState::Isolated;
    }

    let port = cfg.model_relay.port;
    match (wired, verify_port_ownership(port)) {
        (Some(_), PortOwnership::Owned) => ModelRelayState::Wired,
        (Some(_), PortOwnership::Unreachable) => ModelRelayState::WiredButDown,
        (Some(_), PortOwnership::Foreign) => ModelRelayState::WiredToForeign,
        (None, PortOwnership::Owned) => {
            // "Up but unwired" stopped being a single condition once the wiring
            // was gated on a live round trip: the daemon leaves the agent
            // unwired ON PURPOSE when the model relay cannot forward, and telling
            // that operator to restart sends them in a circle. The listener
            // knows which case it is; ask it.
            let live = probe_model_relay(port);
            match live
                .as_ref()
                .and_then(|v| v.get("preflight"))
                .and_then(|v| v.get(agent))
                .and_then(|v| v.as_str())
            {
                Some("failed") => ModelRelayState::PreflightFailed(
                    live.as_ref()
                        .and_then(|v| v.get("preflight_error"))
                        .and_then(|v| v.get(agent))
                        .and_then(|v| v.as_str())
                        .unwrap_or("no round trip to the provider completed")
                        .to_string(),
                ),
                Some("pending") => ModelRelayState::PreflightPending,
                _ => ModelRelayState::UpUnwired,
            }
        }
        (None, PortOwnership::Unreachable) => ModelRelayState::Down,
        (None, PortOwnership::Foreign) => ModelRelayState::ForeignIdle,
    }
}

/// Is this agent wired to us, and to what?
///
/// **THE one convention reader.** Four callers ask this question — `doctor`'s
/// Model relay check, `model-relay enable/disable/status`, `openlatch stop`'s
/// teardown probe and the `status` dashboard — and all four call here. Four
/// hand-written copies is how they come to disagree, which is the failure the
/// *one question, one set of detectors* invariant exists to stop.
///
/// `None` for an agent with no request plane, and `None` for an agent whose
/// endpoint is the customer's own: only OUR loopback counts as our wiring, on
/// both conventions.
pub(crate) fn read_agent_wiring(
    binding: &dyn crate::hooks::binding::AgentBinding,
) -> Option<String> {
    use crate::hooks::binding::EndpointConvention;
    match binding.model_relay_wiring()?.endpoint {
        // The leaf reads the file, not the variable name.
        EndpointConvention::EnvVars { .. } => {
            read_model_relay_base_url(&binding.hook_config_path())
        }
        EndpointConvention::TomlProvider { provider_name, .. } => {
            crate::hooks::codex_cli::read_provider_base_url(
                &crate::hooks::codex_cli::config_toml_path(&binding.config_dir()),
                provider_name,
            )
        }
    }
}

/// One provider slot's relay endpoint, classified — the detector `doctor`,
/// `status` and `system model-relay status` all render.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct EndpointRow {
    /// The agent's wire type.
    pub agent: &'static str,
    /// The slot's record key.
    pub key: String,
    /// The provider(s) and setting, for a human: `gemini (geminiBaseUrl)`.
    pub label: String,
    /// The file the slot lives in, when there is one.
    pub file: Option<std::path::PathBuf>,
    /// The endpoint port, once the slot has one.
    pub port: Option<u16>,
    /// What that adds up to.
    pub state: EndpointState,
}

/// Where one provider slot's wiring stands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum EndpointState {
    /// Wired, served, and proven: the agent has dialled the endpoint.
    Active,
    /// Wired and served; the editor picks it up at its next start.
    NextStart,
    /// Configured and not wired yet; the daemon wires it on its next pass.
    Unwired,
    /// The file names the endpoint and nothing is listening there.
    Down,
    /// Something other than this slot's endpoint holds its port.
    Foreign,
    /// The daemon's own verdict: why it could not wire the slot.
    Verdict {
        /// The `OL-RELAY-*` code.
        code: &'static str,
        /// What happened.
        detail: String,
    },
    /// Not carried, for a named reason.
    Uncovered(crate::hooks::cline_providers::UncoveredReason),
    /// The agent's state file could not be read safely.
    StateFile(String),
}

/// Every provider slot of every agent that has them, classified.
///
/// Read-only: the records, the admin status JSON, each endpoint port's owner,
/// and the agent's own state files through its [`observe`] — never an excluded
/// file (PRD C-6). Empty when the relay is switched off (the main row says so)
/// or this instance does not own the agents' wiring.
///
/// `owner` answers who holds an endpoint port; a test passes a stub.
///
/// [`observe`]: crate::hooks::provider_endpoints::ProviderEndpoints::observe
pub(crate) fn endpoint_rows_for(
    cfg: &crate::config::Config,
    agents: &[crate::hooks::DetectedAgent],
    owner: &dyn Fn(u16, &str) -> PortOwnership,
) -> Vec<EndpointRow> {
    if !cfg.model_relay.enabled {
        return Vec::new();
    }
    let mut status: Option<Option<serde_json::Value>> = None;
    let mut rows = Vec::new();
    for agent in agents {
        let Some(endpoints) = agent.binding.provider_endpoints() else {
            continue;
        };
        if !crate::daemon::owns_wiring_for(cfg, &*agent.binding) {
            continue;
        }
        let status = status.get_or_insert_with(|| probe_model_relay(cfg.model_relay.port));
        rows.extend(rows_for_agent(cfg, endpoints, status.as_ref(), owner));
    }
    rows
}

fn rows_for_agent(
    cfg: &crate::config::Config,
    endpoints: &dyn crate::hooks::provider_endpoints::ProviderEndpoints,
    status: Option<&serde_json::Value>,
    owner: &dyn Fn(u16, &str) -> PortOwnership,
) -> Vec<EndpointRow> {
    use crate::hooks::cline_providers::{
        decide, DecideCtx, Decision, SlotId, SlotObservation, UncoveredReason,
    };
    use crate::model_relay::endpoints::RelayPorts;

    let agent = endpoints.agent_type();
    let row = |key: String, label: String, file, port, state| EndpointRow {
        agent,
        key,
        label,
        file,
        port,
        state,
    };
    let records: std::collections::BTreeMap<
        String,
        crate::hooks::model_relay_endpoints::EndpointRecord,
    > = match crate::hooks::model_relay_endpoints::endpoint_records(endpoints.record_prefix()) {
        Ok(records) => records.into_iter().collect(),
        Err(e) => {
            return vec![row(
                endpoints.record_prefix().to_string(),
                "provider endpoint records".into(),
                None,
                None,
                EndpointState::StateFile(e.message),
            )]
        }
    };
    let daemon_up = status.is_some();
    let verdict = |key: &str| {
        let v = status?.get("endpoint_verdicts")?.get(key)?;
        let code = v.get("code")?.as_str()?;
        let code = crate::error::ERR_MODEL_RELAY_CODES
            .iter()
            .copied()
            .find(|c| *c == code)?;
        Some(EndpointState::Verdict {
            code,
            detail: v
                .get("detail")
                .and_then(|d| d.as_str())
                .unwrap_or_default()
                .to_string(),
        })
    };
    let last_request = |key: &str| {
        status
            .and_then(|s| s.get("endpoints"))
            .and_then(|e| e.as_array())
            .and_then(|all| all.iter().find(|e| e["key"].as_str() == Some(key)))
            .and_then(|e| e["last_request_unix"].as_u64())
    };
    let label = |obs: &SlotObservation| {
        let setting = match &obs.slot {
            SlotId::GlobalState { key, .. } => key.clone(),
            SlotId::ProvidersJson { .. } => "providers.json".to_string(),
        };
        let ids = match (&obs.slot, obs.row) {
            (SlotId::ProvidersJson { id }, _) => id.clone(),
            (_, Some(row)) => row.ids.join(", "),
            (_, None) => obs.selected_ids.join(", "),
        };
        format!("{ids} ({setting})")
    };

    let recorded = records.keys().cloned().collect();
    let observation = endpoints.observe(&recorded);
    let ctx = DecideCtx {
        ports: RelayPorts {
            daemon: cfg.port,
            main: cfg.model_relay.port,
        },
        // Not a daemon: every teardown already happened "before", so a slot an
        // uninstall handed back stays quiet here rather than reading as unwired.
        started_at: u64::MAX,
    };

    let mut rows = Vec::new();
    for problem in &observation.problems {
        let (path, why) = match problem {
            crate::hooks::cline_providers::FileProblem::TooLarge { path, size } => (
                path.clone(),
                format!(
                    "{} is {size} bytes, over the limit OpenLatch reads",
                    crate::core::path_compat::display_path(path)
                ),
            ),
            crate::hooks::cline_providers::FileProblem::Unparseable { path } => (
                path.clone(),
                format!(
                    "{} is not readable as JSON",
                    crate::core::path_compat::display_path(path)
                ),
            ),
        };
        rows.push(row(
            format!("{}file", endpoints.record_prefix()),
            "provider settings".into(),
            Some(path),
            None,
            EndpointState::StateFile(why),
        ));
    }

    let mut covered: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for obs in &observation.slots {
        let key = obs.slot.record_key();
        covered.extend(obs.selected_ids.iter().cloned());
        if let SlotId::ProvidersJson { id } = &obs.slot {
            covered.insert(id.clone());
        }
        let rec = records.get(&key);
        let port = rec.map(|r| r.port);
        let state = if let Some(v) = verdict(&key) {
            Some(v)
        } else {
            match decide(obs, rec, &ctx) {
                Decision::Keep => {
                    use crate::hooks::model_relay_endpoints::Proof;
                    let rec = rec.filter(|r| r.is_live());
                    rec.map(|r| match owner(r.port, &key) {
                        PortOwnership::Owned
                            if r.served_since_written(last_request(&key))
                                || r.proven_by == Some(Proof::Traffic) =>
                        {
                            EndpointState::Active
                        }
                        // Holds our URL, uses the provider, sends nothing through it.
                        PortOwnership::Owned if r.misconfigured_event.is_some() => {
                            EndpointState::Verdict {
                                code: crate::error::ERR_MODEL_RELAY_MISCONFIGURED,
                                detail: "the editor uses this provider and no request reaches \
                                         its endpoint"
                                    .to_string(),
                            }
                        }
                        // Only a request proves a slot the editor may not route by.
                        PortOwnership::Owned => match obs.traffic_only() {
                            Some(reason) => EndpointState::Uncovered(reason),
                            None if r.proven_at.is_some() => EndpointState::Active,
                            None => EndpointState::NextStart,
                        },
                        PortOwnership::Unreachable => EndpointState::Down,
                        PortOwnership::Foreign => EndpointState::Foreign,
                    })
                }
                Decision::Wire { .. } | Decision::Reapply | Decision::NewPrior { .. } => {
                    Some(if daemon_up {
                        EndpointState::Unwired
                    } else if rec.is_some_and(|r| r.is_live()) {
                        EndpointState::Down
                    } else {
                        EndpointState::Unwired
                    })
                }
                Decision::Uncovered(reason) => Some(EndpointState::Uncovered(reason)),
                Decision::Release { .. } | Decision::Skip => None,
            }
        };
        if let Some(state) = state {
            rows.push(row(key, label(obs), Some(obs.file.clone()), port, state));
        }
    }

    // A provider selected with no slot to carry it: the legacy build's
    // hardcoded hosts, or a provider this build has never heard of.
    let mut reported = std::collections::BTreeSet::new();
    for selection in &observation.selections {
        if covered.contains(&selection.id) || !reported.insert(selection.id.clone()) {
            continue;
        }
        let reason = match crate::hooks::cline_providers::providers_json_row(&selection.id) {
            Some(row) => row.never.unwrap_or(UncoveredReason::NoSetting),
            None => UncoveredReason::DefaultUnknown,
        };
        rows.push(row(
            format!("{}selected:{}", endpoints.record_prefix(), selection.id),
            selection.id.clone(),
            None,
            None,
            EndpointState::Uncovered(reason),
        ));
    }
    rows
}

/// Every provider slot as `system model-relay status` reports it: the check
/// `doctor` renders for the slot, plus what its record and the running daemon
/// know. Returns the JSON entries and the checks, one of each per row.
///
/// The origin is the slot's forward target, already reduced to scheme, host and
/// port, with any credential in it masked.
pub(crate) fn endpoint_status(
    rows: &[EndpointRow],
    status: Option<&serde_json::Value>,
) -> (Vec<serde_json::Value>, Vec<crate::cli::report::Check>) {
    let mut report = crate::cli::report::Report::new();
    crate::cli::commands::doctor::check_provider_endpoints(rows, &mut report);
    let records: std::collections::BTreeMap<
        String,
        crate::hooks::model_relay_endpoints::EndpointRecord,
    > = crate::hooks::model_relay_endpoints::endpoint_records("")
        .map(|all| all.into_iter().collect())
        .unwrap_or_default();
    let live = |key: &str| {
        status
            .and_then(|s| s.get("endpoints"))
            .and_then(|e| e.as_array())
            .and_then(|all| all.iter().find(|e| e["key"].as_str() == Some(key)))
    };
    let entries = rows
        .iter()
        .zip(report.checks())
        .map(|(row, check)| {
            let rec = records.get(&row.key);
            let live = live(&row.key);
            serde_json::json!({
                "agent": row.agent,
                "key": row.key,
                "label": row.label,
                "port": row.port,
                "state": check.state.key(),
                "code": check.code,
                "headline": check.headline,
                "remedy": check.remedy,
                "origin": rec.map(|r| crate::core::egress::credentials::mask_userinfo(&r.origin)),
                "proven_at": rec.and_then(|r| r.proven_at),
                "proven_by": rec.and_then(|r| r.proven_by),
                "requests": live.and_then(|e| e["requests"].as_u64()),
                "contested": live
                    .and_then(|e| e["contested"].as_bool())
                    .unwrap_or(false),
            })
        })
        .collect();
    (entries, report.checks().to_vec())
}

/// The worst of the slot checks, on [`model_relay_severity`]'s scale.
pub(crate) fn endpoint_severity(checks: &[crate::cli::report::Check]) -> u8 {
    checks
        .iter()
        .map(|c| {
            if c.state.is_failure() {
                2
            } else if c.state.is_warning() {
                1
            } else {
                0
            }
        })
        .max()
        .unwrap_or(0)
}

/// Read `env.ANTHROPIC_BASE_URL` from the agent settings, but only when it is
/// OUR loopback URL — a customer's corporate gateway is not our wiring and must
/// not be reported as such.
pub(crate) fn read_model_relay_base_url(settings_path: &std::path::Path) -> Option<String> {
    let raw = std::fs::read_to_string(settings_path).ok()?;
    let parsed = crate::hooks::jsonc::parse_settings_value(&raw).ok()?;
    let url = parsed
        .get("env")?
        .get("ANTHROPIC_BASE_URL")?
        .as_str()?
        .to_string();
    reqwest::Url::parse(url.trim())
        .ok()
        .filter(|u| u.host_str() == Some("127.0.0.1"))
        .map(|_| url)
}

#[cfg(test)]
mod endpoint_row_tests {
    use super::{endpoint_rows_for, EndpointState, PortOwnership};
    use crate::hooks::cline_providers::{
        state_lanes_from, ClineProviderEndpoints, UncoveredReason,
    };
    use crate::hooks::model_relay_endpoints::{self, EndpointRecord, SlotState, SlotValue};
    use std::path::{Path, PathBuf};

    // Field order IS drop order (fields drop in declaration order, the
    // opposite of locals). `_env` must be declared — and so dropped — before
    // `_lock`: otherwise the lock releases first, and a racing `host()` on
    // another thread can acquire it, set its own `OPENLATCH_DIR`, and have
    // this guard's delayed restore stomp that value while the racer still
    // believes it holds the lock exclusively. See `ClineSeam` in
    // `src/hooks/cline.rs` and `HookEnvGuard` in
    // `src/cli/commands/doctor_fix.rs` for the same convention, correctly
    // ordered.
    struct Host {
        _env: crate::hooks::cline::EnvOverride,
        _lock: std::sync::MutexGuard<'static, ()>,
        _dir: tempfile::TempDir,
        root: PathBuf,
    }

    fn host() -> Host {
        let lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path().to_path_buf();
        let env = crate::hooks::cline::EnvOverride::apply([(
            "OPENLATCH_DIR",
            Some(root.join("openlatch").into_os_string()),
        )]);
        Host {
            _env: env,
            _lock: lock,
            _dir: dir,
            root,
        }
    }

    /// Pins the hazard the field-order comment above documents: with the lock
    /// declared (and so dropped) before the env restore, releasing one
    /// `Host` can stomp the `OPENLATCH_DIR` a racing `host()` just set while
    /// that racer still believes it holds the lock exclusively. Two threads
    /// hammer `host()` with no sleep so the drop of one lands inside the
    /// critical section of the other; on the buggy order this reliably
    /// desyncs within a few hundred iterations, which is what turned
    /// `model_relay_status_reports_each_slot_as_doctor_does` into an
    /// intermittent Windows failure (#377) — a slower `tempdir()`/mutex-wake
    /// path there widens the very same gap.
    #[test]
    fn host_never_lets_a_racing_host_see_its_openlatch_dir_stomped() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        let corrupted = Arc::new(AtomicBool::new(false));
        let stop = Arc::new(AtomicBool::new(false));

        let worker = |corrupted: Arc<AtomicBool>, stop: Arc<AtomicBool>| {
            std::thread::spawn(move || {
                for _ in 0..500 {
                    if stop.load(Ordering::Relaxed) {
                        return;
                    }
                    let h = host();
                    let expected = h.root.join("openlatch").into_os_string();
                    // Stay inside the critical section for a bit, giving a
                    // peer's delayed restore room to land — this stands in
                    // for the real gap between `put_endpoint` and the read in
                    // the flaky test.
                    for _ in 0..200 {
                        if std::env::var_os("OPENLATCH_DIR").as_deref() != Some(&expected) {
                            corrupted.store(true, Ordering::Relaxed);
                            stop.store(true, Ordering::Relaxed);
                            break;
                        }
                        std::thread::yield_now();
                    }
                    drop(h);
                }
            })
        };
        let a = worker(corrupted.clone(), stop.clone());
        let b = worker(corrupted.clone(), stop.clone());
        a.join().expect("thread a");
        b.join().expect("thread b");
        assert!(
            !corrupted.load(Ordering::Relaxed),
            "a racing host() observed its OPENLATCH_DIR stomped by another \
             guard's delayed restore — the lock released before the env was \
             put back"
        );
    }

    /// A config that owns wiring from a port nothing listens on, so the probe of
    /// the main listener answers "no daemon" instead of reaching a real one.
    fn config() -> crate::config::Config {
        let mut cfg = crate::config::Config::defaults();
        cfg.model_relay.port = crate::core::egress::test_support::dead_port();
        cfg.model_relay.own_agent_wiring = Some(true);
        cfg
    }

    fn agent(root: &Path, state: &str, providers: Option<&str>) -> crate::hooks::DetectedAgent {
        let gs = root.join("data").join("globalState.json");
        std::fs::create_dir_all(gs.parent().expect("parent")).expect("mkdir");
        std::fs::write(&gs, state).expect("write");
        let pj = providers.map(|body| {
            let path = root.join("data").join("settings").join("providers.json");
            std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
            std::fs::write(&path, body).expect("write");
            path
        });
        let endpoints: &'static ClineProviderEndpoints = Box::leak(Box::new(
            ClineProviderEndpoints::at(state_lanes_from(Some(gs.clone()), Some(gs)), pj),
        ));
        crate::hooks::DetectedAgent {
            kind: crate::hooks::AgentKind::Cline,
            binding: std::sync::Arc::new(crate::hooks::binding::test_support::FakeBinding {
                agent_type: "cline",
                provider_endpoints: Some(endpoints),
                ..Default::default()
            }),
        }
    }

    fn wired(root: &Path, port: u16, proven: bool) -> EndpointRecord {
        EndpointRecord {
            port,
            origin: "https://generativelanguage.googleapis.com/".into(),
            prior: SlotValue::Absent,
            last_written: Some(format!("http://127.0.0.1:{port}")),
            file: root.join("data").join("globalState.json"),
            state: SlotState::Wired,
            released_by: None,
            changed_at: 1,
            proven_at: proven.then_some(2),
            family: None,
            pending_event: None,
            proven_by: None,
            misconfigured_event: None,
        }
    }

    #[test]
    fn endpoint_rows_are_empty_without_records_or_configuration() {
        let host = host();
        let agents = [agent(&host.root, "{}", None)];
        let rows = endpoint_rows_for(&config(), &agents, &|_, _| PortOwnership::Owned);
        assert!(rows.is_empty(), "{rows:?}");
    }

    #[test]
    fn each_slot_is_classified_from_its_record_its_port_and_its_file() {
        let host = host();
        let cfg = config();
        let block = crate::model_relay::endpoints::endpoint_port_block(cfg.model_relay.port);
        let (p1, p2, p3, p4) = (
            *block.start(),
            block.start() + 1,
            block.start() + 2,
            block.start() + 3,
        );
        let state = format!(
            r#"{{"actModeApiProvider":"ollama","planModeApiProvider":"bedrock",
                "geminiBaseUrl":"http://127.0.0.1:{p1}",
                "anthropicBaseUrl":"http://127.0.0.1:{p2}",
                "openAiBaseUrl":"http://127.0.0.1:{p3}/v1",
                "liteLlmBaseUrl":"http://127.0.0.1:{p4}",
                "awsBedrockEndpoint":"https://vpce.example"}}"#
        );
        let agents = [agent(&host.root, &state, None)];
        for (key, port, proven) in [
            ("geminiBaseUrl", p1, false),
            ("anthropicBaseUrl", p2, true),
            ("openAiBaseUrl", p3, false),
            ("liteLlmBaseUrl", p4, false),
        ] {
            let mut rec = wired(&host.root, port, proven);
            if key == "openAiBaseUrl" {
                rec.last_written = Some(format!("http://127.0.0.1:{p3}/v1"));
            }
            model_relay_endpoints::put_endpoint(&format!("cline:gs:shared:{key}"), rec)
                .expect("put");
        }
        let owner = move |port: u16, _key: &str| match port {
            p if p == p3 => PortOwnership::Unreachable,
            p if p == p4 => PortOwnership::Foreign,
            _ => PortOwnership::Owned,
        };

        let rows = endpoint_rows_for(&cfg, &agents, &owner);
        let state_of = |needle: &str| {
            rows.iter()
                .find(|r| r.key.ends_with(needle))
                .map(|r| r.state.clone())
                .unwrap_or_else(|| panic!("no row for {needle}: {rows:#?}"))
        };
        assert_eq!(state_of("geminiBaseUrl"), EndpointState::NextStart);
        assert_eq!(state_of("anthropicBaseUrl"), EndpointState::Active);
        assert_eq!(state_of("openAiBaseUrl"), EndpointState::Down);
        assert_eq!(state_of("liteLlmBaseUrl"), EndpointState::Foreign);
        assert_eq!(state_of("ollamaBaseUrl"), EndpointState::Unwired);
        assert_eq!(
            state_of("awsBedrockEndpoint"),
            EndpointState::Uncovered(UncoveredReason::SignedHost)
        );
    }

    /// A provider the legacy build hardcodes and next has no entry for is named,
    /// not silently dropped.
    #[test]
    fn a_selected_provider_with_no_setting_is_uncovered() {
        let host = host();
        let agents = [agent(
            &host.root,
            r#"{"actModeApiProvider":"deepseek"}"#,
            Some(r#"{"providers":{}}"#),
        )];
        let rows = endpoint_rows_for(&config(), &agents, &|_, _| PortOwnership::Owned);
        assert_eq!(rows.len(), 1, "{rows:?}");
        assert_eq!(rows[0].key, "cline:selected:deepseek");
        assert_eq!(
            rows[0].state,
            EndpointState::Uncovered(UncoveredReason::NoSetting)
        );
    }

    /// A slot the editor may not route by — a `providers.json` entry only the
    /// next build reads, a key an organisation's remote configuration can
    /// override — is never green on an editor save, only on a request.
    #[test]
    fn a_slot_the_editor_may_not_route_by_is_off_until_a_request_proves_it() {
        use crate::hooks::model_relay_endpoints::Proof;
        let host = host();
        let cfg = config();
        let block = crate::model_relay::endpoints::endpoint_port_block(cfg.model_relay.port);
        let (p1, p2) = (*block.start(), block.start() + 1);
        let state = format!(
            r#"{{"actModeApiProvider":"anthropic","lastManagedOrganizationId":"org_1",
                "anthropicBaseUrl":"http://127.0.0.1:{p1}"}}"#
        );
        let providers = format!(
            r#"{{"providers":{{"deepseek":{{"settings":{{"provider":"deepseek",
                "baseUrl":"http://127.0.0.1:{p2}/v1"}}}}}}}}"#
        );
        let agents = [agent(&host.root, &state, Some(&providers))];
        let mut anthropic = wired(&host.root, p1, true);
        anthropic.proven_by = Some(Proof::EditorSave);
        model_relay_endpoints::put_endpoint("cline:gs:shared:anthropicBaseUrl", anthropic.clone())
            .expect("put");
        let mut deepseek = wired(&host.root, p2, true);
        deepseek.last_written = Some(format!("http://127.0.0.1:{p2}/v1"));
        deepseek.file = host
            .root
            .join("data")
            .join("settings")
            .join("providers.json");
        deepseek.proven_by = Some(Proof::EditorSave);
        model_relay_endpoints::put_endpoint("cline:pj:deepseek", deepseek.clone()).expect("put");

        let state_of = |needle: &str| {
            endpoint_rows_for(&cfg, &agents, &|_, _| PortOwnership::Owned)
                .into_iter()
                .find(|r| r.key.ends_with(needle))
                .map(|r| r.state)
                .unwrap_or_else(|| panic!("no row for {needle}"))
        };
        assert_eq!(
            state_of("anthropicBaseUrl"),
            EndpointState::Uncovered(UncoveredReason::ManagedOverride)
        );
        assert_eq!(
            state_of("pj:deepseek"),
            EndpointState::Uncovered(UncoveredReason::NextBundleOnly)
        );

        for (key, mut rec) in [
            ("cline:gs:shared:anthropicBaseUrl", anthropic),
            ("cline:pj:deepseek", deepseek),
        ] {
            rec.proven_by = Some(Proof::Traffic);
            model_relay_endpoints::put_endpoint(key, rec).expect("put");
        }
        assert_eq!(state_of("anthropicBaseUrl"), EndpointState::Active);
        assert_eq!(state_of("pj:deepseek"), EndpointState::Active);
    }

    /// An editor that loaded the relay URL, uses the provider, and sends nothing
    /// through it is a failure with its own code — never green.
    #[test]
    fn a_misconfigured_slot_is_reported_from_its_record() {
        use crate::hooks::model_relay_endpoints::Proof;
        let host = host();
        let cfg = config();
        let port =
            *crate::model_relay::endpoints::endpoint_port_block(cfg.model_relay.port).start();
        let state = format!(
            r#"{{"actModeApiProvider":"gemini","geminiBaseUrl":"http://127.0.0.1:{port}"}}"#
        );
        let agents = [agent(&host.root, &state, None)];
        let mut rec = wired(&host.root, port, true);
        rec.proven_by = Some(Proof::EditorSave);
        rec.misconfigured_event = Some("evt".into());
        model_relay_endpoints::put_endpoint("cline:gs:shared:geminiBaseUrl", rec).expect("put");
        let rows = endpoint_rows_for(&cfg, &agents, &|_, _| PortOwnership::Owned);
        assert!(
            matches!(
                &rows[..],
                [row] if matches!(row.state, EndpointState::Verdict { code, .. }
                    if code == crate::error::ERR_MODEL_RELAY_MISCONFIGURED)
            ),
            "{rows:#?}"
        );
    }

    /// `system model-relay status` reports each slot with the state, code and
    /// remedy doctor gives it, the record's masked origin and proof, and fails
    /// when a slot fails.
    #[test]
    fn model_relay_status_reports_each_slot_as_doctor_does() {
        use crate::cli::commands::model_relay::{endpoint_severity, endpoint_status, EndpointRow};
        use crate::hooks::model_relay_endpoints::Proof;
        let host = host();
        let mut rec = wired(&host.root, 7601, true);
        rec.origin = "https://user:secret@gw.corp.example/".into();
        rec.proven_by = Some(Proof::Traffic);
        model_relay_endpoints::put_endpoint("cline:gs:shared:geminiBaseUrl", rec).expect("put");
        let row = |key: &str, port, state| EndpointRow {
            agent: "cline",
            key: key.into(),
            label: format!("{key} (label)"),
            file: None,
            port,
            state,
        };
        let rows = vec![
            row(
                "cline:gs:shared:geminiBaseUrl",
                Some(7601),
                EndpointState::Active,
            ),
            row(
                "cline:gs:shared:ollamaBaseUrl",
                Some(7602),
                EndpointState::NextStart,
            ),
            row(
                "cline:gs:shared:openAiBaseUrl",
                Some(7603),
                EndpointState::Down,
            ),
        ];
        let status = serde_json::json!({
            "endpoints": [{"key": "cline:gs:shared:geminiBaseUrl", "requests": 3, "contested": true}]
        });
        let (entries, checks) = endpoint_status(&rows, Some(&status));

        let mut report = crate::cli::report::Report::new();
        crate::cli::commands::doctor::check_provider_endpoints(&rows, &mut report);
        for (entry, check) in entries.iter().zip(report.checks()) {
            assert_eq!(entry["state"], check.state.key());
            assert_eq!(entry["code"], serde_json::json!(check.code));
            assert_eq!(entry["remedy"], serde_json::json!(check.remedy));
        }
        assert_eq!(entries[0]["state"], "ok");
        assert_eq!(entries[1]["state"], "pending");
        assert_eq!(entries[1]["code"], crate::error::ERR_MODEL_RELAY_NEXT_START);
        let origin = entries[0]["origin"].as_str().expect("origin");
        assert!(!origin.contains("secret"), "{origin}");
        assert_eq!(entries[0]["proven_by"], "traffic");
        assert_eq!(entries[0]["requests"], 3);
        assert_eq!(entries[0]["contested"], true);
        assert_eq!(entries[1]["contested"], false);

        assert_eq!(endpoint_severity(&checks), 2, "a slot nothing serves fails");
        assert_eq!(endpoint_severity(&checks[..2]), 1, "a pending slot warns");
        assert_eq!(endpoint_severity(&checks[..1]), 0);
    }

    /// A request from before the slot was last written — a revert re-applied
    /// since — says nothing about the editor that saved the old value: it holds
    /// that value until it restarts.
    #[test]
    fn only_a_request_since_the_last_write_makes_a_slot_active() {
        let host = host();
        let cfg = config();
        let port =
            *crate::model_relay::endpoints::endpoint_port_block(cfg.model_relay.port).start();
        let state = format!(
            r#"{{"actModeApiProvider":"gemini","geminiBaseUrl":"http://127.0.0.1:{port}"}}"#
        );
        let gs = host.root.join("data").join("globalState.json");
        std::fs::create_dir_all(gs.parent().expect("parent")).expect("mkdir");
        std::fs::write(&gs, &state).expect("write");
        let endpoints =
            ClineProviderEndpoints::at(state_lanes_from(Some(gs.clone()), Some(gs)), None);
        let mut rec = wired(&host.root, port, false);
        rec.changed_at = 5_000;
        model_relay_endpoints::put_endpoint("cline:gs:shared:geminiBaseUrl", rec).expect("put");
        let state_with = |last_request: u64| {
            let status = serde_json::json!({"endpoints": [{
                "key": "cline:gs:shared:geminiBaseUrl",
                "requests": 7,
                "last_request_unix": last_request,
            }]});
            super::rows_for_agent(&cfg, &endpoints, Some(&status), &|_, _| {
                PortOwnership::Owned
            })
            .into_iter()
            .map(|r| r.state)
            .collect::<Vec<_>>()
        };
        assert_eq!(state_with(4_999), vec![EndpointState::NextStart]);
        assert_eq!(state_with(5_000), vec![EndpointState::Active]);
    }

    /// An isolated instance does not own the agents' wiring, so it reports none
    /// of their slots.
    #[test]
    fn an_isolated_instance_reports_no_slots() {
        let host = host();
        let mut cfg = config();
        cfg.model_relay.own_agent_wiring = Some(false);
        let agents = [agent(
            &host.root,
            r#"{"actModeApiProvider":"ollama"}"#,
            None,
        )];
        assert!(endpoint_rows_for(&cfg, &agents, &|_, _| PortOwnership::Owned).is_empty());
    }
}

#[cfg(test)]
mod tests {
    use super::{verify_port_ownership, PortOwnership};
    use crate::core::egress::test_support::dead_port;

    #[test]
    fn verify_port_ownership_refuses_closed_and_foreign_ports() {
        // Connection-refused branch: nothing is listening ⇒ Unreachable
        // (enable will tell the user to start the daemon first).
        //
        // This half is the platform regression gate, and it only ever fires
        // off-CI: Linux refuses a closed loopback port instantly, Windows can
        // take ~2s, so a budgeted probe there times out instead of seeing the
        // refusal — see the comment on the raw-TCP probe in
        // `verify_port_ownership`. Anything that reintroduces a
        // reason-sensitive classification (`is_connect()`, or splitting
        // timed-out back out of `Unreachable`) turns this red on Windows and
        // green on the runners.
        let closed = dead_port();
        assert_eq!(verify_port_ownership(closed), PortOwnership::Unreachable);

        // Wrong-signature branch: a NON-OpenLatch listener answers 200 with a
        // body lacking our `status`/`upstream` keys ⇒ Foreign (enable refuses,
        // so no provider credential is ever pointed at it).
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let foreign = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            use std::io::{Read, Write};
            for mut s in listener.incoming().flatten() {
                let mut buf = [0u8; 1024];
                let _ = s.read(&mut buf);
                let body = br#"{"foo":"bar"}"#;
                let head = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                     Content-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                let _ = s.write_all(head.as_bytes());
                let _ = s.write_all(body);
                let _ = s.flush();
            }
        });
        // Give the listener a moment to be ready before probing.
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert_eq!(verify_port_ownership(foreign), PortOwnership::Foreign);
    }

    /// Every endpoint listener IS the relay, so the signature alone would accept
    /// the main port or a sibling slot's port as this slot's — sending one
    /// provider's traffic to another provider's origin. Only the slot's own key
    /// proves it.
    #[tokio::test(flavor = "multi_thread")]
    async fn verify_endpoint_ownership_rejects_main_and_sibling_listeners() {
        use super::verify_endpoint_ownership;
        use crate::model_relay::endpoints::{
            normalize_origin, EndpointListeners, EndpointSpec, RelayPorts,
        };
        use crate::model_relay::{serve_ephemeral, ModelRelayState};
        use std::sync::Arc;

        let nowhere = reqwest::Url::parse("http://127.0.0.1:9").expect("url");
        let factory_base = nowhere.clone();
        let listeners = EndpointListeners::new(Arc::new(move |_| {
            ModelRelayState::new(factory_base.clone(), 0, 1, &[])
        }));
        let free = || {
            std::net::TcpListener::bind("127.0.0.1:0")
                .and_then(|l| l.local_addr())
                .expect("free port")
                .port()
        };
        // No endpoint block at the top of the range, so no test port is "ours".
        let ports = RelayPorts {
            daemon: 1,
            main: u16::MAX,
        };
        let mut slot_ports = Vec::new();
        for key in ["test:a", "test:b"] {
            let port = free();
            listeners
                .ensure(EndpointSpec {
                    key: key.to_string(),
                    agent: "cline",
                    family: None,
                    port,
                    origin: normalize_origin(&nowhere, &ports).expect("origin"),
                })
                .await
                .expect("endpoint binds");
            slot_ports.push(port);
        }
        let main = serve_ephemeral(Arc::new(ModelRelayState::new(nowhere, 0, 1, &[]))).await;
        let dead = dead_port();
        let (a, b) = (slot_ports[0], slot_ports[1]);

        tokio::task::spawn_blocking(move || {
            assert_eq!(verify_endpoint_ownership(a, "test:a"), PortOwnership::Owned);
            assert_eq!(
                verify_endpoint_ownership(b, "test:a"),
                PortOwnership::Foreign,
                "a sibling slot's listener is not this slot's"
            );
            assert_eq!(
                verify_endpoint_ownership(main, "test:a"),
                PortOwnership::Foreign,
                "the main listener is not this slot's"
            );
            assert_eq!(
                verify_endpoint_ownership(dead, "test:a"),
                PortOwnership::Unreachable
            );
            // The main port's own question is unchanged: any relay is ours.
            assert_eq!(verify_port_ownership(a), PortOwnership::Owned);
        })
        .await
        .expect("blocking checks");
        listeners.shutdown_all().await;
    }

    /// The #165 regression: with `[model_relay] enabled = false` and an unrelated
    /// process on the pinned port, `status` printed
    /// `FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed)`
    /// seconds after the daemon logged that it had removed the agent wiring. No
    /// agent was pointed at that port. The classifier must short-circuit on the
    /// config switch and never probe the port at all — so this test can assert
    /// it without any listener, on a port nothing is bound to.
    #[test]
    fn disabled_in_config_short_circuits_before_any_probe() {
        use crate::cli::commands::model_relay::{classify_model_relay, ModelRelayState};

        let mut cfg = crate::config::Config::defaults();
        cfg.model_relay.enabled = false;

        assert_eq!(
            classify_model_relay(&cfg, "claude-code", None),
            ModelRelayState::Disabled
        );
        // Even a wired-looking agent config cannot turn a disabled model relay
        // into an alarm: the daemon does not bind, so nothing of ours is there.
        assert_eq!(
            classify_model_relay(&cfg, "claude-code", Some("http://127.0.0.1:7600")),
            ModelRelayState::Disabled
        );
        assert_eq!(ModelRelayState::Disabled.label(), "disabled");
    }

    /// A non-default model relay port means the instance never touches the
    /// machine-global agent config, so wiring and listening are not supposed to
    /// line up — checked before the probe for the same reason.
    #[test]
    fn isolated_instance_short_circuits_before_any_probe() {
        use crate::cli::commands::model_relay::{classify_model_relay, ModelRelayState};

        let mut cfg = crate::config::Config::defaults();
        cfg.model_relay.enabled = true;
        cfg.model_relay.port = crate::model_relay::default_model_relay_port() + 1;

        assert_eq!(
            classify_model_relay(&cfg, "claude-code", None),
            ModelRelayState::Isolated
        );
    }

    /// **The new per-agent field.** `.agents[].wireformat` is present and names
    /// a resolved protocol, not `"unknown"`.
    ///
    /// This is what proves a plane resolves rather than being forwarded
    /// opaquely, and no shipped field carried it: `wired_to` says a base URL is
    /// on disk, which is true of a misrouted plane too.
    ///
    /// `up` is deliberately not asserted per agent — it is a top-level sibling
    /// of `agents`, one fact about our own listener.
    #[test]
    fn status_json_carries_per_agent_wireformat() {
        use super::{agent_row_json, AgentRelay, ModelRelayState};
        use crate::model_relay::wire_format::WireFormat;

        let row = AgentRelay {
            agent: "cline",
            display_name: "Cline",
            wired: Some("http://127.0.0.1:7600/v1".to_string()),
            state: ModelRelayState::Wired,
            wire_format: Some(WireFormat::OpenAiChatCompletions),
            route_hint: "providers.openai-compatible.settings.baseUrl".to_string(),
        };

        let json = agent_row_json(&row);

        assert_eq!(json["agent"], "cline");
        assert_eq!(
            json["wireformat"], "openai-chat-completions",
            "the field must carry the resolved format's wire name"
        );
        assert_ne!(
            json["wireformat"], "unknown",
            "`unknown` on a wired plane is a misroute, not a shrug"
        );
        assert!(
            json.get("up").is_none(),
            "`up` is a TOP-LEVEL sibling of `agents`, never a member"
        );
        assert_eq!(
            json["wired_to"], "http://127.0.0.1:7600/v1",
            "and the shipped fields are untouched"
        );

        // The Google half, so the field is not a constant wearing a lookup.
        let google = AgentRelay {
            wire_format: Some(WireFormat::GoogleGenerateContent),
            ..row
        };
        assert_eq!(
            agent_row_json(&google)["wireformat"],
            "google-generate-content"
        );

        // A plane read from Cline's editor lane declares no protocol: `null`,
        // never `"unknown"`, which would read as a misroute on a wired plane.
        let editor = AgentRelay {
            wire_format: None,
            ..google
        };
        assert!(agent_row_json(&editor)["wireformat"].is_null());
    }
}