openlatch-client 0.6.5

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
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
//! 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;

use super::alias::{AliasTable, Resolved};

/// 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`]. Cursor's is
/// `tool_output`.
pub const TOOL_RESULT_KEYS: &[&str] = &["tool_result", "result", "tool_response", "tool_output"];

/// 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, as `turn_id`; Cursor calls its turn a generation.
pub fn turn_id_of(data: &Value) -> Option<&str> {
    field(data, &["turn_id", "turnId", "generation_id"])
        .and_then(Value::as_str)
        .and_then(non_empty)
}

/// The agent software's own version, when it reports one.
///
/// Three spellings, all from agents rather than invented here: the neutral
/// `agent_version`, Cline's `clineVersion` and Cursor's `cursor_version`. 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", "cursor_version"])
        .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))
}

/// A tool call read off a payload and resolved against its binding's alias
/// table (D-I16-22).
///
/// Re-exported shape of [`Resolved`]: the name the evaluator sees, the input
/// in the canonical keys, the name the agent used, and whether the table knew
/// the tool at all.
pub type ToolCall = Resolved;

/// The tool and its arguments in the common vocabulary — `Bash`, `Read`,
/// `Write`, `Edit`, `Grep`, `Glob`, `WebFetch`, `mcp__{server}__{tool}` —
/// through `table`, the alias table of the binding the payload came from.
///
/// **The table decides, never the payload's spelling.** Where the arguments
/// live (`tool_input`, Cline's stringified `parameters`, the SDK call record)
/// is read by shape; what a tool is called, what its argument keys mean and how
/// its MCP calls are spelled is the binding's data. `table` is `None` for a
/// source no binding answers for: the name and input are then returned as sent
/// and nothing is claimed about them.
///
/// A tool the table does not map keeps its own name here and is reported with
/// `mapped == false`; [`ToolCall::native`] keeps what the agent called it. The
/// original payload is not lost: [`to_common`] carries it under
/// `raw_agent_payload` whenever this rewrote anything.
pub fn tool_call_of(data: &Value, table: Option<&AliasTable>) -> Option<ToolCall> {
    let input = if is_camel_tool_shape(data) {
        camel_tool_input(data)
    } else {
        tool_input_of(data).cloned()
    };
    let Some(table) = table else {
        let name = tool_name_of(data)?;
        return Some(ToolCall {
            name: name.to_string(),
            input,
            native: name.to_string(),
            mapped: true,
        });
    };
    let server = table
        .mcp_rule
        .server_field
        .and_then(|key| field(data, &[key]))
        .and_then(Value::as_str)
        .and_then(non_empty);
    match tool_name_of(data) {
        Some(native) => Some(table.resolve(native, input, server)),
        None => table.resolve_event(native_event_of(data)?, data),
    }
}

/// The tool and its arguments in the common vocabulary, as [`tool_call_of`].
pub fn common_tool_of(data: &Value, table: Option<&AliasTable>) -> Option<(String, Option<Value>)> {
    tool_call_of(data, table).map(|call| (call.name, call.input))
}

/// Whether this payload is Cursor's: it names its own build in a string
/// `cursor_version`.
///
/// **The shape, not the agent**, as with [`is_camel_tool_shape`]. Cursor is the
/// one shipped agent that decides a shell command on an event with no
/// `tool_name` at all; the surface and the encoding flag are read off this
/// shape, never off `source`.
pub fn is_cursor_shape(data: &Value) -> bool {
    data.get("cursor_version").is_some_and(Value::is_string)
}

/// The surface an agent's event came from — `ide`, `cli` or `unknown` — for an
/// agent whose surfaces share one hook file.
///
/// Cursor's IDE and its CLI read the same `hooks.json` and name no surface; the
/// build does. The IDE is versioned `3.22.12`, the CLI by date,
/// `2026.09.28-64d2043`. A version in neither form is `unknown`, never a guess.
/// `None` for every other shape: that agent has one surface, or says which.
pub fn agent_surface_of(data: &Value) -> Option<&'static str> {
    let version = data.get("cursor_version")?.as_str()?;
    let numbers = |part: &str, len: Option<usize>| {
        !part.is_empty()
            && part.bytes().all(|b| b.is_ascii_digit())
            && len.is_none_or(|len| part.len() == len)
    };
    let dated = version.split_once('-').is_some_and(|(date, _)| {
        let parts: Vec<&str> = date.split('.').collect();
        parts.len() == 3
            && numbers(parts[0], Some(4))
            && numbers(parts[1], Some(2))
            && numbers(parts[2], Some(2))
    });
    let parts: Vec<&str> = version.split('.').collect();
    let semver = matches!(parts.len(), 2 | 3) && parts.iter().all(|part| numbers(part, None));
    Some(if dated {
        "cli"
    } else if semver {
        "ide"
    } else {
        "unknown"
    })
}

