surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
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
//! NVIDIA SkillSpector (#30), the optional external scanner since 0.8.0:
//! a local second opinion on a skill before it is installed or updated,
//! or on a library skill on request. Off by default.
//!
//! It runs, in this order of preference ([`detect`]):
//!
//! 1. the pinned uvx form, `uvx --python 3.13 --from skillspector==2.13.7
//!    skillspector ...` (or `uv tool run ...` when only `uv` is on
//!    `PATH`), once [`prepare`] downloaded it into uv's cache; scans pass
//!    uv's `--offline`, so a scan never downloads anything. The uv is the
//!    user's own on `PATH`, else the private uv "Set up SkillSpector"
//!    ([`setup`]) put in Surjection's data folder ([`uv::PrivateUv`]);
//! 2. a `skillspector` the user installed on `PATH` (any version; one
//!    that is not [`VERSION`] gets a visible "not tested" note);
//! 3. a uv without the download yet: "needs Prepare".
//!
//! **What leaves the machine** ([`DISCLOSURE`]): only the names and
//! versions of the skill's dependencies, sent to OSV.dev when the skill
//! has a dependency manifest (SkillSpector 2.13.7 has no switch to turn
//! that off), and the one-time download of [`prepare`]. Skill content is
//! never uploaded.
//!
//! One scan ([`Runner::scan_files`]) stages exactly the content that will
//! be written, runs `skillspector scan --no-llm --format json
//! --fail-on-incomplete -- <staged folder>` with stdin closed, a scrubbed
//! environment ([`child_env`]: no provider keys, LangSmith tracing off)
//! and a timeout, kills the whole process tree on timeout or cancel, and
//! maps the JSON report into M40 findings ([`parse`]).

mod adapter;
#[cfg(test)]
mod tests;
pub mod uv;
pub mod uv_pin;

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::AtomicBool;
use std::time::Duration;

pub use adapter::{parse, version_of};
pub use uv::uv_download;

use super::download::Download;
use super::process::{self, Drained, Ended, MAX_STDOUT, RunDir, passed};
use super::{Choice, ExternalReport, NotScanned, Scanner, snyk_leftover, text};
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::local_settings::{LocalSettings, SkillSpectorSettings};
use crate::paths::SurjectionHome;
use crate::skills::{SkillFiles, content_hash};
use uv::PrivateUv;

/// The `scanner` of SkillSpector's findings and reports.
pub const SCANNER: Scanner = Scanner::SkillSpector;
/// The version this Surjection is tested with; the uvx form pins it.
pub const VERSION: &str = "2.13.7";
/// The uvx form's interpreter (yara-python has no wheels for 3.14+).
pub const PYTHON: &str = "3.13";
/// Seconds per scan unless `[skillspector] timeout_secs` says otherwise.
/// An ordinary skill with Python scripts and a dependency manifest took
/// 231 s on a first scan and 135 s after that (#42).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(600);
/// The longest a scan may run whatever `timeout_secs` says: a run folder
/// older than an hour is swept as abandoned, so a scan must end before.
pub const MAX_TIMEOUT: Duration = Duration::from_secs(59 * 60);
const _: () = assert!(
    MAX_TIMEOUT.as_secs() < process::STALE_RUN.as_secs()
        && PREPARE_TIMEOUT.as_secs() < process::STALE_RUN.as_secs()
);
/// How long [`prepare`] may take: the first run downloads a few hundred
/// MB (and maybe a Python build).
pub const PREPARE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
/// How long a `--version` probe may take (a first start compiles
/// Python's bytecode).
const PROBE_TIMEOUT: Duration = Duration::from_secs(60);
/// The most a probe's or Prepare's stdout is read.
const PROBE_STDOUT: usize = 64 * 1024;
/// The longest progress line passed on.
const MAX_PROGRESS_LINE: usize = 300;

/// A scan's arguments after the runtime's prefix; the staged folder
/// follows the `--`. Never `--output` (POSIX-only), `--transitive*`,
/// `--inspect-dependencies`, `--use-shipped-baseline`, `--baseline`,
/// `--mcp-registry*`, `--yara-rules-dir`, `--recursive`, a URL or an LLM
/// flag.
pub const SCAN_ARGS: &[&str] = &[
    "scan",
    "--no-llm",
    "--format",
    "json",
    "--fail-on-incomplete",
    "--",
];

