openlatch-client 0.1.6

The open-source security layer for AI agents — client forwarder
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
pub mod heal;
pub mod request;

use std::path::{Path, PathBuf};

use tokio::sync::mpsc;

use crate::cloud::tamper::{FieldDelta, TamperCloudEventKind, TamperEvent};
use crate::cloud::CloudEvent;
use crate::core::hook_state::diff::diff_entry_fields;
use crate::core::hook_state::hmac::verify_entry_hmac;
use crate::core::hook_state::key::HmacKeyStore;
use crate::core::hook_state::marker::{classify_marker, MarkerShape};
use crate::core::hook_state::{hash_settings_path, HookStateFile, StateEntry};
use crate::core::logging::tamper_log::TamperLogger;
use crate::core::telemetry::{self, Event};
use crate::hooks::jsonc;

use heal::HealManager;
use request::ReconcileRequest;

/// The canonical agent type string for the current build. Kept as a constant
/// so detection events and heal events always agree on wire format.
const AGENT_TYPE: &str = "claude-code";

/// The OS string stamped on tamper CloudEvents. Matches the same vocabulary
/// used for hook CloudEvents (`linux` / `macos` / `windows`) so the platform
/// can aggregate across both channels.
fn current_os() -> &'static str {
    if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(target_os = "windows") {
        "windows"
    } else {
        "linux"
    }
}

/// Shared sinks the reconciler uses to publish tamper-detection events.
///
/// Grouped into a single struct so construction sites can pass `None` when
/// running outside a full daemon (e.g. `run_startup_reconcile`). Each field
/// is independently optional: telemetry may be off while local JSONL and
/// cloud forwarding are on, etc.
#[derive(Clone, Default)]
pub struct TamperSinks {
    pub logger: Option<TamperLogger>,
    pub cloud_tx: Option<mpsc::Sender<CloudEvent>>,
    pub agent_id: String,
    pub client_version: String,
}

/// Result of checking a single tracked hook entry against its recorded
/// HMAC. The `Drifted` variant names *why* so callers can route, heal, and
/// report without re-deriving the reason.
#[derive(Debug, Clone)]
enum DriftOutcome {
    Healthy,
    Drifted {
        method: &'static str,
        deltas: Vec<FieldDelta>,
    },
}

pub struct Reconciler {
    rx: mpsc::Receiver<ReconcileRequest>,
    settings_path: PathBuf,
    openlatch_dir: PathBuf,
    port: u16,
    token_file_path: PathBuf,
    heal_manager: HealManager,
    sinks: TamperSinks,
}

impl Reconciler {
    pub fn new(
        rx: mpsc::Receiver<ReconcileRequest>,
        settings_path: PathBuf,
        openlatch_dir: PathBuf,
        port: u16,
        token_file_path: PathBuf,
    ) -> Self {
        Self::new_with_sinks(
            rx,
            settings_path,
            openlatch_dir,
            port,
            token_file_path,
            TamperSinks::default(),
        )
    }

    pub fn new_with_sinks(
        rx: mpsc::Receiver<ReconcileRequest>,
        settings_path: PathBuf,
        openlatch_dir: PathBuf,
        port: u16,
        token_file_path: PathBuf,
        sinks: TamperSinks,
    ) -> Self {
        Self {
            rx,
            settings_path,
            openlatch_dir,
            port,
            token_file_path,
            heal_manager: HealManager::new(),
            sinks,
        }
    }

    pub async fn run(mut self) {
        tracing::info!("reconciler started");

        while let Some(req) = self.rx.recv().await {
            match req {
                ReconcileRequest::Shutdown => {
                    tracing::info!("reconciler shutting down");
                    break;
                }
                ReconcileRequest::Fs | ReconcileRequest::Poll => {
                    self.reconcile().await;
                }
            }
        }
    }

    pub fn reconcile_sync(&mut self) {
        let rt = tokio::runtime::Handle::try_current();
        if rt.is_ok() {
            self.do_reconcile();
        }
    }

    async fn reconcile(&mut self) {
        self.do_reconcile();
    }

