synaps-engine 0.10.1

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
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
//! Daemon front-end (`synaps daemon`): UDS listener, per-connection pump,
//! registry file, lifecycle (PLAN-phase2 §2.11). Lives in `agent-engine`
//! (S289 D-1 amended) — `agent-tui` must never appear in this graph.
//!
//! On by default: the first `--attach`/`attach` client auto-spawns the
//! daemon ([`ensure_running`]); `SYNAPS_DAEMON=0` disables every daemon
//! feature (exit 3 with a one-line reason). Safety properties that are
//! NEVER stubbed: the flock liveness oracle, the ready-fd pipe, socket
//! perms 0700/0600, the spawn lock (one spawner per registry dir).

pub mod conn;
pub mod lifecycle;
pub mod listener;
pub mod registry;
pub mod reload;

use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use tokio_util::sync::CancellationToken;

use crate::session::{SessionConfig, SessionHandle, SessionId, SessionMeta};
use crate::EngineHost;
use registry::{DaemonInfo, DaemonLock, DaemonPaths};

/// Exit code when the daemon refuses to start (flag off / legacy MCP).
pub const EXIT_REFUSED: i32 = 3;
/// Exit code for a protocol/version refusal on the client side.
pub const EXIT_VERSION: i32 = 2;
/// The daemon was lost (SIGKILL / crash) and reconnection failed within the
/// budget (`SYNAPS_TUI_ATTACH_RECONNECT_SECS`).
pub const EXIT_DAEMON_LOST: i32 = 4;
/// Env var carrying the write end of the ready pipe to a spawned daemon.
pub const READY_FD_ENV: &str = "SYNAPS_DAEMON_READY_FD";
/// How long `spawn_detached` waits for the child's ready byte.
pub const SPAWN_READY_TIMEOUT: Duration = Duration::from_secs(5);

/// `SYNAPS_DAEMON` feature flag: ON unless set to `0`/`false`/`off`/`no`.
/// `SYNAPS_DAEMON=1` is accepted (no-op, kept for older scripts).
pub fn enabled() -> bool {
    enabled_from(std::env::var("SYNAPS_DAEMON").ok().as_deref())
}

fn env_is_off(v: Option<&str>) -> bool {
    matches!(v.map(|s| s.trim().to_ascii_lowercase()).as_deref(), Some("0" | "false" | "off" | "no"))
}

fn enabled_from(v: Option<&str>) -> bool {
    !env_is_off(v)
}

/// `SYNAPS_DAEMON_AUTOSPAWN`: ON unless `0`/`false`/`off`/`no`. Off means
/// an attach with no live daemon fails with the "no daemon running" message
/// instead of starting one.
pub fn autospawn_enabled() -> bool {
    !env_is_off(std::env::var("SYNAPS_DAEMON_AUTOSPAWN").ok().as_deref())
}

/// One-line reason used by every attach path when the flag is off.
pub const DISABLED_NOTICE: &str = "daemon disabled by SYNAPS_DAEMON=0";

/// `SYNAPS_DAEMON_ALLOW_LEGACY_MCP=1` (§4.4).
pub fn allow_legacy_mcp_env() -> bool {
    matches!(std::env::var("SYNAPS_DAEMON_ALLOW_LEGACY_MCP").as_deref(), Ok("1") | Ok("true"))
}

/// Builds a session for `Attach::Create`: `host_factory` (real actor) or
/// `echo_factory` (tests).
pub type SessionFactory = Arc<
    dyn Fn(SessionConfig) -> Pin<Box<dyn Future<Output = Result<SessionHandle, String>> + Send>>
        + Send
        + Sync,
>;

/// EchoActor-backed factory (B's socket tests before A1).
#[cfg(any(test, feature = "testing"))]
pub fn echo_factory() -> SessionFactory {
    Arc::new(|cfg: SessionConfig| {
        Box::pin(async move {
            let id = SessionId(format!(
                "echo-{}-{}",
                chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"),
                uuid::Uuid::new_v4().simple()
            ));
            let (handle, _task) = SessionHandle::echo_for_test(id);
            let _ = cfg;
            Ok(handle)
        })
    })
}

