openlatch-client 0.6.5

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! The verdict lattice and record assembly — plan 02 §2g, PRD §Verdict lattice.
//!
//! # The lattice
//!
//! `Block > Ask > Optimize > Allow`, joined across **enforce-mode atoms only**.
//! Monitor-mode atoms and `monitor_only` atoms contribute `would_have_verdict`
//! and an anomaly; they NEVER enter the join. *Monitor never joins* is the
//! invariant, and [`assemble`] is where a reviewer checks it: the slice is
//! partitioned once, by [`Contribution::is_enforcing`], and every field that can
//! reach the agent — the verdict, the hold, the rewrite, the matched exception's
//! ground key — is read off the enforcing half.
//!
//! `enforcement_enabled: false` makes every artifact monitor, which is why the
//! kill switch needs no second rule here: it composes into the mode above the
//! tiers and the partition does the rest.
//!
//! # R10 — exactly one rewrite per action
//!
//! At most one rewrite leaves the engine. It is owned by the **first optimize
//! contribution in artifact order that declares a lever**, and only an
//! **enforcing** one: folding over all contributions sent a steer instruction to
//! the agent with the org-wide kill switch off, and let a monitor artifact spend
//! R10's single slot while the artifact that actually decided lost its own.
//!
//! A second optimize does not get a turn. The corpus pins the whole set —
//! `07-rewrite-{one,two,none,enforcement-off,monitor,two-a-monitor}`.
//!
//! **What is not here, and why it is not a gap.** R10 continues: *"evaluate all
//! tiers → at most one rewrite → re-evaluate every tier on the final input
//! **in-daemon** → a second rewrite downgrades to ASK/BLOCK;
//! `original_input`/`updated_input`/`rewrite_rule_id` recorded"*. The second pass
//! is over a **mutated action**, and the PRD puts it in the daemon: this function
//! is pure and never sees the rewritten input, so it reports the one rewrite the
//! daemon would apply and the daemon calls [`super::evaluate`] again with it. The
//! three recorded fields are the decision record's `rewrite` column (PRD
//! §`decision_records`), not [`Rewrite`] — the corpus pins the engine's shape as
//! `{lever, artifact_id, steer_instruction}`, and the oracle agrees.

use std::collections::{BTreeMap, BTreeSet};

use super::effect::catalogue::Origin;
use super::types::{
    Anomaly, AskPolicy, Classification, Contribution, Decision, EvalContext, Event,
    OptimizeCandidate, OptimizeContext, ReportedEffect, Rewrite,
};
use crate::generated::types::Verdict;

/// Where a verdict sits in the lattice. Block dominates; Allow yields.
pub fn rank(verdict: &Verdict) -> u8 {
    match verdict {
        Verdict::Allow => 0,
        Verdict::Optimize => 1,
        Verdict::Ask => 2,
        Verdict::Block => 3,
    }
}

/// What an ASK does once it reaches the agent (AZ-4 §6.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AskDelivery {
    /// The agent's own prompt.
    Agent,
    /// The artifact's `ask_fallback` verdict, which is still an ASK on the wire.
    Fallback(AskFallback),
}

/// The verdict an ASK degrades to when it cannot be a native prompt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AskFallback {
    Allow,
    Block,
}

impl AskPolicy {
    /// How this ASK is delivered to an agent that can, or cannot, prompt.
    ///
    /// | `ask_mode` | agent can prompt | delivery |
    /// | ---------- | ---------------- | -------- |
    /// | `platform` | any | the fallback |
    /// | `agent` · `both` | yes | the agent's prompt |
    /// | `agent` · `both` | no | the fallback |
    ///
    /// Whether a ground opens is the platform's, from `olaskdelivery` and the
    /// mode; it is not an engine fact.
    pub fn delivery(&self, can_ask: bool) -> AskDelivery {
        let prompts = self.mode != "platform" && can_ask;
        if prompts {
            AskDelivery::Agent
        } else if self.fallback == "block" {
            AskDelivery::Fallback(AskFallback::Block)
        } else {
            AskDelivery::Fallback(AskFallback::Allow)
        }
    }
}

/// Whether the agent can prompt on this event: `ask` is in the set it declares.
pub fn event_can_ask(event: &Event) -> bool {
    event
        .expressible
        .as_ref()
        .is_some_and(|set| set.iter().any(|verdict| verdict == "ask"))
}

