openlatch-client 0.3.3

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

use std::path::PathBuf;
use std::sync::Arc;

use crate::core::hook_state::hmac::compute_entry_hmac;
use crate::core::hook_state::key::HmacKeyStore;
use crate::core::hook_state::marker::OpenlatchMarker;
use crate::core::hook_state::{self, HookStateFile, StateEntry};
use crate::error::{OlError, ERR_HOOK_AGENT_NOT_FOUND, ERR_HOOK_BINARY_UNRESOLVABLE};
use crate::hooks::binding::AgentBinding;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A detected AI agent, paired with the binding that acts on it.
///
/// `kind` is what callers match on; `binding` is what they act through. The
/// binding already resolved every path, so a duplicated payload here would be a
/// second copy that can disagree with it. One field, one source.
#[derive(Clone)]
pub struct DetectedAgent {
    /// Which agent this is.
    pub kind: AgentKind,
    /// Everything the client needs in order to act on it.
    pub binding: Arc<dyn AgentBinding>,
}

/// The identity half of a [`DetectedAgent`].
///
/// `#[non_exhaustive]` has **no effect inside this crate** — every match on it
/// here still breaks, usefully, when agent three lands. It is a semver
/// affordance for downstream consumers of the published lib, nothing more.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentKind {
    /// Claude Code.
    ClaudeCode,
    /// Codex CLI.
    CodexCli,
}

impl DetectedAgent {
    /// The agent's config directory — read from the binding, never duplicated.
    pub fn config_dir(&self) -> PathBuf {
        self.binding.config_dir()
    }

    /// The file this agent's hook registrations are written into.
    pub fn settings_path(&self) -> PathBuf {
        self.binding.hook_config_path()
    }

    /// The CloudEvents `source` wire value, e.g. `"claude-code"`.
    pub fn agent_type(&self) -> &'static str {
        self.binding.agent_type()
    }

    /// Human-facing label, e.g. `"Claude Code"`. Feeds doctor's Environment
    /// line and init's detected-agent step.
    pub fn display_name(&self) -> &'static str {
        self.binding.display_name()
    }
}

// Hand-written: `Arc<dyn AgentBinding>` is not `Debug`. The kind and the
// resolved config directory are enough for a log line, and no more.
impl std::fmt::Debug for DetectedAgent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DetectedAgent")
            .field("kind", &self.kind)
            .field("config_dir", &self.binding.config_dir())
            .finish()
    }
}

/// The result of a successful [`install_hooks`] call.
#[derive(Debug)]
pub struct HookInstallResult {
    /// Per-hook-event status showing whether the entry was added or replaced.
    pub entries: Vec<HookEntryStatus>,
}

/// Status of a single hook event entry after installation.
#[derive(Debug)]
pub struct HookEntryStatus {
    /// The hook event type (e.g. `"PreToolUse"`, `"UserPromptSubmit"`, `"Stop"`).
    pub event_type: String,
    /// Whether the entry was newly added or replaced an existing OpenLatch entry.
    pub action: HookAction,
}

/// Whether a hook entry was newly created or replaced an existing one.
#[derive(Debug, Clone, PartialEq)]
pub enum HookAction {
    /// A new hook entry was appended to the array.
    Added,
    /// An existing OpenLatch-owned entry was replaced (idempotent re-install).
    Replaced,
}