/// The default factory for a booted host: `EngineHost::create_session` (A1) —
/// the real `SessionActor` owning one `Runtime` + `ConversationState`.
pub fn host_factory(host: &Arc<EngineHost>) -> SessionFactory {
    let host = Arc::clone(host);
    Arc::new(move |cfg: SessionConfig| {
        let host = Arc::clone(&host);
        Box::pin(async move { host.create_session(cfg).await.map_err(|e| e.to_string()) })
    })
}

#[derive(Clone, Default)]
pub struct DaemonOpts {
    /// Override the socket path (the lock/json/pid stay under `registry_dir()`).
    pub socket: Option<PathBuf>,
    pub profile: Option<String>,
    /// Exit after this long with zero connections and no session running a
    /// turn (idle, client-less sessions are saved on exit; `--continue`
    /// brings them back). A turn in flight always blocks the exit.
    pub idle_exit: Option<Duration>,
    pub allow_legacy_mcp: bool,
    /// Test seam: `registry_dir()` replacement.
    pub runtime_dir: Option<PathBuf>,
    /// Test seam / A1 hook: how `Attach::Create` builds a session.
    pub factory: Option<SessionFactory>,
}

impl DaemonOpts {
    pub fn paths(&self) -> DaemonPaths {
        let mut p = match &self.runtime_dir {
            Some(d) => registry::daemon_paths_in(d, self.profile.as_deref()),
            None => registry::daemon_paths(self.profile.as_deref()),
        };
        if let Some(s) = &self.socket {
            p.sock = s.clone();
        }
        p
    }
}

/// Shared by the accept loop and every connection.
pub struct DaemonState {
    pub host: Arc<EngineHost>,
    pub paths: DaemonPaths,
    pub profile: Option<String>,
    pub started: Instant,
    pub factory: SessionFactory,
    pub connections: AtomicUsize,
    pub shutdown: CancellationToken,
    pub force_shutdown: AtomicBool,
    // ── C3 reload ──
    /// Reload counter (`Welcome.generation`; starts at 1).
    pub generation: u64,
    /// Drain: refuse `Attach::Create` / new turns while set.
    pub reloading: AtomicBool,
    /// Generation announced in `Reloading`/`Bye{Reloading}`.
    pub reload_generation: std::sync::atomic::AtomicU64,
    /// Cancelled once per reload attempt: every conn sends `Reloading` +
    /// `Bye`. Replaced with a fresh token when the exec fails (M4) so the
    /// surviving image accepts connections again — read via `announce()`.
    pub reload_announce: Mutex<CancellationToken>,
    /// The flock, held here (not on `Daemon`) so `reload` can hand its fd
    /// to the next image.
    pub lock_fd: Mutex<Option<DaemonLock>>,
    /// `old id → new id` for one generation (ids differ only if a
    /// LinkedSuccessor compaction happened since boot).
    pub reload_aliases: Mutex<HashMap<String, String>>,
}

impl DaemonState {
    pub fn uptime_s(&self) -> u64 {
        self.started.elapsed().as_secs()
    }

