openlatch-client 0.5.2

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
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
//! The file-shaped hook installer: ten scripts, two platform shapes, one owner.
//!
//! Every other agent this client supports registers hooks by writing entries
//! into one JSON config file. Cline discovers them as **executable scripts in a
//! directory**, one per event, named after the event, so
//! [`crate::hooks::binding::HookSurface::Directory`] needs a writer that deals
//! in files rather than in JSON.
//!
//! # The prime invariant: these shims never deny
//!
//! `openlatch-hook` returns real verdicts. A Cline file hook that forwarded one
//! would set `cancel: true` → `stop: true` → `ControlledStopError` → run status
//! `aborted`, killing the developer's whole session rather than the one tool
//! call. So the shims post the event, **discard the response** and print `{}`.
//! They pass `--capture-only`, which is also what keeps them off the hold path:
//! a hold makes `openlatch-hook` issue a second blocking request and wait
//! `hold_timeout_ms + 1000 ms` for an answer this lane then throws away.
//!
//! # This module cannot find the developer's Cline install
//!
//! **Every write entry point takes its directory as a parameter**, and nothing
//! here calls a path resolver. That is deliberate and structural: a real Cline
//! store lives under the developer's home on machines this code runs on today,
//! and the isolation discipline that would otherwise protect it is prose that a
//! new test author can simply not read. A unit test hands this module a
//! `tempdir()` and physically cannot reach a real install, because the module
//! does not know how to find one. Resolution happens once, in `install_hooks`'
//! `Directory` arm, from `binding.hook_surface()`.
//!
//! `no_resolver_is_called_from_the_writer` greps this file for the resolver
//! names and fails on a hit.

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

use regex::Regex;
use sha2::{Digest, Sha256};

use crate::core::hook_state::key::hex;
use crate::core::hook_state::FileDescriptor;
use crate::error::{OlError, ERR_HOOK_WRITE_FAILED};
use crate::hooks::claude_code::pascal_to_snake;

/// THE ten, exactly as Cline's `HookConfigFileName` spells them.
///
/// All ten install; **not all ten fire**, and the gap is Cline's rather than
/// ours. Its VS Code adapter defers `TaskResume`, `TaskError` and
/// `SessionShutdown`, and `PreCompact` fires in neither lane — Cline maps it to
/// `undefined` and skips every file whose event name is falsy. It is a filename
/// Cline recognises with nothing behind it.
///
/// Install it anyway: it costs one file and makes the day Cline wires it a
/// no-op for us. But **never report it as capturing**, and never read its
/// absence from an event log as a defect on this side. A directory listing
/// proves the installer wrote ten files with the right names; it proves nothing
/// whatever about capture.
///
/// Version-pinned, not structural — re-verify on a Cline minor bump.
pub const CLINE_HOOK_FILES: [&str; 10] = [
    "TaskStart",
    "TaskResume",
    "TaskCancel",
    "TaskComplete",
    "TaskError",
    "PreToolUse",
    "PostToolUse",
    "UserPromptSubmit",
    "PreCompact",
    "SessionShutdown",
];

/// The mode every shim is left in, and the value recorded in its descriptor.
///
/// The writer's contract rather than a `stat`: `fs_secure::write_executable`
/// guarantees `0o755` on Unix and Windows has no mode to record, so this reads
/// the same on both and a real mode that disagrees is drift. `0o600` — what
/// `restrict_to_owner` would set — is permission-denied on every Cline event.
pub const HOOK_FILE_MODE: u32 = 0o755;

/// D-03's **single** platform decision.
///
/// Every generator below takes the answer as a parameter instead of asking
/// again, which is what lets a macOS or Linux test run exercise the Windows
/// half. `windows-cross` only compiles it; nothing else executes it before a
/// post-merge job on a real runner.
fn host_is_windows() -> bool {
    cfg!(windows)
}

/// The file name Cline discovers this event under, on this host.
pub fn hook_file_name(event: &str) -> String {
    file_name_for(event, host_is_windows())
}

/// [`hook_file_name`]'s body, with the platform decision passed in.
///
/// Cline's discovery is per-platform and **mutually exclusive**: the PowerShell
/// lane looks for `<HookName>.ps1` and the POSIX lane for a bare `<HookName>`.
/// A wrong-platform name is not an error, it is silently ignored — which is how
/// a one-shape installer reports a successful install on a host capturing
/// nothing.
fn file_name_for(event: &str, windows: bool) -> String {
    if windows {
        format!("{event}.ps1")
    } else {
        event.to_string()
    }
}

/// Single-quote for `/bin/sh`, escaping the quote character itself.
///
/// Quoting alone is not enough: a developer home like `/Users/O'Brien` ends the
/// string early and leaves the rest of the line as stray shell syntax. POSIX
/// has no escape *inside* single quotes, so the idiom closes the string, adds a
/// backslash-escaped quote and reopens it — `'` becomes `'\''`.
fn quote_posix(value: &str) -> String {
    format!("'{}'", value.replace('\'', r"'\''"))
}

