openlatch-client 0.5.6

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
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
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
//! Codex CLI path detection.
//!
//! The sibling of [`crate::hooks::claude_code`], and deliberately the same
//! shape: this module owns `$CODEX_HOME` resolution for **every** caller —
//! the binding, the config-monitor manifest, and the model relay writer that
//! arrives with I-3. Nothing else resolves it.
//!
//! Codex registers hooks in a dedicated `hooks.json` rather than a section of
//! a larger settings file, and carries its own `config.toml` beside it; both
//! paths are derived here so no caller re-joins them.

use std::path::{Path, PathBuf};

use crate::error::{OlError, ERR_MODEL_RELAY_FOREIGN_PROVIDER};
use crate::hooks::binding::TrustOccasion;

/// Relocates Codex CLI's configuration directory.
///
/// The seam `olbox` exports so a sandboxed instance never reads the
/// developer's real `~/.codex`.
pub(crate) const CONFIG_DIR_ENV: &str = "CODEX_HOME";

/// Serializes the tests that mutate [`CONFIG_DIR_ENV`].
///
/// A **sibling** of [`crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK`], never a
/// reuse of it: the two guard different variables, and a lock that covers both
/// would serialise suites that have no reason to exclude one another. Taken
/// **last** wherever a test needs more than one env lock, so two tests cannot
/// deadlock by acquiring them in opposite orders.
///
/// A private lock is correct here only because `CODEX_HOME` is absent from
/// `daemon::identity::MANAGED` — unlike `CLAUDE_CONFIG_DIR`, which is in it and
/// therefore uses `identity::ENV_LOCK` and its `EnvGuard`.
///
/// `#[cfg(test)]` because an ungated `pub(crate)` static read only from tests
/// is dead code, and CI runs clippy with `-D warnings`.
#[cfg(test)]
pub(crate) static CONFIG_DIR_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// `$CODEX_HOME` when set to something non-empty.
///
/// An empty value reads as unset — the conventional reading, and the only safe
/// one here: an exported-but-blank variable would otherwise resolve every path
/// below it relative to the process cwd.
fn relocated_dir() -> Option<PathBuf> {
    std::env::var_os(CONFIG_DIR_ENV)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
}

/// Where Codex CLI's configuration directory *would* be, whether or not it
/// exists: `$CODEX_HOME` when set and non-empty, else `~/.codex`
/// (`%USERPROFILE%\.codex` on Windows).
///
/// Split out from [`detect`] for the same reason its Claude Code counterpart
/// is: `detect` answers "is Codex installed" and must stat the directory, while
/// the config-monitor manifest needs the path regardless of existence.
pub fn config_dir() -> Option<PathBuf> {
    match relocated_dir() {
        Some(relocated) => Some(relocated),
        None => Some(dirs::home_dir()?.join(".codex")),
    }
}

/// Detect whether Codex CLI is installed.
///
/// Returns `Some(codex_dir)` for [`config_dir`] if that directory exists.
///
/// **This is the single resolver.** Every caller routes through it rather than
/// calling `dirs::home_dir()` itself — the binding used to do exactly that for
/// Claude Code, and the duplication is why `$CLAUDE_CONFIG_DIR` was honoured on
/// one path and ignored on another (`bindings/claude_code.rs`). The distinction
/// is not academic on Windows, where `dirs::home_dir()` resolves
/// `FOLDERID_Profile` through `SHGetKnownFolderPath` and consults no
/// environment variable at all: a redirected `HOME` cannot reach it, so a
/// sandbox that only set `HOME` would silently write the developer's real
/// `~/.codex`. An env seam is the only redirection that works on all three
/// platforms.
pub fn detect() -> Option<PathBuf> {
    let codex_dir = config_dir()?;
    codex_dir.is_dir().then_some(codex_dir)
}

/// Is the Codex config this process would write the **machine-global** one?
///
/// `~/.codex` is shared by every Codex session on the host. A relocated
/// `$CODEX_HOME` is a different directory, used only by sessions launched with
/// the same variable — writing it takes nothing away from anybody.
///
/// Paths are canonicalized, so a `$CODEX_HOME` pointed deliberately at the real
/// `~/.codex` (through a symlink, or with a trailing slash) is still recognised
/// as machine-global. Anything we cannot resolve answers `true`: declining to
/// write is the safe direction.
///
/// Its one consumer is the daemon ownership guard that arrives with I-3, via
/// [`crate::hooks::bindings::codex_cli::CodexCliBinding::config_is_machine_global`].
/// Nothing in this unit calls it.
pub fn config_is_machine_global() -> bool {
    let Some(resolved) = config_dir() else {
        return true;
    };
    let Some(default) = dirs::home_dir().map(|home| home.join(".codex")) else {
        return true;
    };
    let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    canonical(&resolved) == canonical(&default)
}

/// Return the path to `hooks.json` inside the Codex config directory — the
/// file hook registrations are written into.
pub fn hooks_json_path(codex_dir: &Path) -> PathBuf {
    codex_dir.join("hooks.json")
}

/// Return the path to `config.toml` inside the Codex config directory.
///
/// Declared here so it has one owner. Its consumers arrive later: the `[hooks]`
/// trust and suppression state lives in this file rather than in `hooks.json`,
/// and I-3's model-relay writer targets it. Nothing in this unit calls it.
pub fn config_toml_path(codex_dir: &Path) -> PathBuf {
    codex_dir.join("config.toml")
}

// ---------------------------------------------------------------------------
// The system requirements layer
// ---------------------------------------------------------------------------

/// The system-wide requirements file — Codex's administrative config layer.
///
/// `Some("/etc/codex/requirements.toml")` on Unix. The literal is pinned
/// against Codex CLI **0.150.1**, the version the vendored hook-output schema
/// records, where it sits beside the `hooks.managed_dir` and
/// `hooks.windows_managed_dir` keys.
///
/// **`None` on Windows, deliberately.** The darwin binary carries no
/// `ProgramData` / `%PROGRAMDATA%` / `OpenAI\Codex` string, so the Windows
/// location is *unpinned* — and a doctor that reads the wrong file reports the
/// wrong answer confidently, which is worse than reporting that it could not
/// tell. On `None` the caller observes nothing for the managed-only dimension
/// and says so, rather than guessing a default.
///
/// `cfg!` rather than `#[cfg]` so both arms compile on every platform and the
/// Windows decision is type-checked by the Linux run, the same reason
/// [`crate::core::path_compat`] passes its platform decision in.
pub fn requirements_toml_path() -> Option<PathBuf> {
    if cfg!(windows) {
        None
    } else {
        Some(PathBuf::from("/etc/codex/requirements.toml")) // portability-ok: Codex 0.150.1's own Unix location, cfg-guarded above
    }
}

// ---------------------------------------------------------------------------
// The narrow slice of Codex config these checks read
// ---------------------------------------------------------------------------

/// The part of a Codex config-layer TOML the liveness checks read — and
/// nothing more.
///
/// Both `config.toml` and the system `requirements.toml` are layers of one
/// schema, so one struct reads both: `[hooks]` carries per-handler trust state
/// and the administrative managed-only switch, `[features]` carries the
/// wholesale hook kill switches. Every field is `Option`/`default`, so a
/// customer's own keys — and every key Codex adds later — pass straight
/// through. **This is not a model of Codex's configuration** and must not grow
/// into one.
///
/// **There is no `profile` field, and its absence is a decision.** Codex
/// 0.150.1 removed persisted profiles: `profile = "p"` in `config.toml` is
/// refused outright, a profile is chosen per invocation with `--profile <name>`
/// and lives in `$CODEX_HOME/<name>.config.toml`. So there is no "profile in
/// force" recorded anywhere to read, the root `[features]` table is the only
/// one this build can observe, and the check that reads it says so out loud
/// rather than pretending to have seen more.
#[derive(Debug, Default, serde::Deserialize)]
struct CodexConfig {
    #[serde(default)]
    hooks: HooksSection,
    #[serde(default)]
    features: FeaturesSection,
}

/// `[hooks]` — trust state, and the administrative switch that drops every
/// non-managed hook.
#[derive(Debug, Default, serde::Deserialize)]
struct HooksSection {
    /// Per-handler trust, keyed
    /// `"{source_path}:{event_name}:{group_index}:{handler_index}"` with the
    /// event in snake_case. See [`trust_key`].
    #[serde(default)]
    state: std::collections::BTreeMap<String, HookStateToml>,
    /// When set, Codex drops every non-managed hook with a bare `continue` and
    /// pushes **no warning**: our hook is present on disk, listed nowhere and
    /// never executed, with zero diagnostic output. Read from the requirements
    /// layer.
    #[serde(default)]
    allow_managed_hooks_only: Option<bool>,
}

/// One `[hooks.state]` entry.
///
/// Deliberately only the two fields we can act on. Codex's four internal
/// statuses (`Managed`, `Trusted`, `Modified`, `Untrusted`) are computed from a
/// digest whose function is **not** documented, so we never recompute one: the
/// hash we write is the one `hooks/list` publishes, and telling `Modified` from
/// `Trusted` is left to `hooks/list` too.
#[derive(Debug, Default, serde::Deserialize)]
struct HookStateToml {
    enabled: Option<bool>,
    trusted_hash: Option<String>,
}

/// The root `[features]` table, and only the three keys that can switch hooks
/// off wholesale.
#[derive(Debug, Default, serde::Deserialize)]
struct FeaturesSection {
    hooks: Option<bool>,
    codex_hooks: Option<bool>,
    plugin_hooks: Option<bool>,
}

/// What reading one config layer produced.
///
/// The three states are not interchangeable, and collapsing them is the bug
/// this enum exists to make unwritable: an **absent** file is the ordinary
/// state of a fresh install and means "nothing configured here", while an
/// **unreadable** one means "this build cannot tell" — which the caller must
/// render as unknown, never as a confident red.
enum ConfigLayer {
    /// No such file. Nothing is configured, and that is an answer.
    Absent,
    /// Parsed.
    Read(CodexConfig),
    /// Present, and unreadable or not valid TOML.
    Unreadable,
}

