openlatch-client 0.5.4

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
//! 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::types::{
    Anomaly, Contribution, Decision, EvalContext, OptimizeCandidate, OptimizeContext, 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,
    }
}

/// The highest-ranked contribution, or `None` when the slice is empty.
///
/// **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]) -> Option<&Contribution> {
    best(contributions.iter())
}

/// [`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>) -> Option<&'a Contribution> {
    contributions.min_by(|left, right| {
        rank(&right.verdict)
            .cmp(&rank(&left.verdict))
            .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 joined = best(enforcing.iter().copied());
    // 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());
    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(),
        // 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(),
    }
}

/** 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,
        }
    }

    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)
    }

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