openlatch-client 0.6.1

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
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
/// `openlatch uninstall` command handler.
///
/// Removes OpenLatch hooks from the agent config and stops the daemon.
/// Optionally deletes the openlatch data directory and the OS-keychain
/// credential with `--purge`.
///
/// SECURITY (T-02-08): Only deletes openlatch_dir(), never follows symlinks outside it.
/// Requires --yes or interactive confirmation.
use std::io::{IsTerminal, Write};

use crate::cli::commands::lifecycle;
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::UninstallArgs;
use crate::config;
use crate::error::{OlError, ERR_INVALID_CONFIG};
use crate::hooks;

/// Directory names `--purge` will delete.
///
/// The last line of defence before an unrecoverable `remove_dir_all`, so it is
/// a fixed list rather than a heuristic. Anything else — an `OPENLATCH_DIR`
/// pointed at a home directory, a repository root, a typo — is refused.
pub(crate) const PURGEABLE_STATE_DIR_NAMES: [&str; 2] = ["openlatch", ".openlatch"];

/// Would `--purge` accept a state directory with this basename?
///
/// Shared with `tools/sandbox` (the `olbox` binary), which has to produce a
/// layout this accepts: a sandbox is a complete install, so `uninstall --purge`
/// inside one must work. It did not — the sandbox state directory was called
/// `ol`, and the command refused it with `OL-1300` after it had already removed
/// the hooks and the supervisor, leaving a half-uninstalled sandbox. The
/// coupling is pinned by `tests::the_state_directory_olbox_creates_is_purgeable`
/// below, which is the only thing keeping the two repositories' halves in
/// agreement now that they build separately.
pub(crate) fn is_purgeable_state_dir_name(name: &str) -> bool {
    PURGEABLE_STATE_DIR_NAMES.contains(&name)
}

/// Resolve and validate what `--purge` would delete, before anything is
/// touched.
///
/// `Ok(None)` means there is nothing there — not an error, just an install
/// whose data directory is already gone. `Err` means the path exists and must
/// not be deleted, and returning it from step 0 is what keeps a rejected name
/// from costing the operator their hooks and their supervisor first.
///
/// # Errors
///
/// `OL-1300` when the path cannot be canonicalized, or when its basename is not
/// one [`is_purgeable_state_dir_name`] accepts.
fn resolve_purge_target() -> Result<Option<std::path::PathBuf>, OlError> {
    let ol_dir = config::openlatch_dir();
    if !ol_dir.exists() {
        return Ok(None);
    }

    // SECURITY: canonicalize before comparing, so a symlink cannot present an
    // acceptable basename for an unacceptable target.
    let canonical = std::fs::canonicalize(&ol_dir).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot canonicalize openlatch directory: {e}"),
        )
    })?;

    let dir_name = canonical.file_name().and_then(|n| n.to_str()).unwrap_or("");
    if !is_purgeable_state_dir_name(dir_name) {
        return Err(OlError::new(
            ERR_INVALID_CONFIG,
            format!(
                "Unexpected openlatch directory name '{}' — refusing to delete for safety",
                canonical.display()
            ),
        )
        .with_suggestion(format!(
            "`--purge` only deletes a directory named {}. Point OPENLATCH_DIR at one, or \
             delete this directory by hand. Nothing has been changed.",
            PURGEABLE_STATE_DIR_NAMES
                .map(|n| format!("'{n}'"))
                .join(" or ")
        )));
    }
    Ok(Some(canonical))
}

/// Is the install being uninstalled the machine's default one?
///
/// The OS keychain holds exactly one `openlatch` credential per machine, no
/// matter how many state directories sit beside it. A sandbox — `olbox`, a test
/// lab, any `OPENLATCH_DIR` override — is a complete install in every respect
/// except that one, so a `--purge` inside it that deleted the keychain entry
/// would log the machine's real install out of the cloud. Same reasoning
/// [`crate::supervision::unreproducible_environment`] applies to the supervisor
/// unit: a machine-global artifact belongs to the default install and to
/// nothing else.
///
/// Answered before anything is deleted, so both sides can still be
/// canonicalized (a path that no longer exists compares as written).
fn is_machine_default_install() -> bool {
    same_directory(&config::openlatch_dir(), &config::default_openlatch_dir())
}

/// Do two paths name the same directory? Resolved before comparing, so an
/// `OPENLATCH_DIR` pointed deliberately at the default — through a symlink, or
/// with a trailing slash — is still recognised as the default. A path that
/// cannot be resolved compares as written.
fn same_directory(a: &std::path::Path, b: &std::path::Path) -> bool {
    let canonical =
        |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    canonical(a) == canonical(b)
}