/// Variables passed through to SkillSpector (and uv) when set (any case
/// on Windows): what Python and uv need to start, find uv's cache and
/// reach OSV.dev through a proxy. Never a provider key (`OPENAI_*`,
/// `ANTHROPIC_*`, `AWS_*`, `NVIDIA_*`, `GOOGLE_*`, `LANGSMITH_*`,
/// `LANGCHAIN_*`), never `SKILLSPECTOR_*`, nothing else; the temp folder
/// is the run's own ([`TEMP_VARS`]).
pub const PASSED_VARS: &[&str] = &[
    "PATH",
    "PATHEXT",
    "SYSTEMROOT",
    "SYSTEMDRIVE",
    "WINDIR",
    "COMSPEC",
    "PROGRAMDATA",
    "PROCESSOR_ARCHITECTURE",
    "HOME",
    "USERPROFILE",
    "USERNAME",
    "USER",
    "LOGNAME",
    "APPDATA",
    "LOCALAPPDATA",
    "XDG_CACHE_HOME",
    "XDG_DATA_HOME",
    "XDG_CONFIG_HOME",
    "LANG",
    "LC_ALL",
    "HTTPS_PROXY",
    "https_proxy",
    "HTTP_PROXY",
    "http_proxy",
    "ALL_PROXY",
    "all_proxy",
    "NO_PROXY",
    "no_proxy",
    "SSL_CERT_FILE",
    "SSL_CERT_DIR",
    "REQUESTS_CA_BUNDLE",
    "UV_CACHE_DIR",
    "UV_PYTHON_INSTALL_DIR",
    "UV_TOOL_DIR",
];

/// Temp-folder variables, always the run's own `tmp` folder (removed with
/// the run).
pub const TEMP_VARS: &[&str] = &["TEMP", "TMP", "TMPDIR"];

/// Always set: UTF-8 output, no colors, and LangSmith tracing off (the
/// scan runs as a LangGraph graph; a user's tracing setting must never
/// send it anywhere).
pub const SET_VARS: &[(&str, &str)] = &[
    ("PYTHONIOENCODING", "utf-8"),
    ("PYTHONUTF8", "1"),
    ("NO_COLOR", "1"),
    ("LANGSMITH_TRACING", "false"),
    ("LANGCHAIN_TRACING_V2", "false"),
];

/// The child's whole environment (after `env_clear`): [`PASSED_VARS`]
/// that are set, [`TEMP_VARS`] set to `tmp`, and [`SET_VARS`].
pub fn child_env(env: &Env, tmp: &Path) -> Vec<(String, OsString)> {
    let mut vars = passed(env, PASSED_VARS);
    for name in TEMP_VARS {
        vars.push(((*name).to_owned(), tmp.as_os_str().to_owned()));
    }
    for (name, value) in SET_VARS {
        vars.push(((*name).to_owned(), (*value).into()));
    }
    vars
}

/// Where the uv of the uvx form comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UvSource {
    /// The user's own, on `PATH`.
    System,
    /// The one "Set up SkillSpector" put in Surjection's data folder
    /// ([`uv::PrivateUv`]).
    Private,
}

impl UvSource {
    pub const fn as_str(self) -> &'static str {
        match self {
            UvSource::System => "system",
            UvSource::Private => "private",
        }
    }
}

/// The environment of a process `source`'s uv starts (or a `skillspector`
/// on `PATH`, `None`): [`child_env`], and for the private uv any `UV_*`
/// dropped and [`uv::PrivateUv::env`] added. A system uv gets nothing of
/// the private one's.
fn run_env(
    env: &Env,
    home: &SurjectionHome,
    tmp: &Path,
    source: Option<UvSource>,
) -> Vec<(String, OsString)> {
    let mut vars = child_env(env, tmp);
    if source == Some(UvSource::Private) {
        vars.retain(|(name, _)| !name.to_ascii_uppercase().starts_with("UV_"));
        vars.extend(uv::env_in(&uv::root(home)));
    }
    vars
}

/// SkillSpector's settings on this machine.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Settings {
    pub enabled: bool,
    /// Seconds per scan; 0 or unset is [`DEFAULT_TIMEOUT`], more than
    /// [`MAX_TIMEOUT`] is [`MAX_TIMEOUT`].
    pub timeout_secs: Option<u64>,
}