/// Read one Codex config layer. Never panics, never errors — the three
/// outcomes are the return value.
fn read_config_layer(path: &Path) -> ConfigLayer {
    let raw = match std::fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return ConfigLayer::Absent,
        Err(_) => return ConfigLayer::Unreadable,
    };
    match toml::from_str::<CodexConfig>(&raw) {
        Ok(config) => ConfigLayer::Read(config),
        Err(_) => ConfigLayer::Unreadable,
    }
}

// ---------------------------------------------------------------------------
// Locating our own handler inside hooks.json
// ---------------------------------------------------------------------------

/// OpenLatch's own hook handler inside a Codex `hooks.json` event, **and where
/// Codex indexes it**.
///
/// The indices are the point. Codex keys hook trust on the group and handler
/// position, our group is *appended* rather than prepended, and on any host
/// with a pre-existing customer hook ours is therefore not at zero — so a
/// reader that assumes `:0:0` reports the *customer's* trust state as ours.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstalledHandler {
    /// The command string exactly as written in `hooks.json`, quoting
    /// included. Run this, never a path recomputed from scratch: the point of
    /// invoking is to exercise what Codex would actually run.
    pub command: String,
    /// The row's own `timeout`, in seconds, as written.
    pub timeout_secs: Option<u64>,
    /// Index of our matcher group inside the event's array.
    pub group_index: usize,
    /// Index of our handler inside that group's `hooks` array.
    pub handler_index: usize,
}

/// Find OpenLatch's own handler for `event` (PascalCase, as `hooks.json` keys
/// it) and record the indices it was found at.
///
/// Ownership is the same predicate the writer uses
/// (`jsonc::is_openlatch_owned_node`): the `_openlatch` marker, or — for an
/// install that predates the marker — a command naming the `openlatch-hook`
/// binary. One predicate, so the writer and the reader cannot disagree about
/// which group is ours.
///
/// `None` when `hooks.json` is absent, unparsable, or carries no group of
/// ours for that event.
pub fn installed_handler(codex_dir: &Path, event: &str) -> Option<InstalledHandler> {
    own_handler_in(&read_hooks_json(codex_dir)?, event)
}

/// `hooks.json`, parsed. `None` when absent or unparsable.
fn read_hooks_json(codex_dir: &Path) -> Option<serde_json::Value> {
    let raw = std::fs::read_to_string(hooks_json_path(codex_dir)).ok()?;
    super::jsonc::parse_settings_value(&raw).ok()
}

/// [`installed_handler`] over an already-parsed `hooks.json`, so a caller
/// walking every event reads the file once.
fn own_handler_in(parsed: &serde_json::Value, event: &str) -> Option<InstalledHandler> {
    let groups = parsed
        .get("hooks")
        .and_then(|hooks| hooks.get(event))
        .and_then(serde_json::Value::as_array)?;

    for (group_index, group) in groups.iter().enumerate() {
        let marked = matches!(
            group.get("_openlatch"),
            Some(serde_json::Value::Bool(true)) | Some(serde_json::Value::Object(_))
        );
        let Some(handlers) = group.get("hooks").and_then(serde_json::Value::as_array) else {
            continue;
        };
        for (handler_index, handler) in handlers.iter().enumerate() {
            let Some(command) = handler.get("command").and_then(serde_json::Value::as_str) else {
                continue;
            };
            if !marked && !command.contains("openlatch-hook") {
                continue;
            }
            return Some(InstalledHandler {
                command: command.to_string(),
                timeout_secs: handler.get("timeout").and_then(serde_json::Value::as_u64),
                group_index,
                handler_index,
            });
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Trust state
// ---------------------------------------------------------------------------

/// The `[hooks].state` key Codex writes for `handler`:
/// `"{source_path}:{event_name}:{group_index}:{handler_index}"` — note the
/// event is **snake_case** in the key while the `hooks.json` property that
/// declares it is PascalCase.
///
/// Built from the indices [`installed_handler`] *found*, never from an assumed
/// `:0:0`.
pub fn trust_key(codex_dir: &Path, event: &str, handler: &InstalledHandler) -> String {
    format!(
        "{}:{}:{}:{}",
        hooks_json_path(codex_dir).display(),
        super::claude_code::pascal_to_snake(event),
        handler.group_index,
        handler.handler_index
    )
}

/// What Codex holds about one of our hook handlers.
///
/// Two readers answer it, and they can see different amounts. Codex's own
/// `hooks/list` ([`listed_trust`]) sees all of it, because Codex owns the
/// digest and compares it. The file fallback ([`hook_trust`]) cannot recompute
/// that digest, so from `config.toml` alone it never answers `Modified` or
/// `Managed`: a stored hash that no longer matches reads to it as `Trusted`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookTrust {
    /// Delivered through Codex's managed channel, which needs no trust.
    Managed,
    /// Our key carries a `trusted_hash` that matches the command. Codex will
    /// spawn the hook.
    Trusted,
    /// Trusted once, and the command changed since — Codex re-armed the review
    /// and will not spawn it. Only `hooks/list` can tell this apart.
    Modified,
    /// Our key is absent from `state`, or present with no `trusted_hash`.
    NeverTrusted,
    /// Our key carries `enabled = false`. Explicitly switched off.
    Disabled,
}

/// Read what `config.toml`'s `[hooks].state` records for `handler`.
///
/// `None` means the config layer could not be read at all — the caller must
/// render that as unknown, never as untrusted.
///
/// Trust lives on the **config layer**, not on the standalone `hooks.json` we
/// write: a `hooks.json` has nowhere to carry its own trust. The lookup is
/// therefore a scan of `state`, not a string index into it, because the
/// `source_path` Codex stored and the one we compute differ whenever
/// `$CODEX_HOME` reaches the same directory by another name — and a lookup
/// miss would render a confident "never trusted" on a perfectly trusted host.
pub fn hook_trust(codex_dir: &Path, event: &str, handler: &InstalledHandler) -> Option<HookTrust> {
    match read_config_layer(&config_toml_path(codex_dir)) {
        ConfigLayer::Unreadable => None,
        ConfigLayer::Absent => Some(HookTrust::NeverTrusted),
        ConfigLayer::Read(config) => Some(trust_in(&config, codex_dir, event, handler)),
    }
}

/// [`hook_trust`] over an already-parsed config layer.
fn trust_in(
    config: &CodexConfig,
    codex_dir: &Path,
    event: &str,
    handler: &InstalledHandler,
) -> HookTrust {
    let wire_event = super::claude_code::pascal_to_snake(event);
    let ours = hooks_json_path(codex_dir);
    let found = config.hooks.state.iter().find(|(key, _)| {
        let Some(parsed) = split_state_key(key) else {
            return false;
        };
        parsed.event == wire_event
            && parsed.group_index == handler.group_index
            && parsed.handler_index == handler.handler_index
            && is_same_file(Path::new(parsed.source_path), &ours)
    });

    match found {
        None => HookTrust::NeverTrusted,
        Some((_, state)) if state.enabled == Some(false) => HookTrust::Disabled,
        Some((_, state)) if state.trusted_hash.is_some() => HookTrust::Trusted,
        Some(_) => HookTrust::NeverTrusted,
    }
}

/// The four fields of a parsed `[hooks].state` key.
struct StateKey<'a> {
    source_path: &'a str,
    event: &'a str,
    group_index: usize,
    handler_index: usize,
}

/// Parse a `[hooks].state` key **from the right**.
///
/// A left split is wrong: a Windows drive letter carries a `:` of its own, so
/// `"C:\Users\u\.codex\hooks.json:pre_tool_use:0:0"` splits into five pieces
/// from the left and the source path loses its drive. From the right the three
/// trailing fields are fixed and everything before them is the path, whatever
/// it contains.
fn split_state_key(key: &str) -> Option<StateKey<'_>> {
    let mut parts = key.rsplitn(4, ':');
    let handler_index = parts.next()?.parse().ok()?;
    let group_index = parts.next()?.parse().ok()?;
    let event = parts.next()?;
    let source_path = parts.next()?;
    Some(StateKey {
        source_path,
        event,
        group_index,
        handler_index,
    })
}

/// Does this `[hooks.state]` key belong to the `hooks.json` at `hooks_json`?
///
/// The same canonicalized compare the trust lookup makes, so a key Codex
/// spelled through `/private/tmp` still matches a `$CODEX_HOME` under `/tmp`.
pub(crate) fn key_names_file(key: &str, hooks_json: &Path) -> bool {
    split_state_key(key).is_some_and(|k| is_same_file(Path::new(k.source_path), hooks_json))
}

/// "Are these two paths the same file?", for the trust-key compare.
///
/// Canonicalized on both sides so a symlinked `$CODEX_HOME` — or a trailing
/// slash — still matches the literal string Codex stored, and reduced through
/// [`dedup_key`] so Windows' case-insensitive-but-case-preserving filesystem
/// does not turn one file into two keys. A path that cannot be canonicalized
/// (the file has since gone) falls back to itself, which degrades to the plain
/// string compare rather than to a false match.
///
/// [`dedup_key`]: crate::core::path_compat::dedup_key
fn is_same_file(a: &Path, b: &Path) -> bool {
    let resolved = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    crate::core::path_compat::dedup_key(&resolved(a))
        == crate::core::path_compat::dedup_key(&resolved(b))
}

// ---------------------------------------------------------------------------
// Codex's own answer: `hooks/list`
// ---------------------------------------------------------------------------

/// Codex's verdict on one hook, as `hooks/list` reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TrustStatus {
    Managed,
    Trusted,
    Modified,
    Untrusted,
    /// A status this build does not know. Read as "no answer", so the caller
    /// falls back to the file rather than guessing.
    #[serde(other)]
    Unrecognised,
}

