openlatch-client 0.6.14

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
//! What OpenCode exposes on this host, whether OpenCode loaded our plugin, and
//! whether the plugin's hook reaches the daemon — the `agents.opencode` object
//! of `doctor --json` (AGT-5 C-5).
//!
//! **Reads only.** The CLI's version comes from `opencode --version`, which
//! prints and exits; the Desktop application is **never launched**, and its
//! version is read from the bundle's metadata. OpenCode's own storage, logs,
//! database and `auth.json` are never opened (C-7).
//!
//! **Loading is evidence, not inference.** OpenCode loads plugins only when its
//! server starts, and a load failure is silent, so a present file proves
//! nothing: `plugin_seen` is `seen` only once the plugin's own load report
//! (`daemon::opencode_plugin_seen`) arrived after the current file was written.
//!
//! `relay` and `bypass_suspected` are the request plane's (AGT-5-P2): doctor
//! fills them from the relay's status endpoint once the model relay row is
//! rendered ([`OpencodeRelay`]), and they are absent when no relay is compiled
//! in or OpenCode declares no lane on this host.

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

use chrono::{DateTime, TimeZone, Utc};

use crate::daemon::opencode_plugin_seen;
use crate::error::{
    ERR_OPENCODE_HOOK_UNREACHABLE, ERR_OPENCODE_PLUGIN_NOT_LOADED, ERR_OPENCODE_RELAY_UNPROVEN,
    ERR_OPENCODE_RELAY_UNSUPPORTED, ERR_OPENCODE_SURFACE_UNDETERMINED,
    ERR_OPENCODE_VERSION_UNSUPPORTED,
};
use crate::hooks::cline::SurfaceState;
use crate::hooks::cursor_attestation::RelayDelivery;
use crate::hooks::hook_files::{self, Existing};
use crate::hooks::opencode::{self, Installed, Located};

/// The agent this attestation is about, as every OpenLatch surface names it.
pub const AGENT: &str = "opencode";

/// How long `opencode --version` may take before the CLI counts as undetermined.
const VERSION_TIMEOUT: Duration = Duration::from_secs(5);

/// The OpenCode CLI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliReport {
    pub state: SurfaceState,
    /// From `opencode --version`.
    pub version: Option<String>,
    /// `version >= 1.17.0`; `None` when the version is unknown.
    pub supported: Option<bool>,
    /// The build reports a pre-release version (`0.0.0-dev-…`, `-beta-…`): its OpenAI
    /// WebSocket transport is forced on (C-6).
    pub prerelease: bool,
}

/// The OpenCode Desktop application.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DesktopReport {
    pub state: SurfaceState,
    /// From the bundle's metadata; never by launching the app.
    pub version: Option<String>,
}

/// What holds our plugin path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginFileState {
    Present,
    Absent,
    /// A file OpenLatch does not own (`ERR_OPENCODE_PLUGIN_FOREIGN`).
    Foreign,
}

impl PluginFileState {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Present => "present",
            Self::Absent => "absent",
            Self::Foreign => "foreign",
        }
    }
}

/// Does the plugin's hook reach the daemon? Evidence only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reachability {
    /// A live OpenCode event reached the daemon since the plugin was written.
    Proven,
    /// No OpenCode event yet.
    Pending,
    /// OpenCode events since then exist only in `fallback.jsonl`.
    Failed,
}

impl Reachability {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Proven => "proven",
            Self::Pending => "pending",
            Self::Failed => "failed",
        }
    }
}

/// The `agents.opencode` attestation, every C-5 field but `relay` and
/// `bypass_suspected`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpencodeAttestation {
    pub as_of: DateTime<Utc>,
    pub config_root: Option<(PathBuf, Located)>,
    pub cli: CliReport,
    pub desktop: DesktopReport,
    pub plugin_file: PluginFileState,
    /// `seen` once a load report arrived after the current file was written.
    pub plugin_seen: bool,
    pub last_seen: Option<DateTime<Utc>>,
    pub surfaces_seen: Vec<String>,
    /// Other plugin files OpenCode loads from the global folders, and any
    /// managed-config path present — read, never written.
    pub other_plugins: Vec<PathBuf>,
    pub managed: Vec<PathBuf>,
    pub reachability: Reachability,
    /// The request plane's half (C-5 `relay`), filled by doctor from the relay's status.
    pub relay: Option<OpencodeRelay>,
    /// C-5 `bypass_suspected`; `None` without the request plane wired, where it cannot be known.
    pub bypass_suspected: Option<bool>,
}

/// How OpenCode's OpenAI turns travel (C-6): the relay classifies HTTP requests only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebsocketMode {
    /// HTTP/SSE: stable build, transport left off or pinned off by the delivery.
    Off,
    /// The developer set `OPENCODE_EXPERIMENTAL_WEBSOCKETS=true`, which the delivery never
    /// overwrites.
    DeveloperOn,
    /// A pre-release build, where no setting turns it off.
    Forced,
}

impl WebsocketMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::DeveloperOn => "developer_on",
            Self::Forced => "forced",
        }
    }

    /// Plan D-5, from the developer's environment value and the CLI's pre-release flag. An empty
    /// value counts as unset (D-4); only `true` turns it on, as OpenCode reads it.
    pub fn from_facts(developer_value: Option<&str>, prerelease: bool) -> Self {
        if prerelease {
            Self::Forced
        } else if developer_value.is_some_and(|v| v.trim().eq_ignore_ascii_case("true")) {
            Self::DeveloperOn
        } else {
            Self::Off
        }
    }
}

/// `agents.opencode.relay` (C-5): each surface's delivery, the one traffic proof, the WebSocket
/// transport, and the configured provider hosts the relay does not capture.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpencodeRelay {
    pub cli: RelayDelivery,
    /// Always `Unsupported` in this build: Desktop's request plane is macOS-only and gated on
    /// probe P-4b (Plan D-13).
    pub desktop: RelayDelivery,
    /// An OpenCode model turn (its `User-Agent`, a C-6 session header) reached the relay.
    pub traffic_proven: bool,
    /// When the relay last recorded one, in epoch milliseconds.
    pub last_traffic_ms: Option<i64>,
    /// The relay's window is younger than 24 hours: the daemon started inside it.
    pub since_daemon_start: bool,
    pub websocket: WebsocketMode,
    /// Hosts named in a `provider.*.options.baseURL` that the relay tunnels and never decrypts
    /// (Plan D-11). Host names only.
    pub tunnelled_hosts: Vec<String>,
    /// Providers on loopback (Ollama, LM Studio): never captured (C-6).
    pub loopback_hosts: Vec<String>,
    /// Why the CLI is not wired, as the model relay row states it.
    pub unwired: Option<(&'static str, String)>,
    /// Windows with no PowerShell profile: no shell sources `env.ps1`, so the CLI goes direct from
    /// `cmd` and PowerShell alike (C-8). Makes `cli` unsupported, with its own remedy.
    pub no_shell_profile: bool,
}

