openlatch-client 0.5.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! One answer to "what does a healthy hook install look like?".
//!
//! The question used to be re-derived in three places with three different
//! answers, and #165 is what that divergence costs:
//!
//! - `doctor`'s Check 5 asked "does the file contain these substrings?"
//! - `doctor --fix`'s `heal_hooks` asked the same substring question, so an
//!   entry that *existed* but pointed at a binary that did not was considered
//!   healthy and `--fix` left every command untouched.
//! - `doctor`'s `check_hook_binding` asked the real question — does the command
//!   resolve to a file that exists? — and reported one `ERR Hook binary missing`
//!   per configured event,
//!   while the repair path right next to it declared everything fine.
//!
//! This module owns the predicate. Everything that needs to know whether an
//! install is healthy — diagnose, repair, or report — reads the same struct,
//! so a diagnostic and its own fix can no longer disagree.

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

use crate::core::hook_state::{FileDescriptor, HookStateFile};
use crate::error::OlError;
use crate::hooks::binding::AgentBinding;

/// The state of the OpenLatch hook entries in an agent's settings file.
#[derive(Debug, Clone, Default)]
pub struct HookHealth {
    /// What the hook command should point at, per `resolve_hook_binary_path()`.
    pub expected_bin: PathBuf,
    /// Load-bearing events with no OpenLatch-owned entry at all.
    pub missing_events: Vec<String>,
    /// Binary paths referenced by a hook command that do not exist on disk.
    /// This is the #165 outage: 12 entries present, every one of them dead.
    pub missing_bin: Vec<String>,
    /// Binary paths that exist but are not the current resolution — a stale
    /// link after `cargo install` or a tarball upgrade.
    pub drifted_bin: Vec<String>,
    /// How many OpenLatch-owned hook commands were found.
    pub commands: usize,
}

impl HookHealth {
    /// Whether every load-bearing event is present and every command resolves
    /// to the binary this install actually ships.
    pub fn is_healthy(&self) -> bool {
        self.commands > 0
            && self.missing_events.is_empty()
            && self.missing_bin.is_empty()
            && self.drifted_bin.is_empty()
    }

    /// Whether a reinstall would fix what is wrong.
    ///
    /// Deliberately the negation of [`is_healthy`]: a dangling or stale command
    /// is repaired by rewriting it, exactly like a missing one. Treating only
    /// absence as repairable is what left `doctor --fix` unable to fix the
    /// condition `doctor` had just diagnosed.
    ///
    /// [`is_healthy`]: HookHealth::is_healthy
    pub fn needs_reinstall(&self) -> bool {
        !self.is_healthy()
    }
}

/// Inspect a parsed settings.json against the binding that owns it.
///
/// The load-bearing event list is the **binding's**, never a shared constant:
/// judging every agent on Claude Code's three names is the containment-line
/// violation this signature removes. An agent that registers a different set is
/// judged on its set.
pub fn inspect(settings: &serde_json::Value, binding: &dyn AgentBinding) -> HookHealth {
    let expected_bin = super::resolve_hook_binary_path();
    let mut health = HookHealth {
        expected_bin: expected_bin.clone(),
        ..Default::default()
    };

    let events = openlatch_hook_events(settings);
    for required in binding.load_bearing_events() {
        if !events.iter().any(|(event, _)| event == required) {
            health.missing_events.push((*required).to_string());
        }
    }

    for (_, command) in &events {
        health.commands += 1;
        let Some(bin) = extract_quoted_binary(command) else {
            continue;
        };
        let bin_path = PathBuf::from(&bin);
        if !bin_path.exists() {
            health.missing_bin.push(bin);
        } else if bin_path != expected_bin {
            health.drifted_bin.push(bin);
        }
    }
    health.missing_bin.sort();
    health.missing_bin.dedup();
    health.drifted_bin.sort();
    health.drifted_bin.dedup();

    health
}

