openlatch-client 0.6.23

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
//! Alias tables — how one binding's native tool vocabulary becomes OpenLatch's
//! canonical one (D-I16-22).
//!
//! The evaluator reads **canonical** names only (`Bash`, `Read`, `Write`,
//! `Edit`, `Grep`, `Glob`, `WebFetch`, `mcp__<server>__<tool>`, …). They belong
//! to no agent. Everything an agent adds to that — its own tool ids, its own
//! argument keys, how it spells an MCP call — is **data in its binding**: a
//! static [`AliasTable`] under `src/hooks/bindings/`. This module holds the
//! table's shape and the one function that applies it, so a new agent is a new
//! table and no shared code changes.
//!
//! Applying a table does three things, once, before evaluation:
//!
//! 1. the native tool name becomes the canonical one (or an `mcp__` name);
//! 2. the native argument keys become the canonical ones the evaluator reads
//!    (`file_path`, `url`, `command`), and a native input carrying several
//!    targets keeps **all** of them (a path or URL key may hold an array);
//! 3. a tool the table does not map is reported as **unmapped**, so the caller
//!    can key it `<olbinding>:<native name>` and the evaluator treats it as
//!    unknown (D-8).
//!
//! A leaf module: it imports `serde_json` and nothing else of this crate.

use serde_json::{Map, Value};

/// One binding's native-to-canonical mapping.
#[derive(Debug)]
pub struct AliasTable {
    /// The agent's wire name (`source`), which is how a payload finds its table.
    pub agent: &'static str,
    /// The `olbinding` id this agent's hook lane decides through.
    pub binding: &'static str,
    /// The id of the lane that is not a hook, when the agent has one — the
    /// binding is part of the tool key because two lanes of one agent are
    /// distinct bindings.
    pub renders_binding: Option<&'static str>,
    /// Native tool name → canonical name. A native name that is already the
    /// canonical one is listed too (identity row): **a tool absent from this
    /// list is unmapped on purpose** and is learned as unknown.
    pub tools: &'static [(&'static str, &'static str)],
    /// Events that ARE a tool call and carry no tool name.
    pub event_tools: &'static [EventTool],
    /// Native tool → the only argument keys it keeps (the rest is evidence the
    /// agent already holds, never a target).
    pub keep: &'static [(&'static str, &'static [&'static str])],
    /// Argument-key renames: `(tool or "*", native key, canonical key)`.
    pub inputs: &'static [(&'static str, &'static str, &'static str)],
    /// A native tool that is its canonical alternative when the keys named are
    /// absent (an editor that writes a file instead of editing it).
    pub creates: &'static [Creates],
    /// How an MCP invocation becomes `mcp__<server>__<tool>`.
    pub mcp_rule: McpKeyRule,
    /// How an input carrying several targets is kept.
    pub multi: MultiValueRule,
    /// The native tools (and tool-call events, by event name) whose `command`
    /// string the agent runs in the **host's** shell rather than one it names:
    /// on a Windows host they are `PowerShell`, not `Bash` ([`HostShell`]).
    /// Empty for an agent whose shell tool is Bash everywhere — Claude Code's
    /// `Bash` runs Git Bash on Windows.
    pub host_shell: &'static [&'static str],
}

/// The shell a host runs an agent's command in when the agent does not say
/// (finding #1).
///
/// Cursor's `Shell` tool and its `beforeShellExecution` event, and Codex's
/// `Bash` given a command string, run that string in the host's own shell:
/// PowerShell on Windows. Read as Bash there, `Get-Content C:\Users\dev\.env`
/// loses every separator to Bash's escape rule and resolves to a workspace
/// file, and the read is allowed. So on such a host the binding names the call
/// `PowerShell`, the canonical tool whose command the evaluator reads with
/// PowerShell's rules.
///
/// **The decision rides the event, never the platform.** The canonical name is
/// what the evaluator receives as `tool_name`, what the decision event records
/// and what the platform stores, so a replay of the stored event on any OS
/// decides as the host did; the engine itself stays platform-independent and
/// reads only the name. The native name stays on the call
/// ([`Resolved::native`]) and in `raw_agent_payload`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostShell {
    /// A POSIX shell: the command is Bash's.
    Posix,
    /// Windows PowerShell or `pwsh`.
    PowerShell,
}

