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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
//! Cline's **enforcement** surface: one plugin, one file, one verdict lane.
//!
//! [`crate::hooks::hook_files`] writes the ten hook scripts and every one of
//! them discards the daemon's answer, because a `cancel` returned through
//! Cline's file-hook lane raises `ControlledStopError` and aborts the
//! developer's whole task. This module writes the artefact that *can* refuse a
//! single tool call: a plugin whose `beforeTool` returns `{skip, reason}`.
//!
//! # Where it goes, and why it is not beside the ten
//!
//! `<store root>/plugins/openlatch/index.js` — a **directory under the store
//! root**, not under the user-asset root where `Hooks/` lives. Cline's plugin
//! search path is `join(resolveClineDir(), "plugins")` (`paths.ts:567`, v4.1.17)
//! and its directory scan takes `index.js` as the entry point of any directory
//! it walks into (`PLUGIN_DIRECTORY_INDEX_CANDIDATES`, `paths.ts:594`). The
//! **directory name is the plugin id**, which is what `disabledPlugins` in
//! `global-settings.json` holds — so the id is [`PLUGIN_ID`] and the artefact is
//! [`PLUGIN_ENTRY_FILE_NAME`] inside it.
//!
//! Every predicate here therefore hangs on the **file**. The directory is the
//! id; the file is the thing we own, back up, verify and remove.
//!
//! # One ownership marker, not a second one
//!
//! `// openlatch-hook <sha256-of-the-body-without-this-line>` on line 2, matched
//! by [`hook_files::is_ours`] — the same predicate the ten use, unchanged. Its
//! comment prefix is parametric (`#` or `//`) and its uuid group is optional for
//! exactly this artefact: the plugin has no hook event, so there is no
//! per-entry UUIDv7 to carry. A file at this path that fails that predicate is
//! the developer's and is never written, never removed, only reported.
//!
//! # This module resolves nothing
//!
//! Like [`hook_files`], every entry point takes its directory as a parameter and
//! calls no path resolver. A unit test hands it a `tempdir()` and physically
//! cannot reach `~/.cline`, whose `data/secrets.json` holds plaintext API keys.
//! Resolution happens once, on the binding
//! ([`crate::hooks::binding::AgentBinding::plugin_surface`]).
//! `no_resolver_is_called_from_the_plugin_writer` greps this file and fails on a
//! hit.
//!
//! # The switch is the developer's
//!
//! Nothing here reads or writes `global-settings.json`. [`is_disabled`] is a
//! pure predicate over the list Cline asserts, offered so a *reporter* can say
//! "installed but switched off"; install must never take a plugin off
//! `disabledPlugins`, because that is the developer's control and not ours.

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

use crate::core::hook_state::FileDescriptor;
use crate::error::{OlError, ERR_HOOK_WRITE_FAILED};
use crate::hooks::hook_files::{self, Existing};

/// The plugin id, which **is** the directory name Cline discovers it under and
/// the string `disabledPlugins` would hold.
pub const PLUGIN_ID: &str = "openlatch";

/// The entry file inside [`PLUGIN_ID`]'s directory.
///
/// One of Cline's two `PLUGIN_DIRECTORY_INDEX_CANDIDATES`; the other is
/// `index.ts`, which needs a transpile step we have no reason to ask for.
pub const PLUGIN_ENTRY_FILE_NAME: &str = "index.js";

/// The mode the entry file is left in, and the value recorded in its
/// descriptor.
///
/// **0644, not the ten's 0755.** Node *imports* this file; nothing ever
/// executes it. Writing 0755 would hand the developer an executable that is not
/// one, on a path where the execute bit can only ever mislead.
pub const PLUGIN_FILE_MODE: u32 = 0o644;

/// The `hook_event` the plugin's **one** state row is keyed under.
///
/// The key is `(agent, settings_path_hash, hook_event)` — the same triple the
/// ten hook files use — so the plugin has to name a value in a namespace it
/// shares with Cline's own hook names. It has no hook event of its own, hence
/// a spelling Cline could not produce.
///
/// `the_plugin_entry_event_collides_with_no_hook` is what keeps that true: a
/// Cline event arriving under this name would alias the plugin's row onto that
/// hook file's, one silently overwriting the other on every install, and the
/// reconciler would then verify one artefact twice and the other never.
pub const PLUGIN_ENTRY_EVENT: &str = "__plugin";

/// The plugin source, embedded at compile time.
///
/// A **template**, not the finished file: `include_str!` is compile-time and the
/// plugin cannot otherwise learn where its daemon lives, so the installer
/// substitutes [`OL_DIR_PLACEHOLDER`] at write time. No runtime fetch, and
/// nothing but a path is ever baked in — D-09 forbids a daemon token reaching
/// an agent's own tree.
const PLUGIN_TEMPLATE: &str = include_str!("../../assets/cline/openlatch-plugin.js");

/// The token in [`PLUGIN_TEMPLATE`] the installer replaces with a JSON-quoted
/// `<ol_dir>`.
///
/// A bare identifier so the template is still parseable JavaScript, which is
/// what lets `node --check` and an editor's language server read the asset as
/// the file it becomes.
const OL_DIR_PLACEHOLDER: &str = "__OPENLATCH_DIR__";

/// The placeholder the shell-tool list is substituted into.
///
/// The list keeps ONE owner — `core::policy::SHELL_TOOL_NAMES` — and reaches
/// the plugin the same way `<ol_dir>` does, at write time. A second hand-kept
/// copy in JavaScript is how the plugin comes to spawn for a tool no rule can
/// match, or to skip one that a rule just started matching.
const SHELL_TOOLS_PLACEHOLDER: &str = "__OPENLATCH_SHELL_TOOLS__";