/// Inspect a settings file on disk.
///
/// A file that cannot be read or parsed is not reported as "healthy but
/// unreadable" — the caller gets the error and decides. `heal_hooks` treats an
/// absent file as "reinstall", since `install_hooks` creates it.
///
/// # Errors
///
/// Returns the I/O error as `OL-1401`, or the parse error from
/// [`jsonc::parse_settings_value`] unchanged.
///
/// [`jsonc::parse_settings_value`]: super::jsonc::parse_settings_value
pub fn inspect_file(
    settings_path: &Path,
    binding: &dyn AgentBinding,
) -> Result<HookHealth, OlError> {
    let raw = std::fs::read_to_string(settings_path).map_err(|e| {
        OlError::new(
            crate::error::ERR_HOOK_WRITE_FAILED,
            format!("Cannot read '{}': {e}", settings_path.display()),
        )
    })?;
    let parsed = super::jsonc::parse_settings_value(&raw)?;
    Ok(inspect(&parsed, binding))
}

// ---------------------------------------------------------------------------
// The file-shaped half: a directory of scripts rather than one JSON document
// ---------------------------------------------------------------------------

/// The state of the hook **scripts** in a directory hook surface.
///
/// [`HookHealth`]'s sibling, and a separate type rather than a widened one:
/// everything above this line is JSON-shaped — it parses a settings document
/// and pulls commands out of marked entries — and a shell script has no
/// entries, no marker object and no command string to extract. Sharing a struct
/// would mean fields that are always empty on one side or the other, and a
/// caller unable to tell which question it had actually asked.
#[derive(Debug, Clone, Default)]
pub struct DirectoryHookHealth {
    /// The directory inspected.
    pub hooks_dir: PathBuf,
    /// Registered events with nothing at their script path at all.
    pub missing_files: Vec<String>,
    /// Script paths holding a file that fails the ownership predicate: the
    /// developer's, never rewritten and never removed, reported here so a
    /// reader knows why the install is short.
    pub foreign_files: Vec<String>,
    /// Scripts that are ours and whose bytes no longer hash to the descriptor
    /// recorded at install. Tamper, or a half-finished upgrade; a reinstall is
    /// the repair.
    pub drifted_files: Vec<String>,
    /// Scripts that are ours with **no stored descriptor to check against** —
    /// the state file was lost, or predates the field.
    ///
    /// Not drift, and deliberately not part of [`Self::is_healthy`]: the marker
    /// line carries a hash of the body with itself removed, so a file that
    /// satisfies the predicate has already proved it is intact and ours with no
    /// external record at all. Calling that drift would put a standing red on
    /// every host whose `hook-state.json` was deleted, and heal nothing.
    pub unverified_files: Vec<String>,
    /// How many registered events have a script of ours on disk.
    pub files: usize,
}

impl DirectoryHookHealth {
    /// Whether every registered event has a script of ours whose bytes are the
    /// ones we wrote.
    pub fn is_healthy(&self) -> bool {
        self.files > 0
            && self.missing_files.is_empty()
            && self.foreign_files.is_empty()
            && self.drifted_files.is_empty()
    }

    /// Whether a reinstall would fix what is wrong — [`Self::is_healthy`]'s
    /// negation, exactly as it is for [`HookHealth`].
    ///
    /// A foreign file counts even though a reinstall will not touch it: the
    /// reinstall is still the right action for the others, and the writer's own
    /// collision rule is what keeps the developer's file intact through it.
    pub fn needs_reinstall(&self) -> bool {
        !self.is_healthy()
    }
}

