openlatch-client 0.6.6

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
//! Byte-identical uninstall, for a binding that opts in
//! ([`crate::hooks::binding::AgentBinding::byte_identical_restore`] — Cursor).
//!
//! Before OpenLatch first writes an agent's hook file, the file's exact bytes
//! are kept (or the fact that it did not exist); after every OpenLatch write,
//! the SHA-256 of the bytes written is kept. Uninstall puts the original back
//! **exactly** when the file on disk is still our last write, and otherwise
//! touches nothing here — the caller falls back to removing our entries by CST.
//!
//! Layout, owner-only, under `<openlatch_dir>/agent-backups/<agent>/`:
//!
//! - `<name>.pre` — the bytes before our first write, or
//! - `<name>.pre.absent` — an empty marker: the file did not exist;
//! - `<name>.last` — lowercase-hex SHA-256 of the bytes we last wrote;
//! - `<name>.last.theirs` — SHA-256 of the developer's part of those bytes
//!   (see below).
//!
//! **A user edit is never blessed.** Every OpenLatch write compares the bytes
//! it read against `.last`; when they differ the developer edited the file
//! since our last write, so those pre-write bytes — with our entries removed
//! as uninstall's CST path removes them, since the file held them — become the
//! new `.pre`. Uninstall can therefore never restore content older than the
//! developer's latest edit, nor restore our entries with it.
//!
//! **A change to our own entries is not a user edit.** A tamper the reconciler
//! heals — one of our entries deleted or altered — leaves the developer's part
//! of the file exactly as it was. Taking those bytes as the new `.pre` would
//! make uninstall restore a file still holding the rest of our entries. So the
//! comparison is also made on the developer's part alone — the file with our
//! entries (by the sidecar signature) and the event arrays that leaves empty
//! removed, canonicalised — and when that is unchanged the snapshot stands.

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

use crate::error::{OlError, ERR_HOOK_WRITE_FAILED};
use crate::hooks::hook_files::sha256_hex;

/// What [`restore_if_unchanged`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RestoreOutcome {
    /// The file held our last write; its pre-install bytes are back.
    RestoredExact,
    /// The file held our last write and did not exist before us; it is gone.
    DeletedCreated,
    /// The file changed since our last write (or is gone); nothing touched.
    UserEditedSince,
    /// No complete snapshot to restore from; nothing touched.
    NoSnapshot,
}

/// The three snapshot paths for `path`, owned by `agent`.
struct Snapshot {
    dir: PathBuf,
    pre: PathBuf,
    pre_absent: PathBuf,
    last: PathBuf,
    last_theirs: PathBuf,
}

fn snapshot(openlatch_dir: &Path, agent: &str, path: &Path) -> Snapshot {
    let dir = openlatch_dir.join("agent-backups").join(agent);
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "hooks.json".to_string());
    Snapshot {
        pre: dir.join(format!("{name}.pre")),
        pre_absent: dir.join(format!("{name}.pre.absent")),
        last: dir.join(format!("{name}.last")),
        last_theirs: dir.join(format!("{name}.last.theirs")),
        dir,
    }
}

fn io_err(action: &str, path: &Path, e: &std::io::Error) -> OlError {
    OlError::new(
        ERR_HOOK_WRITE_FAILED,
        format!("Cannot {action} '{}': {e}", path.display()),
    )
    .with_suggestion("Check permissions on the OpenLatch state directory.")
}

fn write(path: &Path, body: &str) -> Result<(), OlError> {
    crate::fs_secure::write_owner_only(path, body).map_err(|e| io_err("write", path, &e))
}

fn remove_if_present(path: &Path) -> Result<(), OlError> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(io_err("remove", path, &e)),
    }
}

/// Keep `before` as the pre-install state: its bytes, or "absent".
fn keep_pre(s: &Snapshot, before: Option<&str>) -> Result<(), OlError> {
    crate::fs_secure::create_dir_owner_only(&s.dir).map_err(|e| io_err("create", &s.dir, &e))?;
    match before {
        Some(bytes) => {
            write(&s.pre, bytes)?;
            remove_if_present(&s.pre_absent)
        }
        None => {
            write(&s.pre_absent, "")?;
            remove_if_present(&s.pre)
        }
    }
}