/// How strict a contribution's delivery is, lowest first: an ASK whose delivery is
/// the `block` fallback, then one that prompts, then one whose delivery is the
/// `allow` fallback. A contribution that is not an ASK, or whose artifact declares
/// no ask policy, is the prompt that was always delivered.
fn ask_strictness(contribution: &Contribution, can_ask: bool) -> u8 {
    if contribution.verdict != Verdict::Ask {
        return 1;
    }
    // A fired hold takes precedence over the mode (§6.10): its own deferral is
    // its delivery, so it is never weaker than another ASK's fallback or prompt.
    if contribution.hold.is_some() {
        return 0;
    }
    match contribution
        .ask
        .as_ref()
        .map(|policy| policy.delivery(can_ask))
    {
        Some(AskDelivery::Fallback(AskFallback::Block)) => 0,
        Some(AskDelivery::Fallback(AskFallback::Allow)) => 2,
        Some(AskDelivery::Agent) | None => 1,
    }
}

/// The highest-ranked contribution, or `None` when the slice is empty.
///
/// **Several ASKs on one action** are ordered by how each would be delivered
/// (see [`ask_strictness`]): a `platform`/`block` ASK can never be bypassed by
/// another ASK's prompt, and exactly one ASK decides. **Ties break on
/// `artifact_id`**, ascending, so two artifacts that both block name the same one
/// on every host and every replay. Without it the answer would depend on
/// iteration order, and a decision record a CISO reads as evidence would name a
/// different rule on a re-run of the same event.
pub fn join(contributions: &[Contribution], can_ask: bool) -> Option<&Contribution> {
    best(contributions.iter(), can_ask)
}

/// [`join`] over any iterator, so the enforcing and monitoring halves are each
/// joined without materialising a second slice.
fn best<'a>(
    contributions: impl Iterator<Item = &'a Contribution>,
    can_ask: bool,
) -> Option<&'a Contribution> {
    contributions.min_by(|left, right| {
        rank(&right.verdict)
            .cmp(&rank(&left.verdict))
            .then_with(|| ask_strictness(left, can_ask).cmp(&ask_strictness(right, can_ask)))
            .then_with(|| artifact_id(left).cmp(artifact_id(right)))
    })
}

