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
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use serde_json::{json, Value};

use crate::boundary::wire_format::WireFormat;
use crate::core::hook_state::marker::OpenlatchMarker;
use crate::error::ERR_HOOK_NOT_ARMED;
use crate::hooks::codex_cli::{HookTrust, InstalledHandler, ManagedHooksOnly};

use super::super::binding::{
    AgentBinding, BindingCapabilities, BoundaryWiring, DaemonChannel, EndpointConvention,
    FailureMode, LivenessReport,
};

/// Every hook event OpenLatch registers with Codex CLI.
///
/// **TWELVE — all of Codex's native events.** `"PreToolUse"` is first in the
/// list because it is the one that matters: that single array element **is**
/// the registration. `install_hooks` loops `binding.hook_event_types()`
/// unconditionally and nothing filters it, so this list is the install list,
/// never a capability declaration.
///
/// `"PreToolUse"` and the `"codex-cli"` arm of
/// [`crate::hook_output::translate`] are **one change**, and they landed in one
/// commit. `SHELL_TOOL_NAMES` already contains `"Bash"`, `evaluate()` matches
/// on `tool_name` regardless of which agent sent it, and Codex's shell tools
/// report as `"Bash"` — so this entry is what starts evaluating Codex shell
/// commands. Delete the translator arm and leave this element behind and every
/// deny is discarded before the developer sees it; the other eleven events are
/// never evaluated at all, because `evaluate()` is reached only for
/// `pre_tool_use`.
///
/// `Interrupt` is first class, not a curiosity: Codex declares it in
/// `HookEventsToml`, pins it in a twelve-element return type, ships it in
/// `config.schema.json` and matches it exhaustively.
const EVENT_TYPES: [&str; 12] = [
    // THE REGISTRATION. See above before touching it.
    "PreToolUse",
    "PermissionRequest",
    "PostToolUse",
    "UserPromptSubmit",
    "SessionStart",
    "SessionEnd",
    "PreCompact",
    "PostCompact",
    "Stop",
    "SubagentStop",
    "SubagentStart",
    "Interrupt",
];

/// Codex CLI's hook registrations live in a dedicated file rather than a
/// section of a larger settings file, so the binding carries both the directory
/// and that file.
pub struct CodexCliBinding {
    /// `$CODEX_HOME`, else `~/.codex` — resolved by `hooks::codex_cli`.
    pub codex_dir: PathBuf,
    /// `<codex_dir>/hooks.json`.
    pub hooks_path: PathBuf,
    /// Codex's **system** requirements layer, the administrative config an
    /// MDM-locked host is configured through — `crate::hooks::codex_cli::requirements_toml_path()`
    /// on a real install, and `None` where that path is not pinned.
    ///
    /// A field rather than a call inside [`liveness`](AgentBinding::liveness)
    /// for one reason: the pinned location is `/etc/codex/requirements.toml`,
    /// and no test may write there. The resolver still owns the path (D-01) —
    /// [`detect`](Self::detect) is the only place it is read — while the check
    /// that consumes it stays drivable from a temporary directory.
    pub requirements_toml: Option<PathBuf>,
}

impl CodexCliBinding {
    /// Delegates to `hooks::codex_cli`, which owns directory resolution for
    /// every caller. Resolving `$CODEX_HOME` here instead would repeat, on
    /// purpose, the duplication that made `$CLAUDE_CONFIG_DIR` honoured on one
    /// path and ignored on another.
    pub fn detect() -> Option<Self> {
        let codex_dir = crate::hooks::codex_cli::detect()?;
        let hooks_path = crate::hooks::codex_cli::hooks_json_path(&codex_dir);
        Some(Self {
            codex_dir,
            hooks_path,
            requirements_toml: crate::hooks::codex_cli::requirements_toml_path(),
        })
    }
}

