openlatch-client 0.3.3

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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
pub mod heal;
pub mod request;

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

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::binding::AgentBinding;
use crate::hooks::jsonc;

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

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

/// One agent the reconciler watches: the file its hook entries live in, and
/// the binding that can heal them.
///
/// One value rather than two parallel lists. A heal reinstalls into the file
/// the drift was observed in, and pairing them is the only thing that keeps
/// those two facts from being matched up by index at the call site.
#[derive(Clone)]
pub struct AgentTarget {
    /// The agent's hook config file — `settings.json`, `hooks.json`, whatever
    /// that agent registers into.
    pub settings_path: PathBuf,
    /// `Arc`, not `&dyn`: a borrow would put a lifetime on the struct. Held
    /// rather than re-detected per heal, so a reconciler can never heal a
    /// different agent from the one it is watching.
    pub binding: Arc<dyn AgentBinding>,
}

impl AgentTarget {
    /// The target for one detected agent.
    pub fn for_agent(agent: &crate::hooks::DetectedAgent) -> Self {
        Self {
            settings_path: agent.settings_path(),
            binding: agent.binding.clone(),
        }
    }
}

pub struct Reconciler {
    rx: mpsc::Receiver<ReconcileRequest>,
    /// Every agent this reconciler watches, in detection order.
    targets: Vec<AgentTarget>,
    openlatch_dir: PathBuf,
    port: u16,
    token_file_path: PathBuf,
    heal_manager: HealManager,
    sinks: TamperSinks,
}

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

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

    /// Drain reconcile requests until the channel closes or `Shutdown` arrives.
    ///
    /// Borrows rather than consuming `self` so the daemon's task supervisor can
    /// re-enter the loop after a panic on the **same** receiver — a consumed
    /// `self` would take the queue with it and leave tamper reconciliation dead
    /// for the rest of the process lifetime.
    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();
    }

    /// One pass over every agent this reconciler watches.
    ///
    /// The state file and the HMAC key are loaded once here rather than per
    /// target: both are properties of the install, not of an agent, and
    /// re-reading a megabyte of state once per agent on a 30 s poll is a cost
    /// paid for nothing.
    fn do_reconcile(&mut self) {
        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;
            }
        };

        // Cloned so the per-target pass can take `&mut self` — a target is a
        // path and an `Arc`, one per installed agent.
        for target in self.targets.clone() {
            self.reconcile_target(&target, &state, &hmac_key);
        }
    }

    /// Verify one agent's tracked entries against that agent's own config file.
    fn reconcile_target(&mut self, target: &AgentTarget, state: &HookStateFile, hmac_key: &[u8]) {
        let raw = match std::fs::read_to_string(&target.settings_path) {
            Ok(c) => c,
            Err(e) => {
                tracing::debug!(error = %e, "reconciler: cannot read settings.json");
                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 => {
                // Scoped, like the walk below: an install that tracks entries
                // for a second agent and none for this one has nothing missing
                // here, and healing on that reading reinstalls this agent's
                // hooks into a file whose `hooks` key its owner deliberately
                // removed.
                if tracked_in(state, &hash_settings_path(&target.settings_path))
                    .next()
                    .is_some()
                {
                    tracing::warn!(
                        "reconciler: hooks object missing from settings.json — will heal"
                    );
                    let _ = self.try_heal(target);
                }
                return;
            }
        };

        let settings_path_hash = hash_settings_path(&target.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 tracked_in(state, &settings_path_hash) {
            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,
                &*target.binding,
            );

            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(),
                    // The agent whose file this entry was found in, asked rather than
                    // assumed. The constant that used to sit here said "claude-code" for
                    // every reconciler, so a second binding's tamper events would have
                    // been mislabelled with no compile error to catch it.
                    target.binding.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(target).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, target: &AgentTarget) -> 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(());
            }
        };

        // The binding of the target whose drift was observed, never a fresh
        // detection and never another target's: re-detecting here, or reaching
        // for a single held binding, heals a different agent from the one that
        // drifted.
        match crate::hooks::install_hooks(&*target.binding, self.port, &token) {
            Ok(result) => {
                tracing::warn!(
                    hooks_reinstalled = result.entries.len(),
                    agent = target.binding.agent_type(),
                    "reconciler: hooks healed via reinstall"
                );
                Ok(())
            }
            Err(e) => {
                tracing::warn!(error = %e, "reconciler: heal failed");
                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")
            }
        }
    }
}

