zshrs 0.11.4

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
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
//! Daemon-presence detection + per-user config knob.
//!
//! **zshrs-original infrastructure — no C source counterpart.** C
//! zsh has no daemon process. Shell state lives in the running
//! interpreter and re-initializes on every launch. zshrs ships
//! `zshrs-daemon` as a separate binary that holds canonical
//! parameter/option/function state in shared memory; the shell
//! probes its socket at startup and decides whether to use the
//! cached state or fall back to vanilla full-init mode.
//!
//! Per the `zshrs ↔ zshrs-daemon = independent binaries` rule
//! (docs/DAEMON.md "Daemon lifecycle"), the shell does NOT spawn the
//! daemon. It probes once at startup and runs in one of three modes:
//!
//! | Mode             | Trigger                                       |
//! |------------------|-----------------------------------------------|
//! | DaemonPresent    | socket alive, daemon answered handshake       |
//! | DaemonAbsent     | no socket / connect refused; degraded vanilla |
//! | DaemonDisabled   | user set `[daemon] enabled = "off"` in config |
//!
//! Without the daemon: zshrs runs as a Rust-fast vanilla zsh — no
//! cache, no canonical state, every config re-evaluated per shell
//! launch ("rebuilding your house every morning"). With the daemon:
//! zshrs uses the cached canonical state for fast cold-start.
//!
//! The probe is single-shot at startup. Builtins / hooks check
//! `is_present()` before calling into the daemon client; on absent,
//! they noop or fall back to source-interp behavior.
//!
//! Config (`$ZSHRS_HOME/zshrs.toml` or `~/.zshrs/zshrs.toml`, all optional):
//!
//! ```toml
//! [daemon]
//! # "auto" (default) = probe at startup, use if alive
//! # "off"            = never probe; pure vanilla zsh mode
//! # "require"        = probe and warn if absent (no spawn either way)
//! enabled = "auto"
//!
//! [shell]
//! # "off"  (default) = always source .zshenv/.zprofile/.zshrc/.zlogin
//! # "auto"           = if daemon is present + has zshrs rows, skip
//! #                    every dotfile and apply canonical state
//! #                    from the daemon instead. ~10ms cold-start.
//! # "on"             = always skip dotfiles when the daemon is up;
//! #                    don't even check for zshrs rows. Strict mode.
//! skip_configs = "off"
//! ```
//!
//! Lives in `~/.zshrs/` alongside everything else (rkyv shards,
//! catalog.db, daemon.sock, zshrs-daemon.toml, log, …) — single
//! directory rule for all zshrs files. Survives OS cache eviction
//! (this is NOT cache-semantic state). `rm -rf ~/.zshrs/` is the
//! one-verb total reset.

use std::sync::atomic::{AtomicU8, Ordering};

/// Daemon-presence probe result.
/// zshrs-original — no C counterpart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Mode {
    /// Probe hasn't run yet.
    Unknown = 0,
    /// Socket connected; assume daemon is alive.
    Present = 1,
    /// Probe ran; daemon was not reachable. Shell runs in vanilla mode.
    Absent = 2,
    /// User opted out via `[daemon] enabled = "off"`. No probe attempted.
    Disabled = 3,
}

impl Mode {
    #[inline]
    fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Present,
            2 => Self::Absent,
            3 => Self::Disabled,
            _ => Self::Unknown,
        }
    }
}

static STATE: AtomicU8 = AtomicU8::new(Mode::Unknown as u8);

/// What the user said in `[daemon].enabled` (or the auto default).
/// zshrs-original — no C counterpart. C zsh has no daemon to enable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigSetting {
    /// Probe at startup; use the daemon if alive (default).
    Auto,
    /// Skip the probe entirely; never talk to the daemon.
    Off,
    /// Probe at startup; if the daemon isn't alive, log a warning
    /// (still doesn't spawn — that's the user's responsibility).
    Require,
}