    fn do_reconcile(&mut self) {
        let raw = match std::fs::read_to_string(&self.settings_path) {
            Ok(c) => c,
            Err(e) => {
                tracing::debug!(error = %e, "reconciler: cannot read settings.json");
                return;
            }
        };

        let state = match HookStateFile::load(&self.openlatch_dir) {
            Ok(Some(s)) => s,
            Ok(None) => {
                tracing::debug!("reconciler: no state file yet, skipping verification");
                return;
            }
            Err(e) => {
                tracing::warn!(error = %e, "reconciler: cannot load state file");
                return;
            }
        };

        let hmac_key = match HmacKeyStore::new(&self.openlatch_dir).load_or_create() {
            Ok(k) => k,
            Err(e) => {
                tracing::warn!(error = %e, "reconciler: cannot load HMAC key");
                return;
            }
        };

        let parsed = match jsonc::parse_settings_value(&raw) {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(error = %e, "reconciler: cannot parse settings.json");
                return;
            }
        };

        let hooks_obj = match parsed.get("hooks").and_then(|h| h.as_object()) {
            Some(h) => h,
            None => {
                if !state.entries.is_empty() {
                    tracing::warn!(
                        "reconciler: hooks object missing from settings.json — will heal"
                    );
                    let _ = self.try_heal();
                }
                return;
            }
        };

        let settings_path_hash = hash_settings_path(&self.settings_path);

        // Phase 1: detect and emit tamper_detected events. Hold onto them so
        // the healed follow-up can carry matching metadata + related_event_id.
        let mut pending_detections: Vec<(StateEntry, TamperEvent)> = Vec::new();
        let mut drift_results: Vec<(String, bool)> = Vec::new();

        for state_entry in &state.entries {
            if self.heal_manager.tracker(&state_entry.id).is_circuit_open() {
                drift_results.push((state_entry.id.clone(), false));
                continue;
            }

            let outcome = check_entry_drift(
                &state_entry.hook_event,
                &state_entry.id,
                hooks_obj,
                &hmac_key,
                self.port,
            );

            let drifted = matches!(outcome, DriftOutcome::Drifted { .. });
            drift_results.push((state_entry.id.clone(), drifted));

            if let DriftOutcome::Drifted { method, deltas } = outcome {
                let event = TamperEvent::new(
                    state_entry.id.clone(),
                    AGENT_TYPE.to_string(),
                    settings_path_hash.clone(),
                    state_entry.hook_event.clone(),
                    method.to_string(),
                )
                .with_field_deltas(deltas);

                self.publish_detected(&event);
                pending_detections.push((state_entry.clone(), event));
            }
        }

        // Phase 2: heal and emit tamper_healed events per pending detection.
        let mut any_drift = false;
        for (entry_id, drifted) in &drift_results {
            let tracker = self.heal_manager.tracker(entry_id);
            if *drifted {
                tracker.mark_drifted();
                any_drift = true;
            } else {
                tracker.mark_healthy();
            }
        }

