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
//! Bounded tool-dispatch actuators for selected schema-2 Optimize directives.
//!
//! The evaluator remains pure. This module owns adapter capability checks,
//! one possible tool-input change, final-input re-evaluation, and the small
//! hashed session history required by loop/steer delivery.

use std::path::Path;
use std::time::{Duration, Instant};

use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::daemon::session_state::DispatchStateManager;
use crate::generated::types::Verdict;
use crate::zone_eval::types::OptimizeParams;
use crate::zone_eval::{Bundle, Decision, Event, SessionState};

#[derive(Clone, Debug, Default)]
pub struct Delivery {
    pub updated_input: Option<Map<String, Value>>,
    pub additional_context: Option<String>,
    pub system_message: Option<String>,
    pub enforced: Option<bool>,
    pub result: Option<&'static str>,
    pub second_optimize_degraded: bool,
}

#[derive(Clone, Debug)]
pub struct Outcome {
    pub decision: Decision,
    pub state_to_commit: SessionState,
    pub delivery: Delivery,
}

/// Evaluate once against an immutable prior snapshot, apply at most one
/// selected directive, and evaluate a changed input once more against that same
/// snapshot. The caller commits `state_to_commit` exactly once.
#[allow(clippy::too_many_arguments)]
pub fn evaluate_and_dispatch(
    bundle: &Bundle,
    event: &Event,
    source: &str,
    dispatch_sessions: &DispatchStateManager,
    output_dir: &Path,
    prior: Option<&SessionState>,
    now: Instant,
    now_ms: i64,
) -> Outcome {
    let (mut initial, initial_state) = crate::zone_eval::evaluate(bundle, event, prior, now_ms);
    let mut delivery = Delivery::default();

    observe_completion(dispatch_sessions, event, now);
    if event.event_type == "post_tool_use" {
        delivery.additional_context = take_output_context(dispatch_sessions, event, now, source);
    }
    if matches!(event.event_type.as_str(), "stop" | "subagent_stop") {
        delivery.system_message = take_stop_reason(dispatch_sessions, event, now, source);
    }

    // The evaluator retains Optimize candidates as evidence even when a Block
    // or Ask contribution wins the verdict lattice. Those candidates are not
    // actionable: dispatching one here could overwrite the stricter verdict.
    if matches!(initial.verdict, Verdict::Block | Verdict::Ask) {
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    }

    let selected = initial
        .optimize
        .as_ref()
        .and_then(|context| context.actual.as_ref().or(context.monitor.as_ref()));
    let Some(selected) = selected else {
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    };
    let directive = selected
        .artifact_id
        .as_deref()
        .and_then(|id| {
            bundle
                .artifacts
                .iter()
                .find(|artifact| artifact.artifact_id() == Some(id))
        })
        .and_then(|artifact| artifact.optimize.as_ref());
    let Some(directive) = directive else {
        mark_selected_reason(&mut initial, "incapable");
        initial.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    };

    let monitor_only = initial
        .optimize
        .as_ref()
        .is_some_and(|context| context.actual.is_none() && context.monitor.is_some());
    if monitor_only {
        monitor(
            directive.params.clone(),
            event,
            dispatch_sessions,
            now,
            &mut initial,
            &mut delivery,
        );
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    }

    match &directive.params {
        OptimizeParams::LoopStop(params) => {
            apply_loop_stop(
                params,
                event,
                source,
                dispatch_sessions,
                now,
                &mut initial,
                &mut delivery,
            );
            Outcome {
                decision: initial,
                state_to_commit: initial_state,
                delivery,
            }
        }
        OptimizeParams::Steer(params) => {
            apply_steer(
                params,
                event,
                source,
                dispatch_sessions,
                now,
                &mut initial,
                &mut delivery,
            );
            Outcome {
                decision: initial,
                state_to_commit: initial_state,
                delivery,
            }
        }
        OptimizeParams::NarrowOutput(params) => apply_narrow_output(
            params,
            bundle,
            event,
            source,
            dispatch_sessions,
            output_dir,
            prior,
            now,
            now_ms,
            initial,
            initial_state,
            delivery,
        ),
        OptimizeParams::Substitute(_) => {
            mark_selected_reason(&mut initial, "incapable");
            initial.verdict = Verdict::Allow;
            delivery.enforced = Some(false);
            delivery.result = Some("skipped_invalid");
            Outcome {
                decision: initial,
                state_to_commit: initial_state,
                delivery,
            }
        }
        _ => {
            mark_selected_reason(&mut initial, "incapable");
            initial.verdict = Verdict::Allow;
            delivery.enforced = Some(false);
            delivery.result = Some("flagged");
            Outcome {
                decision: initial,
                state_to_commit: initial_state,
                delivery,
            }
        }
    }
}

