openlatch-client 0.5.2

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
//! Trigger, normalization and resolution — PRD § "Evaluation Semantics".
//!
//! Evaluation is a pure, in-memory function of `(ResidentBundle, envelope)`.
//! It performs no I/O, never calls the platform, and is order-independent:
//! shuffling `rules[]` must produce an identical verdict **and** an identical
//! reported `rule_id`.

use serde_json::Value;

use super::matcher;
use super::{ResidentBundle, Rule};
use crate::generated::types::{AgentFunction, PolicyRuleMode, PolicyRuleSeverity};

/// The only envelope `type` that carries an actionable pre-execution decision.
///
/// Post-action and notification events have no deny channel in any agent's hook
/// protocol, so evaluating them could only ever produce a verdict that gets
/// discarded — see `.claude/rules/envelope-format.md` § "Hook output
/// translation", invariant 2.
pub const EVENT_TYPE_PRE_TOOL_USE: &str = "pre_tool_use";

/// Frozen shell-execution tool list (D13 — PRD SCOPE CORRECTION).
///
/// The PRD freezes FIVE entries (Claude Code `Bash`, Cursor `run_terminal_cmd`,
/// Codex CLI `shell`, Gemini CLI `run_shell_command`, Cline/OpenClaw
/// `execute_command`). **Three ship: Claude Code, Codex CLI and Cline** —
/// `"Bash"` is Claude Code's tool name and also the single wire name Codex CLI
/// serialises both shell *and* unified exec as, while `"run_commands"` and
/// `"execute_command"` are Cline's. Cursor and Gemini CLI are still out, for
/// the reason below: neither has a translator.
///
/// WHY THE GATE: `src/hook_output/mod.rs::translate` dispatches per agent, and
/// an agent with no arm falls through to `empty()` — the universal "continue
/// normally" `{}`. So a deny produced for an agent with no arm would evaluate
/// correctly here and then be SILENTLY DISCARDED before the developer ever saw
/// it. The PRD itself calls that a broken feature.
///
/// WHAT UNBLOCKS AN AGENT: a translator in `src/hook_output/` plus its
/// vendored hook-output schema under `schemas/vendor/<agent>/`, wired into the
/// parametric test in `tests/hook_output_schema.rs`. Adding a `tool_name` here
/// without it re-opens the silent-discard hole. Cline cleared that bar with
/// `hook_output::cline` and `schemas/vendor/cline/hook-output.schema.json`,
/// registered in **both** dispatches — which is why its names are here and
/// Cursor's is not.
///
/// **Cline ships TWO spellings and both are listed, because both reach the
/// wire** (verified against `cline/cline` v4.1.17):
///
/// - `run_commands` — the canonical SDK tool id
///   (`sdk/packages/core/src/extensions/tools/runtime.ts:63`).
/// - `execute_command` — the legacy VS Code name, still live in VS Code's own
///   tool enum (`apps/vscode/src/shared/tools.ts:11`, `BASH = "execute_command"`)
///   and treated as ONE set with the other by its policy layer
///   (`apps/vscode/src/sdk/sdk-tool-policies.ts:27`).
///
/// Cline does have an alias map folding `execute_command` into `run_commands`
/// (`CONFIGURED_AGENT_TOOL_NAME_ALIASES`, `runtime-builder.ts:95-99`), but it is
/// scoped to **configured agents** and is not a universal normalizer — so it
/// cannot be relied on to collapse the two, and carrying either spelling alone
/// would leave the other silently unevaluated.
///
/// Extending this list is a client release (deliberate — making it
/// bundle-driven would let the platform widen the client's evaluation surface
/// remotely, which needs its own review).
///
/// Matched case-sensitively, exactly as the agent emits it. Cline's lowercase
/// `bash` alias is therefore NOT covered, and `"Bash"` is Claude Code's.
pub const SHELL_TOOL_NAMES: &[&str] = &["Bash", "run_commands", "execute_command"];

/// The outcome of an evaluation that matched at least one rule.
///
/// `None` from [`evaluate`] means "no rule matched, or nothing was evaluated" —
/// both are an `allow` with no policy annotation beyond the bundle metadata the
/// caller stamps anyway.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PolicyMatch {
    /// The rule that **decided**: lexicographically first within the deciding
    /// set, never across all matches.
    pub rule_id: String,
    /// The deciding rule's plain-language explanation, shown to the developer
    /// verbatim.
    pub reason: String,
    /// The deciding rule's author-assigned severity.
    pub severity: PolicyRuleSeverity,
    /// The deciding rule's authored mode. Note this is the rule as written, not
    /// the effective behaviour: with `enforcement_enabled == false` a
    /// `mode: enforce` rule still reports `enforce` here while `shadow` is
    /// `true`, which is what makes the kill switch visible in the daemon log.
    pub mode: PolicyRuleMode,
    /// `true` means **"would have denied"**: the caller returns `allow` and
    /// stamps `olverdictshadow`. `false` means the caller must return `deny`.
    pub shadow: bool,
}