impl AgentBinding for CodexCliBinding {
    fn agent_type(&self) -> &'static str {
        "codex-cli"
    }

    fn display_name(&self) -> &'static str {
        "Codex CLI"
    }

    fn config_dir(&self) -> PathBuf {
        self.codex_dir.clone()
    }

    fn hook_config_path(&self) -> PathBuf {
        self.hooks_path.clone()
    }

    fn hook_event_types(&self) -> &'static [&'static str] {
        &EVENT_TYPES
    }

    fn load_bearing_events(&self) -> &'static [&'static str] {
        // Codex is judged on ITS events, not Claude Code's. `PreToolUse` is
        // here because it is here in `EVENT_TYPES` — two arrays, one fact.
        // `health::inspect` reports a missing load-bearing event, and this is
        // the event that carries every Codex deny: leave it out and a Codex
        // install whose `PreToolUse` row was stripped renders healthy while
        // enforcing nothing.
        &["PreToolUse", "PostToolUse", "SessionStart"]
    }

    fn daemon_channel(&self) -> DaemonChannel {
        // Codex cannot forward environment variables: `HookHandlerConfig` has
        // no `allowedEnvVars`, and its `HooksFile` is `deny_unknown_fields`, so
        // a top-level `env` block would make Codex reject the customer's whole
        // file. The hook is told where to look on its own command line instead
        // and reads both secrets from that directory — the token *value* never
        // reaches the config, only a path.
        DaemonChannel::OpenlatchDirArg
    }

    fn liveness(&self) -> LivenessReport {
        // A = our binary resolves (invoke it) · B = the `PreToolUse` row is
        // trusted (read it) · C = nothing suppresses it administratively.
        //
        // Three, not one, because an untrusted Codex hook is **never spawned**:
        // it produces no runtime symptom at all — nothing calls us, nothing
        // errors, and the file on disk looks perfect. Invoking therefore proves
        // our binary resolves and answers; it does **not** prove Codex would
        // ever call it. Rendering green on the strength of a successful
        // invocation is exactly the "disabled subsystem reporting healthy"
        // failure the client's contract exists to stop.
        //
        // All three run every time — the probe fires even when trust has
        // already failed, because the two answers are independent and a
        // developer fixing one wants to know about the other.
        let handler = crate::hooks::codex_cli::installed_handler(&self.codex_dir, PROBE_EVENT);

        // What this build cannot see, said out loud on whichever check we push.
        // It is `detail` text and never a `State`: a `Pending` here would be a
        // warning, `counts.warned > 0` is `Overall::Degraded`, and these keys
        // are absent on every default host — so an unclearable warning would
        // ride on every healthy Codex install, from `doctor`, from `status` and
        // from `init`.
        // No longer mutated: the only push was the suppression dimension's,
        // and that now reports itself as unobservable instead of as a caveat
        // riding on a green check.
        let caveats = vec![
            FEATURE_DEFAULT_CAVEAT.to_string(),
            PROFILE_CAVEAT.to_string(),
        ];

        let dimensions = [
            self.check_binary_resolves(handler.as_ref()),
            self.check_trusted(handler.as_ref()),
            self.check_not_suppressed(),
        ];

        // `detail` / `remedy` / `code` describe the FIRST failing dimension, in
        // the order A, B, C — stated so two engineers do not pick different
        // precedence when more than one fails. A precedes B because an
        // unresolvable binary makes trust moot; B precedes C because an
        // untrusted hook is the common self-serve case and its remedy is the
        // one the developer can act on today.
        let mut failure: Option<(String, String)> = None;
        let mut unknowns: Vec<String> = Vec::new();
        for dimension in dimensions {
            match dimension {
                Dimension::Ok => {}
                Dimension::Failed { detail, remedy } => {
                    if failure.is_none() {
                        failure = Some((detail, remedy));
                    }
                }
                Dimension::Unobservable(note) => unknowns.push(note),
            }
        }

        // An OBSERVED failure outranks an unreadable dimension. Nothing is
        // guessed either way: a host whose trust state proves the hook inert is
        // inert whether or not some *other* dimension could be read, and
        // answering `None` there would push no check at all and hide a
        // provably-dark host behind "this build cannot tell".
        if let Some((detail, remedy)) = failure {
            return LivenessReport {
                armed: Some(false),
                detail: Some(sentences(&detail, &unknowns, &caveats)),
                remedy: Some(remedy),
                // `Check::validate` rejects a failed check with no OL-XXXX
                // code, and I-1's renderer unwraps this one. One code, three
                // remedies — the remedy above says which dimension it was.
                code: Some(ERR_HOOK_NOT_ARMED),
            };
        }

        // Nothing observed as failing, and something could not be read at all.
        // That is I-1's stated meaning for `None` — "this build cannot tell" —
        // and the renderer pushes nothing for it. It is NOT "Codex cannot be
        // un-armed".
        if !unknowns.is_empty() {
            return LivenessReport {
                armed: None,
                detail: Some(sentences(CANNOT_TELL, &unknowns, &caveats)),
                remedy: None,
                code: None,
            };
        }

        LivenessReport {
            armed: Some(true),
            detail: Some(sentences(ARMED, &unknowns, &caveats)),
            remedy: None,
            code: None,
        }
    }

    fn build_hook_entry(
        &self,
        event: &str,
        binary: &Path,
        _port: u16,
        marker: &OpenlatchMarker,
    ) -> Value {
        let wire_event = crate::hooks::claude_code::pascal_to_snake(event);
        let binary_str = binary.display().to_string();
        // The channel this binding declares, spelled out on the command line:
        // the same `openlatch_dir()` call `install_hooks` makes, so a relocated
        // `$OPENLATCH_DIR` reaches the spawned hook. The port argument is
        // deliberately unused — the hook reads `<dir>/daemon.port` and
        // `<dir>/daemon.token` from this path.
        let openlatch_dir = crate::config::openlatch_dir().display().to_string();

        // Quote paths with spaces. Windows paths often contain spaces; POSIX
        // shells interpret unquoted spaces as argument separators.
        let command = format!(
            r#""{binary_str}" --agent codex-cli --event {wire_event} --openlatch-dir "{openlatch_dir}""#
        );

        // Always explicit, and in SECONDS. Omitting it inherits Codex's
        // `timeout_sec.unwrap_or(600)` — ten minutes on the verdict path.
        // `SessionEnd` and `Interrupt` are the exception: they default to 1s
        // and cap at 3s, so a larger value there is silently clamped.
        //
        // The wire key is camelCase `timeout`, never the Rust field name
        // `timeout_sec`, which the handler struct ignores — handing the hook
        // the 600 s default this line exists to prevent.
        let timeout = match event {
            "SessionEnd" | "Interrupt" => 3,
            _ => 10,
        };

        // No `async` key. It defaults to `false`; setting it removes the hook
        // from the blocking path by construction, which would make a deny
        // undeliverable no matter what we emit.
        let hook_inner = json!({
            "type": "command",
            "command": command,
            "timeout": timeout,
        });

        let marker_value =
            serde_json::to_value(marker).expect("OpenlatchMarker is always serializable");

        // `matcher` is a real three-tier filter: absent, `""` and `"*"` match
        // every tool; a value of `[A-Za-z0-9_|]` only is the EXACT tier — split
        // on `|`, compared with `==`, no regex engine and no substring match;
        // anything else is an unanchored regex.
        //
        // `PreToolUse` is the one event with a real matcher, and it is exactly
        // `"Bash"`. That is the exact tier, so it cannot capture a future
        // `"BashOutput"`. It is the single wire `tool_name` Codex serialises
        // for its shell-like tools — unified exec included — and the only one
        // `SHELL_TOOL_NAMES` evaluates. NOT `"Bash|apply_patch"`:
        // `evaluate()` needs `tool_input.command` and a patch has none, so
        // `apply_patch` would pay a process spawn per file mutation to decide
        // nothing. It enters this matcher in the same change as the extraction
        // that can read it.
        //
        // Everything else carries `""`, because this build wants every tool on
        // those events. `UserPromptSubmit`, `Stop` and `Interrupt` hard-code
        // `None` internally and silently discard any matcher configured —
        // writing a meaningful-looking value there would be a lie in a file a
        // customer reads.
        let matcher = match event {
            "PreToolUse" => "Bash",
            _ => "",
        };

        // The marker goes INSIDE the group: `MatcherGroup` does not deny
        // unknown fields, while `HooksFile` — the top level — does.
        json!({
            "matcher": matcher,
            "_openlatch": marker_value,
            "hooks": [hook_inner],
        })
    }

    fn config_is_machine_global(&self) -> bool {
        // Delegate, never re-derive from `self.codex_dir`.
        crate::hooks::codex_cli::config_is_machine_global()
    }

    fn capabilities(&self) -> BindingCapabilities {
        BindingCapabilities {
            // TWO tiers, not three. Codex PARSES `permissionDecision: "ask"`
            // and does NOT support it: it marks the hook run failed, reports
            // the error and CONTINUES the tool call. Declaring "ask" here would
            // make the degradation ladder deliver a silent fail-open — the
            // discarded-verdict failure this whole initiative exists to remove,
            // arriving by the one path nobody would test.
            expressible: &["allow", "deny"],
            // `updatedInput` — declared, never emitted. The client does not
            // mutate agent traffic.
            can_mutate_arguments: true,
            native_failure_mode: FailureMode::FailOpen,
            admin_owned_settings: true,
            declares_session_in_request: false,
        }
    }

    fn boundary_wiring(&self) -> Option<BoundaryWiring> {
        // Declared here and consumed by nothing until I-3 writes
        // `config.toml`. Codex has no request plane in this build, which is
        // also why no Boundary check runs for it: that read is gated on
        // `EndpointConvention::EnvVars`.
        Some(BoundaryWiring {
            wire_format: WireFormat::OpenAiResponses,
            endpoint: EndpointConvention::TomlProvider {
                provider_name: "openlatch",
                wire_api: "responses",
            },
            install_id_header: "x-openlatch-install-id",
        })
    }
}

