openlatch-client 0.6.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! 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.
///
/// Claude Code and Codex say `tool_use_id`. Cline's SDK-built hosts carry the
/// id too, in three places: `toolCallId` flat on the plugin lane, and on the
/// file lane inside the record the hook describes — `tool_call.id` before the
/// call, `tool_result.id` after it. Read by exact pointer, never by a probe for
/// any `id`: an `id` one level down is as likely to be a message's or a file's.
///
/// Only an id the AGENT sent. [`common_tool_use_id_of`] adds the derived one,
/// and a caller that keys anything durable on "same call" — the lane dedup —
/// must use this function, because two genuinely separate `ls` calls derive the
/// same id.
pub fn tool_use_id_of(data: &Value) -> Option<&str> {
    field(data, &["tool_use_id", "toolUseId", "toolCallId"])
        .or_else(|| data.pointer("/tool_call/id"))
        .or_else(|| data.pointer("/tool_result/id"))
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// Keys whose value is a string by meaning, whatever it looks like.
///
/// Cline's `parameters` is a `Record<string, string>`: its SDK hosts
/// `JSON.stringify` every non-string value per key, and its classic host sends
/// every value as the string the model wrote. So a string that parses as JSON
/// is ambiguous — a stringified array, or a `package.json` the agent is about
/// to write. These keys are never re-parsed: a file's content, a command line
/// and a path are text, and turning one into an object would change what the
/// platform shows and what a rule matches.
const TEXT_PARAMS: &[&str] = &[
    "command",
    "path",
    "file_path",
    "content",
    "diff",
    "patch",
    "old_text",
    "new_text",
    "regex",
    "file_pattern",
    "url",
    "uri",
    "prompt",
    "query",
    "question",
    "response",
    "result",
    "text",
    "input",
    "server_name",
    "tool_name",
];

/// Undo the per-key `JSON.stringify` Cline applies to `parameters`.
///
/// Only a value that parses to an object or an array is replaced, and never
/// under a [`TEXT_PARAMS`] key. A scalar stays the string it arrived as: `"true"`
/// from the classic host is what the model wrote, and turning `"123"` into a
/// number would change nothing a consumer needs and break a hash that pairs a
/// pre with its post.
///
/// Duplicated, deliberately, by `core::policy::evaluate::reparse_stringified`:
/// `core::policy` is a leaf and may not import this module, and its copy keeps
/// its own narrower job — reading the command a rule matches.
fn reparse_params(params: &Value) -> Value {
    let Some(object) = params.as_object() else {
        return params.clone();
    };
    let reparsed = object
        .iter()
        .map(|(key, value)| {
            let parsed = match value.as_str() {
                Some(raw) if !TEXT_PARAMS.contains(&key.as_str()) => {
                    let trimmed = raw.trim_start();
                    if trimmed.starts_with('{') || trimmed.starts_with('[') {
                        serde_json::from_str::<Value>(raw)
                            .ok()
                            .filter(|v| v.is_object() || v.is_array())
                    } else {
                        None
                    }
                }
                _ => None,
            };
            (key.clone(), parsed.unwrap_or_else(|| value.clone()))
        })
        .collect();
    Value::Object(reparsed)
}

/// Whether the tool name was spelled `toolName` — Cline's shape.
///
/// **The shape, not the agent.** Every other agent shipped here spells it
/// `tool_name` and already names its tools in the common vocabulary; a payload
/// that says `toolName` is one whose tool ids are the agent's own. So the
/// vocabulary mapping below keys on the SPELLING, and a fork of Cline — or any
/// agent that adopts its shape — is mapped with no code change.
fn is_camel_tool_shape(data: &Value) -> bool {
    matches!(
        located(data, &["tool_name", "toolName"]),
        Some((pointer, _)) if pointer.ends_with("/toolName")
    )
}

/// The tool's real arguments, for a camelCase-shaped payload.
///
/// Cline's SDK hosts carry the arguments twice on the file lane: real JSON in
/// the record (`tool_call.input`, `tool_result.input`) and per-key stringified
/// in `parameters`. The record wins — there is nothing to guess. `parameters`
/// is the fallback, reparsed ([`reparse_params`]), for the classic host, which
/// has no record, and for the plugin lane, which sends real JSON there.
fn camel_tool_input(data: &Value) -> Option<Value> {
    ["/tool_call/input", "/tool_result/input"]
        .iter()
        .find_map(|pointer| data.pointer(pointer).filter(|v| v.is_object()))
        .cloned()
        .or_else(|| tool_input_of(data).map(reparse_params))
}

/// The tool and its arguments in the common vocabulary — `Bash`, `Read`,
/// `Write`, `Edit`, `Grep`, `Glob`, `WebFetch`, `mcp__{server}__{tool}`.
///
/// A `tool_name`-shaped payload is returned as it came: it already speaks the
/// vocabulary. A `toolName`-shaped one ([`is_camel_tool_shape`]) is mapped by
/// [`map_camel_tool`], and a tool it does not know keeps its own name with its
/// arguments reparsed — `browser_action` stays `browser_action`, because a
/// guessed equivalent would be a claim about what the tool did.
///
/// The original name and arguments are not lost: [`to_common`] carries the
/// whole payload under `raw_agent_payload` whenever this rewrote anything.
pub fn common_tool_of(data: &Value) -> Option<(String, Option<Value>)> {
    let name = tool_name_of(data)?;
    if !is_camel_tool_shape(data) {
        return Some((name.to_string(), tool_input_of(data).cloned()));
    }
    Some(map_camel_tool(name, camel_tool_input(data)))
}

/// Cline's tool ids, in both of its vocabularies, onto the common one.
///
/// Two vocabularies because Cline ships two: the classic host
/// (`execute_command`, `write_to_file`, `use_mcp_tool`, … — `ClineDefaultTool`)
/// and the SDK-built hosts (`run_commands`, `read_files`, `editor`,
/// `fetch_web_content`, MCP tools as `{server}__{tool}` —
/// `@cline/core` `DefaultToolNames`). Argument keys verified against both:
/// `path` (never `file_path`), `regex`/`file_pattern`, `server_name`/
/// `tool_name`/`arguments`, `old_text`/`new_text`/`insert_line`.
///
/// Keys are renamed and everything else is kept: a rule or a consumer that
/// reads `file_path` finds it, and nothing the agent sent is dropped.
fn map_camel_tool(name: &str, input: Option<Value>) -> (String, Option<Value>) {
    let mut args = match input {
        Some(Value::Object(map)) => map,
        other => {
            return (
                camel_mcp_name(name).unwrap_or_else(|| name.to_string()),
                other,
            )
        }
    };
    let rename = |args: &mut serde_json::Map<String, Value>, from: &str, to: &str| {
        if let Some(value) = args.remove(from) {
            args.entry(to.to_string()).or_insert(value);
        }
    };
    let canonical = match name {
        "execute_command" => "Bash",
        "run_commands" => {
            if let Some(joined) = commands_line(args.get("commands")) {
                args.remove("commands");
                args.entry("command".to_string())
                    .or_insert(Value::String(joined));
            }
            "Bash"
        }
        "read_file" => {
            rename(&mut args, "path", "file_path");
            "Read"
        }
        "read_files" => {
            if let Some(first) = first_read_path(&args) {
                args.entry("file_path".to_string())
                    .or_insert(Value::String(first));
            }
            "Read"
        }
        "write_to_file" => {
            rename(&mut args, "path", "file_path");
            "Write"
        }
        "replace_in_file" | "apply_diff" => {
            rename(&mut args, "path", "file_path");
            "Edit"
        }
        "editor" => {
            rename(&mut args, "path", "file_path");
            let creates = args.get("old_text").is_none_or(Value::is_null)
                && args.get("insert_line").is_none_or(Value::is_null);
            if creates {
                args.remove("old_text");
                args.remove("insert_line");
                rename(&mut args, "new_text", "content");
                "Write"
            } else {
                rename(&mut args, "old_text", "old_string");
                rename(&mut args, "new_text", "new_string");
                "Edit"
            }
        }
        "search_files" => {
            rename(&mut args, "regex", "pattern");
            rename(&mut args, "file_pattern", "glob");
            "Grep"
        }
        "list_files" => "Glob",
        "use_mcp_tool" => {
            let server = args.get("server_name").and_then(Value::as_str);
            let tool = args.get("tool_name").and_then(Value::as_str);
            let Some(name) = server.zip(tool).map(|(s, t)| format!("mcp__{s}__{t}")) else {
                return (name.to_string(), Some(Value::Object(args)));
            };
            let arguments = match args.remove("arguments") {
                Some(Value::String(raw)) => serde_json::from_str(&raw)
                    .ok()
                    .filter(Value::is_object)
                    .unwrap_or(Value::String(raw)),
                Some(other) => other,
                None => Value::Object(serde_json::Map::new()),
            };
            return (name, Some(arguments));
        }
        "access_mcp_resource" => {
            rename(&mut args, "server_name", "server");
            "ReadMcpResourceTool"
        }
        "web_fetch" => "WebFetch",
        "fetch_web_content" => {
            let first = args
                .get("requests")
                .and_then(Value::as_array)
                .and_then(|requests| requests.first())
                .and_then(Value::as_object)
                .cloned();
            for (key, value) in first.iter().flatten() {
                if key == "url" || key == "prompt" {
                    args.entry(key.clone()).or_insert(value.clone());
                }
            }
            "WebFetch"
        }
        other => {
            return (
                camel_mcp_name(other).unwrap_or_else(|| other.to_string()),
                Some(Value::Object(args)),
            );
        }
    };
    (canonical.to_string(), Some(Value::Object(args)))
}

/// An SDK-host MCP tool (`{server}__{tool}`) in the common `mcp__` spelling.
///
/// `@cline/core` names every MCP tool `${server}__${tool}` — sanitised, and
/// hashed when it would run past its length cap, which this cannot undo and
/// does not try to. No built-in id of either Cline vocabulary contains `__`, so
/// the separator alone identifies one.
fn camel_mcp_name(name: &str) -> Option<String> {
    (!name.starts_with("mcp__") && name.contains("__")).then(|| format!("mcp__{name}"))
}

/// `run_commands`' list as one command line, one command per line.
///
/// Entries are either a command string or `{command, …}`; a bare string is the
/// single-command form Cline's parser also accepts.
fn commands_line(commands: Option<&Value>) -> Option<String> {
    let lines: Vec<&str> = match commands? {
        Value::String(one) => vec![one.as_str()],
        Value::Array(items) => items
            .iter()
            .filter_map(|item| {
                item.as_str()
                    .or_else(|| item.get("command").and_then(Value::as_str))
            })
            .collect(),
        _ => return None,
    };
    (!lines.is_empty()).then(|| lines.join("\n"))
}

/// The first path `read_files` names, in any of the shapes its input union
/// accepts: `files` / `paths` / `file_paths` as a list or a single entry, each
/// entry a path string or `{path}`.
fn first_read_path(args: &serde_json::Map<String, Value>) -> Option<String> {
    let entry_path = |entry: &Value| -> Option<String> {
        entry
            .as_str()
            .or_else(|| entry.get("path").and_then(Value::as_str))
            .map(str::to_string)
    };
    ["files", "paths", "file_paths", "path"]
        .iter()
        .filter_map(|key| args.get(*key))
        .find_map(|value| match value {
            Value::Array(items) => items.iter().find_map(entry_path),
            other => entry_path(other),
        })
}

/// What the tool answered, in the common `{content, is_error}` shape for a
/// camelCase-shaped payload, and as the agent sent it otherwise.
///
/// Cline reports its outcome beside the result — `postToolUse.result` and
/// `postToolUse.success` — where Claude Code puts `is_error` inside the
/// response. Its SDK hosts also put their whole call record at the top-level
/// `tool_result`, which is not the answer: it carries the input again, the
/// timings and the id.
pub fn common_tool_response_of(data: &Value) -> Option<Value> {
    if !is_camel_tool_shape(data) {
        return tool_result_of(data).cloned();
    }
    let content = field(data, &["result"]).cloned();
    let ok = field(data, &["success"]).and_then(Value::as_bool);
    if content.is_none() && ok.is_none() {
        return None;
    }
    let mut response = serde_json::Map::new();
    response.insert("content".to_string(), content.unwrap_or(Value::Null));
    if let Some(ok) = ok {
        response.insert("is_error".to_string(), Value::Bool(!ok));
    }
    Some(Value::Object(response))
}

/// The id that pairs a `pre_tool_use` with its `post_tool_use`.
///
/// The agent's own when it sent one ([`tool_use_id_of`]). Cline's classic host
/// sends none, so for a camelCase-shaped payload one is derived from what both
/// halves of a call carry: the session, the common tool name and its common
/// arguments. Deterministic, so the pre and the post of one call derive the
/// same id — and `ol_`-prefixed, so it is never mistaken for a provider's.
///
/// Its limit, stated rather than discovered: two identical calls in one session
/// derive one id. It pairs a call with its answer; it does not identify a call
/// uniquely, which is why no dedup keys on it.
pub fn common_tool_use_id_of(data: &Value) -> Option<String> {
    use sha2::{Digest, Sha256};

    if let Some(id) = tool_use_id_of(data) {
        return Some(id.to_string());
    }
    if !is_camel_tool_shape(data) {
        return None;
    }
    let (name, input) = common_tool_of(data)?;
    let key = Value::Array(vec![
        Value::String(session_id_of(data).unwrap_or_default().to_string()),
        Value::String(name),
        input.unwrap_or(Value::Null),
    ]);
    let canonical = serde_json_canonicalizer::to_string(&key).ok()?;
    let digest = Sha256::digest(canonical.as_bytes());
    let hex: String = digest[..12].iter().map(|b| format!("{b:02x}")).collect();
    Some(format!("ol_{hex}"))
}

/// 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 workspace root the agent itself declared, when it declares one.
///
/// Cline sends `workspaceRoots` and resolves its workspace rules, skills and
/// workflows (`.clinerules/`, `.cline/rules/`, …) against the first entry — so
/// that entry IS the project root, a fact the agent stated rather than one a
/// marker walk has to guess. Claude Code and Codex send a `cwd` only, which is
/// wherever the session happens to be and may sit deep inside the project.
pub fn declared_workspace_root_of(data: &Value) -> Option<&str> {
    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.
/// The prefix of every key the daemon itself adds to `data`.
pub const ENRICHMENT_PREFIX: &str = "openlatch.";

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));
    match common_tool_of(data) {
        Some((name, input)) => {
            put("tool_name", Some(Value::String(name)));
            put("tool_input", input);
        }
        None => put("tool_input", tool_input_of(data).cloned()),
    }
    put("tool_response", common_tool_response_of(data));
    put(
        "tool_use_id",
        common_tool_use_id_of(data).map(Value::String),
    );
    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();
    // The daemon's own enrichment (`openlatch.declared_*`, `openlatch.cwd`) is
    // written into `data` before this mapping runs. It is not the agent's, so
    // it travels at the top level where every consumer reads it — exactly as
    // it does on a native session start — and not inside the original.
    if let Some(obj) = raw.as_object_mut() {
        let ours: Vec<String> = obj
            .keys()
            .filter(|key| key.starts_with(ENRICHMENT_PREFIX))
            .cloned()
            .collect();
        for key in ours {
            if let Some(value) = obj.remove(&key) {
                common.insert(key, value);
            }
        }
    }
    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));
    }

    /// Cline's tool vocabulary — both of them — travels as the common one.
    ///
    /// Argument keys are the ones Cline actually sends: `path`, never
    /// `file_path`; `regex`; `server_name` / `tool_name` / `arguments`.
    #[test]
    fn clines_tools_map_onto_the_common_vocabulary() {
        let common = |tool: &str, params: Value| {
            common_tool_of(
                &json!({"taskId": "t", "preToolUse": {"toolName": tool, "parameters": params}}),
            )
            .expect("a tool")
        };
        let cases = [
            (
                "execute_command",
                json!({"command": "ls", "requires_approval": "false"}),
                "Bash",
                json!({"command": "ls", "requires_approval": "false"}),
            ),
            (
                "run_commands",
                json!({"commands": "[\"ls\",\"pwd\"]"}),
                "Bash",
                json!({"command": "ls\npwd"}),
            ),
            (
                "read_file",
                json!({"path": "src/a.rs"}),
                "Read",
                json!({"file_path": "src/a.rs"}),
            ),
            (
                "write_to_file",
                json!({"path": "p.json", "content": "{\"a\":1}"}),
                "Write",
                json!({"file_path": "p.json", "content": "{\"a\":1}"}),
            ),
            (
                "replace_in_file",
                json!({"path": "a.rs", "diff": "---"}),
                "Edit",
                json!({"file_path": "a.rs", "diff": "---"}),
            ),
            (
                "apply_diff",
                json!({"path": "a.rs", "diff": "---"}),
                "Edit",
                json!({"file_path": "a.rs", "diff": "---"}),
            ),
            (
                "search_files",
                json!({"path": "src", "regex": "fn main", "file_pattern": "*.rs"}),
                "Grep",
                json!({"path": "src", "pattern": "fn main", "glob": "*.rs"}),
            ),
            (
                "list_files",
                json!({"path": "src", "recursive": "true"}),
                "Glob",
                json!({"path": "src", "recursive": "true"}),
            ),
            (
                "use_mcp_tool",
                json!({"server_name": "github", "tool_name": "create_issue", "arguments": "{\"title\":\"x\"}"}),
                "mcp__github__create_issue",
                json!({"title": "x"}),
            ),
            (
                "access_mcp_resource",
                json!({"server_name": "docs", "uri": "file:///a"}),
                "ReadMcpResourceTool",
                json!({"server": "docs", "uri": "file:///a"}),
            ),
            (
                "web_fetch",
                json!({"url": "https://example.com"}),
                "WebFetch",
                json!({"url": "https://example.com"}),
            ),
            // The SDK-built hosts' vocabulary.
            (
                "editor",
                json!({"path": "new.rs", "new_text": "fn x() {}"}),
                "Write",
                json!({"file_path": "new.rs", "content": "fn x() {}"}),
            ),
            (
                "editor",
                json!({"path": "a.rs", "old_text": "a", "new_text": "b"}),
                "Edit",
                json!({"file_path": "a.rs", "old_string": "a", "new_string": "b"}),
            ),
            (
                "read_files",
                json!({"files": [{"path": "a.rs"}, {"path": "b.rs"}]}),
                "Read",
                json!({"file_path": "a.rs", "files": [{"path": "a.rs"}, {"path": "b.rs"}]}),
            ),
            (
                "fetch_web_content",
                json!({"requests": [{"url": "https://e.com", "prompt": "p"}]}),
                "WebFetch",
                json!({"requests": [{"url": "https://e.com", "prompt": "p"}], "url": "https://e.com", "prompt": "p"}),
            ),
            (
                "github__create_issue",
                json!({"title": "x"}),
                "mcp__github__create_issue",
                json!({"title": "x"}),
            ),
            // Everything else keeps its own name — a guess would be a claim.
            (
                "browser_action",
                json!({"action": "launch"}),
                "browser_action",
                json!({"action": "launch"}),
            ),
            (
                "attempt_completion",
                json!({"result": "{\"done\":true}"}),
                "attempt_completion",
                json!({"result": "{\"done\":true}"}),
            ),
        ];
        for (tool, params, name, input) in cases {
            assert_eq!(
                common(tool, params),
                (name.to_string(), Some(input)),
                "{tool}"
            );
        }
    }

    /// A `tool_name`-spelled payload already speaks the vocabulary — even a
    /// tool that happens to share one of Cline's ids is left alone.
    #[test]
    fn the_snake_case_shape_is_never_remapped() {
        let native = json!({"tool_name": "read_file", "tool_input": {"path": "a"}});
        assert_eq!(
            common_tool_of(&native),
            Some(("read_file".to_string(), Some(json!({"path": "a"}))))
        );
        assert_eq!(common_tool_use_id_of(&native), None, "nothing derived");
        let claude =
            json!({"tool_name": "Bash", "tool_input": {"command": "ls"}, "tool_use_id": "toolu_1"});
        assert_eq!(
            to_common(&claude),
            None,
            "a native payload travels untouched"
        );
    }

    /// The SDK hosts' file lane carries real JSON in its call record; that
    /// wins over the stringified `parameters`, and its id is the call's.
    #[test]
    fn the_sdk_record_supplies_the_input_and_the_id() {
        let pre = json!({
            "taskId": "conv_1",
            "hookName": "tool_call",
            "tool_call": {"id": "call_9", "name": "run_commands", "input": {"commands": ["ls"]}},
            "preToolUse": {"toolName": "run_commands", "parameters": {"commands": "[\"ls\"]"}}
        });
        let post = json!({
            "taskId": "conv_1",
            "hookName": "tool_result",
            "tool_result": {"id": "call_9", "name": "run_commands", "input": {"commands": ["ls"]}, "output": "x"},
            "postToolUse": {"toolName": "run_commands", "parameters": {"commands": "[\"ls\"]"}, "result": "x", "success": true}
        });
        let plugin = json!({"taskId": "conv_1", "toolName": "run_commands", "parameters": {"commands": ["ls"]}, "toolCallId": "call_9"});
        for data in [&pre, &post, &plugin] {
            assert_eq!(
                common_tool_use_id_of(data).as_deref(),
                Some("call_9"),
                "{data}"
            );
            assert_eq!(
                common_tool_of(data),
                Some(("Bash".to_string(), Some(json!({"command": "ls"})))),
                "{data}"
            );
        }
        // The answer is the result and the outcome, not the SDK's call record.
        assert_eq!(
            common_tool_response_of(&post),
            Some(json!({"content": "x", "is_error": false}))
        );
        let mapped = to_common(&post).expect("remapped");
        assert_eq!(mapped["tool_response"]["content"], "x");
        assert_eq!(
            mapped["raw_agent_payload"]["postToolUse"]["toolName"],
            "run_commands"
        );
    }

    /// With no id from the agent, the pre and the post of one call derive the
    /// same one — and a different call derives a different one.
    #[test]
    fn a_derived_id_pairs_a_pre_with_its_post() {
        let pre = json!({"taskId": "t1", "preToolUse": {"toolName": "write_to_file", "parameters": {"path": "a", "content": "x"}}});
        let post = json!({"taskId": "t1", "postToolUse": {"toolName": "write_to_file", "parameters": {"path": "a", "content": "x"}, "result": "ok", "success": true}});
        let id = common_tool_use_id_of(&pre).expect("derived");
        assert!(id.starts_with("ol_"), "{id}");
        assert_eq!(common_tool_use_id_of(&post).as_deref(), Some(id.as_str()));

        let other_session = json!({"taskId": "t2", "preToolUse": {"toolName": "write_to_file", "parameters": {"path": "a", "content": "x"}}});
        assert_ne!(
            common_tool_use_id_of(&other_session).as_deref(),
            Some(id.as_str())
        );
        // And the derived id is never offered as the agent's own.
        assert_eq!(tool_use_id_of(&pre), None);
    }

    /// The daemon's enrichment rides at the top level of a remapped payload,
    /// never inside the agent's original.
    #[test]
    fn enrichment_stays_top_level_through_the_mapping() {
        let enriched = json!({
            "taskId": "conv_1",
            "hookName": "TaskStart",
            "workspaceRoots": ["/work"],
            "taskStart": {"taskMetadata": {}},
            "openlatch.declared_skills": [],
            "openlatch.declared_mcp_sources": [{"source_id": "s"}],
            "openlatch.declared_rules_hash": "abc",
            "openlatch.cwd": "def"
        });
        let mapped = to_common(&enriched).expect("a Cline payload is remapped");
        for key in [
            "openlatch.declared_skills",
            "openlatch.declared_mcp_sources",
            "openlatch.declared_rules_hash",
            "openlatch.cwd",
        ] {
            assert_eq!(mapped[key], enriched[key], "{key} must be top-level");
            assert!(
                mapped["raw_agent_payload"].get(key).is_none(),
                "{key} is not the agent's"
            );
        }
        assert_eq!(mapped["raw_agent_payload"]["taskId"], "conv_1");
        assert_eq!(declared_workspace_root_of(&enriched), Some("/work"));
        assert_eq!(declared_workspace_root_of(&json!({"cwd": "/w"})), 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")));
    }
}