/// What the user said in `[shell].skip_configs`.
/// Explicit discriminants pin the AtomicU8 round-trip in
/// `skip_configs_setting()`.
/// zshrs-original — no C counterpart. C zsh always sources every
/// startup file (Src/init.c `source_home_file()` chain); the
/// canonical-state path that lets us skip those is unique to zshrs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum SkipConfigs {
    /// Always source dotfiles (legacy / vanilla zsh behavior). Default.
    Off = 0,
    /// Skip dotfiles iff daemon is present AND has zshrs canonical
    /// rows. Falls back to dotfile sourcing otherwise. The recommended
    /// setting once the recorder has populated canonical state.
    Auto = 1,
    /// Always skip dotfiles when the daemon is up; don't bother
    /// checking for zshrs rows. Strict mode for users who know their
    /// daemon is fully populated.
    On = 2,
}

impl ConfigSetting {
    fn parse(s: &str) -> Option<Self> {
        match s {
            "auto" | "" => Some(Self::Auto),
            "off" | "false" | "no" | "0" => Some(Self::Off),
            "require" | "on" | "true" | "yes" | "1" => Some(Self::Require),
            _ => None,
        }
    }
}

impl SkipConfigs {
    fn parse(s: &str) -> Option<Self> {
        match s {
            "off" | "false" | "no" | "0" | "" => Some(Self::Off),
            "auto" => Some(Self::Auto),
            "on" | "true" | "yes" | "1" => Some(Self::On),
            _ => None,
        }
    }
}

/// Both knobs from `~/.zshrs/zshrs.toml`. Missing file / section
/// / key returns the safe defaults (`daemon=auto`,
/// `skip_configs=off`). Unrecognized values fall back with a log
/// warning.
/// zshrs-original — no C counterpart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
    pub daemon: ConfigSetting,
    pub skip_configs: SkipConfigs,
}

pub fn read_config_full() -> Config {
    let defaults = Config {
        daemon: ConfigSetting::Auto,
        skip_configs: SkipConfigs::Off,
    };
    let path = match config_file_path() {
        Some(p) => p,
        None => return defaults,
    };
    let body = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(_) => return defaults,
    };
    let parsed = match body.parse::<toml::Table>() {
        Ok(t) => t,
        Err(e) => {
            tracing::warn!(path = %path.display(), error = %e, "zshrs.toml: parse failed; using defaults");
            return defaults;
        }
    };
    let daemon = parsed
        .get("daemon")
        .and_then(|v| v.as_table())
        .and_then(|t| t.get("enabled"))
        .and_then(|v| v.as_str())
        .map(|s| {
            ConfigSetting::parse(s).unwrap_or_else(|| {
                tracing::warn!(value = s, "zshrs.toml: [daemon].enabled invalid; using auto");
                ConfigSetting::Auto
            })
        })
        .unwrap_or(ConfigSetting::Auto);
    let skip_configs = parsed
        .get("shell")
        .and_then(|v| v.as_table())
        .and_then(|t| t.get("skip_configs"))
        .and_then(|v| v.as_str())
        .map(|s| {
            SkipConfigs::parse(s).unwrap_or_else(|| {
                tracing::warn!(value = s, "zshrs.toml: [shell].skip_configs invalid; using off");
                SkipConfigs::Off
            })
        })
        .unwrap_or(SkipConfigs::Off);
    Config {
        daemon,
        skip_configs,
    }
}

/// Back-compat wrapper kept for callers that only need the daemon knob.
pub fn read_config() -> ConfigSetting {
    read_config_full().daemon
}

/// `[log] level` from `~/.zshrs/zshrs.toml` for the SHELL side
/// (zsh::log + zshrs-recorder). Same precedence model the daemon uses
/// for its own side: `$ZSHRS_LOG` env wins, then this directive, then
/// `"info"`. Caller hands the returned string straight to
/// `EnvFilter::try_new`. Errors / missing file / missing key all
/// resolve to "info" silently — a malformed directive produces a
/// useful "bad directive" message at the EnvFilter parse layer
/// instead.
pub fn read_log_directive() -> String {
    const DEFAULT: &str = "info";
    let path = match config_file_path() {
        Some(p) => p,
        None => return DEFAULT.into(),
    };
    let body = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(_) => return DEFAULT.into(),
    };
    let parsed = match body.parse::<toml::Table>() {
        Ok(t) => t,
        Err(_) => return DEFAULT.into(),
    };
    parsed
        .get("log")
        .and_then(|v| v.as_table())
        .and_then(|t| t.get("level"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| DEFAULT.into())
}