/// Single-quote for PowerShell, escaping the quote character itself.
///
/// PowerShell doubles it instead: `'` becomes `''`. Same failure without it,
/// and the two escapes are not interchangeable.
fn quote_powershell(value: &str) -> String {
    format!("'{}'", value.replace('\'', "''"))
}

/// The shim in two pieces, with the marker line's slot between them.
///
/// Split this way because the marker is not computable from the finished file:
/// it carries a hash *of the body with the marker line removed*, so the
/// unmarked body has to exist first. `head` is everything above the marker
/// (the shebang, on POSIX; nothing on Windows, which has no shebang and so puts
/// its marker on line 1) and `tail` everything below.
///
/// `--openlatch-dir` and **not** an environment variable: the hook's port file
/// lookup ignores `OPENLATCH_DIR` while its log directory honours it, so an
/// env-only shim talks to the wrong daemon and logs to the right directory.
fn shim_around_marker(bin: &Path, ol_dir: &Path, event: &str, windows: bool) -> (String, String) {
    let bin = bin.to_string_lossy();
    let ol_dir = ol_dir.to_string_lossy();
    if windows {
        // `*> $null`, `try/catch` and an explicit `exit 0` — all three, because
        // the prime invariant has to hold under a host we do not control.
        //
        // `| Out-Null` alone was wrong: it discards only the SUCCESS stream, so
        // native stderr and PowerShell error records still reach Cline. And a
        // profile setting `$ErrorActionPreference = 'Stop'` — or PowerShell 7's
        // native-command error preference — turns a stderr write into a
        // TERMINATING error, which ends the script before `Write-Output` runs:
        // the shim then emits nothing and exits non-zero, on a lane whose one
        // job is to emit `{}` and get out of the way.
        //
        // The POSIX half suppresses both streams with `>/dev/null 2>&1` and
        // cannot fail this way. The two halves must behave identically (D-02) —
        // that is the whole reason the platform decision is a parameter.
        let tail = format!(
            "try {{ & {bin} --agent cline --event {event} --openlatch-dir {dir} \
             --capture-only *> $null }} catch {{ }}\nWrite-Output '{{}}'\nexit 0\n",
            bin = quote_powershell(&bin),
            dir = quote_powershell(&ol_dir),
        );
        (String::new(), tail)
    } else {
        let tail = format!(
            "{bin} --agent cline --event {event} --openlatch-dir {dir} --capture-only \
             >/dev/null 2>&1\nprintf '{{}}'\n",
            bin = quote_posix(&bin),
            dir = quote_posix(&ol_dir),
        );
        ("#!/bin/sh\n".to_string(), tail)
    }
}

/// One shim, marker line included.
///
/// `bin` must be the **staged absolute path** to `openlatch-hook`, never a bare
/// name: a bare name on a PATH that does not carry it kills every hook with
/// exit 127, silently, because the hook fails open. `event` is the snake_case
/// wire spelling, not the file name.
///
/// `entry_id` is the per-file UUIDv7 that also keys this file's state row. It
/// is an **audit breadcrumb, not the predicate** — nothing compares it against
/// anything, and [`is_ours`] accepts a marker without one so a surface with no
/// event of its own can share this exact predicate rather than invent a second.
///
/// The hash is computed here rather than by the caller because it cannot be
/// computed anywhere else: hashing the finished file would be circular, since
/// the marker is part of what it would hash.
pub fn shim_body(bin: &Path, ol_dir: &Path, event: &str, entry_id: &str, windows: bool) -> String {
    let (head, tail) = shim_around_marker(bin, ol_dir, event, windows);
    let unmarked = format!("{head}{tail}");
    let digest = sha256_hex(&unmarked);
    let uuid = marker_uuid_field(entry_id);
    format!("{head}# openlatch-hook {uuid}{digest}\n{tail}")
}

/// The marker's optional uuid field, already spaced, or the empty string.
///
/// The predicate's uuid group is `[0-9a-f-]{36}` and optional, so an
/// `entry_id` that does not fit that shape is **left out** rather than written
/// into the line. A marker carrying it would match nothing, and the file would
/// be an orphan on the developer's disk that we could never recognise, never
/// heal and never remove — every consumer of [`is_ours`] would read it as
/// theirs and refuse to touch it.
///
/// Losing an audit breadcrumb is by far the cheaper failure. The hash is the
/// predicate; the uuid never was.
fn marker_uuid_field(entry_id: &str) -> String {
    let well_formed = entry_id.len() == 36
        && entry_id
            .bytes()
            .all(|b| (b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) || b == b'-');
    if well_formed {
        format!("{entry_id} ")
    } else {
        String::new()
    }
}

/// Lowercase-hex SHA-256 of `body`.
pub fn sha256_hex(body: &str) -> String {
    sha256_bytes(body.as_bytes())
}

