wire/ensure_up.rs
1//! Background-process bootstrapper for the MCP path.
2//!
3//! Post-pair, an agent shouldn't have to ask the user "start the daemon?" —
4//! `wire_pair_confirm` invokes [`ensure_daemon_running`] + [`ensure_notify_running`]
5//! so push/pull and OS toasts are already armed by the time the agent surfaces
6//! "paired ✓" back to chat.
7//!
8//! ## Idempotency
9//!
10//! Each subcommand writes its pid record to `$WIRE_HOME/state/wire/<name>.pid`
11//! on spawn. The next call reads the record and skips spawning if the pid is
12//! still alive. Stale pid files (process died) are silently overwritten.
13//!
14//! ## Pid-file shape (P0.4, 0.5.11)
15//!
16//! The pid file used to be a raw integer (`12345\n`). Today's debug surfaced
17//! a process running an OLD binary text in memory under a current symlink,
18//! and `wire status` had no way to detect that. The pid file is now a
19//! versioned JSON record:
20//!
21//! ```json
22//! {
23//! "schema": "wire-daemon-pid-v1",
24//! "pid": 12345,
25//! "bin_path": "/usr/local/bin/wire",
26//! "version": "0.5.11",
27//! "started_at": "2026-05-16T01:23:45Z",
28//! "did": "did:wire:paul-mac",
29//! "relay_url": "https://wireup.net"
30//! }
31//! ```
32//!
33//! Readers are TOLERANT of the legacy int form for one transition cycle —
34//! `read_daemon_pid` falls through to raw-int parse when JSON decode fails
35//! and reports `version: None` so callers can degrade gracefully.
36//!
37//! ## Wait-until-alive
38//!
39//! On spawn, we wait briefly for the child to be alive before persisting the
40//! pid file. A concurrent CLI seeing the file pointing at a not-yet-bound
41//! PID is the "daemon reports running but can't accept connections" race
42//! spark flagged in our P0.4 design call.
43//!
44//! ## Detachment (Unix)
45//!
46//! Spawned with stdio nulled. Since `wire mcp` runs without a controlling
47//! TTY (it's a stdio MCP server, not a login shell), the spawned children
48//! inherit no TTY → no SIGHUP arrives when the parent exits, so they
49//! survive a Claude Code restart cycle. PIDs are reaped by init.
50//!
51//! Worst case: a child dies; the next `wire_pair_confirm` call respawns it.
52//! No data is lost (outbox/inbox is on disk, content-addressed dedupe).
53
54use std::path::PathBuf;
55use std::process::{Command, Stdio};
56use std::time::{Duration, Instant};
57
58use anyhow::Result;
59use serde::{Deserialize, Serialize};
60use serde_json::Value;
61
62/// Schema string written into every JSON pid file. Bumped if the pid-file
63/// shape ever changes incompatibly. Readers warn on unknown schema.
64pub const DAEMON_PID_SCHEMA: &str = "wire-daemon-pid-v1";
65
66/// Versioned daemon pid record — the JSON form written by 0.5.11+.
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
68pub struct DaemonPid {
69 /// Schema discriminator. Always `wire-daemon-pid-v1` for now.
70 pub schema: String,
71 pub pid: u32,
72 /// Absolute path of the binary that was exec'd. Catches today's exact
73 /// bug: a stale 0.2.4 daemon process kept running under a symlink that
74 /// was repointed at 0.5.10 — `wire --version` says 0.5.10 but the
75 /// running daemon's text in memory is still 0.2.4.
76 pub bin_path: String,
77 /// CARGO_PKG_VERSION captured at spawn. Compared against the CLI's
78 /// own version on every invocation; mismatch = loud warn.
79 pub version: String,
80 /// RFC3339 timestamp of spawn.
81 pub started_at: String,
82 /// Self DID — catches multi-identity contamination (one user, two wire
83 /// identities on same host, daemon launched as wrong one). Cheap
84 /// field, expensive bug.
85 pub did: Option<String>,
86 /// Relay this daemon was bound to at spawn. Catches daemon-bound-to-
87 /// old-relay-after-migration drift.
88 pub relay_url: Option<String>,
89}
90
91/// Result of reading a pid file. Distinguishes legacy-int (no metadata)
92/// from JSON (full metadata) so callers can degrade gracefully.
93#[derive(Debug, Clone)]
94pub enum PidRecord {
95 Json(DaemonPid),
96 LegacyInt(u32),
97 Missing,
98 Corrupt(String),
99}
100
101impl PidRecord {
102 pub fn pid(&self) -> Option<u32> {
103 match self {
104 PidRecord::Json(d) => Some(d.pid),
105 PidRecord::LegacyInt(p) => Some(*p),
106 _ => None,
107 }
108 }
109}
110
111/// Ensure a `wire daemon --interval 5` process is alive. Returns `Ok(true)`
112/// if a fresh process was spawned, `Ok(false)` if one was already running.
113pub fn ensure_daemon_running() -> Result<bool> {
114 ensure_background("daemon", &["daemon", "--interval", "5"])
115}
116
117/// Ensure a `wire notify --interval 2` process is alive (OS toasts on
118/// every new verified inbox event). Returns true if newly spawned.
119pub fn ensure_notify_running() -> Result<bool> {
120 ensure_background("notify", &["notify", "--interval", "2"])
121}
122
123fn pid_file(name: &str) -> Result<PathBuf> {
124 Ok(crate::config::state_dir()?.join(format!("{name}.pid")))
125}
126
127/// Snapshot of daemon liveness state read through ONE consistent
128/// view. Consumed by `wire status`, `wire doctor`'s `daemon` check,
129/// and `daemon_pid_consistency` so all three surfaces agree by
130/// construction — issue #2 root cause was three call sites that
131/// each computed liveness independently and disagreed for 25 min.
132#[derive(Debug, Clone)]
133pub struct DaemonLiveness {
134 /// PID claimed by `daemon.pid` (None if missing/corrupt).
135 pub pidfile_pid: Option<u32>,
136 /// True iff `pidfile_pid` is currently a live process.
137 pub pidfile_alive: bool,
138 /// Every PID matching `pgrep -f "wire daemon"`. Empty if pgrep is
139 /// unavailable (non-Unix systems, missing util) — the consumer
140 /// must not treat empty as "no daemons" without considering this.
141 pub pgrep_pids: Vec<u32>,
142 /// PIDs in `pgrep_pids` that do NOT match `pidfile_pid`. These are
143 /// orphan daemons racing the cursor with the pidfile-recorded one.
144 pub orphan_pids: Vec<u32>,
145 /// Full parsed pidfile record (Json / LegacyInt / Missing / Corrupt).
146 pub record: PidRecord,
147}
148
149/// True iff `pid` is currently a live OS process. Delegates to the
150/// platform-aware check (`/proc` on Linux, `kill -0` on other Unix,
151/// `tasklist` on Windows) so callers never disagree across OSes. The old
152/// local `kill -0` path false-negatived on Windows (no `kill`), making
153/// `wire status`/`doctor` report the daemon DOWN while it was alive.
154pub fn pid_is_alive(pid: u32) -> bool {
155 crate::platform::process_alive(pid)
156}
157
158/// Read the daemon pid file + pgrep in one shot, producing a snapshot
159/// every caller can interpret identically. The point of this helper
160/// is that three independent callers used to compute liveness three
161/// different ways (#2): pidfile-pid-alive (cmd_status), pgrep-only
162/// (early check_daemon_health), neither (check_daemon_pid_consistency).
163/// Now all three flow through the same `DaemonLiveness`.
164pub fn daemon_liveness() -> DaemonLiveness {
165 let record = read_pid_record("daemon");
166 let pidfile_pid = record.pid();
167 let pidfile_alive = pidfile_pid.map(pid_is_alive).unwrap_or(false);
168 // Platform-aware cmdline scan (Unix `pgrep`, Windows PowerShell CIM).
169 // Field stays named `pgrep_pids` for callers; on Windows the old direct
170 // `pgrep` shell-out returned empty (no such tool), masking live daemons.
171 let pgrep_pids: Vec<u32> = crate::platform::find_processes_by_cmdline("wire daemon");
172 // A2 (v0.13.2): on a multi-session box EVERY session runs its own daemon,
173 // so the old "any `wire daemon` whose pid != my pidfile = orphan" rule
174 // flagged sibling sessions' LEGITIMATE daemons as orphans — `wire doctor`
175 // FAILed on the very multi-agent-per-box setup wire exists for. A true
176 // orphan is a wire daemon owned by NO session: exclude every session's
177 // pidfile pid, not just this session's.
178 let known_session_pids: std::collections::HashSet<u32> = crate::session::list_sessions()
179 .map(|sessions| {
180 sessions
181 .iter()
182 .filter_map(|s| crate::session::session_daemon_pid(&s.home_dir))
183 .collect()
184 })
185 .unwrap_or_default();
186 let orphan_pids: Vec<u32> = pgrep_pids
187 .iter()
188 .filter(|p| Some(**p) != pidfile_pid && !known_session_pids.contains(*p))
189 .copied()
190 .collect();
191 DaemonLiveness {
192 pidfile_pid,
193 pidfile_alive,
194 pgrep_pids,
195 orphan_pids,
196 record,
197 }
198}
199
200/// Read a pid file, tolerating both JSON and legacy-int forms. Never
201/// panics — corrupt input becomes `PidRecord::Corrupt`.
202pub fn read_pid_record(name: &str) -> PidRecord {
203 let path = match pid_file(name) {
204 Ok(p) => p,
205 Err(_) => return PidRecord::Missing,
206 };
207 let body = match std::fs::read_to_string(&path) {
208 Ok(b) => b,
209 Err(_) => return PidRecord::Missing,
210 };
211 let trimmed = body.trim();
212 if trimmed.is_empty() {
213 return PidRecord::Missing;
214 }
215 // JSON form first.
216 if trimmed.starts_with('{') {
217 match serde_json::from_str::<DaemonPid>(trimmed) {
218 Ok(d) => return PidRecord::Json(d),
219 Err(e) => return PidRecord::Corrupt(format!("JSON parse: {e}")),
220 }
221 }
222 // Legacy raw-int form — keep readable for one transition cycle so a
223 // 0.5.11 daemon can take over from a 0.5.10 leftover without
224 // operator intervention.
225 match trimmed.parse::<u32>() {
226 Ok(pid) => PidRecord::LegacyInt(pid),
227 Err(e) => PidRecord::Corrupt(format!("expected int or JSON: {e}")),
228 }
229}
230
231/// Write a JSON pid record. P0.4: replaces the raw-int write.
232fn write_pid_record(name: &str, record: &DaemonPid) -> Result<()> {
233 let path = pid_file(name)?;
234 let body = serde_json::to_vec_pretty(record)?;
235 std::fs::write(&path, body)?;
236 Ok(())
237}
238
239/// Build a `DaemonPid` for a freshly-spawned child. Reads bin_path,
240/// current binary version, identity DID, and bound relay URL.
241fn build_pid_record(pid: u32) -> DaemonPid {
242 let bin_path = std::env::current_exe()
243 .map(|p| p.to_string_lossy().to_string())
244 .unwrap_or_default();
245 let version = env!("CARGO_PKG_VERSION").to_string();
246 let started_at = time::OffsetDateTime::now_utc()
247 .format(&time::format_description::well_known::Rfc3339)
248 .unwrap_or_default();
249 let (did, relay_url) = identity_for_pid_record();
250 DaemonPid {
251 schema: DAEMON_PID_SCHEMA.to_string(),
252 pid,
253 bin_path,
254 version,
255 started_at,
256 did,
257 relay_url,
258 }
259}
260
261/// Best-effort: pull DID + relay_url from the configured identity. None
262/// fields are written as `null` so the file stays well-formed even before
263/// the operator runs `wire init`.
264fn identity_for_pid_record() -> (Option<String>, Option<String>) {
265 let did = crate::config::read_agent_card()
266 .ok()
267 .and_then(|card| card.get("did").and_then(Value::as_str).map(str::to_string));
268 let relay_url = crate::config::read_relay_state().ok().and_then(|state| {
269 state
270 .get("self")
271 .and_then(|s| s.get("relay_url"))
272 .and_then(Value::as_str)
273 .map(str::to_string)
274 });
275 (did, relay_url)
276}
277
278/// Wait briefly for `process_alive(pid)` to be true. Returns true if the
279/// child went live within the budget. Default budget is 500ms — enough for
280/// std::process::Command::spawn to fork + exec on any reasonable platform.
281fn wait_until_alive(pid: u32, budget: Duration) -> bool {
282 let deadline = Instant::now() + budget;
283 while Instant::now() < deadline {
284 if process_alive(pid) {
285 return true;
286 }
287 std::thread::sleep(Duration::from_millis(10));
288 }
289 process_alive(pid)
290}
291
292fn ensure_background(name: &str, args: &[&str]) -> Result<bool> {
293 // Test escape hatch — tests/mcp_pair.rs spawns wire mcp with this env
294 // var set so wire_pair_confirm doesn't fork persistent daemon/notify
295 // processes that survive the test's temp WIRE_HOME.
296 if std::env::var("WIRE_MCP_SKIP_AUTO_UP").is_ok() {
297 return Ok(false);
298 }
299
300 // Skip spawn if existing pid is still alive.
301 if let Some(pid) = read_pid_record(name).pid()
302 && process_alive(pid)
303 {
304 return Ok(false);
305 }
306
307 crate::config::ensure_dirs()?;
308 let exe = std::env::current_exe()?;
309 let child = Command::new(&exe)
310 .args(args)
311 .stdin(Stdio::null())
312 .stdout(Stdio::null())
313 .stderr(Stdio::null())
314 .spawn()?;
315
316 // P0.4: wait until the child is actually alive before persisting the
317 // pid file. Otherwise a concurrent CLI sees the file pointing at a
318 // PID that isn't yet bound to anything — "daemon reports running but
319 // can't accept connections" race.
320 let pid = child.id();
321 if !wait_until_alive(pid, Duration::from_millis(500)) {
322 anyhow::bail!(
323 "spawned `wire {}` (pid {pid}) did not appear alive within 500ms",
324 args.join(" ")
325 );
326 }
327
328 let record = build_pid_record(pid);
329 write_pid_record(name, &record)?;
330 Ok(true)
331}
332
333/// Check the running daemon's version against the CLI's CARGO_PKG_VERSION.
334/// Returns Some(stale_version) if they disagree, None if they match (or no
335/// daemon, or legacy-int pidfile without version info).
336///
337/// Called by `wire status` + `wire doctor`. The intent is loud, non-fatal
338/// warning — don't BLOCK CLI invocations on version mismatch (operator may
339/// be running a one-shot debug while daemon is old), but DO make it
340/// impossible to miss.
341pub fn daemon_version_mismatch() -> Option<String> {
342 let record = read_pid_record("daemon");
343 let pid = record.pid()?;
344 if !process_alive(pid) {
345 return None;
346 }
347 match record {
348 PidRecord::Json(d) => {
349 if d.version != env!("CARGO_PKG_VERSION") {
350 Some(d.version)
351 } else {
352 None
353 }
354 }
355 PidRecord::LegacyInt(_) => {
356 // Legacy pidfile = pre-0.5.11 daemon writing raw int. By
357 // definition older than this CLI, so flag it.
358 Some("<pre-0.5.11>".to_string())
359 }
360 _ => None,
361 }
362}
363
364fn process_alive(pid: u32) -> bool {
365 crate::platform::process_alive(pid)
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 #[test]
373 fn process_alive_self() {
374 assert!(process_alive(std::process::id()));
375 }
376
377 #[test]
378 fn process_alive_zero_is_false_or_self() {
379 assert!(!process_alive(99_999_999));
380 }
381
382 #[test]
383 fn pid_record_round_trips_via_json_form() {
384 // P0.4 contract: a record written by 0.5.11 must be readable by
385 // 0.5.11. If serde gets out of sync with the file format, every
386 // single CLI invocation breaks silently.
387 crate::config::test_support::with_temp_home(|| {
388 crate::config::ensure_dirs().unwrap();
389 let record = DaemonPid {
390 schema: DAEMON_PID_SCHEMA.to_string(),
391 pid: 12345,
392 bin_path: "/usr/local/bin/wire".to_string(),
393 version: "0.5.11".to_string(),
394 started_at: "2026-05-16T01:23:45Z".to_string(),
395 did: Some("did:wire:paul-mac".to_string()),
396 relay_url: Some("https://wireup.net".to_string()),
397 };
398 write_pid_record("daemon", &record).unwrap();
399 let read = read_pid_record("daemon");
400 match read {
401 PidRecord::Json(d) => assert_eq!(d, record),
402 other => panic!("expected JSON record, got {other:?}"),
403 }
404 });
405 }
406
407 #[test]
408 fn pid_record_tolerates_legacy_int_form() {
409 // The whole point of LegacyInt: a 0.5.11 daemon must be able to
410 // take over from a 0.5.10 leftover without operator intervention.
411 // If this assertion fails, every operator with a 0.5.10 daemon
412 // running has to manually delete their pidfile on upgrade.
413 crate::config::test_support::with_temp_home(|| {
414 crate::config::ensure_dirs().unwrap();
415 let path = super::pid_file("daemon").unwrap();
416 std::fs::write(&path, "98765").unwrap();
417 let read = read_pid_record("daemon");
418 match read {
419 PidRecord::LegacyInt(pid) => assert_eq!(pid, 98765),
420 other => panic!("expected LegacyInt, got {other:?}"),
421 }
422 });
423 }
424
425 #[test]
426 fn pid_record_corrupt_reports_corrupt_not_panic() {
427 // Today's debug had a stale pidfile pointing at a dead PID. The
428 // reader was tolerant. A future bug might write garbage; the reader
429 // must not panic — it must report Corrupt so wire doctor can
430 // surface it visibly.
431 crate::config::test_support::with_temp_home(|| {
432 crate::config::ensure_dirs().unwrap();
433 let path = super::pid_file("daemon").unwrap();
434 std::fs::write(&path, "not-a-pid-or-json {{{").unwrap();
435 let read = read_pid_record("daemon");
436 assert!(matches!(read, PidRecord::Corrupt(_)), "got {read:?}");
437 });
438 }
439
440 #[test]
441 fn daemon_version_mismatch_returns_none_when_no_pidfile() {
442 crate::config::test_support::with_temp_home(|| {
443 assert_eq!(daemon_version_mismatch(), None);
444 });
445 }
446}