/// Build the `Decision` from the contributions, the classification and the
/// context's accumulators.
pub fn assemble(contributions: &[Contribution], ctx: &EvalContext<'_>) -> Decision {
    // A non-matching artifact produces no contribution, so applicability is
    // known only here. Same-layer conflicts must not disable disjoint regions.
    let active = without_same_layer_conflicts(contributions);
    // The one partition the whole invariant rests on. Everything that can reach
    // the agent is read off `decided`; `shadow` only ever reports.
    let enforcing: Vec<&Contribution> = active
        .iter()
        .copied()
        .filter(|c| c.is_enforcing())
        .collect();
    let monitoring: Vec<&Contribution> = active
        .iter()
        .copied()
        .filter(|c| !c.is_enforcing())
        .collect();
    let can_ask = event_can_ask(ctx.event);
    let joined = best(enforcing.iter().copied(), can_ask);
    // What Enforce would have done. Read off the monitor half alone: a shadow
    // verdict is only meaningful for the artifacts that were not allowed to
    // decide.
    let shadow = best(monitoring.iter().copied(), can_ask);
    let (actual_optimize, mut optimize_shadowed) =
        if joined.is_some_and(|c| c.verdict == Verdict::Optimize) {
            select_optimize(&enforcing)
        } else {
            (None, Vec::new())
        };
    let (monitor_optimize, monitor_shadowed) =
        if shadow.is_some_and(|c| c.verdict == Verdict::Optimize) {
            select_optimize(&monitoring)
        } else {
            (None, Vec::new())
        };
    optimize_shadowed.extend(monitor_shadowed);
    optimize_shadowed.truncate(32);
    let decided = actual_optimize.or(joined);
    let record_source = match decided {
        Some(candidate) if matches!(candidate.verdict, Verdict::Block | Verdict::Ask) => {
            Some(candidate)
        }
        Some(candidate) if candidate.verdict == Verdict::Allow && monitor_optimize.is_some() => {
            monitor_optimize
        }
        Some(candidate) => Some(candidate),
        None => shadow
            .filter(|candidate| matches!(candidate.verdict, Verdict::Block | Verdict::Ask))
            .or(monitor_optimize),
    };

    // Sorted and deduplicated, across EVERY contribution — a monitor artifact
    // that could not read a fact has still found a gap, and the gap is the point.
    let inconclusive_facts: Vec<String> = active
        .iter()
        .flat_map(|c| c.inconclusive.iter().cloned())
        .collect::<BTreeSet<String>>()
        .into_iter()
        .collect();

    // Anomalies record; they never decide. Every contribution's, in artifact
    // order, because a monitor artifact raising one is the whole reason Monitor
    // mode exists.
    let anomalies: Vec<Anomaly> = active
        .iter()
        .flat_map(|c| {
            c.anomalies.iter().map(|code| Anomaly {
                code: code.clone(),
                artifact_id: c.artifact_id.clone(),
                atom_id: c.atom_id.clone(),
            })
        })
        .collect();

    Decision {
        verdict: decided.map(|c| c.verdict).unwrap_or(Verdict::Allow),
        artifact_id: record_source.and_then(|c| c.artifact_id.clone()),
        atom_id: record_source.and_then(|c| c.atom_id.clone()),
        policy_public_id: record_source.and_then(|c| c.policy_public_id.clone()),
        dimension: record_source.and_then(|c| c.dimension.clone()),
        mode: record_source.map(|c| c.mode.clone()),
        tier: record_source.and_then(|c| c.tier),
        reason: record_source.map(|c| c.reason.clone()).unwrap_or_default(),
        would_have_verdict: shadow.map(|c| c.verdict),
        inconclusive_facts,
        rewrite: rewrite(enforcing.iter().copied()),
        optimize: (actual_optimize.is_some() || monitor_optimize.is_some()).then(|| {
            OptimizeContext {
                actual: actual_optimize.and_then(selected_evidence),
                monitor: monitor_optimize.and_then(selected_evidence),
                shadowed: optimize_shadowed,
            }
        }),
        hold: decided.and_then(|c| c.hold.clone()),
        effects: ctx.classification.effects.clone(),
        effect_report: effect_report(ctx.classification),
        // True when NOTHING contributed — distinct from `verdict: allow`, which
        // an artifact may have decided on purpose, and from an all-monitor
        // bundle, which decided nothing but was not silent.
        undecided: active.is_empty(),
        unknown: ctx.classification.unknown.clone(),
        anomalies,
        ground_key: decided.and_then(|c| c.exception_ground_key.clone()),
        warnings: ctx.warnings.clone(),
    }
}

/// The full classification as the decision event reports it: every tuple with the
/// origins that produced it and the path or host it names.
///
/// A path-based class names the first declared path the resolver gave that class;
/// `network_host` names the first URL's host. A tuple about nothing addressable
/// (`execute × shell`) has no target.
fn effect_report(classification: &Classification) -> Vec<ReportedEffect> {
    classification
        .tuples_with_origins()
        .into_iter()
        .map(|(effect, origins)| {
            let target = if effect.target_class.0 == "network_host" {
                classification.urls.first().map(|url| url.host.clone())
            } else {
                classification
                    .paths
                    .iter()
                    .find(|path| path.class == effect.target_class)
                    .map(|path| path.value.clone())
            };
            ReportedEffect {
                origin: origins.iter().map(Origin::label).collect(),
                target,
                effect,
            }
        })
        .collect()
}

/** Drop incompatible directives only after they matched on one mode path. */
fn without_same_layer_conflicts(contributions: &[Contribution]) -> Vec<&Contribution> {
    type GroupKey = (Vec<String>, String);
    let mut groups: BTreeMap<GroupKey, Vec<&super::types::OptimizeCandidateInternal>> =
        BTreeMap::new();
    for contribution in contributions {
        let Some(optimize) = contribution.optimize.as_ref() else {
            continue;
        };
        groups
            .entry((optimize.layer_path.clone(), contribution.mode.0.clone()))
            .or_default()
            .push(optimize);
    }
    let conflicted: BTreeSet<GroupKey> = groups
        .into_iter()
        .filter_map(|(key, candidates)| {
            let first = candidates.first()?;
            candidates
                .iter()
                .skip(1)
                .any(|candidate| {
                    candidate.evidence.lever != first.evidence.lever
                        || candidate.params.canonical_value() != first.params.canonical_value()
                })
                .then_some(key)
        })
        .collect();
    contributions
        .iter()
        .filter(|contribution| {
            contribution.optimize.as_ref().is_none_or(|optimize| {
                !conflicted.contains(&(optimize.layer_path.clone(), contribution.mode.0.clone()))
            })
        })
        .collect()
}