/// Resolve the absolute path to the `openlatch-hook` binary that hook
/// configs should invoke.
///
/// Order of precedence:
///
/// 1. `OPENLATCH_HOOK_BIN` env var (override for tests, custom installs).
/// 2. `<openlatch_dir>/bin/openlatch-hook[.exe]` — the canonical install
///    location, populated by [`staging::stage_hook_binary`], which `init` and
///    `doctor --fix` both call before writing any hook. Resolved through
///    [`crate::config::openlatch_dir`] so it honours `$OPENLATCH_DIR`, exactly
///    like the side that writes it.
/// 3. `openlatch-hook[.exe]` next to the current running binary (typical
///    during `cargo install` or portable tarball extractions).
/// 4. Bare `"openlatch-hook"` as a last resort — relies on the hook
///    subprocess resolving it via `PATH`.
///
/// Step 4 is a path that may not exist, and writing it into a hook command is
/// what produced the #165 outage: `/bin/sh: openlatch-hook: command not found`
/// on every tool call, invisible because the hook fails open. [`install_hooks`]
/// therefore refuses any resolution that is not an existing file — callers must
/// stage the binary first rather than let this fall through.
pub fn resolve_hook_binary_path() -> PathBuf {
    let bin_name = if cfg!(windows) {
        "openlatch-hook.exe"
    } else {
        "openlatch-hook"
    };

    if let Ok(override_path) = std::env::var("OPENLATCH_HOOK_BIN") {
        if !override_path.is_empty() {
            return PathBuf::from(override_path);
        }
    }

    // `config::openlatch_dir()`, not `home/.openlatch`: the staging side writes
    // into `<ol_dir>/bin`, and `<ol_dir>` honours `$OPENLATCH_DIR` (and resolves
    // under `%APPDATA%` on Windows). Hardcoding the home-relative path here made
    // the two disagree on any non-default directory — the resolver looked in a
    // directory nothing had ever staged into, and fell through to the bare name.
    let candidate = crate::config::openlatch_dir().join("bin").join(bin_name);
    if candidate.exists() {
        return candidate;
    }

    if let Ok(current_exe) = std::env::current_exe() {
        if let Some(dir) = current_exe.parent() {
            let candidate = dir.join(bin_name);
            if candidate.exists() {
                return candidate;
            }
        }
    }

    PathBuf::from(bin_name)
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Every AI agent installed on this machine, in detection order.
///
/// Plural is the primitive: callers that must act on the whole host iterate
/// this. Order is fixed (Claude Code first) and load-bearing.
pub fn detect_agents() -> Vec<DetectedAgent> {
    binding::detect_all()
}

/// The **first** detected agent.
///
/// For callers that own wiring for the *instance* rather than acting per
/// agent — "which agent does this daemon instance own wiring for" is singular
/// by construction. Callers that must reach every agent use
/// [`detect_agents`].
///
/// # Errors
///
/// Returns `OL-1400` if no supported AI agent is detected.
pub fn detect_agent() -> Result<DetectedAgent, OlError> {
    detect_agents()
        .into_iter()
        .next()
        .ok_or_else(agent_not_found_err)
}

/// `OL-1400`, with a remedy naming **every** agent this build can detect.
///
/// The old text named Claude Code and only Claude Code, with a
/// `https://claude.ai/download` link. One URL cannot serve a list, and
/// `.with_docs` already carries the OL-1400 page where per-agent install
/// instructions belong.
pub(crate) fn agent_not_found_err() -> OlError {
    OlError::new(ERR_HOOK_AGENT_NOT_FOUND, "No AI agents detected")
        .with_suggestion(format!(
            "Install a supported agent ({}) and try again.",
            binding::DETECTABLE_AGENT_NAMES.join(", ")
        ))
        .with_docs("https://docs.openlatch.ai/errors/OL-1400")
}

/// Narrow `agents` to the ones the operator named with `--agent` (D-09).
///
/// **Coverage is the default**: an empty `wanted` returns every detected agent
/// untouched, so an operator who says nothing gets everything on the host
/// wired. Opting an agent *out* is the explicit act, not opting one in.
///
/// The three failure directions, and why they differ:
///
/// - **A name that is not an agent type at all** is a typo in the flag. It
///   fails, listing the valid wire values from
///   [`crate::generated::known_values::SCHEMA_AGENT_TYPES`] — the schema
///   vocabulary, deliberately wider than the two agents this build can detect,
///   so the message distinguishes "not a thing" from "not here".
/// - **A valid name that is not on this host** fails too, naming it. It is
///   still a typo — the operator believes they are covering an agent they are
///   not — and quietly doing nothing is how somebody ends up trusting an
///   uncaptured host.
/// - **A detected agent nobody named** is skipped in silence. That is the flag
///   working, not a condition to report.
///
/// # Errors
///
/// `OL-1400` in both failing directions: the agent asked for is not one this
/// command can act on. No new code — the existing one already means exactly
/// that, and its docs page is where per-agent install instructions live.
pub fn select_agents(
    agents: Vec<DetectedAgent>,
    wanted: &[String],
) -> Result<Vec<DetectedAgent>, OlError> {
    if wanted.is_empty() {
        return Ok(agents);
    }

    let known = crate::generated::known_values::SCHEMA_AGENT_TYPES;

    for name in wanted {
        if !known.contains(&name.as_str()) {
            return Err(OlError::new(
                ERR_HOOK_AGENT_NOT_FOUND,
                format!("Unknown agent type '{name}'"),
            )
            .with_suggestion(format!("Valid values: {}.", known.join(", ")))
            .with_docs("https://docs.openlatch.ai/errors/OL-1400"));
        }
        if !agents.iter().any(|a| a.agent_type() == name) {
            return Err(OlError::new(
                ERR_HOOK_AGENT_NOT_FOUND,
                format!("Agent '{name}' was not detected on this machine"),
            )
            .with_suggestion(format!(
                "Detected agents: {}. Omit --agent to cover every one of them.",
                if agents.is_empty() {
                    "none".to_string()
                } else {
                    agents
                        .iter()
                        .map(DetectedAgent::agent_type)
                        .collect::<Vec<_>>()
                        .join(", ")
                }
            ))
            .with_docs("https://docs.openlatch.ai/errors/OL-1400"));
        }
    }

    // Detection order, not flag order: `detect_all`'s declaration order is
    // load-bearing everywhere else, and `--agent codex-cli --agent claude-code`
    // must not reverse it.
    Ok(agents
        .into_iter()
        .filter(|a| wanted.iter().any(|w| w == a.agent_type()))
        .collect())
}

/// Env var name carrying the daemon bearer token to a hook subprocess.
///
/// Written into the agent's `env` block by [`install_hooks`] and removed by
/// [`remove_hooks`]. Declared here, once, because those two must agree on the
/// name: while each held its own local copy, install wrote two `env` keys that
/// uninstall did not know about, and `openlatch uninstall --purge` left the
/// token — in plaintext — in `settings.json`.
pub const OPENLATCH_TOKEN_ENV: &str = "OPENLATCH_TOKEN";

/// Env var name pinning the daemon port for a hook subprocess. Same
/// install/remove symmetry as [`OPENLATCH_TOKEN_ENV`].
pub const OPENLATCH_PORT_ENV: &str = "OPENLATCH_PORT";

/// Install OpenLatch HTTP hook entries into the agent's config.
///
/// Every event in `binding.hook_event_types()` is written. Re-running this
/// function is idempotent: existing OpenLatch entries are replaced rather than
/// duplicated. Hooks from other tools are never touched.
///
/// # Arguments
///
/// - `binding`: the agent binding to install into — from
///   [`detect_agents`]/[`detect_agent`], or any other `AgentBinding`
/// - `port`: the daemon's listen port (written into each hook URL)
/// - `token`: the bearer token value — for an agent whose
///   [`DaemonChannel`](binding::DaemonChannel) is `EnvVars`, only the *env var
///   name* reaches settings.json; the actual token is stored separately
///
/// # Errors
///
/// - `OL-1401` if settings.json cannot be read or written.
/// - `OL-1402` if settings.json contains malformed JSONC.
/// - `OL-1404` if [`resolve_hook_binary_path`] does not resolve to an existing
///   file. settings.json is left untouched: writing a command that cannot
///   resolve is worse than not writing one.
pub fn install_hooks(
    binding: &dyn AgentBinding,
    port: u16,
    token: &str,
) -> Result<HookInstallResult, OlError> {
    let settings_path = binding.hook_config_path();
    let event_types = binding.hook_event_types();

    // The env-var pair, when this agent's channel is one. An agent on
    // `OpenlatchDirArg` gets no `env` key at all — for Codex that is not a
    // preference but a hard requirement, since its hooks file is
    // `deny_unknown_fields`.
    let env_keys = match binding.daemon_channel() {
        binding::DaemonChannel::EnvVars {
            token: token_env,
            port: port_env,
        } => Some((token_env, port_env)),
        binding::DaemonChannel::OpenlatchDirArg => None,
    };

    let openlatch_dir = crate::config::openlatch_dir();
    let hook_bin = resolve_hook_binary_path();

    // The command we are about to write into every hook entry must point
    // at a binary that exists. `resolve_hook_binary_path()` ends in a
    // bare `"openlatch-hook"` that relies on the agent's PATH, and when
    // that name is not on it every hook on the machine dies with exit
    // 127 — silently, because the hook fails open. Callers stage the
    // binary first (`hooks::staging::stage_hook_binary`); this is the
    // post-condition that makes "an install that cannot resolve its own
    // hook binary" impossible to write rather than merely unlikely.
    if !hook_bin.is_file() {
        return Err(OlError::new(
            ERR_HOOK_BINARY_UNRESOLVABLE,
            format!(
                "Refusing to install hooks: '{}' is not an existing file",
                hook_bin.display()
            ),
        )
        .with_suggestion(
            "Run 'openlatch doctor --fix' to stage the hook binary, or point \
             OPENLATCH_HOOK_BIN at an existing one.",
        ));
    }

    let key_store = HmacKeyStore::new(&openlatch_dir);
    let hmac_key = key_store.load_or_create()?;

    let token_fp = crate::core::hook_state::key::key_fingerprint(token.as_bytes());
    let settings_path_hash = hook_state::hash_settings_path(&settings_path);

    let mut entries_with_markers: Vec<(String, serde_json::Value, String)> = Vec::new();
    for &et in event_types {
        let entry_id = uuid::Uuid::now_v7().to_string();
        let mut marker = OpenlatchMarker::new(entry_id.clone());

        let mut entry = binding.build_hook_entry(et, &hook_bin, port, &marker);

        let hmac_value = compute_entry_hmac(&entry, &hmac_key)?;
        marker = marker.with_hmac(hmac_value.clone());

        let marker_value = serde_json::to_value(&marker).expect("OpenlatchMarker serializes");
        entry["_openlatch"] = marker_value;

        entries_with_markers.push((et.to_string(), entry, entry_id));
    }

    let jsonc_entries: Vec<(String, serde_json::Value)> = entries_with_markers
        .iter()
        .map(|(et, entry, _)| (et.clone(), entry.clone()))
        .collect();

    let token_owned = token.to_string();
    let actions = std::cell::RefCell::new(Vec::new());

    atomic::atomic_rewrite_jsonc(&settings_path, |root| {
        let a = jsonc::insert_hook_entries_cst(root, &jsonc_entries)?;
        if let Some((token_env, port_env)) = env_keys {
            jsonc::set_env_var_cst(root, token_env, &token_owned)?;
            // Pin the port too, not just the token.
            //
            // The hook resolves its port as OPENLATCH_PORT (its own env,
            // populated by the agent from this settings block) ->
            // <openlatch_dir>/daemon.port -> 7443. OPENLATCH_DIR is
            // deliberately NOT in a hook entry's allowedEnvVars, so a
            // daemon on a non-default directory is unreachable by the
            // middle step: the hook reads the DEFAULT directory's port
            // file and connects to the wrong daemon, or none at all.
            // Because the hook fails open — prints `{}`, exits 0, spools
            // to fallback.jsonl — the whole install looks healthy while
            // every event is dropped.
            //
            // Writing the concrete port here removes the dependency on
            // directory discovery entirely. It is already declared in each
            // entry's allowedEnvVars, so it reaches the subprocess.
            jsonc::set_env_var_cst(root, port_env, &port.to_string())?;
        }
        *actions.borrow_mut() = a;
        Ok(())
    })?;

    let actions = actions.into_inner();

    let mut state =
        HookStateFile::load(&openlatch_dir)?.unwrap_or_else(|| HookStateFile::new("kid-01".into()));

    for (et, entry, entry_id) in &entries_with_markers {
        let hmac_val = entry["_openlatch"]["hmac"]
            .as_str()
            .map(str::to_string)
            .unwrap_or_default();

        state.upsert_entry(StateEntry {
            id: entry_id.clone(),
            agent: binding.agent_type().into(),
            settings_path_hash: settings_path_hash.clone(),
            hook_event: et.clone(),
            expected_entry_hmac: hmac_val,
            daemon_port_at_install: port,
            daemon_token_fp: token_fp.clone(),
            v: 1,
        });
    }

    if let Err(e) = state.save(&openlatch_dir) {
        tracing::warn!(
            code = crate::error::ERR_STATE_FILE_WRITE_FAILED,
            error = %e,
            "failed to write hook state file — hooks installed but state file out of sync"
        );
    }

    let entries = event_types
        .iter()
        .zip(actions)
        .map(|(&et, action)| HookEntryStatus {
            event_type: et.to_string(),
            action,
        })
        .collect();

    Ok(HookInstallResult { entries })
}

/// Remove everything [`install_hooks`] wrote into the detected agent's config.
///
/// Two halves, both of them ours:
///
/// - hook entries carrying the OpenLatch ownership marker (either the legacy
///   `"_openlatch": true` boolean or the current tamper-evident object);
/// - the two `env` keys the binding's [`DaemonChannel`] names — for an
///   `OpenlatchDirArg` agent there are none, because install wrote none.
///
/// Hooks and env vars belonging to other tools are never touched. The `env`
/// half is not a courtesy: it used to be missing, so `openlatch uninstall`
/// removed the hooks and left the bearer token in plaintext in `settings.json`
/// next to a port no daemon answers on — `--purge` included, which is the one
/// command that promises to leave nothing behind. Uninstall is the inverse of
/// install or it is a half-uninstall.
///
/// # Errors
///
/// - `OL-1401` if settings.json cannot be read or written.
/// - `OL-1402` if settings.json contains malformed JSONC.
pub fn remove_hooks(binding: &dyn AgentBinding) -> Result<(), OlError> {
    let settings_path = binding.hook_config_path();
    if !settings_path.exists() {
        return Ok(());
    }

    // Ask the binding which keys install actually wrote, exactly as `install_hooks`
    // does — same `match`, same source of truth. Hardcoding the two constants here
    // would make uninstall Claude-shaped in shared code: a second binding whose
    // `EnvVars` channel names different keys would leave its bearer token behind in
    // plaintext, and an `OpenlatchDirArg` agent has no `env` block to strip at all.
    // For Claude Code the channel answers exactly `OPENLATCH_TOKEN_ENV` /
    // `OPENLATCH_PORT_ENV`, so the bytes removed today are unchanged.
    let env_keys = match binding.daemon_channel() {
        binding::DaemonChannel::EnvVars {
            token: token_env,
            port: port_env,
        } => Some((token_env, port_env)),
        binding::DaemonChannel::OpenlatchDirArg => None,
    };

    atomic::atomic_rewrite_jsonc(&settings_path, |root| {
        jsonc::remove_owned_entries_cst(root)?;
        if let Some((token_env, port_env)) = env_keys {
            jsonc::remove_env_var_cst(root, token_env)?;
            jsonc::remove_env_var_cst(root, port_env)?;
        }
        Ok(())
    })?;

    Ok(())
}

// ---------------------------------------------------------------------------
// Model-boundary config wiring (D-07 / D-01)
// ---------------------------------------------------------------------------

/// Env var name Claude Code reads for the model-provider base URL.
pub const ANTHROPIC_BASE_URL_ENV: &str = "ANTHROPIC_BASE_URL";
/// Env var name Claude Code reads for extra static request headers.
/// Newline-separated `Name: Value` entries (Anthropic SDK convention).
pub const ANTHROPIC_CUSTOM_HEADERS_ENV: &str = "ANTHROPIC_CUSTOM_HEADERS";
/// Both spellings of the agent's proxy-bypass variable.
///
/// Both, always. Node reads `NO_PROXY`; a great deal of tooling in the same process tree
/// reads `no_proxy`; and which one wins is not something this client gets to decide inside
/// somebody else's runtime. Writing one and not the other is a coin flip on whether the
/// bypass applies at all.
const NO_PROXY_ENV_KEYS: [&str; 2] = ["NO_PROXY", "no_proxy"];

/// The entries D-24 guarantees are present, in the order they are appended.
const LOOPBACK_BYPASS_ENTRIES: [&str; 2] = ["127.0.0.1", "localhost"];

/// Merge the loopback entries into an existing comma-separated bypass list.
///
/// Verified against a live Claude Code (2026-08): **it has no implicit loopback bypass.**
/// With a corporate `HTTPS_PROXY` in the environment and the model boundary enabled, the
/// agent issues `CONNECT 127.0.0.1:7600` to the corporate proxy, which has no route to the
/// customer's own laptop and answers 502. Every model call on the host fails, and nothing
/// in any log looks like a proxy problem. This is the fix, and it has to live in the
/// agent's own environment because the agent is the process making the connection.
///
/// Additive-only, byte-for-byte, in the `merge_install_id_header` discipline: every
/// pre-existing entry survives in its original order and its original spelling. A customer
/// bypass list is a security control in its own right, and reordering or normalising it is
/// a change we have no mandate to make.
fn merge_loopback_entries(existing: Option<&str>) -> String {
    let mut entries: Vec<String> = existing
        .unwrap_or_default()
        .split(',')
        .map(str::trim)
        .filter(|e| !e.is_empty())
        .map(str::to_string)
        .collect();
    for wanted in LOOPBACK_BYPASS_ENTRIES {
        // Case-insensitive, because `LOCALHOST` and `localhost` are the same host and
        // appending a second spelling is noise the customer has to read past forever.
        if !entries.iter().any(|e| e.eq_ignore_ascii_case(wanted)) {
            entries.push(wanted.to_string());
        }
    }
    entries.join(",")
}

/// `true` when a single custom-header line declares the OpenLatch install-id
/// header (name compared case-insensitively).
///
/// The name is a parameter rather than a module constant: it is declared by the
/// agent's own [`BoundaryWiring`](binding::BoundaryWiring), so the writer, the
/// merger and the stripper cannot disagree with the binding about which header
/// is ours.
fn is_install_id_line(line: &str, header: &str) -> bool {
    line.split_once(':')
        .map(|(name, _)| name.trim().eq_ignore_ascii_case(header))
        .unwrap_or(false)
}

/// Merge our install-id line INTO an existing `ANTHROPIC_CUSTOM_HEADERS` value,
/// preserving every customer line and replacing only a prior install-id line.
/// Additive-only: corporate proxy/routing/auth headers survive untouched.
///
/// Reuses [`strip_install_id_header`] for the parse-and-drop-our-line pass, then
/// appends our current line. `kept.is_empty()` is byte-equivalent to the old
/// empty-Vec check: `strip_install_id_header` joins only non-blank customer
/// lines with `\n`, so its result is empty exactly when no customer line remains.
fn merge_install_id_header(existing: Option<&str>, header: &str, install_id: &str) -> String {
    let kept = existing
        .map(|value| strip_install_id_header(value, header))
        .unwrap_or_default();
    let our_line = format!("{header}: {install_id}");
    if kept.is_empty() {
        our_line
    } else {
        format!("{kept}\n{our_line}")
    }
}

/// Strip OUR install-id line(s) from an existing `ANTHROPIC_CUSTOM_HEADERS`
/// value, returning the remaining customer lines (possibly empty).
fn strip_install_id_header(existing: &str, header: &str) -> String {
    existing
        .split('\n')
        .filter(|line| !line.trim().is_empty() && !is_install_id_line(line, header))
        .collect::<Vec<_>>()
        .join("\n")
}

/// `true` when `value` is a loopback base URL OpenLatch would have written —
/// host `127.0.0.1`, any port, http or https. A customer-set base URL pointing
/// anywhere else must be left untouched on disable.
///
/// `pub(crate)` because the `TomlProvider` convention asks the identical
/// question of a `[model_providers.<name>].base_url`
/// (`codex_cli::provider_table_is_ours`). One predicate, so the two conventions
/// cannot disagree about what "ours" means.
pub(crate) fn is_openlatch_loopback_base_url(value: &str) -> bool {
    reqwest::Url::parse(value.trim())
        .ok()
        .and_then(|u| u.host_str().map(|h| h == "127.0.0.1"))
        .unwrap_or(false)
}

/// The file this agent's boundary wiring is written into, when it has a request
/// plane at all.
///
/// **Not [`AgentBinding::hook_config_path`], and the difference is easy to
/// miss.** Claude Code's hooks and its `ANTHROPIC_BASE_URL` share one
/// `settings.json`; Codex's do not — its hooks live in `hooks.json` and its
/// provider table in `config.toml`. Every log line, remedy and diagnostic that
/// names "the file we wired" names this one, so the two layers cannot drift
/// into naming a file the writer never touched.
pub fn boundary_config_path(binding: &dyn AgentBinding) -> Option<PathBuf> {
    match binding.boundary_wiring()?.endpoint {
        binding::EndpointConvention::EnvVars { .. } => Some(binding.hook_config_path()),
        binding::EndpointConvention::TomlProvider { .. } => {
            Some(codex_cli::config_toml_path(&binding.config_dir()))
        }
    }
}

/// Point the agent at the model-boundary listener, in whatever way that agent
/// names its model provider.
///
/// **Only the process holding `port` may call this.** The daemon does, right
/// after [`crate::boundary::bind_pinned`] returns `Ok` — never before, and never
/// from a process that will not go on to serve that port. Writing the base URL
/// on the strength of an intention to bind is what pointed every agent on the
/// machine at a port nobody held.
///
/// The binding decides the convention, not this function:
///
/// - [`EndpointConvention::EnvVars`] — the JSONC path on
///   [`AgentBinding::hook_config_path`]: the base URL, the install-id header and
///   D-24's `NO_PROXY` / `no_proxy` loopback merge, with the two variable names
///   read from the variant rather than from an `ANTHROPIC_*` literal.
/// - [`EndpointConvention::TomlProvider`] — the format-preserving
///   `[model_providers.<name>]` write on the agent's `config.toml`. **A
///   different file from that agent's hooks file**; do not assume one path per
///   agent.
/// - No [`AgentBinding::boundary_wiring`] at all — nothing is written, and that
///   is not an error. An agent with no request plane is a question that does
///   not apply.
///
/// Both arms record the endpoint the agent named **before** us, so uninstall can
/// put it back ([`boundary_endpoints`]). The record is taken **only when the
/// current value is not already ours**: on a re-install it already is, and
/// recording it would overwrite the customer's real prior with our own value.
///
/// D-01 ships the plain-`http://` base URL as the default (the HTTPS +
/// `NODE_EXTRA_CA_CERTS` fallback is specified in `boundary::bind_pinned`'s
/// docs but conditional on the empirical loopback spike). `install_id` MUST be
/// PII-free — it reaches the provider on every request (F-22); the existing
/// `agent_id` is used verbatim (no new persisted field is introduced).
///
/// # Errors
///
/// Propagates whatever the convention's writer reports — a malformed agent
/// config, an unwritable file, or (`TomlProvider` only)
/// [`crate::error::ERR_BOUNDARY_FOREIGN_PROVIDER`] when a provider table of our
/// name exists and is somebody else's.
pub fn write_boundary_config(
    binding: &dyn AgentBinding,
    port: u16,
    install_id: &str,
) -> Result<(), OlError> {
    let Some(wiring) = binding.boundary_wiring() else {
        return Ok(());
    };
    let agent = binding.agent_type();
    match wiring.endpoint {
        binding::EndpointConvention::EnvVars { base_url, headers } => {
            let settings_path = binding.hook_config_path();
            let our_base_url = format!("http://127.0.0.1:{port}");
            atomic::atomic_rewrite_jsonc(&settings_path, |root| {
                // D-10 — remember what the agent pointed at before us, but only
                // when that value is not already ours. A second install
                // otherwise records our own loopback URL and uninstall
                // "restores" a dead port.
                let current = jsonc::get_env_var_cst(root, base_url);
                let already_ours = current
                    .as_deref()
                    .map(is_openlatch_loopback_base_url)
                    .unwrap_or(false);
                if !already_ours {
                    boundary_endpoints::record(agent, current)?;
                }
                jsonc::set_env_var_cst(root, base_url, &our_base_url)?;
                // Additive-only: merge our install-id line into any pre-existing
                // custom-headers value (corporate proxy/routing/auth headers)
                // rather than clobbering the whole value.
                let existing = jsonc::get_env_var_cst(root, headers);
                let merged = merge_install_id_header(
                    existing.as_deref(),
                    wiring.install_id_header,
                    install_id,
                );
                jsonc::set_env_var_cst(root, headers, &merged)?;
                // D-24 — the base URL above points the agent at a loopback
                // listener, and on a proxied estate the agent would tunnel to it
                // through the corporate proxy and get a 502. Both spellings,
                // merge-preserving. Never recorded and never restored: see
                // `remove_boundary_config`.
                for key in NO_PROXY_ENV_KEYS {
                    let existing = jsonc::get_env_var_cst(root, key);
                    let merged = merge_loopback_entries(existing.as_deref());
                    jsonc::set_env_var_cst(root, key, &merged)?;
                }
                Ok(())
            })
        }
        binding::EndpointConvention::TomlProvider {
            provider_name,
            wire_api,
        } => {
            let config_toml = codex_cli::config_toml_path(&binding.config_dir());
            // RECORD BEFORE THE WRITE COMMITS. The obvious order — write, then
            // record what it displaced — has a window: if recording fails or
            // the process dies between the two, the customer's file points at
            // us with no restoration record, and the eventual uninstall reads
            // "nothing was here before" and deletes a setting they had. The
            // reverse window is harmless by comparison: a record with no write
            // is never consumed, because uninstall's ownership test sees a
            // provider table that is not ours and returns early.
            let prior = codex_cli::read_prior_provider(&config_toml, provider_name)?;
            if let codex_cli::Prior::Theirs(ref p) = prior {
                boundary_endpoints::record(agent, p.clone())?;
            }
            let write = codex_cli::write_provider_table(
                &config_toml,
                provider_name,
                wire_api,
                wiring.install_id_header,
                port,
                install_id,
            );
            if write.is_err() && matches!(prior, codex_cli::Prior::Theirs(_)) {
                // Best effort: the write we recorded for did not happen, so the
                // record describes nothing. Leaving it is survivable (see
                // above); clearing it is tidier.
                boundary_endpoints::forget(agent);
            }
            write.map(|_| ())
        }
    }
}

/// Remove the model-boundary wiring, and put back whatever the agent named
/// before it.
///
/// Called by the daemon when it stops holding the pinned port (teardown), or
/// when it starts with the boundary disabled (reconciliation after a SIGKILL or
/// a config change); by `openlatch stop` as a net for the escalation paths where
/// the daemon never got to run its own teardown; and by `openlatch uninstall`.
///
/// **Idempotent, because it runs two or three times per uninstall.** Both arms
/// test ownership *before* consuming the record, so a second pass finds nothing
/// of ours, changes nothing, and cannot delete the pointer the first pass
/// restored.
///
/// Additive-safe reversal:
///
/// - The base URL / provider table is reclaimed ONLY while it still names our
///   loopback listener; a customer-set endpoint is left untouched.
/// - The custom-headers value loses only OUR install-id line(s); any customer
///   headers survive. If nothing remains, the key is dropped entirely.
/// - **`NO_PROXY` / `no_proxy` are deliberately left alone**, loopback entries included.
///   `127.0.0.1` and `localhost` carry no ownership marker: a customer whose bypass list
///   already named them, or who added them for their own tooling, is indistinguishable
///   from one who got them from us, and stripping the entries would break their setup to
///   tidy ours. Leaving a host's own loopback in its own bypass list costs nothing — it is
///   the correct value for that host whether OpenLatch is installed or not. This is a
///   contract, not an oversight: `tests/cli_contract.rs` asserts the entries survive.
///   It follows that the bypass is never *recorded* either — §2's record covers
///   the endpoint only.
///
/// A no-op when the file, the keys or the request plane are absent.
pub fn remove_boundary_config(binding: &dyn AgentBinding) -> Result<(), OlError> {
    let Some(wiring) = binding.boundary_wiring() else {
        return Ok(());
    };
    let agent = binding.agent_type();
    match wiring.endpoint {
        binding::EndpointConvention::EnvVars { base_url, headers } => {
            let settings_path = binding.hook_config_path();
            if !settings_path.exists() {
                return Ok(());
            }
            atomic::atomic_rewrite_jsonc(&settings_path, |root| {
                // Only reclaim the base URL if it is OUR loopback URL — and ask
                // that BEFORE taking the record, or a second pass drops the
                // customer's recorded prior on the floor.
                if let Some(current) = jsonc::get_env_var_cst(root, base_url) {
                    if is_openlatch_loopback_base_url(&current) {
                        // D-10 — put the customer's endpoint back.
                        //
                        // `Some(None)` is "they named none". `None` is "no
                        // record at all", which is an install that predates the
                        // record store — and it removes the key too, because
                        // the daemon's stale-wiring reconciliation is exactly
                        // that case: a SIGKILLed daemon leaves a base URL on
                        // disk with no record, and the next start has to clear
                        // it or every session on the host dies on a dead port
                        // (`tests/boundary_wiring.rs`'s
                        // `startup_clears_a_stale_base_url_when_the_boundary_is_off`).
                        // The second-uninstall-pass hazard those two arms are
                        // otherwise told apart for is already closed one line
                        // up: the ownership test above is false once the key is
                        // gone or the customer's own value is back.
                        //
                        // A replace, never remove-then-add: `set_env_var_cst`
                        // leaves the key where the customer had it, with the
                        // comments around it.
                        // PEEK, not take. `take` deletes the entry first, so a
                        // rewrite that then failed at the rename would leave the
                        // agent pointed at us with its real prior endpoint gone
                        // for good. The record is cleared after the write lands.
                        match boundary_endpoints::peek(agent) {
                            Some(Some(prior)) => jsonc::set_env_var_cst(root, base_url, &prior)?,
                            Some(None) | None => jsonc::remove_env_var_cst(root, base_url)?,
                        }
                    }
                }
                // Strip only our install-id line from the custom-headers value.
                if let Some(current) = jsonc::get_env_var_cst(root, headers) {
                    let remainder = strip_install_id_header(&current, wiring.install_id_header);
                    if remainder.trim().is_empty() {
                        jsonc::remove_env_var_cst(root, headers)?;
                    } else {
                        jsonc::set_env_var_cst(root, headers, &remainder)?;
                    }
                }
                Ok(())
            })?;
            // Cleared only now, after the atomic rewrite has landed. See the
            // `peek` comment above: consuming the record before the rename
            // would lose the customer's prior endpoint on a failed write.
            boundary_endpoints::forget(agent);
            Ok(())
        }
        binding::EndpointConvention::TomlProvider { provider_name, .. } => {
            let config_toml = codex_cli::config_toml_path(&binding.config_dir());
            // Ownership first, record second: `take` deletes the entry, and an
            // implementation that takes before it knows the table is ours drops
            // the customer's recorded prior on the second uninstall pass.
            let is_ours = std::fs::read_to_string(&config_toml)
                .ok()
                .and_then(|raw| raw.parse::<toml_edit::DocumentMut>().ok())
                .and_then(|doc| codex_cli::provider_table_is_ours(&doc, provider_name))
                == Some(true);
            if !is_ours {
                return Ok(());
            }
            // PEEK, then clear only once the rewrite has landed — same reason
            // as the arm above: `take` would drop the customer's real prior on
            // a rename that failed.
            let result = codex_cli::remove_provider_table(
                &config_toml,
                provider_name,
                boundary_endpoints::peek(agent),
            );
            if result.is_ok() {
                boundary_endpoints::forget(agent);
            }
            result
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    /// D-24's merge, in isolation.
    #[test]
    fn loopback_entries_are_added_when_the_list_is_empty() {
        assert_eq!(super::merge_loopback_entries(None), "127.0.0.1,localhost");
        assert_eq!(
            super::merge_loopback_entries(Some("")),
            "127.0.0.1,localhost"
        );
    }

    /// A customer bypass list is a security control in its own right. Every entry keeps
    /// its place and its spelling.
    #[test]
    fn customer_entries_survive_byte_for_byte() {
        assert_eq!(
            super::merge_loopback_entries(Some("internal.corp,10.0.0.0/8,.corp.example")),
            "internal.corp,10.0.0.0/8,.corp.example,127.0.0.1,localhost"
        );
    }

    /// Idempotent, and case-insensitively so: re-running `init` must not grow the list by
    /// two entries every time, and `LOCALHOST` is the same host as `localhost`.
    #[test]
    fn the_merge_is_idempotent() {
        let once = super::merge_loopback_entries(Some("internal.corp"));
        let twice = super::merge_loopback_entries(Some(&once));
        assert_eq!(once, twice);
        assert_eq!(
            super::merge_loopback_entries(Some("LOCALHOST,internal.corp")),
            "LOCALHOST,internal.corp,127.0.0.1"
        );
    }

    /// Whitespace an operator left around their own entries is not a reason to add a
    /// duplicate.
    #[test]
    fn spacing_does_not_produce_duplicates() {
        assert_eq!(
            super::merge_loopback_entries(Some(" localhost , internal.corp ")),
            "localhost,internal.corp,127.0.0.1"
        );
    }

    /// Smoke-test detect_agent when ~/.claude/ does NOT exist.
    ///
    /// We override HOME so that dirs::home_dir() points to an empty tempdir,
    /// and clear every config-dir seam that would win over it.
    #[test]
    #[cfg(unix)]
    fn test_detect_agent_returns_ol_1400_when_no_claude_dir() {
        use super::detect_agent;
        use crate::error::ERR_HOOK_AGENT_NOT_FOUND;

        // Every config-dir seam must be controlled, and controlled exclusively:
        // each `detect` honours its own variable *over* $HOME, and other suites
        // set them concurrently. See `claude_code::CONFIG_DIR_ENV_LOCK`, and
        // `codex_cli::CONFIG_DIR_ENV_LOCK` — taken last, the ordering rule for
        // every test that needs both. `$CODEX_HOME` joined this list when
        // `detect_agents` gained its Codex arm: redirecting `$HOME` alone hides
        // `~/.codex` but not an exported `CODEX_HOME`, and this assertion is
        // that NO agent is found.
        let _env = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _codex_env = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let prev_claude = std::env::var(crate::hooks::claude_code::CONFIG_DIR_ENV).ok();
        let prev_codex = std::env::var(crate::hooks::codex_cli::CONFIG_DIR_ENV).ok();
        std::env::remove_var(crate::hooks::claude_code::CONFIG_DIR_ENV);
        std::env::remove_var(crate::hooks::codex_cli::CONFIG_DIR_ENV);
        // Override HOME so neither ~/.claude/ nor ~/.codex/ exists.
        std::env::set_var("HOME", dir.path());
        let result = detect_agent();
        std::env::remove_var("HOME");
        if let Some(v) = prev_claude {
            std::env::set_var(crate::hooks::claude_code::CONFIG_DIR_ENV, v);
        }
        if let Some(v) = prev_codex {
            std::env::set_var(crate::hooks::codex_cli::CONFIG_DIR_ENV, v);
        }

        let err = result.unwrap_err();
        assert_eq!(
            err.code, ERR_HOOK_AGENT_NOT_FOUND,
            "Expected OL-1400, got {}",
            err.code
        );
    }

    // -----------------------------------------------------------------------
    // Boundary config wiring — additive-only guarantee (FIX 2)
    // -----------------------------------------------------------------------

    use super::{remove_boundary_config, write_boundary_config, ANTHROPIC_CUSTOM_HEADERS_ENV};
    use crate::hooks::binding::test_support::FakeBinding;
    use crate::hooks::binding::{BoundaryWiring, EndpointConvention};

    /// An `EnvVars` agent rooted at `dir`, carrying Claude Code's own two
    /// variable names and header — the binding these tests drive shared code
    /// through, rather than a `ClaudeCodeBinding` under a config-dir env lock.
    fn envvars_agent(dir: &std::path::Path) -> FakeBinding {
        FakeBinding {
            agent_type: "claude-code",
            config_dir: dir.to_path_buf(),
            boundary_wiring: Some(BoundaryWiring {
                wire_format: crate::boundary::wire_format::WireFormat::AnthropicMessages,
                endpoint: EndpointConvention::EnvVars {
                    base_url: super::ANTHROPIC_BASE_URL_ENV,
                    headers: super::ANTHROPIC_CUSTOM_HEADERS_ENV,
                },
                install_id_header: "x-openlatch-install-id",
            }),
            ..Default::default()
        }
    }

    /// Run `f` with `OPENLATCH_DIR` pointed at a tempdir, under **the** lock for
    /// that variable.
    ///
    /// Not optional hygiene: the writer records the endpoint the agent named
    /// before us into `$OPENLATCH_DIR/boundary-endpoints.json`, so a test that
    /// left the variable alone would write the developer's real record.
    fn with_openlatch_dir<T>(f: impl FnOnce() -> T) -> T {
        let _guard = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().expect("tempdir");
        let prev = std::env::var_os("OPENLATCH_DIR");
        std::env::set_var("OPENLATCH_DIR", tmp.path());
        let out = f();
        match prev {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }
        out
    }

    /// Read a settings.json file back as plain JSON for assertions.
    fn read_env(path: &std::path::Path) -> serde_json::Value {
        let raw = std::fs::read_to_string(path).unwrap();
        serde_json::from_str(&raw).unwrap()
    }

    #[test]
    fn boundary_enable_preserves_existing_custom_headers() {
        // (a) A customer already ships a corporate header; enable must append
        // our install-id line, keeping theirs.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_CUSTOM_HEADERS":"x-corp-proxy: foo"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| write_boundary_config(&agent, 7600, "agt_x").unwrap());

        let v = read_env(&path);
        let headers = v["env"][ANTHROPIC_CUSTOM_HEADERS_ENV].as_str().unwrap();
        assert!(
            headers.contains("x-corp-proxy: foo"),
            "customer header must survive enable: {headers}"
        );
        assert!(
            headers.contains("x-openlatch-install-id: agt_x"),
            "our install-id line must be added: {headers}"
        );
        assert_eq!(v["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:7600");
    }

    #[test]
    fn boundary_disable_keeps_customer_headers_and_drops_ours() {
        // (b) After enable, disable must remove ONLY our line — the corporate
        // header (and the key itself) remain.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_CUSTOM_HEADERS":"x-corp-proxy: foo"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            write_boundary_config(&agent, 7600, "agt_x").unwrap();
            remove_boundary_config(&agent).unwrap();
        });

        let v = read_env(&path);
        let headers = v["env"][ANTHROPIC_CUSTOM_HEADERS_ENV].as_str().unwrap();
        assert!(
            headers.contains("x-corp-proxy: foo"),
            "customer header must remain after disable: {headers}"
        );
        assert!(
            !headers.contains("x-openlatch-install-id"),
            "our install-id line must be gone: {headers}"
        );
        // Our loopback base URL was reclaimed.
        assert!(v["env"].get("ANTHROPIC_BASE_URL").is_none());
    }

    #[test]
    fn boundary_disable_removes_headers_key_when_only_ours_existed() {
        // (c) When only our line existed, disable drops the key entirely.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(&path, "{}").unwrap();

        with_openlatch_dir(|| {
            write_boundary_config(&agent, 7600, "agt_x").unwrap();
            remove_boundary_config(&agent).unwrap();
        });

        let v = read_env(&path);
        assert!(
            v["env"].get(ANTHROPIC_CUSTOM_HEADERS_ENV).is_none(),
            "an all-ours header value must be removed entirely: {v}"
        );
    }

    #[test]
    fn boundary_disable_leaves_non_loopback_base_url_untouched() {
        // (d) A customer base URL pointing at a corporate gateway must survive
        // disable (we only reclaim our own 127.0.0.1 loopback URL).
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gateway.corp.example"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| remove_boundary_config(&agent).unwrap());

        let v = read_env(&path);
        assert_eq!(
            v["env"]["ANTHROPIC_BASE_URL"], "https://gateway.corp.example",
            "a non-loopback base URL must be left untouched: {v}"
        );
    }

    /// **The existing-gap fix (D-10).** A customer whose Claude Code already
    /// pointed at a corporate gateway got that value clobbered on install and
    /// never got it back: the writer overwrote `ANTHROPIC_BASE_URL`
    /// unconditionally, and the remover only knew how to delete the key.
    ///
    /// Fails on the pre-D-10 code, which is the point.
    #[test]
    fn claude_boundary_config_restores_a_prior_base_url() {
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gw.example"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            write_boundary_config(&agent, 7600, "agt_x").unwrap();
            assert_eq!(
                read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
                "http://127.0.0.1:7600",
                "precondition: install really did point the agent at us"
            );
            remove_boundary_config(&agent).unwrap();
        });

        assert_eq!(
            read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
            "https://gw.example",
            "uninstall must put the customer's own gateway back"
        );
    }

    /// The re-install trap, on the `EnvVars` side. Two installs with no
    /// intervening uninstall: the second sees our own loopback URL on disk, and
    /// recording it would make uninstall "restore" a dead port.
    #[test]
    fn reinstall_keeps_the_first_installs_recorded_prior() {
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gw.example"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            write_boundary_config(&agent, 7600, "agt_x").unwrap();
            write_boundary_config(&agent, 7600, "agt_x").unwrap();
            remove_boundary_config(&agent).unwrap();
        });

        assert_eq!(
            read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
            "https://gw.example",
            "the second install must not have overwritten the recorded prior"
        );
    }

    // -----------------------------------------------------------------------
    // Uninstall is the inverse of install — the `env` half
    // -----------------------------------------------------------------------

    use super::{remove_hooks, AgentKind, DetectedAgent, OPENLATCH_PORT_ENV, OPENLATCH_TOKEN_ENV};

    /// A settings.json in the state `install_hooks` leaves behind: one owned
    /// hook entry, our two `env` keys, and a customer key beside them.
    fn installed_settings(dir: &std::path::Path) -> DetectedAgent {
        let settings_path = dir.join("settings.json");
        std::fs::write(
            &settings_path,
            r#"{
  "env": {
    "ANOTHER_TOOL_TOKEN": "keep-me",
    "OPENLATCH_TOKEN": "not-a-real-token",
    "OPENLATCH_PORT": "7443"
  },
  "hooks": {
    "Stop": [
      {"_openlatch": {"v": 1, "id": "x"}, "hooks": [{"type": "command", "command": "openlatch-hook"}]},
      {"hooks": [{"type": "command", "command": "sh other-tool.sh"}]}
    ]
  }
}"#,
        )
        .unwrap();
        DetectedAgent {
            kind: AgentKind::ClaudeCode,
            binding: std::sync::Arc::new(crate::hooks::bindings::claude_code::ClaudeCodeBinding {
                claude_dir: dir.to_path_buf(),
                settings_path,
            }),
        }
    }

    // -----------------------------------------------------------------------
    // The `env` block is written per DaemonChannel, not unconditionally
    // -----------------------------------------------------------------------

    /// Restores the variables `install_hooks` resolves its directories, its
    /// hook binary and its HMAC key from, on unwind as well as on success.
    ///
    /// It is save/restore only — the mutual exclusion comes from the locks the
    /// caller holds. `CODEX_HOME` rides along here rather than in a guard of
    /// its own because it is absent from `daemon::identity::MANAGED`, so
    /// nothing else would put it back.
    struct EnvVars(Vec<(&'static str, Option<std::ffi::OsString>)>);

    impl EnvVars {
        fn set<const N: usize>(pairs: [(&'static str, &std::ffi::OsStr); N]) -> Self {
            let saved = pairs
                .iter()
                .map(|(key, _)| (*key, std::env::var_os(key)))
                .collect();
            for (key, value) in pairs {
                std::env::set_var(key, value);
            }
            Self(saved)
        }
    }

    impl Drop for EnvVars {
        fn drop(&mut self) {
            for (key, value) in self.0.drain(..) {
                match value {
                    Some(v) => std::env::set_var(key, v),
                    None => std::env::remove_var(key),
                }
            }
        }
    }

    /// Site 4 of the containment move: the top-level `env` block is now written
    /// only when the binding's channel is `DaemonChannel::EnvVars`. Claude Code
    /// answers exactly that, so the block it produces is byte-identical to the
    /// one an unconditional write produced — an agent that cannot forward
    /// environment variables is the case that changed, and there is none in
    /// this build.
    #[test]
    fn env_channel_still_writes_the_env_block() {
        use crate::hooks::binding::AgentBinding;
        use crate::hooks::bindings::claude_code::ClaudeCodeBinding;

        // Three locks, in the crate's order — `OPENLATCH_DIR` first, then
        // `$CLAUDE_CONFIG_DIR`, then the hook-binary trio.
        // `config::OPENLATCH_DIR_ENV_LOCK` is **the** lock for `OPENLATCH_DIR`,
        // and this test writes that variable: the boundary-wiring tests above
        // hold it while they read the endpoint record back out of
        // `$OPENLATCH_DIR`, so without it this test's write lands under their
        // feet.
        let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let ol = tempfile::tempdir().unwrap();
        let claude = tempfile::tempdir().unwrap();
        let staged = tempfile::tempdir().unwrap();
        // `install_hooks` refuses to write a command naming a path that is not
        // an existing file, so the fake binary has to really be there.
        let hook_bin = staged.path().join("openlatch-hook");
        std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").unwrap();

        let _env = EnvVars::set([
            ("OPENLATCH_DIR", ol.path().as_os_str()),
            ("CLAUDE_CONFIG_DIR", claude.path().as_os_str()),
            ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str()),
            // `HmacKeyStore::load_or_create` is file-first and falls through to
            // the OS keychain, which on a developer's machine raises a GUI
            // dialog and blocks the whole suite behind it.
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
        ]);

        let binding = ClaudeCodeBinding {
            claude_dir: claude.path().to_path_buf(),
            settings_path: claude.path().join("settings.json"),
        };
        assert!(
            matches!(
                binding.daemon_channel(),
                super::binding::DaemonChannel::EnvVars { .. }
            ),
            "the premise of this test: Claude Code forwards named env vars"
        );

        super::install_hooks(&binding, 7443, "a-token").unwrap();

        let v = read_env(&binding.settings_path);
        assert_eq!(
            v["env"][OPENLATCH_TOKEN_ENV], "a-token",
            "an EnvVars channel still pins the token: {v}"
        );
        assert_eq!(
            v["env"][OPENLATCH_PORT_ENV], "7443",
            "and the port beside it: {v}"
        );
    }

    /// Uninstall used to remove the hook entries and stop there, leaving the
    /// bearer token — in plaintext — and a dead port in the agent's `env`
    /// block. `--purge`, the command that promises to leave nothing behind,
    /// left them too. Reported on a real machine after a purge.
    #[test]
    fn remove_hooks_takes_the_env_keys_install_wrote() {
        let dir = tempfile::tempdir().unwrap();
        let agent = installed_settings(dir.path());
        let settings_path = agent.settings_path();

        remove_hooks(&*agent.binding).unwrap();

        let v = read_env(&settings_path);
        for key in [OPENLATCH_TOKEN_ENV, OPENLATCH_PORT_ENV] {
            assert!(
                v["env"].get(key).is_none(),
                "install wrote {key}; uninstall must take it back: {v}"
            );
        }
    }

    /// The `env` block is shared. Only the two keys we wrote may go.
    #[test]
    fn remove_hooks_leaves_every_env_key_that_is_not_ours() {
        let dir = tempfile::tempdir().unwrap();
        let agent = installed_settings(dir.path());
        let settings_path = agent.settings_path();

        remove_hooks(&*agent.binding).unwrap();

        let v = read_env(&settings_path);
        assert_eq!(
            v["env"]["ANOTHER_TOOL_TOKEN"], "keep-me",
            "a key we never wrote must survive uninstall: {v}"
        );
        let stop = v["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 1, "only the owned entry may go: {v}");
        assert_eq!(stop[0]["hooks"][0]["command"], "sh other-tool.sh");
    }

    // -----------------------------------------------------------------------
    // Codex CLI: the hooks.json writer and its reversal
    // -----------------------------------------------------------------------

    /// One customer-owned `PostToolUse` group, exactly as a customer's own
    /// `hooks.json` carries one — no `_openlatch` marker, no `openlatch-hook`
    /// in its command, so nothing in the writer may claim it.
    const CUSTOMER_GROUP: &str = r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"echo mine","timeout":5}]}]}}"#;

    // `hook_config_path` is a trait method, and these tests hold the concrete
    // binding rather than a `dyn AgentBinding`.
    use crate::hooks::binding::AgentBinding as _;

    /// Everything an in-module install test must redirect, under the two locks
    /// that make it safe, with a real staged hook binary and a Codex CLI
    /// binding pointed at a temp `$CODEX_HOME`.
    ///
    /// Three of these redirections are not tidiness. `install_hooks` resolves
    /// `crate::config::openlatch_dir()` and then `HmacKeyStore::load_or_create`
    /// and a `HookStateFile` upsert under it, so a test that leaves
    /// `OPENLATCH_DIR` alone writes `agent: "codex-cli"` rows into the
    /// developer's — and the CI runner's — real `~/.openlatch/hook-state.json`,
    /// the file the live daemon's reconciler reads, and nothing fails.
    /// `OPENLATCH_SKIP_KEYRING` keeps the HMAC key off the OS keychain, whose
    /// dialog blocks the whole suite. And `OPENLATCH_HOOK_BIN` has to name a
    /// file that exists or `install_hooks` refuses with `OL-1404`.
    ///
    /// Lock order is `config::OPENLATCH_DIR_ENV_LOCK` then `HOOK_BIN_ENV_LOCK`
    /// then `codex_cli::CONFIG_DIR_ENV_LOCK`, everywhere: `OPENLATCH_DIR` has
    /// its own lock and it is taken first, and a config-directory lock is
    /// always taken last, or two tests deadlock by taking them in opposite
    /// orders.
    fn with_codex_install_env<T>(
        f: impl FnOnce(&crate::hooks::bindings::codex_cli::CodexCliBinding) -> T,
    ) -> T {
        use crate::hooks::bindings::codex_cli::CodexCliBinding;

        let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _codex_lock = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let ol = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let staged = tempfile::tempdir().unwrap();
        let hook_bin = staged.path().join("openlatch-hook");
        std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").unwrap();

        // Declared after the locks so it is dropped BEFORE them: a failing
        // assertion must not release the lock while the variables are still
        // redirected.
        let _env = EnvVars::set([
            ("OPENLATCH_DIR", ol.path().as_os_str()),
            ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str()),
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
            ("CODEX_HOME", codex.path().as_os_str()),
        ]);

        let binding =
            CodexCliBinding::detect().expect("a $CODEX_HOME that exists must be detected");
        f(&binding)
    }

    /// The registration, asserted from the install side.
    ///
    /// Twelve event keys, `PreToolUse` among them, and that key is what makes
    /// Codex *enforced* rather than merely captured: `SHELL_TOOL_NAMES`
    /// contains `"Bash"`, `evaluate()` matches on `tool_name` whoever sent it,
    /// and Codex's shell tools report as `"Bash"`. It may only be written while
    /// `hook_output::codex_cli` can express a deny.
    #[test]
    fn install_writes_twelve_events() {
        with_codex_install_env(|binding| {
            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");

            let v = read_env(&binding.hook_config_path());
            let hooks = v["hooks"].as_object().expect("a hooks object: {v}");
            assert_eq!(hooks.len(), 12, "twelve event keys: {v}");
            assert!(
                hooks.contains_key("PreToolUse"),
                "PreToolUse is the registration — without it no Codex deny is ever \
                 evaluated: {v}"
            );

            // The matcher tiers, on disk. `PreToolUse` is the EXACT tier —
            // split on `|`, compared with `==`, so `"Bash"` cannot capture a
            // future `"BashOutput"` — and every other event takes `""`, which
            // matches all. Not `"Bash|apply_patch"`: `evaluate()` needs
            // `tool_input.command` and a patch has none.
            for (event, groups) in hooks {
                let group = &groups.as_array().unwrap()[0];
                let expected = if event == "PreToolUse" { "Bash" } else { "" };
                assert_eq!(
                    group["matcher"].as_str(),
                    Some(expected),
                    "{event} carries the wrong matcher: {group}"
                );
            }

            // Nothing at the TOP level but `hooks`: Codex's `HooksFile` is
            // `#[serde(deny_unknown_fields)]`, so one extra key there makes it
            // reject the customer's entire file. In particular no `env` block —
            // this binding's channel is `OpenlatchDirArg` for that reason.
            let top: Vec<&String> = v.as_object().unwrap().keys().collect();
            assert_eq!(top, vec!["hooks"], "top level must carry only `hooks`: {v}");

            // Every entry carries an explicit timeout and the directory flag,
            // and none sets `async`. An omitted timeout inherits Codex's
            // 600-second default on the verdict path.
            for (event, groups) in hooks {
                let group = &groups.as_array().unwrap()[0];
                let handler = &group["hooks"][0];
                assert!(
                    handler["timeout"].is_number(),
                    "{event} has no explicit timeout: {group}"
                );
                assert!(
                    handler.get("async").is_none(),
                    "{event} sets async: {group}"
                );
                let command = handler["command"].as_str().unwrap();
                assert!(
                    command.contains("--openlatch-dir"),
                    "{event} must carry the directory the hook reads its port and \
                     token from: {command}"
                );
                assert!(
                    !command.contains("--event unknown"),
                    "{event} installed as `--event unknown` — pascal_to_snake is \
                     missing an arm: {command}"
                );
            }
        });
    }

    /// A customer's own group survives an install and keeps index 0.
    ///
    /// Index is the assertion, not decoration: Codex keys hook trust on
    /// `"{source_path}:{event}:{group_index}:{handler_index}"`, so moving a
    /// customer's group re-arms `/hooks` review on hooks they already trusted.
    #[test]
    fn install_appends_and_preserves_a_customer_group() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            std::fs::write(&path, CUSTOMER_GROUP).unwrap();
            let seeded: serde_json::Value = serde_json::from_str(CUSTOMER_GROUP).unwrap();
            let theirs = seeded["hooks"]["PostToolUse"][0].clone();

            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");

            let v = read_env(&path);
            let arr = v["hooks"]["PostToolUse"].as_array().unwrap();
            assert_eq!(arr.len(), 2, "ours is appended beside theirs: {v}");
            assert_eq!(
                arr[0], theirs,
                "the customer's group must be untouched: {v}"
            );
            assert!(
                arr[1].get("_openlatch").is_some(),
                "ours must be the appended one: {v}"
            );
        });
    }

    /// **The D-06 gate.** A re-install must not move a customer group that sits
    /// *after* ours.
    ///
    /// The customer group is added AFTER the first install on purpose. Seeding
    /// it first makes the test blind: remove-then-append leaves them at index 0
    /// either way, and index 0 is exactly where the old writer left them while
    /// silently shifting anything behind it.
    #[test]
    fn reinstall_does_not_move_a_later_customer_group() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            super::install_hooks(binding, 7443, "a-token").expect("first install");

            // The array is now [ours]. Append theirs, so it is [ours, theirs].
            let mut v = read_env(&path);
            v["hooks"]["PostToolUse"]
                .as_array_mut()
                .expect("PostToolUse is one of the twelve")
                .push(serde_json::json!({
                    "matcher": "",
                    "hooks": [{"type": "command", "command": "echo later", "timeout": 5}],
                }));
            std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();

            super::install_hooks(binding, 7443, "a-token").expect("re-install");

            let v = read_env(&path);
            let arr = v["hooks"]["PostToolUse"].as_array().unwrap();
            assert_eq!(arr.len(), 2, "a re-install replaces, never duplicates: {v}");
            assert!(
                arr[0].get("_openlatch").is_some(),
                "ours must be replaced IN PLACE at index 0: {v}"
            );
            assert_eq!(
                arr[1]["hooks"][0]["command"], "echo later",
                "the customer's later group must still be at index 1 — \
                 remove-then-append would have moved it to 0: {v}"
            );
        });
    }

    /// Uninstall is the inverse of install: seed → install → uninstall gives
    /// the customer their file back.
    ///
    /// Install writes twelve event keys, eleven of which the seeded file never
    /// had. Removing only our *elements* leaves eleven `"SessionStart": []` keys
    /// behind — a file we created still naming OpenLatch on every event — so
    /// the key set is the sharpest assertion here.
    ///
    /// **Compared as JSON, not as bytes.** The file comes back through the
    /// JSONC CST serialiser, which leaves the whitespace its own insertion
    /// introduced, so a byte comparison would pin a formatting contract nothing
    /// specifies — the same reason this plan's live acceptance diffs `jq -S`
    /// output rather than raw files. What must be identical is the customer's
    /// content and the shape around it, and that is what is asserted.
    #[test]
    fn uninstall_restores_the_seeded_file_byte_for_byte() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            std::fs::write(&path, CUSTOMER_GROUP).unwrap();
            let seeded: serde_json::Value = serde_json::from_str(CUSTOMER_GROUP).unwrap();

            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");
            super::remove_hooks(binding).expect("uninstall must succeed");

            // THE CUSTOMER'S OWN GROUP MUST COME BACK AS ITS ORIGINAL TEXT.
            // A parsed comparison alone would pass over a silent reformat of
            // their content, which is the one mutation they would actually
            // notice in a file they wrote — so assert their bytes directly.
            //
            // Not the WHOLE file, and the difference is worth stating because
            // this test's name reads like it. Removing our elements makes the
            // CST reflow the container around them: the file comes back as
            // `{"hooks":{\n    "PostToolUse":[…]\n  }}` where it was seeded
            // flat. Their group is untouched; the whitespace that held our
            // entries is not restored. Making it so would mean teaching the
            // shared JSONC writer to reproduce removed whitespace exactly —
            // a formatting contract this plan deliberately does not specify,
            // and one Claude Code would inherit too. Verified empirically
            // rather than assumed: the strict assertion was written first and
            // failed on exactly that whitespace.
            let customer_group = CUSTOMER_GROUP
                .split_once("\"PostToolUse\":[")
                .and_then(|(_, rest)| rest.rsplit_once("]"))
                .map(|(group, _)| group)
                .expect("the seed's customer group");
            assert!(
                std::fs::read_to_string(&path)
                    .unwrap()
                    .contains(customer_group),
                "uninstall must give the customer's own group back as the exact text \
                 they wrote, not a reserialisation of it"
            );

            let restored = read_env(&path);
            assert_eq!(
                restored, seeded,
                "uninstall must give the customer their file back: every group they \
                 owned, no leftovers, and none of the ten event keys install added"
            );
            // Stated separately so a failure says which half broke: a `del` that
            // leaves ten empty arrays behind still fails the line above, but this
            // one names the reason.
            let keys: Vec<&String> = restored["hooks"].as_object().unwrap().keys().collect();
            assert_eq!(
                keys,
                vec!["PostToolUse"],
                "an event key we emptied must be pruned, not left holding []"
            );
        });
    }

    /// `--agent` semantics (D-09), on the two-agent fixture so no environment
    /// is involved.
    ///
    /// Coverage is the default and a detected-but-unnamed agent is skipped in
    /// silence — that is the flag working. Both *failing* directions are
    /// failures on purpose: a name that is not an agent type is a typo, and a
    /// valid name that is not on this host is a typo too. Quietly wiring
    /// nothing is how somebody comes to believe they are covered.
    #[test]
    fn agent_flag_narrows_coverage_and_refuses_a_name_that_is_not_here() {
        let root = tempfile::tempdir().unwrap();
        let detected = crate::hooks::binding::test_support::two_detected_agents(root.path());
        let types = |v: Vec<DetectedAgent>| {
            v.iter()
                .map(DetectedAgent::agent_type)
                .collect::<Vec<&str>>()
        };

        assert_eq!(
            types(super::select_agents(detected.clone(), &[]).unwrap()),
            vec!["claude-code", "cursor"],
            "no --agent means every detected agent"
        );
        assert_eq!(
            types(super::select_agents(detected.clone(), &["cursor".to_string()]).unwrap()),
            vec!["cursor"],
            "a detected agent nobody named is skipped, silently"
        );
        assert_eq!(
            types(
                super::select_agents(
                    detected.clone(),
                    &["cursor".to_string(), "claude-code".to_string()],
                )
                .unwrap()
            ),
            vec!["claude-code", "cursor"],
            "detection order wins over flag order — it is load-bearing elsewhere"
        );

        // A schema-valid agent this host does not have. `gemini-cli` is in
        // SCHEMA_AGENT_TYPES and is not one of the two this build detects.
        let err = super::select_agents(detected.clone(), &["gemini-cli".to_string()])
            .expect_err("a named-but-undetected agent must fail");
        assert_eq!(err.code, crate::error::ERR_HOOK_AGENT_NOT_FOUND);
        assert!(
            err.message.contains("gemini-cli"),
            "the error must NAME the agent, or the operator cannot see their typo: {}",
            err.message
        );

        // Not an agent type at all: a different message, listing what is.
        let err = super::select_agents(detected, &["claude_code".to_string()])
            .expect_err("an unknown agent type must fail");
        assert_eq!(err.code, crate::error::ERR_HOOK_AGENT_NOT_FOUND);
        assert!(
            err.suggestion
                .as_deref()
                .is_some_and(|s| s.contains("claude-code")),
            "the remedy must list the valid values: {err:?}"
        );
    }

    /// The unseeded branch: install then uninstall on a file that did not
    /// exist leaves `{}`, never a deleted file.
    ///
    /// Nothing records that we created it — `StateEntry` carries no creation
    /// flag — and deleting unconditionally would take a customer's own empty
    /// `hooks.json` with it. Every other case here seeds a file, so this branch
    /// is otherwise untested.
    #[test]
    fn uninstall_of_an_unseeded_file_leaves_an_empty_object() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            assert!(!path.exists(), "the fixture starts with no hooks.json");

            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");
            super::remove_hooks(binding).expect("uninstall must succeed");

            assert_eq!(std::fs::read_to_string(&path).unwrap(), "{}");
        });
    }
}