openlatch-client 0.6.19

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
//! OpenCode-only process identity for the Desktop service manager (AGT-6 C-8 Leg B; plan
//! AGT-6-P2 D-3, D-4, D-5, D-16, D-19).
//!
//! This module reads, enumerates, signals and spawns processes for OpenCode's shared service and
//! nothing else. The Cline hub's reader (`src/hooks/cline_app/process.rs`) is deliberately not
//! shared or modified (D-4): that code keeps its own behaviour byte for byte.
//!
//! # Process identity
//!
//! A [`ProcId`] is a pid plus the OS-native **start identity** and the executable path. Two reads
//! name the same process only when all three match. The start identity is kept as a string in the
//! OS's own representation and is only ever compared with another value read by this same module,
//! so it is never converted between clocks or truncated (D-5, D-21):
//!
//! | OS | Start identity | Executable |
//! | -- | -------------- | ---------- |
//! | Linux | `/proc/<pid>/stat` field 22 (clock ticks since boot), counted after the last `)` | `readlink /proc/<pid>/exe` |
//! | macOS | `proc_pidinfo(PROC_PIDTBSDINFO)` start, in microseconds since the epoch | `proc_pidpath` |
//! | Windows | `GetProcessTimes` creation time, a FILETIME as a decimal integer | `QueryFullProcessImageNameW` |
//!
//! An identity that cannot be read is `None`, and a `None` is never signalled: everything here
//! fails closed.
//!
//! # Stopping
//!
//! [`stop`] signals only a process whose pid, start identity and executable still match the
//! caller's earlier read, re-read immediately before each signal:
//!
//! - **Linux** pins the process with a pidfd (`pidfd_open`), re-verifies through `/proc`, then
//!   sends SIGTERM, and SIGKILL after the grace period, through that pidfd. A pid reused during
//!   the grace period is never signalled. A kernel without pidfds (`ENOSYS`) falls back to
//!   `kill(2)` after a fresh re-read.
//! - **Windows** opens one process handle (`PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE
//!   | SYNCHRONIZE`), re-verifies the creation time and image **on that handle**, then calls
//!   `TerminateProcess` and waits on the same handle (D-3). No `taskkill`: it re-resolves the pid.
//! - **macOS** has no user-scope handle that pins a process, so it re-reads the start identity and
//!   path immediately before each `kill(2)`. A residual race remains between that re-read and the
//!   signal: a process that exits and whose pid is reused inside that window would be signalled.
//!   This is accepted under the client's threat model — a misbehaving, not a malicious, agent —
//!   and stated here as the Spec requires (AGT-6 Risks).
//!
//! # Spawning
//!
//! [`spawn`] starts `<cli> serve --service` detached, stdio closed, cwd the user's home, with the
//! environment [`ServiceEnv`] describes (D-16): the daemon's own, minus every `OPENLATCH_*`
//! variable and every variable the daemon reads a credential from, plus exactly the four relay
//! keys. The environment is never cleared wholesale (Bun on Windows needs `SystemRoot`). On Unix
//! the child calls `setsid()` alone — never with `process_group(0)`, which makes the following
//! `setsid` fail with `EPERM` — and a reaper thread waits on it. On Windows it is created with no
//! console window in a new process group, breaking away from the daemon's job where the job
//! allows it.

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

/// How long [`stop`] waits after SIGTERM (or, on Windows, after `TerminateProcess`) before it
/// escalates or gives up (D-5).
pub const STOP_GRACE: Duration = Duration::from_secs(5);

/// How long [`stop`] waits for the process to disappear after SIGKILL (Unix; Windows terminates
/// once and waits `grace`).
#[cfg(unix)]
const KILL_WAIT: Duration = Duration::from_secs(2);

/// Executable base names that count as an OpenCode process (D-19), compared case-insensitively
/// with a trailing `.exe` stripped: Desktop's main process (`OpenCode`; on Linux electron-builder
/// names it after the app id, `ai.opencode.desktop`), the CLI and TUI (`opencode`) and the
/// bundled service binary (`opencode-cli`).
const OPENCODE_NAMES: &[&str] = &["opencode", "opencode-cli", "ai.opencode.desktop"];

/// The service binary's base name, without `.exe`.
pub const SERVICE_BINARY: &str = "opencode-cli";

/// A process as one read saw it: pid, OS-native start identity, executable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcId {
    pub pid: u32,
    /// The OS-native start identity (module doc), never normalised across OSes.
    pub start: String,
    pub exe: PathBuf,
}

impl ProcId {
    /// The same process: pid, start identity and executable all equal.
    #[must_use]
    pub fn same_process(&self, other: &ProcId) -> bool {
        self.pid == other.pid && self.start == other.start && same_path(&self.exe, &other.exe)
    }
}

/// Whether any OpenCode process other than the excluded pids is running (D-19).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Attached {
    Yes,
    No,
    /// The process table could not be read. Callers treat it as [`Attached::Yes`]: fail closed.
    Unknown,
}

impl Attached {
    /// `true` unless the table was read and showed no OpenCode process.
    #[must_use]
    pub fn blocks_replacement(self) -> bool {
        !matches!(self, Attached::No)
    }
}

/// How a [`stop`] ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StopOutcome {
    /// Signalled and gone.
    Stopped,
    /// Already gone before any signal was sent.
    Gone,
    /// Still running, but its start identity or executable no longer matches: not signalled.
    Changed,
    /// Its identity could not be read at the re-read: not signalled (fail closed).
    Unreadable,
    /// A signal could not be sent, or the process survived SIGKILL.
    Failed(String),
}

impl StopOutcome {
    /// The process the caller verified is no longer running.
    #[must_use]
    pub fn is_gone(&self) -> bool {
        matches!(self, StopOutcome::Stopped | StopOutcome::Gone)
    }
}

/// The process primitives the manager needs, behind a trait so its rules are tested against a
/// fake table. [`SystemTable`] is the real one.
pub trait ProcessTable: Send + Sync {
    /// A fresh identity read, `None` when the process is gone or its identity cannot be read.
    fn read(&self, pid: u32) -> Option<ProcId>;
    /// Whether `pid` names a running process at all, its identity readable or not — what tells
    /// "gone" from "unreadable" when [`Self::read`] answers `None` (D-19: fail closed).
    fn exists(&self, pid: u32) -> bool;
    /// Every running process whose executable base name is an OpenCode name, as `(pid, exe)`.
    /// `Err` when the table cannot be read.
    fn opencode_processes(&self) -> Result<Vec<(u32, PathBuf)>, String>;
    /// [`stop`] on the real table.
    fn stop(&self, expected: &ProcId, grace: Duration) -> StopOutcome;
    /// [`spawn`] on the real table.
    fn spawn(&self, cli: &Path, env: &ServiceEnv) -> std::io::Result<ProcId>;
}

