openlatch-client 0.5.4

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
pub mod diff;
pub mod hmac;
pub mod key;
pub mod marker;

use std::path::Path;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::error::{OlError, ERR_STATE_FILE_CORRUPT, ERR_STATE_FILE_WRITE_FAILED};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookStateFile {
    pub schema_version: u32,
    pub generated_at: DateTime<Utc>,
    pub hmac_key_id: String,
    pub entries: Vec<StateEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateEntry {
    pub id: String,
    pub agent: String,
    pub settings_path_hash: String,
    pub hook_event: String,
    pub expected_entry_hmac: String,
    pub daemon_port_at_install: u16,
    pub daemon_token_fp: String,
    /// What we wrote, for an agent whose hook surface is a **directory of
    /// scripts** rather than one JSON file.
    ///
    /// `None` for every JSON-file agent, and `None` in every state file written
    /// before this field existed — hence `#[serde(default)]`, which is what
    /// lets an install predating it keep loading, and
    /// `skip_serializing_if = "Option::is_none"`, which leaves those files
    /// byte-identical when they are rewritten.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub descriptor: Option<FileDescriptor>,
    pub v: u8,
}

/// What we wrote to one hook-script path, as the state file records it.
///
/// A `StateEntry` has only ever carried `expected_entry_hmac`, and **an HMAC is
/// not reversible**: health and the reconciler need the body hash they should
/// find on disk, so it has to be *stored* rather than recovered from the row.
///
/// It stays a JSON object on purpose. [`hmac::compute_entry_hmac`] is unchanged
/// by this — the non-object rejection is one frame down, in its private
/// `canonicalize_entry` — so a descriptor is signed for tamper-evidence through
/// exactly the path every other entry already goes through.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileDescriptor {
    /// Absolute path of the script, as written.
    pub path: String,
    /// Lowercase-hex SHA-256 of the file's **whole** body, marker line
    /// included — the bytes a later read must hash to.
    ///
    /// Distinct from, and not comparable with, the hash *inside* the marker
    /// line, which is taken over the body with that line removed so that a
    /// script can describe itself with no state file present at all.
    pub sha256: String,
    /// The mode the writer left the file in — `0o755` on Unix.
    ///
    /// The writer's contract rather than a `stat`, so it reads the same on
    /// every platform and a file whose real mode disagrees is drift, which is
    /// the question health is asking.
    pub mode: u32,
}

const STATE_FILE_NAME: &str = "hook-state.json";
const CURRENT_SCHEMA_VERSION: u32 = 1;

/// Shape version of a single [`StateEntry`], carried in its `v` field.
///
/// `2` since the entry gained [`StateEntry::descriptor`]. Deliberately **not**
/// [`CURRENT_SCHEMA_VERSION`]: `load` rejects a *future* `schema_version`
/// outright, so moving that would make an older client refuse a state file it
/// can in fact read — the new field is optional and defaulted precisely so it
/// does not have to.
pub const STATE_ENTRY_VERSION: u8 = 2;

impl HookStateFile {
    pub fn new(hmac_key_id: String) -> Self {
        Self {
            schema_version: CURRENT_SCHEMA_VERSION,
            generated_at: Utc::now(),
            hmac_key_id,
            entries: Vec::new(),
        }
    }

    pub fn load(openlatch_dir: &Path) -> Result<Option<Self>, OlError> {
        let path = openlatch_dir.join(STATE_FILE_NAME);
        if !path.exists() {
            return Ok(None);
        }

        let content = std::fs::read_to_string(&path).map_err(|e| {
            OlError::new(
                ERR_STATE_FILE_CORRUPT,
                format!("Cannot read hook state file: {e}"),
            )
        })?;

        let state: Self = serde_json::from_str(&content).map_err(|e| {
            OlError::new(
                ERR_STATE_FILE_CORRUPT,
                format!("Cannot parse hook state file: {e}"),
            )
            .with_suggestion("Delete ~/.openlatch/hook-state.json and re-run `openlatch init`.")
        })?;

        if state.schema_version > CURRENT_SCHEMA_VERSION {
            return Err(OlError::new(
                ERR_STATE_FILE_CORRUPT,
                format!(
                    "Hook state file has schema_version {} (expected <= {CURRENT_SCHEMA_VERSION})",
                    state.schema_version
                ),
            )
            .with_suggestion("Upgrade openlatch to the latest version."));
        }

        Ok(Some(state))
    }