fn monitor(
    params: OptimizeParams,
    event: &Event,
    sessions: &DispatchStateManager,
    now: Instant,
    decision: &mut Decision,
    delivery: &mut Delivery,
) {
    delivery.enforced = Some(false);
    match params {
        OptimizeParams::LoopStop(params) => {
            if loop_stop_trigger(&params, event, sessions, now) {
                decision.would_have_verdict = Some(Verdict::Ask);
                delivery.result = Some("flagged");
            } else {
                decision.would_have_verdict = None;
                delivery.result = Some("allowed");
            }
        }
        OptimizeParams::Substitute(params) => {
            delivery.result = Some(if substitute_pair(&params, event).is_some() {
                "flagged"
            } else {
                "skipped_invalid"
            });
        }
        _ => delivery.result = Some("flagged"),
    }
    decision.verdict = Verdict::Allow;
}

fn apply_loop_stop(
    params: &Map<String, Value>,
    event: &Event,
    source: &str,
    sessions: &DispatchStateManager,
    now: Instant,
    decision: &mut Decision,
    delivery: &mut Delivery,
) {
    if event.event_type != "pre_tool_use" || !matches!(source, "claude-code" | "codex-cli") {
        mark_selected_reason(decision, "incapable");
        decision.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return;
    }
    if loop_stop_trigger(params, event, sessions, now) {
        decision.verdict = Verdict::Block;
        decision.reason = "OpenLatch stopped a repeated tool loop.".into();
        delivery.enforced = Some(true);
        delivery.result = Some("blocked");
    } else {
        decision.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("allowed");
    }
}

fn loop_stop_trigger(
    params: &Map<String, Value>,
    event: &Event,
    sessions: &DispatchStateManager,
    now: Instant,
) -> bool {
    if event.event_type != "pre_tool_use" || exempt_loop(params, event) {
        return false;
    }
    let action_key = action_key(event);
    let n_errors = params.get("n_errors").and_then(Value::as_u64).unwrap_or(3);
    let n_identical = params
        .get("n_identical")
        .and_then(Value::as_u64)
        .unwrap_or(4);
    sessions.with_session(&event.session_id, now, |state| {
        state.last_action_key.as_deref() == Some(action_key.as_str())
            && ((state.last_result_was_error
                && state.identical_error_completions.saturating_add(1) >= n_errors)
                || state.identical_completions.saturating_add(1) >= n_identical)
    })
}

fn apply_steer(
    params: &Map<String, Value>,
    event: &Event,
    source: &str,
    sessions: &DispatchStateManager,
    now: Instant,
    decision: &mut Decision,
    delivery: &mut Delivery,
) {
    if event.event_type != "pre_tool_use" || !matches!(source, "claude-code" | "codex-cli") {
        mark_selected_reason(decision, "incapable");
        decision.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return;
    }
    let instruction = params
        .get("steer_instruction")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let window = Duration::from_secs(
        params
            .get("dedupe_window_s")
            .and_then(Value::as_u64)
            .unwrap_or(0),
    );
    let key = action_key(event);
    let duplicate = sessions.with_session(&event.session_id, now, |state| {
        let duplicate = state.last_steer_key.as_deref() == Some(key.as_str())
            && state
                .last_steer_at
                .is_some_and(|at| now.saturating_duration_since(at) <= window);
        if !duplicate {
            state.last_steer_key = Some(key);
            state.last_steer_at = Some(now);
            if source == "claude-code" {
                state.pending_stop_reason = Some(instruction.to_string());
                state.remaining_stop_blocks = 1;
            }
        }
        duplicate
    });
    if duplicate || instruction.trim().is_empty() {
        mark_selected_reason(decision, "guarded");
        decision.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return;
    }
    decision.verdict = Verdict::Block;
    decision.reason = instruction.to_string();
    delivery.enforced = Some(true);
    delivery.result = Some("steered");
}