/// Run the `openlatch uninstall` command.
///
/// Steps:
/// 0. If --purge, resolve and validate the target — before anything is touched
/// 1. Confirm (unless --yes or non-interactive)
/// 2. Remove hooks from settings.json
/// 3. Stop the daemon
/// 4. If --purge, delete the openlatch data directory and the OS-keychain
///    credential
///
/// # Errors
///
/// Returns an error if hook removal or directory deletion fails.
/// Remove the hooks and the model-relay wiring from every selected agent.
///
/// **Extracted from [`run_uninstall`] so the guard below can be tested at all.**
/// The command it came from also tears down supervision, stops the daemon and
/// may purge the state directory, so a test that drove the whole thing to reach
/// this loop would be a test of the developer's machine. The loop is the part
/// with a regression in it; this is the part a test can hold.
///
/// One agent's failure never stops the others: leaving a second agent wired to a
/// daemon this command is about to stop is the worse outcome.
fn remove_from_agents(selected: &[hooks::DetectedAgent], output: &OutputConfig) {
    for agent in selected {
        // Provider slots wired to relay endpoints are handed back here and only
        // here — `openlatch stop` and a daemon restart leave them wired. Before
        // the hook surface, and independent of it for the same reason the
        // model-relay teardown below is: an agent we never wrote hooks for can
        // still have slots pointed at the relay. The daemon is still running at
        // this point; the tombstones this writes first are what stop its next
        // wiring pass from undoing the restore.
        #[cfg(feature = "model-relay")]
        if let Some(endpoints) = agent.binding.provider_endpoints() {
            let summary = hooks::provider_endpoints::release_all(
                endpoints,
                hooks::model_relay_endpoints::ReleasedBy::Teardown,
            );
            if summary.restored > 0 {
                output.print_step(&format!(
                    "Restored {} {} provider setting(s) the model relay had replaced",
                    summary.restored,
                    agent.binding.display_name()
                ));
            }
            for failure in &summary.failed {
                output.print_info(&format!(
                    "Warning: could not restore a provider setting: {failure}"
                ));
            }
        }
        // I-4 D-43: an agent with a ProxyEnv plane gets its deliveries back here too, BEFORE the
        // hook surface. A failed hook removal must never leave VS Code's `http.proxy` naming a
        // relay this command is about to stop. Idempotent with the release in the `Ok` arm below
        // (and in the not-installable arm's `remove_model_relay_config`). Claude Code and Codex
        // never take it.
        #[cfg(feature = "model-relay")]
        if hooks::declares_proxy_env(&*agent.binding) {
            if let Err(e) = hooks::release_proxy_env(
                &*agent.binding,
                hooks::model_relay_endpoints::ReleasedBy::Teardown,
            ) {
                output.print_info(&format!(
                    "Warning: could not release the model relay proxy settings: {} ({})",
                    e.message, e.code
                ));
            }
        }
        // An agent this build never writes HOOKS into has no hooks to remove.
        // `remove_hooks` refuses too — but it returns `Ok(())`, and the arm
        // below turns `Ok(())` into "Hooks removed from <path>", a claim about
        // a path we have never touched. The mirror of `init`'s skip: same
        // predicate, same silence.
        //
        // BUT IT STILL UNWIRES. Corrected 2026-09-14 by review: a bare
        // `continue` here skipped the whole loop body, including the
        // model-relay teardown below — and this file's own comment twenty lines
        // on says why that is wrong: "A `matches!` on `EnvVars` here would
        // silently exempt every future convention from uninstall." Skipping the
        // body does exactly that, by a different route. Hooks and wiring are
        // INDEPENDENT surfaces: `installable()` is about the hook surface only,
        // and an agent we never wrote a hook for can still be pointed at the
        // relay. Live since I-4: Cline declares `ProxyEnv`.
        if !agent.installable() {
            // Deliberately duplicated rather than hoisted. For an installable
            // agent this teardown is gated on `remove_hooks` returning `Ok`;
            // hoisting it out of that arm would run it after a FAILED hook
            // removal too, which is a behaviour change to Claude Code and Codex
            // CLI — and M4 requires this unit leave those two untouched.
            #[cfg(feature = "model-relay")]
            if let Err(e) = hooks::remove_model_relay_config(&*agent.binding) {
                output.print_info(&format!(
                    "Warning: could not remove model relay wiring: {} ({})",
                    e.message, e.code
                ));
            }
            continue;
        }

        // One agent's failure never stops the others: leaving a second agent
        // wired to a daemon this command is about to stop is the worse outcome.
        match hooks::remove_hooks(&*agent.binding) {
            Ok(()) => {
                let settings_path = agent.settings_path();
                output.print_step(&format!("Hooks removed from {}", settings_path.display()));

                // Also tear down the model-relay wiring. The model relay is on
                // by default, so without this uninstall would leave the agent
                // pointed at a dead 127.0.0.1:7600. Idempotent + loopback-safe:
                // only OUR endpoint / install-id lines are removed, whatever the
                // agent recorded before us is restored, and customer-set values
                // survive.
                //
                // No convention gate here any more: the writer dispatches on the
                // binding, and an agent that declares no request plane at all is
                // its own `Ok(())` arm inside it. A `matches!` on `EnvVars` here
                // would silently exempt every future convention from uninstall.
                #[cfg(feature = "model-relay")]
                if let Err(e) = hooks::remove_model_relay_config(&*agent.binding) {
                    output.print_info(&format!(
                        "Warning: could not remove model relay wiring: {} ({})",
                        e.message, e.code
                    ));
                }
            }
            Err(e) => {
                // Non-fatal: log but continue
                output.print_info(&format!(
                    "Warning: could not remove hooks for {}: {} ({})",
                    agent.display_name(),
                    e.message,
                    e.code
                ));
            }
        }
    }
}

/// Install-scoped artefacts of the intercepting relay (D-06r): the CA directory (and a
/// rotation's staging copy and kept previous root, `ca.next`/`ca.prev`), the CA's entry in the
/// USER trust store, the env files, the live marker and the shell-profile line. They belong to
/// the INSTALL, not to one agent: kept while any detected agent outside `selected` still
/// declares `ProxyEnv`. `stop` never reaches this.
#[cfg(feature = "model-relay")]
pub(crate) struct InstallScope<'a> {
    pub ol_dir: &'a std::path::Path,
    pub home: Option<&'a std::path::Path>,
    pub documents: Option<&'a std::path::Path>,
    pub machine_global: bool, // owns_machine_supervision()
    pub store: &'a dyn crate::model_relay::trust_store::TrustStore,
}

/// Every `ProxyEnv` agent detected but not selected for removal — pure, so the survivor rule is
/// testable without detection (round-4 lesson).
#[cfg(feature = "model-relay")]
fn proxy_env_survivors(
    selected: &[hooks::DetectedAgent],
    detected: &[hooks::DetectedAgent],
) -> Vec<&'static str> {
    use crate::hooks::binding::EndpointConvention;
    detected
        .iter()
        .filter(|a| !selected.iter().any(|s| s.agent_type() == a.agent_type()))
        .filter(|a| {
            a.binding
                .model_relay_wiring()
                .is_some_and(|w| matches!(w.endpoint, EndpointConvention::ProxyEnv { .. }))
        })
        .map(|a| a.agent_type())
        .collect()
}

/// Does `dir` exist and hold at least one entry? A directory that is absent or empty has nothing
/// on disk worth keeping, so the C3 garbage-`ca.pem` carve-out below only fires when there is
/// something to lose.
#[cfg(feature = "model-relay")]
fn dir_holds_files(dir: &std::path::Path) -> bool {
    std::fs::read_dir(dir)
        .map(|mut entries| entries.next().is_some())
        .unwrap_or(false)
}

