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
//! Codex CLI hook-output translator.
//!
//! A deliberate copy of `claude_code.rs`'s shape, not a shared abstraction
//! (I-2 D-03): the two contracts diverge in the tool-name namespace, in the
//! decision tier Codex lacks, in `updatedInput` being gated to `allow` only,
//! and in Codex carrying a second exit-code channel. A shared helper would
//! encode every one of those as a branch.
//!
//! The upstream shapes are vendored at
//! `schemas/vendor/codex-cli/hook-output.schema.json`, extracted from
//! codex-cli 0.150.1.
//!
//! | Event | allow / approve | deny | ask |
//! |-------|-----------------|------|-----|
//! | PreToolUse | `{}` | `hookSpecificOutput.permissionDecision = "deny"` **with a non-empty reason** | `{"systemMessage": reason}` |
//! | every other event | `{}` | `{}` | `{}` |
//!
//! # What this translator may never emit, and why the schema does not say so
//!
//! The vendored schema **permits** `permissionDecision: "ask"` — its
//! `PreToolUsePermissionDecisionWire` is `["allow", "deny", "ask"]`. The same
//! binary refuses it at runtime:
//!
//! ```text
//! PreToolUse hook returned unsupported permissionDecision:ask
//! PreToolUse hook returned unsupported permissionDecision:allow
//! PreToolUse hook returned permissionDecision:deny without a non-empty permissionDecisionReason
//! ```
//!
//! When Codex hits one of those it marks the hook run **failed**, reports the
//! error, and **continues the tool call**. So an `ask` — or an explicit
//! `allow`, or a deny with no reason — is a *silent fail-open* wearing
//! correct-looking JSON, which is the exact failure this unit exists to close.
//! The vendored schema cannot catch it; only
//! `codex_never_emits_an_unsupported_blocking_field` (below) can.
//!
//! Three consequences, all load-bearing:
//!
//! 1. **The plain-allow arm stays `{}` forever.** "Improving" it to an explicit
//!    `permissionDecision: "allow"` is a fail-open.
//! 2. **A deny always carries a non-empty reason.** Not a preference: a deny
//!    Codex rejects is a deny that fails open.
//! 3. **`decision`, `continue`, `stopReason` and `suppressOutput` are never
//!    emitted.** Codex parses each and supports none of them.

use super::{empty, Verdict};
use serde_json::{json, Value};

/// The reason attached to a deny that arrived without one. A verdict with no
/// reason is a policy-authoring gap; it is never a reason to risk the one
/// output that has to land.
const DEFAULT_DENY_REASON: &str = "Blocked by OpenLatch policy.";

/// Translate a Codex CLI verdict for the named event type.
///
/// `PreToolUse` is the only event with an actionable deny channel. Everything
/// else — `PermissionRequest`, `PostToolUse`, `UserPromptSubmit`,
/// `SessionStart`, `SessionEnd`, `PreCompact`, `PostCompact`, `Stop`,
/// `SubagentStop`, `SubagentStart`, `Interrupt`, and any event a later Codex
/// release adds — degrades to `{}`, the universal continue-normally signal.
pub fn translate(event: &str, verdict: &Verdict<'_>) -> Value {
    match event {
        "pre_tool_use" => pre_tool_use(verdict),
        _ => empty(),
    }
}

fn pre_tool_use(verdict: &Verdict<'_>) -> Value {
    match (verdict.decision, verdict.context) {
        ("deny", Some(ctx)) => deny(&format!("{}: {}", ctx.headline, ctx.body)),
        ("deny", None) => deny(verdict.reason.unwrap_or(DEFAULT_DENY_REASON)),

        // `("allow", _)` IS NOT A DEGRADED ASK. `allow` carrying a reason and a
        // context is produced today by the daemon's `attach_alert_context` when
        // a config-monitor alert is queued: it sets `context` and `reason` while
        // the wire verdict stays `allow`. It means "a config file changed", not
        // "a rule asked". Claude Code renders that `{}` on purpose
        // (`claude_code.rs`: "allow+context has no surface here — SessionStart
        // owns additionalContext for that"), and Codex matches it. A
        // `systemMessage` here would print an alert banner on every Codex tool
        // call while an alert is queued that a Claude user never sees.
        ("allow", _) => empty(),

        // Written now, unreachable until Autonomy Zone D14 widens the wire
        // `Verdict` enum past `Allow | Approve | Deny`. Render the REASON,
        // never the verdict: `permissionDecision: "ask"` is parsed, unsupported,
        // and continues the tool call. When D14 lands, the binding's
        // `expressible: &["allow", "deny"]` degrades ask -> allow daemon-side
        // before the hook sees it, and the `verdict.degraded` record is emitted
        // there, not here — so this is the belt-and-braces arm for a daemon that
        // did not. Degrading to `deny` instead would ESCALATE, which the
        // degradation ladder forbids.
        ("ask", _) => verdict
            .reason
            .map_or_else(empty, |r| json!({ "systemMessage": r })),

        // "approve" is not an ask — it falls here, to allow. So does any wire
        // value a future schema adds.
        _ => empty(),
    }
}