/// One hook, as Codex's app-server lists it.
///
/// Only the fields we act on. The response is app-server RPC, not a published
/// contract, so everything else is ignored and a hook that fails to parse is
/// skipped rather than failing the whole listing.
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListedHook {
    /// The `[hooks.state]` key Codex reads trust from — positional, and
    /// therefore read back from here rather than rebuilt from indices.
    pub key: String,
    #[serde(default)]
    pub command: Option<String>,
    pub source_path: PathBuf,
    #[serde(default = "enabled_by_default")]
    pub enabled: bool,
    #[serde(default)]
    pub is_managed: bool,
    /// The digest Codex expects in `trusted_hash`.
    pub current_hash: String,
    pub trust_status: TrustStatus,
}

fn enabled_by_default() -> bool {
    true
}

impl ListedHook {
    /// Is this one of ours, in the `hooks.json` under `codex_dir`?
    ///
    /// `hooks/list` carries no `_openlatch` marker, so the command is the only
    /// ownership signal it offers — the same fallback half of the predicate
    /// [`installed_handler`] uses. The source file is checked too: a project
    /// `hooks.json` that happens to run our binary is not ours to trust.
    fn is_ours(&self, codex_dir: &Path) -> bool {
        self.command
            .as_deref()
            .is_some_and(|c| c.contains("openlatch-hook"))
            && is_same_file(&self.source_path, &hooks_json_path(codex_dir))
    }

    /// Codex's answer as a [`HookTrust`]. `None` for a status this build does
    /// not recognise.
    fn trust(&self) -> Option<HookTrust> {
        if !self.enabled {
            return Some(HookTrust::Disabled);
        }
        match self.trust_status {
            _ if self.is_managed => Some(HookTrust::Managed),
            TrustStatus::Managed => Some(HookTrust::Managed),
            TrustStatus::Trusted => Some(HookTrust::Trusted),
            TrustStatus::Modified => Some(HookTrust::Modified),
            TrustStatus::Untrusted => Some(HookTrust::NeverTrusted),
            TrustStatus::Unrecognised => None,
        }
    }
}

/// How the binding obtains Codex's hook listing.
///
/// A seam rather than a call, for the reason `requirements_toml` is a field:
/// CI has no `codex` binary, so a test injects the listing instead of spawning
/// one. `None` from the lister means Codex could not be asked.
pub type HookLister = std::sync::Arc<dyn Fn(&Path) -> Option<Vec<ListedHook>> + Send + Sync>;

/// The production lister: ask a real `codex app-server`.
pub fn app_server_lister() -> HookLister {
    std::sync::Arc::new(list_hooks)
}

/// How long Codex gets to answer. It answers in well under a second; this
/// bound exists so a hung app-server degrades `doctor` to the file fallback
/// rather than hanging it.
const APP_SERVER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// The id of our `hooks/list` request, matched on the response.
const LIST_REQUEST_ID: u64 = 2;

/// Ask Codex, over its app-server's JSON-RPC stdio, which hooks it sees and
/// what it thinks of each: `initialize` → `initialized` → `hooks/list`.
///
/// `None` when Codex cannot be started, does not answer in time, or answers
/// with an error. Never panics, never blocks past [`APP_SERVER_TIMEOUT`].
///
/// **Through a login shell on Unix**, the way Codex runs hook commands: a
/// supervised daemon starts with a minimal `PATH`, and `codex` usually lives
/// somewhere only the developer's profile adds. `CODEX_HOME` is set inside
/// the command, after the profile has run, so a profile exporting its own
/// value cannot point the listing at another directory. The working
/// directory is the Codex directory itself, so no project's `.codex/` is
/// folded into the listing.
pub fn list_hooks(codex_dir: &Path) -> Option<Vec<ListedHook>> {
    use std::io::{BufRead as _, Write as _};

    let mut command = if cfg!(windows) {
        // No login shell to borrow a PATH from; a `codex` that is not on this
        // process's PATH answers `None`, and the file fallback reports.
        let mut c = std::process::Command::new("codex");
        c.arg("app-server").env(CONFIG_DIR_ENV, codex_dir);
        c
    } else {
        let mut c = std::process::Command::new("sh");
        c.args(["-lc", "CODEX_HOME=\"$1\" exec codex app-server", "sh"])
            .arg(codex_dir);
        c
    };
    let mut child = command
        .current_dir(codex_dir)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .ok()?;

    // Read on a thread so the deadline below bounds a server that never
    // answers. Not joined: a killed server closes the pipe and ends it.
    let stdout = child.stdout.take()?;
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        for line in std::io::BufReader::new(stdout).lines() {
            let Ok(line) = line else { break };
            let Ok(message) = serde_json::from_str::<serde_json::Value>(&line) else {
                continue;
            };
            if message.get("id").and_then(serde_json::Value::as_u64) == Some(LIST_REQUEST_ID) {
                let _ = tx.send(message);
                break;
            }
        }
    });

    // Held open until the answer arrives: the server stops on end of input.
    let mut stdin = child.stdin.take()?;
    let requests = [
        serde_json::json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {"clientInfo": {"name": "openlatch", "version": env!("CARGO_PKG_VERSION")}}}),
        serde_json::json!({"jsonrpc": "2.0", "method": "initialized"}),
        serde_json::json!({"jsonrpc": "2.0", "id": LIST_REQUEST_ID, "method": "hooks/list",
            "params": {}}),
    ];
    let wrote = requests
        .iter()
        .try_for_each(|r| writeln!(stdin, "{r}"))
        .and_then(|()| stdin.flush());

    let response = wrote
        .ok()
        .and_then(|()| rx.recv_timeout(APP_SERVER_TIMEOUT).ok());
    drop(stdin);
    let _ = child.kill();
    let _ = child.wait();
    parse_hooks_list(&response?)
}

/// The hooks in a `hooks/list` response, across every directory it reports.
///
/// `None` for an error response or one without the expected shape. A config
/// Codex could not load answers `hooks: []` with an `errors` entry — which is
/// why an empty listing is never read as "untrusted" by anyone: callers look
/// for **our** hook in it and fall back when it is absent.
pub fn parse_hooks_list(response: &serde_json::Value) -> Option<Vec<ListedHook>> {
    let data = response.get("result")?.get("data")?.as_array()?;
    Some(
        data.iter()
            .filter_map(|dir| dir.get("hooks")?.as_array())
            .flatten()
            .filter_map(|hook| serde_json::from_value(hook.clone()).ok())
            .collect(),
    )
}

/// Codex's answer for our handler of `event`, found at `handler`'s position.
///
/// `None` when the listing does not include it — Codex could not load its
/// config, or an administrative policy dropped it — or reports a status this
/// build does not know. The caller falls back to the file read.
pub fn listed_trust<'a>(
    listing: &'a [ListedHook],
    codex_dir: &Path,
    event: &str,
    handler: &InstalledHandler,
) -> Option<(HookTrust, &'a ListedHook)> {
    let wire_event = super::claude_code::pascal_to_snake(event);
    let hook = listing.iter().find(|hook| {
        hook.is_ours(codex_dir)
            && split_state_key(&hook.key).is_some_and(|k| {
                k.event == wire_event
                    && k.group_index == handler.group_index
                    && k.handler_index == handler.handler_index
            })
    })?;
    Some((hook.trust()?, hook))
}

// ---------------------------------------------------------------------------
// Granting trust to our own hooks
// ---------------------------------------------------------------------------

/// Does any of our handlers, on disk, sit at a position with no trust
/// recorded for it?
///
/// The cheap gate in front of [`grant_own_hook_trust`] on the drift path. It
/// reads two files and spawns nothing, so the daemon can ask it on every
/// `hooks.json` change and only start Codex when it answers `true`. A handler
/// switched off with `enabled = false` does not count: that is the developer's
/// choice, not drift.
///
/// It cannot see `Modified` — a stored hash that no longer matches — but only
/// a changed command produces that, and a changed command is an install, which
/// grants on its own. An unreadable `config.toml` answers `false`: Codex cannot
/// load it either, so there is nothing a grant could fix.
pub fn own_hooks_need_trust(codex_dir: &Path) -> bool {
    let Some(parsed) = read_hooks_json(codex_dir) else {
        return false;
    };
    let config = match read_config_layer(&config_toml_path(codex_dir)) {
        ConfigLayer::Read(config) => config,
        ConfigLayer::Absent => CodexConfig::default(),
        ConfigLayer::Unreadable => return false,
    };
    let Some(events) = parsed.get("hooks").and_then(serde_json::Value::as_object) else {
        return false;
    };
    events.keys().any(|event| {
        own_handler_in(&parsed, event).is_some_and(|handler| {
            trust_in(&config, codex_dir, event, &handler) == HookTrust::NeverTrusted
        })
    })
}

/// One trust entry OpenLatch wrote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
    /// The `[hooks.state]` key.
    pub key: String,
    /// The `trusted_hash` written under it.
    pub trusted_hash: String,
}

/// Write Codex's `[hooks.state]` trust for every handler of ours that Codex
/// will not run, using the key and hash **Codex** published in `listing`.
///
/// Nothing is recomputed: the key is positional and the digest undocumented,
/// and reading both back from `hooks/list` is what keeps this correct when
/// either changes. Only our keys are touched, and only when something needs
/// doing, so a host that is already trusted is not rewritten.
///
/// Returns what was written, for the provenance record.
pub fn grant_own_hook_trust(
    codex_dir: &Path,
    listing: &[ListedHook],
    occasion: TrustOccasion,
) -> Result<Vec<Grant>, OlError> {
    let wanted: Vec<&ListedHook> = listing
        .iter()
        // A managed hook needs no trust, and its entry is not ours to write.
        .filter(|hook| hook.is_ours(codex_dir) && !hook.is_managed)
        .filter(|hook| {
            let untrusted = matches!(
                hook.trust_status,
                TrustStatus::Untrusted | TrustStatus::Modified
            );
            untrusted || (occasion == TrustOccasion::Install && !hook.enabled)
        })
        .collect();
    if wanted.is_empty() {
        return Ok(Vec::new());
    }

    let config_toml = config_toml_path(codex_dir);
    crate::hooks::atomic::atomic_rewrite_toml(&config_toml, |doc| {
        let state = implicit_table(doc.as_table_mut(), "hooks", &config_toml)
            .and_then(|hooks| implicit_table(hooks, "state", &config_toml))?;
        for hook in &wanted {
            let entry = state
                .entry(&hook.key)
                .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()));
            let Some(entry) = entry.as_table_mut() else {
                return Err(not_a_table(&config_toml, &hook.key));
            };
            entry.insert("trusted_hash", toml_edit::value(&hook.current_hash));
            if occasion == TrustOccasion::Install {
                entry.insert("enabled", toml_edit::value(true));
            }
        }
        Ok(())
    })?;

    Ok(wanted
        .into_iter()
        .map(|hook| Grant {
            key: hook.key.clone(),
            trusted_hash: hook.current_hash.clone(),
        })
        .collect())
}