impl Settings {
    /// The effective scan timeout (see [`Settings::timeout_secs`]).
    pub fn timeout(&self) -> Duration {
        self.timeout_secs
            .filter(|secs| *secs > 0)
            .map_or(DEFAULT_TIMEOUT, Duration::from_secs)
            .min(MAX_TIMEOUT)
    }
}

pub fn settings(fs: &dyn Fs, home: &SurjectionHome) -> Result<Settings, CoreError> {
    let saved = LocalSettings::load(fs, &home.state_dir())?
        .skillspector
        .unwrap_or_default();
    Ok(Settings {
        enabled: saved.enabled == Some(true),
        timeout_secs: saved.timeout_secs,
    })
}

/// Turns SkillSpector on or off on this machine.
pub fn set_enabled(fs: &dyn Fs, home: &SurjectionHome, enabled: bool) -> Result<(), CoreError> {
    let state = home.state_dir();
    let mut settings = LocalSettings::load(fs, &state)?;
    let mut scanner = settings.skillspector.take().unwrap_or_default();
    scanner.enabled = Some(enabled);
    settings.skillspector = (scanner != SkillSpectorSettings::default()).then_some(scanner);
    settings.save(fs, &state)
}

/// Whether to run: [`Choice::On`], or [`Choice::Default`] with SkillSpector
/// turned on.
pub fn wanted(settings: &Settings, choice: Choice) -> bool {
    choice.wants(settings.enabled)
}

/// How SkillSpector is run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RuntimeKind {
    /// The pinned uvx form (`uvx`, or `uv tool run`).
    Uvx,
    /// A `skillspector` on `PATH`.
    Path,
}

impl RuntimeKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            RuntimeKind::Uvx => "uvx",
            RuntimeKind::Path => "path",
        }
    }
}

/// A SkillSpector that answers: ready to run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Runtime {
    pub kind: RuntimeKind,
    /// `uvx`, `uv` or `skillspector`, absolute.
    pub program: PathBuf,
    /// What it reported (the uvx form: [`VERSION`]).
    pub version: String,
    /// Where the uv comes from (the uvx form only).
    pub uv: Option<UvSource>,
}

impl Runtime {
    /// The version is the one this Surjection is tested with.
    pub fn tested(&self) -> bool {
        self.version == VERSION
    }

    /// "SkillSpector X is not tested with this Surjection (tested: 2.13.7)"
    /// for another version.
    pub fn note(&self) -> Option<String> {
        (!self.tested()).then(|| untested_note(&self.version))
    }

    /// Every argument of a scan of `skill` (the staged folder).
    pub fn argv(&self, skill: &Path) -> Vec<OsString> {
        let mut argv: Vec<OsString> = match self.kind {
            RuntimeKind::Uvx => uvx_prefix(&self.program, true)
                .into_iter()
                .map(OsString::from)
                .collect(),
            RuntimeKind::Path => Vec::new(),
        };
        argv.extend(SCAN_ARGS.iter().map(OsString::from));
        argv.push(skill.as_os_str().to_owned());
        argv
    }

    /// How it is started, for `scanner status`: `uvx --python 3.13 --from
    /// skillspector==2.13.7 skillspector` or the program's path.
    pub fn command_line(&self) -> String {
        let program = self.program.display().to_string();
        match self.kind {
            RuntimeKind::Uvx => {
                let prefix = uvx_prefix(&self.program, false).join(" ");
                format!("{program} {prefix}")
            }
            RuntimeKind::Path => program,
        }
    }
}

/// "SkillSpector X is not tested with this Surjection (tested: 2.13.7)".
pub fn untested_note(version: &str) -> String {
    format!("SkillSpector {version} is not tested with this Surjection (tested: {VERSION})")
}

/// The arguments before SkillSpector's own: `[tool run] [--offline]
/// --python 3.13 --from skillspector==2.13.7 skillspector`. `tool run`
/// when `program` is `uv` rather than `uvx`.
fn uvx_prefix(program: &Path, offline: bool) -> Vec<String> {
    let mut prefix = Vec::new();
    if is_uv(program) {
        prefix.extend(["tool".to_owned(), "run".to_owned()]);
    }
    if offline {
        prefix.push("--offline".to_owned());
    }
    prefix.extend([
        "--python".to_owned(),
        PYTHON.to_owned(),
        "--from".to_owned(),
        format!("skillspector=={VERSION}"),
        "skillspector".to_owned(),
    ]);
    prefix
}