        if any_drift {
            for (entry_id, _) in &drift_results {
                let tracker = self.heal_manager.tracker(entry_id);
                if tracker.should_heal() {
                    tracker.record_heal_attempt();
                }
            }

            let heal_ok = self.try_heal().is_ok();

            for (entry_id, _) in &drift_results {
                let tracker = self.heal_manager.tracker(entry_id);
                if matches!(tracker.state, heal::HealState::Healing) {
                    if heal_ok {
                        tracker.record_heal_success();
                    } else {
                        tracker.record_heal_failure();
                    }
                }
            }

            for (state_entry, detected) in &pending_detections {
                let tracker = self.heal_manager.tracker(&state_entry.id);
                let (outcome_str, circuit_str) = heal_outcome_strings(tracker, heal_ok);
                let healed =
                    TamperEvent::new_healed(detected, outcome_str, tracker.attempt, circuit_str);
                self.publish_healed(&state_entry.hook_event, &healed);
            }
        }
    }

    fn publish_detected(&self, event: &TamperEvent) {
        if let Some(logger) = &self.sinks.logger {
            logger.log(event.clone());
        }
        if let Some(tx) = &self.sinks.cloud_tx {
            let ce = event.to_cloud_event(
                &self.sinks.agent_id,
                &self.sinks.client_version,
                current_os(),
                TamperCloudEventKind::Detected,
            );
            let _ = tx.try_send(ce);
        }
        telemetry::capture_global(Event::tamper_detected(
            &event.tamper.detection_method,
            &event.tamper.agent_type,
        ));
    }

    fn publish_healed(&self, _hook_event: &str, event: &TamperEvent) {
        if let Some(logger) = &self.sinks.logger {
            logger.log(event.clone());
        }
        if let Some(tx) = &self.sinks.cloud_tx {
            let ce = event.to_cloud_event(
                &self.sinks.agent_id,
                &self.sinks.client_version,
                current_os(),
                TamperCloudEventKind::Healed,
            );
            let _ = tx.try_send(ce);
        }
        telemetry::capture_global(Event::tamper_healed(
            &event.tamper.detection_method,
            &event.tamper.agent_type,
            &event.tamper.heal.outcome,
            event.tamper.heal.attempt,
        ));
    }

    fn try_heal(&self) -> Result<(), ()> {
        let token = match std::fs::read_to_string(&self.token_file_path) {
            Ok(t) => t.trim().to_string(),
            Err(e) => {
                tracing::warn!(error = %e, "reconciler: cannot read daemon token for heal");
                return Err(());
            }
        };

        match crate::hooks::detect_agent() {
            Ok(agent) => match crate::hooks::install_hooks(&agent, self.port, &token) {
                Ok(result) => {
                    tracing::warn!(
                        hooks_reinstalled = result.entries.len(),
                        "reconciler: hooks healed via reinstall"
                    );
                    Ok(())
                }
                Err(e) => {
                    tracing::warn!(error = %e, "reconciler: heal failed");
                    Err(())
                }
            },
            Err(e) => {
                tracing::debug!(error = %e, "reconciler: cannot detect agent for heal");
                Err(())
            }
        }
    }

    pub fn open_circuits(&self) -> Vec<&str> {
        self.heal_manager.open_circuits()
    }
}

/// Translate a per-entry heal tracker state into the `outcome` + `circuit`
/// strings that appear in the OCSF `HealOutcome`. Kept as a free function
/// so the reconciler body stays readable and so unit tests can cover the
/// mapping in isolation.
fn heal_outcome_strings(
    tracker: &heal::EntryHealTracker,
    heal_ok: bool,
) -> (&'static str, &'static str) {
    use heal::HealState;
    match tracker.state {
        HealState::CircuitOpen { .. } => ("circuit_open", "open"),
        HealState::Healthy => (if heal_ok { "succeeded" } else { "failed" }, "closed"),
        HealState::Backoff { .. } | HealState::Drifted | HealState::Healing => {
            if heal_ok {
                ("succeeded", "closed")
            } else {
                ("failed", "closed")
            }
        }
    }
}