impl HostShell {
    /// This host's shell: PowerShell on Windows, POSIX everywhere else. The one
    /// place the host OS enters the mapping.
    pub const CURRENT: HostShell = if cfg!(windows) {
        HostShell::PowerShell
    } else {
        HostShell::Posix
    };

    /// The canonical tool a host-shell command string is on this shell.
    pub const fn tool(self) -> &'static str {
        match self {
            HostShell::Posix => "Bash",
            HostShell::PowerShell => "PowerShell",
        }
    }
}

/// A hook event that is itself a tool call.
#[derive(Debug)]
pub struct EventTool {
    /// The native event name (`hook_event_name`).
    pub event: &'static str,
    /// The canonical tool it is.
    pub canonical: &'static str,
    /// The payload's own keys that form the tool input. The **first** must be
    /// a string — it is the action itself — or the event is not a tool call.
    pub keys: &'static [&'static str],
}

/// A tool that is a different canonical tool when some keys are absent.
#[derive(Debug)]
pub struct Creates {
    /// The native tool.
    pub tool: &'static str,
    /// The canonical tool it is in that case.
    pub canonical: &'static str,
    /// Keys that must all be absent (or null) for it to apply.
    pub when_absent: &'static [&'static str],
    /// Renames applied in that case, in place of the ordinary ones for them.
    pub renames: &'static [(&'static str, &'static str)],
}

/// How a binding spells an MCP call.
///
/// A name that already starts `mcp__` is canonical for every binding and needs
/// no rule. Each part below is optional: a binding declares the ones its agent
/// uses.
#[derive(Debug)]
pub struct McpKeyRule {
    /// The payload field that names the server beside the tool.
    pub server_field: Option<&'static str>,
    /// A prefix on the tool name when no server is named; the call is then
    /// `mcp__unknown__<tool>`.
    pub bare_prefix: Option<&'static str>,
    /// A native tool that wraps the call, naming server, tool and arguments in
    /// its own input.
    pub wrapper: Option<McpWrapper>,
    /// The agent joins server and tool as `<server>__<tool>`.
    pub joined: bool,
    /// The arguments arrive as a JSON string.
    pub json_string_input: bool,
}

impl McpKeyRule {
    /// No MCP spelling beyond the canonical one.
    pub const NATIVE: McpKeyRule = McpKeyRule {
        server_field: None,
        bare_prefix: None,
        wrapper: None,
        joined: false,
        json_string_input: false,
    };
}

/// An MCP call wrapped in a native tool's own input.
#[derive(Debug)]
pub struct McpWrapper {
    pub tool: &'static str,
    pub server_key: &'static str,
    pub tool_key: &'static str,
    pub arguments_key: &'static str,
}

/// The rules that keep a multi-target input whole.
#[derive(Debug)]
pub struct MultiValueRule {
    pub rules: &'static [MultiRule],
}

impl MultiValueRule {
    /// No input of this binding carries several targets.
    pub const NONE: MultiValueRule = MultiValueRule { rules: &[] };
}

/// One multi-target input.
#[derive(Debug)]
pub struct MultiRule {
    /// Native tools it applies to; empty means every tool.
    pub tools: &'static [&'static str],
    /// The native keys that may hold the values, first present one wins.
    pub from: &'static [&'static str],
    /// When an entry is an object, the key holding its value.
    pub element_key: Option<&'static str>,
    /// The canonical key the values land under.
    pub to: &'static str,
    /// How the values are combined.
    pub join: Join,
}

/// How several values become one canonical input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Join {
    /// Every value kept: a string for one, an array for several. A path or
    /// URL key may hold an array and every element is classified.
    Array,
    /// Separate command lines, joined with newlines so each runs as its own
    /// command. The source key is removed.
    Lines,
    /// One argv array, each element POSIX-quoted and joined with spaces.
    Argv,
    /// The first value only.
    First,
}