/// `program` is `uv` (not `uvx`).
fn is_uv(program: &Path) -> bool {
    program
        .file_stem()
        .is_some_and(|stem| stem.eq_ignore_ascii_case("uv"))
}

/// Whether SkillSpector can run on this machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Availability {
    Ready(Runtime),
    /// A uv (`uvx`, or `uv` itself; the user's on `PATH`, else Surjection's
    /// private one) but the pinned SkillSpector is not in its cache:
    /// [`prepare`] downloads it.
    NeedsPrepare {
        uv: PathBuf,
        source: UvSource,
    },
    /// Neither a uv nor a usable `skillspector` ([`SETUP`]).
    NotAvailable,
}

impl Availability {
    pub const fn as_str(&self) -> &'static str {
        match self {
            Availability::Ready(_) => "ready",
            Availability::NeedsPrepare { .. } => "needs_prepare",
            Availability::NotAvailable => "not_available",
        }
    }

    pub fn runtime(&self) -> Option<&Runtime> {
        match self {
            Availability::Ready(runtime) => Some(runtime),
            _ => None,
        }
    }
}

/// The first `PATH` folder holding `name` (on Windows `name.exe`; batch
/// files and other `PATHEXT` kinds are not run). Relative entries are
/// skipped.
fn find_program(env: &Env, name: &str) -> Option<PathBuf> {
    let path = env.var("PATH")?.to_string_lossy().into_owned();
    let windows = env.os() == Os::Windows;
    let separator = if windows { ';' } else { ':' };
    let file = if windows {
        format!("{name}.exe")
    } else {
        name.to_owned()
    };
    path.split(separator)
        .map(|dir| Path::new(dir.trim().trim_matches('"')))
        .filter(|dir| dir.is_absolute())
        .map(|dir| dir.join(&file))
        .find(|candidate| candidate.is_file())
}

/// `uvx`, else `uv`, on `PATH`.
fn find_system_uv(env: &Env) -> Option<PathBuf> {
    find_program(env, "uvx").or_else(|| find_program(env, "uv"))
}

/// The private uv, when installed and verified (one that fails
/// [`PrivateUv::verify`] is treated as absent).
fn find_private_uv(env: &Env, home: &SurjectionHome) -> Option<PrivateUv> {
    PrivateUv::for_env(env, home)
        .ok()
        .filter(|private| private.installed() && private.verify().is_ok())
}

/// The uv [`prepare`] runs: `uvx`, else `uv`, on `PATH`; else the
/// installed and verified private `uvx`.
pub fn find_uv(env: &Env, home: &SurjectionHome) -> Option<(PathBuf, UvSource)> {
    if let Some(uv) = find_system_uv(env) {
        return Some((uv, UvSource::System));
    }
    find_private_uv(env, home).map(|private| (private.uvx(), UvSource::Private))
}

/// Runs `program args...` once, bounded, in a run folder of its own with
/// the scrubbed environment; its stdout when it exits 0.
fn probe(
    env: &Env,
    home: &SurjectionHome,
    program: &Path,
    source: Option<UvSource>,
    args: &[String],
    timeout: Duration,
) -> Result<String, String> {
    let run = process::stage(home, &SkillFiles::new())?;
    let mut command = Command::new(program);
    command
        .args(args)
        .current_dir(&run.dir)
        .env_clear()
        .envs(run_env(env, home, &run.tmp, source));
    let executed = process::execute(command, timeout, None, PROBE_STDOUT, None)?;
    match executed.ended {
        Ended::Exited(Some(0)) => Ok(executed
            .stdout
            .map(|drained| String::from_utf8_lossy(&drained.kept).into_owned())
            .unwrap_or_default()),
        Ended::Exited(code) => Err(format!(
            "exit code {}: {}",
            code.map_or_else(|| "none".to_owned(), |code| code.to_string()),
            executed.last_stderr_line().unwrap_or_default()
        )),
        Ended::TimedOut => Err(format!("no answer in {} seconds", timeout.as_secs())),
        Ended::Canceled => Err("canceled".to_owned()),
        Ended::Failed(why) => Err(why),
    }
}