/// Whether a Cursor command or prompt may have been garbled on its way in.
///
/// Cursor's Windows pipe to a hook is not UTF-8 clean, so on a Windows build a
/// non-ASCII character in the command or the prompt may already be a
/// replacement for the one the developer typed. The text is flagged, never
/// repaired: a repair would be a guess about what someone meant, and a rule
/// would then match the guess.
fn encoding_suspect(data: &Value, windows: bool) -> bool {
    windows
        && is_cursor_shape(data)
        && [
            data.get("command"),
            data.pointer("/tool_input/command"),
            data.get("prompt"),
        ]
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .any(|text| !text.is_ascii())
}

/// 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 tool name and its arguments as the
/// agent sent them (no alias table is applied: both halves of a call come from
/// one binding, so they agree). 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, None)?;
    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. Cursor sends a
/// `cwd` that is often empty, beside the same list spelled `workspace_roots`.
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", "workspace_roots"])?
        .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`; Cursor sends `session_id` beside the `conversation_id` it
/// equals. 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", "conversation_id"],
    )
    .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.";

///
/// `binding` is the `olbinding` the payload was decided through: a tool the
/// table does not map travels as `<binding>:<native name>`, the same key the
/// evaluator used (D-8). The caller names it; this module knows no agent.
pub fn to_common(data: &Value, table: Option<&AliasTable>, binding: &str) -> 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 tool_call_of(data, table) {
        Some(call) => {
            put("tool_name", Some(Value::String(call.key(binding))));
            put("tool_input", call.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());
    put("agent_surface", text(agent_surface_of(data)));
    // Present only when true: its absence is the ordinary case.
    if encoding_suspect(data, cfg!(windows)) {
        put("encoding_suspect", Some(Value::Bool(true)));
    }

    // 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 crate::hooks::bindings::{claude_code, cline as cline_binding, cursor as cursor_binding};

    fn claude() -> Option<&'static AliasTable> {
        Some(&claude_code::ALIASES)
    }

    fn cline() -> Option<&'static AliasTable> {
        Some(&cline_binding::ALIASES)
    }

    fn cursor() -> Option<&'static AliasTable> {
        Some(&cursor_binding::ALIASES)
    }
    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, cline(), "cline_hook").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}}),
                cline(),
            )
            .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"}),
            ),
            // Unmapped on purpose: learned as unknown, never guessed at.
            (
                "access_mcp_resource",
                json!({"server_name": "docs", "uri": "file:///a"}),
                "access_mcp_resource",
                json!({"server_name": "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",
                // AC-96: every target kept, not the first.
                json!({"file_path": ["a.rs", "b.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"}),
            ),
            (
                "search_codebase",
                json!({"queries": ["fn main", "struct A"]}),
                "Grep",
                json!({"queries": ["fn main", "struct A"], "pattern": ["fn main", "struct A"]}),
            ),
            (
                "fetch_web_content",
                json!({"requests": [{"url": "https://a.com"}, {"url": "https://b.com"}]}),
                "WebFetch",
                json!({"requests": [{"url": "https://a.com"}, {"url": "https://b.com"}], "url": ["https://a.com", "https://b.com"]}),
            ),
            (
                "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 the table does not list keeps its own name and is reported
    /// unmapped — even one that happens to share an id with another agent's
    /// vocabulary. A guess would be a claim.
    #[test]
    fn a_tool_the_table_does_not_list_is_unmapped_not_guessed() {
        let native = json!({"tool_name": "read_file", "tool_input": {"path": "a"}});
        let call = tool_call_of(&native, claude()).expect("a call");
        assert_eq!(call.name, "read_file");
        assert_eq!(call.native, "read_file");
        assert!(!call.mapped);
        assert_eq!(call.input, Some(json!({"path": "a"})));
        assert_eq!(common_tool_use_id_of(&native), None, "nothing derived");
        let claude_payload =
            json!({"tool_name": "Bash", "tool_input": {"command": "ls"}, "tool_use_id": "toolu_1"});
        assert_eq!(
            to_common(&claude_payload, claude(), "claude_hook"),
            None,
            "a native payload travels untouched"
        );
        // No binding answers for the source: nothing is mapped or claimed.
        let call = tool_call_of(&native, None).expect("a call");
        assert_eq!((call.name.as_str(), call.mapped), ("read_file", true));
    }

    /// 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, cline()),
                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, cline(), "cline_hook").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, cline(), "cline_hook").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")));
    }

    /// Every Cursor fixture (`.local/.brainstorms/cursor-command-plane/fixtures.md`)
    /// onto the common shape — keyed on `cursor_version`, never on `source`.
    #[test]
    fn cursor_shapes_map_to_common() {
        let fixture = |raw: &str| serde_json::from_str::<Value>(raw).expect("fixture");

        // beforeShellExecution, IDE: flat, no `tool_name`, empty `cwd` and roots.
        let ide = fixture(include_str!(
            "../../../tests/fixtures/cursor/before-shell-ide.json"
        ));
        let common = to_common(&ide, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["hook_event_name"], "beforeShellExecution");
        assert_eq!(common["session_id"], "953caf59-f1d4-4188-812c-32f8ab9a9945");
        assert_eq!(common["turn_id"], "1108e70f-7ae0-4501-9a40-8e8ffa3e834f");
        assert_eq!(common["model"], "grok-4.6");
        assert_eq!(common["agent_version"], "3.22.12");
        assert_eq!(common["agent_surface"], "ide");
        assert_eq!(common["tool_name"], "Bash");
        assert_eq!(
            common["tool_input"],
            json!({"command": "rm -rf /tmp/ol-i1", "cwd": "", "sandbox": false})
        );
        assert!(common.get("cwd").is_none(), "no cwd is not an empty one");
        assert!(common.get("encoding_suspect").is_none());
        assert_eq!(common["raw_agent_payload"], ide);

        // beforeShellExecution, CLI: date-shaped build, roots set.
        let cli = fixture(include_str!(
            "../../../tests/fixtures/cursor/before-shell-cli.json"
        ));
        let common = to_common(&cli, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["agent_surface"], "cli");
        assert_eq!(common["agent_version"], "2026.09.28-64d2043");
        assert_eq!(common["cwd"], "/Users/dev/work");
        assert_eq!(common["tool_name"], "Bash");
        assert_eq!(common["tool_input"]["sandbox"], true);

        // preToolUse for `Shell`.
        let pre = fixture(include_str!(
            "../../../tests/fixtures/cursor/pre-tool-shell-ide.json"
        ));
        let common = to_common(&pre, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["tool_name"], "Bash");
        assert_eq!(
            common["tool_input"],
            json!({"command": "rm -rf /tmp/ol-i1", "cwd": ""})
        );
        assert_eq!(
            common["tool_use_id"],
            "454c7fcf-fba9-48c8-9877-e1d8b11a351d"
        );
        assert_eq!(common["hook_event_name"], "preToolUse");

        // postToolUse for `Shell`: the answer is `tool_output`, as sent.
        let post = fixture(
            r#"{"conversation_id":"953caf59-f1d4-4188-812c-32f8ab9a9945","cursor_version":"3.22.12","cwd":"","duration":386.305,"generation_id":"1108e70f-7ae0-4501-9a40-8e8ffa3e834f","hook_event_name":"postToolUse","model":"grok-4.6","session_id":"953caf59-f1d4-4188-812c-32f8ab9a9945","tool_input":{"command":"rm -rf /tmp/ol-probe-p1","cwd":"","timeout":30000},"tool_name":"Shell","tool_output":"{\"output\":\"\",\"exitCode\":0}","tool_use_id":"07cd67eb-588c-4f14-8bfc-9b86506a7eb5"}"#,
        );
        let common = to_common(&post, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["tool_name"], "Bash");
        assert_eq!(common["tool_response"], "{\"output\":\"\",\"exitCode\":0}");
        assert_eq!(
            common["tool_use_id"],
            "07cd67eb-588c-4f14-8bfc-9b86506a7eb5"
        );

        // sessionStart: no tool, an empty generation id is no turn.
        let start = fixture(
            r#"{"conversation_id":"953caf59-f1d4-4188-812c-32f8ab9a9945","generation_id":"","model":"cursor-grok-4.6-medium","model_id":"grok-4.6","model_params":[{"id":"effort","value":"medium"},{"id":"fast","value":"false"}],"is_background_agent":false,"composer_mode":"agent","session_id":"953caf59-f1d4-4188-812c-32f8ab9a9945","hook_event_name":"sessionStart","cursor_version":"3.22.12","workspace_roots":[],"user_email":"dev@example.com","transcript_path":null}"#,
        );
        let common = to_common(&start, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["hook_event_name"], "sessionStart");
        assert_eq!(common["agent_surface"], "ide");
        assert!(common.get("turn_id").is_none());
        assert!(common.get("tool_name").is_none());

        // stop.
        let stop = fixture(
            r#"{"cache_read_tokens":19840,"cache_write_tokens":0,"conversation_id":"953caf59-f1d4-4188-812c-32f8ab9a9945","cursor_version":"3.22.12","generation_id":"1108e70f-7ae0-4501-9a40-8e8ffa3e834f","hook_event_name":"stop","input_tokens":36863,"loop_count":0,"model":"cursor-grok-4.6-medium","model_id":"grok-4.6","model_params":[{"id":"effort","value":"medium"},{"id":"fast","value":"false"}],"output_tokens":132,"session_id":"953caf59-f1d4-4188-812c-32f8ab9a9945","status":"completed"}"#,
        );
        let common = to_common(&stop, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["session_id"], "953caf59-f1d4-4188-812c-32f8ab9a9945");
        assert_eq!(common["model"], "cursor-grok-4.6-medium");

        // documented, not captured: beforeMCPExecution, arguments as a JSON string.
        let mcp = fixture(
            r#"{"conversation_id":"c1","generation_id":"g1","model":"default","tool_name":"create_issue","tool_input":"{\"title\":\"x\"}","mcp_server_name":"github","url":"https://api.example.com/mcp","session_id":"c1","hook_event_name":"beforeMCPExecution","cursor_version":"3.22.12","workspace_roots":[]}"#,
        );
        let common = to_common(&mcp, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["tool_name"], "mcp__github__create_issue");
        assert_eq!(common["tool_input"], json!({"title": "x"}));
        let mut unparsed = mcp.clone();
        unparsed["tool_input"] = json!("not json");
        assert_eq!(
            to_common(&unparsed, cursor(), "cursor_hook").unwrap()["tool_input"],
            "not json"
        );

        // documented, not captured: beforeSubmitPrompt.
        let prompt = fixture(
            r#"{"conversation_id":"c1","generation_id":"g1","model":"default","prompt":"hello","attachments":[],"session_id":"c1","hook_event_name":"beforeSubmitPrompt","cursor_version":"2026.09.28-64d2043","workspace_roots":[]}"#,
        );
        let common = to_common(&prompt, cursor(), "cursor_hook").expect("remapped");
        assert_eq!(common["prompt"], "hello");
        assert_eq!(common["agent_surface"], "cli");

        // A preToolUse for an MCP tool names no server.
        let pre_mcp = json!({"cursor_version": "3.22.12", "tool_name": "MCP:create_issue", "tool_input": {"title": "x"}});
        assert_eq!(
            common_tool_of(&pre_mcp, cursor()),
            Some((
                "mcp__unknown__create_issue".to_string(),
                Some(json!({"title": "x"}))
            ))
        );
        // Cursor's own names that are already common stay as sent.
        let read = json!({"cursor_version": "3.22.12", "tool_name": "Read", "tool_input": {"file_path": "a"}});
        assert_eq!(
            common_tool_of(&read, cursor()),
            Some(("Read".to_string(), Some(json!({"file_path": "a"}))))
        );
    }

    /// The shape decides, never the key's presence alone: a `cursor_version`
    /// that is not a string is not Cursor's, and the surface is never guessed.
    #[test]
    fn the_surface_is_read_from_the_build_and_never_guessed() {
        for (version, surface) in [
            ("3.22.12", "ide"),
            ("3.22", "ide"),
            ("2026.09.28-64d2043", "cli"),
            ("nightly", "unknown"),
            ("3.22.12-beta", "unknown"),
            ("2026.9.28-x", "unknown"),
        ] {
            assert_eq!(
                agent_surface_of(&json!({"cursor_version": version})),
                Some(surface),
                "{version}"
            );
        }
        assert_eq!(agent_surface_of(&json!({"agent_version": "3.22.12"})), None);
        assert_eq!(
            common_tool_of(&json!({"cursor_version": 3, "command": "ls"}), cursor()),
            None,
            "not the Cursor shape, and no tool_name"
        );
    }

    /// Flagged, never repaired — and only where the garbling happens.
    #[test]
    fn a_non_ascii_cursor_command_is_suspect_on_windows_only() {
        let cafe = json!({"cursor_version": "3.22.12", "hook_event_name": "beforeShellExecution", "command": "echo café"});
        assert!(encoding_suspect(&cafe, true));
        assert!(!encoding_suspect(&cafe, false));
        assert!(!encoding_suspect(
            &json!({"cursor_version": "3.22.12", "command": "echo cafe"}),
            true
        ));
        assert!(encoding_suspect(
            &json!({"cursor_version": "3.22.12", "prompt": "résumé"}),
            true
        ));
        assert!(!encoding_suspect(&json!({"command": "echo café"}), true));
        // The text itself is never touched.
        assert_eq!(
            to_common(&cafe, cursor(), "cursor_hook").unwrap()["tool_input"]["command"],
            "echo café"
        );
    }
}