symforge 8.22.2

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! EDR-safe version-drift detection for the SymForge binary.
//!
//! SymForge may be launched from more than one location that can drift apart in
//! version: the per-OS npm global install (refreshed by `npm install -g`), a
//! local dev `target/` build, or any other on-disk copy an MCP client points
//! at. If a client is wired to an older path while a newer install exists
//! elsewhere, that client silently serves stale code.
//!
//! NOTE: there is no longer any *durable* SymForge binary under `~/.symforge/bin`.
//! That promotion mechanism was retired — `symforge init` registers MCP clients
//! against the running native binary's own path AS-IS (the npm global install
//! for that OS; see `cli::init::binary_path_for_registration`), and nothing in
//! current code copies, promotes, or writes a binary into `~/.symforge/bin`.
//! Drift detection therefore compares only the paths that binaries have actually
//! recorded in `versions.json`; a leftover `~/.symforge/bin` entry from an old
//! install is harmless because [`detect_stale`] skips any registered path that
//! no longer exists on disk.
//!
//! This module detects drift **without ever copying, executing, or downloading
//! anything** — the one and only side effect is reading and (rarely) atomically
//! rewriting a small plain-text JSON file. That keeps it clear of antivirus /
//! EDR heuristics that flag a running process which drops or overwrites
//! executables. Any refresh is left to a user-run command surfaced in the
//! warning; the daemon never replaces its own binary.
//!
//! Mechanism: every binary, on launch, records its own canonical path and
//! version into `<home>/versions.json`. The daemon reads that registry and, if
//! a strictly newer version is registered at a *different, still-existing*
//! path, warns that it is serving stale code.

use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};

use crate::domain::ControlStateDir;

/// File name of the version registry within the SymForge home directory.
const REGISTRY_FILE: &str = "versions.json";

/// Compile-time version of the running binary.
pub fn self_version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// Return the process-wide resolved control-state owner used by the registry.
pub fn resolve_home() -> Option<ControlStateDir> {
    crate::paths::process_control_state_placement()
        .directory()
        .cloned()
}

fn registry_path(control_state_dir: &ControlStateDir) -> PathBuf {
    crate::paths::control_state_path(control_state_dir, REGISTRY_FILE)
}

/// Canonical path of the currently running executable, best-effort.
fn current_exe_key() -> Option<String> {
    let exe = std::env::current_exe().ok()?;
    let exe = std::fs::canonicalize(&exe).unwrap_or(exe);
    Some(exe.to_string_lossy().into_owned())
}

/// Load the registry as a `path -> version` map. Missing or malformed files
/// yield an empty map — the registry is advisory, never load-bearing.
fn load(control_state_dir: &ControlStateDir) -> BTreeMap<String, String> {
    std::fs::read(registry_path(control_state_dir))
        .ok()
        .and_then(|bytes| serde_json::from_slice::<BTreeMap<String, String>>(&bytes).ok())
        .unwrap_or_default()
}

fn atomic_write(
    control_state_dir: &ControlStateDir,
    map: &BTreeMap<String, String>,
) -> io::Result<()> {
    crate::paths::ensure_control_state_dir(control_state_dir)?;
    let data = serde_json::to_vec_pretty(map).map_err(io::Error::other)?;
    let target = registry_path(control_state_dir);
    // Write to a sibling temp file then rename so a concurrent reader never
    // observes a half-written registry. `rename` replaces the target on both
    // Windows and Unix.
    let tmp = target.with_extension("json.tmp");
    std::fs::write(&tmp, &data)?;
    std::fs::rename(&tmp, &target)
}

/// Record this binary's `path -> version` in the registry. Best-effort and
/// silent: any failure is ignored so version bookkeeping can never break a
/// real command. Only writes when the recorded value is missing or changed,
/// so the hot path (e.g. repeated hook invocations) reads but does not write.
pub fn record_self(control_state_dir: &ControlStateDir) {
    let _ = record_self_inner(control_state_dir);
}

/// [`record_self`] against the default [`resolve_home`] location — the entry
/// point every binary calls once on launch. Best-effort and silent.
pub fn record_self_default() {
    if let Some(home) = resolve_home() {
        record_self(&home);
    }
}

fn record_self_inner(control_state_dir: &ControlStateDir) -> io::Result<()> {
    let Some(key) = current_exe_key() else {
        return Ok(());
    };
    let mut map = load(control_state_dir);
    if map.get(&key).map(String::as_str) == Some(self_version()) {
        return Ok(()); // unchanged — avoid a needless write
    }
    map.insert(key, self_version().to_string());
    atomic_write(control_state_dir, &map)
}