/// Both D-06r triggers go through this one rule: whole-product `uninstall` (`selected` is every
/// detected agent) and `uninstall --agent <slug>` on the last `ProxyEnv` agent both leave no
/// survivor, so everything goes. Anything else — `stop`, a failed preflight, a restart,
/// relay-off, any runtime unwire — never reaches this function (D-06r: never on a runtime
/// unwire).
#[cfg(feature = "model-relay")]
fn remove_install_scoped_relay_artefacts(
    selected: &[hooks::DetectedAgent],
    detected: &[hooks::DetectedAgent],
    scope: &InstallScope<'_>,
    output: &OutputConfig,
) {
    use crate::hooks::{proxy_env_file, shell_profile};
    use crate::model_relay::{ca, ca_lifecycle};

    let survivors = proxy_env_survivors(selected, detected);
    if !survivors.is_empty() {
        output.print_info(&format!(
            "The model relay's certificate authority is kept: {} still route through it",
            survivors.join(", ")
        ));
        return;
    }

    for dir in [
        ca::ca_dir(scope.ol_dir),
        ca_lifecycle::staging_dir(scope.ol_dir),
        ca_lifecycle::prev_dir(scope.ol_dir), // ca.prev: a rotation's stuck old root
    ] {
        let info = ca::inspect(&dir);
        // Store first, read back to zero; the directory is the only record of WHICH entry is
        // ours, so it is deleted only once the store no longer holds it. Isolated installs
        // never installed (trap 4) and never remove.
        let mut keep_dir = false;
        if let (Some(info), true) = (&info, scope.machine_global) {
            let _ = scope.store.remove(&info.sha256_hex);
            match scope.store.is_trusted(&info.sha256_hex) {
                Ok(false) => {
                    output.print_step("Model relay certificate removed from your trust store")
                }
                Ok(true) | Err(_) => {
                    keep_dir = true;
                    output.print_note(&format!(
                        "Warning: the model relay certificate (SHA-256 {}) is still in your trust \
                         store — re-run `openlatch uninstall` from a desktop session; it is kept \
                         on disk until then ({})",
                        info.sha256_hex,
                        crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED
                    ));
                }
            }
        } else if info.is_none() && scope.machine_global && dir_holds_files(&dir) {
            // C3 (adversarial review): `ca.pem` exists but could not be read, so its trust-store
            // fingerprint is unknowable — deleting the directory here would silently orphan a
            // still-trusted root nobody can name any more. Never for an isolated install (trap
            // 4: it never installed, so there is nothing to orphan) and never for an
            // absent/empty directory (nothing on disk to lose).
            keep_dir = true;
            output.print_note(&format!(
                "Warning: {} could not be read, so its trust-store entry cannot be identified — \
                 it is kept on disk; remove the certificate from your user trust store by hand, \
                 then delete {} yourself ({})",
                ca::ca_pem_path(&dir).display(),
                dir.display(),
                crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED
            ));
        }
        if keep_dir {
            continue;
        }
        match ca::remove(&dir) {
            Ok(true) if !dir.exists() => {
                output.print_step("Model relay certificate authority removed")
            }
            Ok(true) => output.print_note("Warning: the model relay CA directory is still on disk"),
            Ok(false) => {}
            Err(e) => output.print_note(&format!(
                "Warning: could not remove the model relay CA: {} ({})",
                e.message, e.code
            )),
        }
    }

    for p in [
        proxy_env_file::env_sh_path(scope.ol_dir),
        proxy_env_file::env_ps1_path(scope.ol_dir),
        proxy_env_file::live_marker_path(scope.ol_dir),
    ] {
        let _ = std::fs::remove_file(p); // Ok when absent
    }

    if scope.machine_global {
        if let Some(home) = scope.home {
            if let Ok(files) = shell_profile::remove_line(home, scope.documents) {
                if !files.is_empty() {
                    output.print_step("Shell profile line removed");
                }
            }
        }
    }
}