/// The host's real process table.
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemTable;

impl ProcessTable for SystemTable {
    fn read(&self, pid: u32) -> Option<ProcId> {
        read(pid)
    }

    fn exists(&self, pid: u32) -> bool {
        pid != 0 && sys::exists(pid)
    }

    fn opencode_processes(&self) -> Result<Vec<(u32, PathBuf)>, String> {
        sys::processes().map(|all| {
            all.into_iter()
                .filter(|(_, exe)| is_opencode_exe(exe))
                .collect()
        })
    }

    fn stop(&self, expected: &ProcId, grace: Duration) -> StopOutcome {
        stop(expected, grace)
    }

    fn spawn(&self, cli: &Path, env: &ServiceEnv) -> std::io::Result<ProcId> {
        spawn(cli, env)
    }
}

/// A fresh identity read of `pid`. `None` for pid 0, a gone process or an unreadable identity.
#[must_use]
pub fn read(pid: u32) -> Option<ProcId> {
    if pid == 0 {
        return None;
    }
    sys::read(pid)
}

/// Whether an OpenCode process other than `except` is running (D-19). An unreadable table is
/// [`Attached::Unknown`].
pub fn attached(table: &dyn ProcessTable, except: &[u32]) -> Attached {
    match table.opencode_processes() {
        Err(e) => {
            tracing::debug!(error = %e, "OpenCode process table unreadable; counting as attached");
            Attached::Unknown
        }
        Ok(found) => {
            if found.iter().any(|(pid, _)| !except.contains(pid)) {
                Attached::Yes
            } else {
                Attached::No
            }
        }
    }
}

/// The base name of `exe`, lower-cased, with a trailing `.exe` stripped.
fn base_name(exe: &Path) -> Option<String> {
    let name = exe.file_name()?.to_string_lossy().to_ascii_lowercase();
    Some(
        name.strip_suffix(".exe")
            .map(str::to_string)
            .unwrap_or(name),
    )
}

/// `exe`'s base name is one of the OpenCode names (D-19).
#[must_use]
pub fn is_opencode_exe(exe: &Path) -> bool {
    base_name(exe).is_some_and(|n| OPENCODE_NAMES.contains(&n.as_str()))
}

/// `exe`'s base name is the service binary, `opencode-cli`.
#[must_use]
pub fn is_service_binary(exe: &Path) -> bool {
    base_name(exe).is_some_and(|n| n == SERVICE_BINARY)
}

/// Two executable paths name the same file. Compared as given first, then canonicalised, so a
/// path recorded through a symlink still matches the kernel's resolved one.
#[must_use]
pub fn same_path(a: &Path, b: &Path) -> bool {
    if crate::core::path_compat::dedup_key(a) == crate::core::path_compat::dedup_key(b) {
        return true;
    }
    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
        (Ok(a), Ok(b)) => {
            crate::core::path_compat::dedup_key(&a) == crate::core::path_compat::dedup_key(&b)
        }
        _ => false,
    }
}

/// `true` when the daemon runs with elevated rights: effective uid 0 on Unix, an elevated token on
/// Windows. Leg B never spawns the service from an elevated daemon (I-1, PB-2). An unreadable
/// token counts as elevated: fail closed.
#[must_use]
pub fn running_elevated() -> bool {
    sys::running_elevated()
}

// ---------------------------------------------------------------------------
// Environment (D-16)
// ---------------------------------------------------------------------------

/// The four relay keys the service gets, taken from `model-relay/env.json` (never from `env.sh`).
pub const RELAY_KEYS: [&str; 4] = [
    "HTTPS_PROXY",
    "HTTP_PROXY",
    "NO_PROXY",
    "NODE_EXTRA_CA_CERTS",
];

/// Variables the daemon reads a credential from, outside the `OPENLATCH_` prefix: the proxy
/// variables, whose userinfo the egress layer reads as proxy credentials
/// (`core::egress::config`). Removed in every letter case; the relay keys are then added back in
/// upper case with the relay's values. `ALL_PROXY` would also route Bun around the relay.
const CREDENTIAL_VARS: &[&str] = &[
    "HTTPS_PROXY",
    "HTTP_PROXY",
    "ALL_PROXY",
    "NO_PROXY",
    "NODE_EXTRA_CA_CERTS",
];

/// The prefix of every variable OpenLatch reads, credentials included (`OPENLATCH_API_KEY`,
/// `OPENLATCH_TOKEN`, `OPENLATCH_PROXY_AUTH`, `OPENLATCH_POSTHOG_KEY`).
const OPENLATCH_PREFIX: &str = "OPENLATCH_";

/// The environment the service is spawned with, as a subtraction from the daemon's own plus the
/// four relay keys (D-16).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServiceEnv {
    /// Inherited variable names removed from the child, in the case the daemon holds them.
    pub remove: Vec<OsString>,
    /// The four relay keys and their values, in [`RELAY_KEYS`] order.
    pub add: Vec<(&'static str, String)>,
}

impl ServiceEnv {
    /// Build from the inherited environment and the four relay values (`env.json`).
    pub fn new<I>(inherited: I, keys: &crate::hooks::proxy_env_file::EnvJson) -> Self
    where
        I: IntoIterator<Item = (OsString, OsString)>,
    {
        let remove = inherited
            .into_iter()
            .map(|(k, _)| k)
            .filter(|k| strips(k))
            .collect();
        let add = vec![
            (RELAY_KEYS[0], keys.https_proxy.clone()),
            (RELAY_KEYS[1], keys.http_proxy.clone()),
            (RELAY_KEYS[2], keys.no_proxy.clone()),
            (RELAY_KEYS[3], keys.node_extra_ca_certs.clone()),
        ];
        Self { remove, add }
    }

    /// Apply to `cmd`: remove first, then add, so an inherited relay key is replaced.
    pub fn apply(&self, cmd: &mut std::process::Command) {
        for k in &self.remove {
            cmd.env_remove(k);
        }
        for (k, v) in &self.add {
            cmd.env(k, v);
        }
    }
}

/// `true` for a variable the service must not inherit (D-16).
fn strips(name: &OsStr) -> bool {
    let upper = name.to_string_lossy().to_ascii_uppercase();
    upper.starts_with(OPENLATCH_PREFIX) || CREDENTIAL_VARS.contains(&upper.as_str())
}

/// Start `<cli> serve --service` detached with `env` (D-16) and return its identity. The process
/// is stopped again when its identity cannot be read, so nothing runs that the ledger could not
/// name.
pub fn spawn(cli: &Path, env: &ServiceEnv) -> std::io::Result<ProcId> {
    spawn_in(cli, env, dirs::home_dir().as_deref())
}