/// Lowercase-hex SHA-256 of raw bytes.
///
/// The form a **verifier** wants. A script replaced with something non-UTF-8
/// has drifted, and a reader that had to decode it first would turn that into
/// an I/O error and then have to decide what the error means — with "could not
/// check, assume fine" the easy wrong answer. Hashing bytes answers the only
/// question being asked, are these the bytes we wrote, for every possible file.
pub fn sha256_bytes(bytes: &[u8]) -> String {
    hex::encode(&Sha256::digest(bytes))
}

/// THE ownership predicate, used verbatim by install, health, removal,
/// uninstall and the reconciler.
///
/// A file is ours **iff** some line among the **first two** matches
///
/// ```text
/// ^(#|//)\s*openlatch-hook\s+(?:([0-9a-f-]{36})\s+)?([0-9a-f]{64})\s*$
/// ```
///
/// **and** the SHA-256 of the body with *that* line removed equals the last
/// capture group.
///
/// *First two lines, not "line 2".* The POSIX shim opens with `#!/bin/sh`,
/// putting the marker on line 2; the PowerShell shim has no shebang, so its
/// marker is on line 1. A predicate hard-coded to line 2 makes every Windows
/// install unrecognisable to uninstall, health, rescue and the reconciler —
/// all four would read our own files as the developer's and refuse to touch
/// them.
///
/// The comment prefix is parametric (`#` for shell and PowerShell, `//` for
/// JavaScript) and the uuid group is optional, so a surface that has no hook
/// event and no state row is still recognisably ours. The self-describing hash
/// is what makes that work with no external record at all, which is the whole
/// reason the comment exists.
///
/// A file failing either half is the developer's: never modified, never
/// deleted, reported.
pub fn is_ours(body: &str) -> bool {
    owning_marker_line(body).is_some()
}

/// The index of the line that makes `body` ours, if any.
fn owning_marker_line(body: &str) -> Option<usize> {
    let pattern = marker_pattern();
    for (index, line) in body.lines().take(2).enumerate() {
        let Some(captures) = pattern.captures(line) else {
            continue;
        };
        // Group 1 is the comment prefix, group 2 the optional uuid; the hash is
        // the last group either way.
        let Some(claimed) = captures.get(3) else {
            continue;
        };
        if sha256_hex(&without_line(body, index)) == claimed.as_str() {
            return Some(index);
        }
    }
    None
}

fn marker_pattern() -> &'static Regex {
    static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"^(#|//)\s*openlatch-hook\s+(?:([0-9a-f-]{36})\s+)?([0-9a-f]{64})\s*$")
            .expect("the ownership marker pattern is a literal and compiles")
    })
}

/// `body` with line `index` removed, line terminators preserved.
///
/// `split_inclusive` rather than `lines()`: the hash has to be taken over the
/// exact remaining bytes, and `lines()` would drop every terminator it walked
/// past. Both split on `\n`, so the index means the same thing to each.
fn without_line(body: &str, index: usize) -> String {
    body.split_inclusive('\n')
        .enumerate()
        .filter(|(i, _)| *i != index)
        .map(|(_, segment)| segment)
        .collect()
}

/// One shim this run wrote.
///
/// Carries the id as well as the descriptor so that the marker comment in the
/// file and the file's state row name the **same** UUIDv7. The writer mints it
/// because it is the writer that has to embed it before the body can be hashed;
/// minting a second one at the caller would put two different ids on one file.
#[derive(Debug, Clone)]
pub struct WrittenHookFile {
    /// The PascalCase hook file name, which is also the event as we name it.
    pub event: String,
    /// The per-file UUIDv7 in the marker line, for the entry's state row.
    pub entry_id: String,
    /// `{path, sha256, mode}` — what the state row stores.
    pub descriptor: FileDescriptor,
    /// `true` when this write replaced a script of **ours**, `false` when the
    /// path was empty.
    ///
    /// Carried here because this is the only place that knows:
    /// `whatever_is_there` already classified the path, and a caller that
    /// re-stats afterwards is asking a question the write made unanswerable.
    pub replaced: bool,
}

/// What [`write_all`] did — the sibling of [`RemovalReport`], and the same
/// shape for the same reason.
///
/// A write that skipped a path is not a write that wrote everything, and a
/// caller cannot tell the difference from a count: it would have to know how
/// many files were expected, which means knowing the agent. `left` says it
/// directly, so no caller re-derives it and none of them names Cline.
#[derive(Debug, Clone, Default)]
pub struct InstallReport {
    /// The shims this run wrote.
    pub written: Vec<WrittenHookFile>,
    /// Paths holding a file that is **not** ours, left exactly as they were.
    pub left: Vec<PathBuf>,
}

/// What [`remove_all`] did, per path.
#[derive(Debug, Clone, Default)]
pub struct RemovalReport {
    /// Paths that satisfied [`is_ours`] and were removed.
    pub removed: Vec<PathBuf>,
    /// Paths holding a file at one of the ten names that is **not** ours, and
    /// was therefore left exactly as it was.
    pub left: Vec<PathBuf>,
}