/// A native tool call resolved against a table.
#[derive(Debug, Clone, PartialEq)]
pub struct Resolved {
    /// The canonical name, or the native one when nothing maps it.
    pub name: String,
    /// The input in the canonical shape.
    pub input: Option<Value>,
    /// The name the agent used.
    pub native: String,
    /// `false` when the table has no row for it: the tool is unknown.
    pub mapped: bool,
}

impl Resolved {
    /// The tool key the evaluator, the decision event and the platform all
    /// use: the canonical name, or `<binding>:<native name>` for a tool the
    /// table does not map (D-8) — one string, never derived anywhere else.
    pub fn key(&self, binding: &str) -> String {
        if self.mapped {
            self.name.clone()
        } else {
            format!("{binding}:{}", self.native)
        }
    }
}

impl AliasTable {
    /// A table that maps nothing: every tool of the agent is unmapped.
    pub const fn empty(agent: &'static str, binding: &'static str) -> AliasTable {
        AliasTable {
            agent,
            binding,
            renders_binding: None,
            tools: &[],
            event_tools: &[],
            keep: &[],
            inputs: &[],
            creates: &[],
            mcp_rule: McpKeyRule::NATIVE,
            multi: MultiValueRule::NONE,
            host_shell: &[],
        }
    }

    /// The `olbinding` id of a lane of this agent.
    pub fn binding_id(&self, renders: bool) -> &'static str {
        match (renders, self.renders_binding) {
            (true, Some(plugin)) => plugin,
            _ => self.binding,
        }
    }

    /// Resolve a tool named by the payload, on this host ([`HostShell::CURRENT`]).
    ///
    /// `server` is the value of [`McpKeyRule::server_field`] in the payload,
    /// when it carries one.
    pub fn resolve(&self, native: &str, input: Option<Value>, server: Option<&str>) -> Resolved {
        self.resolve_on(HostShell::CURRENT, native, input, server)
    }

    /// [`resolve`](Self::resolve) on a host whose shell is `host`.
    pub fn resolve_on(
        &self,
        host: HostShell,
        native: &str,
        input: Option<Value>,
        server: Option<&str>,
    ) -> Resolved {
        let in_host_shell = self.runs_in_host_shell(host, native, input.as_ref());
        let mut resolved = self.resolve_native(native, input, server);
        if in_host_shell && resolved.mapped && resolved.name == "Bash" {
            resolved.name = host.tool().to_string();
        }
        resolved
    }

    /// Whether `native` hands a command string to a PowerShell host's own shell.
    /// Only a string: an argv array is executed as it is, with no shell between,
    /// and its POSIX-quoted join stays a Bash spelling of exactly those words
    /// (a `powershell -Command …` inside it is followed by the shell reading).
    fn runs_in_host_shell(&self, host: HostShell, native: &str, input: Option<&Value>) -> bool {
        host == HostShell::PowerShell
            && self.host_shell.contains(&native)
            && input
                .and_then(|input| input.get("command"))
                .is_some_and(Value::is_string)
    }

    fn resolve_native(&self, native: &str, input: Option<Value>, server: Option<&str>) -> Resolved {
        let mapped = |name: String, input: Option<Value>| Resolved {
            name,
            input,
            native: native.to_string(),
            mapped: true,
        };
        if native.starts_with("mcp__") {
            return mapped(native.to_string(), input);
        }
        let rule = &self.mcp_rule;
        if let Some(server) = server {
            let tool = rule
                .bare_prefix
                .and_then(|prefix| native.strip_prefix(prefix))
                .unwrap_or(native);
            let input = match input {
                Some(Value::String(raw)) if rule.json_string_input => {
                    // A string that does not parse is kept: it is what the model sent.
                    Some(serde_json::from_str(&raw).unwrap_or(Value::String(raw)))
                }
                other => other,
            };
            return mapped(format!("mcp__{server}__{tool}"), input);
        }
        if let Some(tool) = rule.bare_prefix.and_then(|p| native.strip_prefix(p)) {
            return mapped(format!("mcp__unknown__{tool}"), input);
        }
        if let Some(wrapper) = rule.wrapper.as_ref().filter(|w| w.tool == native) {
            if let Some(resolved) = unwrap_mcp(wrapper, native, &input) {
                return resolved;
            }
        }
        if let Some((_, canonical)) = self.tools.iter().find(|(name, _)| *name == native) {
            return self.map_tool(native, canonical, input);
        }
        if rule.joined && native.contains("__") {
            return mapped(format!("mcp__{native}"), input);
        }
        Resolved {
            name: native.to_string(),
            input,
            native: native.to_string(),
            mapped: false,
        }
    }

    /// Resolve an event that is itself a tool call, from the payload's own keys,
    /// on this host ([`HostShell::CURRENT`]).
    pub fn resolve_event(&self, event: &str, payload: &Value) -> Option<Resolved> {
        self.resolve_event_on(HostShell::CURRENT, event, payload)
    }

    /// [`resolve_event`](Self::resolve_event) on a host whose shell is `host`.
    pub fn resolve_event_on(
        &self,
        host: HostShell,
        event: &str,
        payload: &Value,
    ) -> Option<Resolved> {
        let row = self.event_tools.iter().find(|row| row.event == event)?;
        payload.get(row.keys.first()?)?.as_str()?;
        let input: Map<String, Value> = row
            .keys
            .iter()
            .filter_map(|key| Some((key.to_string(), payload.get(key)?.clone())))
            .collect();
        let input = Value::Object(input);
        let name = if row.canonical == "Bash" && self.runs_in_host_shell(host, event, Some(&input))
        {
            host.tool()
        } else {
            row.canonical
        };
        Some(Resolved {
            name: name.to_string(),
            input: Some(input),
            native: event.to_string(),
            mapped: true,
        })
    }

    fn map_tool(&self, native: &str, canonical: &str, input: Option<Value>) -> Resolved {
        let mut canonical = canonical;
        let Some(Value::Object(mut args)) = input else {
            return Resolved {
                name: canonical.to_string(),
                input,
                native: native.to_string(),
                mapped: true,
            };
        };
        if let Some((_, keys)) = self.keep.iter().find(|(tool, _)| *tool == native) {
            args.retain(|key, _| keys.contains(&key.as_str()));
        }
        let mut renames: Vec<(&str, &str)> = Vec::new();
        let creating = self.creates.iter().find(|row| {
            row.tool == native
                && row
                    .when_absent
                    .iter()
                    .all(|key| args.get(*key).is_none_or(Value::is_null))
        });
        if let Some(row) = creating {
            canonical = row.canonical;
            for key in row.when_absent {
                args.remove(*key);
            }
            renames.extend(row.renames);
        }
        renames.extend(
            self.inputs
                .iter()
                .filter(|(tool, _, _)| *tool == "*" || *tool == native)
                .map(|(_, from, to)| (*from, *to)),
        );
        for (from, to) in renames {
            let Some(value) = args.remove(from) else {
                continue;
            };
            // Both spellings, different values: which one the tool reads is the
            // agent's business, so both stay targets and a rule on either decides.
            // Keeping only one let the other run unseen.
            match args.get_mut(to) {
                None => {
                    args.insert(to.to_string(), value);
                }
                Some(existing) if *existing == value => {}
                Some(existing) => {
                    let mut all = match existing.take() {
                        Value::Array(items) => items,
                        other => vec![other],
                    };
                    let added = match value {
                        Value::Array(items) => items,
                        other => vec![other],
                    };
                    for item in added {
                        if !all.contains(&item) {
                            all.push(item);
                        }
                    }
                    *existing = Value::Array(all);
                }
            }
        }
        for rule in self
            .multi
            .rules
            .iter()
            .filter(|rule| rule.tools.is_empty() || rule.tools.contains(&native))
        {
            apply_multi(rule, &mut args);
        }
        Resolved {
            name: canonical.to_string(),
            input: Some(Value::Object(args)),
            native: native.to_string(),
            mapped: true,
        }
    }
}