/** Select one directive in root-to-child path order and explain every overlap. */
fn select_optimize<'a>(
    contributions: &[&'a Contribution],
) -> (Option<&'a Contribution>, Vec<OptimizeCandidate>) {
    let mut candidates: Vec<&Contribution> = contributions
        .iter()
        .copied()
        .filter(|contribution| {
            contribution.verdict == Verdict::Optimize && contribution.optimize.is_some()
        })
        .collect();
    candidates.sort_by(|left, right| {
        candidate_path(left)
            .len()
            .cmp(&candidate_path(right).len())
            .then_with(|| candidate_path(left).cmp(candidate_path(right)))
            .then_with(|| artifact_id(left).cmp(artifact_id(right)))
    });
    let Some(selected) = candidates.first().copied() else {
        return (None, Vec::new());
    };
    let selected_path = candidate_path(selected).to_vec();
    let shadowed = candidates
        .into_iter()
        .skip(1)
        .filter_map(|candidate| {
            let optimize = candidate.optimize.as_ref()?;
            let mut evidence = optimize.evidence.clone();
            evidence.reason = if optimize.layer_path == selected_path {
                "same_layer_equivalent"
            } else {
                "parent_overlap"
            }
            .to_string();
            Some(evidence)
        })
        .collect();
    (Some(selected), shadowed)
}

fn selected_evidence(contribution: &Contribution) -> Option<OptimizeCandidate> {
    contribution
        .optimize
        .as_ref()
        .map(|optimize| optimize.evidence.clone())
}

fn candidate_path(contribution: &Contribution) -> &[String] {
    contribution
        .optimize
        .as_ref()
        .map(|candidate| candidate.layer_path.as_slice())
        .unwrap_or_default()
}

/// R10's legacy rewrite slot. Canonical artifact directives are selected but
/// never applied here; plan 03 retires this body projection at activation.
fn rewrite<'a>(enforcing: impl Iterator<Item = &'a Contribution>) -> Option<Rewrite> {
    enforcing
        .filter(|c| c.verdict == Verdict::Optimize && c.optimize.is_none())
        .find_map(|c| {
            c.lever.clone().map(|lever| Rewrite {
                lever,
                artifact_id: c.artifact_id.clone(),
                steer_instruction: c.steer_instruction.clone(),
            })
        })
}