    /// The current reload-announce token (clone; select on `.cancelled()`).
    pub fn announce(&self) -> CancellationToken {
        self.reload_announce
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// Fire the announce (every conn says `Reloading` + `Bye`).
    pub fn fire_announce(&self) {
        self.announce().cancel();
    }

    /// Exec failed: arm a fresh token so new connections are served again.
    pub fn reset_announce(&self) {
        *self.reload_announce.lock().unwrap_or_else(|e| e.into_inner()) = CancellationToken::new();
    }

    /// B4: ONE session map — `EngineHost` owns it; these delegate.
    pub fn live_sessions(&self) -> Vec<SessionHandle> {
        self.host.session_handles()
    }

    /// Listing metas with lifecycle / clients / input_owner / journal_id
    /// (B4: `EngineHost::sessions()` fills the handle cells).
    pub fn session_metas(&self) -> Vec<SessionMeta> {
        self.host.sessions()
    }

    /// Live handle by id; falls back to the C3 reload alias
    /// (`old id → new id`, set when a LinkedSuccessor compaction happened
    /// since boot) so clients reconnecting after `daemon reload` find
    /// their session under the id they last saw.
    pub fn attach(&self, id: &SessionId) -> Option<SessionHandle> {
        self.host.attach(id).filter(|h| h.is_alive()).or_else(|| {
            let alias = self
                .reload_aliases
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .get(id.as_str())
                .cloned()?;
            self.host
                .attach(&SessionId::from(alias.as_str()))
                .filter(|h| h.is_alive())
        })
    }

    pub fn insert(&self, handle: SessionHandle) {
        self.host.adopt_session(handle);
    }

    pub fn remove(&self, id: &SessionId) {
        self.host.remove_session(id);
    }

    pub async fn create(&self, cfg: SessionConfig) -> Result<SessionHandle, String> {
        let handle = (self.factory)(cfg).await?;
        self.insert(handle.clone());
        Ok(handle)
    }

    /// F23: a lock-held placeholder (`meta.locked_by.is_some()`) is retried on
    /// every attach. Pull it out of the map first — otherwise the host's
    /// attach-if-live short-circuit hands the placeholder straight back —
    /// and re-run the real `create` from the journal. Success replaces the
    /// placeholder under the same id; still-held puts it back and the caller
    /// attaches to it (→ `AttachRefused` naming the holder).
    pub async fn retry_locked_placeholder(&self, placeholder: SessionHandle) -> SessionHandle {
        let cfg = SessionConfig {
            continue_session: Some(Some(placeholder.id.as_str().to_string())),
            ..placeholder.placeholder_config().cloned().unwrap_or_default()
        };
        self.remove(&placeholder.id);
        match (self.factory)(cfg).await {
            Ok(real) if real.id == placeholder.id || real.journal_id() == placeholder.id.as_str() => {
                tracing::info!(session = %placeholder.id, "daemon: locked journal released — placeholder replaced by the real session");
                self.insert(real.clone());
                real
            }
            Ok(other) => {
                // Journal resolved somewhere else (e.g. compacted_into follow): keep it, drop the placeholder.
                tracing::warn!(session = %placeholder.id, resolved = %other.id, "daemon: placeholder retry resolved to a different id");
                self.insert(other.clone());
                other
            }
            Err(e) => {
                tracing::debug!(session = %placeholder.id, error = %e, "daemon: journal still locked; keeping placeholder");
                self.insert(placeholder.clone());
                placeholder
            }
        }
    }

    pub fn request_shutdown(&self, force: bool) {
        if force {
            self.force_shutdown.store(true, Ordering::SeqCst);
        }
        self.shutdown.cancel();
    }
}

/// A running daemon (bound socket, lock held, accept loop spawned).
pub struct Daemon {
    pub paths: DaemonPaths,
    pub state: Arc<DaemonState>,
    accept: tokio::task::JoinHandle<()>,
}

/// Refuse-to-start check (§2.11): legacy `McpTool` connections would be
/// shared across sessions.
pub fn legacy_mcp_conflict(host: &EngineHost, allow: bool) -> Option<String> {
    if allow || allow_legacy_mcp_env() {
        return None;
    }
    let cfg = host.config();
    if !cfg.progressive_tool_disclosure && host.mcp_server_count() > 0 {
        return Some(format!(
            "progressive_tool_disclosure=false with {} MCP server(s) configured: legacy McpTool connections would be shared across sessions. Set progressive_tool_disclosure=true, or pass --allow-legacy-mcp / SYNAPS_DAEMON_ALLOW_LEGACY_MCP=1",
            host.mcp_server_count()
        ));
    }
    None
}

impl Daemon {
    /// Reap stale files, take the flock, bind (dir 0700 / sock 0600), write
    /// `daemon.json`, spawn the accept loop, signal the ready fd if any.
    pub async fn start(host: Arc<EngineHost>, opts: DaemonOpts) -> anyhow::Result<Self> {
        let paths = opts.paths();
        std::fs::create_dir_all(&paths.dir)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&paths.dir, std::fs::Permissions::from_mode(0o700))?;
        }
        if let Some(msg) = legacy_mcp_conflict(&host, opts.allow_legacy_mcp) {
            anyhow::bail!("refusing to start: {msg}");
        }
        // C3: after `reload` the new image ADOPTS the inherited flock and
        // skips `reap_stale` (the old image's files are ours).
        let adopted = reload::adopt_from_env()?;
        let (lock, reload_state) = match adopted {
            Some((lock, rs, rs_path)) => {
                let _ = std::fs::remove_file(&rs_path);
                (lock, Some(rs))
            }
            None => {
                registry::reap_stale(&paths);
                let lock = match DaemonLock::try_acquire(&paths)? {
                    Some(l) => l,
                    None => {
                        let who = registry::read_daemon_json(&paths).map(|i| i.pid);
                        anyhow::bail!(
                            "another daemon holds {} (pid {})",
                            paths.lock.display(),
                            who.map_or("unknown".to_string(), |p| p.to_string())
                        );
                    }
                };
                (lock, None)
            }
        };
        let generation = reload_state.as_ref().map_or(1, |rs| rs.generation);
        let listener = listener::bind(&paths.sock)?;