    pub fn save(&mut self, openlatch_dir: &Path) -> Result<(), OlError> {
        let path = openlatch_dir.join(STATE_FILE_NAME);

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                OlError::new(
                    ERR_STATE_FILE_WRITE_FAILED,
                    format!("Cannot create state file directory: {e}"),
                )
            })?;
        }

        self.generated_at = Utc::now();

        let content = serde_json::to_string_pretty(self).map_err(|e| {
            OlError::new(
                ERR_STATE_FILE_WRITE_FAILED,
                format!("Cannot serialize hook state: {e}"),
            )
        })?;

        let tmp_path = path.with_extension("json.tmp");
        std::fs::write(&tmp_path, &content).map_err(|e| {
            OlError::new(
                ERR_STATE_FILE_WRITE_FAILED,
                format!("Cannot write state file: {e}"),
            )
        })?;
        std::fs::rename(&tmp_path, &path).map_err(|e| {
            OlError::new(
                ERR_STATE_FILE_WRITE_FAILED,
                format!("Cannot rename state file: {e}"),
            )
        })?;

        // Best-effort, as it has always been here: a state file that cannot be
        // locked down is still a state file the daemon needs.
        let _ = crate::fs_secure::restrict_to_owner(&path);

        Ok(())
    }

    pub fn find_entry(&self, entry_id: &str) -> Option<&StateEntry> {
        self.entries.iter().find(|e| e.id == entry_id)
    }

    /// Record one hook registration, replacing the row it supersedes.
    ///
    /// Keyed on the **natural key** — this agent, this config file, this event
    /// — because that is the triple `install_hooks` writes exactly one of. It
    /// was keyed on `entry.id`, and install mints a fresh UUID per entry per
    /// run, so the id looked for was one that by construction could not be
    /// there: every reinstall appended a full set and nothing ever pruned.
    ///
    /// All three parts are load-bearing. Two agents share one state file and
    /// register the same event names, so dropping `agent` or
    /// `settings_path_hash` from the key would make installing the second
    /// agent delete the first agent's rows.
    pub fn upsert_entry(&mut self, entry: StateEntry) {
        let same_registration = |e: &StateEntry| {
            e.agent == entry.agent
                && e.settings_path_hash == entry.settings_path_hash
                && e.hook_event == entry.hook_event
        };
        if let Some(existing) = self.entries.iter_mut().find(|e| same_registration(e)) {
            *existing = entry;
        } else {
            self.entries.push(entry);
        }
    }

    /// Drop the row registered for `(agent, settings_path_hash, hook_event)`,
    /// and say whether one was there.
    ///
    /// [`Self::upsert_entry`]'s inverse, keyed identically and for the same
    /// reason: two agents share one state file and register the same event
    /// names, so a narrower key would delete another agent's row.
    ///
    /// Uninstall is what needs it. A row left behind after its artefact is
    /// deleted is not inert — the reconciler reads a missing file as drift and
    /// heals it by reinstalling, so the row alone is enough to re-create what
    /// uninstall just removed, on the next poll, silently.
    pub fn remove_entry(
        &mut self,
        agent: &str,
        settings_path_hash: &str,
        hook_event: &str,
    ) -> bool {
        let before = self.entries.len();
        self.entries.retain(|e| {
            !(e.agent == agent
                && e.settings_path_hash == settings_path_hash
                && e.hook_event == hook_event)
        });
        self.entries.len() != before
    }
}