/// Inspect a directory hook surface against the binding that owns it and the
/// descriptors install recorded.
///
/// Three questions per file, which is the whole of the predicate: does it
/// exist, does it satisfy the ownership predicate, and does its SHA-256 match
/// the stored descriptor.
///
/// The event list is the **binding's** — never a constant naming one agent's
/// ten — for the reason [`inspect`] takes the load-bearing list from the
/// binding: an agent that registers a different set is judged on its set. A
/// binding that registers nothing reports zero files and is therefore not
/// healthy, which is the honest answer for a surface nothing was written to.
///
/// `expected` maps a hook event to the descriptor recorded for it; build it
/// with [`tracked_descriptors`]. An event missing from it is *unverified*, not
/// drifted — see [`DirectoryHookHealth::unverified_files`].
///
/// **Reads, never writes.** A path that cannot be read at all — a directory, a
/// device node, a file this user has no permission for — counts as foreign:
/// whatever it is, it is not a script we wrote, and the action for every one of
/// them is the same.
pub fn inspect_directory(
    hooks_dir: &Path,
    binding: &dyn AgentBinding,
    expected: &BTreeMap<String, FileDescriptor>,
) -> DirectoryHookHealth {
    let mut health = DirectoryHookHealth {
        hooks_dir: hooks_dir.to_path_buf(),
        ..Default::default()
    };

    for event in binding.hook_event_types() {
        let name = super::hook_files::hook_file_name(event);
        let path = hooks_dir.join(&name);

        // Bytes, converted lossily, rather than `read_to_string`: a non-UTF-8
        // file at one of our paths is emphatically not ours, and making it an
        // I/O error would turn somebody else's file into a failed diagnostic.
        // The replacement character can only ever FAIL the predicate.
        let body = match std::fs::read(&path) {
            Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                health.missing_files.push(name);
                continue;
            }
            Err(_) => {
                health.foreign_files.push(name);
                continue;
            }
        };

        if !super::hook_files::is_ours(&body) {
            health.foreign_files.push(name);
            continue;
        }

        health.files += 1;
        match expected.get(*event) {
            None => health.unverified_files.push(name),
            Some(descriptor) if descriptor.sha256 != super::hook_files::sha256_hex(&body) => {
                health.drifted_files.push(name);
            }
            Some(_) => {}
        }
    }

    health
}

/// The descriptors recorded for one directory surface, keyed by hook event.
///
/// The rows are keyed to the **directory**, which is what `install_hooks` wrote
/// them under: the natural key is `(agent, settings_path_hash, hook_event)` and
/// `hook_event` already separates the files from one another, so hashing each
/// script's own path would make the rows unfindable from the surface the
/// binding reports.
///
/// An entry with no descriptor — every JSON-file agent's, and any row written
/// before the field existed — is skipped rather than defaulted, so
/// [`inspect_directory`] sees *no record* rather than a record that disagrees.
pub fn tracked_descriptors(
    state: &HookStateFile,
    hooks_dir: &Path,
) -> BTreeMap<String, FileDescriptor> {
    let surface_hash = crate::core::hook_state::hash_settings_path(hooks_dir);
    state
        .entries
        .iter()
        .filter(|entry| entry.settings_path_hash == surface_hash)
        .filter_map(|entry| {
            entry
                .descriptor
                .clone()
                .map(|descriptor| (entry.hook_event.clone(), descriptor))
        })
        .collect()
}

/// Every `(event, command)` pair owned by OpenLatch, identified by the
/// `_openlatch` marker rather than by scanning for substrings.
pub fn openlatch_hook_events(settings: &serde_json::Value) -> Vec<(String, String)> {
    let Some(hooks) = settings.get("hooks").and_then(|v| v.as_object()) else {
        return Vec::new();
    };
    let mut out: Vec<(String, String)> = Vec::new();
    for (event, entries) in hooks {
        let Some(entries) = entries.as_array() else {
            continue;
        };
        for entry in entries {
            if !matches!(
                entry.get("_openlatch"),
                Some(serde_json::Value::Bool(true)) | Some(serde_json::Value::Object(_))
            ) {
                continue;
            }
            let Some(inner) = entry.get("hooks").and_then(|v| v.as_array()) else {
                continue;
            };
            for h in inner {
                if let Some(cmd) = h.get("command").and_then(|v| v.as_str()) {
                    out.push((event.clone(), cmd.to_string()));
                }
            }
        }
    }
    out
}