/// A newer SymForge install discovered at a different path than the running
/// binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleBinary {
    pub running_version: String,
    pub running_path: String,
    pub newer_version: String,
    pub newer_path: String,
}

/// Returns `Some` when a strictly newer version is registered at a different,
/// still-existing path than the running binary — i.e. the running binary is
/// stale. Read-only; performs no writes, no process spawns, no network.
pub fn detect_stale(control_state_dir: &ControlStateDir) -> Option<StaleBinary> {
    let running_path = current_exe_key()?;
    let running_version = self_version();
    let map = load(control_state_dir);

    let mut best: Option<(&String, &String)> = None;
    for (path, version) in &map {
        if path == &running_path {
            continue;
        }
        if !crate::cli::version::is_newer_version(version, running_version) {
            continue;
        }
        // Ignore registry entries whose binary has since been removed, so an
        // uninstalled-but-still-listed version never raises a false warning.
        if !Path::new(path).exists() {
            continue;
        }
        match best {
            Some((_, best_version))
                if !crate::cli::version::is_newer_version(version, best_version) => {}
            _ => best = Some((path, version)),
        }
    }

    best.map(|(path, version)| StaleBinary {
        running_version: running_version.to_string(),
        running_path,
        newer_version: version.clone(),
        newer_path: path.clone(),
    })
}

/// Remove registry entries whose recorded binary path no longer exists on disk,
/// while preserving entries on a transiently-offline mount (one whose whole
/// ancestor chain is unreachable — e.g. an unplugged removable or network drive).
/// Best-effort and advisory: returns the number of entries removed (`0` on any
/// I/O error or when nothing changed). `symforge update` calls this so the
/// registry does not accumulate dead entries (e.g. removed git-worktree dev
/// builds, or the retired `~/.symforge/bin` durable binary once it is removed).
pub fn prune_missing_entries(control_state_dir: &ControlStateDir) -> usize {
    let map = load(control_state_dir);
    let before = map.len();
    let pruned: BTreeMap<String, String> = map
        .into_iter()
        // Keep an entry when its binary still exists, OR when its WHOLE mount is
        // unreachable (an unplugged removable / offline network drive). Drop a
        // vanished file only when the drive is online — e.g. a removed git
        // worktree's `target/debug/symforge.exe` whose entire subtree is gone.
        // Checking only the immediate parent (the old behavior) wrongly kept such
        // dead entries forever whenever a directory subtree was deleted.
        .filter(|(path, _)| {
            let candidate = Path::new(path);
            candidate.exists() || !mount_is_reachable(candidate)
        })
        .collect();
    let removed = before - pruned.len();
    if removed > 0 {
        let _ = atomic_write(control_state_dir, &pruned);
    }
    removed
}

/// Whether the mount/drive holding `candidate` is currently reachable: true if
/// any *real* ancestor exists on disk. "Real" deliberately excludes the Windows
/// verbatim/UNC pseudo-roots `\\?` and `\\`, which `Path::exists()` reports as
/// existing for EVERY path (so a canonicalized `\\?\C:\...` entry would otherwise
/// always look reachable, defeating the offline-mount check). The genuine drive
/// root — `C:\` for a plain path, `\\?\C:` for a verbatim one — is retained, so
/// an unplugged `Z:` drive yields no reachable ancestor and its entry is kept.
fn mount_is_reachable(candidate: &Path) -> bool {
    candidate.ancestors().any(|ancestor| {
        if is_universal_pseudo_root(ancestor) {
            return false;
        }
        ancestor.exists()
    })
}

/// True for the Windows verbatim/UNC prefix pseudo-roots (`\\` and `\\?`) that
/// `Path::exists()` universally reports as existing. Everywhere else (including
/// the Unix root `/` and real drive roots like `C:\` / `\\?\C:`) returns false so
/// their genuine existence is honored.
fn is_universal_pseudo_root(ancestor: &Path) -> bool {
    matches!(ancestor.as_os_str().to_str(), Some(r"\\") | Some(r"\\?"))
}

/// Human-readable, EDR-safe drift warning. Surfaces a command the **user**
/// runs in their own shell to overwrite the stale running binary with the newer
/// install — the daemon itself never copies or replaces the executable.
pub fn stale_warning(stale: &StaleBinary) -> String {
    let refresh = if cfg!(windows) {
        format!(
            "    Get-Process symforge | Stop-Process -Force\n    \
             Copy-Item \"{}\" \"{}\" -Force",
            stale.newer_path, stale.running_path
        )
    } else {
        format!(
            "    pkill -f symforge 2>/dev/null; sleep 1\n    \
             cp -f \"{}\" \"{}\"",
            stale.newer_path, stale.running_path
        )
    };
    format!(
        "── \u{26a0} Version drift ──\n\
         This daemon is serving symforge {running_ver} from:\n  {running_path}\n\
         but a newer install ({newer_ver}) exists at:\n  {newer_path}\n\
         The MCP daemon is serving stale code. In your own shell, overwrite the\n\
         stale binary with the newer install, then reconnect your MCP client (e.g. /mcp):\n{refresh}",
        running_ver = stale.running_version,
        running_path = stale.running_path,
        newer_ver = stale.newer_version,
        newer_path = stale.newer_path,
    )
}