/// [`spawn`] with its working directory given: the user's home in product, a directory the
/// caller owns in a test, which must not read `HOME` while other tests point it elsewhere.
fn spawn_in(cli: &Path, env: &ServiceEnv, cwd: Option<&Path>) -> std::io::Result<ProcId> {
    let mut cmd = std::process::Command::new(cli);
    cmd.arg("serve")
        .arg("--service")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    if let Some(cwd) = cwd {
        cmd.current_dir(cwd);
    }
    env.apply(&mut cmd);
    let mut child = sys::spawn_detached(&mut cmd)?;
    let pid = child.id();
    let Some(id) = read(pid) else {
        let _ = child.kill();
        let _ = child.wait();
        return Err(std::io::Error::other(format!(
            "the identity of the spawned service (pid {pid}) could not be read; stopped it"
        )));
    };
    // The reaper: an exited service never lingers as a zombie a pid probe would call alive. The
    // child is shared with it, so a reaper that cannot start still leaves the child here to be
    // stopped: a service with no reaper and no ledger must not keep running.
    let child = std::sync::Arc::new(std::sync::Mutex::new(child));
    let reaped = std::sync::Arc::clone(&child);
    if let Err(e) = std::thread::Builder::new()
        .name("opencode-service-reaper".into())
        .spawn(move || {
            let _ = reaped.lock().unwrap_or_else(|e| e.into_inner()).wait();
        })
    {
        let mut child = child.lock().unwrap_or_else(|e| e.into_inner());
        let _ = child.kill();
        let _ = child.wait();
        return Err(std::io::Error::other(format!(
            "the reaper for the spawned service (pid {pid}) could not start: {e}; stopped it"
        )));
    }
    Ok(id)
}

/// Stop `expected` if it is still the same process (module doc). `grace` is the wait between
/// SIGTERM and SIGKILL (Unix) or after `TerminateProcess` (Windows).
pub fn stop(expected: &ProcId, grace: Duration) -> StopOutcome {
    if expected.pid == 0 {
        return StopOutcome::Failed("refusing to signal pid 0".into());
    }
    sys::stop(expected, grace)
}

/// Re-read `expected.pid` and classify it against `expected`. The Unix signalling path's: Windows
/// re-verifies on its pinned process handle instead.
#[cfg(unix)]
fn verify(expected: &ProcId) -> Verified {
    match read(expected.pid) {
        Some(now) if now.same_process(expected) => Verified::Same,
        Some(_) => Verified::Changed,
        None if sys::exists(expected.pid) => Verified::Unreadable,
        None => Verified::Gone,
    }
}

#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Verified {
    Same,
    Changed,
    Unreadable,
    Gone,
}

/// `/proc/<pid>/stat` field 22 (starttime), counted after the **last** `)` so a `comm` holding
/// `)` or spaces cannot shift it: field 3 is index 0 of the remainder, so field 22 is index 19.
#[cfg(any(target_os = "linux", test))]
fn parse_stat_start(stat: &str) -> Option<u64> {
    let (_, rest) = stat.rsplit_once(')')?;
    rest.split_whitespace().nth(19)?.parse().ok()
}

// ---------------------------------------------------------------------------
// Per-OS primitives
// ---------------------------------------------------------------------------

#[cfg(unix)]
mod unix_common {
    use std::time::{Duration, Instant};

    pub(super) fn to_pid(pid: u32) -> Option<libc::pid_t> {
        // pid 0 and anything that is not a positive pid_t would signal a process GROUP.
        libc::pid_t::try_from(pid).ok().filter(|p| *p > 0)
    }

    /// `kill(pid, sig)`. `Ok(false)` when the process is already gone (`ESRCH`).
    pub(super) fn kill(pid: u32, sig: libc::c_int) -> Result<bool, String> {
        let p = to_pid(pid).ok_or_else(|| format!("refusing to signal pid {pid}"))?;
        // SAFETY: `kill(2)` with a positive pid signals exactly that process.
        if unsafe { libc::kill(p, sig) } == 0 {
            return Ok(true);
        }
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() == Some(libc::ESRCH) {
            return Ok(false);
        }
        Err(format!("signalling pid {pid}: {err}"))
    }

    /// The pid names a process at all (zombies included).
    pub(super) fn exists(pid: u32) -> bool {
        let Some(p) = to_pid(pid) else { return false };
        // SAFETY: signal 0 performs the permission and existence checks only.
        let rc = unsafe { libc::kill(p, 0) };
        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    }

    pub(super) fn running_elevated() -> bool {
        // SAFETY: `geteuid` cannot fail.
        unsafe { libc::geteuid() == 0 }
    }

    /// `setsid()` alone in the child (D-16), its return checked, then spawn.
    pub(super) fn spawn_detached(
        cmd: &mut std::process::Command,
    ) -> std::io::Result<std::process::Child> {
        use std::os::unix::process::CommandExt;
        // SAFETY: `pre_exec` runs in the forked child between `fork` and `exec`, where only
        // async-signal-safe calls are permitted; `setsid(2)` and reading `errno` are. The child
        // is never put in a new process group first: `setsid` from a group leader fails `EPERM`.
        unsafe {
            cmd.pre_exec(|| {
                if libc::setsid() == -1 {
                    return Err(std::io::Error::last_os_error());
                }
                Ok(())
            });
        }
        cmd.spawn()
    }

    /// Kill-and-poll stop for a pid with no pinning handle: re-verify immediately before each
    /// signal (macOS; Linux without pidfds).
    pub(super) fn stop_by_reread(expected: &super::ProcId, grace: Duration) -> super::StopOutcome {
        use super::{verify, StopOutcome, Verified};
        match verify(expected) {
            Verified::Same => {}
            Verified::Gone => return StopOutcome::Gone,
            Verified::Changed => return StopOutcome::Changed,
            Verified::Unreadable => return StopOutcome::Unreadable,
        }
        match kill(expected.pid, libc::SIGTERM) {
            Ok(true) => {}
            Ok(false) => return StopOutcome::Gone,
            Err(e) => return StopOutcome::Failed(e),
        }
        if wait_gone(expected, grace) {
            return StopOutcome::Stopped;
        }
        match verify(expected) {
            Verified::Same => {}
            Verified::Gone => return StopOutcome::Stopped,
            // Not the process we signalled any more: never escalate onto it.
            Verified::Changed | Verified::Unreadable => return StopOutcome::Stopped,
        }
        match kill(expected.pid, libc::SIGKILL) {
            Ok(true) => {}
            Ok(false) => return StopOutcome::Stopped,
            Err(e) => return StopOutcome::Failed(e),
        }
        if wait_gone(expected, super::KILL_WAIT) {
            StopOutcome::Stopped
        } else {
            StopOutcome::Failed(format!("pid {} survived SIGKILL", expected.pid))
        }
    }