/// The hook command we write always quotes the binary path as its first token
/// (so spaces in Windows paths survive); everything between the first pair of
/// double quotes is the path.
pub fn extract_quoted_binary(command: &str) -> Option<String> {
    let start = command.find('"')? + 1;
    let end = command[start..].find('"')? + start;
    if start == end {
        return None;
    }
    Some(command[start..end].to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hooks::bindings::claude_code::ClaudeCodeBinding;
    use tempfile::TempDir;

    /// A binding with resolved paths that no test reads — every assertion here
    /// is about the settings value, and the binding supplies only the
    /// load-bearing event list.
    fn claude() -> ClaudeCodeBinding {
        ClaudeCodeBinding {
            claude_dir: PathBuf::from("/home/test/.claude"),
            settings_path: PathBuf::from("/home/test/.claude/settings.json"),
        }
    }

    fn settings_with(command: &str) -> serde_json::Value {
        let entry = || {
            serde_json::json!({
                "matcher": "*",
                "_openlatch": { "entry_id": "test" },
                "hooks": [{ "type": "command", "command": command }]
            })
        };
        serde_json::json!({
            "hooks": {
                "PreToolUse": [entry()],
                "UserPromptSubmit": [entry()],
                "Stop": [entry()],
            }
        })
    }

    /// The exact #165 condition: all entries present, every command pointing
    /// at a binary that does not exist. The old substring predicate called this
    /// healthy; it must not.
    #[test]
    fn entries_present_but_binary_missing_is_not_healthy() {
        let settings = settings_with("\"/nonexistent/openlatch-hook\" --event PreToolUse");
        let health = inspect(&settings, &claude());

        assert!(health.missing_events.is_empty(), "entries ARE present");
        assert_eq!(health.commands, 3);
        assert_eq!(health.missing_bin, vec!["/nonexistent/openlatch-hook"]);
        assert!(!health.is_healthy());
        assert!(health.needs_reinstall());
    }

    /// The bare-name last resort `init` used to write. It is not a path that
    /// exists, so it must classify as missing rather than silently pass.
    #[test]
    fn bare_command_name_is_missing() {
        let settings = settings_with("\"openlatch-hook\" --event PreToolUse");
        let health = inspect(&settings, &claude());
        assert_eq!(health.missing_bin, vec!["openlatch-hook"]);
        assert!(health.needs_reinstall());
    }

    /// A command pointing at a real file that is not the current resolution is
    /// drift, not absence — same repair, different diagnosis.
    #[test]
    fn existing_but_unexpected_binary_is_drift() {
        let tmp = TempDir::new().unwrap();
        let stale = tmp.path().join("openlatch-hook");
        std::fs::write(&stale, b"x").unwrap();

        let health = inspect(
            &settings_with(&format!("\"{}\" --event x", stale.display())),
            &claude(),
        );

        assert!(health.missing_bin.is_empty());
        assert_eq!(health.drifted_bin.len(), 1);
        assert!(health.needs_reinstall());
    }

    #[test]
    fn absent_load_bearing_event_is_reported() {
        let settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [{
                    "matcher": "*",
                    "_openlatch": true,
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\"" }]
                }]
            }
        });
        let health = inspect(&settings, &claude());
        assert_eq!(health.missing_events, vec!["UserPromptSubmit", "Stop"]);
        assert!(health.needs_reinstall());
    }

    /// Entries a user wrote themselves are none of our business — only
    /// `_openlatch`-marked ones are inspected or rewritten.
    #[test]
    fn foreign_entries_are_ignored() {
        let settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [{
                    "matcher": "*",
                    "hooks": [{ "type": "command", "command": "\"/usr/bin/their-hook\"" }]
                }]
            }
        });
        let health = inspect(&settings, &claude());
        assert_eq!(health.commands, 0);
        assert!(health.missing_bin.is_empty());
        assert!(health.needs_reinstall(), "no OpenLatch entries at all");
    }

    // ── the file-shaped half ────────────────────────────────────────────────

    /// Write a script of ours for `event` into `dir` and hand back its
    /// descriptor, exactly as `install_hooks` would record one.
    ///
    /// Goes through the real generator rather than a hand-rolled marker: a
    /// fixture that writes its own marker line proves the predicate accepts
    /// what the fixture writes, which is not the question.
    fn seed_our_script(dir: &Path, event: &str) -> crate::core::hook_state::FileDescriptor {
        let bin = dir.join("openlatch-hook");
        let body = crate::hooks::hook_files::shim_body(
            &bin,
            dir,
            event,
            "01997a1e-0000-7000-8000-00000000000a",
            cfg!(windows),
        );
        let path = dir.join(crate::hooks::hook_files::hook_file_name(event));
        std::fs::create_dir_all(dir).expect("the hooks directory");
        std::fs::write(&path, &body).expect("write a seeded script");
        crate::core::hook_state::FileDescriptor {
            path: path.to_string_lossy().into_owned(),
            sha256: crate::hooks::hook_files::sha256_hex(&body),
            mode: 0o755,
        }
    }

    /// Every registered event, written by us, verified against its descriptor.
    #[test]
    fn a_fully_written_directory_is_healthy() {
        let tmp = TempDir::new().unwrap();
        let binding = claude();

        let expected: BTreeMap<String, crate::core::hook_state::FileDescriptor> = binding
            .hook_event_types()
            .iter()
            .map(|event| ((*event).to_string(), seed_our_script(tmp.path(), event)))
            .collect();

        let health = inspect_directory(tmp.path(), &binding, &expected);
        assert_eq!(health.files, binding.hook_event_types().len());
        assert!(health.missing_files.is_empty());
        assert!(health.foreign_files.is_empty());
        assert!(health.drifted_files.is_empty());
        assert!(health.unverified_files.is_empty());
        assert!(health.is_healthy());
        assert!(!health.needs_reinstall());
    }

    /// Missing, foreign and drifted are three different findings, and the
    /// fourth case is the one that says why the last two are not one.
    ///
    /// **An edited script is FOREIGN, not drifted.** The marker line carries a
    /// hash of the body with itself removed, so editing the body breaks the
    /// ownership predicate before the descriptor comparison is ever reached —
    /// and that is the safe answer: a file we can no longer recognise is one we
    /// must not overwrite. *Drifted* is the narrower, real case of a script
    /// that is internally consistent and still ours, and is simply not the
    /// bytes THIS state file recorded: an install that ran again with a
    /// different staged binary, or a state file restored from before an
    /// upgrade.
    #[test]
    fn missing_foreign_and_drifted_are_different_findings() {
        let tmp = TempDir::new().unwrap();
        let binding = claude();
        let events = binding.hook_event_types();
        let name = crate::hooks::hook_files::hook_file_name;

        let mut expected = BTreeMap::new();
        for event in events.iter().skip(1) {
            expected.insert((*event).to_string(), seed_our_script(tmp.path(), event));
        }

        // events[0] is never written at all.
        // events[1] holds the developer's own script.
        std::fs::write(tmp.path().join(name(events[1])), "#!/bin/sh\necho mine\n")
            .expect("write their script");

        // events[2] is a VALID shim of ours — self-consistent marker, so the
        // ownership predicate passes — that names a different binary from the
        // one the recorded descriptor was taken over.
        let reinstalled = crate::hooks::hook_files::shim_body(
            &tmp.path().join("some-other-openlatch-hook"),
            tmp.path(),
            events[2],
            "01997a1e-0000-7000-8000-00000000000b",
            cfg!(windows),
        );
        std::fs::write(tmp.path().join(name(events[2])), &reinstalled)
            .expect("write a second install's shim");

        // events[3] is ours, hand-edited afterwards.
        let edited = format!(
            "{}# appended by hand\n",
            std::fs::read_to_string(tmp.path().join(name(events[3]))).expect("read ours")
        );
        std::fs::write(tmp.path().join(name(events[3])), edited).expect("edit ours");

        let health = inspect_directory(tmp.path(), &binding, &expected);
        assert_eq!(health.missing_files, vec![name(events[0])]);
        assert_eq!(
            health.foreign_files,
            vec![name(events[1]), name(events[3])],
            "a file failing the ownership predicate is the developer's — whether they wrote \
             it from scratch or edited one of ours — and is REPORTED, never rewritten"
        );
        assert_eq!(
            health.drifted_files,
            vec![name(events[2])],
            "recognisably ours, and not the bytes THIS state file recorded"
        );
        assert!(health.needs_reinstall());
    }

    /// A lost state file is not drift: the marker's own hash already proved the
    /// file is intact and ours, so health says *unverified* and stays green.
    #[test]
    fn a_script_with_no_stored_descriptor_is_unverified_not_drifted() {
        let tmp = TempDir::new().unwrap();
        let binding = claude();
        for event in binding.hook_event_types() {
            seed_our_script(tmp.path(), event);
        }

        let health = inspect_directory(tmp.path(), &binding, &BTreeMap::new());
        assert!(
            health.drifted_files.is_empty(),
            "no record is not a mismatch"
        );
        assert_eq!(
            health.unverified_files.len(),
            binding.hook_event_types().len()
        );
        assert!(
            health.is_healthy(),
            "a host whose hook-state.json was deleted is not a host with broken hooks"
        );
    }

    /// An empty directory is not healthy — "we wrote nothing" is never a pass.
    #[test]
    fn an_empty_directory_needs_a_reinstall() {
        let tmp = TempDir::new().unwrap();
        let health = inspect_directory(tmp.path(), &claude(), &BTreeMap::new());
        assert_eq!(health.files, 0);
        assert!(!health.is_healthy());
        assert!(health.needs_reinstall());
    }

    /// The descriptor lookup is keyed to the DIRECTORY, so a row written for a
    /// different surface is invisible here.
    #[test]
    fn tracked_descriptors_are_scoped_to_one_directory() {
        use crate::core::hook_state::{FileDescriptor, HookStateFile, StateEntry};

        let mine = Path::new("/tmp/openlatch-test/Hooks");
        let theirs = Path::new("/tmp/openlatch-test/OtherHooks");

        let mut state = HookStateFile::new("kid-01".into());
        let row = |dir: &Path, event: &str, descriptor: Option<FileDescriptor>| StateEntry {
            id: format!("id-{event}"),
            agent: "cline".into(),
            settings_path_hash: crate::core::hook_state::hash_settings_path(dir),
            hook_event: event.into(),
            expected_entry_hmac: String::new(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp".into(),
            descriptor,
            v: crate::core::hook_state::STATE_ENTRY_VERSION,
        };
        let descriptor = |sha: &str| FileDescriptor {
            path: "/tmp/openlatch-test/Hooks/PreToolUse".into(),
            sha256: sha.into(),
            mode: 0o755,
        };

        state.upsert_entry(row(mine, "PreToolUse", Some(descriptor("aa"))));
        state.upsert_entry(row(theirs, "PostToolUse", Some(descriptor("bb"))));
        // A JSON-file agent's row: no descriptor, so nothing to key on.
        state.upsert_entry(row(mine, "Stop", None));

        let found = tracked_descriptors(&state, mine);
        assert_eq!(found.len(), 1);
        assert_eq!(found["PreToolUse"].sha256, "aa");
    }

    #[test]
    fn extract_quoted_binary_handles_spaces_and_rejects_empties() {
        assert_eq!(
            extract_quoted_binary("\"C:\\Program Files\\openlatch-hook.exe\" --event Stop"),
            Some("C:\\Program Files\\openlatch-hook.exe".to_string())
        );
        assert_eq!(extract_quoted_binary("\"\" --event Stop"), None);
        assert_eq!(extract_quoted_binary("openlatch-hook --event Stop"), None);
    }
}