/// `server`, `tool` and `arguments` out of a wrapper tool's own input.
fn unwrap_mcp(wrapper: &McpWrapper, native: &str, input: &Option<Value>) -> Option<Resolved> {
    let args = input.as_ref()?.as_object()?;
    let server = args.get(wrapper.server_key)?.as_str()?;
    let tool = args.get(wrapper.tool_key)?.as_str()?;
    let arguments = match args.get(wrapper.arguments_key) {
        Some(Value::String(raw)) => serde_json::from_str(raw)
            .ok()
            .filter(Value::is_object)
            .unwrap_or_else(|| Value::String(raw.clone())),
        Some(other) => other.clone(),
        None => Value::Object(Map::new()),
    };
    Some(Resolved {
        name: format!("mcp__{server}__{tool}"),
        input: Some(arguments),
        native: native.to_string(),
        mapped: true,
    })
}

/// The string values a multi-target key holds, in order.
fn values_of(value: &Value, element_key: Option<&str>, out: &mut Vec<Value>) {
    let entry = |item: &Value, out: &mut Vec<Value>| {
        let text = item
            .as_str()
            .or_else(|| element_key.and_then(|key| item.get(key)?.as_str()));
        if let Some(text) = text {
            out.push(Value::String(text.to_string()));
        }
    };
    match value {
        Value::Array(items) => items.iter().for_each(|item| entry(item, out)),
        other => entry(other, out),
    }
}