/// Write all ten shims into `hooks_dir`, creating it if it does not exist.
///
/// `hooks_dir`, `bin` and `ol_dir` are all parameters and none of them is
/// resolved here — see the module header for why that is structural rather
/// than stylistic.
///
/// **Collisions.** A path already holding a file that fails [`is_ours`] is the
/// developer's: it is never overwritten, it is reported through a warning, and
/// the install continues with the other nine. A path holding a file that passes
/// is ours, and is copied to `<name>.bak` beside it before being rewritten so
/// that `doctor --restore` has something to return to.
///
/// # Errors
///
/// `OL-1401` if the directory or a script cannot be written. A hook that cannot
/// be written is not a hook, so an I/O failure propagates rather than being
/// downgraded to a skip — unlike a collision, which is a decision about someone
/// else's file.
pub fn write_all(hooks_dir: &Path, bin: &Path, ol_dir: &Path) -> Result<InstallReport, OlError> {
    std::fs::create_dir_all(hooks_dir).map_err(|e| write_failed(hooks_dir, &e))?;

    let windows = host_is_windows();
    let mut report = InstallReport {
        written: Vec::with_capacity(CLINE_HOOK_FILES.len()),
        left: Vec::new(),
    };

    for event in CLINE_HOOK_FILES {
        let path = hooks_dir.join(file_name_for(event, windows));

        let replaced = match whatever_is_there(&path) {
            Existing::Nothing => false,
            Existing::Ours => {
                back_up(&path)?;
                true
            }
            Existing::Theirs => {
                tracing::warn!(
                    path = %path.display(),
                    "a file we did not write already holds this hook name; leaving it alone"
                );
                report.left.push(path);
                continue;
            }
        };

        let entry_id = uuid::Uuid::now_v7().to_string();
        let body = shim_body(bin, ol_dir, pascal_to_snake(event), &entry_id, windows);
        crate::fs_secure::write_executable(&path, &body).map_err(|e| write_failed(&path, &e))?;

        report.written.push(WrittenHookFile {
            event: event.to_string(),
            entry_id,
            descriptor: FileDescriptor {
                path: path.to_string_lossy().into_owned(),
                sha256: sha256_hex(&body),
                mode: HOOK_FILE_MODE,
            },
            replaced,
        });
    }

    Ok(report)
}

/// Remove the shims in `hooks_dir` that satisfy [`is_ours`], and only those.
///
/// There is no install id to compare against — the self-describing hash is the
/// whole predicate, which is what lets uninstall work on a host whose state
/// file was lost. A file failing either half of it is left alone and reported;
/// backups are left alone too, because `--restore` is what they are for.
///
/// # Errors
///
/// `OL-1401` if a file that is ours cannot be removed. **Not** for anything
/// about the developer's own files: `uninstall` gates the model-relay teardown
/// on this returning `Ok`, and an `Err` there leaves Cline pointed at a dead
/// loopback port. A partial removal is an `Ok` plus a warning per skipped file.
pub fn remove_all(hooks_dir: &Path) -> Result<RemovalReport, OlError> {
    let windows = host_is_windows();
    let mut report = RemovalReport::default();

    for event in CLINE_HOOK_FILES {
        let path = hooks_dir.join(file_name_for(event, windows));
        match whatever_is_there(&path) {
            Existing::Nothing => {}
            Existing::Ours => {
                std::fs::remove_file(&path).map_err(|e| write_failed(&path, &e))?;
                report.removed.push(path);
            }
            Existing::Theirs => {
                tracing::warn!(
                    path = %path.display(),
                    "hook file is not one of ours; leaving it in place"
                );
                report.left.push(path);
            }
        }
    }

    Ok(report)
}

/// Whose the thing at this path is, as far as this installer is concerned.
///
/// `pub(crate)` because Cline's enforcement plugin is classified by the very
/// same predicate — see [`crate::hooks::cline_plugin`]. One marker, one
/// classifier: a second copy is a second answer, and the two would disagree the
/// first time either is fixed.
pub(crate) enum Existing {
    /// The path is free.
    Nothing,
    /// A file satisfying [`is_ours`].
    Ours,
    /// Anything else at that path — a script the developer wrote, a binary, a
    /// directory, something we lack permission to read. All one answer,
    /// because the action is the same for all of them: leave it and say so.
    Theirs,
}

/// Classify the path, without ever turning someone else's artefact into an
/// error.
///
/// Reads bytes and converts lossily rather than going through
/// `read_to_string`, which fails outright on a non-UTF-8 file, and treats every
/// non-`NotFound` error as `Theirs` rather than propagating it. A directory or
/// an unreadable file at one of the ten names is emphatically not ours; making
/// it an `Err` would abort an uninstall over a file we were never going to
/// touch. Lossy is safe here because the replacement character can only ever
/// *fail* the ownership predicate.
pub(crate) fn whatever_is_there(path: &Path) -> Existing {
    match std::fs::read(path) {
        Ok(bytes) if is_ours(&String::from_utf8_lossy(&bytes)) => Existing::Ours,
        Ok(_) => Existing::Theirs,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Existing::Nothing,
        Err(_) => Existing::Theirs,
    }
}