/// Call BEFORE the first OpenLatch write to `path` for `agent`.
///
/// Idempotent: once a `.pre` (or `.pre.absent`) exists this is a no-op. It
/// exists so a crash between the rewrite and [`record_last_write`] still
/// leaves the original behind. Answers whether THIS call took the snapshot, so
/// a caller whose write is then refused can [`retire`] it again.
///
/// # Errors
///
/// `OL-1401` when the file cannot be read or the snapshot cannot be written.
pub fn snapshot_before_first_write(
    openlatch_dir: &Path,
    agent: &str,
    path: &Path,
) -> Result<bool, OlError> {
    let s = snapshot(openlatch_dir, agent, path);
    if s.pre.exists() || s.pre_absent.exists() {
        return Ok(false);
    }
    let before = match std::fs::read_to_string(path) {
        Ok(raw) => Some(raw),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(io_err("read", path, &e)),
    };
    keep_pre(&s, before.as_deref())?;
    Ok(true)
}

/// Call AFTER every OpenLatch write (install, heal): `before` is the text the
/// write read (`None`: the file did not exist), `written` the exact text it
/// renamed into place — never a re-read of the file.
///
/// When `before` is not our last write, the developer edited the file since,
/// so those bytes, our entries removed, become the pre-install state. With no last write yet, the
/// snapshot [`snapshot_before_first_write`] took stands: a crash between an
/// earlier rewrite and this record left OUR bytes in the file, and refreshing
/// from them would bless them. Then `.last` records `written`.
///
/// # Errors
///
/// `OL-1401` when a snapshot file cannot be read or written.
pub fn record_last_write(
    openlatch_dir: &Path,
    agent: &str,
    path: &Path,
    before: Option<&str>,
    written: &str,
) -> Result<(), OlError> {
    let s = snapshot(openlatch_dir, agent, path);
    let last = std::fs::read_to_string(&s.last).ok();
    let last_theirs = std::fs::read_to_string(&s.last_theirs).ok();
    let edited_since = match (last.as_deref(), before) {
        (None, _) => !(s.pre.exists() || s.pre_absent.exists()),
        // The bytes decide first: the digest is parsed only when they differ.
        (Some(last), Some(before)) => {
            last.trim() != sha256_hex(before)
                && !matches!(
                    (last_theirs.as_deref(), theirs_digest(before, agent)),
                    (Some(last), Some(now)) if last.trim() == now
                )
        }
        (Some(_), None) => true,
    };
    if edited_since {
        let theirs = before.map(|text| without_ours(text, agent));
        keep_pre(&s, theirs.as_deref())?;
    }
    write(&s.last, &sha256_hex(written))?;
    match theirs_digest(written, agent) {
        Some(digest) => write(&s.last_theirs, &digest),
        None => remove_if_present(&s.last_theirs),
    }
}

/// `text` with our entries removed exactly as uninstall's CST path removes
/// them — the sidecar signature for `agent`, the event arrays that empties and
/// then an emptied `hooks` — keeping the developer's formatting and comments.
///
/// The bytes a write read over a developer's edit still hold the entries we
/// installed before it; kept as `.pre` unstripped, uninstall would restore
/// live OpenLatch hooks. Text that does not parse is kept as it is: uninstall
/// refuses such a file on its CST path too.
fn without_ours(text: &str, agent: &str) -> String {
    let Ok(root) =
        jsonc_parser::cst::CstRootNode::parse(text, &jsonc_parser::ParseOptions::default())
    else {
        return text.to_string();
    };
    match crate::hooks::jsonc::remove_owned_entries_cst_by(&root, &|node| {
        crate::hooks::entry_shape::is_sidecar_owned_node(node, agent)
    }) {
        Ok(()) => root.to_string(),
        Err(_) => text.to_string(),
    }
}