/// The one blocking channel Codex 0.150.1 honours, with the reason Codex
/// requires.
///
/// A blank reason is refused by Codex exactly as a missing one is, so an empty
/// or whitespace-only reason is replaced rather than forwarded — the deny has
/// to land.
fn deny(reason: &str) -> Value {
    let reason = if reason.trim().is_empty() {
        DEFAULT_DENY_REASON
    } else {
        reason
    };
    json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": reason,
        }
    })
}

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

    /// Codex's twelve hook events on the wire, plus a sentinel for whatever the
    /// next release adds.
    const EVENTS: [&str; 13] = [
        "pre_tool_use",
        "permission_request",
        "post_tool_use",
        "user_prompt_submit",
        "session_start",
        "session_end",
        "pre_compact",
        "post_compact",
        "stop",
        "subagent_stop",
        "subagent_start",
        "interrupt",
        "future_event_from_next_release",
    ];

    /// Every decision string the daemon can hand a translator today, plus the
    /// one Autonomy Zone D14 adds, plus a value no schema will ever carry.
    const DECISIONS: [&str; 5] = ["allow", "approve", "deny", "ask", "nonsense"];

    /// Walk every object in the output and hand each `(key, value)` to `check`.
    fn walk(value: &Value, check: &mut impl FnMut(&str, &Value)) {
        match value {
            Value::Object(map) => {
                for (k, v) in map {
                    check(k, v);
                    walk(v, check);
                }
            }
            Value::Array(items) => {
                for item in items {
                    walk(item, check);
                }
            }
            _ => {}
        }
    }

    /// **The guard for D-04**, and the only thing in the repo that can catch it:
    /// the vendored schema PERMITS `permissionDecision: "ask"`, so schema
    /// validation passes on the exact output that makes Codex mark the hook run
    /// failed and continue the tool call.
    ///
    /// For every event x every decision x reason present/absent x context
    /// present/absent, the output carries none of the fields Codex parses and
    /// does not support, and any `permissionDecision` it does carry is `"deny"`
    /// — the only value Codex honours.
    #[test]
    fn codex_never_emits_an_unsupported_blocking_field() {
        let ctx = VerdictContext {
            headline: "Configuration alert pending",
            body: "MCP server 'evil' was added; review before running.",
        };
        for event in EVENTS {
            for decision in DECISIONS {
                for reason in [None, Some("test reason")] {
                    for context in [None, Some(&ctx)] {
                        let verdict = Verdict {
                            decision,
                            reason,
                            context,
                        };
                        let out = translate(event, &verdict);
                        let label = format!(
                            "event={event} decision={decision} reason={reason:?} context={}",
                            context.is_some()
                        );
                        walk(&out, &mut |key, value| {
                            assert!(
                                !matches!(
                                    key,
                                    "decision" | "continue" | "stopReason" | "suppressOutput"
                                ),
                                "{label}: emitted unsupported field {key:?} -- Codex parses it, \
                                 marks the hook run failed and CONTINUES the tool call"
                            );
                            if key == "permissionDecision" {
                                assert_eq!(
                                    value.as_str(),
                                    Some("deny"),
                                    "{label}: `deny` is the only permissionDecision Codex \
                                     honours; `ask` and `allow` are both silent fail-opens"
                                );
                            }
                        });
                    }
                }
            }
        }
    }

    /// A deny that Codex rejects is a deny that fails open, and Codex rejects a
    /// deny whose `permissionDecisionReason` is missing or empty. So the field
    /// is present and non-empty in all four shapes a deny can arrive in.
    #[test]
    fn codex_deny_carries_the_reason() {
        let ctx = VerdictContext {
            headline: "Configuration alert pending",
            body: "MCP server 'evil' was added; review before running.",
        };
        let cases: [(&str, Verdict<'_>); 4] = [
            (
                "reason",
                Verdict {
                    decision: "deny",
                    reason: Some("credentials detected"),
                    context: None,
                },
            ),
            (
                "context",
                Verdict {
                    decision: "deny",
                    reason: None,
                    context: Some(&ctx),
                },
            ),
            (
                "neither",
                Verdict {
                    decision: "deny",
                    reason: None,
                    context: None,
                },
            ),
            (
                "empty reason",
                Verdict {
                    decision: "deny",
                    reason: Some("   "),
                    context: None,
                },
            ),
        ];

        for (label, verdict) in cases {
            let out = translate("pre_tool_use", &verdict);
            let specific = &out["hookSpecificOutput"];
            assert_eq!(
                specific["hookEventName"].as_str(),
                Some("PreToolUse"),
                "{label}"
            );
            assert_eq!(
                specific["permissionDecision"].as_str(),
                Some("deny"),
                "{label}"
            );
            let rendered = specific["permissionDecisionReason"]
                .as_str()
                .unwrap_or_else(|| panic!("{label}: a deny must carry permissionDecisionReason"));
            assert!(
                !rendered.trim().is_empty(),
                "{label}: Codex refuses `permissionDecision:deny` without a NON-EMPTY reason, \
                 and a refused deny fails open"
            );
        }

        // The rule's own words reach the terminal verbatim, and a context deny
        // inlines "headline: body" so the cloud's intent travels with it.
        let out = translate(
            "pre_tool_use",
            &Verdict {
                decision: "deny",
                reason: Some("Canary enforce"),
                context: None,
            },
        );
        assert_eq!(
            out,
            json!({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": "Canary enforce",
                }
            })
        );
        let with_context = translate(
            "pre_tool_use",
            &Verdict {
                decision: "deny",
                reason: None,
                context: Some(&ctx),
            },
        );
        let rendered = with_context["hookSpecificOutput"]["permissionDecisionReason"]
            .as_str()
            .expect("context deny carries a reason");
        assert!(rendered.contains("Configuration alert pending"));
        assert!(rendered.contains("MCP server 'evil'"));
    }

    /// Allow is `{}` with a reason, without one, and **with a context** — the
    /// last is the regression guard. `attach_alert_context` produces
    /// allow+reason+context today for a queued config-monitor alert, and it must
    /// render exactly as Claude Code's `pre_tool_use_allow_with_context_is_empty`
    /// does. An explicit `permissionDecision: "allow"` would also be schema-valid
    /// and would be a fail-open, since Codex does not support it.
    #[test]
    fn codex_allow_is_always_empty() {
        let ctx = VerdictContext {
            headline: "Heads up",
            body: "Two new skills landed.",
        };
        for decision in ["allow", "approve"] {
            for reason in [None, Some("a config file changed")] {
                for context in [None, Some(&ctx)] {
                    let verdict = Verdict {
                        decision,
                        reason,
                        context,
                    };
                    assert_eq!(
                        translate("pre_tool_use", &verdict),
                        empty(),
                        "decision={decision} reason={reason:?} context={}",
                        context.is_some()
                    );
                }
            }
        }
    }

    /// D-04. **Unreachable until Autonomy Zone D14** widens the wire `Verdict`
    /// enum: at HEAD it is `Allow | Approve | Deny` and `PolicyRuleMode` is
    /// `Observe | Enforce`, so no Ask rule can be authored and no Ask verdict can
    /// be produced. Asserted here and nowhere else — no live gate can fake a
    /// verdict the daemon cannot emit.
    #[test]
    fn codex_ask_renders_a_system_message() {
        let out = translate(
            "pre_tool_use",
            &Verdict {
                decision: "ask",
                reason: Some("This touches production credentials."),
                context: None,
            },
        );
        assert_eq!(
            out,
            json!({ "systemMessage": "This touches production credentials." })
        );
        assert!(
            out.get("hookSpecificOutput").is_none(),
            "an ask has no permissionDecision to express -- Codex has no ask tier"
        );

        // No reason means nothing to say, so nothing is said.
        let silent = translate(
            "pre_tool_use",
            &Verdict {
                decision: "ask",
                reason: None,
                context: None,
            },
        );
        assert_eq!(silent, empty());
    }

    /// `PreToolUse` is the only event with an actionable deny channel. Every
    /// other Codex event — including a future one — is `{}` for every decision.
    #[test]
    fn codex_non_pre_tool_use_is_empty() {
        let ctx = VerdictContext {
            headline: "Configuration alert pending",
            body: "MCP server 'evil' was added.",
        };
        for event in EVENTS.into_iter().filter(|e| *e != "pre_tool_use") {
            for decision in DECISIONS {
                for reason in [None, Some("test reason")] {
                    for context in [None, Some(&ctx)] {
                        let verdict = Verdict {
                            decision,
                            reason,
                            context,
                        };
                        assert_eq!(
                            translate(event, &verdict),
                            empty(),
                            "event={event} decision={decision} reason={reason:?} context={}",
                            context.is_some()
                        );
                    }
                }
            }
        }
    }
}