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
//! `SURJECTION_HOME` resolution, data layout and sync-root detection (SPEC 4.5).

use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf, Prefix};

use crate::brand;
use crate::env::{Env, KnownFolder, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;

/// The machine-local state directory inside `SURJECTION_HOME`.
pub const STATE_DIR: &str = "state";

/// Where the resolved `SURJECTION_HOME` came from, highest precedence first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HomeSource {
    /// The `--home` command-line flag.
    Flag,
    /// The `SURJECTION_HOME` environment variable.
    EnvVar,
    /// The per-OS default.
    Default,
}

impl HomeSource {
    pub const fn as_str(self) -> &'static str {
        match self {
            HomeSource::Flag => "flag",
            HomeSource::EnvVar => "env",
            HomeSource::Default => "default",
        }
    }
}

/// File-sync tool owning a folder. Live git repos and lock files must not
/// live inside one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncRootKind {
    Resilio,
    Syncthing,
    OneDrive,
    Dropbox,
    GoogleDrive,
}

impl SyncRootKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            SyncRootKind::Resilio => "resilio",
            SyncRootKind::Syncthing => "syncthing",
            SyncRootKind::OneDrive => "onedrive",
            SyncRootKind::Dropbox => "dropbox",
            SyncRootKind::GoogleDrive => "google_drive",
        }
    }
}

/// A sync folder containing a path. Reported by `surject doctor` as
/// `sync_root_detected`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncRoot {
    pub kind: SyncRootKind,
    /// Top folder managed by the sync tool.
    pub root: PathBuf,
}

/// The resolved data directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SurjectionHome {
    /// Absolute and lexically normalized.
    pub path: PathBuf,
    pub source: HomeSource,
    /// Set when `path` lies inside a file-sync folder.
    pub sync_root: Option<SyncRoot>,
}

impl SurjectionHome {
    /// Versioned desired state (git repo).
    pub fn store_dir(&self) -> PathBuf {
        self.path.join("store")
    }

    /// Machine-local, unversioned state.
    pub fn state_dir(&self) -> PathBuf {
        self.path.join(STATE_DIR)
    }

    /// Pre-write copies of client files and trash; never pushed.
    pub fn backups_dir(&self) -> PathBuf {
        self.path.join("backups")
    }

    /// Re-creatable caches.
    pub fn cache_dir(&self) -> PathBuf {
        self.path.join("cache")
    }

    /// Migration inputs.
    pub fn imports_dir(&self) -> PathBuf {
        self.path.join("imports")
    }

    pub fn logs_dir(&self) -> PathBuf {
        self.path.join("logs")
    }
}

/// Resolves `SURJECTION_HOME`: `flag` (the CLI `--home`), else the
/// `SURJECTION_HOME` variable, else the former `LOADOUT_HOME` variable,
/// else the per-OS default. Overrides must be absolute. The result is
/// checked for an enclosing sync folder.
pub fn surjection_home(
    env: &Env,
    fs: &dyn Fs,
    flag: Option<&Path>,
) -> Result<SurjectionHome, CoreError> {
    let (path, source, name) = match (flag, home_var(env)) {
        (Some(flag), _) => (flag.to_path_buf(), HomeSource::Flag, brand::HOME_ENV_VAR),
        (None, Some((name, var))) => (PathBuf::from(var), HomeSource::EnvVar, name),
        (None, None) => (
            default_or_legacy(env, fs),
            HomeSource::Default,
            brand::HOME_ENV_VAR,
        ),
    };
    if !path.is_absolute() {
        return Err(CoreError::new(
            ErrorCode::InvalidPath,
            format!("{name} must be an absolute path"),
        )
        .with_path(path));
    }
    let path = normalize(&path);
    let sync_root = detect_sync_root(env, fs, &path);
    Ok(SurjectionHome {
        path,
        source,
        sync_root,
    })
}

/// The data folder variable in effect and its value: `SURJECTION_HOME`, or
/// `LOADOUT_HOME` (Loadout 1.0.x) when the former is unset.
pub fn home_var(env: &Env) -> Option<(&'static str, &std::ffi::OsStr)> {
    env.var(brand::HOME_ENV_VAR)
        .map(|value| (brand::HOME_ENV_VAR, value))
        .or_else(|| {
            env.var(brand::legacy::HOME_ENV_VAR)
                .map(|value| (brand::legacy::HOME_ENV_VAR, value))
        })
}

/// The per-OS default data directory of Loadout 1.0.x (what
/// `surject migrate loadout` moves).
pub fn legacy_default_home(env: &Env) -> PathBuf {
    let current = default_surjection_home(env);
    let name = match env.os() {
        Os::Windows => brand::legacy::DATA_DIR_WINDOWS,
        Os::Linux => brand::legacy::DATA_DIR_LINUX,
        Os::MacOs => brand::legacy::DATA_DIR_MACOS,
    };
    current.with_file_name(name)
}