/// Remove the trust entries OpenLatch granted, reversing
/// [`grant_own_hook_trust`] at uninstall.
///
/// Each entry goes only while its `trusted_hash` is still the one we wrote. A
/// hash that changed was re-granted by someone else — Codex's `/hooks`, most
/// likely — and is theirs now. Emptied `[hooks.state]` / `[hooks]` tables are
/// pruned so no bare header survives; the file itself is never deleted.
pub fn revoke_granted_trust(codex_dir: &Path, grants: &[Grant]) -> Result<(), OlError> {
    let config_toml = config_toml_path(codex_dir);
    if grants.is_empty() || !config_toml.exists() {
        return Ok(());
    }
    crate::hooks::atomic::atomic_rewrite_toml(&config_toml, |doc| {
        let Some(hooks) = doc.get_mut("hooks").and_then(toml_edit::Item::as_table_mut) else {
            return Ok(());
        };
        if let Some(state) = hooks
            .get_mut("state")
            .and_then(toml_edit::Item::as_table_mut)
        {
            for grant in grants {
                let still_ours = state
                    .get(&grant.key)
                    .and_then(|entry| entry.get("trusted_hash"))
                    .and_then(toml_edit::Item::as_str)
                    == Some(grant.trusted_hash.as_str());
                if still_ours {
                    state.remove(&grant.key);
                }
            }
            if state.is_empty() {
                hooks.remove("state");
            }
        }
        if hooks.is_empty() {
            doc.remove("hooks");
        }
        Ok(())
    })
}

/// `parent.<name>` as a table, created **implicit** when absent so no bare
/// `[hooks]` or `[hooks.state]` header is written into a file the customer
/// reads — the same care the provider table's parent takes.
fn implicit_table<'a>(
    parent: &'a mut toml_edit::Table,
    name: &str,
    config_toml: &Path,
) -> Result<&'a mut toml_edit::Table, OlError> {
    parent
        .entry(name)
        .or_insert_with(|| {
            let mut table = toml_edit::Table::new();
            table.set_implicit(true);
            toml_edit::Item::Table(table)
        })
        .as_table_mut()
        .ok_or_else(|| not_a_table(config_toml, name))
}

/// The refusal for a key we need as a table that the file declares as
/// something else. We do not rewrite a value we did not write.
fn not_a_table(config_toml: &Path, key: &str) -> OlError {
    OlError::new(
        crate::error::ERR_HOOK_MALFORMED_TOML,
        format!(
            "'{}' declares `{key}` as something other than a table",
            crate::core::path_compat::display_path(config_toml)
        ),
    )
    .with_suggestion(
        "Fix or remove that key, then run `openlatch doctor --fix` — OpenLatch will not \
         rewrite a value it did not write.",
    )
}

// ---------------------------------------------------------------------------
// Administrative suppression
// ---------------------------------------------------------------------------

/// The `features.*` key observed **present and `false`** in the root
/// `[features]` table of `config.toml`, if any.
///
/// `codex_hooks` is a legacy **alias** for the canonical hooks feature
/// (0.150.1 `features/src/legacy.rs` maps alias → canonical), so either one
/// present-and-`false` suppresses hooks identically.
///
/// **An absent key is not a suppression, and this is load-bearing.** These keys
/// are absent on every default host and their defaults are undocumented, so a
/// reader that treated absent as unproven would make a healthy host render
/// degraded forever. Only an *observed* `false` is reported; the uncertainty
/// belongs in the check's detail text, not in its state.
///
/// The scan is root-only. A `codex --profile <name>` invocation may override
/// `features.*` from `<name>.config.toml`, which is not observable from
/// `config.toml` — the caller says so rather than scanning `*.config.toml`.
pub fn suppressing_feature_flag(codex_dir: &Path) -> Option<&'static str> {
    let ConfigLayer::Read(config) = read_config_layer(&config_toml_path(codex_dir)) else {
        return None;
    };
    [
        ("hooks", config.features.hooks),
        ("codex_hooks", config.features.codex_hooks),
        ("plugin_hooks", config.features.plugin_hooks),
    ]
    .into_iter()
    .find_map(|(name, value)| (value == Some(false)).then_some(name))
}

/// What the requirements layer says about `hooks.allow_managed_hooks_only`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ManagedHooksOnly {
    /// The layer was consulted, and the switch is on or off.
    Observed(bool),
    /// The layer could not be consulted at all — no pinned path on this
    /// platform, or a file present and unreadable. The caller observes nothing
    /// for this dimension and says so.
    Unobservable,
}

/// Read `hooks.allow_managed_hooks_only` from the requirements layer.
///
/// The path is a parameter rather than a call to [`requirements_toml_path`] so
/// the read is exercisable without a host `/etc`; pass
/// `requirements_toml_path().as_deref()`. `None` — the platform has no pinned
/// path — is [`ManagedHooksOnly::Unobservable`], never a green default.
///
/// An **absent** file is `Observed(false)`: no requirements layer exists on
/// this host, so nothing is restricting hooks. An unparsable one is
/// `Unobservable`, because an administrative policy we could not read is
/// exactly the thing not to report as green.
pub fn managed_hooks_only(requirements_toml: Option<&Path>) -> ManagedHooksOnly {
    let Some(path) = requirements_toml else {
        return ManagedHooksOnly::Unobservable;
    };
    match read_config_layer(path) {
        ConfigLayer::Absent => ManagedHooksOnly::Observed(false),
        ConfigLayer::Read(config) => {
            ManagedHooksOnly::Observed(config.hooks.allow_managed_hooks_only.unwrap_or(false))
        }
        ConfigLayer::Unreadable => ManagedHooksOnly::Unobservable,
    }
}

// ---------------------------------------------------------------------------
// The model-relay provider table (I-3 §1)
// ---------------------------------------------------------------------------

// The table this writer maintains, rendered from the binding's values:
//
//     model_provider = "openlatch"
//
//     [model_providers.openlatch]
//     name                 = "OpenLatch model relay"
//     base_url             = "http://127.0.0.1:{port}/v1"
//     wire_api             = "responses"
//     requires_openai_auth = true
//
//     [model_providers.openlatch.http_headers]
//     x-openlatch-install-id = "<install_id>"
//
// Validated `exit 0` against Codex CLI 0.150.1's own config validator
// (`codex debug models -c …`). Three facts that check established, and that the
// code below depends on:
//
// - `name` is MANDATORY. A provider without it fails with `provider name must
//   not be empty`, and Codex then rejects the ENTIRE config — the same blast
//   radius as a malformed hooks file one directory over. It is not a cosmetic
//   label; do not tidy it away.
// - `openlatch` is a legal provider ID. `model_providers.openai` is refused as
//   a reserved built-in; the negative is what proves the check is live rather
//   than vacuous.
// - `base_url` carries `/v1`, unlike Claude Code's `ANTHROPIC_BASE_URL` which
//   has none: Codex appends its own path to the provider base.

/// The provider table's mandatory human label.
const PROVIDER_LABEL: &str = "OpenLatch model relay";

/// The key naming which provider Codex uses for the current session.
const MODEL_PROVIDER_KEY: &str = "model_provider";

/// The parent table every provider lives under.
const MODEL_PROVIDERS_TABLE: &str = "model_providers";

/// `base_url` of `[model_providers.<provider_name>]`, if that table exists and
/// declares one.
fn provider_base_url<'a>(doc: &'a toml_edit::DocumentMut, provider_name: &str) -> Option<&'a str> {
    doc.get(MODEL_PROVIDERS_TABLE)
        .and_then(toml_edit::Item::as_table_like)
        .and_then(|providers| providers.get(provider_name))
        .and_then(toml_edit::Item::as_table_like)
        .and_then(|provider| provider.get("base_url"))
        .and_then(toml_edit::Item::as_str)
}

/// Is the `[model_providers.<provider_name>]` table in `doc` **ours**?
///
/// - `None` — no such table. Install writes ours; uninstall has nothing to do.
/// - `Some(true)` — ours. Install replaces it in place; uninstall reverses it.
/// - `Some(false)` — **somebody else's.** Install refuses with
///   [`ERR_MODEL_RELAY_FOREIGN_PROVIDER`] rather than overwriting, because
///   uninstall could not then round-trip the file: the reversal would delete a
///   table that was never ours.
///
/// The predicate is [`crate::hooks::is_openlatch_loopback_base_url`] — the same
/// one the Claude Code path applies to `ANTHROPIC_BASE_URL`, not a second copy
/// of it, so the two conventions cannot disagree about what "ours" means.
pub(crate) fn provider_table_is_ours(
    doc: &toml_edit::DocumentMut,
    provider_name: &str,
) -> Option<bool> {
    provider_base_url(doc, provider_name).map(crate::hooks::is_openlatch_loopback_base_url)
}

