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
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
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, HookSurface};
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,
}
impl TamperSinks {
/// Send a `tamper_detected` event to every configured sink: the local
/// tamper log, the cloud rail, and aggregate telemetry.
///
/// Shared by the reconciler and the model relay's endpoint wiring, so a
/// wiring event travels exactly the path a hook tamper event does.
pub fn publish_detected(&self, event: &TamperEvent) {
if let Some(logger) = &self.logger {
logger.log(event.clone());
}
if let Some(tx) = &self.cloud_tx {
let ce = event.to_cloud_event(
&self.agent_id,
&self.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,
));
}
/// The `tamper_healed` half of [`Self::publish_detected`].
pub fn publish_healed(&self, event: &TamperEvent) {
if let Some(logger) = &self.logger {
logger.log(event.clone());
}
if let Some(tx) = &self.cloud_tx {
let ce = event.to_cloud_event(
&self.agent_id,
&self.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,
));
}
}
/// 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 its own hook surface.
///
/// **The shape of the surface is the first question, before any read.**
/// `AgentTarget::settings_path` is documented as a config file and is built
/// from `DetectedAgent::settings_path()`, so there is no enum on the target
/// to match — the binding is what knows, and asking it here is what keeps a
/// directory of executable scripts out of `jsonc::parse_settings_value`.
/// Cline is already a target and already watched; this path is inert for it
/// today only because `read_to_string` on a directory errors, which is an
/// accident rather than a guard.
///
/// The `ConfigFile` arm keeps using `target.settings_path`, unchanged: it is
/// the path install wrote and the path the entries are keyed under, and
/// routing it through the variant instead would be a behaviour change
/// dressed as a refactor.
fn reconcile_target(&mut self, target: &AgentTarget, state: &HookStateFile, hmac_key: &[u8]) {
match target.binding.hook_surface() {
HookSurface::ConfigFile(_) => self.reconcile_config_file(target, state, hmac_key),
HookSurface::Directory(hooks_dir) => {
self.reconcile_hook_files(target, &hooks_dir, state);
}
}
}
/// Verify one agent's tracked entries against that agent's own config file.
fn reconcile_config_file(
&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, None);
}
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));
}
}
// `None`: a config-file surface has no plugin lane, and that default is
// what keeps every agent but Cline unchanged by §3a existing.
self.settle_drift(target, &drift_results, &pending_detections, None);
}
/// Verify a **directory** hook surface: each tracked script against the
/// SHA-256 the descriptor in its state row records, and re-write the ones
/// that no longer match.
///
/// The **eleventh artefact rides this walk too** (plan 02 §3a). The
/// enforcement plugin is the one file on this surface that can refuse a
/// tool call, and before it had a state row it was also the only one that
/// could not repair itself — ten capture files self-healing while the file
/// carrying enforcement stayed broken until a human re-ran `init`. Its row
/// is keyed on the plugin's own file path rather than on this directory, so
/// it is fetched separately and appended; everything after that is
/// identical, down to the per-entry circuit breaker.
///
/// Phase 1 only, then the shared phase 2 — the heal is
/// [`Self::try_heal`]'s reinstall, which for this surface is the file
/// installer, and the `tamper_healed` CloudEvent it emits is the existing
/// one. There is no second event shape for a script: the same entry id, the
/// same surface hash and the same hook event name, with a detection method
/// that says a file rather than an entry was what moved.
///
/// Nothing here parses JSON, and nothing here reads `settings_path`.
///
/// `hmac_key` is not taken: the tamper-evidence an entry carries in its
/// `_openlatch` marker has no equivalent inside a shell script, and the
/// descriptor's hash is what a rewritten file fails. The row's
/// `expected_entry_hmac` still signs that descriptor at rest — that is the
/// state file's integrity, which `HookStateFile` owns, not this walk's.
fn reconcile_hook_files(
&mut self,
target: &AgentTarget,
hooks_dir: &Path,
state: &HookStateFile,
) {
// The ten are keyed to the DIRECTORY, which is what `install_hooks`
// wrote them under.
let settings_path_hash = hash_settings_path(hooks_dir);
let mut rows: Vec<&StateEntry> = tracked_in(state, &settings_path_hash).collect();
// The eleventh artefact rides the same walk. Its row is keyed on the
// plugin's own FILE path — the directory name is only the plugin id —
// so it is unreachable from the hash above and needs its own lookup.
//
// Finding one is also what makes the repair ours to make. `is_ours`
// proves a file is internally consistent, not that it is ours, and a
// plugin corrupted badly enough to break its own marker line fails it;
// the row is the authority the file can no longer supply for itself. A
// plugin directory with no row is one we never installed, and nothing
// below will write into it.
let plugin_dir = target.binding.plugin_surface();
let plugin_hash = plugin_dir
.as_deref()
.map(|dir| hash_settings_path(&crate::hooks::cline_plugin::entry_path(dir)));
let mut owned_plugin_dir: Option<&Path> = None;
if let (Some(dir), Some(hash)) = (plugin_dir.as_deref(), plugin_hash.as_deref()) {
let mut plugin_rows: Vec<&StateEntry> = tracked_in(state, hash).collect();
if !plugin_rows.is_empty() {
owned_plugin_dir = Some(dir);
rows.append(&mut plugin_rows);
}
}
let mut pending_detections: Vec<(StateEntry, TamperEvent)> = Vec::new();
let mut drift_results: Vec<(String, bool)> = Vec::new();
for state_entry in rows {
if self.heal_manager.tracker(&state_entry.id).is_circuit_open() {
drift_results.push((state_entry.id.clone(), false));
continue;
}
let outcome = check_file_drift(state_entry);
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(),
target.binding.agent_type().to_string(),
// The ROW's surface hash, not the directory's. It is the
// same string for all ten by construction — `tracked_in`
// selected them on it — and for the plugin it is the only
// correct answer, since its row is keyed on a file.
state_entry.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));
}
}
self.settle_drift(
target,
&drift_results,
&pending_detections,
owned_plugin_dir,
);
}
/// Phase 2, shared by both surface shapes: move every tracker, heal once if
/// anything drifted, and emit one `tamper_healed` per detection.
///
/// One implementation rather than two, because the heal accounting is where
/// the subtlety lives — a heal is attempted **once per target**, not once
/// per drifted entry, and every pending detection is answered with the
/// outcome of that one attempt. Two copies of this would drift into two
/// different stories about the same repair.
/// `owned_plugin_dir` is the enforcement plugin's directory when — and only
/// when — this target holds a state row for the file inside it. It is the
/// authority [`Self::try_heal`] repairs that file on; `None` everywhere
/// else, including for every `ConfigFile` surface.
fn settle_drift(
&mut self,
target: &AgentTarget,
drift_results: &[(String, bool)],
pending_detections: &[(StateEntry, TamperEvent)],
owned_plugin_dir: Option<&Path>,
) {
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 {
return;
}
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, owned_plugin_dir).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) {
self.sinks.publish_detected(event);
}
fn publish_healed(&self, _hook_event: &str, event: &TamperEvent) {
self.sinks.publish_healed(event);
}
fn try_heal(&self, target: &AgentTarget, owned_plugin_dir: Option<&Path>) -> Result<(), ()> {
// An agent this build cannot write a hook surface into has nothing to
// heal. `install_hooks` is guarded too, and answers `Ok` with zero
// entries — which is precisely why the guard is repeated here: the
// `Ok` arm below logs "hooks healed via reinstall" and the caller
// records a heal SUCCESS from it, so the primitive's honest "I wrote
// nothing" would be re-read as "the drift is fixed", once per tamper
// event, for as long as the drift stands.
//
// `Err`, not `Ok`, and the distinction is the whole point:
// `heal_outcome_strings` turns `Ok` into the outcome string
// `"succeeded"` on a `tamper_healed` CloudEvent. A heal that did not
// happen must never reach an operator as one that did; "failed" is the
// true statement, because the drift the caller observed is still there.
if !target.binding.installable() {
tracing::debug!(
agent = target.binding.agent_type(),
"reconciler: agent has no writable hook surface — nothing to heal"
);
return Err(());
}
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 enforcement plugin, repaired BEFORE the reinstall and on the
// authority of its state row rather than of its own marker line.
//
// `install_hooks` below classifies that path with `is_ours`, so a
// plugin corrupted badly enough to break its marker reads to it as the
// developer's: left alone, reported through `left_alone`, and the heal
// declared incomplete — leaving the one artefact that can refuse a tool
// call broken until a human re-runs `init`. `Some` here means the
// caller is holding a row recording this exact path, which is what
// makes the rewrite ours to make.
//
// `crate::config::openlatch_dir()` deliberately, the same call
// `install_hooks` makes one frame down: two different answers would
// have the two writers disagree about the body and rewrite each other
// on every poll.
//
// Nothing here reads or writes `global-settings.json`. Repairing our
// own artefact and taking the plugin off `disabledPlugins` are
// different acts, and only one of them is ours to make.
if let Some(plugin_dir) = owned_plugin_dir {
if let Err(e) =
crate::hooks::cline_plugin::repair(plugin_dir, &crate::config::openlatch_dir())
{
tracing::warn!(
error = %e,
dir = %plugin_dir.display(),
"reconciler: cannot repair the enforcement plugin — refusing to report \
a heal that did not happen"
);
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) => {
// `Ok` means the CALL succeeded, never that the drift is gone —
// and on a `Directory` surface those are genuinely different.
// `hook_files::write_all` honours the collision rule: a file
// failing the ownership predicate is the developer's, so it is
// left exactly where it is and simply omitted from `entries`.
// A tampered script is precisely such a file. Reinstalling over
// it writes the other nine, returns `Ok`, and — without this
// check — puts `tamper_healed` on the wire while the tampered
// script is still on disk and still the one Cline executes.
//
// This is the SAME failure the guard at the top of this function
// prevents for a non-installable binding, reached by a second
// route that guard does not cover. "A heal that did not happen
// must never reach an operator as one that did."
//
// No surface match and no agent-named constant: `left_alone` is
// empty on a `ConfigFile` install by construction, so this one
// condition is correct for every agent and a future
// directory-shaped binding needs no new arm here.
if !result.left_alone.is_empty() {
tracing::warn!(
rewrote = result.entries.len(),
left_alone = ?result.left_alone,
agent = target.binding.agent_type(),
"reconciler: heal INCOMPLETE — a file we do not own holds a hook \
name; refusing to report a heal that did not happen"
);
return Err(());
}
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)
}
/// Verify one tracked hook **script** against the descriptor its state row
/// recorded.
///
/// The question `check_entry_drift` asks of a JSON entry, asked of a file: is
/// it still there, and are its bytes still the bytes we wrote? The comparison
/// is a SHA-256 over the whole body, marker line included, which is what
/// `install_hooks` stored — deliberately a different hash from the one INSIDE
/// the marker line, which is taken over the body with that line removed so a
/// script can describe itself with no state file present.
///
/// A row with no descriptor is `Healthy`: it is either a JSON-file agent's row
/// under a surface hash that cannot match, or a row written before the field
/// existed. **Not** drift — there is nothing to compare against, and healing on
/// "we have no record" would rewrite a correct file on every tick.
///
/// The detection methods are `file_` prefixed rather than reusing
/// `entry_deleted` / `hmac_mismatch`: neither an entry nor an HMAC is what
/// moved, and an operator reading `hmac_mismatch` against a shell script would
/// go looking for a marker object that a script has never carried.
fn check_file_drift(entry: &StateEntry) -> DriftOutcome {
let Some(descriptor) = entry.descriptor.as_ref() else {
return DriftOutcome::Healthy;
};
let path = Path::new(&descriptor.path);
// Bytes rather than `read_to_string`: a script that was replaced with
// something non-UTF-8 has drifted, and must not come back as an I/O error
// that the caller then reads as "could not check, assume fine".
match std::fs::read(path) {
Ok(bytes) => {
let found = crate::hooks::hook_files::sha256_bytes(&bytes);
if found == descriptor.sha256 {
DriftOutcome::Healthy
} else {
tracing::warn!(
hook_event = %entry.hook_event,
entry_id = %entry.id,
detection_method = "file_hash_mismatch",
"reconciler: hook script no longer hashes to its descriptor — tampered"
);
DriftOutcome::Drifted {
method: "file_hash_mismatch",
// Paths only, never values — the delta names the field that
// moved and the wire message carries no body.
deltas: vec![FieldDelta {
field: "sha256".to_string(),
change: "modified".to_string(),
}],
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::warn!(
hook_event = %entry.hook_event,
detection_method = "file_deleted",
"reconciler: hook script is gone — will heal"
);
DriftOutcome::Drifted {
method: "file_deleted",
deltas: Vec::new(),
}
}
Err(e) => {
// Refused, not absent. Healing is still the right move — a reinstall
// is what restores a script whose mode was stripped — but the
// method says we could not read it rather than claiming a hash we
// never computed.
tracing::warn!(
error = %e,
hook_event = %entry.hook_event,
detection_method = "file_unreadable",
"reconciler: hook script could not be read — will heal"
);
DriftOutcome::Drifted {
method: "file_unreadable",
deltas: Vec::new(),
}
}
}
}
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(),
descriptor: None,
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
}
// ── the file-shaped arm ─────────────────────────────────────────────────
/// A state row for a directory surface, pointing at `path` and expecting
/// `sha256` there.
fn file_row(path: &std::path::Path, sha256: &str) -> StateEntry {
StateEntry {
id: "entry-file".into(),
agent: "cline".into(),
settings_path_hash: hash_settings_path(path.parent().expect("the hooks directory")),
hook_event: "PreToolUse".into(),
expected_entry_hmac: String::new(),
daemon_port_at_install: 7443,
daemon_token_fp: "fp".into(),
descriptor: Some(crate::core::hook_state::FileDescriptor {
path: path.to_string_lossy().into_owned(),
sha256: sha256.into(),
mode: 0o755,
}),
v: crate::core::hook_state::STATE_ENTRY_VERSION,
}
}
/// The four answers a hook SCRIPT can give, and the fifth that is not an
/// answer at all.
///
/// The last case is the one worth the test: a row with no descriptor is
/// **healthy**, not drifted. Read the other way, every tick would rewrite a
/// perfectly good file because the state file had nothing to compare it to.
#[test]
fn a_hook_script_drifts_when_its_bytes_stop_matching_its_descriptor() {
let root = tempfile::tempdir().expect("fixture root");
let script = root.path().join("PreToolUse");
std::fs::write(&script, "#!/bin/sh\nprintf '{}'\n").expect("seed the script");
let recorded =
crate::hooks::hook_files::sha256_bytes(&std::fs::read(&script).expect("read it back"));
assert!(matches!(
check_file_drift(&file_row(&script, &recorded)),
DriftOutcome::Healthy
));
// Rewritten: the bytes are no longer the ones install recorded.
std::fs::write(&script, "#!/bin/sh\ncurl evil.example\n").expect("rewrite it");
match check_file_drift(&file_row(&script, &recorded)) {
DriftOutcome::Drifted { method, deltas } => {
assert_eq!(method, "file_hash_mismatch");
assert_eq!(deltas.len(), 1);
assert_eq!(deltas[0].field, "sha256");
assert_eq!(deltas[0].change, "modified");
}
DriftOutcome::Healthy => panic!("a rewritten hook script is drift"),
}
// Deleted: the hook is simply gone, which is the same defect with a
// different name and no field to point at.
std::fs::remove_file(&script).expect("delete it");
match check_file_drift(&file_row(&script, &recorded)) {
DriftOutcome::Drifted { method, deltas } => {
assert_eq!(method, "file_deleted");
assert!(deltas.is_empty());
}
DriftOutcome::Healthy => panic!("a deleted hook script is drift"),
}
// No descriptor: nothing to compare. Healing on this would rewrite a
// correct file on every tick, forever.
let mut no_descriptor = file_row(&script, &recorded);
no_descriptor.descriptor = None;
assert!(matches!(
check_file_drift(&no_descriptor),
DriftOutcome::Healthy
));
}
/// 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"
);
}
/// A reinstall that SKIPPED the drifted file is not a heal.
///
/// The sibling of `heal_refuses_an_agent_with_no_writable_hook_surface`,
/// and the second route to the same false green. That one covers a binding
/// that writes nothing because it is not installable. This one covers a
/// binding that IS installable and still leaves the drifted file alone —
/// because `hook_files::write_all` honours the collision rule: a file
/// failing the ownership predicate is the developer's, so it is left
/// exactly where it is and omitted from `entries`.
///
/// **A tampered script is precisely such a file.** Reinstalling over it
/// rewrites the other nine, returns `Ok`, and without the check in
/// `try_heal` puts `tamper_healed` on the wire while the tampered script is
/// still on disk and still the one Cline executes. That is not a cosmetic
/// reporting bug: it is a security claim that is false.
#[test]
fn heal_refuses_to_claim_success_when_a_file_was_skipped() {
// Locks in the crate's documented order — `OPENLATCH_DIR`, then the
// hook-binary trio, then the Cline seams. This test writes all three
// groups, and `install_hooks` walks them.
let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let _bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let _cline_lock = crate::hooks::cline::SEAM_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let root = tempfile::tempdir().expect("fixture root");
let openlatch_dir = root.path().join("openlatch");
let hooks_dir = root.path().join("Hooks");
std::fs::create_dir_all(&openlatch_dir).expect("openlatch dir");
std::fs::create_dir_all(&hooks_dir).expect("hooks dir");
// `install_hooks` refuses a hook binary that is not an existing file
// (OL-1404), so the fake has to really be there — otherwise this test
// would pass on the wrong error and prove nothing about the skip.
let hook_bin = root.path().join("openlatch-hook");
std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").expect("fake hook binary");
let mut env_pairs: Vec<(&'static str, Option<std::ffi::OsString>)> = vec![
("OPENLATCH_DIR", Some(openlatch_dir.as_os_str().to_owned())),
("OPENLATCH_HOOK_BIN", Some(hook_bin.as_os_str().to_owned())),
// `HmacKeyStore::load_or_create` falls through to the OS keychain,
// which raises a GUI dialog no test run can answer.
(
"OPENLATCH_SKIP_KEYRING",
Some(std::ffi::OsString::from("1")),
),
];
// This fixture WRITES through `install_hooks`. Leaving Cline's seams
// alone points any walk at the developer's real `~/.cline`.
env_pairs.extend(
crate::hooks::cline::absent_seams(root.path())
.into_iter()
.map(|(k, v)| (k, Some(v.into_os_string()))),
);
let _env = crate::hooks::cline::EnvOverride::apply(env_pairs);
let token_file_path = openlatch_dir.join("daemon.token");
std::fs::write(&token_file_path, "test-token").expect("daemon token");
// The developer's own file, squatting on one of the ten hook names.
// `hook_file_name`, never the bare event. On Windows the installer writes
// `PreToolUse.ps1`, so a developer's file planted at `PreToolUse`
// collides with nothing, all ten install, and the premise below fails —
// which is exactly what this test did on the Windows job. The platform
// shape is a decision this crate makes in one place; a test that
// re-spells it by hand is asserting against the wrong host.
let theirs = hooks_dir.join(crate::hooks::hook_files::hook_file_name("PreToolUse"));
std::fs::write(&theirs, "# mine, not yours\n").expect("developer's hook");
let target = AgentTarget {
settings_path: hooks_dir.join("unused-for-a-directory-surface"),
binding: Arc::new(crate::hooks::binding::test_support::FakeBinding {
config_dir: root.path().to_path_buf(),
installable: true,
hook_surface_dir: Some(hooks_dir.clone()),
..Default::default()
}),
};
// The premise, asserted rather than assumed: the primitive really does
// answer `Ok` while writing FEWER than the full set. Without this the
// refusal below could pass for the wrong reason.
let wrote = crate::hooks::install_hooks(&*target.binding, 7443, "test-token")
.expect("the primitive skips a file it does not own rather than erroring");
assert_eq!(
wrote.entries.len(),
crate::hooks::hook_files::CLINE_HOOK_FILES.len() - 1,
"exactly the developer's one file must have been skipped"
);
let r = Reconciler::new(
mpsc::channel(1).1,
vec![target.clone()],
openlatch_dir,
7443,
token_file_path,
);
assert!(
r.try_heal(&target, None).is_err(),
"a reinstall that skipped the drifted file must not be reported as a heal: \
`Ok` here becomes the outcome \"succeeded\" on a tamper_healed event"
);
assert_eq!(
std::fs::read_to_string(&theirs).expect("the developer's file"),
"# mine, not yours\n",
"and the file we do not own is still untouched"
);
}
// ── the eleventh artefact: the enforcement plugin (plan 02 §3a) ─────────
/// A host with the ten scripts **and** the enforcement plugin really
/// installed, plus a reconciler pointed at it.
///
/// Installed through `install_hooks` rather than hand-seeded, because §3a's
/// whole claim is that heal re-renders from the same generator install
/// used: a fixture that wrote its own body would prove the two agree only
/// with itself.
///
/// Field order is drop order in Rust. The environment guard is declared
/// first so the seams are restored before the locks are released — a lock
/// handed on while `$OPENLATCH_DIR` still points here would run the next
/// taker's test against this temp directory. The temp root goes last.
///
/// **All four locks, in the crate's documented total order**, including the
/// home lock: Cline's own fixtures redirect the three seams under
/// `claude_code::CONFIG_DIR_ENV_LOCK`, so a fixture holding only the seam
/// lock runs straight through the middle of one of them.
struct PluginHost {
_env: crate::hooks::cline::EnvOverride,
_dir_lock: std::sync::MutexGuard<'static, ()>,
_home_lock: std::sync::MutexGuard<'static, ()>,
_bin_lock: std::sync::MutexGuard<'static, ()>,
_seam_lock: std::sync::MutexGuard<'static, ()>,
root: tempfile::TempDir,
openlatch_dir: std::path::PathBuf,
plugin_dir: std::path::PathBuf,
target: AgentTarget,
}
impl PluginHost {
fn new() -> Self {
let dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let seam_lock = crate::hooks::cline::SEAM_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let root = tempfile::tempdir().expect("fixture root");
let openlatch_dir = root.path().join("openlatch");
let store = root.path().join("store");
let hooks_dir = store.join("Hooks");
let plugin_dir = store
.join("plugins")
.join(crate::hooks::cline_plugin::PLUGIN_ID);
std::fs::create_dir_all(&openlatch_dir).expect("openlatch dir");
// `install_hooks` refuses a hook binary that is not an existing
// file (OL-1404), so the fake has to really be there.
let hook_bin = root.path().join("openlatch-hook");
std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").expect("a staged hook binary");
let mut env_pairs: Vec<(&'static str, Option<std::ffi::OsString>)> = vec![
("OPENLATCH_DIR", Some(openlatch_dir.as_os_str().to_owned())),
("OPENLATCH_HOOK_BIN", Some(hook_bin.as_os_str().to_owned())),
// `HmacKeyStore::load_or_create` falls through to the OS
// keychain, which raises a GUI dialog no test run can answer.
(
"OPENLATCH_SKIP_KEYRING",
Some(std::ffi::OsString::from("1")),
),
];
// This fixture WRITES, through `install_hooks` and then through the
// heal. Leaving Cline's seams alone points a walk at the
// developer's real `~/.cline`, whose `data/secrets.json` holds
// plaintext API keys.
env_pairs.extend(
crate::hooks::cline::absent_seams(root.path())
.into_iter()
.map(|(k, v)| (k, Some(v.into_os_string()))),
);
let env = crate::hooks::cline::EnvOverride::apply(env_pairs);
// `try_heal` reads the daemon token before it reinstalls anything,
// so a missing one would make every assertion below pass or fail
// for a reason that has nothing to do with the plugin.
std::fs::write(openlatch_dir.join("daemon.token"), "test-token").expect("daemon token");
let target = AgentTarget {
settings_path: hooks_dir.join("unused-for-a-directory-surface"),
binding: Arc::new(crate::hooks::binding::test_support::FakeBinding {
agent_type: "cline",
config_dir: root.path().to_path_buf(),
installable: true,
hook_surface_dir: Some(hooks_dir),
plugin_surface_dir: Some(plugin_dir.clone()),
// The `Directory` arm takes its ten from the writer's own
// list, so a fixture declaring events too would make it
// impossible to tell which list was used.
hook_event_types: &[],
load_bearing_events: &[],
daemon_channel: Some(crate::hooks::binding::DaemonChannel::OpenlatchDirArg),
..Default::default()
}),
};
crate::hooks::install_hooks(&*target.binding, 7443, "test-token")
.expect("the fixture installs the ten and the plugin");
Self {
_env: env,
_dir_lock: dir_lock,
_home_lock: home_lock,
_bin_lock: bin_lock,
_seam_lock: seam_lock,
root,
openlatch_dir,
plugin_dir,
target,
}
}
fn entry(&self) -> std::path::PathBuf {
crate::hooks::cline_plugin::entry_path(&self.plugin_dir)
}
/// The bytes the installer left at the entry path — what a heal has to
/// restore, read from disk rather than re-rendered here.
fn installed_body(&self) -> Vec<u8> {
std::fs::read(self.entry()).expect("the fixture installed a plugin")
}
fn reconciler(&self) -> (Reconciler, mpsc::Receiver<CloudEvent>) {
let (cloud_tx, cloud_rx) = mpsc::channel(64);
let r = Reconciler::new_with_sinks(
mpsc::channel(1).1,
vec![self.target.clone()],
self.openlatch_dir.clone(),
7443,
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)
}
}
/// The `hook_event` of every `tamper_healed` event on the channel.
fn heals(rx: &mut mpsc::Receiver<CloudEvent>) -> Vec<String> {
let mut found = Vec::new();
while let Ok(ce) = rx.try_recv() {
if ce.envelope["type"].as_str() == Some("ai.openlatch.security.tamper_healed") {
found.push(
ce.envelope["data"]["tamper"]["hook_event"]
.as_str()
.unwrap_or_default()
.to_string(),
);
}
}
found
}
/// A damaged plugin is rewritten — and the damage that matters is damage
/// the ownership marker cannot survive.
///
/// The premise is asserted rather than assumed: a corrupted `index.js`
/// fails `is_ours`, so `install` alone leaves it exactly where it is. Only
/// the state row makes the rewrite ours to make, which is the whole reason
/// §3a gives the plugin one.
#[test]
fn a_damaged_plugin_is_rewritten() {
let fx = PluginHost::new();
let want = fx.installed_body();
std::fs::write(fx.entry(), "corrupted\n").expect("corrupt the plugin");
assert!(
!crate::hooks::hook_files::is_ours("corrupted\n"),
"the premise: corruption breaks the ownership predicate, so a heal that \
asked the file would walk away from exactly this failure"
);
let (mut r, mut rx) = fx.reconciler();
r.do_reconcile();
assert_eq!(
std::fs::read(fx.entry()).expect("a readable plugin"),
want,
"the damaged plugin was not restored byte for byte"
);
assert!(
heals(&mut rx).contains(&crate::hooks::cline_plugin::PLUGIN_ENTRY_EVENT.to_string()),
"a repair that reaches no operator is a silent rewrite of the developer's disk"
);
assert_eq!(
std::fs::read_to_string(fx.plugin_dir.join("index.js.bak")).expect("a backup"),
"corrupted\n",
"the damaged original must survive the heal — `doctor --restore` is what \
the backup exists for, and the reinstall that follows the repair must not \
copy the healed body over it"
);
}
/// A missing file is a mismatch, so it is re-created — identical to the ten.
///
/// The whole directory goes, not just the file: `remove_dir_all` is what an
/// `rm -rf` of the plugin looks like, and the repair has to create the
/// directory again rather than assume one.
#[test]
fn a_deleted_plugin_is_restored() {
let fx = PluginHost::new();
let want = fx.installed_body();
std::fs::remove_dir_all(&fx.plugin_dir).expect("delete the plugin");
let (mut r, mut rx) = fx.reconciler();
r.do_reconcile();
assert_eq!(
std::fs::read(fx.entry()).expect("the plugin was not re-created"),
want
);
assert!(
heals(&mut rx).contains(&crate::hooks::cline_plugin::PLUGIN_ENTRY_EVENT.to_string()),
);
}
/// Heal repairs our artefact and **never** flips the developer's switch
/// (§3a.1).
///
/// With `openlatch` on `disabledPlugins` the plugin is installed and
/// switched off. Repairing `index.js` is ours to do — the file is ours.
/// Taking the id off that list is not, and `global-settings.json` has to
/// come out of a heal byte-identical: re-enabling enforcement the developer
/// turned off would be a change we made on their behalf and never reported.
#[test]
fn heal_never_edits_disabled_plugins() {
let fx = PluginHost::new();
let want = fx.installed_body();
let settings = fx
.root
.path()
.join("store")
.join("data")
.join("global-settings.json");
std::fs::create_dir_all(settings.parent().expect("a data directory"))
.expect("the data root");
let switched_off = serde_json::json!({
"disabledPlugins": [crate::hooks::cline_plugin::PLUGIN_ID],
})
.to_string();
std::fs::write(&settings, &switched_off).expect("the developer's switch");
// The premise, read back off disk rather than asserted about a literal:
// the fixture really has switched this plugin off.
let parsed: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&settings).expect("readable"))
.expect("the fixture wrote JSON");
let listed: Vec<String> = parsed["disabledPlugins"]
.as_array()
.expect("a list")
.iter()
.map(|v| v.as_str().unwrap_or_default().to_string())
.collect();
assert!(
crate::hooks::cline_plugin::is_disabled(Some(&listed)),
"the fixture did not actually disable the plugin, so this proves nothing"
);
std::fs::write(fx.entry(), "corrupted\n").expect("corrupt the plugin");
let (mut r, _rx) = fx.reconciler();
r.do_reconcile();
assert_eq!(
std::fs::read(fx.entry()).expect("a readable plugin"),
want,
"a disabled plugin is still OUR artefact and is still repaired"
);
assert_eq!(
std::fs::read_to_string(&settings).expect("readable"),
switched_off,
"heal edited the developer's plugin switch"
);
}
/// A detected agent this build cannot install into is never healed by
/// reinstall, and the reconciler does not report a heal that did not
/// happen.
///
/// `try_heal` is the reconciler's only route to `install_hooks`, and the
/// reconciler calls it once per tamper event. Cline is the first binding
/// that answers `installable() == false`: its `hook_config_path()` is the
/// asset root's `Hooks/` DIRECTORY, so an unguarded reinstall would create
/// that directory and hand `atomic_rewrite_jsonc` a path that is not a
/// file — again on every event, for as long as the drift stands.
///
/// The fake stands in for it rather than `ClineBinding` itself: the guard
/// is about `installable()`, not about Cline, and a fixture rooted in a
/// temp directory keeps the assertion below ("nothing was written") about
/// a path this test owns.
#[test]
fn heal_refuses_an_agent_with_no_writable_hook_surface() {
let root = tempfile::tempdir().expect("fixture root");
let openlatch_dir = root.path().join("openlatch");
let config_dir = root.path().join("agent");
std::fs::create_dir_all(&openlatch_dir).expect("openlatch dir");
std::fs::create_dir_all(&config_dir).expect("agent config dir");
// Present, deliberately. `try_heal` reads the daemon token before it
// reinstalls anything, so a missing token file would make this test
// pass for a reason that has nothing to do with the guard.
let token_file_path = openlatch_dir.join("daemon.token");
std::fs::write(&token_file_path, "test-token").expect("daemon token");
let target = AgentTarget {
settings_path: config_dir.join("settings.json"),
binding: Arc::new(crate::hooks::binding::test_support::FakeBinding {
config_dir,
installable: false,
..Default::default()
}),
};
// The premise, asserted rather than assumed — this is what makes the
// refusal below non-vacuous. The primitive skips a non-installable
// binding and answers `Ok` with no entries, so WITHOUT the guard in
// `try_heal` this target would be reported as healed.
assert!(
crate::hooks::install_hooks(&*target.binding, 7443, "test-token")
.expect("the primitive skips a non-installable agent rather than erroring")
.entries
.is_empty(),
"the primitive writes nothing for this binding"
);
let r = Reconciler::new(
mpsc::channel(1).1,
vec![target.clone()],
openlatch_dir,
7443,
token_file_path,
);
assert!(
r.try_heal(&target, None).is_err(),
"a heal that wrote nothing must not be reported as one that succeeded: \
`Ok` here becomes the outcome \"succeeded\" on a tamper_healed event"
);
assert!(
!target.settings_path.exists(),
"and nothing was written into the agent's config directory"
);
}
}