pub fn hash_settings_path(path: &Path) -> String {
    use sha2::{Digest, Sha256};
    let path_str = path.to_string_lossy();
    let hash = Sha256::digest(path_str.as_bytes());
    format!(
        "sha256:{}",
        crate::core::hook_state::key::hex::encode(&hash)
    )
}

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

    #[test]
    fn state_file_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let mut state = HookStateFile::new("kid-01".into());
        state.entries.push(StateEntry {
            id: "test-entry-id".into(),
            agent: "claude-code".into(),
            settings_path_hash: "sha256:abc123".into(),
            hook_event: "PreToolUse".into(),
            expected_entry_hmac: "hmac-value".into(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp-value".into(),
            descriptor: None,
            v: 1,
        });
        state.save(dir.path()).unwrap();

        let loaded = HookStateFile::load(dir.path()).unwrap().unwrap();
        assert_eq!(loaded.schema_version, 1);
        assert_eq!(loaded.hmac_key_id, "kid-01");
        assert_eq!(loaded.entries.len(), 1);
        assert_eq!(loaded.entries[0].id, "test-entry-id");
    }

    #[test]
    fn load_returns_none_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        assert!(HookStateFile::load(dir.path()).unwrap().is_none());
    }

    #[test]
    fn rejects_future_schema_version() {
        let dir = tempfile::tempdir().unwrap();
        let content = r#"{"schema_version": 99, "generated_at": "2026-04-16T12:00:00Z", "hmac_key_id": "kid-01", "entries": []}"#;
        std::fs::write(dir.path().join(STATE_FILE_NAME), content).unwrap();
        let err = HookStateFile::load(dir.path()).unwrap_err();
        assert_eq!(err.code, "OL-1901");
    }

    #[test]
    fn upsert_replaces_existing() {
        let mut state = HookStateFile::new("kid-01".into());
        state.upsert_entry(StateEntry {
            id: "entry-1".into(),
            agent: "claude-code".into(),
            settings_path_hash: "sha256:abc".into(),
            hook_event: "PreToolUse".into(),
            expected_entry_hmac: "old-hmac".into(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp".into(),
            descriptor: None,
            v: 1,
        });
        state.upsert_entry(StateEntry {
            id: "entry-1".into(),
            agent: "claude-code".into(),
            settings_path_hash: "sha256:abc".into(),
            hook_event: "PreToolUse".into(),
            expected_entry_hmac: "new-hmac".into(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp".into(),
            descriptor: None,
            v: 1,
        });
        assert_eq!(state.entries.len(), 1);
        assert_eq!(state.entries[0].expected_entry_hmac, "new-hmac");
    }

    /// A reinstall must replace the row it supersedes, not sit beside it.
    ///
    /// `install_hooks` mints a fresh UUID for every entry on every run, so an
    /// upsert keyed on the id can never match a reinstall — it appends. One
    /// row per event per install, forever: every `init`, every
    /// `doctor --fix`, every heal. The live sandbox that surfaced this had
    /// 2,412 rows and a 1 MB state file where 12 rows was the whole truth, and
    /// the reconciler re-reads that file on every filesystem event and every
    /// 30 s poll.
    ///
    /// The identity of a hook registration is the triple below, because that
    /// is what install writes exactly one of: this agent, this config file,
    /// this event.
    #[test]
    fn upsert_replaces_a_reinstall_under_a_new_id() {
        let entry = |id: &str, hmac: &str| StateEntry {
            id: id.into(),
            agent: "claude-code".into(),
            settings_path_hash: "sha256:abc".into(),
            hook_event: "PreToolUse".into(),
            expected_entry_hmac: hmac.into(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp".into(),
            descriptor: None,
            v: 1,
        };

        let mut state = HookStateFile::new("kid-01".into());
        state.upsert_entry(entry("01a0759e-first", "old-hmac"));
        state.upsert_entry(entry("01a075f4-second", "new-hmac"));

        assert_eq!(
            state.entries.len(),
            1,
            "a reinstall of the same event, in the same file, for the same agent is one row"
        );
        assert_eq!(state.entries[0].expected_entry_hmac, "new-hmac");
        assert_eq!(state.entries[0].id, "01a075f4-second");
    }

    /// The triple is the key, and every part of it separates.
    ///
    /// Two agents share one state file, and an agent registers the same event
    /// names as its neighbour — collapsing on `hook_event` alone would make
    /// installing the second agent delete the first agent's rows, which is the
    /// same class of bug in the other direction.
    #[test]
    fn upsert_keeps_rows_that_differ_in_any_part_of_the_key() {
        let entry = |agent: &str, path: &str, event: &str| StateEntry {
            id: uuid::Uuid::now_v7().to_string(),
            agent: agent.into(),
            settings_path_hash: path.into(),
            hook_event: event.into(),
            expected_entry_hmac: "hmac".into(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp".into(),
            descriptor: None,
            v: 1,
        };

        let mut state = HookStateFile::new("kid-01".into());
        state.upsert_entry(entry("claude-code", "sha256:a", "PreToolUse"));
        state.upsert_entry(entry("codex-cli", "sha256:b", "PreToolUse"));
        state.upsert_entry(entry("claude-code", "sha256:a", "SessionEnd"));
        // Same agent, same event, relocated config directory.
        state.upsert_entry(entry("claude-code", "sha256:c", "PreToolUse"));

        assert_eq!(state.entries.len(), 4);
    }

    #[test]
    fn hash_settings_path_is_deterministic() {
        let p = Path::new("/home/user/.claude/settings.json");
        let h1 = hash_settings_path(p);
        let h2 = hash_settings_path(p);
        assert_eq!(h1, h2);
        assert!(h1.starts_with("sha256:"));
    }

    #[test]
    fn hash_settings_path_never_contains_literal_path() {
        let p = Path::new("/home/user/.claude/settings.json");
        let h = hash_settings_path(p);
        assert!(!h.contains(".claude"));
        assert!(!h.contains("settings.json"));
    }

    #[test]
    #[cfg(unix)]
    fn state_file_mode_0600() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let mut state = HookStateFile::new("kid-01".into());
        state.save(dir.path()).unwrap();
        let meta = std::fs::metadata(dir.path().join(STATE_FILE_NAME)).unwrap();
        assert_eq!(meta.permissions().mode() & 0o777, 0o600);
    }
}