// ---------------------------------------------------------------------------
// The arming check (D-07)
// ---------------------------------------------------------------------------

/// The reserved `tool_name` the arming probe puts on its synthetic payload.
///
/// Chosen so that **no plausible widening of
/// [`SHELL_TOOL_NAMES`](crate::core::policy::SHELL_TOOL_NAMES) can ever claim
/// it**, which is what keeps the probe inert. A real tool name would not do:
/// `apply_patch` is deferred out of this unit but lands in a follow-on, and a
/// probe using it would silently become able to match a live policy rule the
/// day that unit ships — the one property this check must never have.
///
/// It is load-bearing on the other end too. The probe's payload reaches the
/// daemon exactly like a real tool call, so `daemon::handlers::is_doctor_probe`
/// skips it before the audit log, the event logger and the cloud rail ever see
/// it. `synthetic_probe_uses_a_non_evaluated_tool_name` pins both halves.
pub const DOCTOR_PROBE_TOOL_NAME: &str = "OpenlatchDoctorProbe";

/// The one event the arming check reads and runs.
///
/// Codex trust and Codex execution are both **per event**, so probing any other
/// row proves nothing about the row that carries the deny.
const PROBE_EVENT: &str = "PreToolUse";

/// The bound applied when the installed row carries no `timeout` of its own.
///
/// Not Codex's `timeout_sec.unwrap_or(600)`: ten minutes is a limit for a
/// verdict, not for a diagnostic a developer is waiting on. Matches the value
/// [`AgentBinding::build_hook_entry`] writes for `PreToolUse`.
const PROBE_FALLBACK_TIMEOUT_SECS: u64 = 10;

/// The `/hooks` remedy — both halves of it, the action and the trap.
///
/// The re-arm sentence is the operational trap behind most of these reds, and
/// naming it here is what stops a support round trip. This string is also
/// `init`'s trust message: a fresh self-serve install is `armed: Some(false)`
/// on this dimension, I-1's renderer turns that into a failed Hooks check
/// carrying this remedy, and `init` already prints its report — which is why
/// `init.rs` is not edited to say the same thing in Codex-shaped prose.
const TRUST_REMEDY: &str = "Run `/hooks` in Codex and trust the OpenLatch hook. \
                            A re-install that changes the hook command re-arms this review.";

/// Said on every check this binding pushes: an absent `features.*` key is read
/// as *no suppression observed*, not as unproven.
///
/// *Off is never a pass* forbids rendering a **disabled** subsystem as healthy;
/// it does not require rendering an **undocumented vendor default** as a
/// defect. These keys are absent on every default host, so treating absence as
/// a failure would make `Enforced` unreachable and every correctly-installed
/// Codex host exit 7 forever. The uncertainty goes here, in the text.
const FEATURE_DEFAULT_CAVEAT: &str =
    "An absent `features.*` key is read as no suppression: those keys are absent on a default \
     host and their defaults are undocumented, so they are re-verified on each Codex upgrade.";

/// The other thing this check cannot see, stated in the same place.
const PROFILE_CAVEAT: &str =
    "A `codex --profile <name>` invocation may override `features.*` from `<name>.config.toml`; \
     not observable from `config.toml`.";

/// Lead sentence when every dimension held.
const ARMED: &str = "The installed PreToolUse hook answers, Codex records it as trusted, and no \
                     administrative suppression was observed.";