/// A `skillspector` on `PATH` that answers `--version` with a version.
fn path_runtime(env: &Env, home: &SurjectionHome) -> Option<Runtime> {
    let program = find_program(env, "skillspector")?;
    let stdout = probe(
        env,
        home,
        &program,
        None,
        &["--version".to_owned()],
        PROBE_TIMEOUT,
    )
    .ok()?;
    let version = version_of(&stdout)?;
    Some(Runtime {
        kind: RuntimeKind::Path,
        program,
        version,
        uv: None,
    })
}

/// The uvx form through `uv`, when its `--offline` probe answers.
fn uvx_runtime(env: &Env, home: &SurjectionHome, uv: &Path, source: UvSource) -> Option<Runtime> {
    let mut args = uvx_prefix(uv, true);
    args.push("--version".to_owned());
    let stdout = probe(env, home, uv, Some(source), &args, PROBE_TIMEOUT).ok()?;
    Some(Runtime {
        kind: RuntimeKind::Uvx,
        program: uv.to_owned(),
        version: version_of(&stdout).unwrap_or_else(|| VERSION.to_owned()),
        uv: Some(source),
    })
}

/// Which SkillSpector runs here ([`Availability`]). What the user installed
/// always wins: the uvx form through a uv on `PATH` when it is ready, then
/// a `skillspector` on `PATH`, then the uvx form through the private uv
/// when it is ready; else "needs Prepare" (the uv on `PATH`, else the
/// private one) or not available. No network: the uvx probes run with
/// `--offline`. Starts up to three `--version` probes.
pub fn detect(env: &Env, home: &SurjectionHome) -> Availability {
    let system = find_system_uv(env);
    if let Some(uv) = &system
        && let Some(runtime) = uvx_runtime(env, home, uv, UvSource::System)
    {
        return Availability::Ready(runtime);
    }
    if let Some(runtime) = path_runtime(env, home) {
        return Availability::Ready(runtime);
    }
    let private = find_private_uv(env, home);
    if let Some(private) = &private
        && let Some(runtime) = uvx_runtime(env, home, &private.uvx(), UvSource::Private)
    {
        return Availability::Ready(runtime);
    }
    match (system, private) {
        (Some(uv), _) => Availability::NeedsPrepare {
            uv,
            source: UvSource::System,
        },
        (None, Some(private)) => Availability::NeedsPrepare {
            uv: private.uvx(),
            source: UvSource::Private,
        },
        (None, None) => Availability::NotAvailable,
    }
}

/// What `scanner status` and Settings show.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
    pub availability: Availability,
    pub enabled: bool,
    pub timeout: Duration,
    /// A 0.7.0 Snyk Agent Scan install or its settings remain (`surjection
    /// scanner remove` deletes them).
    pub snyk_installed: bool,
    /// The version of the private uv [`setup`] installed, when it is
    /// installed ([`remove_private_uv`] deletes it).
    pub private_uv: Option<String>,
    /// `tools/uv/` exists, installed or not (a leftover of a failed or
    /// tampered install, or uv's cache): [`remove_private_uv`] deletes it.
    pub private_uv_present: bool,
    /// [`setup`] can install a private uv on this platform.
    pub setup_supported: bool,
}

pub fn status(env: &Env, fs: &dyn Fs, home: &SurjectionHome) -> Result<Status, CoreError> {
    let settings = settings(fs, home)?;
    let snyk_installed = snyk_leftover::present(fs, home)?;
    let availability = detect(env, home);
    let private = PrivateUv::for_env(env, home).ok();
    Ok(Status {
        availability,
        enabled: settings.enabled,
        timeout: settings.timeout(),
        snyk_installed,
        private_uv: private
            .as_ref()
            .filter(|private| private.installed())
            .map(|private| private.version().to_owned()),
        private_uv_present: uv::root(home).exists(),
        setup_supported: private.is_some(),
    })
}

/// Whether an install or update must carry an external report: SkillSpector
/// is on and ready (a not-scanned report still counts as a report).
pub fn required(env: &Env, fs: &dyn Fs, home: &SurjectionHome) -> Result<bool, CoreError> {
    if !settings(fs, home)?.enabled {
        return Ok(false);
    }
    Ok(matches!(detect(env, home), Availability::Ready(_)))
}