fn artifact_id(contribution: &Contribution) -> &str {
    contribution.artifact_id.as_deref().unwrap_or("")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generated::types::{Lever, PolicyMode};
    use crate::zone_eval::facts::FactSet;
    use crate::zone_eval::types::{Classification, Event, MODE_ENFORCE, MODE_MONITOR};

    const NOW: i64 = 1_756_742_400_000;

    fn contribution(artifact_id: &str, mode: &str, verdict: Verdict) -> Contribution {
        Contribution {
            artifact_id: Some(artifact_id.to_string()),
            atom_id: Some(format!("atom-{artifact_id}")),
            policy_public_id: None,
            dimension: None,
            mode: PolicyMode(mode.to_string()),
            tier: Some(1),
            verdict,
            reason: artifact_id.to_string(),
            inconclusive: Vec::new(),
            anomalies: Vec::new(),
            hold: None,
            exception_ground_key: None,
            lever: None,
            steer_instruction: None,
            optimize: None,
            ask: None,
        }
    }

    fn decision(contributions: &[Contribution]) -> Decision {
        let event = Event::default();
        let classification = Classification::default();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        assemble(contributions, &ctx)
    }

    fn ask(artifact_id: &str, mode: &str, fallback: &str) -> Contribution {
        let mut c = contribution(artifact_id, MODE_ENFORCE, Verdict::Ask);
        c.ask = Some(AskPolicy {
            mode: mode.to_string(),
            fallback: fallback.to_string(),
        });
        c
    }

    fn decision_with(asks: &[Contribution], can_ask: bool) -> Decision {
        let event = Event {
            expressible: Some(if can_ask {
                vec!["allow".into(), "ask".into(), "deny".into()]
            } else {
                vec!["allow".into(), "deny".into()]
            }),
            ..Event::default()
        };
        let classification = Classification::default();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        assemble(asks, &ctx)
    }

    /// Which artifact decides when `asks` all fire on an action whose agent can, or
    /// cannot, prompt.
    fn decided_by(asks: &[Contribution], can_ask: bool) -> Option<String> {
        let event = Event {
            expressible: Some(if can_ask {
                vec!["allow".into(), "ask".into(), "deny".into()]
            } else {
                vec!["allow".into(), "deny".into()]
            }),
            ..Event::default()
        };
        let classification = Classification::default();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        assemble(asks, &ctx).artifact_id
    }

    /// D-11, spec §6.10: of several ASKs on one action the strictest delivery
    /// decides: the `block` fallback, then the prompt, then the `allow` fallback,
    /// then the artifact id — whatever the artifacts' order.
    #[test]
    fn several_asks_are_ranked_by_how_each_is_delivered() {
        // `z` is a platform/block ASK, so it beats the prompt of `a` and the allow
        // fallback of `b`, although its id sorts last.
        let asks = [
            ask("a", "agent", "allow"),
            ask("b", "platform", "allow"),
            ask("z", "platform", "block"),
        ];
        assert_eq!(decided_by(&asks, true).as_deref(), Some("z"));
        let mut reversed = asks.clone();
        reversed.reverse();
        assert_eq!(decided_by(&reversed, true).as_deref(), Some("z"));

        // Without the block fallback, the prompt beats the allow fallback.
        let asks = [ask("a", "platform", "allow"), ask("b", "agent", "allow")];
        assert_eq!(decided_by(&asks, true).as_deref(), Some("b"));

        // An agent that cannot prompt turns `agent` and `both` into their fallback,
        // so the same pair now ties on the allow fallback and the id decides ...
        assert_eq!(decided_by(&asks, false).as_deref(), Some("a"));
        // ... and an `agent`/`block` ASK becomes the strictest of all.
        let asks = [ask("a", "platform", "allow"), ask("b", "agent", "block")];
        assert_eq!(decided_by(&asks, false).as_deref(), Some("b"));
        assert_eq!(decided_by(&asks, true).as_deref(), Some("b"));
        let both = [ask("a", "both", "allow"), ask("b", "platform", "block")];
        assert_eq!(decided_by(&both, true).as_deref(), Some("b"));

        // The same strictness, tie and all: equal deliveries fall to the id.
        let tie = [ask("b", "both", "block"), ask("a", "platform", "block")];
        assert_eq!(decided_by(&tie, true).as_deref(), Some("a"));
    }

    /// §6.10: a fired hold keeps precedence over the mode, so an ASK whose
    /// fallback would let the action through never outranks it.
    #[test]
    fn a_fired_hold_is_never_outranked_by_a_weaker_ask() {
        let mut held = ask("z", "platform", "allow");
        held.hold = Some(crate::zone_eval::types::HoldRequest {
            resolve: Some("ask_human".to_string()),
            directive_template_id: None,
            max_attempts: None,
            timeout_s: None,
            on_timeout: None,
            verdict_on_approve: None,
            verdict_on_reject: None,
        });
        let asks = [ask("a", "agent", "allow"), held];
        let decision = decision_with(&asks, true);
        assert_eq!(decision.artifact_id.as_deref(), Some("z"));
        assert!(decision.hold.is_some());
    }

    /// A contribution with no ask policy (a bundle below contract v3) ties with the
    /// prompt that was always delivered, and the lattice still beats strictness.
    #[test]
    fn strictness_never_outranks_the_lattice_and_legacy_asks_are_unchanged() {
        let legacy = contribution("a", MODE_ENFORCE, Verdict::Ask);
        let asks = [
            legacy.clone(),
            contribution("b", MODE_ENFORCE, Verdict::Ask),
        ];
        assert_eq!(decided_by(&asks, true).as_deref(), Some("a"));
        let blocked = [
            ask("a", "platform", "block"),
            contribution("z", MODE_ENFORCE, Verdict::Block),
        ];
        assert_eq!(
            decided_by(&blocked, true).as_deref(),
            Some("z"),
            "a Block still decides over any ASK"
        );
    }

    /// An event that declares no `expressible` is not assumed to prompt.
    #[test]
    fn an_undeclared_event_is_not_assumed_to_prompt() {
        assert!(!event_can_ask(&Event::default()));
    }

    /// AC-82: the report carries each tuple's origins and the path it names.
    #[test]
    fn the_effect_report_names_origins_and_targets() {
        use crate::generated::types::{EffectVerb, TargetClass};
        use crate::zone_eval::types::{ClassifiedPath, ClassifiedUrl, Effect, UrlBoundary};
        let classification = Classification {
            effects: vec![
                Effect {
                    verb: EffectVerb("read".into()),
                    target_class: TargetClass("secret_material".into()),
                    attrs: Default::default(),
                },
                Effect {
                    verb: EffectVerb("network_egress".into()),
                    target_class: TargetClass("network_host".into()),
                    attrs: Default::default(),
                },
                Effect {
                    verb: EffectVerb("execute".into()),
                    target_class: TargetClass("shell".into()),
                    attrs: Default::default(),
                },
            ],
            paths: vec![ClassifiedPath {
                class: TargetClass("secret_material".into()),
                value: "~/.pgpass".into(),
            }],
            urls: vec![ClassifiedUrl {
                value: "https://example.org/x".into(),
                host: "example.org".into(),
                tld: "org".into(),
                scheme: "https".into(),
                boundary: UrlBoundary::External,
            }],
            ..Classification::default()
        };
        let report = effect_report(&classification);
        let targets: Vec<Option<&str>> = report.iter().map(|r| r.target.as_deref()).collect();
        assert_eq!(targets, [Some("~/.pgpass"), Some("example.org"), None]);
        assert!(
            report.iter().all(|r| r.origin.is_empty()),
            "code rows name no entry"
        );
    }

    #[test]
    fn the_lattice_is_block_over_ask_over_optimize_over_allow() {
        assert!(rank(&Verdict::Block) > rank(&Verdict::Ask));
        assert!(rank(&Verdict::Ask) > rank(&Verdict::Optimize));
        assert!(rank(&Verdict::Optimize) > rank(&Verdict::Allow));
    }

    #[test]
    fn monitor_never_joins() {
        // The invariant, in one assertion. A monitor artifact holding the
        // highest verdict in the bundle still contributes nothing to `verdict`.
        let decision = decision(&[
            contribution("m", MODE_MONITOR, Verdict::Block),
            contribution("e", MODE_ENFORCE, Verdict::Allow),
        ]);
        assert_eq!(decision.verdict, Verdict::Allow);
        assert_eq!(decision.artifact_id.as_deref(), Some("e"));
        assert_eq!(decision.would_have_verdict, Some(Verdict::Block));
        assert!(
            !decision.undecided,
            "it was not silent, it just did not decide"
        );
    }

    #[test]
    fn an_all_monitor_ask_or_block_keeps_its_shadow_record_source() {
        for verdict in [Verdict::Ask, Verdict::Block] {
            let decision = decision(&[contribution("m", MODE_MONITOR, verdict)]);
            assert_eq!(decision.verdict, Verdict::Allow);
            assert_eq!(decision.artifact_id.as_deref(), Some("m"));
            assert_eq!(decision.atom_id.as_deref(), Some("atom-m"));
            assert_eq!(
                decision.mode.as_ref().map(|mode| mode.0.as_str()),
                Some(MODE_MONITOR)
            );
            assert_eq!(decision.tier, Some(1));
            assert_eq!(decision.reason, "m");
            assert_eq!(decision.would_have_verdict, Some(verdict));
            assert!(!decision.undecided);
        }
    }

    #[test]
    fn an_all_monitor_allow_still_names_nobody() {
        let decision = decision(&[contribution("m", MODE_MONITOR, Verdict::Allow)]);
        assert_eq!(decision.verdict, Verdict::Allow);
        assert_eq!(decision.artifact_id, None);
        assert_eq!(decision.mode, None);
        assert_eq!(decision.would_have_verdict, Some(Verdict::Allow));
        assert!(!decision.undecided);
    }

    #[test]
    fn nothing_at_all_is_undecided_and_an_allow_is_not() {
        assert!(decision(&[]).undecided);
        assert!(
            !decision(&[contribution("a", MODE_ENFORCE, Verdict::Allow)]).undecided,
            "an artifact may allow on purpose"
        );
    }

    #[test]
    fn a_tie_breaks_on_artifact_id_and_not_on_iteration_order() {
        let forward = decision(&[
            contribution("a", MODE_ENFORCE, Verdict::Block),
            contribution("b", MODE_ENFORCE, Verdict::Block),
        ]);
        let reversed = decision(&[
            contribution("b", MODE_ENFORCE, Verdict::Block),
            contribution("a", MODE_ENFORCE, Verdict::Block),
        ]);
        assert_eq!(forward.artifact_id.as_deref(), Some("a"));
        assert_eq!(forward, reversed, "a replay names the same rule");
    }

    #[test]
    fn r10_gives_the_single_rewrite_to_the_first_enforcing_optimize_with_a_lever() {
        let mut without = contribution("a-no-lever", MODE_ENFORCE, Verdict::Optimize);
        without.lever = None;
        let mut first = contribution("b-steer", MODE_ENFORCE, Verdict::Optimize);
        first.lever = Some(Lever("steer".to_string()));
        first.steer_instruction = Some("push a branch instead".to_string());
        let mut second = contribution("c-clamp", MODE_ENFORCE, Verdict::Optimize);
        second.lever = Some(Lever("effort_clamp".to_string()));

        let rewrite = decision(&[without, first, second])
            .rewrite
            .expect("the first lever-bearing optimize owns it");
        assert_eq!(rewrite.lever.0, "steer");
        assert_eq!(rewrite.artifact_id.as_deref(), Some("b-steer"));
        assert_eq!(
            rewrite.steer_instruction.as_deref(),
            Some("push a branch instead")
        );
    }

    #[test]
    fn a_monitor_artifact_never_spends_r10s_single_slot() {
        // Folding the rewrite over ALL contributions sent a steer instruction to
        // the agent with the org-wide kill switch off, and let a monitor
        // artifact spend the slot the artifact that actually decided needed.
        let mut monitored = contribution("a-monitor", MODE_MONITOR, Verdict::Optimize);
        monitored.lever = Some(Lever("effort_clamp".to_string()));
        let mut enforced = contribution("b-steer", MODE_ENFORCE, Verdict::Optimize);
        enforced.lever = Some(Lever("steer".to_string()));

        let rewrite = decision(&[monitored.clone(), enforced])
            .rewrite
            .expect("the enforcing one owns it");
        assert_eq!(rewrite.artifact_id.as_deref(), Some("b-steer"));
        assert_eq!(
            decision(&[monitored]).rewrite,
            None,
            "a monitor-only bundle applies nothing to the agent"
        );
    }

    #[test]
    fn the_hold_and_the_ground_key_come_from_the_artifact_that_decided() {
        let mut monitored = contribution("a-monitor", MODE_MONITOR, Verdict::Block);
        monitored.exception_ground_key = Some("m".repeat(64));
        let mut enforced = contribution("b-enforce", MODE_ENFORCE, Verdict::Ask);
        enforced.exception_ground_key = Some("e".repeat(64));

        let decision = decision(&[monitored, enforced]);
        assert_eq!(decision.ground_key, Some("e".repeat(64)));
        assert_eq!(decision.hold, None);
    }

    #[test]
    fn inconclusive_facts_are_sorted_deduplicated_and_gathered_from_every_artifact() {
        let mut monitored = contribution("a", MODE_MONITOR, Verdict::Allow);
        monitored.inconclusive = vec!["change_ticket".to_string(), "approved_domains".to_string()];
        let mut enforced = contribution("b", MODE_ENFORCE, Verdict::Allow);
        enforced.inconclusive = vec!["change_ticket".to_string()];

        assert_eq!(
            decision(&[monitored, enforced]).inconclusive_facts,
            vec!["approved_domains".to_string(), "change_ticket".to_string()],
            "a monitor artifact that could not read a fact still found the gap"
        );
    }

    #[test]
    fn anomalies_record_from_every_artifact_and_carry_their_own_provenance() {
        let mut monitored = contribution("a", MODE_MONITOR, Verdict::Allow);
        monitored.anomalies = vec!["burst".to_string()];
        let anomalies = decision(&[monitored]).anomalies;
        assert_eq!(anomalies.len(), 1);
        assert_eq!(anomalies[0].code, "burst");
        assert_eq!(anomalies[0].artifact_id.as_deref(), Some("a"));
        assert_eq!(anomalies[0].atom_id.as_deref(), Some("atom-a"));
    }
}