fn apply_multi(rule: &MultiRule, args: &mut Map<String, Value>) {
    let Some((source, values)) = rule.from.iter().find_map(|key| {
        let mut values = Vec::new();
        values_of(args.get(*key)?, rule.element_key, &mut values);
        (!values.is_empty()).then_some((*key, values))
    }) else {
        return;
    };
    match rule.join {
        Join::Array => {
            let kept = if values.len() == 1 {
                values.into_iter().next().unwrap_or(Value::Null)
            } else {
                Value::Array(values)
            };
            args.entry(rule.to.to_string()).or_insert(kept);
        }
        Join::First => {
            if let Some(first) = values.into_iter().next() {
                args.entry(rule.to.to_string()).or_insert(first);
            }
        }
        Join::Lines => {
            let joined = values
                .iter()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>()
                .join("\n");
            args.remove(source);
            args.entry(rule.to.to_string())
                .or_insert(Value::String(joined));
        }
        Join::Argv => {
            // Only an array is an argv; a string command is already a line.
            if !args.get(source).is_some_and(Value::is_array) {
                return;
            }
            let joined = values
                .iter()
                .filter_map(Value::as_str)
                .map(posix_quote)
                .collect::<Vec<_>>()
                .join(" ");
            args.insert(rule.to.to_string(), Value::String(joined));
        }
    }
}