/// Copy one of our scripts to `<name>.bak` before it is rewritten.
///
/// The suffix **appends**, as it does in `write_executable` and for the same
/// reason: `with_extension` makes a sibling of `PreToolUse` and *replaces* the
/// `.ps1` of `PreToolUse.ps1`. Neither result is the file it was asked to back
/// up, and neither is a name Cline's per-platform discovery picks up.
pub(crate) fn back_up(path: &Path) -> Result<(), OlError> {
    let Some(name) = path.file_name() else {
        return Ok(());
    };
    let mut backup_name = name.to_os_string();
    backup_name.push(".bak");
    let backup = path.with_file_name(backup_name);
    std::fs::copy(path, &backup).map_err(|e| write_failed(&backup, &e))?;
    Ok(())
}

fn write_failed(path: &Path, error: &std::io::Error) -> OlError {
    OlError::new(
        ERR_HOOK_WRITE_FAILED,
        format!("Cannot write hook file '{}': {error}", path.display()),
    )
    .with_suggestion("Check that the agent's hook directory exists and is writable.")
}

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

    /// A UUIDv7 of the shape `write_all` mints, so the fixtures exercise the
    /// marker's uuid-carrying form rather than its degraded one.
    const ENTRY_ID: &str = "01997a1e-0000-7000-8000-00000000000a";

    /// Every fixture in this module builds its whole world inside a `tempdir()`
    /// and hands it to the writer. No seam is read, no resolver is called, and
    /// nothing here can name a real install.
    fn hooks_dir(root: &Path) -> PathBuf {
        root.join("Hooks")
    }

    /// A stand-in for `openlatch-hook` that records the argv and stdin it was
    /// handed and then answers with a deny.
    ///
    /// The recording half is the point: a test that only checks the shim's
    /// stdout passes just as happily when the binary was never invoked at all.
    #[cfg(unix)]
    fn write_fake_hook_binary(path: &Path, record: &Path) {
        let record = record.display().to_string();
        let body = String::from("#!/bin/sh\n")
            + "for a in \"$@\"; do printf '%s\\n' \"$a\" >> "
            + &quote_posix(&record)
            + "; done\n"
            + "cat >> "
            + &quote_posix(&record)
            + "\n"
            + "printf '{\"verdict\":\"deny\",\"reason\":\"rm -rf /\"}'\n";
        crate::fs_secure::write_executable(path, &body).expect("write the fake hook binary");
    }

    /// Run a POSIX shim the way Cline would, feeding it an event on stdin.
    #[cfg(unix)]
    fn run_shim(shim: &Path, stdin: &str) -> std::process::Output {
        use std::io::Write as _;
        use std::process::{Command, Stdio};

        let mut child = Command::new(shim)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("the shim is executable");
        child
            .stdin
            .take()
            .expect("piped stdin")
            .write_all(stdin.as_bytes())
            .expect("feed the shim");
        child.wait_with_output().expect("the shim exits")
    }

    /// **The prime invariant, proven rather than observed.**
    ///
    /// The daemon answers with a deny; the developer's session must not notice.
    /// All three assertions are load-bearing — without the first, the test
    /// passes on a shim that never ran the binary at all.
    #[test]
    #[cfg(unix)]
    fn a_deny_verdict_never_reaches_the_file_lane() {
        let root = tempfile::tempdir().expect("temp dir");
        let record = root.path().join("invocation.txt");
        let fake = root.path().join("fake-openlatch-hook");
        write_fake_hook_binary(&fake, &record);

        let dir = hooks_dir(root.path());
        write_all(&dir, &fake, root.path()).expect("write the ten");

        let output = run_shim(&dir.join("PreToolUse"), r#"{"toolName":"execute_command"}"#);

        let recorded = std::fs::read_to_string(&record)
            .expect("the fake binary was never invoked — the shim ran nothing");
        let argv: Vec<&str> = recorded.lines().collect();
        assert!(
            argv.contains(&"--agent") && argv.contains(&"cline"),
            "argv did not name the agent: {argv:?}"
        );
        assert!(
            argv.contains(&"--event") && argv.contains(&"pre_tool_use"),
            "argv did not carry the snake_case wire event: {argv:?}"
        );
        assert!(
            argv.contains(&"--capture-only"),
            "the file lane must never wait on a hold: {argv:?}"
        );
        assert!(
            recorded.contains("execute_command"),
            "the event body never reached the binary: {recorded}"
        );

        assert!(
            output.status.success(),
            "a shim that exits non-zero aborts the run: {:?}",
            output.status
        );
        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            "{}",
            "the deny reached the agent; this kills the whole session, not one tool call"
        );
    }

    /// **Plan 01's invariant, re-asserted now that a `cline` translator EXISTS.**
    ///
    /// `a_deny_verdict_never_reaches_the_file_lane` above was written when
    /// `hook_output` had no Cline arm, so a `{}` from the shim could not be told
    /// apart from the `_ => empty()` fallback every unknown agent gets. It can
    /// now: the plugin lane renders a deny as `{"skip":true,...}`, and this
    /// feeds the shim a binary answering in exactly that shape.
    ///
    /// `{}` here is therefore a **discard**, which is the whole claim. A shim
    /// that forwarded the skip would set `cancel` -> `stop` ->
    /// `ControlledStopError` and abort the developer's entire task instead of
    /// the one tool call — the failure the plugin lane exists to avoid.
    #[test]
    #[cfg(unix)]
    fn the_file_lane_still_prints_empty() {
        let root = tempfile::tempdir().expect("temp dir");
        let fake = root.path().join("fake-openlatch-hook");
        crate::fs_secure::write_executable(
            &fake,
            "#!/bin/sh\ncat >/dev/null\nprintf '{\"skip\":true,\"reason\":\"rm -rf /\"}'\n",
        )
        .expect("a fake hook binary answering in the PLUGIN lane's shape");

        let dir = hooks_dir(root.path());
        write_all(&dir, &fake, root.path()).expect("write the ten");

        for event in CLINE_HOOK_FILES {
            let output = run_shim(
                &dir.join(file_name_for(event, false)),
                r#"{"toolName":"run_commands","parameters":{"command":"rm -rf /tmp"}}"#,
            );
            assert!(
                output.status.success(),
                "{event}: a shim that exits non-zero aborts the run: {:?}",
                output.status
            );
            assert_eq!(
                String::from_utf8_lossy(&output.stdout),
                "{}",
                "{event}: a real verdict reached the file lane; enforcement belongs to \
                 the plugin, and this kills the whole session rather than one tool call"
            );
        }
    }

    /// Both halves on every host — D-03's whole reason for taking the platform
    /// as a parameter.
    #[test]
    fn both_platform_shapes_are_generated() {
        assert_eq!(file_name_for("PreToolUse", true), "PreToolUse.ps1");
        assert_eq!(file_name_for("PreToolUse", false), "PreToolUse");

        let bin = Path::new("staged").join("openlatch-hook");
        let ol_dir = Path::new("openlatch-dir");

        let posix = shim_body(&bin, ol_dir, "pre_tool_use", ENTRY_ID, false);
        assert!(
            posix.starts_with("#!/bin/sh\n"),
            "the POSIX shim needs its shebang: {posix}"
        );
        assert!(posix.contains(">/dev/null 2>&1"), "{posix}");
        assert!(posix.ends_with("printf '{}'\n"), "{posix}");

        let powershell = shim_body(&bin, ol_dir, "pre_tool_use", ENTRY_ID, true);
        assert!(
            !powershell.starts_with("#!"),
            "PowerShell has no shebang, which is why the marker may sit on line 1: {powershell}"
        );
        // Pin the INVARIANT, not a command shape. `| Out-Null` used to be here
        // and was wrong: it discards only the success stream, leaving native
        // stderr and PowerShell error records to reach Cline, and under
        // `$ErrorActionPreference = 'Stop'` a stderr write TERMINATES the script
        // before `Write-Output` ever runs.
        assert!(
            powershell.contains("*> $null"),
            "every stream must be suppressed, not just stdout: {powershell}"
        );
        assert!(
            !powershell.contains("| Out-Null"),
            "`| Out-Null` discards stdout ALONE — it is not sufficient: {powershell}"
        );
        assert!(
            powershell.contains("try {") && powershell.contains("catch {"),
            "a terminating error must not skip the `{{}}`: {powershell}"
        );
        assert!(
            powershell.ends_with("Write-Output '{}'\nexit 0\n"),
            "the Windows half must print exactly `{{}}` and exit 0, like the \
             POSIX half whose trailing `printf` cannot fail: {powershell}"
        );

        // Neither half may leak a verdict: the POSIX one sends both streams to
        // /dev/null and ends on `printf`, which cannot fail; the Windows one
        // suppresses all streams, cannot terminate early, and exits 0.
        assert!(
            !posix.contains("2>&1 >"),
            "redirection order matters: `2>&1 >file` leaves stderr on the terminal"
        );

        // Line 2 on POSIX, line 1 on Windows, and both recognisably ours.
        assert!(is_ours(&posix), "{posix}");
        assert!(is_ours(&powershell), "{powershell}");
        assert_eq!(owning_marker_line(&posix), Some(1));
        assert_eq!(owning_marker_line(&powershell), Some(0));
    }

    #[test]
    fn all_ten_are_written_and_executable() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = hooks_dir(root.path());
        let bin = root.path().join("bin").join("openlatch-hook");

        let written = write_all(&dir, &bin, root.path())
            .expect("write the ten")
            .written;
        assert_eq!(written.len(), 10, "ten events, ten files");

        let mut got: Vec<String> = std::fs::read_dir(&dir)
            .expect("the installer creates the directory")
            .map(|e| {
                e.expect("dir entry")
                    .file_name()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        got.sort();
        let mut want: Vec<String> = CLINE_HOOK_FILES.iter().map(|e| hook_file_name(e)).collect();
        want.sort();
        assert_eq!(got, want);

        for file in &written {
            let path = Path::new(&file.descriptor.path);
            let body = std::fs::read_to_string(path).expect("read back");
            assert_eq!(
                sha256_hex(&body),
                file.descriptor.sha256,
                "the descriptor must hash the bytes on disk"
            );
            assert!(is_ours(&body), "our own file must satisfy the predicate");
            assert!(
                body.contains(&file.entry_id),
                "the marker and the state row must name one uuid"
            );

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt as _;
                let mode = std::fs::metadata(path).expect("stat").permissions().mode() & 0o777;
                assert_eq!(
                    mode, HOOK_FILE_MODE,
                    "{} is not executable; every Cline event would be permission-denied",
                    file.descriptor.path
                );
            }
        }
    }

    #[test]
    fn a_file_we_did_not_write_is_never_removed() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = hooks_dir(root.path());
        write_all(&dir, &root.path().join("openlatch-hook"), root.path()).expect("write the ten");

        // The developer's own script, sitting at one of the ten names.
        let theirs = dir.join(hook_file_name("PostToolUse"));
        std::fs::write(&theirs, "#!/bin/sh\n# my own hook\n").expect("their file");

        // Ours, then edited: the marker line survives, the hash no longer
        // matches, so the predicate's second half is what catches it.
        let edited = dir.join(hook_file_name("PreToolUse"));
        let mut body = std::fs::read_to_string(&edited).expect("read ours");
        body.push_str("echo tampered\n");
        std::fs::write(&edited, &body).expect("edit ours");

        let report = remove_all(&dir).expect("remove");

        assert_eq!(report.removed.len(), 8, "the untouched eight come out");
        assert!(theirs.exists(), "the developer's file was deleted");
        assert!(
            edited.exists(),
            "an edited file is no longer ours to delete"
        );
        assert!(report.left.contains(&theirs), "{:?}", report.left);
        assert!(report.left.contains(&edited), "{:?}", report.left);
        assert_eq!(
            std::fs::read_to_string(&theirs).expect("read theirs"),
            "#!/bin/sh\n# my own hook\n",
            "the developer's file was modified"
        );
    }

    /// A directory sitting at one of the ten names is the developer's, and
    /// neither install nor uninstall may turn it into an error.
    ///
    /// `uninstall` gates the model-relay teardown on `remove_hooks` returning
    /// `Ok`, so an `Err` raised over a path we were never going to touch would
    /// leave Cline pointed at a dead loopback port.
    #[test]
    fn an_unreadable_artefact_never_fails_either_direction() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = hooks_dir(root.path());
        let occupied = dir.join(hook_file_name("PreToolUse"));
        std::fs::create_dir_all(&occupied).expect("occupy the path with a directory");

        let report =
            write_all(&dir, &root.path().join("openlatch-hook"), root.path()).expect("install");
        assert_eq!(report.written.len(), 9, "the other nine still install");
        assert_eq!(
            report.left.len(),
            1,
            "and the one we did not write is reported as left alone, not merely absent \
             from `written` — this is what lets a caller tell a partial install from a \
             complete one without counting against an agent-named constant"
        );

        let report = remove_all(&dir).expect("uninstall must not error over someone else's path");
        assert_eq!(report.removed.len(), 9);
        assert!(report.left.contains(&occupied), "{:?}", report.left);
        assert!(occupied.is_dir(), "the developer's directory was removed");
    }

    /// Quoting alone is not enough; the quote character has to be escaped, and
    /// the two shells do it differently.
    #[test]
    fn a_path_with_an_apostrophe_is_escaped() {
        let bin = Path::new("/Users/O'Brien/bin/openlatch-hook");
        let ol_dir = Path::new("/Users/O'Brien/.openlatch");

        let posix = shim_body(bin, ol_dir, "pre_tool_use", ENTRY_ID, false);
        assert!(
            posix.contains(r"'/Users/O'\''Brien/bin/openlatch-hook'"),
            "POSIX closes, escapes and reopens: {posix}"
        );
        assert!(posix.contains(r"'/Users/O'\''Brien/.openlatch'"), "{posix}");

        let powershell = shim_body(bin, ol_dir, "pre_tool_use", ENTRY_ID, true);
        assert!(
            powershell.contains("'/Users/O''Brien/bin/openlatch-hook'"),
            "PowerShell doubles it: {powershell}"
        );
        assert!(
            powershell.contains("'/Users/O''Brien/.openlatch'"),
            "{powershell}"
        );
    }

    /// The POSIX half of the escaping, executed by a real `/bin/sh` rather than
    /// matched as a string. The record file deliberately lives on a clean path,
    /// so the fixture does not depend on the escaping it is checking.
    #[test]
    #[cfg(unix)]
    fn an_apostrophe_in_the_path_survives_a_real_shell() {
        let root = tempfile::tempdir().expect("temp dir");
        let record = root.path().join("invocation.txt");
        let odd = root.path().join("O'Brien");
        std::fs::create_dir_all(&odd).expect("create the awkward directory");

        let fake = odd.join("fake-openlatch-hook");
        write_fake_hook_binary(&fake, &record);

        let dir = hooks_dir(&odd);
        write_all(&dir, &fake, &odd).expect("write the ten");

        let output = run_shim(&dir.join("PreToolUse"), "{}");

        assert!(
            record.exists(),
            "the shim never reached the binary: stderr {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(output.status.success(), "{:?}", output.status);
        assert_eq!(String::from_utf8_lossy(&output.stdout), "{}");
    }

    /// §2's structural backstop, and the only guard that does not depend on the
    /// next author reading the isolation rule.
    ///
    /// The needles are assembled from fragments so that this test does not
    /// itself put the forbidden spellings in the file it scans.
    #[test]
    fn no_resolver_is_called_from_the_writer() {
        let source = include_str!("hook_files.rs");
        let forbidden = [
            concat!("asset", "_root"),
            concat!("document", "_dir"),
            concat!("hook", "_config_path"),
        ];

        for needle in forbidden {
            assert!(
                !source.contains(needle),
                "this module resolves a path through `{needle}`; it must take its \
                 directory as a parameter, or a unit test can reach the developer's \
                 real install"
            );
        }
    }

    /// A marker below the second line is not a marker: the two shapes put it on
    /// line 1 and line 2, and a file whose real first lines are someone else's
    /// is someone else's.
    #[test]
    fn a_marker_below_the_second_line_is_not_ours() {
        let tail = "echo hello\n";
        let digest = sha256_hex(&format!("#!/bin/sh\necho first\n{tail}"));
        let body = format!("#!/bin/sh\necho first\n# openlatch-hook {digest}\n{tail}");

        assert!(!is_ours(&body), "{body}");
    }

    /// The uuid group is optional and the prefix is parametric, so a surface
    /// with no hook event — a plugin file, say — shares this predicate instead
    /// of inventing a second one.
    #[test]
    fn a_marker_without_a_uuid_and_behind_a_slash_prefix_is_ours() {
        let tail = "console.log('{}');\n";
        let digest = sha256_hex(tail);
        let body = format!("// openlatch-hook {digest}\n{tail}");

        assert!(is_ours(&body), "{body}");
        assert_eq!(owning_marker_line(&body), Some(0));
    }

    /// An id that cannot fit the predicate's uuid group is dropped from the
    /// marker rather than written into it.
    ///
    /// Writing it would produce a file matching nothing — an orphan on the
    /// developer's disk that uninstall, health and the reconciler would all
    /// read as theirs and refuse to touch. The breadcrumb is expendable; being
    /// able to recognise our own file is not.
    #[test]
    fn a_malformed_entry_id_is_dropped_rather_than_written() {
        let body = shim_body(
            Path::new("openlatch-hook"),
            Path::new("ol"),
            "pre_tool_use",
            "not-a-uuid",
            false,
        );

        assert!(!body.contains("not-a-uuid"), "{body}");
        assert!(is_ours(&body), "the file must still be recognisably ours");

        let kept = shim_body(
            Path::new("openlatch-hook"),
            Path::new("ol"),
            "pre_tool_use",
            ENTRY_ID,
            false,
        );
        assert!(kept.contains(ENTRY_ID), "a well-formed id is kept: {kept}");
        assert!(is_ours(&kept));
    }

    /// The hash covers the body, so editing anything but the marker breaks it.
    #[test]
    fn an_edited_body_stops_being_ours() {
        let bin = Path::new("openlatch-hook");
        let body = shim_body(bin, Path::new("ol"), "pre_tool_use", ENTRY_ID, false);
        assert!(is_ours(&body));

        assert!(!is_ours(&format!("{body}echo extra\n")));
        assert!(!is_ours(&body.replace("pre_tool_use", "post_tool_use")));
    }

    /// A reinstall over our own file keeps a copy for `doctor --restore`, and
    /// the suffix appends rather than replacing an extension.
    #[test]
    fn rewriting_our_own_file_leaves_a_backup() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = hooks_dir(root.path());
        let bin = root.path().join("openlatch-hook");

        let first = write_all(&dir, &bin, root.path())
            .expect("first install")
            .written;
        assert!(
            first.iter().all(|f| !f.replaced),
            "a first install replaces nothing"
        );
        let path = Path::new(&first[0].descriptor.path).to_path_buf();
        let original = std::fs::read_to_string(&path).expect("read the first body");

        write_all(&dir, &bin, root.path()).expect("second install");

        let backup = dir.join(format!("{}.bak", hook_file_name(CLINE_HOOK_FILES[0])));
        assert_eq!(
            std::fs::read_to_string(&backup).expect("the backup is there"),
            original
        );
        assert!(path.exists(), "the live script must still be in place");
    }
}