/// `[model_providers.<provider_name>].base_url`, but only when it is ours.
///
/// The `TomlProvider` leaf of the one "is this agent wired to us?" reader: a
/// customer's own provider table under the same name answers `None`, exactly
/// as a customer-set `ANTHROPIC_BASE_URL` does on the `EnvVars` side.
pub fn read_provider_base_url(config_toml: &Path, provider_name: &str) -> Option<String> {
    let raw = std::fs::read_to_string(config_toml).ok()?;
    let doc = raw.parse::<toml_edit::DocumentMut>().ok()?;
    let url = provider_base_url(&doc, provider_name)?;
    crate::hooks::is_openlatch_loopback_base_url(url).then(|| url.to_string())
}

/// Assign `key = value` at the document root, **keeping the decoration the
/// existing value already had**.
///
/// `doc[key] = value(v)` replaces the whole `Item`, and with it the spacing and
/// any trailing comment the customer wrote around their own value. The key's
/// own decoration (the blank line and comment *above* it) survives either way
/// because the key is not removed — which is also why this never removes and
/// re-inserts.
fn set_root_value(doc: &mut toml_edit::DocumentMut, key: &str, v: &str) {
    let decor = doc
        .get(key)
        .and_then(toml_edit::Item::as_value)
        .map(|existing| existing.decor().clone());
    let mut item = toml_edit::value(v);
    if let (Some(decor), Some(value)) = (decor, item.as_value_mut()) {
        *value.decor_mut() = decor;
    }
    doc[key] = item;
}

/// Point Codex at the model-relay listener.
///
/// Writes exactly two things into `config_toml`: the
/// `[model_providers.<provider_name>]` table, and the top-level
/// `model_provider` key naming it. Everything else in the file — comments, key
/// order, spacing, the customer's own provider tables — is preserved byte for
/// byte, and [`remove_provider_table`] puts the file back the way it was.
///
/// Returns the endpoint the file named **before** this call, for the caller to
/// record: `Some(v)` when a `model_provider` was set, `None` when none was.
/// The caller decides whether to store it — recording on a re-install, when
/// the value is already ours, destroys the real prior.
///
/// # Errors
///
/// - [`ERR_MODEL_RELAY_FOREIGN_PROVIDER`] when a provider table of that name
///   exists and points somewhere other than our loopback listener. The file is
///   left untouched.
/// - [`crate::error::ERR_HOOK_MALFORMED_TOML`] when the file is present and is
///   not valid TOML.
pub fn write_provider_table(
    config_toml: &Path,
    provider_name: &str,
    wire_api: &str,
    install_id_header: &str,
    port: u16,
    install_id: &str,
) -> Result<Prior, OlError> {
    // Read the prior out of the same document the write goes through, so the
    // value recorded and the value replaced cannot come from two different
    // reads of the file.
    let mut prior = Prior::Ours;
    crate::hooks::atomic::atomic_rewrite_toml(config_toml, |doc| {
        if provider_table_is_ours(doc, provider_name) == Some(false) {
            return Err(OlError::new(
                ERR_MODEL_RELAY_FOREIGN_PROVIDER,
                format!(
                    "'{}' already declares a [model_providers.{provider_name}] table that does \
                     not point at the OpenLatch model_relay",
                    crate::core::path_compat::display_path(config_toml)
                ),
            )
            .with_suggestion(
                "Rename or remove that provider table, or disable the model relay for \
                 Codex CLI — OpenLatch will not overwrite a provider entry it did not write.",
            ));
        }

        // The re-install rule lives here because this is the only place that
        // sees the value before it is replaced: a `model_provider` already
        // naming our provider is our own previous install, not a customer's
        // pointer, and recording it would make uninstall restore a name whose
        // table it has just deleted.
        prior = prior_from_document(doc, provider_name);

        // EXPLICIT (`Item::Table`), never an inline table: this renders as a
        // `[model_providers.openlatch]` header rather than one long line in a
        // file the customer reads.
        let mut provider = toml_edit::Table::new();
        provider.insert("name", toml_edit::value(PROVIDER_LABEL));
        provider.insert(
            "base_url",
            toml_edit::value(format!("http://127.0.0.1:{port}/v1")),
        );
        provider.insert("wire_api", toml_edit::value(wire_api));
        provider.insert("requires_openai_auth", toml_edit::value(true));

        let mut headers = toml_edit::Table::new();
        headers.insert(install_id_header, toml_edit::value(install_id));
        provider.insert("http_headers", toml_edit::Item::Table(headers));

        // The PARENT is created IMPLICIT. Without it a bare `[model_providers]`
        // header is emitted above ours — legal TOML, and a diff in the
        // customer's file we did not need to make.
        let parent = doc
            .entry(MODEL_PROVIDERS_TABLE)
            .or_insert(toml_edit::Item::Table({
                let mut t = toml_edit::Table::new();
                t.set_implicit(true);
                t
            }));
        let Some(parent) = parent.as_table_mut() else {
            return Err(OlError::new(
                ERR_MODEL_RELAY_FOREIGN_PROVIDER,
                format!(
                    "'{}' declares `{MODEL_PROVIDERS_TABLE}` as something other than a table",
                    crate::core::path_compat::display_path(config_toml)
                ),
            )
            .with_suggestion(
                "Fix or remove that key — OpenLatch will not rewrite a value it did not write.",
            ));
        };
        parent.insert(provider_name, toml_edit::Item::Table(provider));

        set_root_value(doc, MODEL_PROVIDER_KEY, provider_name);
        Ok(())
    })?;
    Ok(prior)
}

/// What `config.toml` named before an install replaced it.
///
/// Two states rather than a bare `Option<String>`, because "the file already
/// named us" and "the file named nothing" are different facts with different
/// consequences: the first must **not** be recorded (it is our own previous
/// install, and recording it makes uninstall restore a pointer at a table it
/// has just deleted), the second must.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Prior {
    /// The pointer already named our provider — a re-install. Do not touch the
    /// record that is already on file.
    Ours,
    /// The pointer was the customer's, or absent. Record it.
    Theirs(Option<String>),
}

/// Who the `model_provider` pointer currently names.
///
/// One definition, read by the writer (which needs it mid-edit) and by
/// [`read_prior_provider`] (which needs it before the edit). Two copies of this
/// three-arm match would be two chances to disagree about what "ours" means.
fn prior_from_document(doc: &toml_edit::DocumentMut, provider_name: &str) -> Prior {
    match doc
        .get(MODEL_PROVIDER_KEY)
        .and_then(toml_edit::Item::as_str)
    {
        Some(current) if current == provider_name => Prior::Ours,
        Some(current) => Prior::Theirs(Some(current.to_string())),
        None => Prior::Theirs(None),
    }
}

/// What `config.toml` points at right now, WITHOUT writing anything.
///
/// Split out of [`write_provider_table`] so the caller can record the prior
/// endpoint BEFORE the write commits. The writer was the only reader of the
/// pre-write document, which forced write-then-record — and that order has a
/// window where a crash leaves the customer's file pointed at us with no
/// restoration record, so the eventual uninstall reads "nothing was here
/// before" and deletes a setting they had.
///
/// Costs one extra parse at install time. That is the whole price.
pub fn read_prior_provider(config_toml: &Path, provider_name: &str) -> Result<Prior, OlError> {
    if !config_toml.exists() {
        return Ok(Prior::Theirs(None));
    }
    let raw = std::fs::read_to_string(config_toml).map_err(|e| {
        OlError::new(
            ERR_MODEL_RELAY_FOREIGN_PROVIDER,
            format!("cannot read {}: {e}", config_toml.display()),
        )
    })?;
    let doc = raw.parse::<toml_edit::DocumentMut>().map_err(|e| {
        OlError::new(
            ERR_MODEL_RELAY_FOREIGN_PROVIDER,
            format!("{} is not valid TOML: {e}", config_toml.display()),
        )
    })?;
    Ok(prior_from_document(&doc, provider_name))
}

