openlatch-client 0.5.4

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
//! Claude Code hook-output translator.
//!
//! Implements the Claude Code stdout contract documented in the upstream
//! hook-output JSON schema (vendored at
//! `schemas/vendor/claude-code/hook-output.schema.json`).
//!
//! Mapping rationale per event:
//!
//! | Event             | allow / optimize | block                                                       |
//! |-------------------|-----------------|--------------------------------------------------------------|
//! | PreToolUse        | `{}`            | `hookSpecificOutput.permissionDecision = "deny"` (reason inlined when `context` is present) |
//! | UserPromptSubmit  | `{}`            | `decision: "block"` (top-level)                              |
//! | PostToolUse       | `{}`            | `{}` — the tool already ran; deny has no actionable effect   |
//! | Stop / SubagentStop | `{}`          | `{}` — denying a stop would force a runaway loop             |
//! | Notification / PreCompact / SessionEnd | `{}`           | `{}` — no deny channel defined by Claude Code |
//! | SessionStart      | `additionalContext` when `context` present, else `{}` | `{}` — no deny channel |
//! | Unknown(_)        | `{}`            | `{}`                                                         |
//!
//! The `"ask"` decision is only meaningful for PreToolUse.
//!
//! OpenLatch's refusal verdict is spelled `block` (D14); `deny` is its
//! read-alias and is still accepted here, because a daemon predating the
//! rename may be the one answering this hook. Claude Code's own
//! `permissionDecision: "deny"` is a separate vocabulary and is unchanged.
//!
//! Claude Code treats `{}` as "hook passed, continue normally" for every
//! event type — so unknown events or degraded denies never break the
//! agent.

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

/// Translate a Claude Code verdict for the named event type.
pub fn translate(event: &str, verdict: &Verdict<'_>) -> Value {
    match event {
        "pre_tool_use" => pre_tool_use(verdict),
        "user_prompt_submit" => user_prompt_submit(verdict),
        "session_start" => session_start(verdict),
        // PostToolUse, Stop, SubagentStop, Notification, PreCompact,
        // SessionEnd, and any future/unknown event all degrade to the
        // universal safe default: {}.
        _ => empty(),
    }
}

fn pre_tool_use(verdict: &Verdict<'_>) -> Value {
    // deny+context inlines "headline: body" as permissionDecisionReason so
    // the cloud's intent travels on the wire even though Claude Code shows
    // its generic "blocked" message. allow+context has no surface here —
    // SessionStart owns additionalContext for that.
    //
    // `approve` deliberately does NOT take `core::policy::normalise_verdict`'s
    // `approve → Ask` mapping, and the divergence is the point rather than an
    // oversight. That function normalises an AUTHORED verdict on an inbound
    // policy-artifact parse, where `approve` is a rule's own sentence. Here the
    // token arrives as a DAEMON RESPONSE on the hook path, and the only daemon
    // that can still emit it is one predating D14 — where `approve` meant
    // "the user already confirmed this, let it through". So it falls to
    // `empty()`, which is allow-through and the correct reading of that token
    // from that sender. Mapping it to `ask` would newly prompt the developer on
    // every previously user-confirmed allow, and would fail toward a block
    // rather than toward the original bytes. The enforcement cost of reading it
    // this way is nil: a missed ASK is allow-and-flag, never a missed block.
    //
    // `normalise_verdict` could not be reused here in any case — it lives in
    // `core::policy`, which is `full-cli`-gated and never links into
    // `openlatch-hook`.
    let (decision, reason_owned): (&str, Option<String>) = match (verdict.decision, verdict.context)
    {
        ("block" | "deny", Some(ctx)) => ("deny", Some(format!("{}: {}", ctx.headline, ctx.body))),
        ("block" | "deny", None) => ("deny", verdict.reason.map(str::to_string)),
        ("ask", _) => ("ask", verdict.reason.map(str::to_string)),
        _ => return empty(),
    };
    let mut specific = json!({
        "hookEventName": "PreToolUse",
        "permissionDecision": decision,
    });
    if let Some(reason) = reason_owned {
        specific["permissionDecisionReason"] = Value::String(reason);
    }
    json!({ "hookSpecificOutput": specific })
}

