openlatch-client 0.5.8

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
//! Agent-agnostic reads of the two facts every consumer wants: the prompt a
//! developer typed, and the model that answered it.
//!
//! # Why this is here and not on the platform
//!
//! `data` is the agent's raw payload and is never rewritten — that is the
//! envelope's contract and nothing here breaks it. What these produce are
//! CloudEvents **extension attributes**, stamped beside `olverdict` and
//! `ollatencyms` at the single egress, so a consumer reads one field whatever
//! agent produced the event. The alternative is a per-agent parser in every
//! consumer, which is the same knowledge duplicated everywhere it can drift.
//!
//! # Why they match on SHAPE, never on agent
//!
//! Three shipped agents already disagree: Claude Code and Codex put the prompt
//! at `prompt`, Cline nests it at `userPromptSubmit.prompt`. A `match source`
//! would answer `None` for the fourth agent and for every fork of one — and
//! `source` is an open string precisely so an unknown agent round-trips. So
//! these probe the two shapes that exist and stay silent otherwise. A new agent
//! using either gets normalized with no code change; one using neither gets no
//! attribute, which is the honest answer rather than a guess.

use serde_json::Value;

/// The prompt a developer submitted, if this payload carries one.
///
/// Checked top-level first: that is the plain shape, and an agent that nests a
/// DIFFERENT `prompt` deeper should not outrank it.
pub fn prompt_of(data: &Value) -> Option<&str> {
    field(data, &["prompt"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// The tool an action names, in whichever spelling the agent used.
///
/// `tool_name` for Claude Code and Codex CLI, `toolName` for Cline — flat on
/// Cline's plugin lane, nested under `preToolUse` / `postToolUse` on its file
/// lane.
pub fn tool_name_of(data: &Value) -> Option<&str> {
    field(data, &["tool_name", "toolName"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// Every spelling of the tool's argument container.
///
/// Public so a caller that wants the POINTER rather than the value asks for the
/// same field by the same name — [`pointer_to`] and [`tool_input_of`] reading
/// two different lists is a bug that would show up as a pointer aimed at the
/// wrong half of the payload.
pub const TOOL_INPUT_KEYS: &[&str] = &["tool_input", "parameters"];

/// Every spelling of the tool's result. See [`TOOL_INPUT_KEYS`].
pub const TOOL_RESULT_KEYS: &[&str] = &["tool_result", "result", "tool_response"];

/// The tool's argument container, whole and untouched.
pub fn tool_input_of(data: &Value) -> Option<&Value> {
    field(data, TOOL_INPUT_KEYS)
}

/// Whether the tool call succeeded, when the payload says so.
///
/// Cline states it outright as `postToolUse.success`. Claude Code and Codex
/// describe the failure instead — an `is_error` inside the response, or the
/// event type itself being the failure variant, which the caller knows and this
/// function does not. Absent when nothing said either way: a tool call whose
/// outcome was never reported is not a successful one.
pub fn tool_ok_of(data: &Value) -> Option<bool> {
    if let Some(success) = field(data, &["success"]).and_then(Value::as_bool) {
        return Some(success);
    }
    tool_result_of(data)?
        .get("is_error")
        .and_then(Value::as_bool)
        .map(|is_error| !is_error)
}

/// How long the tool took, in milliseconds, when the agent measured it.
pub fn duration_ms_of(data: &Value) -> Option<u64> {
    field(data, &["duration_ms", "durationMs", "executionTimeMs"])?.as_u64()
}

/// The agent's own name for this hook, before it was normalized into the wire
/// `type` — `PreToolUse`, `UserPromptSubmit`. Worth carrying because it is what
/// an agent's own documentation and logs call the event.
pub fn native_event_of(data: &Value) -> Option<&str> {
    field(data, &["hook_event_name", "hookName"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// The turn this event belongs to, for an agent that numbers turns within a
/// session. Codex CLI does; nothing else shipped here does yet.
pub fn turn_id_of(data: &Value) -> Option<&str> {
    field(data, &["turn_id", "turnId"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// The agent software's own version, when it reports one.
///
/// Two spellings, both from agents rather than invented here: the neutral
/// `agent_version`, and Cline's `clineVersion`. A version key named after some
/// future agent is a one-line addition; guessing at `*Version` by suffix would
/// pick up the editor's version, the plugin's, or the schema's.
pub fn agent_version_of(data: &Value) -> Option<&str> {
    field(data, &["agent_version", "clineVersion"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// What the tool answered.
///
/// Three spellings and no winner among them: Claude Code and Codex send
/// `tool_response`, and the zone contract has always read `tool_result` and
/// `result` as well.
pub fn tool_result_of(data: &Value) -> Option<&Value> {
    field(data, TOOL_RESULT_KEYS)
}

/// The provider's own id for this tool call — the join key between a
/// `pre_tool_use` and the `post_tool_use` that answers it.
pub fn tool_use_id_of(data: &Value) -> Option<&str> {
    field(data, &["tool_use_id", "toolUseId"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// The directory the action ran in.
///
/// Cline names no `cwd` at all; it sends `workspaceRoots`, and the first entry
/// is the one its own tools resolve relative paths against.
pub fn cwd_of(data: &Value) -> Option<&str> {
    if let Some(cwd) = field(data, &["cwd"])
        .and_then(Value::as_str)
        .and_then(non_empty)
    {
        return Some(cwd);
    }
    field(data, &["workspaceRoots"])?
        .as_array()?
        .first()?
        .as_str()
        .and_then(non_empty)
}

/// The session this event belongs to, in whichever spelling the agent used.
///
/// Claude Code and Codex CLI say `session_id`; Cline calls a session a task and
/// says `taskId`. Same thing on the wire: the id the agent's own transcript is
/// filed under.
pub fn session_id_of(data: &Value) -> Option<&str> {
    field(data, &["session_id", "sessionId", "taskId"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// The developer's prompt and the mode it was submitted in.
///
/// Cline does not send a prompt; it sends a document. Every prompt arrives
/// wrapped as `<user_input mode="act">…</user_input>`, and the wrapper is the
/// agent's own framing, not something the developer typed. Stored whole it
/// becomes the session's label on the platform, so a fleet's sessions read
/// `<user_input mode="act">hey y</user_input>` instead of `hey y`.
///
/// **Deliberately not a parser.** The wrapper is unwrapped and the mode is
/// lifted out; nothing else about the contents is interpreted. An agent is free
/// to put anything inside, and guessing at its meaning is how a normalizer
/// starts lying. Anything that does not match the exact wrapper shape is
/// returned untouched.
pub fn prompt_and_mode(data: &Value) -> (Option<&str>, Option<&str>) {
    let Some(raw) = prompt_of(data) else {
        return (None, None);
    };
    let Some(rest) = raw.strip_prefix("<user_input") else {
        return (Some(raw), None);
    };
    let Some((attrs, body)) = rest.split_once('>') else {
        return (Some(raw), None);
    };
    let Some(inner) = body.strip_suffix("</user_input>") else {
        return (Some(raw), None);
    };
    let mode = attrs
        .split_once("mode=\"")
        .and_then(|(_, m)| m.split_once('"'))
        .map(|(m, _)| m)
        .and_then(non_empty);
    (non_empty(inner.trim()).or(Some(raw)), mode)
}

/// Every agent's payload, in one shape.
///
/// # Why `data` is rewritten, when it used to be forwarded verbatim
///
/// Two agents is not a contract. Claude Code and Codex CLI send the same flat
/// snake_case keys — Codex adopted Claude Code's hook convention — so every
/// consumer read `tool_name` and `tool_input` off the top level and it worked,
/// not by agreement but by coincidence. Cline sends camelCase nested under each
/// hook's own name, and every one of those reads returned nothing: captured
/// events, null columns, blank screens.
///
/// So the mapping happens once, here, and what travels is the shape everyone
/// already reads. The original is not lost — it rides under
/// `raw_agent_payload`, and it is the only thing that does.
///
/// # What is returned
///
/// `None` when the payload is **already** the common shape, which is the case
/// for every Claude Code and Codex CLI event. Nothing is rewritten and no
/// `raw_agent_payload` is added, because it would be a byte-for-byte copy of
/// its own siblings on a wire with a 256 KB cap. Its absence is therefore
/// meaningful: this agent speaks the common shape natively.
///
/// `Some(mapped)` when the payload had to be remapped. Only then is the
/// original carried, and only then is anything duplicated.
pub fn to_common(data: &Value) -> Option<Value> {
    let mut common = serde_json::Map::new();
    let (prompt, mode) = prompt_and_mode(data);

    let mut put = |key: &str, value: Option<Value>| {
        if let Some(value) = value {
            common.insert(key.to_string(), value);
        }
    };
    let text = |v: Option<&str>| v.map(|s| Value::String(s.to_string()));

    put("hook_event_name", text(native_event_of(data)));
    put("session_id", text(session_id_of(data)));
    put("cwd", text(cwd_of(data)));
    put("prompt", text(prompt));
    put("tool_name", text(tool_name_of(data)));
    put("tool_input", tool_input_of(data).cloned());
    put("tool_response", tool_result_of(data).cloned());
    put("tool_use_id", text(tool_use_id_of(data)));
    put("turn_id", text(turn_id_of(data)));
    put("agent_version", text(agent_version_of(data)));
    put("duration_ms", duration_ms_of(data).map(Value::from));
    // The agent's own form, whatever it is: a bare slug or `{provider, slug}`.
    // Rewriting it into one of the two would discard the half the other names.
    put("model", data.get("model").cloned());

    // Already the common shape? Then leave it alone. A mode means the prompt
    // was unwrapped, which is a rewrite however well the other keys line up.
    if mode.is_none() && common.iter().all(|(k, v)| data.get(k) == Some(v)) {
        return None;
    }

    let mut raw = data.clone();
    if let (Some(mode), Some(obj)) = (mode, raw.as_object_mut()) {
        // The mode IS already in the raw payload, inside the wrapper text. It
        // is lifted to a key of its own so a consumer never has to re-parse
        // the wrapper this function exists to remove.
        obj.insert("mode".to_string(), Value::String(mode.to_string()));
    }
    common.insert("raw_agent_payload".to_string(), raw);
    Some(Value::Object(common))
}

/// Read a field by any of its spellings: top level first, then one level down
/// under any key.
///
/// The second pass is what reads Cline's file lane, whose every hook nests its
/// own fields under the hook's name (`preToolUse.toolName`,
/// `userPromptSubmit.prompt`) — and any future agent that groups its fields the
/// same way, with no code change and no `match source`.
///
/// Three bounds, all load-bearing:
///
/// - **Every spelling at the top outranks every spelling below it.** An agent
///   that sends both keeps the meaning it had before this function existed.
/// - **Exactly one level, never recursive.** An unbounded search over a payload
///   we do not control is how you pick up a `prompt` that means something else
///   entirely — a tool argument named `prompt`, a nested transcript entry.
/// - **Never into a tool's arguments or its answer.** One level is not far
///   enough on its own: `tool_input` IS one level, so the argument named
///   `prompt` the bound above warns about was exactly what it returned. See
///   [`is_argument_container`].
fn field<'a>(data: &'a Value, keys: &[&str]) -> Option<&'a Value> {
    located(data, keys).map(|(_, value)| value)
}

/// Where a field was found, as an RFC 6901 JSON Pointer into `data`.
///
/// The pointer is how a heavy field travels. `tool_input` on a file write
/// carries the whole file, and copying that into an extension attribute would
/// duplicate it on a wire with a 256 KB batch cap — for a value the consumer
/// already has, verbatim, in `data`. Twenty-odd bytes saying where it sits cost
/// nothing and truncate nothing.
///
/// `None` when the field is absent, exactly like [`field`]: a pointer to
/// nowhere is worse than no pointer.
pub fn pointer_to(data: &Value, keys: &[&str]) -> Option<String> {
    located(data, keys).map(|(pointer, _)| pointer)
}

/// The one probe both readers share: the same order, the same bounds, and the
/// pointer and the value can never disagree about which one it found.
fn located<'a>(data: &'a Value, keys: &[&str]) -> Option<(String, &'a Value)> {
    for key in keys {
        if let Some(found) = data.get(key) {
            return Some((format!("/{}", escape(key)), found));
        }
    }
    let object = data.as_object()?;
    keys.iter().find_map(|key| {
        object
            .iter()
            .filter(|(outer, _)| !is_argument_container(outer))
            .find_map(|(outer, nested)| {
                nested
                    .get(key)
                    .map(|found| (format!("/{}/{}", escape(outer), escape(key)), found))
            })
    })
}

/// Whether a key holds the arguments or the answer of a tool call, rather than
/// a hook's own fields.
///
/// The nested pass exists for one shape: an agent that wraps each hook's fields
/// under that hook's name (`preToolUse.toolName`). A payload whose outer key is
/// `tool_input` is not that shape — it is a flat payload, and what is inside is
/// the tool's data, not the hook's.
///
/// Without this the one-level bound does not hold where it matters most. Claude
/// Code's `Task` tool takes an argument literally named `prompt`, so
/// `{tool_name: "Task", tool_input: {prompt: "…"}}` answered [`prompt_of`] with
/// the sub-agent's instructions — one level down, exactly as documented, and
/// exactly the confusion the one-level bound was written to prevent. It reaches
/// `olprompt`, and the platform promotes that to the session's opening prompt.
///
/// Scoped to the nested pass only: at the top level these keys ARE the field
/// being asked for, which is how [`tool_input_of`] and [`tool_result_of`] read.
fn is_argument_container(key: &str) -> bool {
    TOOL_INPUT_KEYS.contains(&key) || TOOL_RESULT_KEYS.contains(&key)
}

/// RFC 6901's two escapes, in the order the spec requires: `~` first, then `/`.
///
/// Reversing them would turn a literal `~1` into a path separator on the way
/// back. No agent ships a key like that today, which is exactly why it would be
/// found late and by someone else.
fn escape(token: &str) -> String {
    token.replace('~', "~0").replace('/', "~1")
}

/// The model that served the turn, as `(provider, slug)`.
///
/// Both halves are optional and independent: an agent may name a model with no
/// provider, and reporting `unknown` for the missing half would be inventing a
/// value the agent did not send.
pub fn model_of(data: &Value) -> (Option<&str>, Option<&str>) {
    let Some(model) = data.get("model") else {
        return (None, None);
    };
    // A bare string is the model itself — there is no provider to report.
    if let Some(slug) = model.as_str() {
        return (None, non_empty(slug));
    }
    (
        model
            .get("provider")
            .and_then(Value::as_str)
            .and_then(non_empty),
        model
            .get("slug")
            .and_then(Value::as_str)
            .and_then(non_empty),
    )
}

/// An empty string is not a value. Stamping `olprompt: ""` would make a
/// consumer's "did this event carry a prompt" test true for one that did not.
fn non_empty(s: &str) -> Option<&str> {
    let t = s.trim();
    (!t.is_empty()).then_some(s)
}

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

    /// Every shipped agent's real shape, and a shape none of them use.
    #[test]
    fn the_prompt_is_found_by_shape_across_agents() {
        // Claude Code and Codex — verified against this crate's own fixtures.
        assert_eq!(
            prompt_of(&json!({"prompt": "hello", "session_id": "abc"})),
            Some("hello")
        );
        // Cline — verified against a live 4.1.17 payload.
        assert_eq!(
            prompt_of(&json!({
                "hookName": "UserPromptSubmit",
                "userPromptSubmit": {"prompt": "hey there !!"}
            })),
            Some("hey there !!")
        );
        // An agent this build has never seen, nesting under its own name.
        assert_eq!(
            prompt_of(&json!({"someFutureHook": {"prompt": "p"}})),
            Some("p")
        );
        // Nothing to report is `None`, never a placeholder.
        assert_eq!(prompt_of(&json!({"toolName": "Bash"})), None);
        assert_eq!(prompt_of(&json!({"prompt": "   "})), None);
    }

    /// Cline's file lane, the shape every one of its hooks actually sends.
    ///
    /// Verified against the 4.1.17 bundle, which builds its hook input as
    /// `{taskId, preToolUse: {toolName, parameters}}` — and against a live
    /// capture for the events this install has on disk. Nothing in the client
    /// read one level down before, so every one of these was absent.
    #[test]
    fn clines_nested_hook_shape_reads_the_same_as_a_flat_one() {
        let nested = json!({
            "taskId": "conv_1789665246332_em78z12",
            "hookName": "PreToolUse",
            "clineVersion": "4.1.17",
            "workspaceRoots": ["/work/scratch"],
            "preToolUse": {
                "toolName": "execute_command",
                "parameters": {"command": "rm -rf /tmp"}
            }
        });
        assert_eq!(tool_name_of(&nested), Some("execute_command"));
        assert_eq!(
            tool_input_of(&nested),
            Some(&json!({"command": "rm -rf /tmp"}))
        );
        assert_eq!(cwd_of(&nested), Some("/work/scratch"));

        // Its post hook carries the result and how long the tool took.
        let post = json!({
            "taskId": "conv_1",
            "postToolUse": {"toolName": "execute_command", "result": "ok", "success": true}
        });
        assert_eq!(tool_result_of(&post), Some(&json!("ok")));

        // Cline's plugin lane sends the same two fields flat, with no task id.
        let flat = json!({"toolName": "execute_command", "parameters": {"command": "ls"}});
        assert_eq!(tool_name_of(&flat), Some("execute_command"));
        assert_eq!(tool_input_of(&flat), Some(&json!({"command": "ls"})));
    }

    /// Claude Code and Codex are unchanged by the nested probe, and an agent
    /// that sends both spellings keeps the meaning it had before.
    #[test]
    fn the_native_spelling_outranks_every_nested_one() {
        let native = json!({
            "session_id": "sess_a",
            "cwd": "/repo",
            "tool_name": "Bash",
            "tool_input": {"command": "cargo test"},
            "tool_use_id": "toolu_01",
            "nested": {"tool_name": "NotThis", "tool_input": {"command": "nor this"}}
        });
        assert_eq!(tool_name_of(&native), Some("Bash"));
        assert_eq!(
            tool_input_of(&native),
            Some(&json!({"command": "cargo test"}))
        );
        assert_eq!(tool_use_id_of(&native), Some("toolu_01"));
        assert_eq!(cwd_of(&native), Some("/repo"));

        // Absent stays absent — no placeholder, at either level.
        let empty = json!({"hookName": "Stop", "taskId": "conv_1"});
        assert_eq!(tool_name_of(&empty), None);
        assert_eq!(tool_input_of(&empty), None);
        assert_eq!(tool_result_of(&empty), None);
        assert_eq!(tool_use_id_of(&empty), None);
        assert_eq!(cwd_of(&empty), None);
    }

    /// The pointer says where the value was found, at either level, and the
    /// two readers can never disagree about which one that is.
    #[test]
    fn a_pointer_resolves_to_the_value_the_reader_returns() {
        for data in [
            json!({"tool_input": {"command": "cargo test"}}),
            json!({"preToolUse": {"parameters": {"command": "cargo test"}}}),
            json!({"parameters": {"command": "cargo test"}}),
        ] {
            let pointer = pointer_to(&data, TOOL_INPUT_KEYS).expect("a pointer");
            assert_eq!(
                data.pointer(&pointer),
                tool_input_of(&data),
                "pointer {pointer} and reader disagree for {data}"
            );
            assert_eq!(
                data.pointer(&pointer).and_then(|v| v.get("command")),
                Some(&json!("cargo test"))
            );
        }

        // Absent is absent: a pointer to nowhere is worse than no pointer.
        assert_eq!(pointer_to(&json!({"prompt": "hi"}), TOOL_INPUT_KEYS), None);
    }

    /// RFC 6901 escaping, in the order the spec requires.
    ///
    /// No shipped agent uses a key like this. That is exactly why an unescaped
    /// pointer would be found by someone else, much later.
    #[test]
    fn pointer_tokens_are_escaped() {
        let data = json!({"a/b": {"tool_input": 1}, "c~d": {"tool_input": 2}});
        let pointer = pointer_to(&data, TOOL_INPUT_KEYS).expect("a pointer");
        assert!(
            pointer == "/a~1b/tool_input" || pointer == "/c~0d/tool_input",
            "unexpected pointer: {pointer}"
        );
        assert!(data.pointer(&pointer).is_some(), "{pointer} must resolve");
    }

    /// The rest of the normalized facts, on the shapes the three shipped agents
    /// actually send.
    #[test]
    fn the_remaining_facts_read_across_agents() {
        let cline_post = json!({
            "taskId": "conv_1",
            "hookName": "PostToolUse",
            "clineVersion": "4.1.17",
            "postToolUse": {
                "toolName": "execute_command",
                "result": "done",
                "success": false,
                "executionTimeMs": 1234
            }
        });
        assert_eq!(tool_ok_of(&cline_post), Some(false));
        assert_eq!(duration_ms_of(&cline_post), Some(1234));
        assert_eq!(native_event_of(&cline_post), Some("PostToolUse"));
        assert_eq!(agent_version_of(&cline_post), Some("4.1.17"));
        assert_eq!(turn_id_of(&cline_post), None);

        // Claude Code and Codex describe the failure instead of the success.
        let claude_post = json!({
            "hook_event_name": "PostToolUse",
            "tool_name": "Bash",
            "tool_response": {"is_error": true, "stdout": ""}
        });
        assert_eq!(tool_ok_of(&claude_post), Some(false));
        assert_eq!(
            tool_ok_of(&json!({"tool_response": {"is_error": false}})),
            Some(true)
        );

        // Codex numbers its turns; nothing else shipped here does.
        let codex = json!({"session_id": "s", "turn_id": "t_1", "hook_event_name": "PreToolUse"});
        assert_eq!(turn_id_of(&codex), Some("t_1"));

        // An outcome nobody reported is not a successful one.
        assert_eq!(tool_ok_of(&json!({"tool_name": "Bash"})), None);
        assert_eq!(duration_ms_of(&json!({"tool_name": "Bash"})), None);
        assert_eq!(agent_version_of(&json!({"tool_name": "Bash"})), None);
    }

    /// One level, and no further. A tool argument called `prompt` is not the
    /// developer's prompt, and a rule that matched one would be matching the
    /// agent's own text back at it.
    #[test]
    fn the_probe_never_descends_past_one_level() {
        let deep = json!({"a": {"b": {"prompt": "buried", "tool_name": "Buried"}}});
        assert_eq!(prompt_of(&deep), None);
        assert_eq!(tool_name_of(&deep), None);
    }

    #[test]
    fn the_model_is_read_without_inventing_the_missing_half() {
        assert_eq!(
            model_of(&json!({"model": {"provider": "ollama", "slug": "qwen2.5-coder:7b"}})),
            (Some("ollama"), Some("qwen2.5-coder:7b"))
        );
        // A bare string names the model and says nothing about the provider.
        assert_eq!(
            model_of(&json!({"model": "claude-opus-5"})),
            (None, Some("claude-opus-5"))
        );
        // Cline sends this verbatim when it cannot resolve the model. It is the
        // AGENT's value and rides in `data` untouched; what must not happen is
        // it being promoted into the normalized attribute as though we knew it.
        assert_eq!(
            model_of(&json!({"model": {"provider": "unknown", "slug": "unknown"}})),
            (Some("unknown"), Some("unknown"))
        );
        assert_eq!(model_of(&json!({})), (None, None));
    }

    /// Cline sends a document, not a prompt.
    ///
    /// Every Cline prompt arrives wrapped as `<user_input mode="act">…`, which
    /// is the agent's own framing. Stored whole it becomes the session's label
    /// on the platform, so real sessions read
    /// `<user_input mode="act">hey y</user_input>` instead of `hey y`.
    #[test]
    fn clines_wrapper_is_removed_and_its_mode_kept() {
        let data = json!({
            "taskId": "conv_1",
            "hookName": "UserPromptSubmit",
            "userPromptSubmit": {"prompt": "<user_input mode=\"act\">hey y</user_input>"}
        });
        assert_eq!(prompt_and_mode(&data), (Some("hey y"), Some("act")));

        let mapped = to_common(&data).expect("a wrapped prompt is a rewrite");
        assert_eq!(mapped["prompt"], "hey y");
        // The mode is lifted beside the original so nobody re-parses the wrapper.
        assert_eq!(mapped["raw_agent_payload"]["mode"], "act");
        // And the wrapper itself still exists, untouched, in the original.
        assert_eq!(
            mapped["raw_agent_payload"]["userPromptSubmit"]["prompt"],
            "<user_input mode=\"act\">hey y</user_input>"
        );
    }

    /// Anything that is not exactly that wrapper is left alone.
    ///
    /// This is an unwrapper, not a parser: an agent may put anything in a
    /// prompt, and guessing at its meaning is how a normalizer starts lying.
    #[test]
    fn a_prompt_that_is_not_wrapped_is_untouched() {
        for raw in [
            "just a prompt",
            "<user_input mode=\"act\">unterminated",
            "look at <user_input mode=\"act\">this</user_input> inline",
        ] {
            let data = json!({"prompt": raw});
            let (prompt, _) = prompt_and_mode(&data);
            assert_eq!(prompt, Some(raw), "must not rewrite {raw:?}");
        }

        // A bare `<user_input>` with no mode still unwraps — the wrapper is
        // noise whether or not it declared one.
        let bare = json!({"prompt": "<user_input>hi</user_input>"});
        assert_eq!(prompt_and_mode(&bare), (Some("hi"), None));
    }

    /// A tool ARGUMENT named `prompt` is not the developer's prompt.
    ///
    /// Claude Code's `Task` tool takes one, so this payload is the ordinary
    /// shape of delegating to a sub-agent — not a corner case. It reached
    /// `olprompt`, and the platform promotes `olprompt` to the session's
    /// opening prompt, so the fleet's sessions were labelled with whatever the
    /// agent last told a sub-agent to do.
    #[test]
    fn a_tool_argument_is_never_mistaken_for_the_prompt() {
        let task = json!({
            "hook_event_name": "PreToolUse",
            "tool_name": "Task",
            "tool_input": {"description": "review", "prompt": "SUBAGENT PROMPT"}
        });
        assert_eq!(prompt_of(&task), None);

        // The same guard, on every field the nested pass serves: what is inside
        // a tool's arguments describes the tool, not the hook.
        let shadowed = json!({
            "tool_name": "Task",
            "tool_input": {"cwd": "/tmp/sub", "toolName": "Inner", "prompt": "x"}
        });
        assert_eq!(cwd_of(&shadowed), None);
        assert_eq!(tool_name_of(&shadowed), Some("Task"));

        // And the shape the nested pass exists for still reads: the wrapper is
        // a hook name, not an argument container.
        let cline = json!({"userPromptSubmit": {"prompt": "the real prompt"}});
        assert_eq!(prompt_of(&cline), Some("the real prompt"));

        // Top level is untouched — there these keys ARE the field asked for.
        let flat = json!({"tool_input": {"command": "ls"}, "tool_result": "ok"});
        assert_eq!(tool_input_of(&flat), Some(&json!({"command": "ls"})));
        assert_eq!(tool_result_of(&flat), Some(&json!("ok")));
    }
}