/// Reverse [`write_provider_table`].
///
/// `prior` is what the record store handed back, and its three shapes are three
/// different instructions — see [`crate::hooks::model_relay_endpoints::take`].
///
/// **A no-op unless the provider table is still ours.** Uninstall runs this two
/// or three times (the command, `run_stop`'s net, and the daemon's own
/// teardown), so the second pass must find nothing to do rather than delete the
/// pointer the first pass restored. The ownership test is therefore made
/// *before* the record is consumed — the caller passes an already-taken record
/// only after this returns, never before.
///
/// **The file is never deleted.** Nothing records whether we created it, and
/// removing a customer's own empty `config.toml` is not ours to do.
pub fn remove_provider_table(
    config_toml: &Path,
    provider_name: &str,
    prior: Option<Option<String>>,
) -> Result<(), OlError> {
    if !config_toml.exists() {
        return Ok(());
    }
    crate::hooks::atomic::atomic_rewrite_toml(config_toml, |doc| {
        if provider_table_is_ours(doc, provider_name) != Some(true) {
            return Ok(());
        }
        let mut parent_is_empty = false;
        if let Some(providers) = doc
            .get_mut(MODEL_PROVIDERS_TABLE)
            .and_then(toml_edit::Item::as_table_mut)
        {
            providers.remove(provider_name);
            parent_is_empty = providers.is_empty();
        }
        // Prune the parent once it is empty, or a bare `[model_providers]`
        // header survives the uninstall.
        if parent_is_empty {
            doc.remove(MODEL_PROVIDERS_TABLE);
        }
        match prior {
            // The customer named a provider before us. Put that name back, in
            // place, so the comment and spacing around it survive — but ONLY if
            // the pointer is still ours to give back. A customer who repointed
            // `model_provider` at something else after our install has made a
            // newer choice than the one we recorded, and restoring over it
            // would silently undo them. Same test the arm below applies, and
            // for the same stated reason: a pointer the customer changed by
            // hand after we wrote ours is theirs again.
            Some(Some(ref v))
                if doc
                    .get(MODEL_PROVIDER_KEY)
                    .and_then(toml_edit::Item::as_str)
                    == Some(provider_name) =>
            {
                set_root_value(doc, MODEL_PROVIDER_KEY, v)
            }
            // Ours was already replaced by the customer: leave their pointer
            // exactly as it is. The owned provider table is still removed above.
            Some(Some(_)) => {}
            // Either the file named nothing before us (`Some(None)`), or no
            // record was ever written (`None`) — an install that predates the
            // record store. Both leave the pointer at a table that no longer
            // exists, which Codex refuses the whole config over, so both drop
            // it. Only ever OUR name: a pointer the customer changed by hand
            // after we wrote ours is theirs again.
            Some(None) | None => {
                if doc
                    .get(MODEL_PROVIDER_KEY)
                    .and_then(toml_edit::Item::as_str)
                    == Some(provider_name)
                {
                    doc.remove(MODEL_PROVIDER_KEY);
                }
            }
        }
        Ok(())
    })
}

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

    /// The two files Codex keeps side by side. Pinned because they are derived
    /// in exactly one place and every later consumer joins nothing of its own.
    #[test]
    fn codex_paths_are_derived_from_the_config_dir() {
        let root = Path::new("/home/test/.codex");
        assert_eq!(hooks_json_path(root), root.join("hooks.json"));
        assert_eq!(config_toml_path(root), root.join("config.toml"));
    }

    /// Codex keys hook trust on **position**, and our group is appended, so on
    /// any host that already had a `PreToolUse` hook ours is not at index zero.
    /// A reader that assumed `:0:0` would report the *customer's* trust state
    /// as ours — a confident wrong answer, which is the failure the whole
    /// arming check exists to prevent.
    ///
    /// The second half proves the compare is canonicalized: a `$CODEX_HOME`
    /// reached through a symlink stores one spelling of the path and computes
    /// another, and a plain string compare would miss the entry and render a
    /// confident "never trusted" on a host that is trusted.
    #[test]
    fn codex_trust_key_uses_the_found_indices() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();

        // A customer's own PreToolUse group FIRST, ours appended after it.
        std::fs::write(
            hooks_json_path(root),
            r#"{
              "hooks": {
                "PreToolUse": [
                  {"matcher": "", "hooks": [{"type": "command", "command": "echo mine", "timeout": 5}]},
                  {"matcher": "Bash", "_openlatch": {"v": 1, "id": "x"},
                   "hooks": [{"type": "command", "command": "\"/ol/bin/openlatch-hook\" --agent codex-cli --event pre_tool_use", "timeout": 10}]}
                ]
              }
            }"#,
        )
        .expect("write hooks.json");

        let ours = installed_handler(root, "PreToolUse").expect("our appended group must be found");
        assert_eq!(ours.group_index, 1, "ours is the SECOND group: {ours:?}");
        assert_eq!(ours.handler_index, 0);
        assert_eq!(ours.timeout_secs, Some(10));
        assert!(ours.command.contains("openlatch-hook"));

        let key = trust_key(root, "PreToolUse", &ours);
        assert!(
            key.ends_with(":1:0"),
            "the key must carry the indices we FOUND, not :0:0 — {key}"
        );
        assert!(
            !key.ends_with(":0:0"),
            "a :0:0 key reads the customer's trust state as ours — {key}"
        );
        // The event is snake_case in the key while the `hooks.json` property
        // that declares it is PascalCase.
        assert!(key.contains(":pre_tool_use:"), "{key}");

        // The whole documented shape. The source path uses the host separator:
        // Codex records a native filesystem path in this key, so a Unix-only
        // literal would reject the correct Windows spelling.
        //
        // UNCONFIRMED — the `source_path` half. This is the form Codex's own
        // documentation gives (`"/home/u/.codex/hooks.json:pre_tool_use:0:0"`),
        // but the exact string a running Codex writes has NOT been observed
        // live: doing so needs an interactive `codex login` plus a `/hooks`
        // trust grant inside the sandbox, which the session that wrote this
        // could not perform. Confirm it against a real `$CODEX_HOME/config.toml`
        // and paste the observed value here.
        //
        // What protects us meanwhile is `is_same_file`, exercised below: the
        // lookup canonicalizes both sides instead of matching the string, so a
        // source path Codex spells differently still resolves to our entry.
        let at_zero = InstalledHandler {
            group_index: 0,
            handler_index: 0,
            ..ours.clone()
        };
        let documented_root = Path::new("/home/u/.codex");
        let documented_key = format!(
            "{}:pre_tool_use:0:0",
            documented_root.join("hooks.json").display()
        );
        assert_eq!(
            trust_key(documented_root, "PreToolUse", &at_zero),
            documented_key
        );

        // No `config.toml` at all is a fresh install: never trusted, and NOT
        // "cannot tell".
        assert_eq!(
            hook_trust(root, "PreToolUse", &ours),
            Some(HookTrust::NeverTrusted),
            "an absent config.toml is an answer, not an unknown"
        );

        // Codex records trust under OUR key. The customer's `:0:0` entry is
        // trusted and must not be mistaken for ours.
        let real_key = trust_key(root, "PreToolUse", &ours);
        let customer_key = trust_key(root, "PreToolUse", &at_zero);
        std::fs::write(
            config_toml_path(root),
            format!(
                "[hooks.state.'{customer_key}']\n\
                 trusted_hash = \"customer-hash\"\n\
                 \n\
                 [hooks.state.'{real_key}']\n\
                 trusted_hash = \"ours\"\n"
            ),
        )
        .expect("write config.toml");
        assert_eq!(
            hook_trust(root, "PreToolUse", &ours),
            Some(HookTrust::Trusted)
        );

        // Strip only OUR `trusted_hash` — exactly the on-disk state a re-armed
        // review leaves behind — and the customer's trusted entry must not
        // rescue it.
        std::fs::write(
            config_toml_path(root),
            format!(
                "[hooks.state.'{customer_key}']\n\
                 trusted_hash = \"customer-hash\"\n\
                 \n\
                 [hooks.state.'{real_key}']\n"
            ),
        )
        .expect("write config.toml");
        assert_eq!(
            hook_trust(root, "PreToolUse", &ours),
            Some(HookTrust::NeverTrusted),
            "a present key with no trusted_hash is a re-armed review"
        );

        // `enabled = false` is its own observation.
        std::fs::write(
            config_toml_path(root),
            format!(
                "[hooks.state.'{real_key}']\n\
                 enabled = false\n\
                 trusted_hash = \"ours\"\n"
            ),
        )
        .expect("write config.toml");
        assert_eq!(
            hook_trust(root, "PreToolUse", &ours),
            Some(HookTrust::Disabled)
        );

        // A config.toml that is present and unparsable is "cannot tell" —
        // never a confident red.
        std::fs::write(config_toml_path(root), "[hooks.state\n").expect("write config.toml");
        assert_eq!(hook_trust(root, "PreToolUse", &ours), None);

        // --- the canonicalized compare -------------------------------------
        //
        // Reach the same directory through a symlink. Codex stored the key
        // under the REAL path; we look it up from the linked one. A plain
        // string compare misses and renders a confident "never trusted".
        std::fs::write(
            config_toml_path(root),
            format!("[hooks.state.'{real_key}']\ntrusted_hash = \"ours\"\n"),
        )
        .expect("write config.toml");

        let link_parent = tempfile::tempdir().expect("temp dir");
        let link = link_parent.path().join("codex-link");
        symlink_dir(root, &link).expect("symlink");
        assert_ne!(
            trust_key(&link, "PreToolUse", &ours),
            real_key,
            "the fixture is pointless unless the two spellings differ"
        );
        assert_eq!(
            hook_trust(&link, "PreToolUse", &ours),
            Some(HookTrust::Trusted),
            "a symlinked $CODEX_HOME must still find the entry Codex wrote"
        );
    }

    /// One `cfg` for the platform's directory-symlink call, so the test above
    /// reads the same on every platform.
    #[cfg(unix)]
    fn symlink_dir(target: &Path, link: &Path) -> std::io::Result<()> {
        std::os::unix::fs::symlink(target, link)
    }

    #[cfg(windows)]
    fn symlink_dir(target: &Path, link: &Path) -> std::io::Result<()> {
        std::os::windows::fs::symlink_dir(target, link)
    }

    // -----------------------------------------------------------------------
    // `hooks/list` and the trust grant
    // -----------------------------------------------------------------------

    /// A `hooks.json` with the customer's `PreToolUse` hook first and ours
    /// appended after it, plus our `SessionStart` alone.
    fn customer_then_ours(root: &Path) {
        std::fs::write(
            hooks_json_path(root),
            r#"{"hooks":{
              "PreToolUse":[
                {"matcher":"","hooks":[{"type":"command","command":"echo mine","timeout":5}]},
                {"matcher":"Bash","_openlatch":{"v":1,"id":"x"},
                 "hooks":[{"type":"command","command":"\"/ol/bin/openlatch-hook\" --event pre_tool_use","timeout":900}]}],
              "SessionStart":[
                {"matcher":"","_openlatch":{"v":1,"id":"y"},
                 "hooks":[{"type":"command","command":"\"/ol/bin/openlatch-hook\" --event session_start","timeout":10}]}]}}"#,
        )
        .expect("write hooks.json");
    }

    /// The listing Codex 0.150.1 answered for [`customer_then_ours`], captured
    /// live against an isolated `$CODEX_HOME` and trimmed to the fields read.
    /// Wrapped in the JSON-RPC response, with a notification-only field the
    /// parser must ignore.
    fn captured_response(root: &Path, statuses: [&str; 3]) -> serde_json::Value {
        let file = hooks_json_path(root);
        let key = |rest: &str| format!("{}:{rest}", file.display());
        serde_json::json!({"id": 2, "result": {"data": [{
            "cwd": root,
            "hooks": [
                {"key": key("pre_tool_use:0:0"), "eventName": "preToolUse",
                 "command": "echo mine", "sourcePath": file, "source": "user",
                 "enabled": true, "isManaged": false,
                 "currentHash": "sha256:customer", "trustStatus": statuses[0]},
                {"key": key("pre_tool_use:1:0"), "eventName": "preToolUse",
                 "command": "\"/ol/bin/openlatch-hook\" --event pre_tool_use",
                 "sourcePath": file, "source": "user", "enabled": true, "isManaged": false,
                 "currentHash": "sha256:ours-pre", "trustStatus": statuses[1]},
                {"key": key("session_start:0:0"), "eventName": "sessionStart",
                 "command": "\"/ol/bin/openlatch-hook\" --event session_start",
                 "sourcePath": file, "source": "user", "enabled": true, "isManaged": false,
                 "currentHash": "sha256:ours-start", "trustStatus": statuses[2]},
                {"key": "malformed — no hash, skipped rather than failing the listing"}
            ],
            "warnings": [], "errors": []}]}})
    }

    #[test]
    fn hooks_list_response_parses_and_errors_do_not() {
        let dir = tempfile::tempdir().expect("temp dir");
        let listing = parse_hooks_list(&captured_response(
            dir.path(),
            ["untrusted", "trusted", "modified"],
        ))
        .expect("a result");
        assert_eq!(
            listing.len(),
            3,
            "the malformed hook is skipped: {listing:?}"
        );
        assert_eq!(listing[2].trust_status, TrustStatus::Modified);

        let error = serde_json::json!({"id": 2, "error": {"code": -32601, "message": "no"}});
        assert!(parse_hooks_list(&error).is_none());

        let unknown = serde_json::json!({"id": 2, "result": {"data": [{"hooks": [{
            "key": "k:pre_tool_use:0:0", "sourcePath": "/x", "currentHash": "h",
            "trustStatus": "someFutureStatus"}]}]}});
        assert_eq!(
            parse_hooks_list(&unknown).expect("a result")[0].trust_status,
            TrustStatus::Unrecognised,
            "a status this build does not know is not a parse failure"
        );
    }

    /// Codex's verdict is read at the position our handler was FOUND at — the
    /// customer's untrusted `:0:0` must not be read as ours.
    #[test]
    fn listed_trust_reads_our_position_not_the_customers() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        customer_then_ours(root);
        let listing = parse_hooks_list(&captured_response(
            root,
            ["untrusted", "trusted", "untrusted"],
        ))
        .expect("a result");
        let ours = installed_handler(root, "PreToolUse").expect("ours");

        let (trust, hook) = listed_trust(&listing, root, "PreToolUse", &ours).expect("listed");
        assert_eq!(trust, HookTrust::Trusted);
        assert_eq!(hook.current_hash, "sha256:ours-pre");
        assert!(listed_trust(&[], root, "PreToolUse", &ours).is_none());
    }

    /// The grant writes **our** keys only, with the hash Codex published, and
    /// leaves every other byte of the customer's file — including their own
    /// trust entry — exactly as it was.
    #[test]
    fn grant_writes_only_our_keys_and_preserves_the_rest() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        customer_then_ours(root);
        let file = hooks_json_path(root).display().to_string();
        let seed = format!(
            "# mine\nmodel = \"gpt-5-codex\"  # trailing\n\n\
             [hooks.state.'{file}:pre_tool_use:0:0']\ntrusted_hash = \"sha256:customer\"\n\n\
             [tui]\ntheme = \"dark\"\n"
        );
        std::fs::write(config_toml_path(root), &seed).expect("seed");
        let listing = parse_hooks_list(&captured_response(
            root,
            ["trusted", "untrusted", "modified"],
        ))
        .expect("a result");

        let grants = grant_own_hook_trust(root, &listing, TrustOccasion::Install).expect("grant");

        assert_eq!(
            grants
                .iter()
                .map(|g| g.trusted_hash.as_str())
                .collect::<Vec<_>>(),
            ["sha256:ours-pre", "sha256:ours-start"],
            "untrusted and modified are both ours to grant, the customer's is not"
        );
        let after = std::fs::read_to_string(config_toml_path(root)).expect("read back");
        assert!(
            after.starts_with(&seed[..seed.find("[tui]").expect("tui")]),
            "{after}"
        );
        assert!(after.contains("[tui]\ntheme = \"dark\""), "{after}");
        assert!(
            after.contains("trusted_hash = \"sha256:customer\""),
            "{after}"
        );
        assert!(
            !after.contains("[hooks]\n"),
            "no bare parent header: {after}"
        );
        let parsed: toml::Value = toml::from_str(&after).expect("valid TOML");
        let state = &parsed["hooks"]["state"];
        assert_eq!(
            state[&format!("{file}:pre_tool_use:1:0")]["trusted_hash"].as_str(),
            Some("sha256:ours-pre")
        );
        assert_eq!(
            state[&format!("{file}:session_start:0:0")]["enabled"].as_bool(),
            Some(true),
            "an install switches our hook on"
        );
        assert!(state[&format!("{file}:pre_tool_use:0:0")]
            .get("enabled")
            .is_none());

        // Nothing left to grant: the file is not rewritten at all.
        let trusted = parse_hooks_list(&captured_response(
            root,
            ["untrusted", "trusted", "trusted"],
        ))
        .expect("a result");
        assert!(grant_own_hook_trust(root, &trusted, TrustOccasion::Drift)
            .expect("no-op")
            .is_empty());
        assert_eq!(
            std::fs::read_to_string(config_toml_path(root)).expect("read back"),
            after
        );
    }

    /// Uninstall takes back what we granted — and only while the hash is still
    /// ours — and gives a file with no other trust back byte for byte.
    #[test]
    fn revoke_takes_back_our_grants_only() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        customer_then_ours(root);
        let seed = "model = \"gpt-5-codex\"\n";
        std::fs::write(config_toml_path(root), seed).expect("seed");
        let listing = parse_hooks_list(&captured_response(
            root,
            ["trusted", "untrusted", "untrusted"],
        ))
        .expect("a result");
        let grants = grant_own_hook_trust(root, &listing, TrustOccasion::Install).expect("grant");

        revoke_granted_trust(root, &grants).expect("revoke");
        assert_eq!(
            std::fs::read_to_string(config_toml_path(root)).expect("read back"),
            seed,
            "no bare [hooks] or [hooks.state] header survives"
        );

        // Re-granted by someone else since: theirs now, and it stays.
        grant_own_hook_trust(root, &listing, TrustOccasion::Install).expect("grant");
        let file = hooks_json_path(root).display().to_string();
        let path = config_toml_path(root);
        let regranted = std::fs::read_to_string(&path).expect("read").replacen(
            "sha256:ours-pre",
            "sha256:reviewed-by-hand",
            1,
        );
        std::fs::write(&path, regranted).expect("write");
        revoke_granted_trust(root, &grants).expect("revoke");
        let after = std::fs::read_to_string(&path).expect("read back");
        assert!(
            after.contains("sha256:reviewed-by-hand") && !after.contains("sha256:ours-start"),
            "{after}"
        );
        assert!(
            after.contains(&format!("{file}:pre_tool_use:1:0")),
            "{after}"
        );
    }

    /// **The positional drift, on disk.** Ours is trusted at `:1:0`; the
    /// customer deletes their own hook above it, ours shifts to `:0:0`, and the
    /// trust recorded at `:1:0` no longer applies. The cheap gate must see it.
    #[test]
    fn an_index_shift_is_seen_as_a_trust_gap() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        customer_then_ours(root);
        let file = hooks_json_path(root).display().to_string();
        std::fs::write(
            config_toml_path(root),
            format!(
                "[hooks.state.'{file}:pre_tool_use:1:0']\ntrusted_hash = \"a\"\n\
                 [hooks.state.'{file}:session_start:0:0']\ntrusted_hash = \"b\"\n"
            ),
        )
        .expect("config");
        // Without this, an unparsable fixture makes the gate answer `false`
        // and the next assertion passes for the wrong reason — which is how a
        // Windows path in a basic-string key (`\U…` read as an escape) hid.
        let ours = installed_handler(root, "PreToolUse").expect("ours");
        assert_eq!(
            hook_trust(root, "PreToolUse", &ours),
            Some(HookTrust::Trusted),
            "the fixture must be readable TOML that trusts ours"
        );
        assert!(
            !own_hooks_need_trust(root),
            "every handler of ours is trusted"
        );

        // The customer removes their hook: ours moves from `:1:0` to `:0:0`.
        let raw = std::fs::read_to_string(hooks_json_path(root)).expect("read");
        let mut parsed: serde_json::Value = serde_json::from_str(&raw).expect("json");
        parsed["hooks"]["PreToolUse"]
            .as_array_mut()
            .expect("array")
            .remove(0);
        std::fs::write(hooks_json_path(root), parsed.to_string()).expect("write");
        assert!(own_hooks_need_trust(root), "the shift left ours untrusted");

        // An off switch is the developer's choice, not a gap.
        std::fs::write(
            config_toml_path(root),
            format!(
                "[hooks.state.'{file}:pre_tool_use:0:0']\nenabled = false\n\
                 [hooks.state.'{file}:session_start:0:0']\ntrusted_hash = \"b\"\n"
            ),
        )
        .expect("config");
        assert!(!own_hooks_need_trust(root));
    }

    // -----------------------------------------------------------------------
    // The model-relay provider table (I-3 §1 / §2)
    // -----------------------------------------------------------------------

    /// A hand-written `config.toml` of the shape a customer actually keeps:
    /// a leading comment, an inline trailing comment, a blank line, their own
    /// provider pointer and provider table, and an unrelated `[tui]` table
    /// after it.
    const SEED: &str = "\
# my config, hand written
model = \"gpt-5-codex\"          # trailing comment