/// What to do on Windows when no PowerShell profile exists to source `env.ps1` (C-8).
pub const NO_SHELL_PROFILE_REMEDY: &str = "No PowerShell profile sources `env.ps1`, so `opencode` \
     goes direct from `cmd` and PowerShell alike. Create one (`New-Item -ItemType File -Force \
     $PROFILE`); OpenLatch adds the line that sources `env.ps1`. Then run `opencode` from \
     PowerShell and rerun `openlatch doctor`.";

/// What to do while no OpenCode model call has reached the relay.
pub const RELAY_UNPROVEN_REMEDY: &str = "Run one OpenCode turn from a shell that sources \
     `env.sh` (PowerShell: `env.ps1`), then rerun `openlatch doctor`.";

impl OpencodeRelay {
    /// Every field that is not green, as `(field, state, code, remedy)`. Off is never a pass.
    pub fn findings(&self) -> Vec<(&'static str, &'static str, &'static str, String)> {
        let mut out = Vec::new();
        match self.cli {
            RelayDelivery::Wired => {}
            RelayDelivery::Unsupported => out.push((
                "cli",
                self.cli.as_str(),
                ERR_OPENCODE_RELAY_UNSUPPORTED,
                if self.no_shell_profile {
                    NO_SHELL_PROFILE_REMEDY
                } else {
                    "Nothing to do: this build does not route the OpenCode CLI through the relay \
                     here; its plugin still enforces."
                }
                .to_string(),
            )),
            RelayDelivery::Unwired => {
                let (code, remedy) = self.unwired.clone().unwrap_or((
                    crate::error::ERR_MODEL_RELAY_PREFLIGHT_FAILED,
                    "Run `openlatch doctor --fix`; the relay wires OpenCode once its preflight \
                     passes."
                        .to_string(),
                ));
                out.push(("cli", self.cli.as_str(), code, remedy));
            }
        }
        if self.desktop == RelayDelivery::Unsupported {
            out.push((
                "desktop",
                self.desktop.as_str(),
                ERR_OPENCODE_RELAY_UNSUPPORTED,
                "Nothing to do: the request plane is not available on OpenCode Desktop in this \
                 build; its model calls go direct, and the plugin still enforces."
                    .to_string(),
            ));
        }
        if self.cli == RelayDelivery::Wired && !self.traffic_proven {
            out.push((
                "traffic",
                "unproven",
                ERR_OPENCODE_RELAY_UNPROVEN,
                RELAY_UNPROVEN_REMEDY.to_string(),
            ));
        }
        if self.websocket != WebsocketMode::Off {
            out.push((
                "websocket",
                self.websocket.as_str(),
                ERR_OPENCODE_RELAY_UNSUPPORTED,
                match self.websocket {
                    WebsocketMode::Forced => {
                        "This pre-release OpenCode sends OpenAI turns over a WebSocket the relay \
                         cannot capture. Use a stable OpenCode build."
                    }
                    _ => {
                        "OpenAI turns travel over a WebSocket the relay cannot capture. Unset \
                         OPENCODE_EXPERIMENTAL_WEBSOCKETS."
                    }
                }
                .to_string(),
            ));
        }
        out
    }

    fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "cli": self.cli.as_str(),
            "desktop": self.desktop.as_str(),
            "traffic": if self.traffic_proven { "proven" } else { "unproven" },
            "websocket": self.websocket.as_str(),
            "since_daemon_start": self.since_daemon_start,
            "tunnelled_hosts": self.tunnelled_hosts,
            "loopback_hosts": self.loopback_hosts,
            "findings": self.findings().into_iter().map(|(field, state, code, remedy)| {
                serde_json::json!({"field": field, "state": state, "code": code, "remedy": remedy})
            }).collect::<Vec<_>>(),
        })
    }
}

/// Whether `opencode --version` names a pre-release build: a `-` suffix on the version token.
pub fn is_prerelease(version_text: &str) -> bool {
    version_text
        .split_whitespace()
        .find(|t| {
            t.trim_start_matches('v')
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_digit())
        })
        .is_some_and(|t| t.split('+').next().unwrap_or_default().contains('-'))
}

/// The hosts of every `provider.*.options.baseURL` in OpenCode's global config and in the
/// repository at `cwd` (`opencode.json`, `opencode.jsonc`), split into tunnelled non-loopback
/// hosts outside `intercepted`, and loopback hosts. Only the base URLs are read out; nothing
/// else in the file is kept. An unparseable file contributes nothing.
pub fn configured_provider_hosts(
    root: Option<&Path>,
    cwd: Option<&Path>,
    intercepted: &[&str],
) -> (Vec<String>, Vec<String>) {
    let (mut tunnelled, mut loopback) = (Vec::new(), Vec::new());
    for dir in [root, cwd].into_iter().flatten() {
        for name in ["opencode.json", "opencode.jsonc"] {
            let Ok(raw) = std::fs::read_to_string(dir.join(name)) else {
                continue;
            };
            let Ok(doc) = crate::hooks::jsonc::parse_settings_value(&raw) else {
                continue;
            };
            let Some(providers) = doc.get("provider").and_then(serde_json::Value::as_object) else {
                continue;
            };
            for provider in providers.values() {
                let Some(host) = provider
                    .pointer("/options/baseURL")
                    .and_then(serde_json::Value::as_str)
                    .and_then(url_host)
                else {
                    continue;
                };
                let list = if is_loopback_host(&host) {
                    &mut loopback
                } else if intercepted.iter().any(|h| h.eq_ignore_ascii_case(&host)) {
                    continue;
                } else {
                    &mut tunnelled
                };
                if !list.contains(&host) {
                    list.push(host);
                }
            }
        }
    }
    tunnelled.sort();
    loopback.sort();
    (tunnelled, loopback)
}

