openlatch-client 0.6.10

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
//! In-memory `ContentHashCache` — bounded LRU keyed by absolute path.
//!
//! Lost on restart; rebuilt by initial inventory + periodic rescan. This is
//! NOT trust state — it's a transient view of "what's currently on disk" so
//! a native-hook event and the FS watcher's later event for the same content
//! don't both reach the cloud. The cloud is the source of truth for trust
//! verdicts (per `.claude/rules/config-monitor.md`).

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::Instant;

use dashmap::DashMap;

/// Composite cache key. `subpath` is `Some` for fan-out kinds (one envelope
/// per MCP server inside a single file) and `None` otherwise.
///
/// `agent` and `kind` are part of the key because one file can be several
/// artifacts. Several agents read one file (workspace `AGENTS.md`), and each
/// reports its own copy; one file is several kinds (Codex CLI's `config.toml`
/// is both the `hooks` perimeter and the `mcp` server list). Keyed on path
/// alone, one copy's scan would read another's entries as its own — suppress
/// its event as a duplicate, or report its servers removed.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CacheKey {
    pub path: PathBuf,
    pub agent: String,
    pub kind: String,
    pub subpath: Option<String>,
}

impl CacheKey {
    /// The path is folded through [`dedup_key`] so the two producers that feed
    /// this cache — the native hook, which reports the path as the agent wrote
    /// it, and the FS watcher, which reports it as the OS spells it — collide
    /// on Windows instead of each minting its own entry and emitting a
    /// duplicate event for one file. On Unix this is the identity.
    ///
    /// [`CacheEntry::path`] keeps the path as observed; only the lookup key is
    /// folded.
    pub fn new(path: PathBuf, agent: &str, kind: &str, subpath: Option<String>) -> Self {
        Self {
            path: crate::path_compat::dedup_key(&path),
            agent: agent.to_string(),
            kind: kind.to_string(),
            subpath,
        }
    }
}

/// One cached observation. `path_hash` and `content_hash` are SHA-256
/// digests stored as raw bytes (the wire format hex-encodes them).
#[derive(Debug, Clone)]
pub struct CacheEntry {
    pub path: PathBuf,
    pub subpath: Option<String>,
    pub path_hash: [u8; 32],
    pub content_hash: [u8; 32],
    pub last_observed: Instant,
    pub kind: String,
    pub agent: String,
}

impl CacheEntry {
    pub fn key(&self) -> CacheKey {
        CacheKey::new(
            self.path.clone(),
            &self.agent,
            &self.kind,
            self.subpath.clone(),
        )
    }
}

/// Bounded LRU cache.
///
/// `DashMap` provides concurrent access for the lookup hot path; a separate
/// `VecDeque<CacheKey>` under a single `Mutex` tracks LRU ordering for
/// eviction. Recency reordering happens only on insert, so reads don't
/// contend with eviction.
pub struct ContentHashCache {
    inner: DashMap<CacheKey, CacheEntry>,
    lru: Mutex<VecDeque<CacheKey>>,
    max_entries: usize,
}

impl ContentHashCache {
    /// Construct a new cache with `max_entries` capacity. A floor of 64
    /// applies regardless of the requested value to keep tiny caps from
    /// thrashing the LRU under realistic workloads.
    pub fn new(max_entries: usize) -> Self {
        let cap = max_entries.max(64);
        Self {
            inner: DashMap::new(),
            lru: Mutex::new(VecDeque::with_capacity(cap)),
            max_entries: cap,
        }
    }

    /// Insert or update. Returns the previous `content_hash` for the entry,
    /// if any. Triggers LRU eviction when size exceeds `max_entries`.
    pub fn insert(&self, entry: CacheEntry) -> Option<[u8; 32]> {
        let key = entry.key();
        let prev = self
            .inner
            .insert(key.clone(), entry)
            .map(|e| e.content_hash);

        let mut lru = self.lock_lru();
        lru.retain(|k| k != &key);
        lru.push_back(key);
        while lru.len() > self.max_entries {
            if let Some(evicted) = lru.pop_front() {
                self.inner.remove(&evicted);
            }
        }

        prev
    }