/// The entry file's path inside `plugin_dir`.
///
/// One function, so install, backup, removal and any future verifier cannot
/// come to disagree about which file carries the plugin.
#[must_use]
pub fn entry_path(plugin_dir: &Path) -> PathBuf {
    plugin_dir.join(PLUGIN_ENTRY_FILE_NAME)
}

/// The exact bytes [`install`] writes for this `ol_dir`, marker line included.
///
/// Public and deterministic on purpose: it is the **one generator**, so a
/// verifier asking "is the file on disk what we would write today?" renders
/// from this rather than from a second, drifting copy.
///
/// The marker cannot be computed from the finished file — it carries a hash of
/// the body with the marker line removed — so the substituted template is built
/// first and the line is spliced in after the banner comment, leaving it on
/// line 2 where [`hook_files::is_ours`] looks.
#[must_use]
pub fn plugin_body(ol_dir: &Path) -> String {
    let unmarked = PLUGIN_TEMPLATE
        .replace(OL_DIR_PLACEHOLDER, &js_string_literal(ol_dir))
        .replace(SHELL_TOOLS_PLACEHOLDER, &shell_tools_literal());
    let digest = hook_files::sha256_hex(&unmarked);
    let (head, tail) = split_after_first_line(&unmarked);
    format!("{head}// openlatch-hook {digest}\n{tail}")
}

/// `SHELL_TOOL_NAMES` as a JavaScript array literal.
///
/// Rendered through `serde_json` for the same reason `js_string_literal` is:
/// it is the same grammar, so the escaping is not ours to get wrong.
fn shell_tools_literal() -> String {
    serde_json::to_string(crate::core::policy::SHELL_TOOL_NAMES)
        .unwrap_or_else(|_| "[]".to_string())
}

/// `path` as a JavaScript string literal, quotes included.
///
/// Through `serde_json`, which is the same grammar: it escapes the backslashes
/// of a Windows path, an apostrophe or quote in a developer's home directory,
/// and any control character, so no call site re-derives an escape. A path that
/// somehow fails to serialize becomes the empty string rather than an unquoted
/// fragment that would make the file a syntax error — a plugin that fails to
/// load is Cline's own fail-open, a plugin that breaks the parse is noise in
/// the developer's log.
fn js_string_literal(path: &Path) -> String {
    serde_json::to_string(path.to_string_lossy().as_ref()).unwrap_or_else(|_| "\"\"".to_string())
}

/// `body` split immediately after its first line terminator.
///
/// `split_inclusive` rather than `lines()`, for the reason
/// [`hook_files::is_ours`]' own splitter gives: the hash is taken over exact
/// bytes and `lines()` drops every terminator it walks past.
fn split_after_first_line(body: &str) -> (&str, &str) {
    match body.find('\n') {
        Some(index) => body.split_at(index + 1),
        None => (body, ""),
    }
}

/// Is [`PLUGIN_ID`] on the list of plugins Cline asserts are switched off?
///
/// A pure predicate over the list a *caller* read, never a read of its own:
/// this module does not touch `global-settings.json` in either direction. That
/// separation is the point — knowing the plugin is disabled is a reporting
/// fact, and re-enabling it is a decision that belongs to the developer who
/// made it.
///
/// `None` — we could not tell — is not disabled. A probe that failed to read
/// the file must not be rendered as the developer having switched enforcement
/// off.
#[must_use]
pub fn is_disabled(disabled_plugins: Option<&[String]>) -> bool {
    disabled_plugins.is_some_and(|list| list.iter().any(|id| id == PLUGIN_ID))
}

/// `<plugins directory>/<PLUGIN_ID>` — the one composition of the plugin's own
/// directory name.
///
/// Takes the `plugins` directory as a parameter, like everything else here, and
/// exists so the binding's `plugin_surface`, the live resolver in
/// [`crate::hooks::cline`] and the probe all spell `.join(PLUGIN_ID)` once. Two
/// spellings of one directory is how a reporter comes to describe a different
/// directory from the one the installer wrote.
#[must_use]
pub fn plugin_dir(plugins_dir: &Path) -> PathBuf {
    plugins_dir.join(PLUGIN_ID)
}

/// Which lane, if any, can refuse a single Cline tool call on this host.
///
/// **Closed at three, and one of the three is always the answer.** Every Cline
/// host has an enforcement surface — `none` is a surface, not a missing field —
/// so a consumer asserting on this can never pass by the value being absent.
///
/// It is not a state of the *file*: [`PluginWrite`] and [`PluginRemoval`]
/// describe what a writer just did, this describes what the host can now do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnforcementSurface {
    /// Our plugin is at the entry path and Cline is not asserting it off: a
    /// deny reaches the developer.
    Plugin,
    /// Our plugin is there and [`PLUGIN_ID`] is on `disabledPlugins`. The
    /// artefact is ours and current, and Cline will not load it — the
    /// developer's switch, which is theirs to hold and never ours to flip.
    Disabled,
    /// Nothing of ours is at the entry path — never installed, uninstalled, or
    /// a file at that path that is somebody else's and was therefore left
    /// exactly where it is.
    None,
}

impl EnforcementSurface {
    /// The wire spelling — `plugin`, `disabled` or `none`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Plugin => "plugin",
            Self::Disabled => "disabled",
            Self::None => "none",
        }
    }

    /// Is a verdict deliverable through this surface?
    ///
    /// **Only [`Self::Plugin`].** `Disabled` and `None` are two different
    /// reasons for one answer, and collapsing them here rather than at each
    /// call site is what keeps the structured *why* (this value) and the
    /// verdict (`liveness`, `OL-1410`) from becoming two detectors that can
    /// disagree.
    #[must_use]
    pub fn is_enforcing(self) -> bool {
        matches!(self, Self::Plugin)
    }
}