/// SHA-256 of the developer's part of a hook file: parsed, our entries (the
/// sidecar signature for `agent`) removed, the event arrays that leaves empty
/// dropped, then JCS-canonicalised so key order and whitespace do not count.
/// `None` when the text does not parse — then only the byte comparison
/// decides, as before this existed.
fn theirs_digest(text: &str, agent: &str) -> Option<String> {
    let mut value = crate::hooks::jsonc::parse_settings_value(text).ok()?;
    if let Some(hooks) = value
        .get_mut("hooks")
        .and_then(serde_json::Value::as_object_mut)
    {
        for entries in hooks.values_mut() {
            if let Some(entries) = entries.as_array_mut() {
                entries.retain(|e| !crate::hooks::entry_shape::is_sidecar_owned_entry(e, agent));
            }
        }
        hooks.retain(|_, entries| entries.as_array().is_none_or(|a| !a.is_empty()));
    }
    let canonical = serde_json_canonicalizer::to_string(&value).ok()?;
    Some(sha256_hex(&canonical))
}

/// Uninstall. When the file's SHA-256 equals `.last`, put `.pre` back exactly
/// (or delete the file when it did not exist before us), then retire the
/// snapshot. Otherwise answer without touching anything — the snapshot
/// included, so the caller can remove our entries and then [`retire`] it.
///
/// # Errors
///
/// `OL-1401` when the file cannot be read, restored or deleted.
pub fn restore_if_unchanged(
    openlatch_dir: &Path,
    agent: &str,
    path: &Path,
) -> Result<RestoreOutcome, OlError> {
    let s = snapshot(openlatch_dir, agent, path);
    let Ok(last) = std::fs::read_to_string(&s.last) else {
        return Ok(RestoreOutcome::NoSnapshot);
    };
    let pre_absent = s.pre_absent.exists();
    if !pre_absent && !s.pre.exists() {
        return Ok(RestoreOutcome::NoSnapshot);
    }
    let current = match std::fs::read(path) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Ok(RestoreOutcome::UserEditedSince)
        }
        Err(e) => return Err(io_err("read", path, &e)),
    };
    if crate::hooks::hook_files::sha256_bytes(&current) != last.trim() {
        return Ok(RestoreOutcome::UserEditedSince);
    }

    let outcome = if pre_absent {
        std::fs::remove_file(path).map_err(|e| io_err("delete", path, &e))?;
        RestoreOutcome::DeletedCreated
    } else {
        let pre = std::fs::read(&s.pre).map_err(|e| io_err("read", &s.pre, &e))?;
        crate::fs_secure::write_preserving_mode(path, &pre)
            .map_err(|e| io_err("restore", path, &e))?;
        RestoreOutcome::RestoredExact
    };
    retire(openlatch_dir, agent, path)?;
    Ok(outcome)
}

/// When OpenLatch's entries in `path` were installed: the time the pre-install
/// snapshot was taken — the first write, or the latest write over a developer's
/// edit. `None` when there is no snapshot.
///
/// `doctor` dates Cursor's reachability evidence against it: a live event from
/// before our entries were written proves nothing about them.
pub fn installed_at(
    openlatch_dir: &Path,
    agent: &str,
    path: &Path,
) -> Option<std::time::SystemTime> {
    let s = snapshot(openlatch_dir, agent, path);
    let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
    modified(&s.pre).or_else(|| modified(&s.pre_absent))
}