/// The host of a URL, lowercased, with no userinfo, port, path or query.
fn url_host(url: &str) -> Option<String> {
    let rest = url.split_once("://")?.1;
    let authority = &rest[..rest.find(['/', '\\', '?', '#']).unwrap_or(rest.len())];
    let host_port = authority.rsplit('@').next()?;
    let host = if let Some(v6) = host_port.strip_prefix('[') {
        v6.split(']').next()?
    } else {
        host_port.split(':').next()?
    };
    (!host.is_empty() && !host.contains(['{', '}', ' '])).then(|| host.to_ascii_lowercase())
}

fn is_loopback_host(host: &str) -> bool {
    host == "localhost"
        || host.ends_with(".localhost")
        || host == "::1"
        || host
            .parse::<std::net::Ipv4Addr>()
            .is_ok_and(|ip| ip.is_loopback())
}

/// What [`probe`] reads from the host, separated so tests can pin it.
pub struct Inputs {
    pub openlatch_dir: PathBuf,
    pub root: Option<(PathBuf, Located)>,
    pub installed: Installed,
    /// The output of `opencode --version`, or why it could not be read; `None`
    /// when no CLI is installed.
    pub cli_version: Option<Result<String, String>>,
    pub desktop_version: Option<String>,
    pub managed_roots: Vec<PathBuf>,
    pub now: DateTime<Utc>,
}

/// Probe this host.
pub fn probe(openlatch_dir: &Path) -> OpencodeAttestation {
    let installed = opencode::installed();
    let cli_version = installed.cli.as_deref().map(run_version);
    let desktop_version = installed.desktop.as_deref().and_then(desktop_version);
    from_inputs(Inputs {
        openlatch_dir: openlatch_dir.to_path_buf(),
        root: opencode::root_located(),
        installed,
        cli_version,
        desktop_version,
        managed_roots: managed_roots(),
        now: Utc::now(),
    })
}

/// The attestation for pinned inputs.
pub fn from_inputs(inputs: Inputs) -> OpencodeAttestation {
    let cli = match (&inputs.installed.cli, &inputs.cli_version) {
        (None, _) => CliReport {
            state: if inputs.root.is_some() {
                SurfaceState::Absent
            } else {
                SurfaceState::Undetermined
            },
            version: None,
            supported: None,
            prerelease: false,
        },
        (Some(_), Some(Ok(text))) => match opencode::parse_version(text) {
            Some(version) => CliReport {
                state: SurfaceState::Present,
                version: Some(format!("{}.{}.{}", version.0, version.1, version.2)),
                supported: Some(opencode::version_supported(version)),
                prerelease: is_prerelease(text),
            },
            None => CliReport {
                state: SurfaceState::Undetermined,
                version: None,
                supported: None,
                prerelease: false,
            },
        },
        (Some(_), _) => CliReport {
            state: SurfaceState::Undetermined,
            version: None,
            supported: None,
            prerelease: false,
        },
    };
    let desktop = DesktopReport {
        state: match (&inputs.installed.desktop, &inputs.root) {
            (Some(_), _) => SurfaceState::Present,
            (None, Some(_)) => SurfaceState::Absent,
            (None, None) => SurfaceState::Undetermined,
        },
        version: inputs.desktop_version.clone(),
    };

    let plugin_path = inputs
        .root
        .as_ref()
        .map(|(root, _)| opencode::plugin_path(root));
    let plugin_file = match plugin_path.as_deref().map(hook_files::whatever_is_there) {
        Some(Existing::Ours) => PluginFileState::Present,
        Some(Existing::Theirs) => PluginFileState::Foreign,
        _ => PluginFileState::Absent,
    };
    let written_ms = plugin_path
        .as_deref()
        .filter(|_| plugin_file == PluginFileState::Present)
        .and_then(opencode_plugin_seen::mtime_ms);
    let seen = opencode_plugin_seen::read_seen(&inputs.openlatch_dir);
    let plugin_seen =
        written_ms.is_some_and(|written| opencode_plugin_seen::seen_since(&seen, written));
    let last_seen =
        opencode_plugin_seen::last_seen(&seen).and_then(|ms| Utc.timestamp_millis_opt(ms).single());
    let installed_at = written_ms.and_then(|ms| Utc.timestamp_millis_opt(ms).single());

    // What OpenCode last reported loading, which sees npm plugins and a
    // repository's `.opencode/plugins`; the global folders only until then.
    let other_plugins = match opencode_plugin_seen::reported_plugins(&inputs.openlatch_dir) {
        Some(reported) => reported_other_plugins(&reported, plugin_path.as_deref()),
        None => inputs
            .root
            .as_ref()
            .map(|(root, _)| other_plugins(root, plugin_path.as_deref()))
            .unwrap_or_default(),
    };

    OpencodeAttestation {
        as_of: inputs.now,
        config_root: inputs.root.clone(),
        cli,
        desktop,
        plugin_file,
        plugin_seen,
        last_seen,
        surfaces_seen: seen.keys().cloned().collect(),
        other_plugins,
        managed: inputs
            .managed_roots
            .into_iter()
            .filter(|p| p.exists())
            .collect(),
        reachability: reachability(&inputs.openlatch_dir, installed_at),
        relay: None,
        bypass_suspected: None,
    }
}

/// `opencode --version`, bounded: a CLI that does not answer in time is
/// undetermined, never waited on.
fn run_version(binary: &Path) -> Result<String, String> {
    run_version_within(binary, VERSION_TIMEOUT)
}