/// The per-OS default data directory. Never reads `HOME` on Windows: the
/// profile comes from [`Env::home`] and the base from `FOLDERID_LocalAppData`.
pub fn default_surjection_home(env: &Env) -> PathBuf {
    match env.os() {
        Os::Windows => env
            .known_folder(KnownFolder::LocalAppData)
            .map(Path::to_path_buf)
            .unwrap_or_else(|| env.home().join("AppData").join("Local"))
            .join(brand::DATA_DIR_WINDOWS),
        Os::Linux => env
            .var("XDG_DATA_HOME")
            .map(PathBuf::from)
            // The XDG spec says relative values are invalid and ignored.
            .filter(|path| path.is_absolute())
            .unwrap_or_else(|| env.home().join(".local").join("share"))
            .join(brand::DATA_DIR_LINUX),
        Os::MacOs => env
            .home()
            .join("Library")
            .join("Application Support")
            .join(brand::DATA_DIR_MACOS),
    }
}

/// Finds a file-sync folder containing `path`.
///
/// Walks the ancestors of `path` (stopping at [`Fs::root`]) for a Resilio
/// `.sync` folder holding `ID` or `IgnoreList`, or a Syncthing `.stfolder`.
/// Then compares against provider roots: OneDrive (`OneDrive`,
/// `OneDriveConsumer`, `OneDriveCommercial` variables), Dropbox
/// (`info.json`), Google Drive (`~/My Drive`, `~/Google Drive`, a
/// `<drive>:\My Drive` stream mount) and macOS `~/Library/CloudStorage`.
pub fn detect_sync_root(env: &Env, fs: &dyn Fs, path: &Path) -> Option<SyncRoot> {
    let path = normalize(path);
    marker_root(env.os(), fs, &path).or_else(|| provider_root(env, fs, &path))
}

fn marker_root(os: Os, fs: &dyn Fs, path: &Path) -> Option<SyncRoot> {
    let ceiling = fs.root().map(normalize);
    for dir in path.ancestors() {
        if ceiling
            .as_deref()
            .is_some_and(|ceiling| !is_within(os, dir, ceiling))
        {
            break;
        }
        let resilio = dir.join(".sync");
        if fs.is_dir(&resilio)
            && (fs.exists(&resilio.join("ID")) || fs.exists(&resilio.join("IgnoreList")))
        {
            return Some(sync_root(SyncRootKind::Resilio, dir));
        }
        if fs.exists(&dir.join(".stfolder")) {
            return Some(sync_root(SyncRootKind::Syncthing, dir));
        }
    }
    None
}

fn provider_root(env: &Env, fs: &dyn Fs, path: &Path) -> Option<SyncRoot> {
    let os = env.os();
    let home = env.home();

    let onedrive = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]
        .into_iter()
        .filter_map(|name| env.var(name))
        .map(|root| (SyncRootKind::OneDrive, PathBuf::from(root)));
    let dropbox = dropbox_info_files(env)
        .into_iter()
        .filter(|info| fs.exists(info))
        .filter_map(|info| fs.read_to_string(&info).ok())
        .flat_map(|text| dropbox_roots(&text))
        .map(|root| (SyncRootKind::Dropbox, root));
    let google = ["My Drive", "Google Drive"]
        .into_iter()
        .map(|name| (SyncRootKind::GoogleDrive, home.join(name)));

    onedrive
        .chain(dropbox)
        .chain(google)
        .filter(|(_, root)| root.is_absolute())
        .map(|(kind, root)| sync_root(kind, &root))
        .find(|candidate| is_within(os, path, &candidate.root))
        .or_else(|| cloud_storage_root(env, path))
        .or_else(|| google_drive_mount(path))
}

fn dropbox_info_files(env: &Env) -> Vec<PathBuf> {
    match env.os() {
        Os::Windows => [KnownFolder::LocalAppData, KnownFolder::RoamingAppData]
            .into_iter()
            .filter_map(|folder| env.known_folder(folder))
            .map(|base| base.join("Dropbox").join("info.json"))
            .collect(),
        Os::Linux | Os::MacOs => vec![env.home().join(".dropbox").join("info.json")],
    }
}

/// Account roots from Dropbox's `info.json` (`{"personal": {"path": ...}, ...}`).
fn dropbox_roots(text: &str) -> Vec<PathBuf> {
    let Ok(serde_json::Value::Object(accounts)) = serde_json::from_str(text) else {
        return Vec::new();
    };
    accounts
        .values()
        .filter_map(|account| account.get("path")?.as_str())
        .map(PathBuf::from)
        .collect()
}

/// macOS File Provider roots: `~/Library/CloudStorage/<Provider>-<account>`.
fn cloud_storage_root(env: &Env, path: &Path) -> Option<SyncRoot> {
    if env.os() != Os::MacOs {
        return None;
    }
    let base = normalize(&env.home().join("Library").join("CloudStorage"));
    let rest = path.strip_prefix(&base).ok()?;
    let Some(Component::Normal(entry)) = rest.components().next() else {
        return None;
    };
    let name = entry.to_string_lossy();
    let kind = [
        ("OneDrive", SyncRootKind::OneDrive),
        ("Dropbox", SyncRootKind::Dropbox),
        ("GoogleDrive", SyncRootKind::GoogleDrive),
    ]
    .into_iter()
    .find_map(|(prefix, kind)| name.starts_with(prefix).then_some(kind))?;
    Some(sync_root(kind, &base.join(entry)))
}