#[allow(clippy::too_many_arguments)]
fn apply_narrow_output(
    params: &Map<String, Value>,
    bundle: &Bundle,
    event: &Event,
    source: &str,
    dispatch_sessions: &DispatchStateManager,
    output_dir: &Path,
    prior: Option<&SessionState>,
    now: Instant,
    now_ms: i64,
    mut initial: Decision,
    initial_state: SessionState,
    mut delivery: Delivery,
) -> Outcome {
    let Some((command, filter)) = narrow_match(params, event) else {
        mark_selected_reason(&mut initial, "guarded");
        initial.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    };
    if source != "claude-code" || event.event_type != "pre_tool_use" {
        mark_selected_reason(&mut initial, "incapable");
        initial.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    }
    let path = output_dir.join(format!(
        "tool-output-{}.log",
        short_hash(&event.tool_use_id)
    ));
    let Some(wrapped) = wrap_command(command, filter, &path) else {
        mark_selected_reason(&mut initial, "guarded");
        initial.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return Outcome {
            decision: initial,
            state_to_commit: initial_state,
            delivery,
        };
    };
    let mut updated = match event.tool_input.as_object() {
        Some(input) => input.clone(),
        None => {
            mark_selected_reason(&mut initial, "guarded");
            initial.verdict = Verdict::Allow;
            delivery.enforced = Some(false);
            delivery.result = Some("flagged");
            return Outcome {
                decision: initial,
                state_to_commit: initial_state,
                delivery,
            };
        }
    };
    updated.insert("command".into(), Value::String(wrapped));
    let mut final_event = event.clone();
    final_event.tool_input = Value::Object(updated.clone());
    let (mut final_decision, final_state) =
        crate::zone_eval::evaluate(bundle, &final_event, prior, now_ms);
    let initial_optimize = initial.optimize.take();
    let selected_id = initial_optimize
        .as_ref()
        .and_then(|ctx| ctx.actual.as_ref())
        .and_then(|candidate| candidate.artifact_id.as_deref());
    let final_id = final_decision
        .optimize
        .as_ref()
        .and_then(|ctx| ctx.actual.as_ref())
        .and_then(|candidate| candidate.artifact_id.as_deref());
    if final_decision.verdict == Verdict::Optimize && final_id != selected_id {
        final_decision.verdict = Verdict::Ask;
        delivery.second_optimize_degraded = true;
    }
    final_decision.optimize = initial_optimize;
    if matches!(final_decision.verdict, Verdict::Block | Verdict::Ask) {
        if final_decision.verdict == Verdict::Block {
            delivery.enforced = Some(true);
            delivery.result = Some("blocked");
        } else {
            delivery.enforced = Some(false);
            delivery.result = Some("flagged");
        }
        return Outcome {
            decision: final_decision,
            state_to_commit: final_state,
            delivery,
        };
    }
    retain_record_identity(&initial, &mut final_decision);
    final_decision.verdict = Verdict::Optimize;
    let reserved = dispatch_sessions.with_session(&event.session_id, now, |state| {
        if state.pending_output_paths.len() >= 32
            && !state.pending_output_paths.contains_key(&event.tool_use_id)
        {
            return false;
        }
        state.pending_output_paths.insert(
            event.tool_use_id.clone(),
            path.to_string_lossy().into_owned(),
        );
        true
    });
    if !reserved {
        mark_selected_reason(&mut final_decision, "guarded");
        final_decision.verdict = Verdict::Allow;
        delivery.enforced = Some(false);
        delivery.result = Some("flagged");
        return Outcome {
            decision: final_decision,
            state_to_commit: initial_state,
            delivery,
        };
    }
    delivery.updated_input = Some(updated);
    delivery.enforced = Some(true);
    delivery.result = Some("rewritten");
    Outcome {
        decision: final_decision,
        state_to_commit: final_state,
        delivery,
    }
}

fn narrow_match<'a>(
    params: &'a Map<String, Value>,
    event: &'a Event,
) -> Option<(&'a str, &'a str)> {
    if event.tool_name != "Bash" {
        return None;
    }
    let command = event.tool_input.get("command")?.as_str()?;
    let entries = params.get("allowlist")?.as_array()?;
    entries.iter().find_map(|entry| {
        let prefix = entry.get("command_prefix")?.as_str()?;
        let filter = entry.get("filter")?.as_str()?;
        if prefix.trim().is_empty()
            || filter.trim().is_empty()
            || !simple_diagnostic_shape(command)
            || !simple_diagnostic_shape(filter)
        {
            return None;
        }
        (command == prefix
            || command
                .strip_prefix(prefix)
                .is_some_and(|tail| tail.starts_with(char::is_whitespace)))
        .then_some((command, filter))
    })
}