/// Drop the snapshot for `path`, so the next install snapshots the file as it
/// is then. Called once uninstall is done with it, whichever way it went —
/// otherwise a later uninstall would restore bytes older than the developer's
/// edits.
///
/// # Errors
///
/// `OL-1401` when a snapshot file exists and cannot be removed.
pub fn retire(openlatch_dir: &Path, agent: &str, path: &Path) -> Result<(), OlError> {
    let s = snapshot(openlatch_dir, agent, path);
    remove_if_present(&s.pre)?;
    remove_if_present(&s.pre_absent)?;
    remove_if_present(&s.last)?;
    remove_if_present(&s.last_theirs)
}

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

    const AGENT: &str = "cursor";

    struct Fixture {
        _root: tempfile::TempDir,
        ol: PathBuf,
        file: PathBuf,
    }

    fn fixture() -> Fixture {
        let root = tempfile::tempdir().expect("temp dir");
        let ol = root.path().join("openlatch");
        let file = root.path().join("cursor").join("hooks.json");
        std::fs::create_dir_all(file.parent().expect("parent")).expect("agent dir");
        Fixture {
            ol,
            file,
            _root: root,
        }
    }

    /// An OpenLatch write, as `install_hooks` performs it: snapshot, write,
    /// record the bytes written.
    fn our_write(f: &Fixture, text: &str) {
        snapshot_before_first_write(&f.ol, AGENT, &f.file).expect("snapshot");
        let before = std::fs::read_to_string(&f.file).ok();
        std::fs::write(&f.file, text).expect("write");
        record_last_write(&f.ol, AGENT, &f.file, before.as_deref(), text).expect("record");
    }

    #[test]
    fn an_untouched_file_restores_byte_for_byte() {
        let f = fixture();
        let original = "{\"hooks\":{\"stop\":[{\"command\":\"echo mine\"}]},\"version\":1}\n";
        std::fs::write(&f.file, original).expect("seed");
        our_write(&f, "ours");

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(std::fs::read_to_string(&f.file).expect("read"), original);
        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("again"),
            RestoreOutcome::NoSnapshot,
            "the snapshot is retired with the restore"
        );
    }

    #[test]
    fn a_file_we_created_is_deleted() {
        let f = fixture();
        our_write(&f, "ours");
        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::DeletedCreated
        );
        assert!(!f.file.exists());
    }

    #[test]
    fn a_crash_before_the_record_keeps_the_original() {
        let f = fixture();
        std::fs::write(&f.file, "theirs").expect("seed");
        snapshot_before_first_write(&f.ol, AGENT, &f.file).expect("snapshot");
        // The rewrite put "ours v1" in place and the process died before
        // `record_last_write`: no `.last`. The next install reads our own bytes.
        std::fs::write(&f.file, "ours v1").expect("crashed write");
        assert!(!snapshot_before_first_write(&f.ol, AGENT, &f.file).expect("snapshot"));
        our_write(&f, "ours v2");

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(std::fs::read_to_string(&f.file).expect("read"), "theirs");
    }

    #[test]
    fn last_write_hash_is_of_the_bytes_written() {
        let f = fixture();
        std::fs::write(&f.file, "theirs").expect("seed");
        snapshot_before_first_write(&f.ol, AGENT, &f.file).expect("snapshot");
        // The rewrite wrote "ours"; before the hash was recorded, another writer
        // replaced it. Recording from what we wrote — not from a re-read — is
        // what keeps that writer's bytes from being blessed as ours.
        std::fs::write(&f.file, "someone else").expect("interleaved write");
        record_last_write(&f.ol, AGENT, &f.file, Some("theirs"), "ours").expect("record");

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::UserEditedSince
        );
        assert_eq!(
            std::fs::read_to_string(&f.file).expect("read"),
            "someone else",
            "nothing is touched when the file is not our last write"
        );
    }

    #[test]
    fn user_edit_uninstall_retires_the_snapshot() {
        let f = fixture();
        std::fs::write(&f.file, "v0").expect("seed");
        our_write(&f, "ours");
        std::fs::write(&f.file, "edited").expect("user edit");

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::UserEditedSince
        );
        // The caller removes our entries by CST, then retires the pair.
        retire(&f.ol, AGENT, &f.file).expect("retire");

        // A reinstall snapshots the file as it is NOW, not as it was at v0.
        our_write(&f, "ours again");
        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(std::fs::read_to_string(&f.file).expect("read"), "edited");
    }

    /// A later OpenLatch write over a user edit refreshes `.pre` from the
    /// bytes it read, so uninstall restores the edit, never v0.
    #[test]
    fn a_later_write_never_blesses_a_user_edit() {
        let f = fixture();
        std::fs::write(&f.file, "v0").expect("seed");
        our_write(&f, "ours-1");
        std::fs::write(&f.file, "edited").expect("user edit");
        our_write(&f, "ours-2"); // a heal, or a re-run of init

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(std::fs::read_to_string(&f.file).expect("read"), "edited");
    }

    /// Our own rewrite over our own last write keeps the original `.pre`.
    #[test]
    fn a_rewrite_over_our_own_write_keeps_the_original() {
        let f = fixture();
        std::fs::write(&f.file, "v0").expect("seed");
        our_write(&f, "ours-1");
        our_write(&f, "ours-2");

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(std::fs::read_to_string(&f.file).expect("read"), "v0");
    }

    /// A tamper confined to our own entries — the kind the reconciler heals —
    /// is not a user edit: the snapshot stands, so uninstall after the heal
    /// still restores the developer's original bytes, none of ours in them.
    #[test]
    fn a_change_to_our_entries_alone_is_not_a_user_edit() {
        let f = fixture();
        let ours = |event: &str| {
            format!(
                r#"{{"command":"\"/x/openlatch-hook\" --agent {AGENT} --event {event} --openlatch-dir \"/o\"","timeout":10}}"#
            )
        };
        let original = "{\"hooks\":{\"stop\":[{\"command\":\"echo mine\"}]},\"version\":1}\n";
        std::fs::write(&f.file, original).expect("seed");
        let installed = format!(
            r#"{{"version":1,"hooks":{{"stop":[{{"command":"echo mine"}},{}],"sessionEnd":[{}]}}}}"#,
            ours("stop"),
            ours("session_end")
        );
        our_write(&f, &installed);

        // One of ours deleted, its array left empty, keys reordered.
        let tampered = format!(
            r#"{{"hooks":{{"sessionEnd":[],"stop":[{{"command":"echo mine"}},{}]}},"version":1}}"#,
            ours("stop")
        );
        std::fs::write(&f.file, &tampered).expect("tamper");
        our_write(&f, &installed); // the heal

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(std::fs::read_to_string(&f.file).expect("read"), original);
    }

    /// A write over a developer's edit keeps the edit as `.pre` with our
    /// entries — which the edited file still held — removed by CST, the
    /// developer's formatting and comments kept, so uninstall restores no
    /// OpenLatch hook.
    #[test]
    fn a_refreshed_snapshot_drops_our_entries() {
        let f = fixture();
        let ours = |event: &str| {
            format!(
                r#"{{"command":"\"/x/openlatch-hook\" --agent {AGENT} --event {event} --openlatch-dir \"/o\"","timeout":10}}"#
            )
        };
        std::fs::write(&f.file, "{\"version\":1}").expect("seed");
        let installed = format!(
            r#"{{"version":1,"hooks":{{"stop":[{}],"sessionEnd":[{}]}}}}"#,
            ours("stop"),
            ours("session_end")
        );
        our_write(&f, &installed);

        // The developer adds a hook of their own, with a comment.
        let edited = format!(
            "{{\n  // mine\n  \"version\": 1,\n  \"hooks\": {{\n    \"stop\": [\n      {{ \"command\": \"echo mine\" }},\n      {}\n    ],\n    \"sessionEnd\": [{}]\n  }}\n}}\n",
            ours("stop"),
            ours("session_end")
        );
        std::fs::write(&f.file, &edited).expect("user edit");
        our_write(&f, &installed); // a heal, or a re-run of init

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(
            std::fs::read_to_string(&f.file).expect("read"),
            "{\n  // mine\n  \"version\": 1,\n  \"hooks\": {\n    \"stop\": [\n      { \"command\": \"echo mine\" }\n    ]\n  }\n}\n"
        );
    }

    /// Bytes that do not parse are kept as they are.
    #[test]
    fn an_unparseable_edit_is_kept_raw() {
        let f = fixture();
        std::fs::write(&f.file, "v0").expect("seed");
        our_write(&f, "ours-1");
        std::fs::write(&f.file, "{ not json openlatch-hook").expect("user edit");
        our_write(&f, "ours-2");

        assert_eq!(
            restore_if_unchanged(&f.ol, AGENT, &f.file).expect("restore"),
            RestoreOutcome::RestoredExact
        );
        assert_eq!(
            std::fs::read_to_string(&f.file).expect("read"),
            "{ not json openlatch-hook"
        );
    }

    #[cfg(unix)]
    #[test]
    fn snapshot_files_are_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let f = fixture();
        std::fs::write(&f.file, "v0").expect("seed");
        our_write(&f, "{}");
        let s = snapshot(&f.ol, AGENT, &f.file);
        for path in [&s.pre, &s.last, &s.last_theirs] {
            let mode = std::fs::metadata(path).expect("meta").permissions().mode() & 0o777;
            assert_eq!(mode, 0o600, "{}", path.display());
        }
    }
}