/// Normalization — trim, then collapse internal whitespace runs to one space.
///
/// NOTHING ELSE: no shell parsing, no alias resolution, no variable expansion,
/// no quote handling. The platform applies the identical normalization to
/// `match_pattern` at build time so authors are not bitten by double spaces.
pub fn normalize(cmd: &str) -> String {
    cmd.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Evaluate one envelope against the resident bundle.
///
/// `event_type` is the CloudEvents `type` attribute as it appears on the wire
/// (e.g. `"pre_tool_use"`); `data` is the envelope's opaque `data` payload.
/// Taking primitives rather than an `EventEnvelope` keeps this module a leaf —
/// `core/envelope/` is a sibling it may not import.
///
/// **Call this on the RAW command, before `privacy::filter_event_with`.** The
/// privacy filter rewrites `envelope.data` in place, so evaluating afterwards
/// would glob-match redacted text and silently change which rules fire.
///
/// Returns `None` — meaning allow, evaluate nothing — when:
///
/// - the event is not a `pre_tool_use`;
/// - `tool_name` (or Cline's `toolName`) is absent, not a string, or outside
///   [`SHELL_TOOL_NAMES`];
/// - `tool_input.command` (or Cline's `parameters.command`) is absent or not a
///   string;
/// - no rule matched.
///
/// **Two spellings, one extraction.** Cline names the same two fields
/// `toolName` and `parameters`, so both are read here rather than normalised
/// into the envelope: `data` is the agent's raw payload and stays opaque.
/// [`SHELL_TOOL_NAMES`] still gates every match, and it now carries Cline's two
/// tool spellings as well as `"Bash"` — so this extraction is what the gate
/// reads, and a Cline deny that leaves here is one `hook_output::cline` can
/// deliver.
///
/// # Known coverage limitations (stated, not discovered)
///
/// 1. Glob matching on a command string is trivially evaded by an agent that
///    *intends* to evade it. The threat model is a **misbehaving** agent, not a
///    malicious one; this is not an unbypassable control.
/// 2. Agents that pass shell arguments as an **array** rather than a single
///    `command` string fall through the `tool_input.command` check and are
///    silently unevaluated. Extracting from array-shaped arguments is a v1.1
///    item.
pub fn evaluate(
    bundle: &ResidentBundle,
    event_type: &str,
    data: Option<&Value>,
) -> Option<PolicyMatch> {
    if event_type != EVENT_TYPE_PRE_TOOL_USE {
        return None;
    }
    let data = data?;

    let tool_name = tool_name_of(data)?;
    if !SHELL_TOOL_NAMES.contains(&tool_name) {
        return None;
    }

    // The native branch borrows. Claude Code and Codex send `tool_input.command`
    // as a plain string, and every one of their `pre_tool_use` events goes
    // through here — making them pay a heap clone for a fallback that exists for
    // a third agent would be a tax on the common path for nothing.
    if let Some(command) = data
        .get("tool_input")
        .and_then(|v| v.get("command"))
        .and_then(Value::as_str)
    {
        return evaluate_command(bundle, command);
    }
    let reparsed = cline_command_of(data)?;
    evaluate_command(bundle, reparsed.as_str()?)
}

/// The tool name, in whichever of its two spellings the agent used.
///
/// Claude Code and Codex CLI send `tool_name`; Cline sends `toolName`. Read
/// side only — the envelope's `data` is the agent's raw payload, opaque and
/// never rewritten (`AGENTS.md`, *Opaque data*). We read it differently; we do
/// not rewrite it, and the daemon is the only place that reads it at all.
fn tool_name_of(data: &Value) -> Option<&str> {
    data.get("tool_name")
        .and_then(Value::as_str)
        .or_else(|| data.get("toolName").and_then(Value::as_str))
}

/// The command string from **Cline's** argument container.
///
/// Cline's `parameters` is a `Record<string, string>`, so every value arrives
/// per-key `JSON.stringify`d and goes through [`reparse_stringified`] first.
///
/// Owned, because the reparsed branch constructs a new `Value` — there is
/// nothing to borrow from. The caller tries the native `tool_input.command`
/// borrow first and only reaches this when that is absent, so the allocation is
/// paid by the agent that needs it and by no one else.
fn cline_command_of(data: &Value) -> Option<Value> {
    data.get("parameters")
        .and_then(|v| v.get("command"))
        .map(reparse_stringified)
}

/// Undo the per-key `JSON.stringify` Cline applies to `parameters`.
///
/// `parameters` is typed `Record<string, string>`, so every value that was not
/// already a string arrived serialised: an object becomes `"{\"a\":1}"`, an
/// array becomes `"[1,2]"`. Parse it back where it parses, and leave it exactly
/// as it came where it does not — a shell command is not valid JSON, so it
/// stays the string it was.
///
/// **This is the single site that conversion lives at.** The shim that writes
/// the event passes `parameters` through untouched, and both evaluators read
/// from here.
///
/// Consequence, stated rather than discovered: a command that is *itself* a
/// valid JSON scalar — `true`, `null`, a bare number — parses to a non-string
/// and is then not evaluated, i.e. allowed. That direction is deliberate; those
/// are shell no-ops, and the alternative (never parsing) loses every genuinely
/// structured parameter.
fn reparse_stringified(value: &Value) -> Value {
    match value.as_str() {
        Some(raw) => serde_json::from_str(raw).unwrap_or_else(|_| value.clone()),
        None => value.clone(),
    }
}

/// Resolution over an already-extracted command string.
///
/// Split out from [`evaluate`] so the trigger and the decision can be tested
/// independently, and so a future non-`pre_tool_use` trigger reuses one
/// resolution path.
///
/// Every rule in `command_rules` is active — disabled rules were omitted at
/// BUILD time, so there is no `enabled` check here. `request_rules` is not
/// consulted: the partition happens once at bundle load (D-U19), so this path
/// gained no branch and the tie-break below is unchanged by construction.
///
/// A rule **matches** when its glob matches the normalized command AND its
/// agent-function scope admits this install ([`scoped_matches`]). Conditions
/// only narrow which rules participate, exactly like `match_pattern`; the
/// deciding set, the tie-break, and the kill switch below never see them.
///
/// ```text
///   enforcement_enabled == false      -> all matches are shadow
///   matched rules with mode=enforce   -> DENY (most restrictive wins)
///   matched rules with mode=observe   -> ALLOW + shadow verdict
///   no matches                        -> ALLOW
/// ```
///
/// **Which rule is reported**: sort lexicographically WITHIN THE DECIDING SET,
/// never across all matches.
///
/// ```text
///   deny          -> deciding set = matched rules with mode=enforce
///   allow+shadow  -> deciding set = matched rules (all observe, or
///                    enforcement is off)
/// ```
///
/// Sorting across ALL matches would let an observe rule named `OL-CMD-AAA`
/// claim credit for a block actually caused by `OL-CMD-ZZZ` — reporting a rule
/// that did not decide and handing the developer the wrong `reason`. Evaluation
/// MUST be order-independent and reproducible: shuffling `rules[]` must produce
/// an identical verdict AND an identical reported `rule_id`.
pub fn evaluate_command(bundle: &ResidentBundle, command: &str) -> Option<PolicyMatch> {
    let normalized = normalize(command);

    let matched: Vec<&Rule> = bundle
        .command_rules
        .iter()
        // Scope first: it is an `Option` discriminant test, while
        // `matcher::matches` collects both the pattern and the command into
        // `Vec<char>` on every call. Both are pure and total, so the order is
        // free to be the cheap one — and a rule scoped to another function
        // then costs nothing at all.
        .filter(|r| {
            scoped_matches(r, bundle.agent_function)
                && matcher::matches(&r.match_pattern, &normalized)
        })
        .collect();
    if matched.is_empty() {
        return None;
    }

    // The kill switch is applied here and nowhere else: with enforcement off,
    // an `enforce` rule is indistinguishable from an `observe` one.
    let deny =
        bundle.enforcement_enabled && matched.iter().any(|r| r.mode == PolicyRuleMode::Enforce);

    let deciding: Vec<&Rule> = if deny {
        matched
            .iter()
            .copied()
            .filter(|r| r.mode == PolicyRuleMode::Enforce)
            .collect()
    } else {
        matched
    };

    // `min_by_key` over a stable key: order-independent by construction, so no
    // sort of the whole set is needed.
    let decider = deciding.iter().min_by_key(|r| r.rule_id.as_str())?;

    Some(PolicyMatch {
        rule_id: decider.rule_id.clone(),
        reason: decider.reason.clone(),
        severity: decider.severity,
        mode: decider.mode,
        shadow: !deny,
    })
}

/// Does this rule's agent-function scope admit an install whose resident
/// context is `agent_function`?
///
/// - An unscoped rule (`scoped_functions == None`) admits every install,
///   including one whose context never arrived.
/// - A scoped rule admits the install only when the context **arrived** and
///   names a member of the set. Absent context (`None`) therefore admits
///   nothing — it is not read as `unknown`, and `AgentFunction::Unknown` inside
///   the set is an ordinary member, not a wildcard (A18 / interview D-4).
///
/// The comparison is enum equality on the value the bundle carried when it was
/// swapped in. Nothing here can tell how old that value is: a stale context
/// keeps matching until the next successful poll replaces the resident bundle,
/// which is what "decides from disk with the network unplugged" means (A17).
fn scoped_matches(rule: &Rule, agent_function: Option<AgentFunction>) -> bool {
    rule.scoped_functions
        .as_ref()
        .is_none_or(|set| agent_function.is_some_and(|f| set.contains(&f)))
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, SystemTime};

    use super::super::test_support::*;
    use super::*;
    use serde_json::json;

    fn bash(command: &str) -> Value {
        json!({ "tool_name": "Bash", "tool_input": { "command": command } })
    }

    fn enforce(rule_id: &str, pattern: &str) -> Rule {
        rule(rule_id, pattern, PolicyRuleMode::Enforce)
    }

    fn observe(rule_id: &str, pattern: &str) -> Rule {
        rule(rule_id, pattern, PolicyRuleMode::Observe)
    }

    // -- normalization ------------------------------------------------------

    #[test]
    fn normalize_trims_and_collapses_only() {
        assert_eq!(normalize("  rm   -rf   /tmp  "), "rm -rf /tmp");
        assert_eq!(normalize("rm\t-rf\n/tmp"), "rm -rf /tmp");
        assert_eq!(normalize(""), "");
        assert_eq!(normalize("   "), "");
        // No quote handling, no variable expansion, no alias resolution.
        assert_eq!(normalize("echo \"a  b\" $HOME"), "echo \"a b\" $HOME");
    }

    // -- trigger ------------------------------------------------------------

    #[test]
    fn only_pre_tool_use_is_evaluated() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        assert!(evaluate(&bundle, "post_tool_use", Some(&bash("rm -rf /"))).is_none());
        assert!(evaluate(&bundle, "stop", Some(&bash("rm -rf /"))).is_none());
        assert!(evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /"))).is_some());
    }

    /// A `tool_name` outside the frozen list is never evaluated, regardless of
    /// what its arguments contain.
    ///
    /// `execute_command` used to sit in this list and has moved to
    /// `execute_command_alone_reaches_a_verdict`: §0a admitted it because Cline
    /// now has a translator. Every name left here belongs to an agent that does
    /// not, so a deny produced for one would be discarded before the developer
    /// saw it.
    #[test]
    fn tool_name_outside_the_frozen_list_is_never_evaluated() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        for tool in [
            "Read",
            "Write",
            "run_terminal_cmd",  // Cursor — no translator yet
            "shell",             // Codex CLI's SDK id; its wire name is `Bash`
            "run_shell_command", // Gemini CLI — no translator yet
            // Case-sensitive: neither is `Bash`, and lowercase `bash` is one of
            // Cline's own configured-agent aliases — an alias is not a wire
            // name, so admitting the two real spellings does not admit it.
            "bash",
            "Execute_Command",
            "Run_Commands",
        ] {
            let data = json!({ "tool_name": tool, "tool_input": { "command": "rm -rf /" } });
            assert!(
                evaluate(&bundle, "pre_tool_use", Some(&data)).is_none(),
                "{tool} must not be evaluated"
            );
        }
    }

    /// The tripwire that made §0a's ordering enforceable — **re-pointed, not
    /// deleted**.
    ///
    /// It was `frozen_list_is_exactly_bash_in_v1`, asserting `&["Bash"]`, so
    /// that no one could widen evaluation coverage without coming here and
    /// reading why the list is short. That reason has not changed: every entry
    /// must be an agent whose deny `src/hook_output/` can express, or the
    /// verdict is evaluated correctly and then silently discarded.
    ///
    /// So the assertion is on the exact literal, deliberately: a fourth name
    /// reddens here, and the fix is a translator plus a vendored schema first —
    /// never an edit to this line.
    #[test]
    fn frozen_list_is_exactly_the_translated_names() {
        assert_eq!(
            SHELL_TOOL_NAMES,
            &["Bash", "run_commands", "execute_command"],
            "widening SHELL_TOOL_NAMES needs a `src/hook_output/` translator and \
             a `schemas/vendor/<agent>/` schema for that agent FIRST — without \
             them the deny is discarded before the developer sees it"
        );
    }

    // -- the agent's own spelling -------------------------------------------

    /// §0 — without this, a Cline event that reaches the daemon is
    /// **unevaluatable**: Cline names the same two fields `toolName` and
    /// `parameters`, and the extraction read neither.
    ///
    /// The rule genuinely matches the payload — through the extraction and
    /// then `evaluate_command`, which is the whole decision. The gate that
    /// used to hold the verdict at the door, [`SHELL_TOOL_NAMES`], is now
    /// **open to Cline**: §0a admitted both spellings once `hook_output::cline`
    /// and `schemas/vendor/cline/hook-output.schema.json` landed, so a deny
    /// leaving here is one something can deliver. Both halves are still
    /// asserted — the extraction and the whole-`evaluate` path — because the
    /// extraction is what makes the gate reachable at all, and losing it would
    /// silently return Cline to unevaluated while the list still named it.
    ///
    /// Per-spelling coverage is deliberately NOT here: this test carries the
    /// canonical id only, and `run_commands_alone_reaches_a_verdict` /
    /// `execute_command_alone_reaches_a_verdict` each feed exactly one name.
    #[test]
    fn a_cline_payload_matches_a_command_rule() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        let cline = json!({
            "toolName": "run_commands",
            "parameters": { "command": "rm -rf /tmp" },
        });

        assert_eq!(tool_name_of(&cline), Some("run_commands"));
        let command = cline_command_of(&cline).expect("parameters.command is extracted");
        assert_eq!(command.as_str(), Some("rm -rf /tmp"));

        let m = evaluate_command(&bundle, command.as_str().unwrap())
            .expect("a `*rm -rf*` rule matches this command");
        assert_eq!(m.rule_id, "OL-CMD-001");
        assert!(!m.shadow, "enforce rule on an enforcing bundle => deny");

        // And the whole path agrees with the hand-assembled one: extraction,
        // gate and resolution, from the payload Cline actually sends.
        let whole = evaluate(&bundle, "pre_tool_use", Some(&cline))
            .expect("SHELL_TOOL_NAMES carries Cline's spellings since §0a");
        assert_eq!(whole, m, "the gate must not change which rule decided");

        // The Claude-shaped payload is untouched by the fallback existing.
        assert!(evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).is_some());
    }

    /// §0a — `run_commands` **on its own**.
    ///
    /// Cline's two spellings get one test each, and neither test mentions the
    /// other name. A single test that loops both, or that feeds the one name it
    /// happens to register, is self-confirming: it passes on a list carrying
    /// only that entry and proves nothing about the sibling. Splitting them
    /// also means the failure names the spelling that regressed.
    #[test]
    fn run_commands_alone_reaches_a_verdict() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        let data = json!({
            "toolName": "run_commands",
            "parameters": { "command": "rm -rf /tmp" },
        });

        let m = evaluate(&bundle, "pre_tool_use", Some(&data))
            .expect("`run_commands` is Cline's canonical SDK tool id (runtime.ts:63)");
        assert_eq!(m.rule_id, "OL-CMD-001");
        assert!(!m.shadow, "enforce rule on an enforcing bundle => deny");
    }

    /// §0a — `execute_command` **on its own**.
    ///
    /// The legacy VS Code spelling, still live: VS Code's tool enum names it
    /// (`apps/vscode/src/shared/tools.ts:11`) and its policy layer treats it as
    /// one set with `run_commands` (`sdk-tool-policies.ts:27`), both at v4.1.17.
    /// Cline's alias map folds it into `run_commands`, but only for **configured
    /// agents** — it is not a universal normalizer, so this name reaches the
    /// wire unfolded and has to be matched here in its own right.
    #[test]
    fn execute_command_alone_reaches_a_verdict() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        let data = json!({
            "toolName": "execute_command",
            "parameters": { "command": "rm -rf /tmp" },
        });

        let m = evaluate(&bundle, "pre_tool_use", Some(&data))
            .expect("`execute_command` reaches the wire unfolded and must be matched");
        assert_eq!(m.rule_id, "OL-CMD-001");
        assert!(!m.shadow, "enforce rule on an enforcing bundle => deny");
    }

    /// The gate reads the NAME, not the container it arrived in.
    ///
    /// `tool_name_of` accepts either spelling of the key, so a Cline tool id
    /// under Claude's `tool_name` is admitted too. Asserted rather than left
    /// implicit because it is the shape a relay or a future adapter would
    /// produce, and it must not be a hole — nor a second gate to keep in sync.
    #[test]
    fn the_frozen_list_matches_the_name_whichever_key_carried_it() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        for tool in ["run_commands", "execute_command"] {
            let data = json!({ "tool_name": tool, "tool_input": { "command": "rm -rf /tmp" } });
            assert!(
                evaluate(&bundle, "pre_tool_use", Some(&data)).is_some(),
                "{tool} under `tool_name` must be evaluated too"
            );
        }
    }

    /// The native spelling wins. Both keys present is not a shape any agent
    /// sends, but the fallback must not be able to override a field the agent
    /// did set.
    #[test]
    fn the_native_spelling_wins_over_the_fallback() {
        let both = json!({
            "tool_name": "Bash",
            "toolName": "run_commands",
            "tool_input": { "command": "native" },
            "parameters": { "command": "fallback" },
        });

        assert_eq!(tool_name_of(&both), Some("Bash"));
        // The native spelling wins, and it wins by being tried first in
        // `evaluate` — where it BORROWS. `cline_command_of` is the fallback and
        // only sees `parameters`, so asserting it returns the Cline value here
        // is asserting the split, not contradicting the precedence.
        assert_eq!(cline_command_of(&both), Some(json!("fallback")));
        let m = evaluate(
            &resident(vec![enforce("OL-CMD-001", "*native*")], true),
            "pre_tool_use",
            Some(&both),
        );
        assert!(
            m.is_some(),
            "a rule matching the NATIVE command must match, which proves \
             `tool_input.command` is what `evaluate` reached for"
        );
    }

    /// Cline's `parameters` is `Record<string, string>`: every value that was
    /// not already a string arrived `JSON.stringify`d per key.
    #[test]
    fn stringified_parameters_are_parsed_back() {
        assert_eq!(reparse_stringified(&json!(r#"{"a":1}"#)), json!({"a": 1}));
        assert_eq!(reparse_stringified(&json!("[1,2]")), json!([1, 2]));

        // A shell command is not valid JSON, so it stays exactly as it came —
        // including one that merely contains JSON punctuation.
        assert_eq!(
            reparse_stringified(&json!("rm -rf /tmp")),
            json!("rm -rf /tmp")
        );
        assert_eq!(reparse_stringified(&json!("echo {}")), json!("echo {}"));

        // A value that was never a string is returned untouched.
        assert_eq!(reparse_stringified(&json!(7)), json!(7));
        assert_eq!(reparse_stringified(&json!(null)), json!(null));
    }

    #[test]
    fn missing_or_non_string_command_allows() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*")], true);

        assert!(evaluate(&bundle, "pre_tool_use", None).is_none());
        assert!(evaluate(&bundle, "pre_tool_use", Some(&json!(null))).is_none());
        assert!(evaluate(&bundle, "pre_tool_use", Some(&json!({}))).is_none());
        assert!(evaluate(
            &bundle,
            "pre_tool_use",
            Some(&json!({ "tool_name": "Bash" }))
        )
        .is_none());
        assert!(evaluate(
            &bundle,
            "pre_tool_use",
            Some(&json!({ "tool_name": "Bash", "tool_input": {} }))
        )
        .is_none());
        // Array-shaped arguments: the documented v1 blind spot.
        assert!(evaluate(
            &bundle,
            "pre_tool_use",
            Some(&json!({ "tool_name": "Bash", "tool_input": { "command": ["rm", "-rf", "/"] } }))
        )
        .is_none());
        assert!(evaluate(
            &bundle,
            "pre_tool_use",
            Some(&json!({ "tool_name": 42, "tool_input": { "command": "rm -rf /" } }))
        )
        .is_none());
    }

    #[test]
    fn evaluate_uses_the_normalized_command() {
        let bundle = resident(vec![enforce("OL-CMD-001", "rm -rf /tmp")], true);
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("  rm   -rf    /tmp ")))
            .expect("normalized command matches the anchored pattern");
        assert_eq!(m.rule_id, "OL-CMD-001");
    }

    // -- resolution ---------------------------------------------------------

    #[test]
    fn empty_rule_set_allows() {
        let bundle = resident(vec![], true);
        assert!(evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /"))).is_none());
    }

    #[test]
    fn no_match_allows() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        assert!(evaluate(&bundle, "pre_tool_use", Some(&bash("ls -la"))).is_none());
    }

    #[test]
    fn enforce_match_denies_with_that_rules_id_and_reason() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], true);
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("sudo rm -rf /tmp")))
            .expect("rule matched");
        assert!(
            !m.shadow,
            "an enforce match under an enabled kill switch denies"
        );
        assert_eq!(m.rule_id, "OL-CMD-001");
        assert_eq!(m.reason, "OL-CMD-001 says no");
        assert_eq!(m.mode, PolicyRuleMode::Enforce);
        assert_eq!(m.severity, PolicyRuleSeverity::High);
    }

    #[test]
    fn observe_match_allows_with_a_shadow_verdict() {
        let bundle = resident(vec![observe("OL-CMD-001", "*rm -rf*")], true);
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).expect("matched");
        assert!(m.shadow, "observe never blocks");
        assert_eq!(m.rule_id, "OL-CMD-001");
        assert_eq!(m.mode, PolicyRuleMode::Observe);
    }

    /// The org-wide kill switch: every rule behaves as observe.
    #[test]
    fn enforcement_disabled_forces_shadow() {
        let bundle = resident(vec![enforce("OL-CMD-001", "*rm -rf*")], false);
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).expect("matched");
        assert!(m.shadow, "kill switch off => nothing blocks");
        assert_eq!(m.rule_id, "OL-CMD-001");
        // The authored mode is still reported, so the log shows an `enforce`
        // rule that did not enforce rather than silently claiming `observe`.
        assert_eq!(m.mode, PolicyRuleMode::Enforce);
    }

    /// Most restrictive wins across matching rules.
    #[test]
    fn enforce_beats_observe_when_both_match() {
        let bundle = resident(
            vec![
                observe("OL-CMD-AAA", "*rm*"),
                enforce("OL-CMD-ZZZ", "*rm -rf*"),
            ],
            true,
        );
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).expect("matched");
        assert!(!m.shadow);
    }

    /// THE deciding-set test. `OL-CMD-AAA` sorts first overall but did not
    /// decide anything — reporting it would hand the developer the wrong reason
    /// for the block.
    #[test]
    fn reported_rule_comes_from_the_deciding_set_not_all_matches() {
        let bundle = resident(
            vec![
                observe("OL-CMD-AAA", "*rm*"),
                enforce("OL-CMD-ZZZ", "*rm -rf*"),
            ],
            true,
        );
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).expect("matched");
        assert_eq!(m.rule_id, "OL-CMD-ZZZ");
        assert_eq!(m.reason, "OL-CMD-ZZZ says no");
        assert!(!m.shadow);
    }

    /// The mirror image: with the kill switch off nothing is enforcing, so the
    /// deciding set is *all* matches and the lexicographically first of those
    /// is reported.
    #[test]
    fn deciding_set_widens_when_enforcement_is_off() {
        let bundle = resident(
            vec![
                observe("OL-CMD-AAA", "*rm*"),
                enforce("OL-CMD-ZZZ", "*rm -rf*"),
            ],
            false,
        );
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).expect("matched");
        assert_eq!(m.rule_id, "OL-CMD-AAA");
        assert!(m.shadow);
    }

    #[test]
    fn lexicographically_first_enforce_rule_is_reported() {
        let bundle = resident(
            vec![
                enforce("OL-CMD-ZZZ", "*rm -rf*"),
                enforce("OL-CMD-BBB", "*rm*"),
                enforce("OL-CMD-MMM", "*-rf*"),
            ],
            true,
        );
        let m = evaluate(&bundle, "pre_tool_use", Some(&bash("rm -rf /tmp"))).expect("matched");
        assert_eq!(m.rule_id, "OL-CMD-BBB");
    }

    /// Order-independence: every permutation of `rules[]` must yield an
    /// identical verdict AND an identical reported `rule_id`.
    #[test]
    fn evaluation_is_order_independent() {
        let rules = vec![
            observe("OL-CMD-AAA", "*rm*"),
            enforce("OL-CMD-ZZZ", "*rm -rf*"),
            observe("OL-CMD-MMM", "*-rf*"),
            enforce("OL-CMD-QQQ", "*rm -rf /tmp*"),
            enforce("OL-CMD-DDD", "*/tmp*"),
        ];
        let expected =
            evaluate_command(&resident(rules.clone(), true), "rm -rf /tmp").expect("matched");
        assert_eq!(expected.rule_id, "OL-CMD-DDD");
        assert!(!expected.shadow);

        // A deterministic shuffle: 100 rotations/reversals over the rule set.
        let mut permuted = rules;
        let len = permuted.len();
        for i in 0..100 {
            permuted.rotate_left(1 + (i % len));
            if i % 3 == 0 {
                permuted.reverse();
            }
            let got = evaluate_command(&resident(permuted.clone(), true), "rm -rf /tmp")
                .expect("matched");
            assert_eq!(got, expected, "permutation {i} changed the verdict");
        }
    }

    #[test]
    fn severity_and_reason_come_from_the_deciding_rule() {
        let mut low = enforce("OL-CMD-BBB", "*rm*");
        low.severity = PolicyRuleSeverity::Low;
        low.reason = "low severity".to_string();
        let mut critical = enforce("OL-CMD-ZZZ", "*rm*");
        critical.severity = PolicyRuleSeverity::Critical;

        let bundle = resident(vec![critical, low], true);
        let m = evaluate_command(&bundle, "rm -rf /tmp").expect("matched");
        // Lexicographic tiebreak, not severity ranking — the PRD picks the
        // first rule_id within the deciding set, deliberately.
        assert_eq!(m.rule_id, "OL-CMD-BBB");
        assert_eq!(m.severity, PolicyRuleSeverity::Low);
        assert_eq!(m.reason, "low severity");
    }

    #[test]
    fn matching_is_anchored_over_the_whole_command() {
        let bundle = resident(vec![enforce("OL-CMD-001", "rm -rf /*")], true);
        assert!(evaluate_command(&bundle, "rm -rf /tmp").is_some());
        assert!(evaluate_command(&bundle, "sudo rm -rf /tmp").is_none());
    }

    // -- agent-context conditions (I-4 C-03) --------------------------------

    /// Every value the enum carries, so "scoped to everything" can be told
    /// apart from "unscoped": the former still admits no install whose context
    /// is absent.
    const EVERY_FUNCTION: [AgentFunction; 14] = [
        AgentFunction::Engineering,
        AgentFunction::Product,
        AgentFunction::Data,
        AgentFunction::Security,
        AgentFunction::ItOps,
        AgentFunction::Sales,
        AgentFunction::Marketing,
        AgentFunction::Finance,
        AgentFunction::Legal,
        AgentFunction::Hr,
        AgentFunction::Support,
        AgentFunction::Research,
        AgentFunction::Other,
        AgentFunction::Unknown,
    ];

    /// `EVERY_FUNCTION` is hand-written, and "scoped to everything" only means
    /// what it says while it really is everything: a 15th value added to the
    /// schema would leave the array a proper subset, and
    /// `agent_context_unknown_not_wildcard` and its neighbours would keep
    /// passing while testing a narrower claim than they read as. typify emits
    /// no variant count, so the schema is the thing to count.
    #[test]
    fn every_function_covers_the_whole_vocabulary() {
        // Same values in the same order, not merely the same count.
        let spelled: Vec<String> = EVERY_FUNCTION.iter().map(|f| f.to_string()).collect();
        assert_eq!(spelled, super::super::validate::agent_function_vocabulary());
    }

    fn scoped(mut r: Rule, functions: &[AgentFunction]) -> Rule {
        r.scoped_functions = Some(functions.to_vec());
        r
    }

    /// Every context an install can be in: each function the vocabulary
    /// carries, and the one where no context ever arrived.
    fn every_context() -> impl Iterator<Item = Option<AgentFunction>> {
        EVERY_FUNCTION.into_iter().map(Some).chain([None])
    }

    fn resident_for(function: Option<AgentFunction>, rules: Vec<Rule>) -> ResidentBundle {
        let mut bundle = resident(rules, true);
        bundle.agent_function = function;
        bundle
    }

    /// The initiative's named test: an enforce rule scoped to a set containing
    /// this install's function denies, decided from the resident bundle alone.
    #[test]
    fn agent_context_rule_matching() {
        let rules = vec![scoped(
            enforce("OL-CMD-002", "*psql*"),
            &[AgentFunction::Marketing, AgentFunction::Sales],
        )];

        let marketing = resident_for(Some(AgentFunction::Marketing), rules.clone());
        let m = evaluate(&marketing, "pre_tool_use", Some(&bash("psql -h prod")))
            .expect("a member function matches");
        assert_eq!(m.rule_id, "OL-CMD-002");
        assert!(!m.shadow, "enforce + member function => deny");

        let sales = resident_for(Some(AgentFunction::Sales), rules.clone());
        assert!(evaluate_command(&sales, "psql -h prod").is_some_and(|m| !m.shadow));

        // The same rule on an install outside the set: nothing matches.
        let engineering = resident_for(Some(AgentFunction::Engineering), rules);
        assert!(evaluate_command(&engineering, "psql -h prod").is_none());
    }

    /// A17's client half. The resident value is what decides; nothing in
    /// `evaluate` can observe how old it is, so a bundle swapped in a month ago
    /// keeps matching identically until a later poll replaces it.
    #[test]
    fn agent_context_stale_still_matches() {
        let rules = vec![scoped(
            enforce("OL-CMD-002", "*psql*"),
            &[AgentFunction::Marketing],
        )];
        let fresh = resident_for(Some(AgentFunction::Marketing), rules.clone());
        let mut stale = resident_for(Some(AgentFunction::Marketing), rules);
        stale.built_at = SystemTime::UNIX_EPOCH;
        stale.revision = 1;

        let now = fresh.built_at + Duration::from_secs(60);
        assert!(
            stale.age_seconds(now) > fresh.age_seconds(now),
            "the fixture is genuinely stale"
        );
        assert_eq!(
            evaluate_command(&stale, "psql -h prod"),
            evaluate_command(&fresh, "psql -h prod"),
            "bundle age is invisible to evaluation"
        );
        assert!(evaluate_command(&stale, "psql -h prod").is_some_and(|m| !m.shadow));
    }

    /// A18. `unknown` is a value the platform assigns; a rule listing it
    /// matches exactly the installs whose context says so — never the ones
    /// whose context is absent, and an `unknown` install is admitted by no
    /// other set.
    #[test]
    fn agent_context_unknown_not_wildcard() {
        let only_unknown = vec![scoped(
            enforce("OL-CMD-003", "*curl*"),
            &[AgentFunction::Unknown],
        )];
        assert!(evaluate_command(
            &resident_for(Some(AgentFunction::Unknown), only_unknown.clone()),
            "curl https://x"
        )
        .is_some());
        assert!(evaluate_command(
            &resident_for(Some(AgentFunction::Marketing), only_unknown.clone()),
            "curl https://x"
        )
        .is_none());
        assert!(
            evaluate_command(&resident_for(None, only_unknown), "curl https://x").is_none(),
            "absent context is not `unknown`"
        );

        let marketing_only = vec![scoped(
            enforce("OL-CMD-002", "*psql*"),
            &[AgentFunction::Marketing],
        )];
        assert!(evaluate_command(
            &resident_for(Some(AgentFunction::Unknown), marketing_only),
            "psql -h prod"
        )
        .is_none());
    }

    /// Interview D-4. No context ⇒ every scoped rule steps aside — even one
    /// scoped to every function there is — while the unconditional rule beside
    /// it keeps enforcing.
    #[test]
    fn absent_context_means_scoped_rules_match_nothing() {
        let bundle = resident_for(
            None,
            vec![
                scoped(enforce("OL-CMD-AAA", "*rm -rf*"), &EVERY_FUNCTION),
                enforce("OL-CMD-ZZZ", "*rm -rf*"),
            ],
        );
        let m = evaluate_command(&bundle, "rm -rf /tmp").expect("the unconditional rule matches");
        assert_eq!(
            m.rule_id, "OL-CMD-ZZZ",
            "the scoped rule is not in the deciding set even though it sorts first"
        );
        assert!(!m.shadow);

        let only_scoped = resident_for(
            None,
            vec![scoped(enforce("OL-CMD-AAA", "*rm -rf*"), &EVERY_FUNCTION)],
        );
        assert!(
            evaluate_command(&only_scoped, "rm -rf /tmp").is_none(),
            "with only scoped rules the command is allowed outright"
        );
    }

    /// AND semantics, wire to verdict: two `in` conditions on one rule admit
    /// only the functions in BOTH sets; disjoint sets admit nobody.
    #[test]
    fn conditions_and_semantics_all_must_hold() {
        let both = scoped_wire_rule(
            "OL-CMD-002",
            "*psql*",
            vec![
                function_in(&[AgentFunction::Marketing, AgentFunction::Sales]),
                function_in(&[AgentFunction::Sales, AgentFunction::Finance]),
            ],
        );
        let disjoint = scoped_wire_rule(
            "OL-CMD-004",
            "*psql*",
            vec![
                function_in(&[AgentFunction::Marketing]),
                function_in(&[AgentFunction::Finance]),
            ],
        );

        let for_function = |f: AgentFunction| {
            let mut resident = ResidentBundle::from_bundle(&wire_bundle(
                vec![both.clone(), disjoint.clone()],
                true,
            ));
            assert_eq!(resident.command_rules.len(), 2, "both rules load");
            resident.agent_function = Some(f);
            resident
        };

        let m = evaluate_command(&for_function(AgentFunction::Sales), "psql -h prod")
            .expect("sales is in both sets");
        assert_eq!(m.rule_id, "OL-CMD-002", "the disjoint rule admits nobody");
        assert!(!m.shadow);
        for outside in [
            AgentFunction::Marketing,
            AgentFunction::Finance,
            AgentFunction::Unknown,
        ] {
            assert!(
                evaluate_command(&for_function(outside), "psql -h prod").is_none(),
                "{outside} is in at most one of the sets"
            );
        }
    }

    #[test]
    fn a_rule_without_conditions_is_unconditional() {
        let rules = vec![enforce("OL-CMD-001", "*rm -rf*")];
        for function in every_context() {
            let m = evaluate_command(&resident_for(function, rules.clone()), "rm -rf /tmp")
                .unwrap_or_else(|| panic!("{function:?} matches an unscoped rule"));
            assert_eq!(m.rule_id, "OL-CMD-001");
            assert!(!m.shadow);
        }
    }

    /// Conditions narrow which rules participate and nothing else: the deciding
    /// set, the tie-break and the kill switch behave exactly as if a scoped-out
    /// rule were not in the bundle.
    #[test]
    fn a_scoped_out_rule_leaves_the_deciding_set_untouched() {
        let rules = vec![
            scoped(enforce("OL-CMD-AAA", "*rm*"), &[AgentFunction::Finance]),
            observe("OL-CMD-MMM", "*rm*"),
            enforce("OL-CMD-ZZZ", "*rm -rf*"),
        ];

        // Engineering: AAA is out; ZZZ decides although AAA sorts first.
        let m = evaluate_command(
            &resident_for(Some(AgentFunction::Engineering), rules.clone()),
            "rm -rf /tmp",
        )
        .expect("matched");
        assert_eq!(m.rule_id, "OL-CMD-ZZZ");
        assert!(!m.shadow);

        // Finance: AAA participates and, first in the deciding set, is reported.
        let m = evaluate_command(
            &resident_for(Some(AgentFunction::Finance), rules.clone()),
            "rm -rf /tmp",
        )
        .expect("matched");
        assert_eq!(m.rule_id, "OL-CMD-AAA");
        assert!(!m.shadow);

        // Kill switch off, engineering: the deciding set is every match this
        // install participates in — MMM, not the scoped-out AAA.
        let mut off = resident_for(Some(AgentFunction::Engineering), rules);
        off.enforcement_enabled = false;
        let m = evaluate_command(&off, "rm -rf /tmp").expect("matched");
        assert_eq!(m.rule_id, "OL-CMD-MMM");
        assert!(m.shadow);
    }

    /// The projected form of disjoint conditions: a scope admitting no function
    /// matches no install, whatever its context says.
    #[test]
    fn an_empty_scope_matches_no_install() {
        let rules = vec![scoped(enforce("OL-CMD-004", "*"), &[])];
        for function in every_context() {
            assert!(
                evaluate_command(&resident_for(function, rules.clone()), "anything").is_none(),
                "{function:?} must not be admitted by an empty scope"
            );
        }
    }
}