fn substitute_pair<'a>(
    params: &'a Map<String, Value>,
    event: &Event,
) -> Option<(&'a str, &'a str)> {
    let command = event.tool_input.get("command")?.as_str()?;
    params.get("pairs")?.as_array()?.iter().find_map(|pair| {
        let from = pair.get("from")?.as_str()?;
        let to = pair.get("to")?.as_str()?;
        if from.trim().is_empty() || to.trim().is_empty() {
            return None;
        }
        command
            .split_whitespace()
            .next()
            .is_some_and(|tool| tool == from)
            .then_some((from, to))
    })
}

fn exempt_loop(params: &Map<String, Value>, event: &Event) -> bool {
    let Some(command) = event.tool_input.get("command").and_then(Value::as_str) else {
        return false;
    };
    let normalized = crate::core::policy::normalize(command);
    let program = normalized.split_whitespace().next().unwrap_or_default();
    if matches!(program, "sleep" | "wait" | "poll") {
        return true;
    }
    params
        .get("exempt_patterns")
        .and_then(Value::as_array)
        .is_some_and(|patterns| {
            patterns
                .iter()
                .filter_map(Value::as_str)
                .any(|pattern| crate::core::policy::matches(pattern, &normalized))
        })
}

fn observe_completion(sessions: &DispatchStateManager, event: &Event, now: Instant) {
    if !matches!(
        event.event_type.as_str(),
        "post_tool_use" | "post_tool_use_failure"
    ) {
        return;
    }
    let Some(result) = event.tool_result.as_ref() else {
        return;
    };
    let action = action_key(event);
    let result_hash = hash_value(result);
    let completed = format!("{action}:{result_hash}");
    let error = result_is_error(result);
    sessions.with_session(&event.session_id, now, |state| {
        if !event.tool_use_id.is_empty() {
            if state
                .seen_completion_ids
                .iter()
                .any(|id| id == &event.tool_use_id)
            {
                return;
            }
            state
                .seen_completion_ids
                .push_back(event.tool_use_id.clone());
            while state.seen_completion_ids.len() > 64 {
                state.seen_completion_ids.pop_front();
            }
        }
        if state.last_completed_key.as_deref() == Some(completed.as_str()) {
            state.identical_completions = state.identical_completions.saturating_add(1);
        } else {
            state.identical_completions = 1;
        }
        if error
            && state.last_action_key.as_deref() == Some(action.as_str())
            && state.last_result_hash.as_deref() == Some(result_hash.as_str())
            && state.last_result_was_error
        {
            state.identical_error_completions = state.identical_error_completions.saturating_add(1);
        } else {
            state.identical_error_completions = u64::from(error);
        }
        state.last_completed_key = Some(completed);
        state.last_action_key = Some(action);
        state.last_result_hash = Some(result_hash);
        state.last_result_was_error = error;
    });
}

fn result_is_error(result: &Value) -> bool {
    result.get("is_error").and_then(Value::as_bool) == Some(true)
        || result
            .get("exit_code")
            .and_then(Value::as_i64)
            .is_some_and(|code| code != 0)
        || result.get("error").is_some_and(|error| !error.is_null())
}

fn action_key(event: &Event) -> String {
    let mut input = event.tool_input.clone();
    if event.tool_name == "Bash" {
        if let Some(command) = input.get_mut("command") {
            if let Some(raw) = command.as_str() {
                *command = Value::String(crate::core::policy::normalize(raw));
            }
        }
    }
    hash_value(&serde_json::json!({"tool": event.tool_name, "input": input}))
}

fn hash_value(value: &Value) -> String {
    let canonical = serde_json_canonicalizer::to_string(value).unwrap_or_default();
    let digest = Sha256::digest(canonical.as_bytes());
    hex::encode(digest)
}

fn short_hash(value: &str) -> String {
    hash_value(&Value::String(value.to_string()))[..16].to_string()
}

fn wrap_command(command: &str, filter: &str, path: &Path) -> Option<String> {
    #[cfg(windows)]
    {
        let _ = (command, filter, path);
        None
    }
    #[cfg(not(windows))]
    {
        let escaped = path.to_string_lossy().replace('\'', "'\\''");
        Some(format!(
            ": > '{escaped}'; {{ {command}; }} > >(tee -a '{escaped}' | {{ {filter}; }}) 2> >(tee -a '{escaped}' >&2); __ol_status=$?; wait; exit \"$__ol_status\""
        ))
    }
}