/// Downloads the pinned SkillSpector into uv's cache: runs `uvx --python
/// 3.13 --from skillspector==2.13.7 skillspector --version` once (PyPI,
/// and a Python 3.13 build when uv has none), at most [`PREPARE_TIMEOUT`],
/// with the uv [`find_uv`] finds (never downloads uv itself).
/// `progress` gets each line uv prints (one line, control characters
/// removed). `scanner_unavailable` without a uv;
/// `scanner_download_failed` when uv fails or takes too long; `canceled`
/// once `cancel` is set (the process tree is killed).
pub fn prepare(
    env: &Env,
    home: &SurjectionHome,
    progress: &mut dyn FnMut(&str),
    cancel: Option<&AtomicBool>,
) -> Result<Runtime, CoreError> {
    let Some((uv, source)) = find_uv(env, home) else {
        return Err(CoreError::new(
            ErrorCode::ScannerUnavailable,
            format!(
                "uv is not on PATH, so there is nothing to prepare. {}",
                setup_text(setup_supported(env, home))
            ),
        ));
    };
    prepare_with(env, home, uv, source, progress, cancel)
}

/// [`prepare`] with `uv` from `source`.
fn prepare_with(
    env: &Env,
    home: &SurjectionHome,
    uv: PathBuf,
    source: UvSource,
    progress: &mut dyn FnMut(&str),
    cancel: Option<&AtomicBool>,
) -> Result<Runtime, CoreError> {
    let failed = |why: String| CoreError::new(ErrorCode::ScannerDownloadFailed, why);
    let run = process::stage(home, &SkillFiles::new())
        .map_err(|why| failed(format!("cannot prepare SkillSpector: {why}")))?;
    let mut args = uvx_prefix(&uv, false);
    args.push("--version".to_owned());
    let mut command = Command::new(&uv);
    command
        .args(&args)
        .current_dir(&run.dir)
        .env_clear()
        .envs(run_env(env, home, &run.tmp, Some(source)));
    let mut on_line = |line: &str| {
        let line = text::clean(line, MAX_PROGRESS_LINE);
        if !line.is_empty() {
            progress(&line);
        }
    };
    let executed = process::execute(
        command,
        PREPARE_TIMEOUT,
        cancel,
        PROBE_STDOUT,
        Some(&mut on_line),
    )
    .map_err(failed)?;
    match executed.ended {
        Ended::Exited(Some(0)) => {
            let stdout = executed
                .stdout
                .map(|drained| String::from_utf8_lossy(&drained.kept).into_owned())
                .unwrap_or_default();
            Ok(Runtime {
                kind: RuntimeKind::Uvx,
                program: uv,
                version: version_of(&stdout).unwrap_or_else(|| VERSION.to_owned()),
                uv: Some(source),
            })
        }
        Ended::Exited(code) => {
            let how = code.map_or_else(
                || "uv was stopped by the system".to_owned(),
                |code| format!("uv exited with code {code}"),
            );
            let detail = executed
                .last_stderr_line()
                .map(|line| format!(": {}", text::clean(&line, MAX_PROGRESS_LINE)))
                .unwrap_or_default();
            Err(failed(format!(
                "uv could not download SkillSpector {VERSION} ({how}){detail}"
            )))
        }
        Ended::TimedOut => Err(failed(format!(
            "preparing SkillSpector did not finish in {} minutes",
            PREPARE_TIMEOUT.as_secs() / 60
        ))),
        Ended::Canceled => Err(CoreError::new(
            ErrorCode::Canceled,
            "preparing SkillSpector was canceled",
        )),
        Ended::Failed(why) => Err(failed(why)),
    }
}

/// One step of [`setup`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetupStep<'a> {
    /// The private uv is downloading (`total` its pinned size when the
    /// server sends none).
    Download { received: u64, total: u64 },
    /// A line uv printed while preparing (as [`prepare`]'s).
    Prepare { line: &'a str },
}