# a customer provider they actually use
model_provider = \"corporate-gateway\"

[model_providers.corporate-gateway]
name     = \"ACME\"
base_url = \"https://llm.acme.internal/v1\"
wire_api = \"responses\"

[tui]
theme = \"dark\"
";

    /// Seed a `config.toml` under a fresh tempdir and hand back both.
    fn seeded_config(seed: &str) -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = config_toml_path(dir.path());
        std::fs::write(&path, seed).expect("seed config.toml");
        (dir, path)
    }

    /// Install this unit's provider table with the values `CodexCliBinding`
    /// declares.
    fn install(path: &Path, port: u16) -> Result<Prior, OlError> {
        write_provider_table(
            path,
            "openlatch",
            "responses",
            "x-openlatch-install-id",
            port,
            "agt_demo",
        )
    }

    /// A customer's `config.toml` is theirs. Comments, key order, spacing and
    /// every table we did not write survive the install untouched — which is
    /// why this uses `toml_edit` rather than a deserialize/serialize round trip.
    #[test]
    fn toml_writer_preserves_comments_and_key_order() {
        let (_dir, path) = seeded_config(SEED);
        install(&path, 7600).expect("install");

        let after = std::fs::read_to_string(&path).expect("read back");
        for fragment in [
            "# my config, hand written",
            "model = \"gpt-5-codex\"          # trailing comment",
            "# a customer provider they actually use",
            "[model_providers.corporate-gateway]",
            "name     = \"ACME\"",
            "base_url = \"https://llm.acme.internal/v1\"",
            "[tui]",
            "theme = \"dark\"",
        ] {
            assert!(
                after.contains(fragment),
                "install ate `{fragment}`:\n{after}"
            );
        }
        assert!(
            after.contains("[model_providers.openlatch]"),
            "our table must be an explicit header, never an inline table:\n{after}"
        );
        assert!(
            after.contains("base_url = \"http://127.0.0.1:7600/v1\""),
            "the RESOLVED port, and Codex's `/v1` suffix:\n{after}"
        );
        assert!(
            after.contains("name = \"OpenLatch model relay\""),
            "`name` is MANDATORY — Codex rejects the whole config without it:\n{after}"
        );
        assert!(
            after.contains("wire_api = \"responses\""),
            "the wire_api comes from the binding:\n{after}"
        );
        assert!(
            after.contains("[model_providers.openlatch.http_headers]"),
            "the install-id header rides on the provider table:\n{after}"
        );
        assert_eq!(
            after.matches("model_provider = ").count(),
            1,
            "the pointer is replaced in place, never duplicated:\n{after}"
        );
        assert!(
            after.contains("model_provider = \"openlatch\""),
            "and it names us after an install:\n{after}"
        );

        // The convention's read side agrees with what the writer wrote — one
        // predicate, so `doctor` and `status` cannot disagree with `install`
        // about whether this agent is wired to us.
        assert_eq!(
            read_provider_base_url(&path, "openlatch").as_deref(),
            Some("http://127.0.0.1:7600/v1")
        );
        assert_eq!(
            read_provider_base_url(&path, "corporate-gateway"),
            None,
            "a customer's own provider table is not evidence that we wired anything"
        );
    }

    /// Install then uninstall must give the customer their file back **byte for
    /// byte** — no bare `[model_providers]` header left behind, no reflowed
    /// spacing, no lost comment. This is the support incident the whole writer
    /// exists to prevent.
    #[test]
    fn toml_uninstall_is_byte_identical_to_the_seed() {
        let (_dir, path) = seeded_config(SEED);
        let prior = install(&path, 7600).expect("install");
        assert_eq!(
            prior,
            Prior::Theirs(Some("corporate-gateway".into())),
            "the writer must hand back what the file named before it"
        );

        remove_provider_table(&path, "openlatch", Some(Some("corporate-gateway".into())))
            .expect("uninstall");

        let after = std::fs::read_to_string(&path).expect("read back");
        assert_eq!(after, SEED, "uninstall must be byte-identical to the seed");
        assert!(
            !after.contains("[model_providers]"),
            "a bare parent header must not survive uninstall:\n{after}"
        );
    }

    /// A choice the customer made AFTER our install outranks the one we
    /// recorded before it.
    ///
    /// Uninstall restores the endpoint we displaced — but only while the
    /// pointer is still ours to give back. Someone who repoints
    /// `model_provider` at a new gateway while OpenLatch is installed has made
    /// a newer decision than the one on file, and restoring over it would
    /// silently undo them. The `Some(None) | None` arm already applied that
    /// test and said so in a comment; the restore arm did not, which is the
    /// asymmetry this pins.
    #[test]
    fn a_provider_the_customer_chose_after_install_is_not_overwritten() {
        let (_dir, path) = seeded_config(SEED);
        install(&path, 7600).expect("install");

        // The customer moves to a different gateway while we are installed.
        let installed = std::fs::read_to_string(&path).expect("read");
        std::fs::write(
            &path,
            installed.replace(
                r#"model_provider = "openlatch""#,
                r#"model_provider = "new-gateway""#,
            ),
        )
        .expect("customer edit");

        remove_provider_table(&path, "openlatch", Some(Some("corporate-gateway".into())))
            .expect("uninstall");

        let after = std::fs::read_to_string(&path).expect("read back");
        assert!(
            after.contains(r#"model_provider = "new-gateway""#),
            "the customer's later choice must survive uninstall:\n{after}"
        );
        // Their own `[model_providers.corporate-gateway]` TABLE must of course
        // survive — it is the customer's, and we never owned it. What must not
        // come back is the POINTER at it, which they moved off deliberately.
        assert!(
            !after.contains(r#"model_provider = "corporate-gateway""#),
            "uninstall must not resurrect the pointer we displaced once the customer \
             has moved on:\n{after}"
        );
        assert!(
            after.contains("[model_providers.corporate-gateway]"),
            "the customer's own provider table is theirs and must survive:\n{after}"
        );
        assert!(
            !after.contains("[model_providers.openlatch]"),
            "our own provider table must still be removed:\n{after}"
        );
    }

    /// The customer's own `model_provider` is restored, not merely deleted.
    /// A fresh file — one that named no provider at all — has the key removed
    /// instead, because leaving `model_provider = "openlatch"` behind points
    /// Codex at a table that no longer exists and it refuses the whole config.
    #[test]
    fn toml_restores_a_customer_model_provider() {
        let (_dir, path) = seeded_config(SEED);
        install(&path, 7600).expect("install");
        remove_provider_table(&path, "openlatch", Some(Some("corporate-gateway".into())))
            .expect("uninstall");
        assert!(
            std::fs::read_to_string(&path)
                .expect("read back")
                .contains("model_provider = \"corporate-gateway\""),
            "the customer's pointer must come back"
        );

        let fresh = "model = \"gpt-5-codex\"\n";
        let (_dir2, path2) = seeded_config(fresh);
        assert_eq!(
            install(&path2, 7600).expect("install"),
            Prior::Theirs(None),
            "a file that named no provider records an absence, not a value"
        );
        remove_provider_table(&path2, "openlatch", Some(None)).expect("uninstall");
        let after = std::fs::read_to_string(&path2).expect("read back");
        assert_eq!(after, fresh, "and the file comes back byte-identical");
        assert!(!after.contains("model_provider"));
    }

    /// **The re-install trap.** Two installs with no uninstall between them:
    /// the second sees `model_provider = "openlatch"` on disk, and recording
    /// that would make uninstall "restore" a pointer at a table it has just
    /// deleted. Every single-install test passes without this.
    ///
    /// Driven through `hooks::write_model_relay_config` rather than the writer
    /// alone, because the record store is the half that can get it wrong.
    #[test]
    fn reinstall_does_not_destroy_the_recorded_prior() {
        let _guard = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let state = tempfile::tempdir().expect("state dir");
        let prev = std::env::var_os("OPENLATCH_DIR");
        std::env::set_var("OPENLATCH_DIR", state.path());

        let (_dir, path) = seeded_config(SEED);
        let binding = crate::hooks::binding::test_support::FakeBinding {
            agent_type: "codex-cli",
            config_dir: path.parent().expect("parent").to_path_buf(),
            model_relay_wiring: Some(crate::hooks::binding::ModelRelayWiring {
                wire_format: crate::model_relay::wire_format::WireFormat::OpenAiResponses,
                endpoint: crate::hooks::binding::EndpointConvention::TomlProvider {
                    provider_name: "openlatch",
                    wire_api: "responses",
                },
                install_id_header: "x-openlatch-install-id",
            }),
            ..Default::default()
        };

        crate::hooks::write_model_relay_config(&binding, 7600, "agt_demo").expect("install");
        crate::hooks::write_model_relay_config(&binding, 7600, "agt_demo").expect("re-install");
        crate::hooks::remove_model_relay_config(&binding).expect("uninstall");
        // Idempotent: uninstall runs two or three times per `openlatch
        // uninstall`, and the second pass must not undo the first.
        crate::hooks::remove_model_relay_config(&binding).expect("second uninstall pass");

        let after = std::fs::read_to_string(&path).expect("read back");
        match prev {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }
        assert_eq!(
            after, SEED,
            "after TWO installs the uninstall must still restore the CUSTOMER's pointer"
        );
    }

    /// **D-11.** A `[model_providers.openlatch]` that is not ours is somebody
    /// else's, and install refuses rather than overwriting it — because
    /// uninstall could not then round-trip the file. The file is left exactly
    /// as it was.
    #[test]
    fn foreign_openlatch_table_refuses() {
        let foreign = "\
# somebody else got here first
model_provider = \"openlatch\"

[model_providers.openlatch]
name     = \"Someone else's openlatch\"
base_url = \"https://openlatch.internal.example/v1\"
wire_api = \"responses\"
";
        let (_dir, path) = seeded_config(foreign);
        let err = install(&path, 7600).expect_err("a foreign table must refuse");
        assert_eq!(err.code, ERR_MODEL_RELAY_FOREIGN_PROVIDER);
        assert!(
            err.suggestion.is_some(),
            "a refusal the operator cannot act on is not a remedy"
        );
        assert_eq!(
            std::fs::read_to_string(&path).expect("read back"),
            foreign,
            "the file must be untouched after the refusal"
        );

        // And the reversal is guarded by the same test: a foreign table is not
        // ours to delete.
        remove_provider_table(&path, "openlatch", Some(Some("whatever".into())))
            .expect("removal is a no-op on a foreign table");
        assert_eq!(
            std::fs::read_to_string(&path).expect("read back"),
            foreign,
            "uninstall must not eat a provider table it did not write"
        );
    }
}