/// The deadline covers the read as well as the exit. The first line of stdout is
/// read on its own thread: a wrapper that starts a background child and exits
/// leaves that child holding the pipe, and a read to EOF on the caller's thread
/// would hang `doctor` and every caller of `run_all_checks` with it. A reader
/// still blocked at the deadline is abandoned — it ends when the pipe closes.
fn run_version_within(binary: &Path, timeout: Duration) -> Result<String, String> {
    use std::io::BufRead;
    let mut child = std::process::Command::new(binary)
        .arg("--version")
        .env("OPENCODE_DISABLE_AUTOUPDATE", "1")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map_err(|e| e.to_string())?;
    let deadline = std::time::Instant::now() + timeout;
    let (tx, rx) = std::sync::mpsc::channel();
    if let Some(stdout) = child.stdout.take() {
        std::thread::spawn(move || {
            let mut line = String::new();
            let _ = std::io::BufReader::new(stdout).read_line(&mut line);
            let _ = tx.send(line);
        });
    }
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if std::time::Instant::now() < deadline => {
                std::thread::sleep(Duration::from_millis(25));
            }
            Ok(None) => {
                let _ = child.kill();
                let _ = child.wait();
                return Err("`opencode --version` did not answer in time".to_string());
            }
            Err(e) => return Err(e.to_string()),
        }
    };
    if !status.success() {
        return Err(format!("`opencode --version` exited with {status}"));
    }
    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
    rx.recv_timeout(remaining)
        .map_err(|_| "`opencode --version` did not answer in time".to_string())
}

/// The Desktop bundle's version, from its metadata. macOS reads the bundle's
/// XML `Info.plist`; elsewhere no file is relied on, and the version stays
/// unknown.
fn desktop_version(location: &Path) -> Option<String> {
    let plist = std::fs::read_to_string(location.join("Contents").join("Info.plist")).ok()?;
    let after_key = plist
        .split("<key>CFBundleShortVersionString</key>")
        .nth(1)?;
    let value = after_key
        .split("<string>")
        .nth(1)?
        .split("</string>")
        .next()?;
    let value = value.trim();
    (!value.is_empty()).then(|| value.to_string())
}

/// OpenCode's managed-config roots (C-7): read as inventory, never written.
fn managed_roots() -> Vec<PathBuf> {
    opencode::managed_dir().into_iter().collect()
}

/// The plugins of a load report other than ours. OpenCode names a file plugin by
/// its `file://` URL and a package by its spec; both are kept, ours dropped.
fn reported_other_plugins(reported: &[String], ours: Option<&Path>) -> Vec<PathBuf> {
    let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    let ours = ours.map(canonical);
    reported
        .iter()
        .map(|entry| file_url_path(entry).unwrap_or_else(|| PathBuf::from(entry)))
        .filter(|path| ours.as_deref() != Some(canonical(path).as_path()))
        .collect()
}

/// The path of a `file://` URL, percent-decoded; `None` for anything else.
fn file_url_path(entry: &str) -> Option<PathBuf> {
    let rest = entry.strip_prefix("file://")?;
    // `file:///C:/x` on Windows: the drive follows the third slash.
    let rest = match rest.as_bytes() {
        [b'/', drive, b':', ..] if drive.is_ascii_alphabetic() && cfg!(windows) => &rest[1..],
        _ => rest,
    };
    let bytes = rest.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
            if let Some(byte) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
                out.push(byte);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    Some(PathBuf::from(String::from_utf8_lossy(&out).into_owned()))
}

/// The other plugin files in the global `plugin/` and `plugins/` folders.
fn other_plugins(root: &Path, ours: Option<&Path>) -> Vec<PathBuf> {
    let mut out: Vec<PathBuf> = ["plugin", opencode::PLUGINS_DIR_NAME]
        .iter()
        .filter_map(|dir| std::fs::read_dir(root.join(dir)).ok())
        .flatten()
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| matches!(path.extension().and_then(|e| e.to_str()), Some("js" | "ts")))
        .filter(|path| Some(path.as_path()) != ours)
        .collect();
    out.sort();
    out
}

/// Evidence-based reachability, dated against the plugin's write: an event from
/// before it proves nothing about it.
fn reachability(openlatch_dir: &Path, installed_at: Option<DateTime<Utc>>) -> Reachability {
    let since = |at: &DateTime<Utc>| installed_at.is_none_or(|installed| *at >= installed);
    if crate::daemon::agent_liveness::read(openlatch_dir)
        .get(AGENT)
        .is_some_and(since)
    {
        return Reachability::Proven;
    }
    if fallback_holds_event(&openlatch_dir.join("logs").join("fallback.jsonl"), &since) {
        return Reachability::Failed;
    }
    Reachability::Pending
}

fn fallback_holds_event(path: &Path, since: &dyn Fn(&DateTime<Utc>) -> bool) -> bool {
    use std::io::BufRead;
    let Ok(file) = std::fs::File::open(path) else {
        return false;
    };
    std::io::BufReader::new(file)
        .lines()
        .map_while(Result::ok)
        .filter(|line| line.contains(AGENT))
        .filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
        .filter(|event| event["source"].as_str() == Some(AGENT))
        // A load report proves the plugin ran, not that a decision was cut short.
        .filter(|event| event["data"]["opencode_hook"].as_str() != Some("plugin_loaded"))
        .any(|event| {
            event["time"]
                .as_str()
                .and_then(|t| DateTime::parse_from_rfc3339(t).ok())
                .is_some_and(|at| since(&at.with_timezone(&Utc)))
        })
}

/// One surface that is not present, with its code and what to do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbsentSurface {
    pub surface: &'static str,
    pub state: SurfaceState,
    pub code: Option<&'static str>,
    pub remedy: String,
}

impl OpencodeAttestation {
    /// Each surface not present (C-5 `surfaces_absent`).
    pub fn surfaces_absent(&self) -> Vec<AbsentSurface> {
        [("cli", self.cli.state), ("desktop", self.desktop.state)]
            .into_iter()
            .filter(|(_, state)| *state != SurfaceState::Present)
            .map(|(surface, state)| match state {
                SurfaceState::Undetermined => AbsentSurface {
                    surface,
                    state,
                    code: Some(ERR_OPENCODE_SURFACE_UNDETERMINED),
                    remedy: format!(
                        "Start OpenCode once on the {surface} surface, then rerun `openlatch doctor`."
                    ),
                },
                _ => AbsentSurface {
                    surface,
                    state,
                    code: None,
                    remedy: format!(
                        "Nothing to do unless you use the OpenCode {surface}; install it, then rerun `openlatch init --agent opencode`."
                    ),
                },
            })
            .collect()
    }