fn check_entry_drift(
    hook_event: &str,
    entry_id: &str,
    hooks_obj: &serde_json::Map<String, serde_json::Value>,
    hmac_key: &[u8],
    port: u16,
) -> DriftOutcome {
    let event_arr = match hooks_obj.get(hook_event).and_then(|a| a.as_array()) {
        Some(a) => a,
        None => {
            tracing::warn!(
                hook_event = %hook_event,
                detection_method = "entry_deleted",
                "reconciler: hook event array missing"
            );
            return DriftOutcome::Drifted {
                method: "entry_deleted",
                deltas: Vec::new(),
            };
        }
    };

    let openlatch_entry = event_arr.iter().find(|entry| {
        matches!(
            classify_marker(entry),
            MarkerShape::Legacy | MarkerShape::Current(_)
        )
    });

    match openlatch_entry {
        None => {
            tracing::warn!(
                hook_event = %hook_event,
                detection_method = "marker_missing",
                "reconciler: openlatch entry missing from hook array"
            );
            DriftOutcome::Drifted {
                method: "marker_missing",
                deltas: Vec::new(),
            }
        }
        Some(entry) => match classify_marker(entry) {
            MarkerShape::Legacy => {
                tracing::info!(
                    code = crate::error::ERR_LEGACY_MARKER_DETECTED,
                    hook_event = %hook_event,
                    detection_method = "legacy_marker_upgrade",
                    "reconciler: legacy boolean marker found — upgrading"
                );
                DriftOutcome::Drifted {
                    method: "legacy_marker_upgrade",
                    deltas: Vec::new(),
                }
            }
            MarkerShape::Current(ref marker) => {
                let hmac = match &marker.hmac {
                    Some(h) => h,
                    None => {
                        return DriftOutcome::Drifted {
                            method: "marker_missing",
                            deltas: Vec::new(),
                        };
                    }
                };
                match verify_entry_hmac(entry, hmac, hmac_key) {
                    Ok(true) => DriftOutcome::Healthy,
                    Ok(false) => {
                        tracing::warn!(
                            hook_event = %hook_event,
                            entry_id = %entry_id,
                            detection_method = "hmac_mismatch",
                            "reconciler: HMAC verification failed — entry tampered"
                        );
                        let deltas = compute_field_deltas(hook_event, port, marker, entry);
                        DriftOutcome::Drifted {
                            method: "hmac_mismatch",
                            deltas,
                        }
                    }
                    Err(_) => DriftOutcome::Drifted {
                        method: "hmac_mismatch",
                        deltas: Vec::new(),
                    },
                }
            }
            MarkerShape::Missing => DriftOutcome::Drifted {
                method: "marker_missing",
                deltas: Vec::new(),
            },
        },
    }
}

/// Rebuild the expected hook entry using the same install-time builder and
/// diff it against the observed entry. Emits field paths only; any failure
/// falls through to an empty delta vec so the detection event still fires.
fn compute_field_deltas(
    hook_event: &str,
    port: u16,
    marker: &crate::core::hook_state::marker::OpenlatchMarker,
    observed: &serde_json::Value,
) -> Vec<FieldDelta> {
    const TOKEN_ENV_VAR: &str = "OPENLATCH_TOKEN";
    let hook_bin = crate::hooks::resolve_hook_binary_path();
    let mut expected = crate::hooks::claude_code::build_hook_entry(
        hook_event,
        port,
        TOKEN_ENV_VAR,
        &hook_bin,
        marker,
    );

    // build_hook_entry does not embed the marker itself — it's added separately
    // by install_hooks. We inject the same marker here so the non-marker fields
    // (hooks, matcher, timeout) are what the diff focuses on.
    if let Ok(marker_value) = serde_json::to_value(marker) {
        expected["_openlatch"] = marker_value;
    }

    diff_entry_fields(&expected, observed)
}