/// **THE** enforcement detector: owned, present, and not switched off.
///
/// One question — *can this host refuse a Cline tool call?* — answered in one
/// place, for the binding's `liveness()` and `capabilities()`, for the
/// attestation's `enforcement_surface`, and for whatever asks next. A second
/// implementation is the second set of detectors the
/// one-question-one-set-of-detectors invariant forbids, and it is how a host
/// comes to report `plugin` beside a `Monitored — enforcing nothing` row.
///
/// Both inputs are parameters: the directory, because this module resolves
/// nothing, and the list, because reading `global-settings.json` belongs to
/// whichever caller already has it open. `disabled_plugins: None` — *we could
/// not tell* — is not disabled, per [`is_disabled`].
///
/// Ownership goes through [`hook_files::whatever_is_there`], the predicate
/// install, removal and the reconciler already share rather than a copy of it:
/// a file at the entry path that is not ours is not an enforcement surface of
/// ours, which is exactly what [`install`] decided when it refused to overwrite
/// it.
#[must_use]
pub fn enforcement_surface(
    plugin_dir: &Path,
    disabled_plugins: Option<&[String]>,
) -> EnforcementSurface {
    match hook_files::whatever_is_there(&entry_path(plugin_dir)) {
        Existing::Ours if is_disabled(disabled_plugins) => EnforcementSurface::Disabled,
        Existing::Ours => EnforcementSurface::Plugin,
        Existing::Nothing | Existing::Theirs => EnforcementSurface::None,
    }
}

/// What [`install`] or [`repair`] did at the entry path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PluginWrite {
    /// The plugin was written. `replaced` is `true` when something was already
    /// at the path, `false` when it was free — through [`install`] that can
    /// only ever have been a plugin of ours, through [`repair`] it is whatever
    /// had taken its place.
    Written {
        /// `{path, sha256, mode}` for the bytes just written.
        descriptor: FileDescriptor,
        /// Whether this write went over a file that was already there.
        replaced: bool,
    },
    /// What is at the entry path is already byte-for-byte what we would write.
    /// Nothing was written and — the load-bearing half — nothing was backed up.
    ///
    /// Not an optimisation. Without this answer every re-run of `init` and
    /// every reconciler pass copies the live body over `index.js.bak`, so the
    /// backup ends up holding a duplicate of the file beside it and whatever it
    /// was preserving — the damaged original a heal just replaced — is gone.
    AlreadyCurrent(FileDescriptor),
    /// A file that is not ours sits at the entry path. It was not read for
    /// anything, not backed up, and not touched.
    LeftAlone(PathBuf),
}

/// What [`remove`] did at the entry path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PluginRemoval {
    /// Our plugin was there and is gone.
    Removed(PathBuf),
    /// There was nothing at the entry path.
    Nothing,
    /// A file that is not ours sits at the entry path and was left exactly as
    /// it was.
    LeftAlone(PathBuf),
}

/// Write the plugin into `plugin_dir`, creating the directory if it is absent.
///
/// `plugin_dir` and `ol_dir` are both parameters and neither is resolved here —
/// see the module header for why that is structural rather than stylistic.
///
/// **Collision.** A file at the entry path failing [`hook_files::is_ours`] is
/// the developer's: it is never overwritten and never read, and the caller is
/// handed [`PluginWrite::LeftAlone`] to report. A file that passes is ours and
/// is copied to `index.js.bak` before being rewritten, through
/// `hook_files::back_up` — `std::fs::copy`, which works on the **file** and
/// would have been meaningless against the directory.
///
/// # Errors
///
/// `OL-1401` if the directory, the backup or the file cannot be written. A
/// plugin that cannot be written is not a plugin, so an I/O failure propagates
/// rather than degrading to a skip — unlike a collision, which is a decision
/// about someone else's file.
pub fn install(plugin_dir: &Path, ol_dir: &Path) -> Result<PluginWrite, OlError> {
    let path = entry_path(plugin_dir);

    // Classified BEFORE the directory is created, so a collision costs no
    // filesystem change at all.
    if matches!(hook_files::whatever_is_there(&path), Existing::Theirs) {
        tracing::warn!(
            path = %path.display(),
            "a file we did not write already holds Cline's plugin entry point; \
             leaving it alone — enforcement stays off rather than overwriting it"
        );
        return Ok(PluginWrite::LeftAlone(path));
    }

    repair(plugin_dir, ol_dir)
}