/// SessionStart has no native deny channel — only `additionalContext`
/// injection (per Claude Code spec). When the cloud returns a `context`
/// payload we surface it here so the model is aware of pending alerts /
/// configuration state at the start of the session. Without context, the
/// translator emits `{}` and the session proceeds silently.
fn session_start(verdict: &Verdict<'_>) -> Value {
    let Some(ctx) = verdict.context else {
        return empty();
    };
    let combined = format!("{}\n\n{}", ctx.headline, ctx.body);
    json!({
        "hookSpecificOutput": {
            "hookEventName": "SessionStart",
            "additionalContext": combined,
        }
    })
}

pub fn translate_delivery(
    event: &str,
    verdict: &Verdict<'_>,
    updated_input: Option<&serde_json::Map<String, Value>>,
    additional_context: Option<&str>,
    system_message: Option<&str>,
    defer: bool,
) -> Value {
    if event == "pre_tool_use" && defer {
        return json!({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "defer"}});
    }
    if event == "pre_tool_use" && matches!(verdict.decision, "allow" | "optimize") {
        if let Some(updated) = updated_input {
            return json!({"hookSpecificOutput": {
                "hookEventName": "PreToolUse", "permissionDecision": "allow", "updatedInput": updated
            }});
        }
    }
    if event == "post_tool_use" {
        if let Some(context) = additional_context {
            return json!({"hookSpecificOutput": {
                "hookEventName": "PostToolUse", "additionalContext": context
            }});
        }
    }
    if matches!(event, "stop" | "subagent_stop") {
        if let Some(reason) = system_message {
            return json!({"decision": "block", "reason": reason});
        }
    }
    if event == "session_start" {
        if let Some(message) = system_message {
            return json!({"systemMessage": message});
        }
        if let Some(context) = additional_context {
            return json!({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}});
        }
    }
    translate(event, verdict)
}