        let factory = opts.factory.clone().unwrap_or_else(|| host_factory(&host));
        let state = Arc::new(DaemonState {
            host,
            paths: paths.clone(),
            profile: opts.profile.clone(),
            started: Instant::now(),
            factory,
            connections: AtomicUsize::new(0),
            shutdown: CancellationToken::new(),
            force_shutdown: AtomicBool::new(false),
            generation,
            reloading: AtomicBool::new(false),
            reload_generation: std::sync::atomic::AtomicU64::new(generation),
            reload_announce: Mutex::new(CancellationToken::new()),
            lock_fd: Mutex::new(Some(lock)),
            reload_aliases: Mutex::new(HashMap::new()),
        });

        let info = DaemonInfo {
            pid: std::process::id(),
            protocol_version: crate::session::wire::PROTOCOL_VERSION,
            daemon_version: crate::session::wire::binary_version(),
            profile: opts.profile.clone(),
            started_at: chrono::Utc::now(),
            socket: paths.sock.to_string_lossy().into_owned(),
            exe: registry::read_daemon_json(&paths).and_then(|i| i.exe).or_else(|| Some(reload::resolve_exe())),
            generation,
        };
        registry::write_daemon_json(&paths, &info)?;

        // C3: rehydrate BEFORE accepting so a reconnecting client finds its session.
        if let Some(rs) = &reload_state {
            reload::rehydrate(&state, rs).await;
        }

        let accept = tokio::spawn(listener::accept_loop(Arc::clone(&state), listener, state.shutdown.clone()));
        if let Some(idle) = opts.idle_exit {
            tokio::spawn(idle_monitor(Arc::clone(&state), idle));
        }
        signal_ready();
        tracing::info!(sock = %paths.sock.display(), pid = info.pid, generation, "daemon: listening");
        Ok(Self { paths, state, accept })
    }

    pub fn shutdown_token(&self) -> CancellationToken {
        self.state.shutdown.clone()
    }

    /// Block until shutdown is requested (frame, signal, idle), then end
    /// every session inside one budget and unlink the files.
    pub async fn wait(self) {
        self.state.shutdown.cancelled().await;
        let force = self.state.force_shutdown.load(Ordering::SeqCst);
        lifecycle::shutdown_all(&self.state, force).await;
        self.accept.abort();
        let _ = self.accept.await;
        for p in [&self.paths.sock, &self.paths.json, &self.paths.pid] {
            crate::events::socket::cleanup_socket(&p.to_string_lossy());
        }
        tracing::info!("daemon: stopped");
        // Release the flock last.
        drop(self.state.lock_fd.lock().unwrap_or_else(|e| e.into_inner()).take());
    }
}

/// How long a `Status` probe may take before the session counts as busy.
const IDLE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);