/// Put the plugin at the entry path **whatever is there now**, and hand back
/// the descriptor of what is there afterwards.
///
/// The difference from [`install`] is one of *authority*, and it is the whole
/// of plan 02 §3a. `install` asks the file whether it is ours, through
/// [`hook_files::is_ours`]; this asks nobody, because its caller already knows
/// — the reconciler reaches it holding a state row that records this exact
/// path and the hash we last wrote there.
///
/// That distinction is not a loophole in the collision rule, it is what makes
/// heal possible at all: the self-describing marker proves a file is
/// internally consistent, not that it is what we would write today, and the
/// damage that matters most — a plugin corrupted badly enough to break its own
/// marker line — **fails** that predicate. Healing from the marker would repair
/// a cosmetic edit and walk away from real corruption.
///
/// A caller with no state row for this path must call [`install`], which will
/// leave a file it does not recognise exactly where it is.
///
/// **Why this may overwrite a file that fails `is_ours`, when the hook installer
/// may not.** The difference is which directory we are in, not which rule we
/// like. `Hooks/` is SHARED — the developer's own hooks live beside ours — so an
/// unrecognised file there is presumed theirs and is never touched.
/// `plugins/openlatch/` is OURS EXCLUSIVELY: we create it, the directory name is
/// our plugin id, and a developer's own plugin lives at `plugins/<their-name>/`.
///
/// Reaching this function at all means a caller held a state row for this exact
/// path, and that row is the authority the file can no longer supply for itself
/// — a plugin corrupted badly enough to mangle its marker line FAILS `is_ours`,
/// so refusing on that basis would walk away from precisely the damage repair
/// exists to undo. The backup below is what keeps the decision reversible.
///
/// The body comes from [`plugin_body`] — the same generator `install` uses,
/// re-rendered and never cached, so a repair cannot put the file into a state
/// an install would never produce.
///
/// # Errors
///
/// `OL-1401` if the directory, the backup or the file cannot be written.
pub fn repair(plugin_dir: &Path, ol_dir: &Path) -> Result<PluginWrite, OlError> {
    let path = entry_path(plugin_dir);
    let body = plugin_body(ol_dir);
    let descriptor = FileDescriptor {
        path: path.to_string_lossy().into_owned(),
        sha256: hook_files::sha256_hex(&body),
        mode: PLUGIN_FILE_MODE,
    };

    // Raw bytes, and deliberately not `is_ours`: the question here is only
    // whether a write would change anything. A plugin replaced with something
    // non-UTF-8 has to compare unequal rather than come back as a read error
    // the caller then has to interpret.
    let present = std::fs::read(&path).ok();
    if present.as_deref() == Some(body.as_bytes()) {
        return Ok(PluginWrite::AlreadyCurrent(descriptor));
    }

    std::fs::create_dir_all(plugin_dir).map_err(|e| write_failed(plugin_dir, &e))?;
    let replaced = present.is_some();
    if replaced {
        // `hook_files::back_up`, not `doctor_fix::backup_file`. Both make the
        // same `<name>.bak` copy, but the latter maps failure to
        // `ERR_INVALID_CONFIG` (OL-1300) — while this function's own `# Errors`
        // section promises OL-1401 for a backup that cannot be written. One of
        // the two had to move; the doc was right and the call site was wrong.
        hook_files::back_up(&path)?;
    }
    crate::fs_secure::write_readable(&path, &body).map_err(|e| write_failed(&path, &e))?;

    Ok(PluginWrite::Written {
        descriptor,
        replaced,
    })
}

