rigspark-runtime 3.1.1

Hardware detection, backend adapters, lifecycle, memory and harness runtime for rigspark.
Documentation
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
use crate::state::{RuntimeState, ServerState, StateError, loopback};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

fn invalid(message: &str) -> StateError {
    StateError {
        kind: "invalid",
        message: message.into(),
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessIdentity {
    pub pid: u32,
    pub process: String,
    pub executable: String,
    pub started: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Listener {
    pub identity: ProcessIdentity,
    pub address: String,
    pub port: u16,
}
fn addresses_match(actual: &str, expected: &str) -> bool {
    let actual = actual.trim_matches(['[', ']']).to_ascii_lowercase();
    let expected = expected.trim_matches(['[', ']']).to_ascii_lowercase();
    if expected == "localhost" {
        ["127.0.0.1", "::1", "localhost"].contains(&actual.as_str())
    } else {
        actual == expected
    }
}
pub fn choose_listener(
    listeners: &[Listener],
    port: u16,
    host: &str,
) -> Result<Listener, StateError> {
    let mut matches = listeners
        .iter()
        .filter(|entry| entry.port == port && addresses_match(&entry.address, host));
    let found = matches
        .next()
        .ok_or_else(|| invalid("listener identity unavailable"))?;
    if matches.next().is_some() {
        return Err(invalid("listener identity ambiguous"));
    }
    Ok(found.clone())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveIdentity {
    pub hash: String,
    pub expected: ProcessIdentity,
}
fn hash(value: &impl Serialize) -> Result<String, StateError> {
    let value = serde_json::to_value(value).map_err(|_| invalid("cannot serialize identity"))?;
    let bytes = serde_json::to_vec(&value).map_err(|_| invalid("cannot encode identity"))?;
    if bytes.len() > 1048576 {
        return Err(invalid("identity exceeds limit"));
    }
    Ok(format!("{:x}", Sha256::digest(bytes)))
}
pub fn capture(
    active: &ServerState,
    observed: &Listener,
    approved_executable: bool,
) -> Result<LiveIdentity, StateError> {
    active.validate()?;
    let url = loopback(&active.endpoint)?;
    let host = url.host_str().ok_or_else(|| invalid("missing host"))?;
    let identity = &observed.identity;
    if observed.port != active.port
        || !addresses_match(&observed.address, host)
        || !approved_executable
        || identity.pid == 0
        || identity.executable.is_empty()
        || identity.started.is_empty()
        || identity.process.is_empty()
        || active.pid.is_some_and(|pid| pid != identity.pid)
        || active
            .process_executable
            .as_ref()
            .is_some_and(|value| value != &identity.executable)
        || active
            .process_started_at
            .as_ref()
            .is_some_and(|value| value != &identity.started)
    {
        return Err(invalid(
            "observed listener does not match approved runtime identity",
        ));
    }
    let value = serde_json::json!({"backend":active.backend,"host":host,"port":active.port,"pid":identity.pid,"ownedByUs":active.owned_by_us,"executable":identity.executable,"startedAt":identity.started});
    Ok(LiveIdentity {
        hash: hash(&value)?,
        expected: identity.clone(),
    })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Operation {
    Down,
    Detach,
    ReplaceServer,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Confirmation {
    operation: Operation,
    canonical_target_ids: Vec<String>,
    backend: Option<String>,
    endpoint: Option<String>,
    owned_by_us: Option<bool>,
    process_identity_hash: Option<String>,
    state_revision_hash: String,
}
impl Confirmation {
    pub fn prepare(
        operation: Operation,
        state: &RuntimeState,
        target: Option<&str>,
        live: Option<&LiveIdentity>,
    ) -> Result<Self, StateError> {
        state.validate()?;
        let active = state.active.as_ref();
        if active.is_some() != live.is_some() {
            return Err(invalid(
                "active confirmation requires live process identity",
            ));
        }
        match operation {
            Operation::Down if active.is_some_and(|entry| !entry.owned_by_us) => {
                return Err(invalid("down requires owned runtime"));
            }
            Operation::Detach if !active.is_some_and(|entry| !entry.owned_by_us) => {
                return Err(invalid("detach requires attached runtime"));
            }
            Operation::ReplaceServer if target.is_none() => {
                return Err(invalid("replacement target required"));
            }
            Operation::Down | Operation::Detach if target.is_some() => {
                return Err(invalid("unexpected target"));
            }
            _ => (),
        }
        let mut targets = active
            .map(|entry| vec![entry.model_id.clone()])
            .unwrap_or_default();
        if let Some(target) = target {
            targets.push(target.into());
        }
        for target in &targets {
            if target.is_empty()
                || target.len() > 8192
                || !target.as_bytes()[0].is_ascii_alphanumeric()
                || target.split('/').any(|part| part == "..")
                || !target
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || b"._:/-".contains(&byte))
            {
                return Err(invalid("unsafe confirmation target"));
            }
        }
        Ok(Self {
            operation,
            canonical_target_ids: targets,
            backend: active.map(|entry| entry.backend.clone()),
            endpoint: active.map(|entry| entry.endpoint.clone()),
            owned_by_us: active.map(|entry| entry.owned_by_us),
            process_identity_hash: live.map(|identity| identity.hash.clone()),
            state_revision_hash: hash(state)?,
        })
    }
    pub fn verify(&self, current: &Self) -> Result<(), StateError> {
        if self == current {
            Ok(())
        } else {
            Err(StateError {
                kind: "drift",
                message: "confirmation target changed; rebuild review".into(),
            })
        }
    }
}

pub fn parse_lsof_listener(raw: &str, port: u16, host: &str) -> Result<u32, StateError> {
    if raw.len() > 65536 {
        return Err(invalid("listener output exceeds limit"));
    }
    let mut pid = None;
    let mut matches = Vec::new();
    for line in raw.lines() {
        if let Some(value) = line.strip_prefix('p') {
            pid = value
                .parse::<u32>()
                .ok()
                .filter(|pid| *pid > 0 && *pid <= i32::MAX as u32);
        }
        if let Some(value) = line.strip_prefix('n') {
            let Some((address, observed_port)) = value.rsplit_once(':') else {
                return Err(invalid("invalid listener address"));
            };
            if observed_port.parse::<u16>().ok() == Some(port) && addresses_match(address, host) {
                matches.push(pid.ok_or_else(|| invalid("missing listener PID"))?);
            }
        }
    }
    if matches.len() != 1 {
        return Err(invalid("listener absent or ambiguous"));
    }
    Ok(matches[0])
}
pub fn parse_start_time(raw: &str) -> Result<String, StateError> {
    if raw.len() > 4096 {
        return Err(invalid("process start output exceeds limit"));
    }
    let rows: Vec<_> = raw.lines().filter(|line| !line.trim().is_empty()).collect();
    if rows.len() != 1 {
        return Err(invalid("process start absent or ambiguous"));
    }
    let parts: Vec<_> = rows[0].split_whitespace().collect();
    if parts.len() != 5 || !["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].contains(&parts[0]) {
        return Err(invalid("invalid process start"));
    }
    let month = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ]
    .iter()
    .position(|month| *month == parts[1])
    .ok_or_else(|| invalid("invalid start month"))?
        + 1;
    let day = parts[2]
        .parse::<u8>()
        .map_err(|_| invalid("invalid start day"))?;
    let time: Vec<_> = parts[3].split(':').collect();
    if !(1..=31).contains(&day)
        || parts[4].len() != 4
        || !parts[4].bytes().all(|byte| byte.is_ascii_digit())
        || time.len() != 3
        || time.iter().enumerate().any(|(index, part)| {
            part.len() != 2
                || part
                    .parse::<u8>()
                    .map_or(true, |value| value > if index == 0 { 23 } else { 59 })
        })
    {
        return Err(invalid("invalid process start"));
    }
    Ok(format!("{}-{month:02}-{day:02} {}", parts[4], parts[3]))
}
pub fn parse_windows_listener(raw: &str, port: u16, host: &str) -> Result<Listener, StateError> {
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Row {
        pid: u32,
        process: String,
        executable: String,
        started: String,
        address: String,
        port: u16,
    }
    if raw.len() > 65536 {
        return Err(invalid("listener output exceeds limit"));
    }
    let rows: Vec<Row> =
        serde_json::from_str(raw).map_err(|_| invalid("invalid Windows listener output"))?;
    let listeners: Vec<_> = rows
        .into_iter()
        .map(|row| Listener {
            identity: ProcessIdentity {
                pid: row.pid,
                process: row.process,
                executable: row.executable,
                started: row.started,
            },
            address: row.address,
            port: row.port,
        })
        .collect();
    let listener = choose_listener(&listeners, port, host)?;
    validate_process(&listener.identity)?;
    Ok(listener)
}
fn validate_process(identity: &ProcessIdentity) -> Result<(), StateError> {
    if identity.pid == 0
        || identity.pid > i32::MAX as u32
        || identity.process.is_empty()
        || identity.executable.is_empty()
        || identity.started.is_empty()
    {
        return Err(invalid("incomplete process identity"));
    }
    Ok(())
}
#[async_trait::async_trait]
pub trait ProcessProbe: Send + Sync {
    async fn listener(&self, port: u16, host: &str) -> Result<Listener, StateError>;
    async fn process(&self, pid: u32) -> Result<ProcessIdentity, StateError>;
    /// Return argv including the executable; unavailable introspection must fail closed.
    async fn command_line(&self, _pid: u32) -> Result<Vec<String>, StateError> {
        Err(invalid("process command line unavailable"))
    }
    /// Whether any process holds `pid`; probes that cannot tell must fail closed.
    async fn alive(&self, _pid: u32) -> Result<bool, StateError> {
        Err(invalid("process liveness unavailable"))
    }
}
pub struct NativeProcessProbe;
async fn output(binary: &str, args: &[&str]) -> Result<String, StateError> {
    crate::hardware::command_output(binary, args)
        .await
        .map_err(|_| invalid("process identity probe failed"))
}
#[async_trait::async_trait]
impl ProcessProbe for NativeProcessProbe {
    async fn alive(&self, pid: u32) -> Result<bool, StateError> {
        if pid == 0 || pid > i32::MAX as u32 {
            return Err(invalid("invalid process PID"));
        }
        tokio::task::spawn_blocking(move || {
            let mut system = sysinfo::System::new();
            let pid = sysinfo::Pid::from_u32(pid);
            system.refresh_processes_specifics(
                sysinfo::ProcessesToUpdate::Some(&[pid]),
                true,
                sysinfo::ProcessRefreshKind::nothing(),
            );
            system.process(pid).is_some()
        })
        .await
        .map_err(|_| invalid("process liveness probe failed"))
    }
    async fn command_line(&self, pid: u32) -> Result<Vec<String>, StateError> {
        tokio::task::spawn_blocking(move || {
            let mut system = sysinfo::System::new();
            let pid = sysinfo::Pid::from_u32(pid);
            system.refresh_processes_specifics(
                sysinfo::ProcessesToUpdate::Some(&[pid]),
                true,
                sysinfo::ProcessRefreshKind::nothing().with_cmd(sysinfo::UpdateKind::Always),
            );
            let process = system
                .process(pid)
                .ok_or_else(|| invalid("process command line unavailable"))?;
            let args = process.cmd();
            if args.is_empty()
                || args.len() > 1024
                || args.iter().map(|arg| arg.len()).sum::<usize>() > 65536
            {
                return Err(invalid("invalid process command line"));
            }
            args.iter()
                .map(|arg| {
                    arg.to_str()
                        .map(str::to_owned)
                        .ok_or_else(|| invalid("non-UTF-8 process command line"))
                })
                .collect()
        })
        .await
        .map_err(|_| invalid("process command line probe failed"))?
    }

    async fn listener(&self, port: u16, host: &str) -> Result<Listener, StateError> {
        loopback(&format!(
            "http://{}:{port}",
            if host.contains(':') && !host.starts_with('[') {
                format!("[{host}]")
            } else {
                host.into()
            }
        ))?;
        #[cfg(windows)]
        {
            let script = format!(
                "$ErrorActionPreference='Stop'; $rows=@(Get-NetTCPConnection -State Listen -LocalPort {port} | ForEach-Object {{ $proc=Get-CimInstance Win32_Process -Filter ('ProcessId='+$_.OwningProcess); [pscustomobject]@{{pid=$_.OwningProcess;process=$proc.Name;executable=$proc.ExecutablePath;started=$proc.CreationDate.ToString('yyyy-MM-dd HH:mm:ss');address=$_.LocalAddress;port=$_.LocalPort}} }}); ConvertTo-Json -InputObject $rows -Compress"
            );
            let raw = output(
                "powershell.exe",
                &["-NoProfile", "-NonInteractive", "-Command", &script],
            )
            .await?;
            parse_windows_listener(&raw, port, host)
        }
        #[cfg(not(windows))]
        {
            let binary = if cfg!(target_os = "macos") {
                "/usr/sbin/lsof"
            } else {
                "lsof"
            };
            let raw = output(
                binary,
                &[
                    "-nP",
                    "-a",
                    &format!("-iTCP:{port}"),
                    "-sTCP:LISTEN",
                    "-Fpn",
                ],
            )
            .await?;
            let pid = parse_lsof_listener(&raw, port, host)?;
            let identity = self.process(pid).await?;
            let repeated = output(
                binary,
                &[
                    "-nP",
                    "-a",
                    &format!("-iTCP:{port}"),
                    "-sTCP:LISTEN",
                    "-Fpn",
                ],
            )
            .await?;
            if parse_lsof_listener(&repeated, port, host)? != pid {
                return Err(invalid("listener changed during probe"));
            }
            Ok(Listener {
                identity,
                address: host.into(),
                port,
            })
        }
    }
    async fn process(&self, pid: u32) -> Result<ProcessIdentity, StateError> {
        if pid == 0 || pid > i32::MAX as u32 {
            return Err(invalid("invalid process PID"));
        }
        #[cfg(windows)]
        {
            let script = format!(
                "$ErrorActionPreference='Stop'; $proc=Get-CimInstance Win32_Process -Filter 'ProcessId={pid}'; [pscustomobject]@{{pid=$proc.ProcessId;process=$proc.Name;executable=$proc.ExecutablePath;started=$proc.CreationDate.ToString('yyyy-MM-dd HH:mm:ss')}} | ConvertTo-Json -Compress"
            );
            let raw = output(
                "powershell.exe",
                &["-NoProfile", "-NonInteractive", "-Command", &script],
            )
            .await?;
            let identity: ProcessIdentity =
                serde_json::from_str(&raw).map_err(|_| invalid("invalid process output"))?;
            validate_process(&identity)?;
            if identity.pid != pid {
                return Err(invalid("process PID drift"));
            }
            Ok(identity)
        }
        #[cfg(not(windows))]
        {
            let pid_text = pid.to_string();
            let started =
                parse_start_time(&output("/bin/ps", &["-p", &pid_text, "-o", "lstart="]).await?)?;
            let executable = if cfg!(target_os = "macos") {
                let raw = output(
                    "/usr/sbin/lsof",
                    &["-a", "-p", &pid_text, "-d", "txt", "-Fn"],
                )
                .await?;
                let rows: Vec<_> = raw.lines().collect();
                rows.windows(2)
                    .find_map(|pair| {
                        if pair[0] == "ftxt" {
                            pair[1].strip_prefix('n')
                        } else {
                            None
                        }
                    })
                    .ok_or_else(|| invalid("process executable unavailable"))?
                    .to_owned()
            } else {
                std::fs::read_link(format!("/proc/{pid}/exe"))
                    .map_err(|_| invalid("process executable unavailable"))?
                    .to_string_lossy()
                    .into_owned()
            };
            let executable = std::fs::canonicalize(executable)
                .map_err(|_| invalid("process executable cannot be resolved"))?
                .to_string_lossy()
                .into_owned();
            let process = std::path::Path::new(&executable)
                .file_name()
                .ok_or_else(|| invalid("missing process name"))?
                .to_string_lossy()
                .into_owned();
            if parse_start_time(&output("/bin/ps", &["-p", &pid_text, "-o", "lstart="]).await?)?
                != started
            {
                return Err(invalid("process changed during probe"));
            }
            let identity = ProcessIdentity {
                pid,
                process,
                executable,
                started,
            };
            validate_process(&identity)?;
            Ok(identity)
        }
    }
}

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

    fn identity() -> ProcessIdentity {
        ProcessIdentity {
            pid: 42,
            process: "llama-server".into(),
            executable: "/opt/llama-server".into(),
            started: "2026-11-08 10:00:00".into(),
        }
    }
    fn listener(port: u16, address: &str) -> Listener {
        Listener {
            identity: identity(),
            address: address.into(),
            port,
        }
    }
    fn active() -> ServerState {
        ServerState {
            backend: "llamacpp".into(),
            model_id: "qwen3:8b".into(),
            endpoint: "http://127.0.0.1:8080".into(),
            port: 8080,
            owned_by_us: true,
            pid: Some(42),
            runtime_model_id: None,
            context: None,
            integrity: None,
            local_manifest_digest: None,
            model_path: None,
            process_executable: Some("/opt/llama-server".into()),
            process_started_at: Some("2026-11-08 10:00:00".into()),
            auth_token: None,
            cache: None,
        }
    }

    #[test]
    fn a_listener_must_match_both_port_and_address() {
        let listeners = [listener(8080, "10.0.0.5"), listener(9090, "127.0.0.1")];
        assert!(choose_listener(&listeners, 8080, "127.0.0.1").is_err());
        assert!(choose_listener(&listeners, 9090, "localhost").is_ok());
        // Another address on the same port, or the same address on another port, is ignored.
        let listeners = [listener(8080, "10.0.0.5"), listener(8080, "127.0.0.1")];
        assert!(choose_listener(&listeners, 8080, "127.0.0.1").is_ok());
        let listeners = [listener(9090, "127.0.0.1")];
        assert!(choose_listener(&listeners, 8080, "127.0.0.1").is_err());
    }

    #[test]
    fn identities_hash_up_to_one_mib() {
        assert!(hash(&"x".repeat(1048574)).is_ok());
        assert!(hash(&"x".repeat(1048575)).is_err());
    }

    #[test]
    fn a_capture_needs_every_identity_field() {
        let observed = listener(8080, "127.0.0.1");
        assert!(capture(&active(), &observed, true).is_ok());
        for change in [
            |i: &mut ProcessIdentity| i.executable.clear(),
            |i: &mut ProcessIdentity| i.started.clear(),
            |i: &mut ProcessIdentity| i.process.clear(),
            |i: &mut ProcessIdentity| i.pid = 0,
        ] {
            let mut missing = observed.clone();
            change(&mut missing.identity);
            assert!(capture(&active(), &missing, true).is_err(), "{missing:?}");
            // Even when the record has nothing to compare against.
            let mut unrecorded = active();
            unrecorded.owned_by_us = false;
            unrecorded.pid = None;
            unrecorded.process_executable = None;
            unrecorded.process_started_at = None;
            assert!(capture(&unrecorded, &observed, true).is_ok());
            assert!(capture(&unrecorded, &missing, true).is_err(), "{missing:?}");
        }
    }

    fn state(owned: bool) -> RuntimeState {
        let mut entry = active();
        entry.owned_by_us = owned;
        RuntimeState {
            schema_version: 2,
            active: Some(entry),
        }
    }

    #[test]
    fn confirmations_name_a_target_only_when_replacing() {
        let observed = listener(8080, "127.0.0.1");
        let live = capture(&active(), &observed, true).unwrap();
        let owned = state(true);
        assert!(
            Confirmation::prepare(Operation::ReplaceServer, &owned, None, Some(&live)).is_err()
        );
        assert!(
            Confirmation::prepare(
                Operation::ReplaceServer,
                &owned,
                Some("llama3:8b"),
                Some(&live)
            )
            .is_ok()
        );
        assert!(Confirmation::prepare(Operation::Down, &owned, Some("x"), Some(&live)).is_err());
        assert!(Confirmation::prepare(Operation::Down, &owned, None, Some(&live)).is_ok());
        let attached = state(false);
        let live = capture(attached.active.as_ref().unwrap(), &observed, true).unwrap();
        assert!(
            Confirmation::prepare(Operation::Detach, &attached, Some("x"), Some(&live)).is_err()
        );
        assert!(Confirmation::prepare(Operation::Detach, &attached, None, Some(&live)).is_ok());
    }

    #[test]
    fn confirmation_targets_are_safe_model_ids() {
        let observed = listener(8080, "127.0.0.1");
        let live = capture(&active(), &observed, true).unwrap();
        let owned = state(true);
        let replace = |target: &str| {
            Confirmation::prepare(Operation::ReplaceServer, &owned, Some(target), Some(&live))
        };
        assert!(replace("hf.co/owner/model:Q4_K_M").is_ok());
        assert!(replace(&"m".repeat(8192)).is_ok());
        for bad in ["", "-model", "a/../b", "a b", "a?b", &"m".repeat(8193)] {
            assert!(replace(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn lsof_and_windows_listener_output_is_capped_at_64_kib() {
        let line = "p42\nn127.0.0.1:8080\n";
        let padded = |size: usize| format!("{line}{}", "f\n".repeat((size - line.len()) / 2));
        assert_eq!(
            parse_lsof_listener(&padded(65536), 8080, "127.0.0.1").unwrap(),
            42
        );
        assert!(parse_lsof_listener(&padded(65538), 8080, "127.0.0.1").is_err());
        let row = serde_json::json!([{"pid": 42, "process": "llama-server.exe",
            "executable": "C:\\\\llama-server.exe", "started": "2026-11-08 10:00:00",
            "address": "127.0.0.1", "port": 8080}])
        .to_string();
        let windows = |size: usize| format!("{row}{}", " ".repeat(size - row.len()));
        assert!(parse_windows_listener(&windows(65536), 8080, "127.0.0.1").is_ok());
        assert!(parse_windows_listener(&windows(65537), 8080, "127.0.0.1").is_err());
    }

    #[test]
    fn start_times_are_one_well_formed_ps_line() {
        assert_eq!(
            parse_start_time("Sun Nov  8 14:28:37 2026\n").unwrap(),
            "2026-11-08 14:28:37"
        );
        let padded = format!("Sun Nov  8 14:28:37 2026{}", " ".repeat(4096 - 24));
        assert!(parse_start_time(&padded).is_ok());
        assert!(parse_start_time(&format!("{padded} ")).is_err());
        assert!(parse_start_time("Sun Nov 31 23:59:59 2026").is_ok());
        for bad in [
            "Sun Nov 8 14:28:37",
            "Xyz Nov 8 14:28:37 2026",
            "Sun Nov 0 14:28:37 2026",
            "Sun Nov 32 14:28:37 2026",
            "Sun Nov 8 14:28:37 26",
            "Sun Nov 8 14:28:37 2O26",
            "Sun Nov 8 14:28 2026",
            "Sun Nov 8 14:28:37:00 2026",
            "Sun Nov 8 1:28:37 2026",
            "Sun Nov 8 24:28:37 2026",
            "Sun Nov 8 14:60:37 2026",
            "Sun Nov 8 14:28:60 2026",
            "Sun Nov 8 aa:28:37 2026",
        ] {
            assert!(parse_start_time(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn process_identities_are_complete_and_in_range() {
        assert!(validate_process(&identity()).is_ok());
        let mut maximum = identity();
        maximum.pid = i32::MAX as u32;
        assert!(validate_process(&maximum).is_ok());
        for change in [
            |i: &mut ProcessIdentity| i.pid = 0,
            |i: &mut ProcessIdentity| i.pid = i32::MAX as u32 + 1,
            |i: &mut ProcessIdentity| i.process.clear(),
            |i: &mut ProcessIdentity| i.executable.clear(),
            |i: &mut ProcessIdentity| i.started.clear(),
        ] {
            let mut value = identity();
            change(&mut value);
            assert!(validate_process(&value).is_err(), "{value:?}");
        }
    }

    struct Minimal;
    #[async_trait::async_trait]
    impl ProcessProbe for Minimal {
        async fn listener(&self, _: u16, _: &str) -> Result<Listener, StateError> {
            Err(invalid("none"))
        }
        async fn process(&self, _: u32) -> Result<ProcessIdentity, StateError> {
            Err(invalid("none"))
        }
    }

    #[tokio::test]
    async fn probes_without_introspection_fail_closed() {
        assert!(Minimal.command_line(1).await.is_err());
        assert!(Minimal.alive(1).await.is_err());
    }

    #[tokio::test]
    async fn the_native_probe_sees_this_process_and_refuses_impossible_pids() {
        let me = std::process::id();
        assert!(NativeProcessProbe.alive(me).await.unwrap());
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let gone = child.id();
        child.wait().unwrap();
        assert!(!NativeProcessProbe.alive(gone).await.unwrap());
        for pid in [0, i32::MAX as u32 + 1] {
            assert!(NativeProcessProbe.alive(pid).await.is_err(), "{pid}");
            assert!(NativeProcessProbe.process(pid).await.is_err(), "{pid}");
        }
        // The largest PID is still looked up; out-of-range PIDs never reach `ps`.
        assert!(!NativeProcessProbe.alive(i32::MAX as u32).await.unwrap());
        for pid in [0, i32::MAX as u32 + 1] {
            assert_eq!(
                NativeProcessProbe.process(pid).await.unwrap_err().message,
                "invalid process PID"
            );
        }
        assert_ne!(
            NativeProcessProbe
                .process(i32::MAX as u32)
                .await
                .unwrap_err()
                .message,
            "invalid process PID"
        );
        let args = NativeProcessProbe.command_line(me).await.unwrap();
        let exe = std::env::current_exe().unwrap();
        assert!(
            args[0].ends_with(exe.file_name().unwrap().to_str().unwrap()),
            "{args:?}"
        );
        assert!(NativeProcessProbe.command_line(gone).await.is_err());
        #[cfg(target_os = "linux")]
        {
            let identity = NativeProcessProbe.process(me).await.unwrap();
            assert_eq!(identity.pid, me);
            assert_eq!(
                identity.executable,
                exe.canonicalize().unwrap().to_string_lossy()
            );
            assert_eq!(identity.process, exe.file_name().unwrap().to_string_lossy());
            assert_eq!(identity.started.len(), "2026-11-08 14:28:37".len());
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn command_lines_are_capped_at_1024_arguments_and_64_kib() {
        // `sh -c 'sleep 30' <name> <args…>` keeps the arguments on a live process.
        async fn probe(args: &[String]) -> Result<Vec<String>, StateError> {
            let mut child = std::process::Command::new("/bin/sh")
                .args(["-c", "sleep 30", "s"])
                .args(args)
                .spawn()
                .unwrap();
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
            let result = NativeProcessProbe.command_line(child.id()).await;
            child.kill().unwrap();
            child.wait().unwrap();
            result
        }
        // "/bin/sh" "-c" "sleep 30" "s" are four arguments and 18 bytes.
        assert_eq!(probe(&vec!["a".into(); 1020]).await.unwrap().len(), 1024);
        assert!(probe(&vec!["a".into(); 1021]).await.is_err());
        assert!(probe(&["b".repeat(65536 - 18)]).await.is_ok());
        assert!(probe(&["b".repeat(65537 - 18)]).await.is_err());
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn the_native_probe_finds_the_process_listening_on_a_port() {
        if std::process::Command::new("lsof")
            .arg("-v")
            .output()
            .is_err()
        {
            eprintln!("lsof is not installed; skipping");
            return;
        }
        let socket = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = socket.local_addr().unwrap().port();
        let found = NativeProcessProbe
            .listener(port, "127.0.0.1")
            .await
            .unwrap();
        assert_eq!(found.identity.pid, std::process::id());
        assert_eq!(found.port, port);
        drop(socket);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn the_native_probe_reads_command_output() {
        assert_eq!(output("echo", &["hello"]).await.unwrap().trim(), "hello");
    }
}