fn take_output_context(
    sessions: &DispatchStateManager,
    event: &Event,
    now: Instant,
    source: &str,
) -> Option<String> {
    if source != "claude-code" || event.tool_use_id.is_empty() {
        return None;
    }
    sessions.with_session(&event.session_id, now, |state| {
        state
            .pending_output_paths
            .remove(&event.tool_use_id)
            .map(|path| format!("Full command output is available at {path}"))
    })
}

fn take_stop_reason(
    sessions: &DispatchStateManager,
    event: &Event,
    now: Instant,
    source: &str,
) -> Option<String> {
    (source == "claude-code").then(|| {
        sessions.with_session(&event.session_id, now, |state| {
            if state.remaining_stop_blocks == 0 {
                state.pending_stop_reason = None;
                return None;
            }
            state.remaining_stop_blocks -= 1;
            let reason = state.pending_stop_reason.clone();
            if state.remaining_stop_blocks == 0 {
                state.pending_stop_reason = None;
            }
            reason
        })
    })?
}

fn simple_diagnostic_shape(command: &str) -> bool {
    let trimmed = command.trim();
    !trimmed.is_empty()
        && !trimmed.contains(['\n', '\r', ';', '|', '&', '>', '<', '`', '#'])
        && !trimmed.contains("$(")
        && !trimmed.contains("${")
}

fn retain_record_identity(initial: &Decision, final_decision: &mut Decision) {
    final_decision.artifact_id = initial.artifact_id.clone();
    final_decision.atom_id = initial.atom_id.clone();
    final_decision.policy_public_id = initial.policy_public_id.clone();
    final_decision.dimension = initial.dimension.clone();
    final_decision.mode = initial.mode.clone();
    final_decision.tier = initial.tier;
    final_decision.reason.clone_from(&initial.reason);
    final_decision.undecided = false;
}

fn mark_selected_reason(decision: &mut Decision, reason: &str) {
    let Some(context) = decision.optimize.as_mut() else {
        return;
    };
    if let Some(candidate) = context.actual.as_mut().or(context.monitor.as_mut()) {
        candidate.reason = reason.to_string();
    }
}

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

    #[test]
    fn result_error_detection_is_explicit() {
        assert!(result_is_error(&serde_json::json!({"exit_code": 1})));
        assert!(result_is_error(&serde_json::json!({"is_error": true})));
        assert!(!result_is_error(&serde_json::json!({"exit_code": 0})));
    }

    #[test]
    fn narrow_prefix_requires_a_token_boundary() {
        let params =
            serde_json::json!({"allowlist":[{"command_prefix":"cargo test","filter":"tail -100"}]});
        let mut event = Event {
            tool_name: "Bash".into(),
            tool_input: serde_json::json!({"command":"cargo tester"}),
            ..Event::default()
        };
        assert!(narrow_match(params.as_object().unwrap(), &event).is_none());
        event.tool_input = serde_json::json!({"command":"cargo test --lib"});
        assert!(narrow_match(params.as_object().unwrap(), &event).is_some());
        event.tool_input = serde_json::json!({"command":"cargo test ; echo unsafe"});
        assert!(narrow_match(params.as_object().unwrap(), &event).is_none());
    }

    #[cfg(unix)]
    #[test]
    fn narrow_wrapper_preserves_output_and_the_original_exit_status() {
        use std::process::Command;

        let dir = tempfile::tempdir().expect("temporary output directory");
        let path = dir.path().join("full.log");
        let wrapped = wrap_command(
            "printf 'full-output\\n'; printf 'full-error\\n' >&2; false",
            "tail -1",
            &path,
        )
        .expect("Unix Bash wrapper");
        // The actuator rejects compound authored commands before this helper;
        // this direct probe deliberately exercises status propagation itself.
        let output = Command::new("bash")
            .args(["-c", &wrapped])
            .output()
            .expect("run Bash wrapper");
        assert_eq!(output.status.code(), Some(1));
        assert_eq!(String::from_utf8_lossy(&output.stdout), "full-output\n");
        assert_eq!(String::from_utf8_lossy(&output.stderr), "full-error\n");
        let full = std::fs::read_to_string(path).unwrap();
        assert!(full.contains("full-output\n"), "{full:?}");
        assert!(full.contains("full-error\n"), "{full:?}");
    }
}