/// Remove the plugin from `plugin_dir`, and only if it is ours.
///
/// The self-describing hash is the whole predicate — no state file is consulted
/// — which is what lets an uninstall work on a host whose state file was lost,
/// and what keeps a plugin the developer wrote under this name off the removal
/// list.
///
/// The `index.js.bak` backup is deliberately left behind, as the ten's are:
/// `doctor --restore` is what it exists for. The now-empty directory is removed
/// **best effort and only when empty** — `remove_dir` refuses a directory with
/// anything in it, so the backup, or anything else the developer put there,
/// keeps the directory alive rather than being taken with it.
///
/// # Errors
///
/// `OL-1401` if a file that is ours cannot be removed.
pub fn remove(plugin_dir: &Path) -> Result<PluginRemoval, OlError> {
    let path = entry_path(plugin_dir);

    match hook_files::whatever_is_there(&path) {
        Existing::Nothing => Ok(PluginRemoval::Nothing),
        Existing::Theirs => {
            tracing::warn!(
                path = %path.display(),
                "Cline's plugin entry point is not one of ours; leaving it in place"
            );
            Ok(PluginRemoval::LeftAlone(path))
        }
        Existing::Ours => {
            std::fs::remove_file(&path).map_err(|e| write_failed(&path, &e))?;
            // Best effort, and it cannot take anything with it: `remove_dir`
            // fails on a non-empty directory.
            let _ = std::fs::remove_dir(plugin_dir);
            Ok(PluginRemoval::Removed(path))
        }
    }
}

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

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

    /// 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.
    ///
    /// The last segment comes off [`super::plugin_dir`] rather than a second
    /// `.join(PLUGIN_ID)`: a fixture that spelled the id itself would keep
    /// passing against a writer that had moved it.
    fn plugin_dir(root: &Path) -> PathBuf {
        super::plugin_dir(&root.join("plugins"))
    }

    /// The 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_plugin_writer() {
        let source = include_str!("cline_plugin.rs");
        let forbidden = [
            concat!("store", "_root"),
            concat!("asset", "_root"),
            concat!("data", "_root"),
            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 Cline store — which holds plaintext API keys"
            );
        }
    }

    /// The template is a template, not the artefact: the placeholder must be
    /// there to substitute, and must be gone afterwards.
    /// The shell-tool list reaches the plugin from Rust, and every name in it.
    ///
    /// `beforeTool` fires for EVERY tool Cline runs — reads, writes, edits,
    /// browser and MCP calls. Only a shell tool can ever match a command rule,
    /// so a plugin that spawns `openlatch-hook` for the rest pays a process and
    /// a loopback round trip per tool call to be told `{}` — and posts a second
    /// envelope for an action the file shim already captured, which the daemon's
    /// dedup cannot collapse because it keys on `(session_id, tool_name,
    /// tool_input)` and this lane sends `{toolName, parameters}` with no session
    /// id. Every one of those spawns is a duplicate event on the cloud rail.
    ///
    /// Asserted against `SHELL_TOOL_NAMES` itself, never a hand-written list —
    /// a test that repeats the names it is checking would keep passing on the
    /// day the const grows a fourth and the plugin stops seeing it.
    #[test]
    fn the_body_carries_every_shell_tool_name() {
        assert!(
            PLUGIN_TEMPLATE.contains(SHELL_TOOLS_PLACEHOLDER),
            "the asset no longer carries the shell-tool placeholder; the plugin \
             would ship gating on nothing"
        );

        let body = plugin_body(Path::new("/tmp/ol"));
        assert!(
            !body.contains(SHELL_TOOLS_PLACEHOLDER),
            "the placeholder survived into the written body: {body}"
        );
        for name in crate::core::policy::SHELL_TOOL_NAMES {
            assert!(
                body.contains(&format!("\"{name}\"")),
                "`{name}` is in SHELL_TOOL_NAMES but not in the rendered plugin, \
                 so a rule matching it would never be consulted: {body}"
            );
        }
        assert!(
            body.contains("SHELL_TOOLS.has(toolCall?.toolName)"),
            "the list is in the body but nothing gates on it: {body}"
        );
    }

    #[test]
    fn the_ol_dir_placeholder_is_substituted() {
        assert!(
            PLUGIN_TEMPLATE.contains(OL_DIR_PLACEHOLDER),
            "the asset no longer carries the placeholder the installer replaces; the \
             plugin would ship with no way to find its daemon"
        );

        let body = plugin_body(Path::new("/tmp/ol"));
        assert!(
            !body.contains(OL_DIR_PLACEHOLDER),
            "the placeholder survived into the written body: {body}"
        );
        assert!(
            body.contains("\"/tmp/ol\""),
            "the openlatch directory is not in the body as a quoted literal: {body}"
        );
    }

    /// An apostrophe or a backslash in the path is a *syntax error* in the
    /// written file unless it is escaped, and a plugin that does not parse is a
    /// plugin that never runs.
    #[test]
    fn an_awkward_path_survives_as_a_javascript_literal() {
        let body = plugin_body(Path::new(r"/Users/O'Brien/\ol"));
        assert!(
            body.contains(r#""/Users/O'Brien/\\ol""#),
            "the path was not escaped as a JSON/JS string literal: {body}"
        );
    }

    /// The shared predicate, unchanged: plan 01's `is_ours` recognises this
    /// artefact with no state file, no uuid and a `//` comment prefix.
    #[test]
    fn the_plugin_is_ours_by_the_shared_predicate() {
        let body = plugin_body(Path::new("/tmp/ol"));
        assert!(
            hook_files::is_ours(&body),
            "the plugin must be recognisable as ours from its own bytes: {body}"
        );

        let marker = body.lines().nth(1).expect("a second line");
        assert!(
            marker.starts_with("// openlatch-hook "),
            "the marker belongs on line 2, behind a `//` prefix: {marker}"
        );
        assert_eq!(
            marker.split_whitespace().count(),
            3,
            "the plugin has no hook event and therefore no uuid to carry: {marker}"
        );
    }

    /// An edit of one byte stops the file being ours — which is what stops heal
    /// and uninstall touching a file somebody else has taken over.
    #[test]
    fn an_edited_plugin_stops_being_ours() {
        let body = plugin_body(Path::new("/tmp/ol"));
        assert!(!hook_files::is_ours(&format!("{body}// trailing edit\n")));
    }

    /// The artefact is a FILE inside a directory named for the id — the
    /// directory is what `disabledPlugins` matches, the file is what we own.
    #[test]
    fn the_artefact_is_index_js_under_the_id_directory() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());
        let entry = entry_path(&dir);

        assert_eq!(entry.file_name().expect("a file name"), "index.js");
        assert_eq!(
            entry
                .parent()
                .expect("a parent")
                .file_name()
                .expect("a directory name"),
            PLUGIN_ID,
            "the plugin id IS the directory name"
        );
    }

    /// A first install creates the directory it was given and writes one file,
    /// readable and **not** executable.
    #[test]
    fn a_first_install_writes_one_readable_file() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());
        assert!(
            !dir.exists(),
            "the fixture must not pre-create the directory"
        );

        let write = install(&dir, root.path()).expect("the plugin is written");

        let PluginWrite::Written {
            descriptor,
            replaced,
        } = write
        else {
            panic!("a free path is a write, not a collision: {write:?}");
        };
        assert!(!replaced, "the path was free");
        assert_eq!(descriptor.mode, PLUGIN_FILE_MODE);

        let path = entry_path(&dir);
        let body = std::fs::read_to_string(&path).expect("a readable plugin");
        assert_eq!(descriptor.sha256, hook_files::sha256_hex(&body));
        assert!(hook_files::is_ours(&body));

        let entries: Vec<String> = std::fs::read_dir(&dir)
            .expect("the installer created the directory")
            .map(|e| {
                e.expect("a readable entry")
                    .file_name()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        assert_eq!(
            entries,
            vec![PLUGIN_ENTRY_FILE_NAME.to_string()],
            "one artefact, exactly this name"
        );

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path)
                .expect("a stat-able plugin")
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(
                mode, 0o644,
                "Node imports this file; 0755 would claim it is an executable"
            );
        }
    }

    /// Rewriting our own plugin leaves `index.js.bak` beside it, so
    /// `doctor --restore` has something to return to.
    #[test]
    fn rewriting_our_own_plugin_leaves_a_backup() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());

        install(&dir, &root.path().join("first")).expect("first install");
        let first = std::fs::read_to_string(entry_path(&dir)).expect("the first body");

        let write = install(&dir, &root.path().join("second")).expect("second install");
        assert!(
            matches!(write, PluginWrite::Written { replaced: true, .. }),
            "a rewrite over our own file is a replacement: {write:?}"
        );

        let backup = dir.join("index.js.bak");
        assert_eq!(
            std::fs::read_to_string(&backup).expect("a backup beside the plugin"),
            first,
            "the backup must hold the bytes that were there before the rewrite"
        );
        assert_ne!(
            std::fs::read_to_string(entry_path(&dir)).expect("the new body"),
            first,
            "the second install pointed the plugin at a different openlatch directory"
        );
    }

    /// A file at the entry path that is not ours is never overwritten, never
    /// backed up and never removed — and the directory is not even created for
    /// it.
    #[test]
    fn a_file_we_did_not_write_is_never_touched() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());
        std::fs::create_dir_all(&dir).expect("the developer's own plugin directory");
        let path = entry_path(&dir);
        std::fs::write(&path, "export default { name: 'mine' };\n").expect("their plugin");

        let write = install(&dir, root.path()).expect("a collision is not an error");
        assert_eq!(write, PluginWrite::LeftAlone(path.clone()));
        assert_eq!(
            std::fs::read_to_string(&path).expect("still readable"),
            "export default { name: 'mine' };\n",
            "their file was rewritten"
        );
        assert!(
            !dir.join("index.js.bak").exists(),
            "a file we refuse to write must not be backed up either"
        );

        let removal = remove(&dir).expect("a collision is not an error");
        assert_eq!(removal, PluginRemoval::LeftAlone(path.clone()));
        assert!(path.exists(), "uninstall removed a file that is not ours");
    }

    /// Uninstall is the inverse of install: our file goes, and the directory it
    /// created goes with it once nothing is left in it.
    #[test]
    fn uninstall_removes_our_plugin_and_the_directory_it_created() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());

        assert_eq!(
            remove(&dir).expect("removing nothing is not an error"),
            PluginRemoval::Nothing
        );

        install(&dir, root.path()).expect("install");
        let removal = remove(&dir).expect("uninstall");
        assert_eq!(removal, PluginRemoval::Removed(entry_path(&dir)));
        assert!(!dir.exists(), "the directory install created is gone too");
    }

    /// A backup keeps the directory alive — `remove_dir` cannot take anything
    /// with it, which is the whole reason it is the call used.
    #[test]
    fn uninstall_never_takes_a_backup_with_it() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());

        install(&dir, root.path()).expect("first install");
        install(&dir, &root.path().join("second")).expect("second install, leaving a backup");
        remove(&dir).expect("uninstall");

        assert!(!entry_path(&dir).exists(), "our plugin is gone");
        assert!(
            dir.join("index.js.bak").exists(),
            "`doctor --restore` is what the backup exists for"
        );
    }

    /// The plugin's state row shares a key namespace with the ten hook files'.
    ///
    /// `(agent, settings_path_hash, hook_event)` is the whole key, so a Cline
    /// event that ever arrives spelled [`PLUGIN_ENTRY_EVENT`] would alias that
    /// hook file's row onto the plugin's — one silently overwriting the other
    /// on every install, after which the reconciler verifies one artefact twice
    /// and the other never. There is no compile error for that, so this is it.
    #[test]
    fn the_plugin_entry_event_collides_with_no_hook() {
        assert!(
            !hook_files::CLINE_HOOK_FILES.contains(&PLUGIN_ENTRY_EVENT),
            "`{PLUGIN_ENTRY_EVENT}` is now one of Cline's own hook events; the plugin's \
             state row aliases that hook file's and one of the two is lost"
        );

        // The file NAMES too, not just the event spellings: the ten are keyed
        // by event but discovered by file name, and on Windows those differ.
        for event in hook_files::CLINE_HOOK_FILES {
            assert_ne!(
                hook_files::hook_file_name(event),
                PLUGIN_ENTRY_EVENT,
                "a hook file is discovered under the plugin's own key"
            );
        }
    }

    /// `repair` is `install` minus the marker question — which is the only way
    /// the damage that matters can be fixed.
    ///
    /// A plugin corrupted badly enough to break its own marker line **fails**
    /// `is_ours`, so `install` leaves it exactly where it is. The reconciler
    /// reaches `repair` holding a state row for the path instead, and that row
    /// is the authority the file can no longer supply for itself.
    #[test]
    fn repair_rewrites_a_plugin_whose_marker_no_longer_parses() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());
        install(&dir, root.path()).expect("install");
        let want = std::fs::read_to_string(entry_path(&dir)).expect("the body we wrote");

        std::fs::write(entry_path(&dir), "corrupted\n").expect("corrupt it");
        assert!(
            !hook_files::is_ours("corrupted\n"),
            "the premise: corruption breaks the ownership predicate"
        );
        assert_eq!(
            install(&dir, root.path()).expect("a collision is not an error"),
            PluginWrite::LeftAlone(entry_path(&dir)),
            "install must still refuse it — that is what `repair` exists beside"
        );

        let write = repair(&dir, root.path()).expect("repair");
        assert!(
            matches!(write, PluginWrite::Written { replaced: true, .. }),
            "{write:?}"
        );
        assert_eq!(
            std::fs::read_to_string(entry_path(&dir)).expect("a readable plugin"),
            want,
            "the repair did not restore the body install writes"
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("index.js.bak")).expect("a backup"),
            "corrupted\n",
            "the damaged original is what the backup is for"
        );
    }

    /// A write that would change nothing writes nothing — and, the half that
    /// matters, backs nothing up.
    ///
    /// The reconciler repairs and then reinstalls over its own repair. Without
    /// this short-circuit the reinstall copies the freshly healed body over
    /// `index.js.bak`, destroying the damaged original the repair had just
    /// preserved there.
    #[test]
    fn an_unchanged_plugin_is_neither_rewritten_nor_backed_up() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());
        install(&dir, root.path()).expect("install");
        std::fs::write(dir.join("index.js.bak"), "the original\n").expect("an earlier backup");

        for write in [
            install(&dir, root.path()).expect("a second install"),
            repair(&dir, root.path()).expect("a repair over our own current file"),
        ] {
            assert!(
                matches!(write, PluginWrite::AlreadyCurrent(_)),
                "an identical body must not be rewritten: {write:?}"
            );
        }

        assert_eq!(
            std::fs::read_to_string(dir.join("index.js.bak")).expect("the backup"),
            "the original\n",
            "a write that did not happen overwrote the backup anyway"
        );
    }

    /// The developer's switch is read, never written.
    #[test]
    fn the_disabled_predicate_matches_the_id_and_nothing_else() {
        assert!(is_disabled(Some(&["openlatch".to_string()])));
        assert!(is_disabled(Some(&[
            "cosmos-guardrails".to_string(),
            "openlatch".to_string(),
        ])));
        assert!(!is_disabled(Some(&["openlatch-hook".to_string()])));
        assert!(!is_disabled(Some(&[])));
        assert!(
            !is_disabled(None),
            "we could not tell is not the developer having switched us off"
        );
    }

    /// The detector, over the four arrangements a host can actually be in.
    ///
    /// The one that has to be asserted rather than assumed is the last:
    /// a file at the entry path that is **not ours** is `None`, not `plugin`.
    /// `install` refused to write it, so nothing of ours is loaded there, and a
    /// host that reported `plugin` over a stranger's file would claim
    /// enforcement it does not have.
    #[test]
    fn the_detector_answers_from_the_file_and_the_switch() {
        let root = tempfile::tempdir().expect("temp dir");
        let dir = plugin_dir(root.path());
        let ol_dir = root.path().join("openlatch");

        assert_eq!(
            enforcement_surface(&dir, None),
            EnforcementSurface::None,
            "nothing installed is nothing to enforce with"
        );

        install(&dir, &ol_dir).expect("install the plugin");
        assert_eq!(enforcement_surface(&dir, None), EnforcementSurface::Plugin);
        assert_eq!(
            enforcement_surface(&dir, Some(&["something-else".to_string()])),
            EnforcementSurface::Plugin,
            "another plugin's id on the list says nothing about ours"
        );
        assert_eq!(
            enforcement_surface(&dir, Some(&[PLUGIN_ID.to_string()])),
            EnforcementSurface::Disabled,
            "ours, current, and switched off by the developer — a third state, not `none`"
        );

        std::fs::write(entry_path(&dir), "// someone else's plugin\n").expect("their file");
        assert_eq!(
            enforcement_surface(&dir, None),
            EnforcementSurface::None,
            "a file we refused to write is not an enforcement surface of ours"
        );
    }

    /// The three spellings are the closed vocabulary `doctor --json` publishes,
    /// and `is_enforcing` is true for exactly one of them.
    #[test]
    fn the_surface_vocabulary_is_closed_at_three() {
        for (surface, spelling, enforcing) in [
            (EnforcementSurface::Plugin, "plugin", true),
            (EnforcementSurface::Disabled, "disabled", false),
            (EnforcementSurface::None, "none", false),
        ] {
            assert_eq!(surface.as_str(), spelling);
            assert_eq!(
                surface.is_enforcing(),
                enforcing,
                "{spelling} must not be a pass: off is never a pass"
            );
        }
    }

    /// Nothing in this module may reach `global-settings.json`, in either
    /// direction: repairing our file and flipping the developer's switch are
    /// different acts and only one of them is ours to make.
    #[test]
    fn install_never_touches_global_settings() {
        let source = include_str!("cline_plugin.rs");
        let needle = concat!("global-", "settings.json");
        let in_code: Vec<&str> = source
            .lines()
            .filter(|line| line.contains(needle))
            .filter(|line| !line.trim_start().starts_with("//"))
            .collect();
        assert!(
            in_code.is_empty(),
            "this module names `{needle}` outside a comment; it must never read or \
             write the developer's plugin switch: {in_code:?}"
        );
    }

    // -----------------------------------------------------------------------
    // The plugin as Cline runs it
    // -----------------------------------------------------------------------

    /// `node`, or `None` on a developer machine that has none.
    ///
    /// **Loud in CI, quiet locally.** Every GitHub runner image this repo uses
    /// ships Node, so a missing interpreter there means the job changed rather
    /// than that the test is optional — and a test that only ever skips is a
    /// test that proves nothing. Locally it degrades, because a Rust
    /// contributor without Node should not be blocked by a JavaScript asset.
    /// `#[cfg(unix)]`, matching its three callers.
    ///
    /// Without it the Windows job fails with `function `node_or_skip` is never
    /// used` under `-D dead-code` — a helper gated differently from everything
    /// that calls it is dead code on the platform where the callers vanish.
    ///
    /// **What that gating costs, stated rather than hidden:** the plugin's
    /// never-throw behaviour is exercised only on Unix. The three tests drive a
    /// real `node` against a fake hook binary that is a shebang script, which
    /// Windows cannot execute. The JavaScript is platform-independent and the
    /// Rust either side of it is covered, but a Windows-only regression in the
    /// plugin's own error handling would not be caught here — and Windows is the
    /// platform the design partner runs. Closing that means a `.cmd` fake, which
    /// is its own unit of work.
    #[cfg(unix)]
    fn node_or_skip() -> Option<std::path::PathBuf> {
        let found = std::env::var_os("PATH")
            .map(|paths| std::env::split_paths(&paths).collect::<Vec<_>>())
            .unwrap_or_default()
            .into_iter()
            .map(|dir| dir.join("node"))
            .find(|candidate| candidate.is_file());

        assert!(
            found.is_some() || std::env::var_os("CI").is_none(),
            "node is not on PATH, and every runner image this repo builds on ships it: \
             a CI run without node cannot prove the plugin's fail-open"
        );
        found
    }

    /// Install the plugin into a tempdir and make plain `node` load it the way
    /// Cline's loader does.
    ///
    /// Cline imports plugins through **jiti** (`plugin-module-import.ts`,
    /// v4.1.17), which transpiles ESM in a `.js` file whatever the nearest
    /// `package.json` says. Bare `node` does not, so the fixture writes a
    /// `{"type":"module"}` marker **into the temp directory only**. It is a
    /// property of the harness, never of the artefact: nothing under
    /// `assets/cline/` or [`install`] writes one.
    #[cfg(unix)]
    fn stage_plugin_for_node(root: &Path, ol_dir: &Path) -> PathBuf {
        let dir = plugin_dir(root);
        install(&dir, ol_dir).expect("install the plugin");
        std::fs::write(dir.join("package.json"), r#"{"type":"module"}"#)
            .expect("the ESM marker plain node needs");
        entry_path(&dir)
    }

    /// Drive `beforeTool` once and return what it resolved with, as JSON.
    #[cfg(unix)]
    fn run_before_tool(
        node: &Path,
        entry: &Path,
        tool_name: &str,
        input_json: &str,
    ) -> serde_json::Value {
        let driver = entry.with_file_name("driver.mjs");
        std::fs::write(
            &driver,
            format!(
                "import plugin from {entry};\n\
                 const out = await plugin.hooks.beforeTool({{ toolCall: {{ toolName: {tool} }}, \
                 input: {input} }});\n\
                 process.stdout.write(JSON.stringify(out === undefined ? null : out));\n",
                entry = serde_json::to_string(&entry.to_string_lossy().as_ref())
                    .expect("a path serializes"),
                tool = serde_json::to_string(tool_name).expect("a name serializes"),
                input = input_json,
            ),
        )
        .expect("write the driver");

        let output = std::process::Command::new(node)
            .arg(&driver)
            .output()
            .expect("node runs");
        assert!(
            output.status.success(),
            "the plugin threw, which kills the developer's whole run: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
            panic!(
                "the plugin did not resolve with JSON ({e}): {:?}",
                String::from_utf8_lossy(&output.stdout)
            )
        })
    }

    /// A stand-in for `openlatch-hook` that records the stdin it was handed and
    /// answers with a `pre_tool_use` deny in the shape the translator emits.
    #[cfg(unix)]
    fn write_fake_hook_binary(ol_dir: &Path, record: &Path) {
        let bin_dir = ol_dir.join("bin");
        std::fs::create_dir_all(&bin_dir).expect("the staged bin directory");
        let record = record.display().to_string();
        let body = format!(
            "#!/bin/sh\ncat >> '{record}'\nprintf '{{\"skip\":true,\"reason\":\"rm -rf /\"}}'\n"
        );
        crate::fs_secure::write_executable(&bin_dir.join("openlatch-hook"), &body)
            .expect("write the fake hook binary");
    }

    /// **The fail-open, proven rather than asserted.**
    ///
    /// No daemon, and no `openlatch-hook` at all — the `<ol_dir>/bin` directory
    /// does not exist, so `spawn` fails the way it does on a host where staging
    /// never ran. The turn must complete: `beforeTool` resolves `undefined` and
    /// the process exits 0. A plugin that throws here takes the whole run with
    /// it.
    #[test]
    #[cfg(unix)]
    fn the_plugin_never_throws() {
        let Some(node) = node_or_skip() else {
            return;
        };
        let root = tempfile::tempdir().expect("temp dir");
        let ol_dir = root.path().join("openlatch");
        let entry = stage_plugin_for_node(root.path(), &ol_dir);

        let verdict = run_before_tool(
            &node,
            &entry,
            "run_commands",
            r#"{"command":"rm -rf /tmp"}"#,
        );
        assert_eq!(
            verdict,
            serde_json::Value::Null,
            "an unreachable hook binary must be the sanctioned fail-open, not a skip \
             and not a throw"
        );
    }

    /// A daemon that answers `{}` — the allow shape every non-deny renders — is
    /// also `undefined`, never an accidental skip.
    #[test]
    #[cfg(unix)]
    fn an_empty_answer_is_not_a_skip() {
        let Some(node) = node_or_skip() else {
            return;
        };
        let root = tempfile::tempdir().expect("temp dir");
        let ol_dir = root.path().join("openlatch");
        let bin_dir = ol_dir.join("bin");
        std::fs::create_dir_all(&bin_dir).expect("the staged bin directory");
        crate::fs_secure::write_executable(
            &bin_dir.join("openlatch-hook"),
            "#!/bin/sh\ncat >/dev/null\nprintf '{}'\n",
        )
        .expect("a fake hook binary that allows");

        let entry = stage_plugin_for_node(root.path(), &ol_dir);
        let verdict = run_before_tool(&node, &entry, "run_commands", r#"{"command":"ls"}"#);
        assert_eq!(verdict, serde_json::Value::Null);
    }

    /// The deny reaches Cline in the plugin lane's own shape, **and** the exact
    /// stdin payload survives the round trip untouched.
    ///
    /// The mixed input is the point: `parameters` carries a plain string, an
    /// object and an array under three keys, and the shim converts none of
    /// them. The re-typing lives once, daemon-side; a second owner in
    /// JavaScript is drift waiting to happen.
    #[test]
    #[cfg(unix)]
    fn a_mixed_input_survives_the_round_trip_and_the_deny_comes_back() {
        let Some(node) = node_or_skip() else {
            return;
        };
        let root = tempfile::tempdir().expect("temp dir");
        let ol_dir = root.path().join("openlatch");
        let record = root.path().join("stdin.json");
        write_fake_hook_binary(&ol_dir, &record);
        let entry = stage_plugin_for_node(root.path(), &ol_dir);

        let input =
            r#"{"command":"rm -rf /tmp","options":{"cwd":"/srv","timeout":5},"args":["-r","-f"]}"#;
        let verdict = run_before_tool(&node, &entry, "run_commands", input);

        assert_eq!(
            verdict,
            serde_json::json!({"skip": true, "reason": "rm -rf /"}),
            "the plugin lane's refusal is `{{skip, reason}}`"
        );

        let sent: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(&record)
                .expect("the hook binary was never invoked — the plugin spawned nothing"),
        )
        .expect("the plugin wrote JSON on stdin");

        assert_eq!(
            sent,
            serde_json::json!({
                "toolName": "run_commands",
                "parameters": {
                    "command": "rm -rf /tmp",
                    "options": {"cwd": "/srv", "timeout": 5},
                    "args": ["-r", "-f"],
                },
            }),
            "the plugin re-typed or dropped part of Cline's parameters"
        );
    }
}