/// Cached `[shell].skip_configs` value. Set by `probe()`; read by the
/// shell-init path before sourcing dotfiles.
static SKIP_CONFIGS: AtomicU8 = AtomicU8::new(0);

/// Have we confirmed the daemon has zshrs canonical rows? Set during
/// the same probe pass so the `skip_configs` decision is one atomic
/// load on the hot path.
static SHOULD_SKIP_CONFIGS: AtomicU8 = AtomicU8::new(0);

/// Resolve `$ZSHRS_HOME/zshrs.toml` or `~/.zshrs/zshrs.toml`.
/// Single-directory rule: every zshrs file lives under one root.
/// Returns None if neither $ZSHRS_HOME nor $HOME is set, which is
/// rare enough to treat as "no config file".
fn config_file_path() -> Option<std::path::PathBuf> {
    let root = if let Some(custom) = std::env::var_os("ZSHRS_HOME") {
        std::path::PathBuf::from(custom)
    } else {
        std::path::PathBuf::from(std::env::var_os("HOME")?).join(".zshrs")
    };
    Some(root.join("zshrs.toml"))
}

/// Cheap probe — connect-only, no handshake — does the daemon
/// socket answer?
/// zshrs-original — no C counterpart. Sets the global state so
/// subsequent `is_present()` checks are O(1) atomic loads.
///
/// Honors `[daemon].enabled`:
///   - `Off` → state = Disabled, no probe
///   - `Auto` / `Require` → probe; state = Present or Absent
///
/// `Require` additionally logs a warning if the daemon isn't alive —
/// signal to the user that they configured the shell to expect a
/// daemon but didn't actually start one.
pub fn probe() -> Mode {
    let cfg = read_config_full();
    SKIP_CONFIGS.store(cfg.skip_configs as u8, Ordering::Relaxed);

    match cfg.daemon {
        ConfigSetting::Off => {
            tracing::info!("daemon: disabled in config ([daemon] enabled = \"off\")");
            STATE.store(Mode::Disabled as u8, Ordering::Relaxed);
            // Disabled daemon → no skip; dotfiles always source.
            SHOULD_SKIP_CONFIGS.store(0, Ordering::Relaxed);
            return Mode::Disabled;
        }
        ConfigSetting::Auto | ConfigSetting::Require => {}
    }

    let alive = probe_socket();
    let mode = if alive { Mode::Present } else { Mode::Absent };
    STATE.store(mode as u8, Ordering::Relaxed);

    if alive {
        tracing::info!("daemon: present (socket reachable)");
    } else {
        match cfg.daemon {
            ConfigSetting::Require => {
                tracing::warn!(
                    "daemon: absent — config requires it but socket is not reachable. \
                     Start it via `zshrs-daemon`, `systemctl --user start zshrs-daemon`, \
                     `launchctl load ~/Library/LaunchAgents/com.menketechnologies.zshrs-daemon.plist`, \
                     or `brew services start zshrs`. Falling back to vanilla mode."
                );
            }
            _ => {
                tracing::info!(
                    "daemon: absent (socket not reachable) — running in vanilla zsh mode"
                );
            }
        }
    }

    // Resolve [shell].skip_configs against daemon presence + zshrs-row
    // availability. Three settings collapse to a yes/no decision:
    //   Off  → never skip
    //   On   → skip iff daemon Present (don't even check rows)
    //   Auto → skip iff daemon Present AND has zshrs canonical rows
    let should_skip = match cfg.skip_configs {
        SkipConfigs::Off => false,
        SkipConfigs::On => mode == Mode::Present,
        SkipConfigs::Auto => mode == Mode::Present && daemon_has_zshrs_rows(),
    };
    SHOULD_SKIP_CONFIGS.store(if should_skip { 1 } else { 0 }, Ordering::Relaxed);
    if should_skip {
        tracing::info!(
            "shell: skip_configs active — bypassing /etc/zshenv + ~/.{{zshenv,zprofile,zshrc,zlogin}} and \
             applying canonical state from daemon"
        );
    } else if cfg.skip_configs != SkipConfigs::Off {
        tracing::info!(
            mode = ?cfg.skip_configs,
            daemon = ?mode,
            "shell: skip_configs configured but conditions not met — sourcing dotfiles normally"
        );
    }
    mode
}