/// Lead sentence when a dimension could not be read at all.
const CANNOT_TELL: &str = "Codex enforcement could not be proven either way on this host.";

/// One of the three questions [`AgentBinding::liveness`] asks, answered.
///
/// `Failed` and `Unobservable` are **not** interchangeable, and keeping them
/// apart is this enum's whole job: a doctor that reads the wrong file, or reads
/// none and guesses, reports the wrong answer confidently — which is worse than
/// reporting that it could not tell.
enum Dimension {
    /// Observed, and holding.
    Ok,
    /// Observed, and provably not arming. Carries what a developer does next.
    Failed {
        /// What was observed, in Codex's own terms.
        detail: String,
        /// The action that clears it.
        remedy: String,
    },
    /// Could not be read at all — "this build cannot tell".
    Unobservable(String),
}

impl CodexCliBinding {
    /// **Check A — does our binary resolve?** Proven by *running* it.
    ///
    /// The #165 lesson: a hook command that could not resolve failed open
    /// invisibly on every tool call, because the agent never reports a hook it
    /// could not start. So this runs the **installed command string**, as
    /// written in `hooks.json`, rather than a path recomputed from scratch —
    /// the point is to exercise what Codex would actually run, quoting
    /// included.
    fn check_binary_resolves(&self, handler: Option<&InstalledHandler>) -> Dimension {
        let Some(handler) = handler else {
            return Dimension::Failed {
                detail: format!(
                    "No OpenLatch {PROBE_EVENT} hook is registered in {} — that row is the one \
                     that carries every deny.",
                    self.hooks_path.display()
                ),
                remedy: "Run `openlatch init` to install the Codex hooks, or `openlatch doctor \
                         --fix` to repair an existing install."
                    .to_string(),
            };
        };

        let timeout =
            Duration::from_secs(handler.timeout_secs.unwrap_or(PROBE_FALLBACK_TIMEOUT_SECS));
        match run_probe(&handler.command, timeout) {
            ProbeOutcome::Answered => Dimension::Ok,
            ProbeOutcome::Unspawnable(why) => Dimension::Unobservable(format!(
                "The login shell Codex runs hook commands through (`sh -lc`) could not be \
                 started here ({why}), so the installed command was never exercised."
            )),
            ProbeOutcome::Bad(why) => Dimension::Failed {
                detail: format!(
                    "The installed {PROBE_EVENT} hook command did not answer: {why}. Codex fails \
                     open on a hook it cannot run, and says nothing while it does."
                ),
                remedy: format!(
                    "Restore the hook binary at {} — `openlatch doctor --fix` restages it — then \
                     re-run `openlatch doctor`.",
                    binary_from_command(&handler.command)
                ),
            },
        }
    }

    /// **Check B — is it trusted?** Read the state; never invoke.
    ///
    /// Codex pushes a hook onto the executable list only when
    /// `enabled && (bypass || Managed || Trusted)`, so an untrusted hook cannot
    /// self-report: it is never spawned at all. A check that inspected the
    /// *file's shape* instead of Codex's own recorded trust would render green
    /// on exactly the host this plan exists to catch.
    ///
    /// Trust is per event, and the key carries the group and handler indices
    /// our group was actually found at — never an assumed `:0:0`, which on any
    /// host with a pre-existing customer hook reads the **customer's** trust
    /// state as ours.
    fn check_trusted(&self, handler: Option<&InstalledHandler>) -> Dimension {
        // Nothing to key the lookup on. Check A already reports the missing row
        // and takes precedence; a second cross for one fault is the cascade the
        // report contract forbids.
        let Some(handler) = handler else {
            return Dimension::Ok;
        };
        let config_toml = crate::hooks::codex_cli::config_toml_path(&self.codex_dir);

        match crate::hooks::codex_cli::hook_trust(&self.codex_dir, PROBE_EVENT, handler) {
            None => Dimension::Unobservable(format!(
                "{} could not be read, so what Codex has recorded about trusting this hook is \
                 unknown.",
                config_toml.display()
            )),
            Some(HookTrust::Trusted) => Dimension::Ok,
            // `Trusted` vs `Modified` is a distinction only Codex can draw,
            // since it owns the digest. From outside, a re-armed review and a
            // never-trusted hook look identical — Codex clears the
            // `trusted_hash` in both cases — and both carry the same remedy.
            Some(HookTrust::NeverTrusted) => Dimension::Failed {
                detail: format!(
                    "Codex has no trusted hash recorded for this hook in {}, so it is marked for \
                     review and never spawned: installed, correct on disk, and completely inert.",
                    config_toml.display()
                ),
                remedy: TRUST_REMEDY.to_string(),
            },
            Some(HookTrust::Disabled) => Dimension::Failed {
                detail: format!(
                    "Codex records this hook as `enabled = false` in {}, so it is never spawned.",
                    config_toml.display()
                ),
                remedy: TRUST_REMEDY.to_string(),
            },
        }
    }