    /// Poll until `expected` is no longer that process (gone, reaped, or a zombie whose
    /// identity no longer reads).
    fn wait_gone(expected: &super::ProcId, within: Duration) -> bool {
        let deadline = Instant::now() + within;
        loop {
            if super::verify(expected) != super::Verified::Same {
                return true;
            }
            if Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
    }
}

#[cfg(target_os = "linux")]
mod sys {
    use super::unix_common;
    use super::{ProcId, StopOutcome};
    use std::path::PathBuf;
    use std::time::Duration;

    pub(super) use unix_common::{exists, running_elevated, spawn_detached};

    fn proc_dir(pid: u32) -> PathBuf {
        PathBuf::from("/proc").join(pid.to_string())
    }

    pub(super) fn read(pid: u32) -> Option<ProcId> {
        let dir = proc_dir(pid);
        let stat = std::fs::read_to_string(dir.join("stat")).ok()?;
        let start = super::parse_stat_start(&stat)?;
        let exe = std::fs::read_link(dir.join("exe")).ok()?;
        Some(ProcId {
            pid,
            start: start.to_string(),
            exe,
        })
    }

    pub(super) fn processes() -> Result<Vec<(u32, PathBuf)>, String> {
        let entries = std::fs::read_dir("/proc").map_err(|e| format!("reading /proc: {e}"))?;
        let mut out = Vec::new();
        for entry in entries.flatten() {
            let Some(pid) = entry
                .file_name()
                .to_str()
                .and_then(|s| s.parse::<u32>().ok())
            else {
                continue;
            };
            // Another user's process (or one that just exited) has no readable `exe`; it is
            // matched by its `comm` name instead, so an unreadable link never hides an OpenCode
            // process from the attached check.
            match std::fs::read_link(entry.path().join("exe")) {
                Ok(exe) => out.push((pid, exe)),
                Err(_) => {
                    if let Ok(comm) = std::fs::read_to_string(entry.path().join("comm")) {
                        out.push((pid, PathBuf::from(comm.trim())));
                    }
                }
            }
        }
        Ok(out)
    }

    fn pidfd_open(pid: u32) -> std::io::Result<libc::c_int> {
        let p = unix_common::to_pid(pid)
            .ok_or_else(|| std::io::Error::other(format!("refusing pid {pid}")))?;
        // SAFETY: `pidfd_open(2)` takes a pid and flags and returns a new fd or -1.
        let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, p, 0 as libc::c_uint) };
        if fd < 0 {
            return Err(std::io::Error::last_os_error());
        }
        libc::c_int::try_from(fd).map_err(|_| std::io::Error::other("pidfd out of range"))
    }

    struct Fd(libc::c_int);

    impl Drop for Fd {
        fn drop(&mut self) {
            // SAFETY: the fd is owned by this guard and closed once.
            unsafe { libc::close(self.0) };
        }
    }

    fn pidfd_signal(fd: &Fd, sig: libc::c_int) -> std::io::Result<bool> {
        // SAFETY: `pidfd_send_signal(2)` with a null siginfo and no flags behaves as `kill(2)`
        // on the process the fd pins.
        let rc = unsafe {
            libc::syscall(
                libc::SYS_pidfd_send_signal,
                fd.0,
                sig,
                std::ptr::null::<libc::siginfo_t>(),
                0 as libc::c_uint,
            )
        };
        if rc == 0 {
            return Ok(true);
        }
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() == Some(libc::ESRCH) {
            return Ok(false);
        }
        Err(err)
    }

    /// Wait until the pinned process exits (the pidfd turns readable), up to `within`.
    fn pidfd_wait(fd: &Fd, within: Duration) -> bool {
        let mut pfd = libc::pollfd {
            fd: fd.0,
            events: libc::POLLIN,
            revents: 0,
        };
        let ms = libc::c_int::try_from(within.as_millis()).unwrap_or(libc::c_int::MAX);
        // SAFETY: one valid pollfd, count 1.
        let rc = unsafe { libc::poll(&mut pfd, 1, ms) };
        rc > 0
    }

    pub(super) fn stop(expected: &ProcId, grace: Duration) -> StopOutcome {
        use super::{verify, Verified};
        let fd = match pidfd_open(expected.pid) {
            Ok(fd) => Fd(fd),
            Err(e) if e.raw_os_error() == Some(libc::ESRCH) => return StopOutcome::Gone,
            Err(e) if e.raw_os_error() == Some(libc::ENOSYS) => {
                return unix_common::stop_by_reread(expected, grace);
            }
            Err(e) => return StopOutcome::Failed(format!("pidfd_open({}): {e}", expected.pid)),
        };
        // The fd now pins the process: re-verify it is still the one the caller read.
        match verify(expected) {
            Verified::Same => {}
            Verified::Gone => return StopOutcome::Gone,
            Verified::Changed => return StopOutcome::Changed,
            Verified::Unreadable => return StopOutcome::Unreadable,
        }
        match pidfd_signal(&fd, libc::SIGTERM) {
            Ok(true) => {}
            Ok(false) => return StopOutcome::Gone,
            Err(e) => return StopOutcome::Failed(format!("SIGTERM to {}: {e}", expected.pid)),
        }
        if pidfd_wait(&fd, grace) {
            return StopOutcome::Stopped;
        }
        match pidfd_signal(&fd, libc::SIGKILL) {
            Ok(true) => {}
            Ok(false) => return StopOutcome::Stopped,
            Err(e) => return StopOutcome::Failed(format!("SIGKILL to {}: {e}", expected.pid)),
        }
        if pidfd_wait(&fd, super::KILL_WAIT) {
            StopOutcome::Stopped
        } else {
            StopOutcome::Failed(format!("pid {} survived SIGKILL", expected.pid))
        }
    }
}

#[cfg(target_os = "macos")]
mod sys {
    use super::unix_common;
    use super::{ProcId, StopOutcome};
    use std::path::PathBuf;
    use std::time::Duration;

    pub(super) use unix_common::{exists, running_elevated, spawn_detached};