    /// The `doctor --json` object.
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "as_of": self.as_of.to_rfc3339(),
            "config_root": self.config_root.as_ref().map(|(path, located)| json!({
                "path": crate::core::path_compat::display_path(path),
                "located": located.as_str(),
            })),
            "cli": {
                "state": self.cli.state.as_str(),
                "version": self.cli.version,
                "supported": self.cli.supported,
            },
            "desktop": {
                "state": self.desktop.state.as_str(),
                "version": self.desktop.version,
            },
            "plugin_file": {
                "state": self.plugin_file.as_str(),
                "ours": self.plugin_file == PluginFileState::Present,
            },
            "plugin_seen": {
                "state": if self.plugin_seen { "seen" } else { "pending" },
                "last_seen": self.last_seen.map(|t| t.to_rfc3339()),
                "surfaces": self.surfaces_seen,
            },
            "other_plugins": self.other_plugins.iter().map(|path| json!({
                "name": path.file_name().map(|n| n.to_string_lossy().into_owned()),
                "path": crate::core::path_compat::display_path(path),
            })).collect::<Vec<_>>(),
            "managed": self.managed.iter().map(|p| crate::core::path_compat::display_path(p)).collect::<Vec<_>>(),
            "reachability": self.reachability.as_str(),
            "surfaces_absent": self.surfaces_absent().iter().map(|s| json!({
                "surface": s.surface,
                "state": s.state.as_str(),
                "code": s.code,
                "remedy": s.remedy,
            })).collect::<Vec<_>>(),
            "relay": self.relay.as_ref().map(OpencodeRelay::to_json),
            "bypass_suspected": self.bypass_suspected,
        })
    }

    /// One line for the human rendering.
    pub fn summary(&self) -> String {
        let cli = match (&self.cli.state, &self.cli.version) {
            (SurfaceState::Present, Some(v)) => format!("CLI {v}"),
            (state, _) => format!("CLI {}", state.as_str()),
        };
        let desktop = match (&self.desktop.state, &self.desktop.version) {
            (SurfaceState::Present, Some(v)) => format!("Desktop {v}"),
            (state, _) => format!("Desktop {}", state.as_str()),
        };
        format!(
            "OpenCode: {cli}, {desktop}; plugin {} ({})",
            self.plugin_file.as_str(),
            if self.plugin_seen { "seen" } else { "pending" }
        )
    }

    /// Every other fact `to_json` carries, one line each.
    pub fn human_lines(&self) -> Vec<String> {
        let mut lines = Vec::new();
        if let Some((path, located)) = &self.config_root {
            lines.push(format!(
                "Config root: {} ({})",
                crate::core::path_compat::display_path(path),
                located.as_str()
            ));
        }
        if let Some(at) = self.last_seen {
            lines.push(format!(
                "Plugin last loaded: {} ({})",
                at.to_rfc3339(),
                self.surfaces_seen.join(", ")
            ));
        }
        for path in &self.other_plugins {
            lines.push(format!(
                "Other plugin: {}",
                crate::core::path_compat::display_path(path)
            ));
        }
        for path in &self.managed {
            lines.push(format!(
                "Managed config (read only): {}",
                crate::core::path_compat::display_path(path)
            ));
        }
        lines.push(format!("Reachability: {}", self.reachability.as_str()));
        if let Some(relay) = &self.relay {
            lines.push(format!(
                "Relay: CLI {}, Desktop {}, traffic {}, WebSocket {}{}",
                relay.cli.as_str(),
                relay.desktop.as_str(),
                if relay.traffic_proven {
                    "proven"
                } else {
                    "unproven"
                },
                relay.websocket.as_str(),
                if relay.since_daemon_start {
                    " (since daemon start)"
                } else {
                    ""
                }
            ));
            for host in &relay.tunnelled_hosts {
                lines.push(format!(
                    "Custom provider host, tunnelled and not captured: {host}"
                ));
            }
            for host in &relay.loopback_hosts {
                lines.push(format!("Loopback provider, not captured: {host}"));
            }
        }
        lines
    }

    /// `ERR_OPENCODE_PLUGIN_NOT_LOADED` (C-8, P2's branch): our file is present and no load
    /// report arrived since it was written, although the relay recorded OpenCode traffic since
    /// then — or a bypass is suspected. Needs the request plane wired; `None` otherwise. The
    /// detail names which signal fired.
    pub fn not_loaded(&self, written_ms: Option<i64>) -> Option<(&'static str, String)> {
        let relay = self.relay.as_ref()?;
        let traffic_since_write = !self.plugin_seen
            && self.plugin_file == PluginFileState::Present
            && relay
                .last_traffic_ms
                .zip(written_ms)
                .is_some_and(|(traffic, written)| traffic >= written);
        let signal = if self.bypass_suspected == Some(true) {
            "the relay recorded OpenCode model traffic for a session the plugin never reported \
             (bypass suspected)"
        } else if traffic_since_write {
            "the relay recorded OpenCode model traffic since the plugin was written, and the \
             plugin has not reported loading"
        } else {
            return None;
        };
        Some((
            ERR_OPENCODE_PLUGIN_NOT_LOADED,
            format!("{signal}. Restart OpenCode and check that it is not started with `--pure`."),
        ))
    }

    /// The version-floor finding (`ERR_OPENCODE_VERSION_UNSUPPORTED`), when the
    /// CLI is below v1.17.0.
    pub fn version_unsupported(&self) -> Option<(&'static str, String)> {
        (self.cli.supported == Some(false)).then(|| {
            (
                ERR_OPENCODE_VERSION_UNSUPPORTED,
                format!(
                    "OpenCode {} is below the supported floor 1.17.0. Run `opencode upgrade`.",
                    self.cli.version.as_deref().unwrap_or("unknown")
                ),
            )
        })
    }

    /// The reachability finding (`ERR_OPENCODE_HOOK_UNREACHABLE`).
    pub fn unreachable(&self) -> Option<(&'static str, String)> {
        (self.reachability == Reachability::Failed).then(|| {
            let likely = if cfg!(windows) {
                "on Windows, check that `openlatch-hook.exe` exists under the OpenLatch `bin` folder and is not blocked"
            } else {
                "check that the daemon is running and that `openlatch-hook` exists under the OpenLatch `bin` folder"
            };
            (
                ERR_OPENCODE_HOOK_UNREACHABLE,
                format!(
                    "The OpenLatch plugin ran the hook but it could not reach the daemon; {likely}. Run `openlatch doctor --fix`, then restart OpenCode."
                ),
            )
        })
    }
}

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

    #[cfg(unix)]
    fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let path = dir.join(name);
        std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        path
    }

    /// A wrapper that exits while a descendant still holds stdout never hangs
    /// the probe: the version line is read, and a silent one is cut at the
    /// deadline.
    #[cfg(unix)]
    #[test]
    fn the_version_probe_is_bounded_when_a_descendant_holds_stdout() {
        let dir = tempfile::tempdir().unwrap();
        let answers = script(dir.path(), "answers", "(sleep 30) &\necho 1.18.35");
        let started = std::time::Instant::now();
        let out = run_version_within(&answers, Duration::from_secs(3)).expect("version");
        assert_eq!(out.trim(), "1.18.35");
        assert!(started.elapsed() < Duration::from_secs(3));

        let silent = script(dir.path(), "silent", "(sleep 30) &\nexit 0");
        let started = std::time::Instant::now();
        assert!(run_version_within(&silent, Duration::from_millis(500)).is_err());
        assert!(started.elapsed() < Duration::from_secs(3));
    }

    struct Host {
        _dir: tempfile::TempDir,
        ol: PathBuf,
        root: PathBuf,
    }

    fn host() -> Host {
        let dir = tempfile::tempdir().expect("tempdir");
        let ol = dir.path().join("openlatch");
        let root = dir.path().join("config").join("opencode");
        std::fs::create_dir_all(&ol).unwrap();
        std::fs::create_dir_all(&root).unwrap();
        Host {
            ol,
            root,
            _dir: dir,
        }
    }

    fn inputs(host: &Host, cli_version: Option<Result<String, String>>) -> Inputs {
        Inputs {
            openlatch_dir: host.ol.clone(),
            root: Some((host.root.clone(), Located::Xdg)),
            installed: Installed {
                cli: cli_version
                    .as_ref()
                    .map(|_| PathBuf::from("/usr/local/bin/opencode")),
                desktop: None,
            },
            cli_version,
            desktop_version: None,
            managed_roots: vec![],
            now: Utc::now(),
        }
    }

    /// AGT-5 C-5, AC-12: `other_plugins` names what OpenCode reported loading —
    /// an npm plugin and a repository plugin are in no global folder — and never
    /// our own file; the folder scan answers only before any report.
    #[test]
    fn other_plugins_follow_the_load_report_then_the_folders() {
        let host = host();
        let plugins = opencode::plugins_dir(&host.root);
        crate::hooks::opencode_plugin::install(&plugins, &host.ol).expect("install");
        std::fs::write(plugins.join("global.js"), "export default async () => ({})").unwrap();

        let before = from_inputs(inputs(&host, None));
        assert_eq!(before.other_plugins, vec![plugins.join("global.js")]);

        let ours = format!("file://{}", opencode::plugin_path(&host.root).display());
        let repo = std::env::temp_dir().join("repo with space/.opencode/plugins/repo.ts");
        let repo_url = format!("file://{}", repo.display()).replace(' ', "%20");
        crate::daemon::opencode_plugin_seen::record_report(
            &host.ol,
            "cli",
            1,
            Some(&["opencode-foo@1.0.0".to_string(), repo_url, ours]),
        )
        .unwrap();
        let after = from_inputs(inputs(&host, None));
        assert_eq!(
            after.other_plugins,
            vec![PathBuf::from("opencode-foo@1.0.0"), repo]
        );
    }

    #[test]
    fn pending_until_a_load_report_follows_the_write_then_seen() {
        let host = host();
        crate::hooks::opencode_plugin::install(&opencode::plugins_dir(&host.root), &host.ol)
            .expect("install");
        let a = from_inputs(inputs(&host, Some(Ok("1.18.35\n".into()))));
        assert_eq!(a.plugin_file, PluginFileState::Present);
        assert!(!a.plugin_seen);
        let json = a.to_json();
        assert_eq!(json["plugin_seen"]["state"], "pending");
        assert_eq!(json["plugin_file"]["ours"], true);
        assert_eq!(json["cli"]["version"], "1.18.35");
        assert_eq!(json["cli"]["supported"], true);
        assert_eq!(json["config_root"]["located"], "xdg");
        assert_eq!(json["reachability"], "pending");

        let later = Utc::now().timestamp_millis() + 1000;
        opencode_plugin_seen::record(&host.ol, "cli", later).unwrap();
        let a = from_inputs(inputs(&host, Some(Ok("1.18.35".into()))));
        assert!(a.plugin_seen);
        assert_eq!(a.to_json()["plugin_seen"]["state"], "seen");
        assert_eq!(
            a.to_json()["plugin_seen"]["surfaces"],
            serde_json::json!(["cli"])
        );
    }

    /// Every C-5 field is rendered; `relay` and `bypass_suspected` are `null` until doctor fills
    /// them from the relay (P2).
    #[test]
    fn every_c5_field_is_rendered() {
        let host = host();
        let json = from_inputs(inputs(&host, Some(Ok("1.18.35".into())))).to_json();
        for field in [
            "as_of",
            "config_root",
            "cli",
            "desktop",
            "plugin_file",
            "plugin_seen",
            "other_plugins",
            "reachability",
            "surfaces_absent",
            "relay",
            "bypass_suspected",
        ] {
            assert!(json.get(field).is_some(), "{field} missing");
        }
        assert!(json["relay"].is_null(), "filled by doctor from the relay");
        assert!(json["bypass_suspected"].is_null());
        assert_eq!(json["plugin_file"]["state"], "absent");
    }

    #[test]
    fn a_cli_below_the_floor_is_unsupported() {
        let host = host();
        let a = from_inputs(inputs(&host, Some(Ok("opencode 1.16.2".into()))));
        assert_eq!(a.cli.supported, Some(false));
        let (code, remedy) = a.version_unsupported().expect("finding");
        assert_eq!(code, ERR_OPENCODE_VERSION_UNSUPPORTED);
        assert!(remedy.contains("opencode upgrade"));
        assert!(from_inputs(inputs(&host, Some(Ok("1.17.0".into()))))
            .version_unsupported()
            .is_none());
    }

    #[test]
    fn an_unanswering_cli_and_an_unresolved_root_are_undetermined() {
        let host = host();
        let a = from_inputs(inputs(&host, Some(Err("timed out".into()))));
        assert_eq!(a.cli.state, SurfaceState::Undetermined);
        let absent = a.surfaces_absent();
        let cli = absent.iter().find(|s| s.surface == "cli").expect("cli");
        assert_eq!(cli.code, Some(ERR_OPENCODE_SURFACE_UNDETERMINED));
        let desktop = absent
            .iter()
            .find(|s| s.surface == "desktop")
            .expect("desktop");
        assert_eq!(desktop.state, SurfaceState::Absent);
        assert_eq!(desktop.code, None);

        let mut no_root = inputs(&host, None);
        no_root.root = None;
        let a = from_inputs(no_root);
        assert_eq!(a.cli.state, SurfaceState::Undetermined);
        assert_eq!(a.desktop.state, SurfaceState::Undetermined);
    }

    #[test]
    fn a_foreign_file_and_other_plugins_are_named() {
        let host = host();
        let plugins = opencode::plugins_dir(&host.root);
        std::fs::create_dir_all(&plugins).unwrap();
        std::fs::write(
            plugins.join("openlatch.js"),
            "export default async () => ({})\n",
        )
        .unwrap();
        std::fs::write(plugins.join("other.ts"), "x").unwrap();
        std::fs::write(plugins.join("notes.md"), "x").unwrap();
        std::fs::create_dir_all(host.root.join("plugin")).unwrap();
        std::fs::write(host.root.join("plugin").join("legacy.js"), "x").unwrap();
        let a = from_inputs(inputs(&host, None));
        assert_eq!(a.plugin_file, PluginFileState::Foreign);
        assert_eq!(a.to_json()["plugin_file"]["ours"], false);
        let names: Vec<_> = a
            .other_plugins
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["legacy.js", "other.ts"]);
    }

    #[test]
    fn reachability_is_proven_by_a_live_event_and_failed_by_fallback_only() {
        let host = host();
        crate::hooks::opencode_plugin::install(&opencode::plugins_dir(&host.root), &host.ol)
            .expect("install");
        let logs = host.ol.join("logs");
        std::fs::create_dir_all(&logs).unwrap();
        let future = (Utc::now() + chrono::Duration::minutes(5)).to_rfc3339();
        // A load report in fallback is not a cut-short decision.
        std::fs::write(
            logs.join("fallback.jsonl"),
            format!(
                "{}\n",
                serde_json::json!({"source": "opencode", "time": future, "data": {"opencode_hook": "plugin_loaded"}})
            ),
        )
        .unwrap();
        assert_eq!(
            from_inputs(inputs(&host, None)).reachability,
            Reachability::Pending
        );
        std::fs::write(
            logs.join("fallback.jsonl"),
            format!(
                "{}\n",
                serde_json::json!({"source": "opencode", "time": future, "data": {"opencode_hook": "tool.execute.before"}})
            ),
        )
        .unwrap();
        let a = from_inputs(inputs(&host, None));
        assert_eq!(a.reachability, Reachability::Failed);
        assert_eq!(
            a.unreachable().map(|(c, _)| c),
            Some(ERR_OPENCODE_HOOK_UNREACHABLE)
        );

        std::fs::write(
            host.ol.join(crate::daemon::agent_liveness::FILE_NAME),
            serde_json::json!({"opencode": future}).to_string(),
        )
        .unwrap();
        assert_eq!(
            from_inputs(inputs(&host, None)).reachability,
            Reachability::Proven
        );
    }

    #[test]
    fn the_desktop_version_is_read_from_the_bundle_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let app = dir.path().join("OpenCode.app");
        std::fs::create_dir_all(app.join("Contents")).unwrap();
        std::fs::write(
            app.join("Contents").join("Info.plist"),
            "<plist><dict><key>CFBundleName</key><string>OpenCode</string>\
             <key>CFBundleShortVersionString</key>\n<string>1.18.35</string></dict></plist>",
        )
        .unwrap();
        assert_eq!(desktop_version(&app).as_deref(), Some("1.18.35"));
        assert_eq!(desktop_version(dir.path()), None);
    }

    fn relay(cli: RelayDelivery, traffic: bool, websocket: WebsocketMode) -> OpencodeRelay {
        OpencodeRelay {
            cli,
            desktop: RelayDelivery::Unsupported,
            traffic_proven: traffic,
            last_traffic_ms: traffic.then_some(2_000),
            since_daemon_start: true,
            websocket,
            tunnelled_hosts: vec!["llm.corp.test".into()],
            loopback_hosts: vec!["localhost".into()],
            unwired: None,
            no_shell_profile: false,
        }
    }

    /// Plan D-5: a pre-release build reports `0.0.0-<channel>-<stamp>` and forces the WebSocket
    /// transport; the developer's `true` turns it on; anything else, or empty, is off.
    #[test]
    fn the_websocket_transport_is_read_from_the_channel_and_the_environment() {
        assert!(is_prerelease("0.0.0-dev-202610092229"));
        assert!(is_prerelease("opencode 0.0.0-beta-202608110357"));
        assert!(!is_prerelease("1.18.35"));
        assert!(!is_prerelease("v1.18.35+build.7"));
        assert!(!is_prerelease(""));
        assert_eq!(WebsocketMode::from_facts(None, false), WebsocketMode::Off);
        assert_eq!(
            WebsocketMode::from_facts(Some(""), false),
            WebsocketMode::Off
        );
        assert_eq!(
            WebsocketMode::from_facts(Some("false"), false),
            WebsocketMode::Off
        );
        assert_eq!(
            WebsocketMode::from_facts(Some("TRUE"), false),
            WebsocketMode::DeveloperOn
        );
        assert_eq!(
            WebsocketMode::from_facts(Some("false"), true),
            WebsocketMode::Forced
        );
    }

    /// AC-12b: the relay codes fire under their stated conditions, each with a remedy.
    #[test]
    fn the_relay_findings_carry_their_codes() {
        let codes = |r: &OpencodeRelay| -> Vec<(&str, &str)> {
            r.findings()
                .into_iter()
                .map(|(f, _, c, _)| (f, c))
                .collect()
        };
        let green = relay(RelayDelivery::Wired, true, WebsocketMode::Off);
        assert_eq!(
            codes(&green),
            vec![("desktop", ERR_OPENCODE_RELAY_UNSUPPORTED)],
            "Desktop has no delivery in this build (D-13)"
        );
        let unproven = relay(RelayDelivery::Wired, false, WebsocketMode::Off);
        assert!(codes(&unproven).contains(&("traffic", ERR_OPENCODE_RELAY_UNPROVEN)));
        for mode in [WebsocketMode::DeveloperOn, WebsocketMode::Forced] {
            assert!(codes(&relay(RelayDelivery::Wired, true, mode))
                .contains(&("websocket", ERR_OPENCODE_RELAY_UNSUPPORTED)));
        }
        let no_profile = OpencodeRelay {
            no_shell_profile: true,
            ..relay(RelayDelivery::Unsupported, false, WebsocketMode::Off)
        };
        let cli = no_profile
            .findings()
            .into_iter()
            .find(|(f, ..)| *f == "cli")
            .expect("a cli finding");
        assert_eq!(cli.2, ERR_OPENCODE_RELAY_UNSUPPORTED);
        assert_eq!(
            cli.3, NO_SHELL_PROFILE_REMEDY,
            "C-8: the Windows cmd reason"
        );
        let unwired = relay(RelayDelivery::Unwired, false, WebsocketMode::Off);
        assert!(
            !codes(&unwired).iter().any(|(f, _)| *f == "traffic"),
            "an unwired CLI is the finding, not its traffic"
        );
        assert!(green
            .findings()
            .iter()
            .chain(unproven.findings().iter())
            .all(|(_, _, _, remedy)| !remedy.is_empty()));
    }

    /// AC-11b / C-8: NOT_LOADED needs the request plane, and fires on traffic since the write
    /// with no load report, or on a suspected bypass; a plugin seen since is never not loaded.
    #[test]
    fn not_loaded_fires_on_traffic_since_the_write_or_a_suspected_bypass() {
        let host = host();
        let plugins = opencode::plugins_dir(&host.root);
        crate::hooks::opencode_plugin::install(&plugins, &host.ol).expect("install");
        let mut att = from_inputs(inputs(&host, None));
        assert!(!att.plugin_seen);
        assert!(att.not_loaded(Some(1_000)).is_none(), "no relay, no signal");

        att.relay = Some(relay(RelayDelivery::Wired, true, WebsocketMode::Off));
        let (code, detail) = att.not_loaded(Some(1_000)).expect("traffic since write");
        assert_eq!(code, ERR_OPENCODE_PLUGIN_NOT_LOADED);
        assert!(detail.contains("--pure"));
        assert!(
            att.not_loaded(Some(5_000)).is_none(),
            "traffic before the write proves nothing"
        );

        att.relay = Some(relay(RelayDelivery::Wired, false, WebsocketMode::Off));
        assert!(att.not_loaded(Some(1_000)).is_none());
        att.bypass_suspected = Some(true);
        let (_, detail) = att.not_loaded(Some(1_000)).expect("bypass");
        assert!(detail.contains("bypass suspected"));

        att.bypass_suspected = Some(false);
        att.plugin_seen = true;
        att.relay = Some(relay(RelayDelivery::Wired, true, WebsocketMode::Off));
        assert!(att.not_loaded(Some(1_000)).is_none());
    }

    /// AC-12b: `doctor --json` renders `relay` and `bypass_suspected` beside every P1 field.
    #[test]
    fn the_json_carries_relay_and_bypass_suspected() {
        let host = host();
        let mut att = from_inputs(inputs(&host, Some(Ok("1.18.35".into()))));
        let json = att.to_json();
        assert!(json["relay"].is_null());
        assert!(json["bypass_suspected"].is_null());

        att.relay = Some(relay(RelayDelivery::Wired, true, WebsocketMode::Off));
        att.bypass_suspected = Some(false);
        let json = att.to_json();
        assert_eq!(json["relay"]["cli"], "wired");
        assert_eq!(json["relay"]["desktop"], "unsupported");
        assert_eq!(json["relay"]["traffic"], "proven");
        assert_eq!(json["relay"]["websocket"], "off");
        assert_eq!(
            json["relay"]["tunnelled_hosts"],
            serde_json::json!(["llm.corp.test"])
        );
        assert_eq!(
            json["relay"]["loopback_hosts"],
            serde_json::json!(["localhost"])
        );
        assert_eq!(json["bypass_suspected"], false);
        assert!(att
            .human_lines()
            .iter()
            .any(|l| l.contains("tunnelled and not captured: llm.corp.test")));
    }

    /// AC-18d / Plan D-11: a custom base URL host, in user or repository config, is reported as
    /// tunnelled; a fixed intercept host is not listed; loopback providers are named apart. Only
    /// hosts leave — never a path, a port, userinfo or a key.
    #[test]
    fn configured_provider_hosts_split_tunnelled_from_loopback() {
        let dir = tempfile::tempdir().unwrap();
        let (root, repo) = (dir.path().join("root"), dir.path().join("repo"));
        std::fs::create_dir_all(&root).unwrap();
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(
            root.join("opencode.json"),
            r#"{"provider":{
                "corp":{"options":{"baseURL":"https://user:pw@LLM.Corp.test:8443/v1?k=SECRET","apiKey":"SENTINEL_KEY"}},
                "anthropic":{"options":{"baseURL":"https://api.anthropic.com/v1"}},
                "ollama":{"options":{"baseURL":"http://127.0.0.1:11434/v1"}}
            }}"#,
        )
        .unwrap();
        std::fs::write(
            repo.join("opencode.jsonc"),
            "// repo config\n{\"provider\":{\"gw\":{\"options\":{\"baseURL\":\"https://gw.example.com/openai\"}},\"lm\":{\"options\":{\"baseURL\":\"http://localhost:1234/v1\"}}}}",
        )
        .unwrap();
        std::fs::write(repo.join("opencode.json"), "{ not json").unwrap();
        let (tunnelled, loopback) = configured_provider_hosts(
            Some(&root),
            Some(&repo),
            crate::hooks::bindings::opencode::OPENCODE_INTERCEPT_HOSTS,
        );
        assert_eq!(tunnelled, vec!["gw.example.com", "llm.corp.test"]);
        assert_eq!(loopback, vec!["127.0.0.1", "localhost"]);
        let all = format!("{tunnelled:?}{loopback:?}");
        for leak in ["SENTINEL_KEY", "SECRET", "pw", "8443", "/v1"] {
            assert!(!all.contains(leak), "{leak}");
        }
    }
}