    /// **Check C — is it administratively suppressed?** Two ways to be dark
    /// that neither A nor B can see.
    ///
    /// `allow_managed_hooks_only` is the one failure mode with no runtime
    /// symptom whatsoever: Codex drops every non-managed hook with a bare
    /// `continue` and pushes no warning, so on an MDM-locked host our hook is
    /// present on disk, listed nowhere, and never executed.
    ///
    /// `features.hooks` / `codex_hooks` / `plugin_hooks` disable hooks
    /// wholesale. `codex_hooks` is a legacy alias for the canonical key, so
    /// either one present-and-`false` counts identically — and an **absent**
    /// key is not a suppression (see [`FEATURE_DEFAULT_CAVEAT`]).
    /// Takes nothing: this check now expresses an unread dimension as
    /// `Dimension::Unobservable`, which `liveness()` folds into `unknowns`,
    /// rather than pushing a caveat alongside a green. It used to take
    /// `&mut Vec<String>` for that push.
    fn check_not_suppressed(&self) -> Dimension {
        let config_toml = crate::hooks::codex_cli::config_toml_path(&self.codex_dir);
        if let Some(key) = crate::hooks::codex_cli::suppressing_feature_flag(&self.codex_dir) {
            return Dimension::Failed {
                detail: format!(
                    "`features.{key} = false` in {} switches Codex hooks off wholesale.",
                    config_toml.display()
                ),
                remedy: format!(
                    "Remove `features.{key} = false` from {} (or set it to `true`), then re-run \
                     `openlatch doctor`.",
                    config_toml.display()
                ),
            };
        }

        match crate::hooks::codex_cli::managed_hooks_only(self.requirements_toml.as_deref()) {
            // Our hook is written to `$CODEX_HOME/hooks.json` — a user-level
            // source, which is never a managed one. So the switch being on is,
            // for us, always a suppression.
            ManagedHooksOnly::Observed(true) => Dimension::Failed {
                detail: format!(
                    "`hooks.allow_managed_hooks_only` is set on this host and {} is a user-level \
                     source, so Codex drops this hook with no diagnostic output at all.",
                    self.hooks_path.display()
                ),
                remedy: "Deploy the OpenLatch hook through Codex's managed channel \
                         (`hooks.managed_dir`, or the system `requirements.toml`), or clear \
                         `hooks.allow_managed_hooks_only`."
                    .to_string(),
            },
            ManagedHooksOnly::Observed(false) => Dimension::Ok,
            // Not a red and not a green — and it must not return `Ok`, which IS
            // a green. This branch used to, with a caveat on the side, and the
            // comment above it already said the right thing while the code did
            // the other: on Windows (no pinned requirements path) or with an
            // unreadable requirements file, a trusted hook rendered
            // `armed: Some(true)` with one of the three dimensions never
            // consulted. `AGENTS.md` is explicit that green means enabled AND
            // proven working, so an unread dimension cannot report armed.
            //
            // `Dimension::Unobservable` already exists for exactly this and
            // `liveness()` already folds it into `unknowns`, which reaches the
            // developer through `detail`. Hence no `caveats` push here: it
            // would say the same thing twice.
            ManagedHooksOnly::Unobservable => Dimension::Unobservable(
                "Codex's system requirements layer could not be consulted here, so \
                 `hooks.allow_managed_hooks_only` was not observed."
                    .to_string(),
            ),
        }
    }
}

/// Join a lead sentence, the dimensions that could not be read, and the
/// standing caveats into one `detail` string.
fn sentences(lead: &str, unknowns: &[String], caveats: &[String]) -> String {
    std::iter::once(lead)
        .chain(unknowns.iter().map(String::as_str))
        .chain(caveats.iter().map(String::as_str))
        .collect::<Vec<_>>()
        .join(" ")
}

/// What running the installed hook command produced.
enum ProbeOutcome {
    /// It ran and answered a well-formed response.
    Answered,
    /// It ran, and did not. Carries why, for the `detail`.
    Bad(String),
    /// It could not be started the way Codex starts hook commands, so nothing
    /// about our binary was observed either way.
    Unspawnable(String),
}

/// The synthetic `PreToolUse` payload the probe writes to the command's stdin.
///
/// Inert by construction: [`DOCTOR_PROBE_TOOL_NAME`] is outside
/// `SHELL_TOOL_NAMES`, so `evaluate()` never reaches a rule with it, and the
/// daemon drops the envelope before the audit trail.
fn probe_payload() -> Value {
    json!({
        "hook_event_name": PROBE_EVENT,
        "tool_name": DOCTOR_PROBE_TOOL_NAME,
        "tool_input": {},
    })
}

/// Run one hook command the way Codex runs it, with the probe payload on stdin.
///
/// **`sh -lc "<command string>"`** — Codex runs hook commands through a login
/// shell, and splitting argv ourselves would skip exactly the quoting this
/// check exists to exercise. A command that cannot resolve therefore surfaces
/// as the shell's own `127`, which is precisely the #165 shape.
fn run_probe(command: &str, timeout: Duration) -> ProbeOutcome {
    let mut child = match Command::new("sh")
        .arg("-lc")
        .arg(command)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        // A login shell's profile chatter is not our diagnostic to report.
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(child) => child,
        Err(e) => return ProbeOutcome::Unspawnable(e.to_string()),
    };

    // Drained on a thread rather than after `wait()`: a hook that filled the
    // pipe buffer would otherwise block forever on a write nobody is reading,
    // and the timeout below would only kill it after the fact.
    let drain = child.stdout.take().map(|mut out| {
        std::thread::spawn(move || {
            let mut buf = String::new();
            let _ = out.read_to_string(&mut buf);
            buf
        })
    });

    if let Some(mut stdin) = child.stdin.take() {
        // A command that exits without reading stdin is not an error here —
        // whether it answered is what the outcome turns on.
        let _ = stdin.write_all(probe_payload().to_string().as_bytes());
    }

    let deadline = Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(10)),
            Err(_) => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
        }
    };

    // Only wait for the reader when the child actually exited. Killing `sh` on
    // the deadline does NOT kill the hook it spawned: that grandchild survives
    // holding the stdout pipe it inherited, so joining here would block forever
    // on precisely the hang the timeout exists to bound — turning one slow hook
    // into a `doctor`, `status` and `init` that never return. The timeout
    // outcome does not read stdout anyway, so there is nothing to wait for.
    // The reader thread is left to end on its own when the pipe finally closes.
    let stdout = match status {
        Some(_) => drain
            .and_then(|handle| handle.join().ok())
            .unwrap_or_default(),
        None => String::new(),
    };

    match status {
        None => ProbeOutcome::Bad(format!("no response within {}s", timeout.as_secs())),
        Some(status) if !status.success() => ProbeOutcome::Bad(match status.code() {
            Some(127) => "the command could not be resolved (exit 127)".to_string(),
            Some(code) => format!("it exited {code}"),
            None => "it was killed by a signal".to_string(),
        }),
        Some(_) if well_formed_response(&stdout) => ProbeOutcome::Answered,
        Some(_) => ProbeOutcome::Bad("its response was not a JSON object".to_string()),
    }
}