/// Whether `handle`'s actor is between turns. Asks `Query{Status}` under the
/// reserved [`crate::session::wire::IDLE_PROBE_QUERY_ID`] (transports swallow
/// it) and reads `streaming`. A no-answer inside [`IDLE_PROBE_TIMEOUT`] —
/// the actor is inside `compact()`/preflight, or its queue is full — counts
/// as busy: the daemon never exits under a running turn (jcode mistake #1).
pub async fn session_is_idle(handle: &SessionHandle) -> bool {
    use crate::session::wire::IDLE_PROBE_QUERY_ID;
    use crate::session::{SessionCommand, SessionEventWire, SessionLifecycle, SessionQuery};
    // B3: a parked session is idle by construction — no probe, no wake.
    if handle.lifecycle() == SessionLifecycle::Parked {
        return true;
    }
    let mut rx = handle.subscribe();
    if handle.send(SessionCommand::Query { id: IDLE_PROBE_QUERY_ID, query: SessionQuery::Status }).await.is_err() {
        return false;
    }
    let probe = async {
        loop {
            match rx.recv().await {
                Ok(env) => {
                    if let SessionEventWire::QueryResult { id, value } = env.event {
                        if id == IDLE_PROBE_QUERY_ID {
                            // Real actor: {"streaming": bool, "pending_prompts": n}. A backend that
                            // does not implement Status (echo) has no turns to protect.
                            let streaming = value.get("streaming").and_then(|v| v.as_bool()).unwrap_or(false);
                            let prompts = value.get("pending_prompts").and_then(|v| v.as_u64()).unwrap_or(0);
                            return !streaming && prompts == 0;
                        }
                    }
                }
                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                Err(tokio::sync::broadcast::error::RecvError::Closed) => return true,
            }
        }
    };
    tokio::time::timeout(IDLE_PROBE_TIMEOUT, probe).await.unwrap_or(false)
}

/// Idle = zero connections AND every live session between turns, held for
/// `idle` continuously. Clients count first so a probe is never sent while
/// someone is attached.
pub async fn daemon_is_idle(state: &DaemonState) -> bool {
    if state.connections.load(Ordering::SeqCst) > 0 {
        return false;
    }
    for h in state.live_sessions() {
        if !session_is_idle(&h).await {
            return false;
        }
    }
    true
}

async fn idle_monitor(state: Arc<DaemonState>, idle: Duration) {
    let mut idle_since: Option<Instant> = None;
    let tick = Duration::from_secs(5).min(idle.max(Duration::from_millis(100)));
    loop {
        tokio::select! {
            _ = state.shutdown.cancelled() => return,
            _ = tokio::time::sleep(tick) => {}
        }
        if !daemon_is_idle(&state).await {
            idle_since = None;
            continue;
        }
        let since = *idle_since.get_or_insert_with(Instant::now);
        if since.elapsed() >= idle {
            tracing::info!("daemon: idle for {:?}, exiting", idle);
            state.request_shutdown(false);
            return;
        }
    }
}

/// Child side of the ready pipe: write `R` to `SYNAPS_DAEMON_READY_FD` (if
/// set), close it, and scrub the env so tool subprocesses do not inherit it.
pub fn signal_ready() {
    #[cfg(unix)]
    {
        let Some(fd) = std::env::var(READY_FD_ENV).ok().and_then(|s| s.parse::<i32>().ok()) else {
            return;
        };
        std::env::remove_var(READY_FD_ENV);
        // SAFETY: fd is the write end handed to us by the parent; we own it.
        unsafe {
            let _ = libc::write(fd, b"R".as_ptr() as *const libc::c_void, 1);
            libc::close(fd);
        }
    }
}