pub fn run_uninstall(args: &UninstallArgs, output: &OutputConfig) -> Result<(), OlError> {
    // Step 0: if `--purge` cannot finish, refuse before anything is touched.
    //
    // This check used to sit at the end, next to the `remove_dir_all` it
    // guards, which reads like the safe place for it and is the opposite. A
    // state directory the guard rejects failed the command *after* the hooks
    // were removed, the supervisor was torn down and the daemon was stopped —
    // so a name mismatch did not fail safely, it half-uninstalled and then told
    // the operator to finish the job by hand. Validated up front, the same
    // mismatch costs nothing.
    let purge_target = if args.purge {
        resolve_purge_target()?
    } else {
        None
    };
    // Also resolved up front, while the state directory is still on disk.
    let purge_machine_global = args.purge && is_machine_default_install();

    // Step 1: Confirm (T-02-08: require explicit confirmation)
    if !args.yes {
        let is_tty = std::io::stdout().is_terminal();
        if is_tty && output.format == OutputFormat::Human {
            let purge_note = if args.purge {
                " and DELETE all OpenLatch data"
            } else {
                ""
            };
            eprint!("This will remove OpenLatch hooks{purge_note} and stop the daemon. Continue? [y/N] ");
            let _ = std::io::stderr().flush();

            let mut line = String::new();
            let _ = std::io::stdin().read_line(&mut line);
            if !line.trim().eq_ignore_ascii_case("y") {
                output.print_info("Aborted.");
                return Ok(());
            }
        }
    }

    // Step 2: Remove hooks from every detected agent's settings.
    //
    // The mirror of `init`'s install loop: `init` wires every agent on the
    // host, so `uninstall` unwires every one of them. `--agent` narrows it —
    // and only this step, not the machine-wide teardown below. A name that is
    // not on this machine fails BEFORE anything is touched, because acting on
    // a typo here costs the operator a stopped daemon.
    //
    // Detected once, here, while detection still sees everything: the
    // install-scoped relay cleanup below (D-06r) needs to know which
    // `ProxyEnv` agents SURVIVE this run, and that answer only exists if both
    // lists come from one detection.
    let detected = hooks::detect_agents();
    let selected = match hooks::select_agents(detected.clone(), &args.agent) {
        Ok(v) => v,
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    };

    if selected.is_empty() {
        // No agent found — hooks might not be installed, that's fine.
        output.print_info("Agent not detected — skipping hook removal");
    }

    remove_from_agents(&selected, output);

    // Step 2.5: Tear down OS supervision BEFORE stopping the daemon.
    // If we stopped the daemon first, the supervisor would immediately restart
    // it. Best-effort — never block uninstall.
    //
    // Only when the unit is ours to remove. It is one machine-global artifact,
    // and `supervision enable` already refuses to install one from an isolated
    // shell for that reason — an uninstall run inside an `olbox` sandbox
    // deregistering the machine's daemon is the same mistake with the sign
    // flipped.
    if !crate::supervision::owns_machine_supervision() {
        output.print_info("Isolated install — the machine's supervisor unit is left in place");
    } else if let Some(supervisor) = crate::supervision::select_supervisor() {
        match supervisor.uninstall() {
            Ok(()) => output.print_step("Supervision removed"),
            Err(e) => output.print_info(&format!(
                "Warning: could not remove supervision: {} ({})",
                e.message, e.code
            )),
        }
    }
    // Best-effort: persist mode=disabled so post-uninstall state reflects reality.
    let config_path = config::openlatch_dir().join("config.toml");
    if config_path.exists() {
        let _ = config::persist_supervision_state(
            &config_path,
            &crate::supervision::SupervisionMode::Disabled,
            &crate::supervision::SupervisorKind::None,
            Some("uninstalled"),
        );
    }

    // Step 3: Stop the daemon
    lifecycle::run_stop(output)?;

    // Step 3.5: install-scoped relay artefacts (D-06r) — the CA, its trust-store entry, the
    // env files, the live marker and the shell-profile line. Runs after the daemon is gone (no
    // wiring tick can re-prove, no relay holds the CA) and before the purge (which deletes
    // `$OPENLATCH_DIR` wholesale, and the store entry must go while its fingerprint can still be
    // read from `ca.pem`).
    #[cfg(feature = "model-relay")]
    remove_install_scoped_relay_artefacts(
        &selected,
        &detected,
        &InstallScope {
            ol_dir: &config::openlatch_dir(),
            home: dirs::home_dir().as_deref(),
            documents: dirs::document_dir().as_deref(),
            machine_global: crate::supervision::owns_machine_supervision(),
            store: &*crate::model_relay::trust_store::store(),
        },
        output,
    );

    // Step 4: Purge the data directory. The path was resolved and validated at
    // step 0, so nothing here can refuse after the fact.
    if args.purge {
        if let Some(canonical) = purge_target {
            std::fs::remove_dir_all(&canonical).map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!(
                        "Cannot delete openlatch directory '{}': {e}",
                        canonical.display()
                    ),
                )
                .with_suggestion("Check that you have write permission.")
            })?;

            output.print_step(&format!("Data directory removed: {}", canonical.display()));
        } else {
            output.print_info("Data directory does not exist — nothing to purge");
        }

        // The API key never lived in that directory. On a machine with a
        // working keychain it is an OS-level secret under the `openlatch`
        // service, so deleting the state directory left a usable credential
        // behind on a machine with no OpenLatch left on it.
        //
        // Local only, deliberately: `auth logout` also revokes the key
        // server-side, which invalidates it for every machine that shares it.
        // `--purge` uninstalls *this* one. Best-effort — a headless box with no
        // secret service must not fail the uninstall over it.
        if purge_machine_global {
            match crate::auth::CredentialStore::delete(&crate::auth::KeyringCredentialStore::new())
            {
                Ok(()) => output.print_step("Credentials cleared from the OS keychain"),
                Err(e) => output.print_info(&format!(
                    "Warning: could not clear the OS keychain credential: {} ({})",
                    e.message, e.code
                )),
            }
        } else {
            output.print_info(
                "Isolated install — the machine's OS-keychain credential is left in place",
            );
        }
    }

    // Telemetry: emit uninstalled. The count is 1 if removal was attempted, 0
    // otherwise — a count of RUNS, not of agents: `remove_all` above already
    // tore down every selected agent. This is best-effort — we do not retain
    // the prior detection result here, which is why the per-agent count is not
    // reported instead.
    crate::telemetry::capture_global(crate::telemetry::Event::uninstalled(1));

    if output.format == OutputFormat::Json {
        let json = serde_json::json!({
            "status": "ok",
            "purged": args.purge,
        });
        output.print_json(&json);
    } else if !output.quiet {
        eprintln!();
        eprintln!("OpenLatch uninstalled successfully.");
        if args.purge {
            eprintln!("All data removed.");
        } else {
            eprintln!(
                "Data directory preserved at {}. Use --purge to remove it.",
                config::openlatch_dir().display()
            );
        }
    }

    Ok(())
}

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

    /// `uninstall` on a host whose only agent is Cline hands back every provider
    /// slot the daemon wired, restoring Cline's own file byte for byte — the
    /// developer's comment, key order and endpoint.
    ///
    /// The slot is wired here the way the daemon's pass wires one: record first,
    /// then the relay value written over the developer's URL.
    #[test]
    #[cfg(feature = "model-relay")]
    fn uninstall_restores_every_cline_provider_slot() {
        use crate::hooks::cline_providers::{write_slot_in, LaneTag, SlotId};
        use crate::hooks::model_relay_endpoints::{EndpointRecord, SlotState, SlotValue};
        use std::sync::Arc;

        // `OPENLATCH_DIR` is process-wide and its lock comes FIRST in the
        // crate's documented order — the endpoint record this test round-trips
        // lives under it.
        let _state_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let root = tempfile::tempdir().expect("temp dir");
        // One data directory for both bundles, as on a real host.
        let data = root.path().join("store").join("data");
        let _seam = crate::hooks::cline::cline_isolated([
            ("HOME", Some(root.path().join("home").into_os_string())),
            (
                "OPENLATCH_DIR",
                Some(root.path().join("openlatch").into_os_string()),
            ),
            (
                crate::hooks::cline::STORE_DIR_ENV,
                Some(root.path().join("store").into_os_string()),
            ),
            (
                crate::hooks::cline::DATA_DIR_ENV,
                Some(data.clone().into_os_string()),
            ),
            (
                crate::hooks::cline::ASSETS_DIR_ENV,
                Some(root.path().join("assets").into_os_string()),
            ),
        ]);
        std::fs::create_dir_all(&data).expect("data dir");
        std::fs::create_dir_all(root.path().join("openlatch")).expect("openlatch dir");
        let state = data.join("globalState.json");
        let before = concat!(
            "{\n",
            "  // the customer's own comment\n",
            "  \"actModeApiProvider\": \"openai-compatible\",\n",
            "  \"openAiBaseUrl\": \"https://qwen.internal.bea/v1\",\n",
            "  \"telemetrySetting\": \"disabled\"\n",
            "}\n"
        );
        std::fs::write(&state, before).expect("seed");

        let key = "cline:gs:shared:openAiBaseUrl";
        crate::hooks::model_relay_endpoints::put_endpoint(
            key,
            EndpointRecord {
                port: 7605,
                origin: "https://qwen.internal.bea/".into(),
                prior: SlotValue::Text("https://qwen.internal.bea/v1".into()),
                last_written: Some("http://127.0.0.1:7605/v1".into()),
                file: state.clone(),
                state: SlotState::Wired,
                released_by: None,
                changed_at: 1,
                proven_at: None,
                family: None,
                pending_event: None,
                proven_by: None,
                misconfigured_event: None,
            },
        )
        .expect("record");
        let slot = SlotId::GlobalState {
            lane: LaneTag::Shared,
            key: "openAiBaseUrl".into(),
        };
        write_slot_in(
            &state,
            &slot,
            &SlotValue::Text("http://127.0.0.1:7605/v1".into()),
            &|_| true,
        )
        .expect("wire");
        assert!(std::fs::read_to_string(&state)
            .expect("read back")
            .contains("http://127.0.0.1:7605/v1"));

        let binding =
            crate::hooks::bindings::cline::ClineBinding::detect().expect("store root exists");
        let selected = vec![hooks::DetectedAgent {
            kind: hooks::AgentKind::Cline,
            binding: Arc::new(binding),
        }];
        remove_from_agents(
            &selected,
            &OutputConfig {
                format: OutputFormat::Human,
                verbose: false,
                debug: false,
                quiet: true,
                color: false,
            },
        );

        assert_eq!(
            std::fs::read_to_string(&state).expect("read back"),
            before,
            "uninstall must restore Cline's file byte-identically"
        );
        drop(home_lock);
    }

    /// The state directory `olbox` creates must be one `--purge` accepts.
    ///
    /// This is the client's half of a coupling whose other half lives in
    /// `tools/sandbox` — a separate crate, which names a sandbox's state
    /// directory `openlatch` for exactly this reason. A sandbox is a complete
    /// install, so `openlatch uninstall --purge` has to work inside one.
    ///
    /// It is asserted here, not there, because this is the side that can
    /// enforce it: `olbox` cannot fail its own build over a list this binary
    /// owns. And the failure is not theoretical — the directory used to be
    /// called `ol`, `--purge` refused it with `OL-1300` *after* removing the
    /// hooks and tearing down the supervisor, and the operator was left with a
    /// half-uninstalled sandbox and instructions to finish by hand.
    ///
    /// If this fails, the fix is one of two: put `openlatch` back on the list,
    /// or change `Sandbox::openlatch_dir` in `tools/sandbox/src/sandbox.rs` to
    /// a name that is on it.
    /// A sandbox is not the machine, however complete it looks.
    ///
    /// `--purge` clears the OS-keychain credential, which is one per machine
    /// rather than one per state directory. The guard is a path comparison, and
    /// the half that is easy to get wrong is the *false negative*: an
    /// `OPENLATCH_DIR` pointed deliberately at the default install through a
    /// symlink is that install, and refusing to clear its credential would
    /// leave the very key `--purge` promises to take.
    #[test]
    #[cfg(unix)]
    fn a_redirected_state_dir_is_the_default_one_only_when_it_resolves_there() {
        let home = tempfile::tempdir().unwrap();
        let default = home.path().join(".openlatch");
        std::fs::create_dir_all(&default).unwrap();

        let elsewhere = home.path().join("sandbox").join("openlatch");
        std::fs::create_dir_all(&elsewhere).unwrap();
        assert!(
            !same_directory(&elsewhere, &default),
            "a sandbox state directory must not pass for the machine's install"
        );

        let via_symlink = home.path().join("link");
        std::os::unix::fs::symlink(&default, &via_symlink).unwrap();
        assert!(
            same_directory(&via_symlink, &default),
            "a redirection that resolves to the default IS the default"
        );
    }

    #[test]
    fn the_state_directory_olbox_creates_is_purgeable() {
        assert!(
            is_purgeable_state_dir_name("openlatch"),
            "`olbox` names a sandbox's state directory `openlatch`; `--purge` must accept it"
        );
    }

    // -----------------------------------------------------------------------
    // I-2 plan 04 §4 — install-scoped relay artefacts (D-06r).
    // -----------------------------------------------------------------------

    fn quiet_output() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        }
    }

    /// S5: the bespoke `CountingStore` this used to declare is gone — every field and method it
    /// had (`trust`, a call log, a keyed removal-refusal set) now lives on
    /// [`crate::model_relay::trust_store::test_support::FakeStore`] itself, so these tests use
    /// that directly. `CountingStore.calls()` returned a bare count; `FakeStore.calls()` returns
    /// the ordered log, so a count comparison here reads `.calls().len()`.
    #[cfg(feature = "model-relay")]
    use crate::model_relay::trust_store::test_support::FakeStore;

    #[test]
    #[cfg(feature = "model-relay")]
    fn whole_uninstall_removes_the_ca_and_its_store_entry_read_back_to_zero() {
        use crate::model_relay::trust_store::TrustStore;

        let ol = tempfile::tempdir().expect("tempdir");
        let ca = crate::model_relay::ca::LocalCa::generate_into(&crate::model_relay::ca::ca_dir(
            ol.path(),
        ))
        .expect("ca");
        let next = crate::model_relay::ca::LocalCa::generate_into(
            &crate::model_relay::ca_lifecycle::staging_dir(ol.path()),
        )
        .expect("next");
        let prev = crate::model_relay::ca::LocalCa::generate_into(
            &crate::model_relay::ca_lifecycle::prev_dir(ol.path()),
        )
        .expect("prev");

        let env_sh = crate::hooks::proxy_env_file::env_sh_path(ol.path());
        std::fs::create_dir_all(env_sh.parent().expect("parent")).expect("mkdir");
        std::fs::write(&env_sh, "content\n").expect("write env.sh");
        std::fs::write(
            crate::hooks::proxy_env_file::env_ps1_path(ol.path()),
            "content\n",
        )
        .expect("write env.ps1");
        std::fs::write(
            crate::hooks::proxy_env_file::live_marker_path(ol.path()),
            "1234",
        )
        .expect("write marker");

        let home = tempfile::tempdir().expect("home");
        let zshrc = home.path().join(".zshrc");
        std::fs::write(
            &zshrc,
            format!(
                "customer line\nsome line  {}\n",
                crate::hooks::shell_profile::MARKER
            ),
        )
        .expect("write zshrc");

        let store = FakeStore::default();
        store.trust(&ca.sha256_hex());
        store.trust(&next.sha256_hex());
        store.trust(&prev.sha256_hex());

        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol.path(),
                home: Some(home.path()),
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );

        assert!(!crate::model_relay::ca::ca_dir(ol.path()).exists());
        assert!(!crate::model_relay::ca_lifecycle::staging_dir(ol.path()).exists());
        assert!(!crate::model_relay::ca_lifecycle::prev_dir(ol.path()).exists());
        assert!(!env_sh.exists());
        assert!(!crate::hooks::proxy_env_file::env_ps1_path(ol.path()).exists());
        assert!(!crate::hooks::proxy_env_file::live_marker_path(ol.path()).exists());
        assert!(!store.is_trusted(&ca.sha256_hex()).expect("is_trusted"));
        assert!(!store.is_trusted(&next.sha256_hex()).expect("is_trusted"));
        assert!(!store.is_trusted(&prev.sha256_hex()).expect("is_trusted"));
        assert!(!std::fs::read_to_string(&zshrc)
            .expect("read zshrc")
            .contains(crate::hooks::shell_profile::MARKER));
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn per_agent_uninstall_keeps_the_ca_while_another_proxy_env_agent_remains() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;
        use std::sync::Arc;

        const DELIVERY: &[ProxyDelivery] = &[ProxyDelivery::EnvFile {
            commands: &["fakecli"],
        }];
        fn agent(agent_type: &'static str) -> hooks::DetectedAgent {
            hooks::DetectedAgent {
                kind: hooks::AgentKind::ClaudeCode,
                binding: Arc::new(FakeBinding {
                    agent_type,
                    model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
                    ..Default::default()
                }),
            }
        }
        let a = agent("fake-a");
        let b = agent("fake-b");
        let detected = vec![a.clone(), b.clone()];

        assert_eq!(
            proxy_env_survivors(std::slice::from_ref(&a), &detected),
            vec!["fake-b"]
        );

        let ol = tempfile::tempdir().expect("tempdir");
        crate::model_relay::ca::LocalCa::generate_into(&crate::model_relay::ca::ca_dir(ol.path()))
            .expect("ca");
        let store = FakeStore::default();

        // Only A selected: B survives, so the CA stays and the store is never touched.
        remove_install_scoped_relay_artefacts(
            std::slice::from_ref(&a),
            &detected,
            &InstallScope {
                ol_dir: ol.path(),
                home: None,
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );
        assert!(crate::model_relay::ca::ca_dir(ol.path()).exists());
        assert_eq!(
            store.calls().len(),
            0,
            "a survivor means the store is never touched"
        );

        // Both selected: no survivor, everything goes.
        remove_install_scoped_relay_artefacts(
            &[a, b],
            &detected,
            &InstallScope {
                ol_dir: ol.path(),
                home: None,
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );
        assert!(!crate::model_relay::ca::ca_dir(ol.path()).exists());
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn an_isolated_uninstall_never_touches_the_store_or_the_profile() {
        let ol = tempfile::tempdir().expect("tempdir");
        crate::model_relay::ca::LocalCa::generate_into(&crate::model_relay::ca::ca_dir(ol.path()))
            .expect("ca");
        let home = tempfile::tempdir().expect("home");
        let zshrc = home.path().join(".zshrc");
        let original = format!(
            "customer line\nsome line  {}\n",
            crate::hooks::shell_profile::MARKER
        );
        std::fs::write(&zshrc, &original).expect("write zshrc");
        let store = FakeStore::default();

        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol.path(),
                home: Some(home.path()),
                documents: None,
                machine_global: false,
                store: &store,
            },
            &quiet_output(),
        );

        assert_eq!(
            store.calls().len(),
            0,
            "an isolated instance never installed, and never removes"
        );
        assert_eq!(
            std::fs::read_to_string(&zshrc).expect("read zshrc"),
            original,
            "the profile is untouched"
        );
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn a_store_removal_that_does_not_read_back_keeps_the_ca_on_disk() {
        let ol = tempfile::tempdir().expect("tempdir");
        let ca = crate::model_relay::ca::LocalCa::generate_into(&crate::model_relay::ca::ca_dir(
            ol.path(),
        ))
        .expect("ca");
        let store = FakeStore::default();
        store.trust(&ca.sha256_hex());
        store.refuse_removal_of(&ca.sha256_hex());

        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol.path(),
                home: None,
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );
        assert!(
            crate::model_relay::ca::ca_dir(ol.path()).exists(),
            "a refused read-back must keep the CA on disk"
        );

        store.allow_removal_of(&ca.sha256_hex());
        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol.path(),
                home: None,
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );
        assert!(
            !crate::model_relay::ca::ca_dir(ol.path()).exists(),
            "a retry with a working store then removes both"
        );
    }

    /// C3 (adversarial review): a `ca.pem` that cannot be parsed carries no readable SHA-256, so
    /// there is no fingerprint left to remove from the store — deleting the directory would
    /// orphan a still-trusted root nobody can name any more. The directory must be kept and a
    /// warning printed, in a machine-global scope only.
    #[test]
    #[cfg(feature = "model-relay")]
    fn a_garbage_ca_pem_in_a_machine_global_scope_is_kept_for_manual_removal() {
        let ol = tempfile::tempdir().expect("tempdir");
        let ca_dir = crate::model_relay::ca::ca_dir(ol.path());
        std::fs::create_dir_all(&ca_dir).expect("mkdir");
        std::fs::write(ca_dir.join("ca.pem"), b"not a certificate").expect("write garbage");
        assert!(
            crate::model_relay::ca::inspect(&ca_dir).is_none(),
            "the fixture must actually be unreadable"
        );
        let store = FakeStore::default();

        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol.path(),
                home: None,
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );

        assert!(
            ca_dir.exists(),
            "an unreadable CA directory must be kept, not deleted"
        );
        assert_eq!(
            store.calls().len(),
            0,
            "with no readable fingerprint there is nothing to remove from the store"
        );

        // Control: the same garbage file in an ISOLATED scope is not our business to keep or
        // warn about (trap 4: an isolated instance never installed, so it never orphans
        // anything) — it goes, exactly as an unreadable directory would otherwise.
        let ol2 = tempfile::tempdir().expect("tempdir");
        let ca_dir2 = crate::model_relay::ca::ca_dir(ol2.path());
        std::fs::create_dir_all(&ca_dir2).expect("mkdir");
        std::fs::write(ca_dir2.join("ca.pem"), b"not a certificate").expect("write garbage");
        let store2 = FakeStore::default();
        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol2.path(),
                home: None,
                documents: None,
                machine_global: false,
                store: &store2,
            },
            &quiet_output(),
        );
        assert!(
            !ca_dir2.exists(),
            "an isolated install still removes its own garbage directory"
        );
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn uninstall_leaves_every_customer_value_intact() {
        let ol = tempfile::tempdir().expect("tempdir");
        let home = tempfile::tempdir().expect("home");
        let zshrc = home.path().join(".zshrc");
        let customer = format!(
            "export PATH=/custom:$PATH\nsome line  {}\nexport FOO=bar\n",
            crate::hooks::shell_profile::MARKER
        );
        std::fs::write(&zshrc, &customer).expect("write zshrc");
        let bashrc = home.path().join(".bashrc");
        std::fs::write(&bashrc, "export ONLY_CUSTOMER=1\n").expect("write bashrc");
        let store = FakeStore::default();

        remove_install_scoped_relay_artefacts(
            &[],
            &[],
            &InstallScope {
                ol_dir: ol.path(),
                home: Some(home.path()),
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );

        assert_eq!(
            std::fs::read_to_string(&zshrc).expect("read zshrc"),
            "export PATH=/custom:$PATH\nexport FOO=bar\n"
        );
        assert_eq!(
            std::fs::read_to_string(&bashrc).expect("read bashrc"),
            "export ONLY_CUSTOMER=1\n"
        );
    }

    // -----------------------------------------------------------------------
    // I-4 plan 05 §9 — nothing left aimed at 127.0.0.1.
    // -----------------------------------------------------------------------

    /// The file shape the proxy-key writer round-trips byte for byte (02's shape 2).
    #[cfg(feature = "model-relay")]
    const EDITOR_SEED: &str = "{\n  \"a\": 1,\n}\n";

    /// Seams for a real Cline under a temp root, with `OPENLATCH_DIR` relocated; the guard is held
    /// until it drops. Lock order: `OPENLATCH_DIR_ENV_LOCK`, then `CONFIG_DIR_ENV_LOCK`, then the
    /// Cline seam (inside `cline_isolated`).
    #[cfg(feature = "model-relay")]
    struct ClineHost {
        _seam: crate::hooks::cline::ClineSeam,
        _home_lock: std::sync::MutexGuard<'static, ()>,
        _state_lock: std::sync::MutexGuard<'static, ()>,
        root: tempfile::TempDir,
        data: std::path::PathBuf,
    }

    #[cfg(feature = "model-relay")]
    fn cline_host() -> ClineHost {
        let _state_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let root = tempfile::tempdir().expect("temp dir");
        let data = root.path().join("store").join("data");
        let _seam = crate::hooks::cline::cline_isolated([
            ("HOME", Some(root.path().join("home").into_os_string())),
            (
                "OPENLATCH_DIR",
                Some(root.path().join("openlatch").into_os_string()),
            ),
            (
                crate::hooks::cline::STORE_DIR_ENV,
                Some(root.path().join("store").into_os_string()),
            ),
            (
                crate::hooks::cline::DATA_DIR_ENV,
                Some(data.clone().into_os_string()),
            ),
            (
                crate::hooks::cline::ASSETS_DIR_ENV,
                Some(root.path().join("assets").into_os_string()),
            ),
        ]);
        std::fs::create_dir_all(&data).expect("data dir");
        std::fs::create_dir_all(root.path().join("openlatch")).expect("openlatch dir");
        ClineHost {
            _seam,
            _home_lock,
            _state_lock,
            root,
            data,
        }
    }

    /// Wire one slot the way the daemon's pass does: record first, then our URL.
    #[cfg(feature = "model-relay")]
    fn wire_slot(
        file: &std::path::Path,
        slot: crate::hooks::cline_providers::SlotId,
        port: u16,
        origin: &str,
    ) {
        use crate::hooks::model_relay_endpoints::{EndpointRecord, SlotState, SlotValue};
        let ours = format!("http://127.0.0.1:{port}");
        crate::hooks::model_relay_endpoints::put_endpoint(
            &slot.record_key(),
            EndpointRecord {
                port,
                origin: origin.into(),
                prior: SlotValue::Absent,
                last_written: Some(ours.clone()),
                file: file.to_path_buf(),
                state: SlotState::Wired,
                released_by: None,
                changed_at: 1,
                proven_at: None,
                family: None,
                pending_event: None,
                proven_by: None,
                misconfigured_event: None,
            },
        )
        .expect("record");
        crate::hooks::cline_providers::write_slot_in(file, &slot, &SlotValue::Text(ours), &|_| {
            true
        })
        .expect("wire");
    }

    /// Point `agent`'s editor key and its CLI wrapper at the relay on 7600, as the daemon's
    /// delivery does.
    #[cfg(feature = "model-relay")]
    fn deliver_proxy(agent: &str, editor: &std::path::Path, key: &str, commands: &[&str]) {
        const RELAY: &str = "http://127.0.0.1:7600";
        crate::hooks::proxy_settings::write_proxy_key(editor, key, RELAY, agent)
            .expect("editor key");
        let ol = config::openlatch_dir();
        crate::hooks::proxy_env_file::write_block(
            agent,
            commands,
            RELAY,
            &crate::model_relay::ca::ca_pem_path(&crate::model_relay::ca::ca_dir(&ol)),
            "127.0.0.1:7600",
        )
        .expect("wrapper");
    }

    /// Every Cline delivery and slot back as it was: a stock slot, a local slot, a
    /// `providers.json` slot, the editor's `http.proxy` and the `cline` wrapper.
    #[cfg(feature = "model-relay")]
    fn wire_every_cline_surface(host: &ClineHost) -> Vec<(std::path::PathBuf, Vec<u8>)> {
        use crate::hooks::cline_providers::{LaneTag, SlotId};

        let state = host.data.join("globalState.json");
        std::fs::write(&state, "{\n  \"actModeApiProvider\": \"anthropic\"\n}\n").expect("seed");
        let pj = crate::hooks::cline::providers_json_path().expect("providers.json path");
        std::fs::create_dir_all(pj.parent().expect("parent")).expect("mkdir");
        std::fs::write(&pj, "{\"providers\":{\"deepseek\":{\"settings\":{}}}}\n").expect("seed");
        let editor = host.root.path().join("editor").join("settings.json");
        std::fs::create_dir_all(editor.parent().expect("parent")).expect("mkdir");
        std::fs::write(&editor, EDITOR_SEED).expect("seed");
        let snapshots: Vec<(std::path::PathBuf, Vec<u8>)> = [&state, &pj, &editor]
            .into_iter()
            .map(|p| (p.clone(), std::fs::read(p).expect("snapshot")))
            .collect();

        let gs = |key: &str| SlotId::GlobalState {
            lane: LaneTag::Shared,
            key: key.into(),
        };
        wire_slot(
            &state,
            gs("anthropicBaseUrl"),
            7601,
            "https://api.anthropic.com/",
        );
        wire_slot(&state, gs("ollamaBaseUrl"), 7602, "http://127.0.0.1:11434/");
        wire_slot(
            &pj,
            SlotId::ProvidersJson {
                id: "deepseek".into(),
            },
            7603,
            "https://api.deepseek.com/",
        );
        deliver_proxy("cline", &editor, "http.proxy", &["cline"]);
        let ol = config::openlatch_dir();
        crate::hooks::proxy_env_file::set_live(true).expect("marker");

        for (path, _) in &snapshots {
            assert!(
                std::fs::read_to_string(path)
                    .expect("read")
                    .contains("127.0.0.1:76"),
                "{} must name the relay before",
                path.display()
            );
        }
        assert!(crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
        assert!(crate::hooks::proxy_env_file::live_marker_path(&ol).exists());
        snapshots
    }

    #[cfg(feature = "model-relay")]
    fn real_cline() -> hooks::DetectedAgent {
        let binding =
            crate::hooks::bindings::cline::ClineBinding::detect().expect("store root exists");
        assert!(
            hooks::declares_proxy_env(&binding),
            "premise: Cline declares ProxyEnv"
        );
        hooks::DetectedAgent {
            kind: hooks::AgentKind::Cline,
            binding: std::sync::Arc::new(binding),
        }
    }

    #[cfg(feature = "model-relay")]
    fn assert_nothing_aimed_at_the_relay(snapshots: &[(std::path::PathBuf, Vec<u8>)]) {
        for (path, before) in snapshots {
            assert_eq!(
                &std::fs::read(path).expect("read back"),
                before,
                "{} must be byte-identical to its snapshot",
                path.display()
            );
        }
        let ol = config::openlatch_dir();
        assert!(!crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
        assert!(!crate::hooks::proxy_env_file::live_marker_path(&ol).exists());
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn uninstall_leaves_no_cline_surface_aimed_at_the_relay() {
        let host = cline_host();
        let snapshots = wire_every_cline_surface(&host);
        remove_from_agents(&[real_cline()], &quiet_output());
        assert_nothing_aimed_at_the_relay(&snapshots);
    }

    /// The reality-check GAP: Cline is the first real `ProxyEnv` agent through BOTH halves of an
    /// uninstall — its per-agent release (step 2) and 04's install-scoped cleanup (step 3.5),
    /// in `run_uninstall`'s order. With no other `ProxyEnv` agent detected, the CA goes too.
    #[test]
    #[cfg(feature = "model-relay")]
    fn a_whole_uninstall_with_cline_on_proxy_env_releases_then_removes_the_ca() {
        use crate::model_relay::trust_store::TrustStore;

        let host = cline_host();
        let snapshots = wire_every_cline_surface(&host);
        let ol = config::openlatch_dir();
        let ca =
            crate::model_relay::ca::LocalCa::generate_into(&crate::model_relay::ca::ca_dir(&ol))
                .expect("ca");
        let store = FakeStore::default();
        store.trust(&ca.sha256_hex());

        let cline = real_cline();
        let claude_shaped = hooks::DetectedAgent {
            kind: hooks::AgentKind::ClaudeCode,
            binding: std::sync::Arc::new(crate::hooks::binding::test_support::FakeBinding {
                agent_type: "claude-shaped",
                installable: false,
                model_relay_wiring: Some(crate::hooks::binding::ModelRelayWiring {
                    wire_format: crate::model_relay::wire_format::WireFormat::AnthropicMessages,
                    endpoint: crate::hooks::binding::EndpointConvention::EnvVars {
                        base_url: "FAKE_BASE_URL",
                        headers: "FAKE_HEADERS",
                    },
                    install_id_header: "x-openlatch-install-id",
                }),
                ..Default::default()
            }),
        };
        let detected = vec![cline.clone(), claude_shaped];
        assert!(
            proxy_env_survivors(std::slice::from_ref(&cline), &detected).is_empty(),
            "a per-agent Cline uninstall leaves no ProxyEnv survivor either"
        );

        // run_uninstall's order: the per-agent release, then the install-scoped cleanup.
        remove_from_agents(std::slice::from_ref(&cline), &quiet_output());
        assert_nothing_aimed_at_the_relay(&snapshots);
        remove_install_scoped_relay_artefacts(
            &detected,
            &detected,
            &InstallScope {
                ol_dir: &ol,
                home: None,
                documents: None,
                machine_global: true,
                store: &store,
            },
            &quiet_output(),
        );
        assert!(!crate::model_relay::ca::ca_dir(&ol).exists());
        assert!(!store.is_trusted(&ca.sha256_hex()).expect("is_trusted"));
        assert_nothing_aimed_at_the_relay(&snapshots);
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn a_failed_hook_removal_still_releases_the_proxy_delivery() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;

        fn editor_file() -> Option<std::path::PathBuf> {
            Some(
                config::openlatch_dir()
                    .join("fake-editor")
                    .join("settings.json"),
            )
        }
        const DELIVERY: &[ProxyDelivery] = &[
            ProxyDelivery::SettingsKey {
                file: editor_file,
                key: "fake.proxy",
            },
            ProxyDelivery::EnvFile {
                commands: &["fakecli"],
            },
        ];

        let _lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().expect("tempdir");
        let _env = crate::hooks::cline::EnvOverride::apply([(
            "OPENLATCH_DIR",
            Some(tmp.path().join("openlatch").into_os_string()),
        )]);
        let ol = config::openlatch_dir();
        let config_dir = tmp.path().join("fake-agent");
        // A directory where the hook settings file must be: the hook removal cannot succeed.
        std::fs::create_dir_all(config_dir.join("settings.json")).expect("plant a directory");
        let binding = FakeBinding {
            agent_type: "fake-a",
            display_name: "Fake",
            config_dir,
            installable: true,
            model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
            ..Default::default()
        };
        assert!(
            hooks::remove_hooks(&binding).is_err(),
            "premise: the hook removal fails"
        );

        let editor = editor_file().expect("path");
        std::fs::create_dir_all(editor.parent().expect("parent")).expect("mkdir");
        std::fs::write(&editor, EDITOR_SEED).expect("seed");
        deliver_proxy("fake-a", &editor, "fake.proxy", &["fakecli"]);
        assert!(crate::hooks::proxy_env_file::env_sh_path(&ol).exists());

        remove_from_agents(
            &[hooks::DetectedAgent {
                kind: hooks::AgentKind::ClaudeCode,
                binding: std::sync::Arc::new(binding),
            }],
            &quiet_output(),
        );

        assert_eq!(std::fs::read_to_string(&editor).expect("read"), EDITOR_SEED);
        assert!(!crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
    }
}