/// Is this what a Codex hook is supposed to write to stdout?
///
/// A JSON object — `{}` is the universal continue-normally signal, and every
/// richer response is an object too. The last-line fall-back exists because
/// `sh -l` sources the host's profile before running anything, and a profile
/// that prints a banner would otherwise turn a perfectly healthy hook into a
/// confident red.
fn well_formed_response(stdout: &str) -> bool {
    let is_object = |s: &str| {
        serde_json::from_str::<Value>(s)
            .map(|v| v.is_object())
            .unwrap_or(false)
    };
    let trimmed = stdout.trim();
    if is_object(trimmed) {
        return true;
    }
    trimmed
        .lines()
        .rev()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .is_some_and(is_object)
}

/// The binary a hook command string invokes, for the remedy text.
///
/// The command is written with the path quoted (Windows paths carry spaces), so
/// the first quoted run is the binary; an unquoted command falls back to its
/// first whitespace-delimited word.
fn binary_from_command(command: &str) -> &str {
    let trimmed = command.trim_start();
    if let Some(rest) = trimmed.strip_prefix('"') {
        if let Some(end) = rest.find('"') {
            return &rest[..end];
        }
    }
    trimmed.split_whitespace().next().unwrap_or(trimmed)
}

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

    /// A binding rooted at `root`, with its requirements layer pointed at a
    /// file under `root` that does not exist.
    ///
    /// Deliberately not the host's `/etc/codex/requirements.toml`: a test that
    /// read the real one would pass or fail on the developer's MDM
    /// configuration. An absent file is `Observed(false)` — no requirements
    /// layer, nothing restricting hooks — which is what every fixture here
    /// wants except `managed_only_suppression_is_armed_false`.
    fn binding_at(root: &Path) -> CodexCliBinding {
        CodexCliBinding {
            codex_dir: root.to_path_buf(),
            hooks_path: root.join("hooks.json"),
            requirements_toml: Some(root.join("requirements.toml")),
        }
    }

    /// `$CODEX_HOME` relocates the file this binding writes — the gate that
    /// keeps a sandbox, and a developer who moved their Codex config, from
    /// resolving to the real `~/.codex`. See `hooks::codex_cli::detect` for why
    /// the seam has to be an env var.
    ///
    /// Takes `codex_cli::CONFIG_DIR_ENV_LOCK`, **not** Claude Code's: the two
    /// guard different variables. `CODEX_HOME` is absent from
    /// `daemon::identity::MANAGED`, so `EnvGuard` does not restore it and this
    /// test saves and restores it itself.
    #[test]
    fn codex_home_relocates_the_hooks_path() {
        let _lock = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let previous = std::env::var_os(crate::hooks::codex_cli::CONFIG_DIR_ENV);
        let dir = tempfile::tempdir().expect("temp dir");

        std::env::set_var(crate::hooks::codex_cli::CONFIG_DIR_ENV, dir.path());
        let b = CodexCliBinding::detect().expect("relocated dir exists, so detect must succeed");
        assert_eq!(b.codex_dir, dir.path());
        assert_eq!(b.hook_config_path(), dir.path().join("hooks.json"));

        // Empty is "unset" — otherwise an exported-but-blank variable would
        // resolve the config directory to "".
        std::env::set_var(crate::hooks::codex_cli::CONFIG_DIR_ENV, "");
        if let Some(b) = CodexCliBinding::detect() {
            assert_ne!(b.codex_dir, Path::new(""));
        }

        match previous {
            Some(v) => std::env::set_var(crate::hooks::codex_cli::CONFIG_DIR_ENV, v),
            None => std::env::remove_var(crate::hooks::codex_cli::CONFIG_DIR_ENV),
        }
    }

    /// The registration, asserted from the binding side: twelve names, with
    /// `PreToolUse` among them.
    ///
    /// This array element **is** the registration, so it may only stand while
    /// `hook_output::codex_cli` can express a deny — dropping that arm and
    /// leaving this one discards every Codex deny before the developer sees it.
    #[test]
    fn codex_binding_event_list_is_the_twelve_with_pre_tool_use() {
        let b = binding_at(Path::new("/home/test/.codex"));
        let events = b.hook_event_types();
        assert_eq!(events.len(), 12, "all twelve of Codex's native events");
        assert!(
            events.contains(&"PreToolUse"),
            "PreToolUse is the registration — without it Codex is captured, never enforced: \
             {events:?}"
        );
        assert!(events.contains(&"Interrupt"));
        assert!(events.contains(&"PostCompact"));

        // The event that carries every deny is also the one a health check has
        // to demand back. Two arrays, one fact.
        assert!(
            b.load_bearing_events().contains(&"PreToolUse"),
            "a stripped PreToolUse row must read as unhealthy: {:?}",
            b.load_bearing_events()
        );
    }

    /// **The regression guard for the whole initiative.** Codex parses
    /// `permissionDecision: "ask"` and does not support it — it marks the hook
    /// run failed and continues the tool call. If `"ask"` ever appears here the
    /// degradation ladder starts emitting a silent fail-open.
    #[test]
    fn codex_capabilities_cannot_express_ask() {
        let b = binding_at(Path::new("/home/test/.codex"));
        assert_eq!(b.capabilities().expressible, &["allow", "deny"]);
    }

    // -----------------------------------------------------------------------
    // The arming check (D-07)
    //
    // Every one of these asserts the VALUES `liveness()` returns — `armed`,
    // `detail`, `remedy`, `code`. None of them reaches for a `Check` or a
    // headline string: the rendering is the shared renderer's, and I-1 owns its
    // two tests. A `Check` assertion here would be the second rendering path
    // the *one question, one set of detectors* invariant exists to prevent.
    // -----------------------------------------------------------------------

    /// The liveness cases invoke real login shells. Running six Git-for-Windows
    /// login shells concurrently can push otherwise instant probe commands past
    /// the five-second product deadline, which tests shell contention instead of
    /// the liveness dimension each case owns. A real doctor run performs one
    /// liveness check, so keep these process-level fixtures serial.
    static PROBE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn probe_test_guard() -> std::sync::MutexGuard<'static, ()> {
        PROBE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// A `hooks.json` whose `PreToolUse` row is ours, carrying a command that
    /// answers the way a healthy `openlatch-hook` does: a JSON object on
    /// stdout.
    ///
    /// The command is a real one and is really run, through `sh -lc`, exactly
    /// as Codex would run it — that IS Check A. Stubbing the invocation out
    /// would leave the one thing the #165 outage taught us to prove untested.
    fn install_probe_hook(root: &Path) -> InstalledHandler {
        std::fs::write(
            root.join("hooks.json"),
            json!({
                "hooks": {
                    "PreToolUse": [{
                        "matcher": "Bash",
                        "_openlatch": { "v": 1, "id": "x" },
                        "hooks": [{
                            "type": "command",
                            "command": "printf '{}'",
                            "timeout": 5,
                        }],
                    }],
                }
            })
            .to_string(),
        )
        .expect("write hooks.json");
        crate::hooks::codex_cli::installed_handler(root, PROBE_EVENT)
            .expect("the group we just wrote is ours")
    }

    /// Record trust the way Codex does: a `trusted_hash` under the key built
    /// from the indices our group was found at.
    fn trust_it(root: &Path, handler: &InstalledHandler, extra: &str) {
        let key = crate::hooks::codex_cli::trust_key(root, PROBE_EVENT, handler);
        std::fs::write(
            crate::hooks::codex_cli::config_toml_path(root),
            format!("{extra}[hooks.state.'{key}']\ntrusted_hash = \"codex-computed\"\n"),
        )
        .expect("write config.toml");
    }

    /// A written, correct, completely inert hook. Codex pushes a hook onto the
    /// executable list only when `enabled && (bypass || Managed || Trusted)`,
    /// so an untrusted one is never spawned: nothing calls us, nothing errors,
    /// and the file on disk looks perfect.
    ///
    /// This is the red the whole plan exists to produce, and the remedy has to
    /// be the one the developer can act on today.
    #[test]
    fn codex_untrusted_is_armed_false_with_a_hooks_remedy() {
        let _probe_guard = probe_test_guard();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        install_probe_hook(root);
        // No `config.toml` at all — a fresh self-serve install, before
        // `/hooks`. Codex has recorded no trusted hash for our group.

        let report = binding_at(root).liveness();

        assert_eq!(
            report.armed,
            Some(false),
            "an untrusted hook enforces nothing: {:?}",
            report.detail
        );
        assert_eq!(report.code, Some(ERR_HOOK_NOT_ARMED));
        let remedy = report.remedy.expect("a Some(false) MUST carry a remedy");
        assert!(
            remedy.contains("/hooks"),
            "the remedy is the one-time trust step: {remedy}"
        );
        assert!(
            remedy.contains("re-arms"),
            "and the trap behind most of these reds — a re-install that changes the command \
             re-arms the review: {remedy}"
        );
        // Check A precedes B, so a detail about the binary here would mean the
        // invocation failed and this test proved nothing about trust.
        let detail = report.detail.expect("a Some(false) explains itself");
        assert!(
            detail.contains("trusted hash"),
            "the FIRST failing dimension is trust, not the binary: {detail}"
        );
    }

    /// The other end: binary answers, Codex recorded a `trusted_hash`, nothing
    /// suppressed. Only then is Codex actually enforcing.
    #[test]
    fn codex_trusted_is_armed_true() {
        let _probe_guard = probe_test_guard();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        let handler = install_probe_hook(root);
        trust_it(root, &handler, "");

        let report = binding_at(root).liveness();

        assert_eq!(
            report.armed,
            Some(true),
            "all three dimensions hold: {:?}",
            report.detail
        );
        assert_eq!(report.code, None, "a proven-armed report carries no code");
        assert_eq!(report.remedy, None, "and nothing to remedy");
    }

    /// `allow_managed_hooks_only` is the one failure mode with **no runtime
    /// symptom at all**: Codex drops every non-managed hook with a bare
    /// `continue` and pushes no warning, so our hook sits on disk, listed
    /// nowhere, never executed.
    ///
    /// Trust is granted here on purpose — B holds, and C is the only thing
    /// left that can make the host dark.
    #[test]
    fn managed_only_suppression_is_armed_false() {
        let _probe_guard = probe_test_guard();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        let handler = install_probe_hook(root);
        trust_it(root, &handler, "");

        let requirements = root.join("requirements.toml");
        std::fs::write(&requirements, "[hooks]\nallow_managed_hooks_only = true\n")
            .expect("write requirements.toml");

        let report = CodexCliBinding {
            requirements_toml: Some(requirements),
            ..binding_at(root)
        }
        .liveness();

        assert_eq!(
            report.armed,
            Some(false),
            "a managed-only host drops a user-level hook silently: {:?}",
            report.detail
        );
        assert_eq!(report.code, Some(ERR_HOOK_NOT_ARMED));
        let remedy = report.remedy.expect("a Some(false) MUST carry a remedy");
        assert!(
            remedy.contains("managed_dir") && remedy.contains("requirements.toml"),
            "the remedy is managed delivery, not `/hooks`: {remedy}"
        );
    }

    /// **The "off is never a pass" guard for the suppression dimension.**
    ///
    /// A host where the system requirements layer cannot be consulted at all —
    /// Windows, where no path is pinned, or an unreadable file — must NOT
    /// report `armed: Some(true)`. `AGENTS.md` is explicit that green means
    /// enabled *and* proven working, and one of the three dimensions here was
    /// never read.
    ///
    /// This reddened when the branch returned `Dimension::Ok` with a caveat on
    /// the side: everything else about the host was healthy, so the caveat rode
    /// along on a green check nobody would read.
    #[test]
    fn unobservable_suppression_is_not_reported_as_armed() {
        let _probe_guard = probe_test_guard();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        let handler = install_probe_hook(root);
        trust_it(root, &handler, "");

        // Everything else is healthy; the requirements layer simply cannot be
        // consulted, which is exactly the Windows shape.
        let report = CodexCliBinding {
            requirements_toml: None,
            ..binding_at(root)
        }
        .liveness();

        assert_ne!(
            report.armed,
            Some(true),
            "a dimension that was never read cannot report armed: {:?}",
            report.detail
        );
        let detail = report.detail.expect("an unread dimension must say so");
        assert!(
            detail.contains("allow_managed_hooks_only"),
            "the detail must name what could not be observed: {detail}"
        );
    }

    /// **The regression guard for "every healthy host exits 7 forever".**
    ///
    /// `features.hooks` / `codex_hooks` / `plugin_hooks` are absent on every
    /// default host and their defaults are undocumented. If an absent key
    /// blocked `Enforced`, no host could ever reach it: `Some(false)` would
    /// ride on every correct install, and a `Pending` would be a warning —
    /// `counts.warned > 0` is Degraded, which is exit 7 from `doctor`, from
    /// `status` and from `init`.
    ///
    /// The uncertainty belongs in the `detail` text, and it is asserted here so
    /// it cannot be quietly dropped either.
    #[test]
    fn absent_feature_flag_does_not_block_armed() {
        let _probe_guard = probe_test_guard();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        let handler = install_probe_hook(root);
        // A config.toml with trust and no `[features]` table whatsoever.
        trust_it(root, &handler, "");

        let raw = std::fs::read_to_string(crate::hooks::codex_cli::config_toml_path(root))
            .expect("read config.toml");
        assert!(
            !raw.contains("features"),
            "the fixture is pointless unless the key really is absent: {raw}"
        );

        let report = binding_at(root).liveness();

        assert_eq!(
            report.armed,
            Some(true),
            "an absent feature flag is `no suppression observed`, never `unproven`: {:?}",
            report.detail
        );
        let detail = report
            .detail
            .expect("the caveats ride on the check we push");
        assert!(
            detail.contains("undocumented"),
            "the undocumented default is recorded in the text, not in the state: {detail}"
        );
        assert!(
            detail.contains("--profile"),
            "and so is what a per-invocation profile could override: {detail}"
        );
    }

    /// The asymmetry's other half: a key **present and `false`** is an observed
    /// suppression, and hooks are off wholesale.
    #[test]
    fn observed_feature_flag_false_is_armed_false() {
        let _probe_guard = probe_test_guard();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        let handler = install_probe_hook(root);
        trust_it(root, &handler, "[features]\nhooks = false\n\n");

        let report = binding_at(root).liveness();

        assert_eq!(
            report.armed,
            Some(false),
            "`features.hooks = false` switches Codex hooks off: {:?}",
            report.detail
        );
        assert_eq!(report.code, Some(ERR_HOOK_NOT_ARMED));
        let remedy = report.remedy.expect("a Some(false) MUST carry a remedy");
        assert!(
            remedy.contains("features.hooks"),
            "the remedy names the key that switched them off: {remedy}"
        );
    }

    /// The probe's `tool_name` is reserved on **both** ends, and this pins it.
    ///
    /// Outside `SHELL_TOOL_NAMES`, so `evaluate()` can never reach a rule with
    /// it — asserted against the literal, so a later widening that claimed the
    /// name reddens here rather than silently making a diagnostic able to match
    /// a live policy rule. And matched by the daemon's own ingest filter, so a
    /// rename on either side is caught rather than fabricating agent activity
    /// in the customer's audit trail.
    #[test]
    fn synthetic_probe_uses_a_non_evaluated_tool_name() {
        assert_eq!(DOCTOR_PROBE_TOOL_NAME, "OpenlatchDoctorProbe");
        assert!(
            !crate::core::policy::SHELL_TOOL_NAMES.contains(&DOCTOR_PROBE_TOOL_NAME),
            "a probe using an evaluated tool name could match a live policy rule: {:?}",
            crate::core::policy::SHELL_TOOL_NAMES
        );

        let payload = probe_payload();
        assert_eq!(payload["tool_name"], DOCTOR_PROBE_TOOL_NAME);
        assert_eq!(
            payload["tool_input"],
            json!({}),
            "an inert payload carries no command for anything to act on"
        );
        assert!(
            crate::daemon::handlers::is_doctor_probe(Some(&payload)),
            "the daemon must skip this envelope before the audit log"
        );
    }

    #[test]
    fn codex_cli_binding_is_arc_dyn_compatible() {
        let b = binding_at(Path::new("/tmp/.codex"));
        let _arc: Arc<dyn AgentBinding> = Arc::new(b);
    }
}