    /// Start identity in microseconds since the epoch, from one `proc_bsdinfo` read.
    fn start_us(pid: libc::c_int) -> Option<u64> {
        // SAFETY: `proc_bsdinfo` is plain old data; all-zero is a valid value.
        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
        let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_bsdinfo>()).ok()?;
        // SAFETY: `info` is a writable `proc_bsdinfo` of exactly `size` bytes.
        let rc = unsafe {
            libc::proc_pidinfo(
                pid,
                libc::PROC_PIDTBSDINFO,
                0,
                (&mut info as *mut libc::proc_bsdinfo).cast(),
                size,
            )
        };
        if rc != size {
            return None;
        }
        info.pbi_start_tvsec
            .checked_mul(1_000_000)
            .and_then(|s| s.checked_add(info.pbi_start_tvusec))
    }

    fn pidpath(pid: libc::c_int) -> Option<PathBuf> {
        use std::os::unix::ffi::OsStrExt;
        let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
        let size = u32::try_from(buf.len()).ok()?;
        // SAFETY: `buf` is a writable buffer of `size` bytes; the call writes at most that.
        let len = unsafe { libc::proc_pidpath(pid, buf.as_mut_ptr().cast(), size) };
        let len = usize::try_from(len).ok().filter(|l| *l > 0)?;
        Some(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
    }

    pub(super) fn read(pid: u32) -> Option<ProcId> {
        let p = unix_common::to_pid(pid)?;
        let start = start_us(p)?;
        let exe = pidpath(p)?;
        // Read the start again after the path: a pid reused between the two reads changes it.
        (start_us(p)? == start).then(|| ProcId {
            pid,
            start: start.to_string(),
            exe,
        })
    }

    pub(super) fn processes() -> Result<Vec<(u32, PathBuf)>, String> {
        // SAFETY: a null buffer asks for the count only.
        let n = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) };
        if n <= 0 {
            return Err("proc_listallpids failed".into());
        }
        // Headroom for processes started between the two calls.
        let mut pids = vec![0 as libc::c_int; usize::try_from(n).unwrap_or(0) + 64];
        let bytes = libc::c_int::try_from(pids.len() * std::mem::size_of::<libc::c_int>())
            .map_err(|_| "proc_listallpids: too many pids".to_string())?;
        // SAFETY: `pids` is a writable buffer of exactly `bytes` bytes.
        let got = unsafe { libc::proc_listallpids(pids.as_mut_ptr().cast(), bytes) };
        if got <= 0 {
            return Err("proc_listallpids failed".into());
        }
        pids.truncate(usize::try_from(got).unwrap_or(0).min(pids.len()));
        let mut out = Vec::new();
        for pid in pids.into_iter().filter(|p| *p > 0) {
            if let Some(exe) = pidpath(pid) {
                out.push((u32::try_from(pid).unwrap_or(0), exe));
            } else if let Some(name) = proc_name(pid) {
                // Another user's process: `proc_pidpath` is refused, `proc_name` is not.
                out.push((u32::try_from(pid).unwrap_or(0), PathBuf::from(name)));
            }
        }
        Ok(out)
    }

    fn proc_name(pid: libc::c_int) -> Option<String> {
        let mut buf = vec![0u8; 256];
        let size = u32::try_from(buf.len()).ok()?;
        // SAFETY: `buf` is a writable buffer of `size` bytes; the call writes at most that.
        let len = unsafe { libc::proc_name(pid, buf.as_mut_ptr().cast(), size) };
        let len = usize::try_from(len).ok().filter(|l| *l > 0)?;
        Some(String::from_utf8_lossy(&buf[..len]).into_owned())
    }

    pub(super) fn stop(expected: &ProcId, grace: Duration) -> StopOutcome {
        unix_common::stop_by_reread(expected, grace)
    }
}

#[cfg(windows)]
mod sys {
    use super::{ProcId, StopOutcome};
    use std::path::PathBuf;
    use std::time::Duration;
    use windows_sys::Win32::Foundation::{
        CloseHandle, ERROR_ACCESS_DENIED, FILETIME, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
    };
    use windows_sys::Win32::System::Threading::{
        GetCurrentProcess, GetExitCodeProcess, GetProcessTimes, OpenProcess, OpenProcessToken,
        QueryFullProcessImageNameW, TerminateProcess, WaitForSingleObject, PROCESS_NAME_WIN32,
        PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
    };

    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
    const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
    const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
    /// `GetExitCodeProcess`'s value for a process still running.
    const STILL_ACTIVE: u32 = 259;

    struct Handle(HANDLE);

    impl Drop for Handle {
        fn drop(&mut self) {
            // SAFETY: the handle is owned by this guard and closed once.
            unsafe { CloseHandle(self.0) };
        }
    }

    fn open(pid: u32, access: u32) -> Option<Handle> {
        // SAFETY: `OpenProcess` returns a handle or null.
        let h = unsafe { OpenProcess(access, 0, pid) };
        (!h.is_null()).then_some(Handle(h))
    }

    fn creation_time(h: &Handle) -> Option<u64> {
        let zero = FILETIME {
            dwLowDateTime: 0,
            dwHighDateTime: 0,
        };
        let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
        // SAFETY: four writable FILETIMEs; the handle carries query rights.
        let ok = unsafe { GetProcessTimes(h.0, &mut created, &mut exited, &mut kernel, &mut user) };
        if ok == 0 {
            return None;
        }
        Some((u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime))
    }

    fn image(h: &Handle) -> Option<PathBuf> {
        use std::os::windows::ffi::OsStringExt;
        let mut buf = vec![0u16; 32_768];
        let mut len = u32::try_from(buf.len()).ok()?;
        // SAFETY: `buf` is a writable buffer of `len` UTF-16 units; `len` is updated in place.
        let ok = unsafe {
            QueryFullProcessImageNameW(h.0, PROCESS_NAME_WIN32, buf.as_mut_ptr(), &mut len)
        };
        if ok == 0 {
            return None;
        }
        buf.truncate(usize::try_from(len).ok()?);
        Some(PathBuf::from(std::ffi::OsString::from_wide(&buf)))
    }

    fn still_running(h: &Handle) -> bool {
        let mut code = 0u32;
        // SAFETY: a writable u32; the handle carries query rights.
        let ok = unsafe { GetExitCodeProcess(h.0, &mut code) };
        ok != 0 && code == STILL_ACTIVE
    }

    fn identity(pid: u32, h: &Handle) -> Option<ProcId> {
        if !still_running(h) {
            return None;
        }
        Some(ProcId {
            pid,
            start: creation_time(h)?.to_string(),
            exe: image(h)?,
        })
    }

    pub(super) fn read(pid: u32) -> Option<ProcId> {
        let h = open(pid, PROCESS_QUERY_LIMITED_INFORMATION)?;
        identity(pid, &h)
    }

    pub(super) fn exists(pid: u32) -> bool {
        open(pid, PROCESS_QUERY_LIMITED_INFORMATION).is_some_and(|h| still_running(&h))
    }