/// Parent side: `current_exe daemon --foreground …` in its own session
/// (`setsid`), stdout → null, stderr → pipe; waits ≤ 5 s for `R` on the
/// ready pipe. EOF before `R` = child died → error with its stderr tail.
#[cfg(unix)]
pub fn spawn_detached(opts: &DaemonOpts) -> anyhow::Result<u32> {
    use std::io::Read;
    use std::os::unix::process::CommandExt;

    let exe = std::env::current_exe()?;
    let mut fds = [0i32; 2];
    // SAFETY: plain pipe(2) on a valid 2-slot array.
    if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
        return Err(std::io::Error::last_os_error().into());
    }
    let (read_fd, write_fd) = (fds[0], fds[1]);

    let mut cmd = std::process::Command::new(exe);
    cmd.arg("daemon").arg("--foreground");
    if let Some(p) = &opts.profile {
        cmd.arg("--profile").arg(p);
    }
    if let Some(s) = &opts.socket {
        cmd.arg("--socket").arg(s);
    }
    if let Some(i) = opts.idle_exit {
        cmd.arg("--idle-exit").arg(i.as_secs().to_string());
    }
    if opts.allow_legacy_mcp {
        cmd.arg("--allow-legacy-mcp");
    }
    cmd.env("SYNAPS_DAEMON", "1")
        .env(READY_FD_ENV, write_fd.to_string())
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped());
    // SAFETY: pre_exec runs in the forked child before exec; only async-signal-safe calls.
    unsafe {
        cmd.pre_exec(move || {
            libc::close(read_fd);
            // Clear CLOEXEC on the write end so it survives exec.
            let flags = libc::fcntl(write_fd, libc::F_GETFD);
            if flags >= 0 {
                libc::fcntl(write_fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
            }
            libc::setsid();
            Ok(())
        });
    }
    let mut child = cmd.spawn()?;
    // SAFETY: parent no longer needs the write end; closing it makes EOF mean "child died".
    unsafe { libc::close(write_fd) };
    let pid = child.id();

    // Wait for 'R' with a deadline (poll(2) on the read end).
    let mut pfd = libc::pollfd { fd: read_fd, events: libc::POLLIN, revents: 0 };
    let deadline = Instant::now() + SPAWN_READY_TIMEOUT;
    let ready = loop {
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            break false;
        }
        // SAFETY: one valid pollfd.
        let n = unsafe { libc::poll(&mut pfd, 1, left.as_millis() as i32) };
        if n < 0 {
            let e = std::io::Error::last_os_error();
            if e.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            break false;
        }
        if n == 0 {
            break false;
        }
        let mut byte = [0u8; 1];
        // SAFETY: reading one byte into a 1-byte buffer.
        let r = unsafe { libc::read(read_fd, byte.as_mut_ptr() as *mut libc::c_void, 1) };
        break r == 1 && byte[0] == b'R';
    };
    // SAFETY: done with the read end.
    unsafe { libc::close(read_fd) };

    if ready {
        // Keep draining stderr so the child never blocks on a full pipe.
        if let Some(mut err) = child.stderr.take() {
            std::thread::spawn(move || {
                let mut sink = Vec::new();
                let _ = err.read_to_end(&mut sink);
            });
        }
        drop(child);
        return Ok(pid);
    }
    let mut tail = String::new();
    if let Some(mut err) = child.stderr.take() {
        let _ = err.read_to_string(&mut tail);
    }
    // EOF before `R`: the child is gone (or dying) — collect its status. A
    // still-running child that just never signalled is killed.
    let status = child.try_wait().ok().flatten().or_else(|| {
        let _ = child.kill();
        child.wait().ok()
    });
    let reason = tail
        .lines()
        .map(str::trim)
        .rfind(|l| !l.is_empty())
        .map(|l| l.trim_start_matches("synaps daemon: ").to_string());
    match (status, reason) {
        (Some(st), Some(r)) if st.code().is_some() => {
            anyhow::bail!("daemon exited (code {}): {r}", st.code().unwrap_or(-1))
        }
        (_, Some(r)) => anyhow::bail!("daemon did not become ready within {SPAWN_READY_TIMEOUT:?}: {r}"),
        (_, None) => anyhow::bail!("daemon did not become ready within {SPAWN_READY_TIMEOUT:?}"),
    }
}

/// Result of [`ensure_running`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ensured {
    /// A daemon already held the flock.
    Running,
    /// We spawned one (pid) and it signalled ready.
    Spawned(u32),
}

/// Why [`ensure_running`] could not hand back a live daemon.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnsureError {
    /// `SYNAPS_DAEMON_AUTOSPAWN=0` and nobody is running.
    AutospawnDisabled,
    /// The spawn failed or the child refused/died: one-line reason.
    Spawn(String),
}

impl std::fmt::Display for EnsureError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AutospawnDisabled => write!(f, "no daemon running (SYNAPS_DAEMON_AUTOSPAWN=0)"),
            Self::Spawn(r) => write!(f, "{r}"),
        }
    }
}