/// Convenience: the drift warning string, or `None` when the running binary is
/// the newest known. Callers append this to diagnostics (e.g. `health`).
pub fn drift_banner(control_state_dir: &ControlStateDir) -> Option<String> {
    detect_stale(control_state_dir).map(|stale| stale_warning(&stale))
}

/// [`drift_banner`] against the default [`resolve_home`] location.
pub fn drift_banner_default() -> Option<String> {
    drift_banner(&resolve_home()?)
}

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

    fn write_registry(control_state_dir: &ControlStateDir, entries: &[(&str, &str)]) {
        let map: BTreeMap<String, String> = entries
            .iter()
            .map(|(p, v)| ((*p).to_string(), (*v).to_string()))
            .collect();
        atomic_write(control_state_dir, &map).unwrap();
    }

    #[test]
    fn record_self_writes_and_is_idempotent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));
        record_self(&home);
        let after_first = std::fs::read_to_string(registry_path(&home)).unwrap();
        let key = current_exe_key().unwrap();
        let map = load(&home);
        assert_eq!(map.get(&key).map(String::as_str), Some(self_version()));

        // A second record with the same version must not rewrite the file.
        record_self(&home);
        let after_second = std::fs::read_to_string(registry_path(&home)).unwrap();
        assert_eq!(after_first, after_second);
    }

    #[test]
    fn prune_missing_entries_drops_dead_paths_and_keeps_live_ones() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));
        // One entry points at a real file, one at a path that no longer exists.
        let live = tmp.path().join("live-symforge");
        std::fs::write(&live, b"binary").unwrap();
        let live_key = live.to_string_lossy().into_owned();
        let dead_key = tmp
            .path()
            .join("gone-symforge")
            .to_string_lossy()
            .into_owned();
        write_registry(
            &home,
            &[(live_key.as_str(), "7.15.4"), (dead_key.as_str(), "7.14.4")],
        );

        let removed = prune_missing_entries(&home);

        assert_eq!(removed, 1, "exactly the dead entry should be pruned");
        let map = load(&home);
        assert!(map.contains_key(&live_key), "live entry kept");
        assert!(!map.contains_key(&dead_key), "dead entry removed");

        // Idempotent: a second prune removes nothing.
        assert_eq!(prune_missing_entries(&home), 0);
    }

    #[test]
    fn prune_missing_entries_drops_dead_entry_when_whole_subtree_was_deleted() {
        // Regression: a removed git worktree's binary lives several directories
        // deep. The immediate parent (and its parents) were all deleted along with
        // the subtree, but the temp root still exists (the drive is online). The
        // old immediate-parent-only check kept this dead entry forever; it must be
        // pruned now.
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));

        let gone_root = tmp.path().join("gone");
        let dead = gone_root.join("deep").join("symforge.exe");
        // Materialize then remove the whole `gone/` subtree, so `gone`, `gone/deep`
        // and the leaf are all absent while `tmp` (an ancestor) still exists.
        std::fs::create_dir_all(dead.parent().unwrap()).unwrap();
        std::fs::write(&dead, b"binary").unwrap();
        std::fs::remove_dir_all(&gone_root).unwrap();
        assert!(!gone_root.exists(), "subtree must be gone for the test");
        assert!(
            tmp.path().exists(),
            "an ancestor must remain (drive online)"
        );

        let dead_key = dead.to_string_lossy().into_owned();

        let live = tmp.path().join("live-symforge");
        std::fs::write(&live, b"binary").unwrap();
        let live_key = live.to_string_lossy().into_owned();

        write_registry(
            &home,
            &[(live_key.as_str(), "7.15.4"), (dead_key.as_str(), "7.14.4")],
        );

        let removed = prune_missing_entries(&home);

        assert_eq!(removed, 1, "the deleted-subtree entry must be pruned");
        let map = load(&home);
        assert!(map.contains_key(&live_key), "live entry kept");
        assert!(
            !map.contains_key(&dead_key),
            "dead deleted-subtree entry removed"
        );
    }

    // An offline removable/network mount means EVERY ancestor up to the drive root
    // is unreachable. That can only be modelled where a drive root itself can be
    // absent — on Windows a `Z:\` root does not exist when the drive is unplugged.
    // On Unix the filesystem root `/` always exists, so a transiently-offline mount
    // there still has a reachable ancestor and, by design, a vanished file under it
    // is treated as a genuine deletion. We therefore exercise the offline-keep path
    // on Windows only; the Unix prune-on-deletion behavior is covered by the
    // deleted-subtree test above.
    //
    // The registry stores canonicalized paths, which on Windows are VERBATIM
    // (`\\?\C:\...`). Their ancestor chain ends in the pseudo-roots `\\?` and `\\`,
    // both of which `Path::exists()` always reports as existing — so we verify the
    // verbatim form specifically to prove `mount_is_reachable` ignores those
    // pseudo-roots and still keeps an offline entry. We pick an unmapped drive
    // letter at runtime so the test is independent of the host's drive layout.
    #[cfg(windows)]
    #[test]
    fn prune_missing_entries_keeps_entry_on_offline_mount() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));

        // Find a drive letter whose root does not exist (genuinely unmapped).
        let absent = ('D'..='Z')
            .rev()
            .find(|d| !Path::new(&format!(r"{d}:\")).exists())
            .expect("at least one drive letter D..=Z should be unmapped on the test host");

        // Verbatim canonical form (what `current_exe_key` records on Windows).
        // The genuine drive root `\\?\{absent}:` is absent; only the universal
        // pseudo-roots (`\\?`, `\\`) may report as existing — which `Path::exists()`
        // does inconsistently depending on the path's internal representation. The
        // load-bearing predicate `mount_is_reachable` must ignore those pseudo-roots
        // and classify the mount as UNREACHABLE regardless.
        let offline_key = format!(r"\\?\{absent}:\offline-mount\bin\symforge.exe");
        assert!(
            !mount_is_reachable(Path::new(&offline_key)),
            "an unmapped drive must be classified unreachable despite the pseudo-root"
        );

        write_registry(&home, &[(offline_key.as_str(), "7.14.4")]);

        let removed = prune_missing_entries(&home);

        assert_eq!(removed, 0, "an offline-mount entry must be kept");
        assert!(load(&home).contains_key(&offline_key), "offline entry kept");
    }

    #[test]
    fn detect_stale_flags_newer_version_at_existing_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));
        // A real file stands in for the "newer" binary so the existence check passes.
        let newer = tmp.path().join("newer-symforge");
        std::fs::write(&newer, b"binary").unwrap();
        let newer_key = std::fs::canonicalize(&newer)
            .unwrap_or(newer)
            .to_string_lossy()
            .into_owned();

        let running = current_exe_key().unwrap();
        write_registry(
            &home,
            &[
                (running.as_str(), self_version()),
                (newer_key.as_str(), "999.0.0"),
            ],
        );

        let stale = detect_stale(&home).expect("newer version at another path is stale");
        assert_eq!(stale.newer_version, "999.0.0");
        assert_eq!(stale.newer_path, newer_key);
        assert_eq!(stale.running_version, self_version());
    }

    #[test]
    fn detect_stale_ignores_missing_newer_binary() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));
        let running = current_exe_key().unwrap();
        // Newer version listed, but its path does not exist on disk.
        write_registry(
            &home,
            &[
                (running.as_str(), self_version()),
                ("/nonexistent/symforge-binary", "999.0.0"),
            ],
        );
        assert!(detect_stale(&home).is_none());
    }

    #[test]
    fn detect_stale_returns_none_when_self_is_newest() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));
        let running = current_exe_key().unwrap();
        write_registry(
            &home,
            &[
                (running.as_str(), self_version()),
                ("/some/old/symforge", "0.0.1"),
            ],
        );
        assert!(detect_stale(&home).is_none());
    }

    #[test]
    fn detect_stale_returns_none_on_empty_registry() {
        let tmp = tempfile::TempDir::new().unwrap();
        let home = ControlStateDir::new(tmp.path().join("control"));
        assert!(detect_stale(&home).is_none());
    }

    #[test]
    fn stale_warning_includes_paths_and_versions() {
        let stale = StaleBinary {
            running_version: "7.14.4".to_string(),
            running_path: "/home/u/.symforge/bin/symforge".to_string(),
            newer_version: "7.14.5".to_string(),
            newer_path: "/home/u/.npm/symforge".to_string(),
        };
        let text = stale_warning(&stale);
        assert!(text.contains("Version drift"));
        assert!(text.contains("7.14.4"));
        assert!(text.contains("7.14.5"));
        assert!(text.contains("/home/u/.symforge/bin/symforge"));
        assert!(text.contains("/home/u/.npm/symforge"));
    }
}