pub fn run_startup_reconcile(settings_path: &Path, openlatch_dir: &Path, port: u16) {
    let token_file = openlatch_dir.join("daemon.token");
    let mut r = Reconciler {
        rx: mpsc::channel(1).1,
        settings_path: settings_path.to_path_buf(),
        openlatch_dir: openlatch_dir.to_path_buf(),
        port,
        token_file_path: token_file,
        heal_manager: HealManager::new(),
        sinks: TamperSinks::default(),
    };
    r.do_reconcile();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::hook_state::hmac::compute_entry_hmac;
    use crate::core::hook_state::marker::OpenlatchMarker;
    use heal::{EntryHealTracker, HealState};

    #[test]
    fn heal_outcome_strings_when_healthy_and_ok() {
        let t = EntryHealTracker::new();
        assert_eq!(heal_outcome_strings(&t, true), ("succeeded", "closed"));
    }

    #[test]
    fn heal_outcome_strings_when_failed() {
        let mut t = EntryHealTracker::new();
        t.mark_drifted();
        t.record_heal_attempt();
        t.record_heal_failure();
        let (outcome, circuit) = heal_outcome_strings(&t, false);
        assert_eq!(outcome, "failed");
        assert_eq!(circuit, "closed");
    }

    #[test]
    fn heal_outcome_strings_when_circuit_open() {
        let mut t = EntryHealTracker::new();
        for _ in 0..5 {
            t.mark_drifted();
            t.record_heal_attempt();
            t.record_heal_success();
            t.mark_drifted();
        }
        assert!(matches!(t.state, HealState::CircuitOpen { .. }));
        assert_eq!(heal_outcome_strings(&t, false), ("circuit_open", "open"));
    }

    #[test]
    fn current_os_returns_a_known_string() {
        let os = current_os();
        assert!(matches!(os, "linux" | "macos" | "windows"));
    }

    /// Construct a well-formed hook entry with a computed HMAC, using a
    /// fixed test key. Mirrors the shape `install_hooks` produces.
    fn make_signed_entry(hook_event: &str, entry_id: &str, key: &[u8]) -> serde_json::Value {
        let marker_no_hmac = OpenlatchMarker::new(entry_id.to_string());
        let mut entry = crate::hooks::claude_code::build_hook_entry(
            hook_event,
            7443,
            "OPENLATCH_TOKEN",
            std::path::Path::new("/opt/openlatch/bin/openlatch-hook"),
            &marker_no_hmac,
        );
        entry["_openlatch"] = serde_json::to_value(&marker_no_hmac).unwrap();
        let hmac = compute_entry_hmac(&entry, key).unwrap();
        let marker = marker_no_hmac.with_hmac(hmac);
        entry["_openlatch"] = serde_json::to_value(&marker).unwrap();
        entry
    }

    fn build_hooks_obj(hook_event: &str, entry: serde_json::Value) -> serde_json::Value {
        serde_json::json!({ hook_event: [entry] })
    }

    #[test]
    fn check_entry_drift_healthy_when_hmac_matches() {
        let key = vec![0x42; 32];
        let entry = make_signed_entry("PreToolUse", "entry-a", &key);
        let hooks = build_hooks_obj("PreToolUse", entry);
        let outcome = check_entry_drift(
            "PreToolUse",
            "entry-a",
            hooks.as_object().unwrap(),
            &key,
            7443,
        );
        assert!(matches!(outcome, DriftOutcome::Healthy));
    }

    #[test]
    fn check_entry_drift_hmac_mismatch_populates_deltas() {
        let key = vec![0x42; 32];
        let mut entry = make_signed_entry("PreToolUse", "entry-a", &key);
        // Tamper a non-marker field — the HMAC is computed over the
        // pre-tamper value, so verification must fail.
        entry["timeout"] = serde_json::json!(999);
        let hooks = build_hooks_obj("PreToolUse", entry);
        let outcome = check_entry_drift(
            "PreToolUse",
            "entry-a",
            hooks.as_object().unwrap(),
            &key,
            7443,
        );
        match outcome {
            DriftOutcome::Drifted { method, deltas } => {
                assert_eq!(method, "hmac_mismatch");
                assert!(
                    deltas.iter().any(|d| d.field == "timeout"),
                    "expected timeout delta, got {deltas:?}"
                );
            }
            _ => panic!("expected Drifted, got {outcome:?}"),
        }
    }

    #[test]
    fn check_entry_drift_reports_entry_deleted_when_event_array_missing() {
        let key = vec![0x42; 32];
        let hooks = serde_json::json!({});
        let outcome = check_entry_drift(
            "PreToolUse",
            "entry-a",
            hooks.as_object().unwrap(),
            &key,
            7443,
        );
        match outcome {
            DriftOutcome::Drifted { method, deltas } => {
                assert_eq!(method, "entry_deleted");
                assert!(deltas.is_empty());
            }
            _ => panic!("expected Drifted"),
        }
    }

    #[test]
    fn check_entry_drift_reports_marker_missing_when_entry_absent() {
        let key = vec![0x42; 32];
        // Event array present but no entry has an _openlatch marker.
        let hooks = serde_json::json!({
            "PreToolUse": [{"matcher": "", "hooks": [{"type": "command", "command": "other"}]}]
        });
        let outcome = check_entry_drift(
            "PreToolUse",
            "entry-a",
            hooks.as_object().unwrap(),
            &key,
            7443,
        );
        match outcome {
            DriftOutcome::Drifted { method, .. } => assert_eq!(method, "marker_missing"),
            _ => panic!("expected Drifted"),
        }
    }

    #[test]
    fn check_entry_drift_reports_legacy_marker_upgrade() {
        let key = vec![0x42; 32];
        let hooks = serde_json::json!({
            "PreToolUse": [{"_openlatch": true, "matcher": "", "hooks": []}]
        });
        let outcome = check_entry_drift(
            "PreToolUse",
            "entry-a",
            hooks.as_object().unwrap(),
            &key,
            7443,
        );
        match outcome {
            DriftOutcome::Drifted { method, .. } => assert_eq!(method, "legacy_marker_upgrade"),
            _ => panic!("expected Drifted"),
        }
    }

    #[tokio::test]
    async fn publish_detected_fans_out_to_cloud_tx() {
        // Construct a reconciler in its loneliest possible form — no watcher,
        // no poll, no heal manager activity. The only thing we exercise is
        // the sink dispatch.
        let (_in_tx, in_rx) = mpsc::channel(1);
        let (cloud_tx, mut cloud_rx) = mpsc::channel(16);
        let tmp = tempfile::tempdir().unwrap();
        let (logger, _handle) =
            crate::core::logging::tamper_log::TamperLogger::new(tmp.path().to_path_buf());

        let reconciler = Reconciler::new_with_sinks(
            in_rx,
            tmp.path().join("settings.json"),
            tmp.path().to_path_buf(),
            7443,
            tmp.path().join("daemon.token"),
            TamperSinks {
                logger: Some(logger),
                cloud_tx: Some(cloud_tx),
                agent_id: "agt_test".into(),
                client_version: "0.0.1-test".into(),
            },
        );

        let event = TamperEvent::new(
            "entry-a".into(),
            "claude-code".into(),
            "sha256:abc".into(),
            "PreToolUse".into(),
            "hmac_mismatch".into(),
        );
        reconciler.publish_detected(&event);

        let ce = cloud_rx.try_recv().expect("cloud channel received event");
        assert_eq!(
            ce.envelope["type"].as_str(),
            Some("ai.openlatch.security.tamper_detected")
        );
        assert_eq!(ce.agent_id, "agt_test");
    }

    #[tokio::test]
    async fn publish_healed_links_to_detection_event_id() {
        let (_in_tx, in_rx) = mpsc::channel(1);
        let (cloud_tx, mut cloud_rx) = mpsc::channel(16);
        let tmp = tempfile::tempdir().unwrap();
        let (logger, _handle) =
            crate::core::logging::tamper_log::TamperLogger::new(tmp.path().to_path_buf());

        let reconciler = Reconciler::new_with_sinks(
            in_rx,
            tmp.path().join("settings.json"),
            tmp.path().to_path_buf(),
            7443,
            tmp.path().join("daemon.token"),
            TamperSinks {
                logger: Some(logger),
                cloud_tx: Some(cloud_tx),
                agent_id: "agt_test".into(),
                client_version: "0.0.1-test".into(),
            },
        );

        let detected = TamperEvent::new(
            "entry-a".into(),
            "claude-code".into(),
            "sha256:abc".into(),
            "PreToolUse".into(),
            "hmac_mismatch".into(),
        );
        let healed = TamperEvent::new_healed(&detected, "succeeded", 1, "closed");
        reconciler.publish_healed("PreToolUse", &healed);

        let ce = cloud_rx.try_recv().expect("cloud channel received event");
        assert_eq!(
            ce.envelope["type"].as_str(),
            Some("ai.openlatch.security.tamper_healed")
        );
        assert_eq!(
            ce.envelope["data"]["tamper"]["related_event_id"].as_str(),
            Some(detected.tamper.event_id.as_str())
        );
    }
}