/// How long a second first-client waits for the spawn lock (the winner's
/// `spawn_detached` is bounded by [`SPAWN_READY_TIMEOUT`]).
const SPAWN_LOCK_WAIT: Duration = SPAWN_READY_TIMEOUT.saturating_add(Duration::from_secs(5));

/// Attach-path entry: a live daemon or a freshly spawned one (jcode model —
/// first client spawns via `setsid` + ready-fd; the daemon holds the flock).
/// The **spawn lock** (`<stem>.spawn.lock` next to the flock) serialises
/// concurrent first-clients: the loser blocks on it, then re-probes the
/// flock and finds the winner's daemon. Never touches the socket on
/// ECONNREFUSED alone — `reap_stale` + the flock decide.
#[cfg(unix)]
pub fn ensure_running(opts: &DaemonOpts) -> Result<Ensured, EnsureError> {
    let paths = opts.paths();
    registry::reap_stale(&paths);
    if registry::is_alive(&paths) {
        return Ok(Ensured::Running);
    }
    if !autospawn_enabled() {
        return Err(EnsureError::AutospawnDisabled);
    }
    let _ = std::fs::create_dir_all(&paths.dir);
    let _guard = registry::SpawnLock::acquire(&paths, SPAWN_LOCK_WAIT)
        .map_err(|e| EnsureError::Spawn(format!("spawn lock {}: {e}", paths.spawn_lock().display())))?;
    // Somebody may have spawned while we waited.
    registry::reap_stale(&paths);
    if registry::is_alive(&paths) {
        return Ok(Ensured::Running);
    }
    // An auto-spawned daemon exits on its own once the last client is gone
    // and no turn is running (parked sessions are journaled; `--continue`
    // brings them back). A daemon started by hand (`synaps daemon`) keeps
    // whatever its caller asked for.
    let mut opts = opts.clone();
    if opts.idle_exit.is_none() {
        opts.idle_exit = autospawn_idle_exit();
    }
    spawn_detached(&opts).map(Ensured::Spawned).map_err(|e| EnsureError::Spawn(e.to_string()))
}

/// `SYNAPS_DAEMON_IDLE_EXIT_SECS` for auto-spawned daemons: default 10 s —
/// when the last client disconnects and no turn is running, the daemon is
/// holding ~100 MB for one reason only: a re-launch inside the window skips
/// extension boot. Ten seconds covers "oops, wrong window"; `0`/`never` →
/// never exit on idle.
pub fn autospawn_idle_exit() -> Option<Duration> {
    // Precedence: env > config (`daemon.idle_exit_secs`) > built-in default.
    let cfg_secs = crate::config::load_config().daemon.idle_exit_secs;
    autospawn_idle_exit_from(
        std::env::var("SYNAPS_DAEMON_IDLE_EXIT_SECS").ok().as_deref(),
        cfg_secs,
    )
}

fn autospawn_idle_exit_from(v: Option<&str>, cfg_secs: u64) -> Option<Duration> {
    // `0` (env or config) disables idle-exit; otherwise config is the default
    // when the env var is absent or unparseable.
    let from_cfg = || (cfg_secs != 0).then(|| Duration::from_secs(cfg_secs));
    match v.map(str::trim) {
        Some("0" | "never" | "off") => None,
        Some(n) => n.parse::<u64>().ok().map(Duration::from_secs).or_else(from_cfg),
        None => from_cfg(),
    }
}

/// Default idle grace for auto-spawned daemons.
pub const AUTOSPAWN_IDLE_EXIT: Duration = Duration::from_secs(10);