    pub(super) fn processes() -> Result<Vec<(u32, PathBuf)>, String> {
        use windows_sys::Win32::System::Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
            TH32CS_SNAPPROCESS,
        };
        // SAFETY: a process snapshot of the whole system; INVALID_HANDLE_VALUE on failure.
        let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
        if snap == INVALID_HANDLE_VALUE || snap.is_null() {
            return Err(format!(
                "CreateToolhelp32Snapshot: {}",
                std::io::Error::last_os_error()
            ));
        }
        let snap = Handle(snap);
        // SAFETY: plain old data; all-zero is valid, and `dwSize` is set before the first call.
        let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
        entry.dwSize = u32::try_from(std::mem::size_of::<PROCESSENTRY32W>()).unwrap_or(0);
        let mut out = Vec::new();
        // SAFETY: a valid snapshot handle and an initialised entry.
        let mut more = unsafe { Process32FirstW(snap.0, &mut entry) } != 0;
        if !more {
            return Err(format!(
                "Process32FirstW: {}",
                std::io::Error::last_os_error()
            ));
        }
        while more {
            let len = entry
                .szExeFile
                .iter()
                .position(|c| *c == 0)
                .unwrap_or(entry.szExeFile.len());
            let name = String::from_utf16_lossy(&entry.szExeFile[..len]);
            out.push((entry.th32ProcessID, PathBuf::from(name)));
            // SAFETY: as above.
            more = unsafe { Process32NextW(snap.0, &mut entry) } != 0;
        }
        Ok(out)
    }

    pub(super) fn running_elevated() -> bool {
        use windows_sys::Win32::Security::{
            GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY,
        };
        let mut token: HANDLE = std::ptr::null_mut();
        // SAFETY: the current-process pseudo-handle and a writable token out-parameter.
        if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
            return true;
        }
        let token = Handle(token);
        let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
        let size = u32::try_from(std::mem::size_of::<TOKEN_ELEVATION>()).unwrap_or(0);
        let mut got = 0u32;
        // SAFETY: a writable TOKEN_ELEVATION of exactly `size` bytes.
        let ok = unsafe {
            GetTokenInformation(
                token.0,
                TokenElevation,
                (&mut elevation as *mut TOKEN_ELEVATION).cast(),
                size,
                &mut got,
            )
        };
        ok == 0 || elevation.TokenIsElevated != 0
    }

    /// No console window, a new process group, and a breakaway from the daemon's job — retried
    /// without the breakaway when the job refuses it (D-16).
    pub(super) fn spawn_detached(
        cmd: &mut std::process::Command,
    ) -> std::io::Result<std::process::Child> {
        use std::os::windows::process::CommandExt;
        crate::core::process_compat::no_console_window(cmd);
        cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB);
        match cmd.spawn() {
            Err(e) if e.raw_os_error() == i32::try_from(ERROR_ACCESS_DENIED).ok() => {
                cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
                cmd.spawn()
            }
            other => other,
        }
    }

    /// One handle pins the process: re-verify creation time and image on it, then terminate it
    /// and wait on the same handle (D-3).
    pub(super) fn stop(expected: &ProcId, grace: Duration) -> StopOutcome {
        let Some(h) = open(
            expected.pid,
            PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE | PROCESS_SYNCHRONIZE,
        ) else {
            return if exists(expected.pid) {
                StopOutcome::Unreadable
            } else {
                StopOutcome::Gone
            };
        };
        if !still_running(&h) {
            return StopOutcome::Gone;
        }
        match identity(expected.pid, &h) {
            Some(now) if now.same_process(expected) => {}
            Some(_) => return StopOutcome::Changed,
            None => return StopOutcome::Unreadable,
        }
        // SAFETY: the handle carries PROCESS_TERMINATE and pins the verified process.
        if unsafe { TerminateProcess(h.0, 1) } == 0 {
            return StopOutcome::Failed(format!(
                "TerminateProcess({}): {}",
                expected.pid,
                std::io::Error::last_os_error()
            ));
        }
        let ms = u32::try_from(grace.as_millis()).unwrap_or(u32::MAX);
        // SAFETY: the handle carries SYNCHRONIZE.
        if unsafe { WaitForSingleObject(h.0, ms) } == WAIT_OBJECT_0 {
            StopOutcome::Stopped
        } else {
            StopOutcome::Failed(format!(
                "pid {} did not exit after termination",
                expected.pid
            ))
        }
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
mod sys {
    use super::unix_common;
    use super::{ProcId, StopOutcome};
    use std::path::PathBuf;
    use std::time::Duration;

    pub(super) use unix_common::{exists, running_elevated, spawn_detached};

    /// No start identity is readable here, so nothing is ever signalled (fail closed).
    pub(super) fn read(_pid: u32) -> Option<ProcId> {
        None
    }

    pub(super) fn processes() -> Result<Vec<(u32, PathBuf)>, String> {
        Err("no process table reader on this OS".into())
    }

    pub(super) fn stop(_expected: &ProcId, _grace: Duration) -> StopOutcome {
        StopOutcome::Unreadable
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hooks::proxy_env_file::EnvJson;

    fn keys() -> EnvJson {
        EnvJson {
            https_proxy: "http://127.0.0.1:47811".into(),
            http_proxy: "http://127.0.0.1:47811".into(),
            no_proxy: "localhost,127.0.0.1,::1,[::1]".into(),
            node_extra_ca_certs: "/ol/model-relay/ca/ca.pem".into(),
            instance_id: "0123456789abcdef0123456789abcdef".into(),
        }
    }

    fn os(k: &str, v: &str) -> (OsString, OsString) {
        (OsString::from(k), OsString::from(v))
    }

    #[test]
    fn opencode_names_match_case_insensitively_with_exe_stripped() {
        for name in [
            "opencode",
            "OpenCode",
            "opencode-cli",
            "opencode-cli.exe",
            "OpenCode.exe",
            "ai.opencode.desktop",
        ] {
            assert!(is_opencode_exe(Path::new(name)), "{name}");
        }
        for name in ["opencoder", "node", "opencode-cli-dev", "bash", "cline"] {
            assert!(!is_opencode_exe(Path::new(name)), "{name}");
        }
        assert!(is_service_binary(Path::new("opencode-cli.EXE")));
        assert!(!is_service_binary(Path::new("opencode")));
    }

    #[test]
    fn the_service_environment_strips_openlatch_credentials_and_proxies_and_adds_four_keys() {
        let inherited = vec![
            os("PATH", "/usr/bin"),
            os("HOME", "/home/dev"),
            os("SystemRoot", "C:\\Windows"),
            os("OPENLATCH_API_KEY", "secret-a"),
            os("OPENLATCH_TOKEN", "secret-b"),
            os("openlatch_proxy_auth", "secret-c"),
            os("ALL_PROXY", "socks5://corp:1080"),
            os("all_proxy", "socks5://corp:1080"),
            os("https_proxy", "http://user:pw@corp:8080"),
            os("HTTP_PROXY", "http://user:pw@corp:8080"),
            os("no_proxy", "corp.internal"),
            os("NODE_EXTRA_CA_CERTS", "/etc/corp.pem"),
            os("ANTHROPIC_API_KEY", "provider-key-kept"),
        ];
        let env = ServiceEnv::new(inherited, &keys());
        let mut cmd = std::process::Command::new("opencode-cli");
        env.apply(&mut cmd);
        let envs: Vec<(String, Option<String>)> = cmd
            .get_envs()
            .map(|(k, v)| {
                (
                    k.to_string_lossy().into_owned(),
                    v.map(|v| v.to_string_lossy().into_owned()),
                )
            })
            .collect();
        // Windows environment names are case-insensitive: `Command` keeps the inherited
        // spelling (`https_proxy`) when an override replaces it, so compare names the way
        // the OS does there and exactly everywhere else.
        let norm = |k: &str| {
            if cfg!(windows) {
                k.to_ascii_uppercase()
            } else {
                k.to_string()
            }
        };
        let set: Vec<&(String, Option<String>)> =
            envs.iter().filter(|(_, v)| v.is_some()).collect();
        let mut set_names: Vec<String> = set.iter().map(|(k, _)| norm(k)).collect();
        set_names.sort();
        let mut want: Vec<String> = RELAY_KEYS.iter().map(|k| norm(k)).collect();
        want.sort();
        assert_eq!(set_names, want, "exactly the four relay keys are added");
        let value = |k: &str| {
            envs.iter()
                .find(|(n, _)| norm(n) == norm(k))
                .and_then(|(_, v)| v.clone())
        };
        assert_eq!(
            value("HTTPS_PROXY").as_deref(),
            Some("http://127.0.0.1:47811")
        );
        assert_eq!(
            value("NODE_EXTRA_CA_CERTS").as_deref(),
            Some("/ol/model-relay/ca/ca.pem")
        );
        let removed: Vec<String> = envs
            .iter()
            .filter(|(_, v)| v.is_none())
            .map(|(k, _)| k.to_ascii_uppercase())
            .collect();
        for gone in [
            "OPENLATCH_API_KEY",
            "OPENLATCH_TOKEN",
            "OPENLATCH_PROXY_AUTH",
            "ALL_PROXY",
            "HTTPS_PROXY",
            "NO_PROXY",
        ] {
            // On Windows a removal and a relay override of the same name collapse into one
            // entry, the override: the inherited value is gone either way.
            let overridden = cfg!(windows) && RELAY_KEYS.contains(&gone) && value(gone).is_some();
            assert!(
                removed.iter().any(|k| k == gone) || overridden,
                "{gone} is removed"
            );
        }
        for kept in ["PATH", "HOME", "SYSTEMROOT", "ANTHROPIC_API_KEY"] {
            assert!(
                !envs.iter().any(|(k, _)| k.eq_ignore_ascii_case(kept)),
                "{kept} is inherited untouched"
            );
        }
    }

    #[test]
    fn stat_start_counts_after_the_last_paren() {
        let stat =
            "4242 (a) b) c) S 1 4242 4242 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 987654 1000 10";
        assert_eq!(parse_stat_start(stat), Some(987_654));
        assert_eq!(parse_stat_start("garbage"), None);
    }

    #[test]
    fn pid_zero_is_never_read_or_signalled() {
        assert!(read(0).is_none());
        let id = ProcId {
            pid: 0,
            start: "1".into(),
            exe: PathBuf::from("opencode-cli"),
        };
        assert!(matches!(
            stop(&id, Duration::from_millis(10)),
            StopOutcome::Failed(_)
        ));
    }

    #[test]
    fn our_own_process_reads_with_a_stable_identity() {
        let me = std::process::id();
        let a = read(me).expect("own identity readable");
        let b = read(me).expect("own identity readable twice");
        assert!(a.same_process(&b));
        assert!(!a.start.is_empty());
    }

    #[test]
    fn an_unreadable_table_counts_as_attached() {
        struct Broken;
        impl ProcessTable for Broken {
            fn read(&self, _: u32) -> Option<ProcId> {
                None
            }
            fn exists(&self, _: u32) -> bool {
                true
            }
            fn opencode_processes(&self) -> Result<Vec<(u32, PathBuf)>, String> {
                Err("denied".into())
            }
            fn stop(&self, _: &ProcId, _: Duration) -> StopOutcome {
                StopOutcome::Unreadable
            }
            fn spawn(&self, _: &Path, _: &ServiceEnv) -> std::io::Result<ProcId> {
                Err(std::io::Error::other("no"))
            }
        }
        assert_eq!(attached(&Broken, &[]), Attached::Unknown);
        assert!(Attached::Unknown.blocks_replacement());
        assert!(Attached::Yes.blocks_replacement());
        assert!(!Attached::No.blocks_replacement());
    }

    /// Real children on Unix: the spawn's `setsid`, its environment, and the identity-checked
    /// stop.
    #[cfg(unix)]
    mod real {
        use super::*;
        use std::time::Instant;

        /// A stub `serve --service`: dumps its environment beside itself, then sleeps.
        fn stub(dir: &Path) -> PathBuf {
            use std::os::unix::fs::PermissionsExt;
            let path = dir.join("opencode-cli");
            std::fs::write(
                &path,
                "#!/bin/sh\nenv > \"$(dirname \"$0\")/env.out.tmp\"\nmv \"$(dirname \"$0\")/env.out.tmp\" \"$(dirname \"$0\")/env.out\"\nexec sleep 30\n",
            )
            .unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        }

        /// `spawn`, retried on `ETXTBSY`: another test thread forking while the stub was open
        /// for writing holds a write descriptor to it for a moment. Run in the stub's own
        /// directory: other tests point `HOME` at a temporary directory and delete it, so
        /// `spawn`'s home lookup would race them.
        fn spawn_retrying(cli: &Path, env: &ServiceEnv) -> ProcId {
            for _ in 0..50 {
                match spawn_in(cli, env, cli.parent()) {
                    Ok(id) => return id,
                    Err(e) if e.raw_os_error() == Some(libc::ETXTBSY) => {
                        std::thread::sleep(Duration::from_millis(20));
                    }
                    Err(e) => panic!("spawn failed: {e}"),
                }
            }
            panic!("spawn kept failing with ETXTBSY");
        }

        fn wait_for(path: &Path) -> String {
            let deadline = Instant::now() + Duration::from_secs(10);
            while Instant::now() < deadline {
                if let Ok(s) = std::fs::read_to_string(path) {
                    return s;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            panic!("{} never appeared", path.display());
        }

        #[test]
        fn a_spawned_service_leads_its_own_session_with_exactly_the_relay_keys() {
            let dir = tempfile::tempdir().unwrap();
            let cli = stub(dir.path());
            // The test process's own environment, as the manager passes the daemon's: whatever
            // OPENLATCH_* or proxy variable the harness exported must not reach the child.
            let env = ServiceEnv::new(std::env::vars_os(), &keys());
            let id = spawn_retrying(&cli, &env);
            // SAFETY: `getsid` reads a pid's session id.
            let sid = unsafe { libc::getsid(libc::pid_t::try_from(id.pid).unwrap()) };
            assert_eq!(
                sid,
                libc::pid_t::try_from(id.pid).unwrap(),
                "setsid made it a session leader"
            );
            let dumped = wait_for(&dir.path().join("env.out"));
            let lines: Vec<&str> = dumped.lines().collect();
            for (k, v) in &env.add {
                assert!(
                    lines.contains(&format!("{k}={v}").as_str()),
                    "{k} set in the child"
                );
            }
            assert!(
                !lines.iter().any(|l| l.starts_with("OPENLATCH_")),
                "no OPENLATCH_ variable reaches the service"
            );
            assert!(
                !lines
                    .iter()
                    .any(|l| l.to_ascii_uppercase().starts_with("ALL_PROXY=")),
                "no ALL_PROXY reaches the service"
            );
            let now = read(id.pid).expect("child readable");
            assert!(stop(&now, Duration::from_secs(5)).is_gone());
        }

        #[test]
        fn stop_signals_only_a_process_whose_identity_still_matches() {
            let mut child = std::process::Command::new("sleep")
                .arg("30")
                .spawn()
                .expect("sleep spawns");
            let pid = child.id();
            let id = read(pid).expect("child readable");

            // A changed start identity is never signalled.
            let reused = ProcId {
                start: format!("{}9", id.start),
                ..id.clone()
            };
            assert_eq!(
                stop(&reused, Duration::from_millis(200)),
                StopOutcome::Changed
            );
            // A different executable is never signalled.
            let other_exe = ProcId {
                exe: PathBuf::from("/nonexistent/opencode-cli"),
                ..id.clone()
            };
            assert_eq!(
                stop(&other_exe, Duration::from_millis(200)),
                StopOutcome::Changed
            );
            assert!(
                read(pid).is_some_and(|p| p.same_process(&id)),
                "still running"
            );

            let reaper = std::thread::spawn(move || child.wait());
            assert_eq!(stop(&id, Duration::from_secs(5)), StopOutcome::Stopped);
            reaper.join().unwrap().unwrap();
            assert_eq!(stop(&id, Duration::from_millis(100)), StopOutcome::Gone);
        }

        #[test]
        fn a_process_ignoring_sigterm_is_killed_after_the_grace() {
            let mut child = std::process::Command::new("sh")
                .arg("-c")
                .arg("trap '' TERM; while :; do sleep 1; done")
                .spawn()
                .expect("sh spawns");
            let pid = child.id();
            // Give the shell time to install its trap.
            std::thread::sleep(Duration::from_millis(300));
            let id = read(pid).expect("child readable");
            let reaper = std::thread::spawn(move || child.wait());
            let began = Instant::now();
            assert_eq!(stop(&id, Duration::from_millis(300)), StopOutcome::Stopped);
            assert!(began.elapsed() >= Duration::from_millis(300));
            reaper.join().unwrap().unwrap();
        }
    }

    /// Real children on Windows (D-3, D-16): the spawn through `spawn_detached`'s creation flags
    /// and its breakaway retry, the environment it delivers, and the termination that re-verifies
    /// the process's identity on the one handle it then terminates. Run by the Windows unit-test
    /// job.
    #[cfg(windows)]
    mod real_windows {
        use super::*;
        use std::time::Instant;

        /// A stub `serve --service`: a batch file that dumps its environment beside itself, then
        /// waits. `Command` runs a `.cmd` through `cmd.exe`, so the spawned pid is that `cmd.exe`.
        fn stub(dir: &Path) -> PathBuf {
            let path = dir.join("opencode-cli.cmd");
            std::fs::write(
                &path,
                "@echo off\r\nset > \"%~dp0env.tmp\"\r\nmove /y \"%~dp0env.tmp\" \"%~dp0env.out\" > nul\r\nping -n 30 127.0.0.1 > nul\r\n",
            )
            .unwrap();
            path
        }

        fn wait_for(path: &Path) -> String {
            let deadline = Instant::now() + Duration::from_secs(20);
            while Instant::now() < deadline {
                if let Ok(s) = std::fs::read_to_string(path) {
                    return s;
                }
                std::thread::sleep(Duration::from_millis(50));
            }
            panic!("{} never appeared", path.display());
        }

        #[test]
        fn a_spawned_service_gets_exactly_the_relay_keys_and_keeps_system_root() {
            let dir = tempfile::tempdir().unwrap();
            let cli = stub(dir.path());
            let env = ServiceEnv::new(std::env::vars_os(), &keys());
            let id = spawn_in(&cli, &env, Some(dir.path())).expect("the service spawns");
            let dumped = wait_for(&dir.path().join("env.out"));
            let lines: Vec<String> = dumped.lines().map(str::to_ascii_uppercase).collect();
            for (k, v) in &env.add {
                let want = format!("{k}={v}").to_ascii_uppercase();
                assert!(lines.contains(&want), "{k} set in the child");
            }
            assert!(
                !lines.iter().any(|l| l.starts_with("OPENLATCH_")),
                "no OPENLATCH_ variable reaches the service"
            );
            assert!(
                !lines.iter().any(|l| l.starts_with("ALL_PROXY=")),
                "no ALL_PROXY reaches the service"
            );
            assert!(
                lines.iter().any(|l| l.starts_with("SYSTEMROOT=")),
                "SystemRoot is inherited: the environment is never cleared"
            );
            let now = read(id.pid).expect("child readable");
            assert!(now.same_process(&id));
            assert!(stop(&now, Duration::from_secs(5)).is_gone());
        }

        #[test]
        fn termination_needs_the_identity_on_the_pinned_handle_to_match() {
            let mut child = std::process::Command::new("ping")
                .args(["-n", "30", "127.0.0.1"])
                .stdout(std::process::Stdio::null())
                .spawn()
                .expect("ping spawns");
            let pid = child.id();
            let id = read(pid).expect("child readable");

            // A changed creation time is never terminated.
            let reused = ProcId {
                start: format!("{}9", id.start),
                ..id.clone()
            };
            assert_eq!(
                stop(&reused, Duration::from_millis(200)),
                StopOutcome::Changed
            );
            // A different image is never terminated.
            let other_exe = ProcId {
                exe: PathBuf::from(r"C:\nonexistent\opencode-cli.exe"),
                ..id.clone()
            };
            assert_eq!(
                stop(&other_exe, Duration::from_millis(200)),
                StopOutcome::Changed
            );
            assert!(
                read(pid).is_some_and(|p| p.same_process(&id)),
                "still running"
            );

            assert_eq!(stop(&id, Duration::from_secs(5)), StopOutcome::Stopped);
            child.wait().expect("reaped");
            assert_eq!(stop(&id, Duration::from_millis(100)), StopOutcome::Gone);
        }
    }
}