    /// Convenience lookup for entries with no subpath (the common
    /// non-fan-out case). For fan-out kinds use `get_subpath` or
    /// `entries_for_path`.
    pub fn get(&self, path: &Path, agent: &str, kind: &str) -> Option<CacheEntry> {
        self.get_subpath(path, agent, kind, None)
    }

    pub fn get_subpath(
        &self,
        path: &Path,
        agent: &str,
        kind: &str,
        subpath: Option<&str>,
    ) -> Option<CacheEntry> {
        let key = CacheKey::new(path.to_path_buf(), agent, kind, subpath.map(str::to_string));
        self.inner.get(&key).map(|r| r.clone())
    }

    /// All cached entries of one agent's `kind` that share `path`, regardless of subpath.
    /// Used by FS-watcher removal (the file is gone — every server inside it
    /// is gone too) and rescan removal detection.
    pub fn entries_for_path(&self, path: &Path, agent: &str, kind: &str) -> Vec<CacheEntry> {
        // Stored keys are folded by `CacheKey::new`; fold the needle too, or
        // this scans for a spelling the map cannot contain.
        let wanted = crate::path_compat::dedup_key(path);
        self.inner
            .iter()
            .filter(|r| r.key().path == wanted && r.key().agent == agent && r.key().kind == kind)
            .map(|r| r.clone())
            .collect()
    }

    pub fn remove(&self, path: &Path, agent: &str, kind: &str) -> Option<CacheEntry> {
        self.remove_subpath(path, agent, kind, None)
    }

    pub fn remove_subpath(
        &self,
        path: &Path,
        agent: &str,
        kind: &str,
        subpath: Option<&str>,
    ) -> Option<CacheEntry> {
        let key = CacheKey::new(path.to_path_buf(), agent, kind, subpath.map(str::to_string));
        self.lock_lru().retain(|k| k != &key);
        self.inner.remove(&key).map(|(_, v)| v)
    }

    /// Remove every entry of one agent's `kind` under `path` (all subpaths). Returns the
    /// removed entries — callers use them to emit `removed` envelopes per
    /// server.
    pub fn remove_all_under_path(&self, path: &Path, agent: &str, kind: &str) -> Vec<CacheEntry> {
        let wanted = crate::path_compat::dedup_key(path);
        let keys: Vec<CacheKey> = self
            .inner
            .iter()
            .filter(|r| r.key().path == wanted && r.key().agent == agent && r.key().kind == kind)
            .map(|r| r.key().clone())
            .collect();
        let mut removed = Vec::with_capacity(keys.len());
        let mut lru = self.lock_lru();
        for key in keys {
            lru.retain(|k| k != &key);
            if let Some((_, v)) = self.inner.remove(&key) {
                removed.push(v);
            }
        }
        removed
    }