/// `synaps daemon --foreground` body: gate → boot host → extension discovery
/// once → start → wait for SIGTERM/SIGINT/Shutdown frame/idle.
pub async fn run_foreground(opts: DaemonOpts) -> anyhow::Result<()> {
    if !enabled() {
        anyhow::bail!("{DISABLED_NOTICE} (exit {EXIT_REFUSED})");
    }
    let host = EngineHost::boot_and_install(crate::HostOpts { profile: opts.profile.clone(), no_extensions: false }).await?;
    if let Some(msg) = legacy_mcp_conflict(&host, opts.allow_legacy_mcp) {
        anyhow::bail!("refusing to start: {msg} (exit {EXIT_REFUSED})");
    }
    // Sidecars spawn once per daemon: discover before accepting (bounded 10 s).
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
    let _loader = crate::extensions::loader::spawn_discover_and_load(Arc::clone(host.ext_manager()), tx, None);
    let wait = async {
        while let Some(ev) = rx.recv().await {
            if let crate::extensions::loader::ExtensionLoaderEvent::Finished { loaded, failed } = ev {
                tracing::info!(loaded = loaded.len(), failed = failed.len(), "daemon: extensions discovered");
                break;
            }
        }
    };
    if tokio::time::timeout(Duration::from_secs(10), wait).await.is_err() {
        tracing::warn!("daemon: extension discovery still running after 10 s; accepting anyway");
    }
    // C3 router: widget.* frames from every sidecar fan out to every live
    // session (daemon-global widgets today — frames carry no session id).
    let _router = crate::extensions::notify_router::spawn_notification_router(Arc::clone(&host));

    let mut opts = opts;
    if opts.factory.is_none() {
        opts.factory = Some(host_factory(&host));
    }
    let daemon = Daemon::start(host, opts).await?;
    let state = Arc::clone(&daemon.state);
    tokio::spawn(async move {
        #[cfg(unix)]
        {
            let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).ok();
            tokio::select! {
                _ = tokio::signal::ctrl_c() => {}
                _ = async { match term.as_mut() { Some(t) => { t.recv().await; } None => std::future::pending::<()>().await } } => {}
                _ = state.shutdown.cancelled() => return,
            }
        }
        #[cfg(not(unix))]
        {
            tokio::select! {
                _ = tokio::signal::ctrl_c() => {}
                _ = state.shutdown.cancelled() => return,
            }
        }
        tracing::info!("daemon: signal received, shutting down");
        state.request_shutdown(false);
    });
    daemon.wait().await;
    Ok(())
}

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

    #[test]
    fn autospawn_idle_exit_defaults_to_10s_and_honours_never() {
        // cfg_secs = 10 mirrors the DaemonConfig default.
        let d = AUTOSPAWN_IDLE_EXIT.as_secs();
        assert_eq!(autospawn_idle_exit_from(None, d), Some(AUTOSPAWN_IDLE_EXIT));
        assert_eq!(AUTOSPAWN_IDLE_EXIT, Duration::from_secs(10));
        assert_eq!(autospawn_idle_exit_from(Some("15"), d), Some(Duration::from_secs(15)));
        assert_eq!(autospawn_idle_exit_from(Some(" 300 "), d), Some(Duration::from_secs(300)));
        for never in ["0", "never", "off"] {
            assert_eq!(autospawn_idle_exit_from(Some(never), d), None, "{never:?}");
        }
        // garbage env → the config default, never "no exit"
        assert_eq!(autospawn_idle_exit_from(Some("soon"), d), Some(AUTOSPAWN_IDLE_EXIT));
        // env absent → config value is the default (env > config > builtin).
        assert_eq!(autospawn_idle_exit_from(None, 42), Some(Duration::from_secs(42)));
        // config 0 disables idle-exit when env is absent.
        assert_eq!(autospawn_idle_exit_from(None, 0), None);
        // env still wins over config.
        assert_eq!(autospawn_idle_exit_from(Some("5"), 42), Some(Duration::from_secs(5)));
    }

    #[test]
    fn enabled_env_matrix() {
        assert!(enabled_from(None), "unset → on");
        for on in ["1", "true", "yes", "on", "", "anything"] {
            assert!(enabled_from(Some(on)), "{on:?} → on");
        }
        for off in ["0", "false", "off", "no", "FALSE", " 0 ", "Off"] {
            assert!(!enabled_from(Some(off)), "{off:?} → off");
        }
    }

    #[test]
    fn env_is_off_is_case_and_space_insensitive() {
        assert!(env_is_off(Some("NO")));
        assert!(!env_is_off(Some("1")));
        assert!(!env_is_off(None));
    }
}