openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
//! 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";

/// v1 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`). v1 ships ONE.
///
/// WHY: `src/hook_output/mod.rs::translate` has a single `"claude-code"` arm;
/// every other agent falls through to `empty()` — the universal "continue
/// normally" `{}`. So a deny produced for the other four 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 THE OTHER FOUR: a translator per agent 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`. That is the v1.1
/// scope; adding a `tool_name` here without it re-opens the silent-discard hole.
///
/// 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; v1.1 item).
///
/// Matched case-sensitively, exactly as the agent emits it.
pub const SHELL_TOOL_NAMES: &[&str] = &["Bash"];

/// 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` is absent, not a string, or outside [`SHELL_TOOL_NAMES`];
/// - `tool_input.command` is absent or not a string;
/// - no rule matched.
///
/// # 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 = data.get("tool_name")?.as_str()?;
    if !SHELL_TOOL_NAMES.contains(&tool_name) {
        return None;
    }

    let command = data.get("tool_input")?.get("command")?.as_str()?;
    evaluate_command(bundle, command)
}

/// 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.
    #[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 — v1.1, no translator yet
            "shell",            // Codex CLI
            "run_shell_command",
            "execute_command",
            "bash", // case-sensitive: not `Bash`
        ] {
            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 in v1"
            );
        }
    }

    #[test]
    fn frozen_list_is_exactly_bash_in_v1() {
        assert_eq!(SHELL_TOOL_NAMES, &["Bash"]);
    }

    #[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"
            );
        }
    }
}