/// "Set up SkillSpector". No uv on `PATH`: installs the private uv
/// ([`PrivateUv::install`], [`SetupStep::Download`] steps), then prepares
/// with it ([`SetupStep::Prepare`] steps). uv on `PATH`: prepares with it
/// only (never downloads uv). No uv on `PATH` but a ready `skillspector`
/// there (which [`detect`] prefers to the private uv):
/// `scanner_unavailable` ("already set up"). No pin for this platform:
/// `not_supported_on_os`. Does not turn SkillSpector on. The ready
/// runtime.
pub fn setup(
    env: &Env,
    home: &SurjectionHome,
    download: &dyn Download,
    progress: &mut dyn FnMut(SetupStep<'_>),
    cancel: Option<&AtomicBool>,
) -> Result<Runtime, CoreError> {
    if let Some(uv) = find_system_uv(env) {
        return prepare_with(
            env,
            home,
            uv,
            UvSource::System,
            &mut |line| progress(SetupStep::Prepare { line }),
            cancel,
        );
    }
    if path_runtime(env, home).is_some() {
        return Err(CoreError::new(
            ErrorCode::ScannerUnavailable,
            "SkillSpector is already set up (on PATH)",
        ));
    }
    let private = PrivateUv::for_env(env, home)?;
    private.install(
        download,
        &mut |received, total| progress(SetupStep::Download { received, total }),
        cancel,
    )?;
    prepare_with(
        env,
        home,
        private.uvx(),
        UvSource::Private,
        &mut |line| progress(SetupStep::Prepare { line }),
        cancel,
    )
}

/// Deletes the private uv with everything it wrote (`tools/uv`: uv, its
/// cache with SkillSpector's environment, its Python); `false` when there
/// was nothing. The SkillSpector switch is left as is.
pub fn remove_private_uv(home: &SurjectionHome) -> Result<bool, CoreError> {
    uv::remove_root(&uv::root(home))
}

/// A ready run, or the `not_scanned` report every skill of the command
/// gets: `not_available` (nothing on `PATH`) or `not_prepared` (uv without
/// the download).
// The `Err` is the report every skill of the command gets, built once per
// command, not an error on a hot path.
#[allow(clippy::result_large_err)]
pub fn prepare_run(
    env: &Env,
    fs: &dyn Fs,
    home: &SurjectionHome,
) -> Result<Runner, ExternalReport> {
    let timeout = settings(fs, home)
        .map_err(|err| {
            ExternalReport::not_scanned(
                SCANNER,
                VERSION,
                NotScanned::Failed,
                Some(err.message().to_owned()),
            )
        })?
        .timeout();
    match detect(env, home) {
        Availability::Ready(runtime) => Ok(Runner::new(runtime, timeout)),
        Availability::NeedsPrepare { source, .. } => Err(ExternalReport::not_scanned(
            SCANNER,
            VERSION,
            NotScanned::NotPrepared,
            Some(match source {
                UvSource::System => format!(
                    "uv is on PATH but SkillSpector {VERSION} is not downloaded yet; prepare \
                     it first (`surject scanner prepare`, or Prepare in Settings > Security)"
                ),
                UvSource::Private => format!(
                    "SkillSpector {VERSION} is not downloaded yet; set it up first (`surject \
                     scanner setup`, or Set up in Settings > Security)"
                ),
            }),
        )),
        Availability::NotAvailable => Err(ExternalReport::not_scanned(
            SCANNER,
            VERSION,
            NotScanned::NotAvailable,
            Some("neither uv nor skillspector is on PATH".to_owned()),
        )),
    }
}

/// A SkillSpector that answered: ready to scan.
#[derive(Debug, Clone)]
pub struct Runner {
    runtime: Runtime,
    timeout: Duration,
}

impl Runner {
    pub fn new(runtime: Runtime, timeout: Duration) -> Self {
        Self { runtime, timeout }
    }

    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

    /// How long one scan may run.
    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    /// Scans `files` (a skill, by relative `/`-separated path): one run,
    /// at most the timeout. Never an error: what went wrong is the
    /// report's `not_scanned` reason.
    pub fn scan_files(
        &self,
        env: &Env,
        home: &SurjectionHome,
        files: &SkillFiles,
        cancel: Option<&AtomicBool>,
    ) -> ExternalReport {
        let started = std::time::Instant::now();
        let hash = content_hash(files);
        let mut report = match process::stage(home, files) {
            // The run folder goes when `run` drops.
            Ok(run) => self.run(env, home, &run, cancel),
            Err(why) => ExternalReport::not_scanned(
                SCANNER,
                &self.runtime.version,
                NotScanned::Failed,
                Some(format!(
                    "the skill could not be prepared for the scanner: {why}"
                )),
            ),
        };
        report.content_hash = Some(hash);
        crate::diagnostics::log::event(
            "scanner.run",
            &[
                ("scanner", &SCANNER.as_str()),
                ("runtime", &self.runtime.kind.as_str()),
                ("status", &report.status.as_str()),
                ("findings", &report.findings.len()),
                ("duration_ms", &started.elapsed().as_millis()),
            ],
        );
        report
    }

    fn run(
        &self,
        env: &Env,
        home: &SurjectionHome,
        run: &RunDir,
        cancel: Option<&AtomicBool>,
    ) -> ExternalReport {
        let version = self.runtime.version.as_str();
        let not_scanned = |reason, detail: Option<String>| {
            ExternalReport::not_scanned(SCANNER, version, reason, detail)
        };
        let mut command = Command::new(&self.runtime.program);
        command
            .args(self.runtime.argv(&run.skill))
            .current_dir(&run.dir)
            .env_clear()
            .envs(run_env(env, home, &run.tmp, self.runtime.uv));
        let executed = match process::execute(command, self.timeout, cancel, MAX_STDOUT, None) {
            Ok(executed) => executed,
            Err(why) => return not_scanned(NotScanned::Failed, Some(why)),
        };
        match executed.ended {
            Ended::Exited(code) => match executed.stdout {
                Some(Drained { overflow: true, .. }) if matches!(code, Some(0 | 1)) => {
                    ExternalReport::not_understood(
                        SCANNER,
                        version,
                        "the output is larger than 16 MiB",
                    )
                }
                Some(Drained { kept, .. }) => {
                    parse(&kept, &executed.stderr, code, &run.skill, version)
                }
                None => not_scanned(
                    NotScanned::Failed,
                    Some("the scanner's output did not end after it exited".to_owned()),
                ),
            },
            Ended::TimedOut => not_scanned(
                NotScanned::Timeout,
                Some(format!(
                    "SkillSpector did not finish in {} seconds",
                    self.timeout.as_secs()
                )),
            ),
            Ended::Canceled => not_scanned(NotScanned::Canceled, None),
            Ended::Failed(why) => not_scanned(NotScanned::Failed, Some(why)),
        }
    }
}

/// What leaves the machine, verbatim as `docs/security.md` lists it; the
/// CLI prints it when SkillSpector is turned on and in `scanner status`.
pub const DISCLOSURE: &str = "SkillSpector runs on this computer and never uploads the skill. \
Nothing leaves this machine except the names and versions of the skill's dependencies, sent to \
OSV.dev (api.osv.dev) to look up known vulnerabilities, when the skill has a dependency manifest \
(requirements.txt, package.json, pyproject.toml or Pipfile). Preparing the uvx form once \
downloads SkillSpector 2.13.7 and its dependencies (a few hundred MB) from PyPI, and a Python \
3.13 build when uv has none; scans themselves never download anything. Set up (when uv is \
missing) also downloads uv 0.13.10 (about 16 MB) from GitHub once, checked against SHA-256 values \
built into Surjection, and keeps it, its cache and the Python it downloads inside Surjection's data \
folder; Remove deletes them. No account, no token, no upload of skill content. Surjection runs it \
only on skills, never on MCP servers (SkillSpector does not read MCP client configs), and only \
when you turn it on (or pass --external).";

/// The manual routes of [`SETUP`] (a macro, so `SETUP` stays a `const`).
macro_rules! manual_setup {
    () => {
        "install uv (https://docs.astral.sh/uv/getting-started/installation/) and run `surject \
         scanner prepare` (or Prepare in Settings > Security), or install SkillSpector with \
         `pipx install skillspector==2.13.7 --python 3.13`. It needs Python 3.12 or 3.13: Python \
         3.14 and later don't work yet (yara-python has no wheels for them)."
    };
}

/// How to get SkillSpector when nothing is found.
pub const SETUP: &str = concat!(
    "Choose Set up in Settings > Security, or run `surject scanner setup`: when uv is missing, \
     Surjection downloads its own copy into its data folder (Remove deletes it). Or set it up \
     yourself: ",
    manual_setup!()
);

/// [`SETUP`] where [`setup`] is `supported`; else only its manual routes
/// ("Set it up yourself: ...").
pub fn setup_text(supported: bool) -> String {
    if supported {
        SETUP.to_owned()
    } else {
        concat!("Set it up yourself: ", manual_setup!()).to_owned()
    }
}

/// [`setup`] can install a private uv here ([`Status::setup_supported`]):
/// there is a pin for this platform (in debug builds, the test archive's).
pub fn setup_supported(env: &Env, home: &SurjectionHome) -> bool {
    PrivateUv::for_env(env, home).is_ok()
}