/// Google Drive for desktop in streaming mode mounts `<drive>:\My Drive`.
fn google_drive_mount(path: &Path) -> Option<SyncRoot> {
    path.ancestors()
        .find(|dir| {
            dir.file_name() == Some(OsStr::new("My Drive"))
                && dir.parent().is_some_and(|parent| parent.parent().is_none())
        })
        .map(|dir| sync_root(SyncRootKind::GoogleDrive, dir))
}

fn sync_root(kind: SyncRootKind, root: &Path) -> SyncRoot {
    SyncRoot {
        kind,
        root: normalize(root),
    }
}

/// Lexically normalizes a path: drops `.` and resolves `..` against earlier
/// components without touching the file system. `..` above a root is dropped.
pub fn normalize(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => match out.components().next_back() {
                Some(Component::Normal(_)) => {
                    out.pop();
                }
                Some(Component::RootDir) => {}
                _ => out.push(".."),
            },
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// The `\\?\` (extended-length) form of an absolute Windows path, which
/// file system calls accept past `MAX_PATH` (SPEC 16.1): `C:\x` is
/// `\\?\C:\x`, `\\server\share\x` is `\\?\UNC\server\share\x`. The path is
/// normalized first, since the OS takes a `\\?\` path literally (no `/`,
/// `.` or `..` handling). Any other path, and every path off Windows, is
/// returned as it is.
pub fn extended(path: &Path) -> Cow<'_, Path> {
    if !path.is_absolute() {
        return Cow::Borrowed(path);
    }
    let normal = normalize(path);
    let mut components = normal.components();
    let Some(Component::Prefix(prefix)) = components.next() else {
        return Cow::Borrowed(path);
    };
    let mut out = match prefix.kind() {
        Prefix::Disk(letter) => OsString::from(format!(r"\\?\{}:", char::from(letter))),
        Prefix::UNC(server, share) => {
            let mut out = OsString::from(r"\\?\UNC\");
            out.push(server);
            out.push(r"\");
            out.push(share);
            out
        }
        _ => return Cow::Borrowed(path),
    };
    let mut named = false;
    for component in components {
        if let Component::Normal(name) = component {
            out.push(r"\");
            out.push(name);
            named = true;
        }
    }
    if !named {
        out.push(r"\");
    }
    Cow::Owned(PathBuf::from(out))
}

/// `path` without a `\\?\` prefix ([`extended`] undone): `\\?\C:\x` is
/// `C:\x`, `\\?\UNC\server\share\x` is `\\server\share\x`. Any other path,
/// and every path off Windows, is returned as it is.
pub fn plain(path: &Path) -> Cow<'_, Path> {
    let mut components = path.components();
    let Some(Component::Prefix(prefix)) = components.next() else {
        return Cow::Borrowed(path);
    };
    let head = match prefix.kind() {
        Prefix::VerbatimDisk(letter) => OsString::from(format!("{}:", char::from(letter))),
        Prefix::VerbatimUNC(server, share) => {
            let mut head = OsString::from(r"\\");
            head.push(server);
            head.push(r"\");
            head.push(share);
            head
        }
        _ => return Cow::Borrowed(path),
    };
    let mut out = PathBuf::from(head);
    out.extend(components);
    Cow::Owned(out)
}

/// Whether `path` equals `base` or lies below it, comparing components
/// case-insensitively on Windows and treating `\\?\C:` like `C:`.
fn is_within(os: Os, path: &Path, base: &Path) -> bool {
    let mut path = path.components();
    base.components().all(|expected| {
        path.next()
            .is_some_and(|actual| same_component(os, actual, expected))
    })
}

fn same_component(os: Os, a: Component<'_>, b: Component<'_>) -> bool {
    match os {
        Os::Windows => component_key(a).to_lowercase() == component_key(b).to_lowercase(),
        Os::Linux | Os::MacOs => a == b,
    }
}

fn component_key(component: Component<'_>) -> Cow<'_, str> {
    if let Component::Prefix(prefix) = component {
        match prefix.kind() {
            Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
                return Cow::Owned(format!("{}:", char::from(letter)));
            }
            Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
                return Cow::Owned(format!(
                    r"\\{}\{}",
                    server.to_string_lossy(),
                    share.to_string_lossy()
                ));
            }
            Prefix::Verbatim(_) | Prefix::DeviceNS(_) => {}
        }
    }
    component.as_os_str().to_string_lossy()
}

/// The per-OS default data directory, or Loadout 1.0.x's default one while
/// only that exists (before `surject migrate loadout` moved it, or when the
/// move could not run yet), so nothing starts over in an empty folder.
fn default_or_legacy(env: &Env, fs: &dyn Fs) -> PathBuf {
    let current = default_surjection_home(env);
    if fs.exists(&current) {
        return current;
    }
    let legacy = legacy_default_home(env);
    if fs.is_dir(&legacy) { legacy } else { current }
}