    /// Lock the LRU deque, recovering from poison. A poisoned lock means a
    /// previous holder panicked; the deque is still well-formed (we never
    /// leave it half-mutated), so we recover the inner data and continue.
    /// Silently swallowing poison would desync `lru` and `inner`.
    fn lock_lru(&self) -> std::sync::MutexGuard<'_, VecDeque<CacheKey>> {
        match self.lru.lock() {
            Ok(g) => g,
            Err(poisoned) => {
                tracing::warn!("ContentHashCache LRU mutex was poisoned — recovering");
                poisoned.into_inner()
            }
        }
    }

    pub fn len(&self) -> usize {
        self.inner.len()
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Snapshot all entries into an owned Vec. Releases internal locks
    /// before returning so callers can iterate without holding them.
    pub fn snapshot(&self) -> Vec<CacheEntry> {
        self.inner.iter().map(|r| r.clone()).collect()
    }

    /// Compare-and-update. Returns `true` when the new entry's
    /// `content_hash` differs from any cached value (and inserts it),
    /// `false` when it matches (cache untouched). Used by the FS watcher
    /// to suppress duplicate events when a native hook has already
    /// recorded the same content.
    pub fn check_and_update(&self, entry: CacheEntry) -> bool {
        let key = entry.key();
        if let Some(existing) = self.inner.get(&key) {
            if existing.content_hash == entry.content_hash {
                return false;
            }
        }
        self.insert(entry);
        true
    }
}

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

    fn entry(path: &str, content: u8) -> CacheEntry {
        CacheEntry {
            path: PathBuf::from(path),
            subpath: None,
            path_hash: [0u8; 32],
            content_hash: [content; 32],
            last_observed: Instant::now(),
            kind: "mcp".to_string(),
            agent: "claude-code".to_string(),
        }
    }

    fn subpath_entry(path: &str, subpath: &str, content: u8) -> CacheEntry {
        CacheEntry {
            path: PathBuf::from(path),
            subpath: Some(subpath.to_string()),
            path_hash: [0u8; 32],
            content_hash: [content; 32],
            last_observed: Instant::now(),
            kind: "mcp".to_string(),
            agent: "claude-code".to_string(),
        }
    }

    #[test]
    fn insert_and_get_round_trip() {
        let cache = ContentHashCache::new(64);
        cache.insert(entry("/tmp/a", 1));
        let got = cache
            .get(Path::new("/tmp/a"), "claude-code", "mcp")
            .unwrap();
        assert_eq!(got.content_hash, [1u8; 32]);
    }

    #[test]
    fn insert_returns_previous_hash_on_replace() {
        let cache = ContentHashCache::new(64);
        assert!(cache.insert(entry("/tmp/a", 1)).is_none());
        let prev = cache.insert(entry("/tmp/a", 2)).unwrap();
        assert_eq!(prev, [1u8; 32]);
    }

    #[test]
    fn remove_clears_both_inner_and_lru() {
        let cache = ContentHashCache::new(64);
        cache.insert(entry("/tmp/a", 1));
        let removed = cache
            .remove(Path::new("/tmp/a"), "claude-code", "mcp")
            .unwrap();
        assert_eq!(removed.content_hash, [1u8; 32]);
        assert!(cache
            .get(Path::new("/tmp/a"), "claude-code", "mcp")
            .is_none());
        assert!(cache.is_empty());
    }

    #[test]
    fn check_and_update_returns_false_on_identical_hash() {
        let cache = ContentHashCache::new(64);
        assert!(cache.check_and_update(entry("/tmp/a", 1)));
        assert!(!cache.check_and_update(entry("/tmp/a", 1)));
    }

    #[test]
    fn check_and_update_returns_true_on_changed_hash() {
        let cache = ContentHashCache::new(64);
        cache.check_and_update(entry("/tmp/a", 1));
        assert!(cache.check_and_update(entry("/tmp/a", 2)));
        assert_eq!(
            cache
                .get(Path::new("/tmp/a"), "claude-code", "mcp")
                .unwrap()
                .content_hash,
            [2u8; 32]
        );
    }

    #[test]
    fn lru_evicts_oldest_when_over_capacity() {
        // Floor of 64 means we need at least 65 inserts to see eviction.
        let cache = ContentHashCache::new(0);
        assert_eq!(cache.max_entries, 64);
        for i in 0..65u8 {
            cache.insert(entry(&format!("/tmp/{i}"), i));
        }
        assert_eq!(cache.len(), 64);
        // The oldest path (/tmp/0) should have been evicted.
        assert!(cache
            .get(Path::new("/tmp/0"), "claude-code", "mcp")
            .is_none());
        assert!(cache
            .get(Path::new("/tmp/64"), "claude-code", "mcp")
            .is_some());
    }

    #[test]
    fn touching_an_entry_updates_recency() {
        let cache = ContentHashCache::new(64);
        for i in 0..64u8 {
            cache.insert(entry(&format!("/tmp/{i}"), i));
        }
        // Re-insert /tmp/0 — moves it to the back of the LRU.
        cache.insert(entry("/tmp/0", 99));
        // Now insert one more — /tmp/1 (next-oldest) should be evicted, not /tmp/0.
        cache.insert(entry("/tmp/new", 1));
        assert!(cache
            .get(Path::new("/tmp/0"), "claude-code", "mcp")
            .is_some());
        assert!(cache
            .get(Path::new("/tmp/1"), "claude-code", "mcp")
            .is_none());
        assert!(cache
            .get(Path::new("/tmp/new"), "claude-code", "mcp")
            .is_some());
    }

    #[test]
    fn snapshot_returns_all_entries() {
        let cache = ContentHashCache::new(64);
        cache.insert(entry("/tmp/a", 1));
        cache.insert(entry("/tmp/b", 2));
        let snap = cache.snapshot();
        assert_eq!(snap.len(), 2);
    }

    #[test]
    fn same_path_different_subpath_coexist() {
        let cache = ContentHashCache::new(64);
        cache.insert(subpath_entry("/tmp/a", "ctx7", 1));
        cache.insert(subpath_entry("/tmp/a", "github", 2));
        let entries = cache.entries_for_path(Path::new("/tmp/a"), "claude-code", "mcp");
        assert_eq!(entries.len(), 2);
        assert_eq!(
            cache
                .get_subpath(Path::new("/tmp/a"), "claude-code", "mcp", Some("ctx7"))
                .unwrap()
                .content_hash,
            [1u8; 32]
        );
        assert_eq!(
            cache
                .get_subpath(Path::new("/tmp/a"), "claude-code", "mcp", Some("github"))
                .unwrap()
                .content_hash,
            [2u8; 32]
        );
    }

    #[test]
    fn remove_all_under_path_clears_every_subpath() {
        let cache = ContentHashCache::new(64);
        cache.insert(subpath_entry("/tmp/a", "ctx7", 1));
        cache.insert(subpath_entry("/tmp/a", "github", 2));
        cache.insert(entry("/tmp/other", 9));
        let removed = cache.remove_all_under_path(Path::new("/tmp/a"), "claude-code", "mcp");
        assert_eq!(removed.len(), 2);
        assert!(cache
            .entries_for_path(Path::new("/tmp/a"), "claude-code", "mcp")
            .is_empty());
        assert!(cache
            .get(Path::new("/tmp/other"), "claude-code", "mcp")
            .is_some());
    }

    /// One file, two kinds — and one file, two agents: no copy sees or
    /// removes another's entries.
    #[test]
    fn kinds_sharing_a_path_stay_apart() {
        let cache = ContentHashCache::new(64);
        cache.insert(subpath_entry("/tmp/config.toml", "ctx7", 1));
        let mut hooks = entry("/tmp/config.toml", 2);
        hooks.kind = "hooks".to_string();
        cache.insert(hooks);

        assert_eq!(
            cache
                .entries_for_path(Path::new("/tmp/config.toml"), "claude-code", "hooks")
                .len(),
            1
        );
        let removed =
            cache.remove_all_under_path(Path::new("/tmp/config.toml"), "claude-code", "hooks");
        assert_eq!(removed.len(), 1);
        assert!(cache
            .get_subpath(
                Path::new("/tmp/config.toml"),
                "claude-code",
                "mcp",
                Some("ctx7")
            )
            .is_some());

        let mut codex = subpath_entry("/tmp/config.toml", "ctx7", 3);
        codex.agent = "codex-cli".to_string();
        cache.insert(codex);
        let claude_ctx7 = || {
            cache.get_subpath(
                Path::new("/tmp/config.toml"),
                "claude-code",
                "mcp",
                Some("ctx7"),
            )
        };
        assert_eq!(
            claude_ctx7().unwrap().content_hash,
            [1u8; 32],
            "another agent's copy does not overwrite this one"
        );
        let codex_removed =
            cache.remove_all_under_path(Path::new("/tmp/config.toml"), "codex-cli", "mcp");
        assert_eq!(codex_removed.len(), 1);
        assert!(claude_ctx7().is_some());
    }
}