/// The tracked entries that belong to one agent's config file.
///
/// `hook-state.json` is one file for the whole install and holds every agent's
/// entries; the file path is what tells them apart. Keyed on the recorded path
/// hash rather than on the agent name because the path is what install wrote
/// and what the reconciler is about to read — an agent whose config directory
/// moved has entries under its old path, and those are equally not this file's
/// to verify.
fn tracked_in<'a>(
    state: &'a HookStateFile,
    settings_path_hash: &'a str,
) -> impl Iterator<Item = &'a StateEntry> {
    state
        .entries
        .iter()
        .filter(move |e| e.settings_path_hash == settings_path_hash)
}

fn check_entry_drift(
    hook_event: &str,
    entry_id: &str,
    hooks_obj: &serde_json::Map<String, serde_json::Value>,
    hmac_key: &[u8],
    port: u16,
    binding: &dyn AgentBinding,
) -> 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, binding);
                        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,
    binding: &dyn AgentBinding,
) -> Vec<FieldDelta> {
    let hook_bin = crate::hooks::resolve_hook_binary_path();
    let mut expected = binding.build_hook_entry(hook_event, &hook_bin, port, 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(targets: Vec<AgentTarget>, openlatch_dir: &Path, port: u16) {
    let token_file = openlatch_dir.join("daemon.token");
    let mut r = Reconciler {
        rx: mpsc::channel(1).1,
        targets,
        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 crate::hooks::bindings::claude_code::ClaudeCodeBinding;
    use heal::{EntryHealTracker, HealState};

    /// The binding every fixture in this module reconciles against.
    ///
    /// Constructed rather than detected: these tests must not depend on
    /// whether the machine running them has Claude Code installed.
    fn fixture_binding() -> ClaudeCodeBinding {
        ClaudeCodeBinding {
            claude_dir: std::path::PathBuf::from("/opt/openlatch/.claude"),
            settings_path: std::path::PathBuf::from("/opt/openlatch/.claude/settings.json"),
        }
    }

    #[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 = fixture_binding().build_hook_entry(
            hook_event,
            std::path::Path::new("/opt/openlatch/bin/openlatch-hook"),
            7443,
            &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,
            &fixture_binding(),
        );
        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,
            &fixture_binding(),
        );
        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,
            &fixture_binding(),
        );
        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,
            &fixture_binding(),
        );
        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,
            &fixture_binding(),
        );
        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,
            vec![AgentTarget {
                settings_path: tmp.path().join("settings.json"),
                binding: Arc::new(fixture_binding()),
            }],
            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,
            vec![AgentTarget {
                settings_path: tmp.path().join("settings.json"),
                binding: Arc::new(fixture_binding()),
            }],
            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())
        );
    }

    // -----------------------------------------------------------------------
    // Multi-agent reconciliation
    // -----------------------------------------------------------------------

    /// Everything a whole-`do_reconcile` test needs, isolated under one root:
    /// an OpenLatch directory to hold the state file and the HMAC key, the
    /// shared two-agent fixture, and the key those agents' entries are signed
    /// with.
    ///
    /// The key comes from the store rather than a literal, because the
    /// reconciler loads it from the same store — a fixed test key would verify
    /// against a different one and every entry would read as tampered for a
    /// reason the test was not written to find.
    struct TwoAgents {
        _root: tempfile::TempDir,
        openlatch_dir: std::path::PathBuf,
        agents: Vec<crate::hooks::DetectedAgent>,
        key: Vec<u8>,
    }

    impl TwoAgents {
        fn new() -> Self {
            let root = tempfile::tempdir().expect("fixture root");
            let openlatch_dir = root.path().join("openlatch");
            std::fs::create_dir_all(&openlatch_dir).expect("openlatch dir");
            let key = HmacKeyStore::new(&openlatch_dir)
                .load_or_create()
                .expect("hmac key");
            let agents = crate::hooks::binding::test_support::two_detected_agents(root.path());
            Self {
                _root: root,
                openlatch_dir,
                agents,
                key,
            }
        }

        fn target(&self, i: usize) -> AgentTarget {
            AgentTarget::for_agent(&self.agents[i])
        }

        /// Write `hooks` as agent `i`'s config file.
        fn seed_config(&self, i: usize, hooks: serde_json::Value) {
            std::fs::write(
                self.agents[i].settings_path(),
                serde_json::json!({ "hooks": hooks }).to_string(),
            )
            .expect("seed agent config");
        }

        /// Track one entry against agent `i`'s config file, the way
        /// `install_hooks` records it.
        fn tracked_entry(&self, i: usize, hook_event: &str, id: &str) -> StateEntry {
            StateEntry {
                id: id.into(),
                agent: self.agents[i].binding.agent_type().into(),
                settings_path_hash: hash_settings_path(&self.agents[i].settings_path()),
                hook_event: hook_event.into(),
                expected_entry_hmac: String::new(),
                daemon_port_at_install: 7443,
                daemon_token_fp: "fp".into(),
                v: 1,
            }
        }

        fn save_state(&self, entries: Vec<StateEntry>) {
            let mut state = HookStateFile::new("kid-01".into());
            for e in entries {
                state.upsert_entry(e);
            }
            state.save(&self.openlatch_dir).expect("save state");
        }

        /// A reconciler over `targets`, with a channel carrying every tamper
        /// event it publishes.
        fn reconciler(
            &self,
            targets: Vec<AgentTarget>,
        ) -> (Reconciler, mpsc::Receiver<CloudEvent>) {
            let (cloud_tx, cloud_rx) = mpsc::channel(32);
            let r = Reconciler::new_with_sinks(
                mpsc::channel(1).1,
                targets,
                self.openlatch_dir.clone(),
                7443,
                // Deliberately absent: `try_heal` reads the token before it
                // reinstalls anything, so a heal in these tests fails at the
                // first step and never writes an agent's config file.
                self.openlatch_dir.join("daemon.token"),
                TamperSinks {
                    logger: None,
                    cloud_tx: Some(cloud_tx),
                    agent_id: "agt_test".into(),
                    client_version: "0.0.1-test".into(),
                },
            );
            (r, cloud_rx)
        }
    }

    /// Every `tamper_detected` event on the channel, as (source, hook_event).
    fn detections(rx: &mut mpsc::Receiver<CloudEvent>) -> Vec<(String, String)> {
        let mut found = Vec::new();
        while let Ok(ce) = rx.try_recv() {
            if ce.envelope["type"].as_str() == Some("ai.openlatch.security.tamper_detected") {
                found.push((
                    ce.envelope["source"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                    ce.envelope["data"]["tamper"]["hook_event"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                ));
            }
        }
        found
    }

    /// A reconciler must verify only the entries recorded against the file it
    /// is reading.
    ///
    /// `hook-state.json` is one file for the whole install, so it holds every
    /// agent's entries. Checking all of them against one agent's config finds
    /// the other agent's entries missing — every time, forever — and each miss
    /// is a `tamper_detected` event, a heal that reinstalls the WRONG agent's
    /// hooks, and another dozen rows in the state file. Observed on a live
    /// two-agent host: 2,120 false tamper events, 202 reinstalls, a 1 MB state
    /// file, and a circuit breaker open on entries nothing had touched.
    #[test]
    fn reconcile_ignores_an_entry_from_another_agents_file() {
        let fx = TwoAgents::new();
        let entry = make_signed_entry("PreToolUse", "entry-a", &fx.key);
        fx.seed_config(0, build_hooks_obj("PreToolUse", entry));
        fx.seed_config(1, serde_json::json!({}));
        fx.save_state(vec![
            fx.tracked_entry(0, "PreToolUse", "entry-a"),
            // The second agent's entry. It is present and healthy in ITS file,
            // which this reconciler is not reading.
            fx.tracked_entry(1, "SessionEnd", "entry-b"),
        ]);

        let (mut r, mut rx) = fx.reconciler(vec![fx.target(0)]);
        r.do_reconcile();

        assert_eq!(
            detections(&mut rx),
            Vec::<(String, String)>::new(),
            "the second agent's entry is not this file's to verify"
        );
    }

    /// Every detected agent is watched, not just the first.
    ///
    /// An agent whose hooks nothing reconciles is enforcement with no
    /// tamper-evidence behind it: strip its entries out of its config and
    /// nothing detects it, nothing heals it, and `doctor` still says the hooks
    /// are installed because the file it reads is the one that was never
    /// touched.
    #[test]
    fn reconcile_watches_every_detected_agent() {
        let fx = TwoAgents::new();
        fx.seed_config(
            0,
            build_hooks_obj(
                "PreToolUse",
                make_signed_entry("PreToolUse", "entry-a", &fx.key),
            ),
        );
        // The second agent's entry is signed and then altered, so only a
        // reconciler that actually reads this file can report it.
        let mut tampered = make_signed_entry("SessionEnd", "entry-b", &fx.key);
        tampered["timeout"] = serde_json::json!(999);
        fx.seed_config(1, build_hooks_obj("SessionEnd", tampered));
        fx.save_state(vec![
            fx.tracked_entry(0, "PreToolUse", "entry-a"),
            fx.tracked_entry(1, "SessionEnd", "entry-b"),
        ]);

        let (mut r, mut rx) = fx.reconciler(vec![fx.target(0), fx.target(1)]);
        r.do_reconcile();

        assert_eq!(
            detections(&mut rx),
            vec![("cursor".to_string(), "SessionEnd".to_string())],
            "the second agent's tampered entry must be detected, and attributed to it"
        );
    }
}