/// One argv element as a POSIX shell word.
fn posix_quote(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', "'\\''"))
    }
}

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

    static TABLE: AliasTable = AliasTable {
        agent: "fixture",
        binding: "fixture_hook",
        renders_binding: Some("fixture_plugin"),
        tools: &[
            ("Sh", "Bash"),
            ("Open", "Read"),
            ("Ed", "Edit"),
            ("Cmds", "Bash"),
        ],
        event_tools: &[EventTool {
            event: "beforeShell",
            canonical: "Bash",
            keys: &["command", "cwd"],
        }],
        keep: &[("Sh", &["command"])],
        inputs: &[("Open", "path", "file_path"), ("*", "q", "query")],
        creates: &[Creates {
            tool: "Ed",
            canonical: "Write",
            when_absent: &["old"],
            renames: &[("new", "content")],
        }],
        mcp_rule: McpKeyRule {
            server_field: Some("server"),
            bare_prefix: Some("MCP:"),
            wrapper: Some(McpWrapper {
                tool: "call_mcp",
                server_key: "s",
                tool_key: "t",
                arguments_key: "a",
            }),
            joined: true,
            json_string_input: true,
        },
        multi: MultiValueRule {
            rules: &[
                MultiRule {
                    tools: &["Open"],
                    from: &["files"],
                    element_key: Some("path"),
                    to: "file_path",
                    join: Join::Array,
                },
                MultiRule {
                    tools: &["Cmds"],
                    from: &["commands"],
                    element_key: Some("command"),
                    to: "command",
                    join: Join::Lines,
                },
                MultiRule {
                    tools: &["Sh"],
                    from: &["command"],
                    element_key: None,
                    to: "command",
                    join: Join::Argv,
                },
            ],
        },
        host_shell: &[],
    };

    #[test]
    fn a_listed_tool_is_mapped_and_an_unlisted_one_is_not() {
        let sh = TABLE.resolve("Sh", Some(json!({"command": "ls", "x": 1})), None);
        assert_eq!(sh.name, "Bash");
        assert!(sh.mapped);
        assert_eq!(sh.input, Some(json!({"command": "ls"})), "keep drops x");
        let other = TABLE.resolve("Mystery", Some(json!({"a": 1})), None);
        assert_eq!((other.name.as_str(), other.mapped), ("Mystery", false));
        assert_eq!(other.native, "Mystery");
        assert_eq!(other.input, Some(json!({"a": 1})));
    }

    #[test]
    fn inputs_are_renamed_per_tool_and_globally() {
        let open = TABLE.resolve("Open", Some(json!({"path": "a", "q": "x"})), None);
        assert_eq!(open.input, Some(json!({"file_path": "a", "query": "x"})));
    }

    /// A payload carrying both the native key and the canonical one: the tool
    /// reads one of them, so neither may be dropped from what a rule sees.
    #[test]
    fn a_native_and_a_canonical_key_together_keep_both_targets() {
        let both = TABLE.resolve(
            "Open",
            Some(json!({"path": "/etc/secret", "file_path": "/tmp/ok"})),
            None,
        );
        assert_eq!(
            both.input.unwrap()["file_path"],
            json!(["/tmp/ok", "/etc/secret"])
        );
        let same = TABLE.resolve("Open", Some(json!({"path": "a", "file_path": "a"})), None);
        assert_eq!(same.input, Some(json!({"file_path": "a"})));
    }

    #[test]
    fn several_targets_are_all_kept() {
        let open = TABLE.resolve(
            "Open",
            Some(json!({"files": [{"path": "a"}, {"path": "b"}]})),
            None,
        );
        assert_eq!(open.input.unwrap()["file_path"], json!(["a", "b"]));
        let one = TABLE.resolve("Open", Some(json!({"files": [{"path": "a"}]})), None);
        assert_eq!(one.input.unwrap()["file_path"], json!("a"));
        let lines = TABLE.resolve(
            "Cmds",
            Some(json!({"commands": ["ls", {"command": "pwd"}]})),
            None,
        );
        assert_eq!(lines.input, Some(json!({"command": "ls\npwd"})));
    }

    #[test]
    fn an_argv_array_is_posix_quoted_and_joined() {
        let sh = TABLE.resolve(
            "Sh",
            Some(json!({"command": ["rm", "-rf", "my dir", "it's"]})),
            None,
        );
        assert_eq!(
            sh.input,
            Some(json!({"command": "rm -rf 'my dir' 'it'\\''s'"}))
        );
        let line = TABLE.resolve("Sh", Some(json!({"command": "rm -rf x"})), None);
        assert_eq!(line.input, Some(json!({"command": "rm -rf x"})));
    }

    #[test]
    fn a_tool_is_its_alternative_when_the_keys_are_absent() {
        let write = TABLE.resolve("Ed", Some(json!({"new": "body"})), None);
        assert_eq!(write.name, "Write");
        assert_eq!(write.input, Some(json!({"content": "body"})));
        let edit = TABLE.resolve("Ed", Some(json!({"old": "a", "new": "b"})), None);
        assert_eq!(edit.name, "Edit");
        assert_eq!(edit.input, Some(json!({"old": "a", "new": "b"})));
    }

    #[test]
    fn mcp_calls_become_the_canonical_name() {
        let canonical = TABLE.resolve("mcp__s__t", None, None);
        assert_eq!(
            (canonical.name.as_str(), canonical.mapped),
            ("mcp__s__t", true)
        );
        let beside = TABLE.resolve("create", Some(json!("{\"a\":1}")), Some("gh"));
        assert_eq!(beside.name, "mcp__gh__create");
        assert_eq!(beside.input, Some(json!({"a": 1})));
        let bare = TABLE.resolve("MCP:create", Some(json!({"a": 1})), None);
        assert_eq!(bare.name, "mcp__unknown__create");
        let wrapped = TABLE.resolve(
            "call_mcp",
            Some(json!({"s": "gh", "t": "create", "a": "{\"x\":1}"})),
            None,
        );
        assert_eq!(wrapped.name, "mcp__gh__create");
        assert_eq!(wrapped.input, Some(json!({"x": 1})));
        assert_eq!(wrapped.native, "call_mcp");
        let joined = TABLE.resolve("gh__create", Some(json!({"a": 1})), None);
        assert_eq!(joined.name, "mcp__gh__create");
        assert!(joined.mapped);
        let broken = TABLE.resolve("call_mcp", Some(json!({"s": "gh"})), None);
        assert!(!broken.mapped, "a wrapper naming no tool is not a call");
    }

    #[test]
    fn an_event_that_is_a_tool_call_needs_its_action() {
        let payload = json!({"command": "ls", "cwd": "/w", "other": 1});
        let call = TABLE
            .resolve_event("beforeShell", &payload)
            .expect("a call");
        assert_eq!(call.name, "Bash");
        assert_eq!(call.input, Some(json!({"command": "ls", "cwd": "/w"})));
        assert_eq!(call.native, "beforeShell");
        assert!(TABLE
            .resolve_event("beforeShell", &json!({"cwd": "/w"}))
            .is_none());
        assert!(TABLE.resolve_event("sessionStart", &payload).is_none());
    }

    /// A binding whose `Sh`, `Open` and `beforeShell` run in the host's shell.
    static HOST_TABLE: AliasTable = AliasTable {
        tools: &[("Sh", "Bash"), ("Cmds", "Bash"), ("Open", "Read")],
        event_tools: &[EventTool {
            event: "beforeShell",
            canonical: "Bash",
            keys: &["command", "cwd"],
        }],
        multi: MultiValueRule {
            rules: &[MultiRule {
                tools: &["Sh"],
                from: &["command"],
                element_key: None,
                to: "command",
                join: Join::Argv,
            }],
        },
        host_shell: &["Sh", "Open", "beforeShell"],
        ..AliasTable::empty("fixture", "fixture_hook")
    };

    /// Finding #1: a command string run in the host's shell is `PowerShell` on a
    /// PowerShell host and `Bash` on a POSIX one; an argv array, a tool the table
    /// does not list and a tool that is not a shell keep their names.
    #[test]
    fn a_host_shell_command_is_powershell_on_a_powershell_host() {
        let line = || Some(json!({"command": "Get-Content C:/x/.env"}));
        let on = |host| HOST_TABLE.resolve_on(host, "Sh", line(), None);
        assert_eq!(on(HostShell::PowerShell).name, "PowerShell");
        assert_eq!(on(HostShell::PowerShell).native, "Sh");
        assert_eq!(on(HostShell::Posix).name, "Bash");
        let argv = HOST_TABLE.resolve_on(
            HostShell::PowerShell,
            "Sh",
            Some(json!({"command": ["cat", ".env"]})),
            None,
        );
        assert_eq!(argv.name, "Bash", "an argv runs with no shell between");
        assert_eq!(argv.input, Some(json!({"command": "cat .env"})));
        let unlisted = HOST_TABLE.resolve_on(HostShell::PowerShell, "Cmds", line(), None);
        assert_eq!(unlisted.name, "Bash");
        let not_a_shell = HOST_TABLE.resolve_on(HostShell::PowerShell, "Open", line(), None);
        assert_eq!(not_a_shell.name, "Read");
        let event = json!({"command": "Get-Content .env", "cwd": "C:/w"});
        let shell_event = |host| {
            HOST_TABLE
                .resolve_event_on(host, "beforeShell", &event)
                .expect("a call")
        };
        assert_eq!(shell_event(HostShell::PowerShell).name, "PowerShell");
        assert_eq!(shell_event(HostShell::Posix).name, "Bash");
        let expected = if cfg!(windows) {
            HostShell::PowerShell
        } else {
            HostShell::Posix
        };
        assert_eq!(HostShell::CURRENT, expected);
    }

    #[test]
    fn a_lane_that_is_not_a_hook_has_its_own_binding() {
        assert_eq!(TABLE.binding_id(false), "fixture_hook");
        assert_eq!(TABLE.binding_id(true), "fixture_plugin");
    }
}