/// Cheap probe: does the daemon have a recorder shard on disk for
/// shell_id "zshrs"? A `*-recorder.rkyv` file in `~/.zshrs/images/`
/// means the recorder ran at least once and we have canonical state to
/// apply. **No IPC** — this is a directory listing + filename match,
/// because the shell cold-start path can afford zero IPC roundtrips
/// (the architecture's whole speed thesis).
///
/// Returns false on any I/O error → caller falls through to vanilla
/// `source_startup_files()`.
#[cfg(feature = "daemon")]
fn daemon_has_zshrs_rows() -> bool {
    let paths = match crate::daemon::paths::CachePaths::resolve() {
        Ok(p) => p,
        Err(_) => return false,
    };
    let entries = match std::fs::read_dir(&paths.images) {
        Ok(it) => it,
        Err(_) => return false,
    };
    for entry in entries.flatten() {
        if let Some(s) = entry.file_name().to_str() {
            if s.ends_with("-recorder.rkyv") {
                return true;
            }
        }
    }
    false
}

#[cfg(not(feature = "daemon"))]
fn daemon_has_zshrs_rows() -> bool {
    false
}

/// Should the shell-init path skip every `/etc/zsh*` + `~/.zsh*`
/// dotfile and apply canonical state from the daemon instead? O(1)
/// atomic load — set by `probe()` at startup.
/// zshrs-original — no C counterpart. C zsh's Src/init.c always
/// sources every startup file unconditionally.
#[inline]
pub fn should_skip_configs() -> bool {
    SHOULD_SKIP_CONFIGS.load(Ordering::Relaxed) != 0
}

/// Read the cached `[shell].skip_configs` setting (verbatim from
/// config — independent of whether conditions to skip were met).
/// Mostly useful for diagnostics / `zshrs --doctor`.
pub fn skip_configs_setting() -> SkipConfigs {
    match SKIP_CONFIGS.load(Ordering::Relaxed) {
        1 => SkipConfigs::Auto,
        2 => SkipConfigs::On,
        _ => SkipConfigs::Off,
    }
}

/// Run the probe via the daemon-client crate's cheap is-alive helper.
/// Falls back to a manual socket check if the daemon feature is off
/// (which is the workspace's stub-mode build path).
#[cfg(feature = "daemon")]
fn probe_socket() -> bool {
    match crate::daemon::paths::CachePaths::resolve() {
        Ok(paths) => crate::daemon::client::Client::is_daemon_alive(&paths),
        Err(_) => false,
    }
}

#[cfg(not(feature = "daemon"))]
fn probe_socket() -> bool {
    false
}

/// O(1) read of the cached probe result. Returns `Unknown` until
/// `probe()` has run.
/// zshrs-original — no C counterpart.
#[inline]
pub fn current() -> Mode {
    Mode::from_u8(STATE.load(Ordering::Relaxed))
}

/// Did the probe see a live daemon? `false` for any other state
/// (`Unknown` / `Absent` / `Disabled`).
/// zshrs-original — no C counterpart.
#[inline]
pub fn is_present() -> bool {
    current() == Mode::Present
}

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

    #[test]
    fn config_setting_parses_common_aliases() {
        assert_eq!(ConfigSetting::parse("auto"), Some(ConfigSetting::Auto));
        assert_eq!(ConfigSetting::parse(""), Some(ConfigSetting::Auto));
        assert_eq!(ConfigSetting::parse("off"), Some(ConfigSetting::Off));
        assert_eq!(ConfigSetting::parse("false"), Some(ConfigSetting::Off));
        assert_eq!(ConfigSetting::parse("no"), Some(ConfigSetting::Off));
        assert_eq!(ConfigSetting::parse("0"), Some(ConfigSetting::Off));
        assert_eq!(ConfigSetting::parse("require"), Some(ConfigSetting::Require));
        assert_eq!(ConfigSetting::parse("on"), Some(ConfigSetting::Require));
        assert_eq!(ConfigSetting::parse("true"), Some(ConfigSetting::Require));
        assert_eq!(ConfigSetting::parse("garbage"), None);
    }

    #[test]
    fn mode_round_trips_through_atomic() {
        for m in [Mode::Unknown, Mode::Present, Mode::Absent, Mode::Disabled] {
            assert_eq!(Mode::from_u8(m as u8), m);
        }
    }
}