fn user_prompt_submit(verdict: &Verdict<'_>) -> Value {
    // UserPromptSubmit's only agent-blocking channel is top-level
    // `decision: "block"`. `hookSpecificOutput.additionalContext` is for
    // context injection, which the forwarder never does — context flows
    // from the agent through the cloud, not the other way.
    if !matches!(verdict.decision, "block" | "deny") {
        return empty();
    }
    let reason = verdict.reason.unwrap_or("Blocked by OpenLatch");
    json!({ "decision": "block", "reason": reason })
}

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

    #[test]
    fn pre_tool_use_allow_is_empty() {
        let out = translate("pre_tool_use", &Verdict::allow());
        assert_eq!(out, empty());
    }

    /// The hook-plane reading of `approve`, pinned so a future agent cannot
    /// "unify" it with `core::policy::normalise_verdict`'s policy-plane reading
    /// by accident. See the rationale on `pre_tool_use` above:
    /// `approve_is_ask_when_authored_and_allow_through_when_answered` in
    /// `core::policy` holds both halves side by side.
    #[test]
    fn pre_tool_use_approve_is_allow_through_not_ask() {
        let v = Verdict {
            decision: "approve",
            reason: Some("the user already confirmed this"),
            context: None,
        };
        assert_eq!(translate("pre_tool_use", &v), empty());
    }

    #[test]
    fn pre_tool_use_deny_uses_hook_specific_output() {
        let v = Verdict {
            decision: "deny",
            reason: Some("credentials detected"),
            context: None,
        };
        let out = translate("pre_tool_use", &v);
        assert_eq!(
            out,
            json!({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": "credentials detected",
                }
            })
        );
    }

    /// D13 confirmation: a local policy deny renders into Claude Code's native
    /// deny shape with the deciding rule's `reason` **verbatim** — no prefix, no
    /// rewrite. This path never ran in production before local policy existed,
    /// so it is asserted rather than assumed. `deny` is the only agent surface
    /// v1 ships (the other four agents in the PRD's frozen list fall through to
    /// `{}` and are v1.1, together with their translators).
    #[test]
    fn pre_tool_use_deny_renders_a_policy_rules_reason_verbatim() {
        let v = Verdict {
            decision: "deny",
            reason: Some("Canary enforce"),
            context: None,
        };
        let out = translate("pre_tool_use", &v);
        assert_eq!(
            out,
            json!({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": "Canary enforce",
                }
            })
        );
    }

    #[test]
    fn pre_tool_use_ask_surfaces_without_reason() {
        let v = Verdict {
            decision: "ask",
            reason: None,
            context: None,
        };
        let out = translate("pre_tool_use", &v);
        assert_eq!(
            out,
            json!({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "ask",
                }
            })
        );
    }

    #[test]
    fn user_prompt_submit_deny_blocks() {
        let v = Verdict {
            decision: "deny",
            reason: Some("prompt injection"),
            context: None,
        };
        let out = translate("user_prompt_submit", &v);
        assert_eq!(
            out,
            json!({ "decision": "block", "reason": "prompt injection" })
        );
    }

    #[test]
    fn user_prompt_submit_allow_is_empty() {
        let out = translate("user_prompt_submit", &Verdict::allow());
        assert_eq!(out, empty());
    }

    #[test]
    fn stop_any_verdict_is_empty() {
        // Stop hook: every verdict degrades to {} so Claude
        // behaves exactly as it would without OpenLatch in the loop.
        for decision in ["allow", "ask", "optimize", "block", "deny"] {
            let v = Verdict {
                decision,
                reason: Some("irrelevant"),
                context: None,
            };
            assert_eq!(translate("stop", &v), empty(), "decision={decision}");
            assert_eq!(
                translate("subagent_stop", &v),
                empty(),
                "decision={decision}"
            );
        }
    }

    #[test]
    fn post_tool_use_any_verdict_is_empty() {
        for decision in ["allow", "ask", "optimize", "block", "deny"] {
            let v = Verdict {
                decision,
                reason: None,
                context: None,
            };
            assert_eq!(
                translate("post_tool_use", &v),
                empty(),
                "decision={decision}"
            );
        }
    }

    #[test]
    fn pre_tool_use_deny_with_context_emits_hard_deny() {
        let ctx = super::super::VerdictContext {
            headline: "Configuration alert pending",
            body: "MCP server 'evil' was added; review before running.",
        };
        let v = Verdict {
            decision: "deny",
            reason: None,
            context: Some(&ctx),
        };
        let out = translate("pre_tool_use", &v);
        assert_eq!(
            out["hookSpecificOutput"]["permissionDecision"]
                .as_str()
                .unwrap(),
            "deny",
            "deny+context must surface as a hard deny"
        );
        let reason = out["hookSpecificOutput"]["permissionDecisionReason"]
            .as_str()
            .unwrap();
        assert!(reason.contains("Configuration alert pending"));
        assert!(reason.contains("MCP server 'evil'"));
    }

    #[test]
    fn pre_tool_use_allow_with_context_is_empty() {
        // allow + context on PreToolUse is not a surface Claude Code can use
        // (no additionalContext channel here); we degrade to silent allow.
        let ctx = super::super::VerdictContext {
            headline: "Heads up",
            body: "Two new skills landed.",
        };
        let v = Verdict {
            decision: "allow",
            reason: None,
            context: Some(&ctx),
        };
        assert_eq!(translate("pre_tool_use", &v), empty());
    }

    #[test]
    fn session_start_with_context_injects_additional_context() {
        let ctx = super::super::VerdictContext {
            headline: "Configuration alert",
            body: "Two new skills were added since your last session.",
        };
        let v = Verdict {
            decision: "allow",
            reason: None,
            context: Some(&ctx),
        };
        let out = translate("session_start", &v);
        assert_eq!(
            out["hookSpecificOutput"]["hookEventName"].as_str().unwrap(),
            "SessionStart"
        );
        let injected = out["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap();
        assert!(injected.contains("Configuration alert"));
        assert!(injected.contains("new skills"));
    }

    #[test]
    fn session_start_without_context_is_empty() {
        let out = translate("session_start", &Verdict::allow());
        assert_eq!(out, empty());
    }

    #[test]
    fn unknown_event_is_empty() {
        let out = translate("some_future_event", &Verdict::allow());
        assert_eq!(out, empty());
    }

    #[test]
    fn notification_and_session_events_are_empty() {
        for ev in [
            "notification",
            "pre_compact",
            "session_start",
            "session_end",
        ] {
            assert_eq!(translate(ev, &Verdict::allow()), empty(), "event={ev}");
        }
    }

    #[test]
    fn delivery_uses_only_verified_claude_fields() {
        let updated = serde_json::json!({"command": "safe"})
            .as_object()
            .cloned()
            .unwrap();
        let rewritten = translate_delivery(
            "pre_tool_use",
            &Verdict::allow(),
            Some(&updated),
            None,
            None,
            false,
        );
        assert_eq!(
            rewritten["hookSpecificOutput"]["updatedInput"]["command"],
            "safe"
        );
        let deferred =
            translate_delivery("pre_tool_use", &Verdict::allow(), None, None, None, true);
        assert_eq!(
            deferred["hookSpecificOutput"]["permissionDecision"],
            "defer"
        );
    }
}