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
//! 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 boundary 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_BOUNDARY_FOREIGN_PROVIDER};

/// 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-boundary 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 and
/// never claim to tell `Modified` from `Trusted`. From outside, both read as
/// "no `trusted_hash` we can vouch for" — and both have the same remedy.
#[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> {
    let raw = std::fs::read_to_string(hooks_json_path(codex_dir)).ok()?;
    let parsed = super::jsonc::parse_settings_value(&raw).ok()?;
    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 has recorded on disk about one of our hook handlers.
///
/// Three values, not Codex's four. `Trusted` and `Modified` are statuses
/// *Codex* computes from a digest it does not document; from outside, a
/// re-armed review looks exactly like a never-trusted one — Codex clears the
/// `trusted_hash` in both cases — and both carry the same remedy, so
/// collapsing them costs the developer nothing and claims nothing untrue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookTrust {
    /// Our key carries a `trusted_hash`. Codex will spawn the hook.
    Trusted,
    /// Our key is absent from `state`, or present with no `trusted_hash` —
    /// never trusted, or a changed command re-armed the review.
    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> {
    let config = match read_config_layer(&config_toml_path(codex_dir)) {
        ConfigLayer::Unreadable => return None,
        ConfigLayer::Absent => return Some(HookTrust::NeverTrusted),
        ConfigLayer::Read(config) => config,
    };

    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)
    });

    Some(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,
    })
}

/// "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))
}

// ---------------------------------------------------------------------------
// 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-boundary provider table (I-3 §1)
// ---------------------------------------------------------------------------

// The table this writer maintains, rendered from the binding's values:
//
//     model_provider = "openlatch"
//
//     [model_providers.openlatch]
//     name                 = "OpenLatch boundary"
//     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 boundary";

/// 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_BOUNDARY_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-boundary 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_BOUNDARY_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_BOUNDARY_FOREIGN_PROVIDER,
                format!(
                    "'{}' already declares a [model_providers.{provider_name}] table that does \
                     not point at the OpenLatch boundary",
                    crate::core::path_compat::display_path(config_toml)
                ),
            )
            .with_suggestion(
                "Rename or remove that provider table, or disable the model boundary 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_BOUNDARY_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_BOUNDARY_FOREIGN_PROVIDER,
            format!("cannot read {}: {e}", config_toml.display()),
        )
    })?;
    let doc = raw.parse::<toml_edit::DocumentMut>().map_err(|e| {
        OlError::new(
            ERR_BOUNDARY_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::boundary_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)
    }

    // -----------------------------------------------------------------------
    // The model-boundary 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 boundary\""),
            "`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_boundary_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(),
            boundary_wiring: Some(crate::hooks::binding::BoundaryWiring {
                wire_format: crate::boundary::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_boundary_config(&binding, 7600, "agt_demo").expect("install");
        crate::hooks::write_boundary_config(&binding, 7600, "agt_demo").expect("re-install");
        crate::hooks::remove_boundary_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_boundary_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_BOUNDARY_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"
        );
    }
}