Skip to main content

winx_code_agent/daemon/
control.rs

1use std::collections::HashMap;
2use std::io::ErrorKind;
3use std::os::unix::fs::MetadataExt;
4use std::os::unix::fs::PermissionsExt;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8
9use tokio::net::{UnixListener, UnixStream};
10use tokio::sync::Mutex;
11
12use super::lifecycle::{GuardianLifecycle, GuardianLimits};
13use super::protocol::{
14    read_json_frame, write_json_frame, CancelActionParams, ConfigureSessionParams,
15    DaemonProcessRole, HelloResult, JournalReadParams, PruneParams, RpcError, RpcRequest,
16    RpcResponse, RunActionParams, SessionInfo, SessionParams,
17    CANCELLABLE_ACTION_RESERVATIONS_CAPABILITY, COMPACT_ACTION_OUTPUT_CAPABILITY,
18    GENERATION_BOUND_ACTIONS_CAPABILITY, PROTOCOL_MAJOR, TYPED_ACTION_RESULT_CAPABILITY,
19};
20use crate::errors::{Result, WinxError};
21use crate::types::normalize_thread_id;
22
23/// Stable control plane. Each logical session is owned by a separate guardian
24/// process, so restarting this process does not close any PTY master.
25pub struct ControlServer {
26    listener: UnixListener,
27    socket_path: PathBuf,
28    lifecycle: Arc<GuardianLifecycle>,
29    guardian_capabilities: Arc<Mutex<HashMap<PathBuf, CachedGuardian>>>,
30    guardian_negotiation_gates: Arc<Mutex<HashMap<PathBuf, GuardianNegotiationGate>>>,
31    epoch: String,
32}
33
34#[derive(Clone)]
35struct CachedGuardian {
36    hello: HelloResult,
37    last_seen: Instant,
38    socket_identity: Option<SocketIdentity>,
39}
40
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42struct SocketIdentity {
43    device: u64,
44    inode: u64,
45    ctime_seconds: i64,
46    ctime_nanoseconds: i64,
47    mtime_seconds: i64,
48    mtime_nanoseconds: i64,
49}
50
51struct GuardianNegotiationGate {
52    gate: Arc<Mutex<()>>,
53    last_seen: Instant,
54}
55
56const MAX_GUARDIAN_NEGOTIATIONS: usize = 256;
57const GUARDIAN_NEGOTIATION_TTL: Duration = Duration::from_secs(5 * 60);
58
59impl ControlServer {
60    pub async fn bind(socket_path: impl AsRef<Path>) -> Result<Self> {
61        let socket_path = socket_path.as_ref().to_path_buf();
62        let parent = socket_path.parent().ok_or_else(|| {
63            WinxError::ConfigurationError("daemon socket must have a parent directory".to_string())
64        })?;
65        tokio::fs::create_dir_all(parent).await?;
66        tokio::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).await?;
67        let guardian_dir = parent.join("guardians");
68        tokio::fs::create_dir_all(&guardian_dir).await?;
69        tokio::fs::set_permissions(&guardian_dir, std::fs::Permissions::from_mode(0o700)).await?;
70
71        if tokio::fs::try_exists(&socket_path).await? {
72            if UnixStream::connect(&socket_path).await.is_ok() {
73                return Err(WinxError::ConfigurationError(format!(
74                    "a winxd instance is already listening at {}",
75                    socket_path.display()
76                )));
77            }
78            tokio::fs::remove_file(&socket_path).await?;
79        }
80        let listener = UnixListener::bind(&socket_path)?;
81        tokio::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600)).await?;
82        let lifecycle = Arc::new(GuardianLifecycle::new(
83            guardian_dir,
84            guardian_binary()?,
85            GuardianLimits::from_env()?,
86        ));
87
88        Ok(Self {
89            listener,
90            socket_path,
91            lifecycle,
92            guardian_capabilities: Arc::new(Mutex::new(HashMap::new())),
93            guardian_negotiation_gates: Arc::new(Mutex::new(HashMap::new())),
94            epoch: format!("{:016x}", rand::random::<u64>()),
95        })
96    }
97
98    pub async fn serve(self) -> Result<()> {
99        self.lifecycle.clone().spawn_sweeper();
100        loop {
101            let (stream, _) = self.listener.accept().await?;
102            if !same_uid(&stream)? {
103                tracing::warn!("Rejected winxd control connection from a different uid");
104                continue;
105            }
106            let lifecycle = self.lifecycle.clone();
107            let guardian_capabilities = self.guardian_capabilities.clone();
108            let guardian_negotiation_gates = self.guardian_negotiation_gates.clone();
109            let epoch = self.epoch.clone();
110            tokio::spawn(async move {
111                if let Err(error) = serve_connection(
112                    stream,
113                    lifecycle,
114                    guardian_capabilities,
115                    guardian_negotiation_gates,
116                    epoch,
117                )
118                .await
119                {
120                    tracing::debug!("winxd control client disconnected: {error}");
121                }
122            });
123        }
124    }
125}
126
127impl Drop for ControlServer {
128    fn drop(&mut self) {
129        let _ = std::fs::remove_file(&self.socket_path);
130    }
131}
132
133async fn serve_connection(
134    mut stream: UnixStream,
135    lifecycle: Arc<GuardianLifecycle>,
136    guardian_capabilities: Arc<Mutex<HashMap<PathBuf, CachedGuardian>>>,
137    guardian_negotiation_gates: Arc<Mutex<HashMap<PathBuf, GuardianNegotiationGate>>>,
138    epoch: String,
139) -> Result<()> {
140    loop {
141        let request: RpcRequest = match read_json_frame(&mut stream).await {
142            Ok(request) => request,
143            Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(()),
144            Err(error) => return Err(error.into()),
145        };
146        let response = dispatch(
147            request,
148            &lifecycle,
149            &guardian_capabilities,
150            &guardian_negotiation_gates,
151            &epoch,
152        )
153        .await;
154        write_json_frame(&mut stream, &response).await?;
155    }
156}
157
158#[allow(clippy::too_many_lines)]
159async fn dispatch(
160    mut request: RpcRequest,
161    lifecycle: &GuardianLifecycle,
162    guardian_capabilities: &Mutex<HashMap<PathBuf, CachedGuardian>>,
163    guardian_negotiation_gates: &Mutex<HashMap<PathBuf, GuardianNegotiationGate>>,
164    epoch: &str,
165) -> RpcResponse {
166    if request.jsonrpc != "2.0" {
167        return rpc_error(request.id, -32600, "JSON-RPC version must be 2.0");
168    }
169    if request.method == "winx.hello" {
170        return rpc_result(
171            request.id,
172            &HelloResult::current(
173                DaemonProcessRole::Control,
174                vec![
175                    "per_session_guardians".to_string(),
176                    "planned_control_restart".to_string(),
177                    "guardian_quota".to_string(),
178                    "guardian_idle_ttl".to_string(),
179                    "guardian_activity_clock".to_string(),
180                    "unused_session_ttl".to_string(),
181                    "quota_reclaims_unused".to_string(),
182                    "session.configure".to_string(),
183                    "session.negotiate".to_string(),
184                    "shell.run_action".to_string(),
185                    TYPED_ACTION_RESULT_CAPABILITY.to_string(),
186                    COMPACT_ACTION_OUTPUT_CAPABILITY.to_string(),
187                    GENERATION_BOUND_ACTIONS_CAPABILITY.to_string(),
188                    CANCELLABLE_ACTION_RESERVATIONS_CAPABILITY.to_string(),
189                    "session.list".to_string(),
190                    "session.read_output".to_string(),
191                    "session.kill".to_string(),
192                    "session.prune".to_string(),
193                    "multi_consumer_cursors".to_string(),
194                    "idempotency".to_string(),
195                ],
196                epoch,
197            ),
198        );
199    }
200
201    if request.method == "session.list" {
202        return match list_sessions(lifecycle.guardian_dir()).await {
203            Ok(sessions) => rpc_result(request.id, &sessions),
204            Err(error) => rpc_error(request.id, -32000, &error.to_string()),
205        };
206    }
207
208    if request.method == "session.prune" {
209        let params = match decode::<PruneParams>(request.params) {
210            Ok(params) => params,
211            Err(error) => return rpc_error(request.id, -32602, &error.to_string()),
212        };
213        return match lifecycle.prune(params.idle_seconds).await {
214            Ok(result) => {
215                let mut cache = guardian_capabilities.lock().await;
216                for thread_id in &result.removed_thread_ids {
217                    cache.remove(&lifecycle.socket_for(thread_id));
218                }
219                rpc_result(request.id, &result)
220            }
221            Err(error) => rpc_error(request.id, -32003, &error.to_string()),
222        };
223    }
224
225    let thread_id = match request_thread_id(&request) {
226        Ok(thread_id) if !thread_id.is_empty() => thread_id,
227        Ok(_) => return rpc_error(request.id, -32602, "explicit thread_id is required"),
228        Err(error) => return rpc_error(request.id, -32602, &error.to_string()),
229    };
230    let guardian_socket = lifecycle.socket_for(&thread_id);
231    if request.method == "session.negotiate" {
232        return match negotiated_guardian(
233            lifecycle,
234            guardian_capabilities,
235            guardian_negotiation_gates,
236            &thread_id,
237            &guardian_socket,
238            true,
239        )
240        .await
241        {
242            Ok(hello) => rpc_result(request.id, &hello),
243            Err(error) => rpc_error(request.id, -32001, &error.to_string()),
244        };
245    }
246    if request.method == "session.kill" {
247        match tokio::fs::try_exists(&guardian_socket).await {
248            Ok(true) => {}
249            Ok(false) => return rpc_result(request.id, &false),
250            Err(error) => return rpc_error(request.id, -32002, &error.to_string()),
251        }
252    }
253
254    let create_if_missing =
255        matches!(request.method.as_str(), "session.configure" | "shell.run_action");
256    let mut hello = match negotiated_guardian(
257        lifecycle,
258        guardian_capabilities,
259        guardian_negotiation_gates,
260        &thread_id,
261        &guardian_socket,
262        create_if_missing,
263    )
264    .await
265    {
266        Ok(hello) => hello,
267        Err(error) => return rpc_error(request.id, -32001, &error.to_string()),
268    };
269    let live_precondition = match request_requires_live_guardian(&request) {
270        Ok(required) => required,
271        Err(error) => return rpc_error(request.id, -32602, &error.to_string()),
272    };
273    if !live_precondition {
274        if let Err(error) = normalize_guardian_request(&mut request, &hello) {
275            return rpc_error(request.id, -32602, &error.to_string());
276        }
277    }
278    let kill_after = request.method == "session.kill";
279    let request_id = request.id;
280    let response = if live_precondition {
281        match relay(&guardian_socket, request.clone()).await {
282            Ok((response, effective)) => {
283                hello = effective.clone();
284                cache_guardian(guardian_capabilities, guardian_socket.clone(), effective).await;
285                response
286            }
287            Err(error) => {
288                guardian_capabilities.lock().await.remove(&guardian_socket);
289                return rpc_error(request_id, -32602, &error.to_string());
290            }
291        }
292    } else {
293        match relay_negotiated(&guardian_socket, request.clone(), &hello).await {
294            Ok(result) => result,
295            Err(first_error) => {
296                guardian_capabilities.lock().await.remove(&guardian_socket);
297                let refreshed = match negotiated_guardian(
298                    lifecycle,
299                    guardian_capabilities,
300                    guardian_negotiation_gates,
301                    &thread_id,
302                    &guardian_socket,
303                    create_if_missing,
304                )
305                .await
306                {
307                    Ok(hello) => hello,
308                    Err(error) => {
309                        return rpc_error(
310                            request_id,
311                            -32002,
312                            &format!("{first_error}; guardian renegotiation failed: {error}"),
313                        )
314                    }
315                };
316                if request.method == "shell.run_action"
317                    && refreshed.daemon_epoch != hello.daemon_epoch
318                {
319                    return rpc_error(
320                    request_id,
321                    -32002,
322                    &format!(
323                        "{first_error}; guardian epoch changed, so winxd will not retry an ambiguously delivered shell action"
324                    ),
325                );
326                }
327                if let Err(error) = normalize_guardian_request(&mut request, &refreshed) {
328                    return rpc_error(request_id, -32602, &error.to_string());
329                }
330                match relay_negotiated(&guardian_socket, request, &refreshed).await {
331                    Ok(result) => {
332                        hello = refreshed;
333                        result
334                    }
335                    Err(error) => return rpc_error(request_id, -32002, &error.to_string()),
336                }
337            }
338        }
339    };
340
341    if kill_after && response.error.is_none() {
342        guardian_capabilities.lock().await.remove(&guardian_socket);
343        if let Err(error) = lifecycle.finish_kill(&guardian_socket, hello.daemon_pid).await {
344            return rpc_error(
345                request_id,
346                -32003,
347                &format!("session state was removed, but guardian cleanup failed: {error}"),
348            );
349        }
350    } else {
351        lifecycle.note_activity(&guardian_socket, &thread_id, hello.daemon_pid).await;
352    }
353    response
354}
355
356fn request_thread_id(request: &RpcRequest) -> Result<String> {
357    let thread_id = match request.method.as_str() {
358        "session.configure" => {
359            decode::<ConfigureSessionParams>(request.params.clone())?.snapshot.chat_id
360        }
361        "shell.run_action" => decode::<RunActionParams>(request.params.clone())?.command.thread_id,
362        "shell.cancel_action" => decode::<CancelActionParams>(request.params.clone())?.thread_id,
363        "session.read_output" => decode::<JournalReadParams>(request.params.clone())?.thread_id,
364        "session.negotiate" | "session.info" | "session.kill" | "session.interrupt" => {
365            decode::<SessionParams>(request.params.clone())?.thread_id
366        }
367        _ => {
368            return Err(WinxError::InvalidInput(format!(
369                "unsupported control method {}",
370                request.method
371            )))
372        }
373    };
374    Ok(normalize_thread_id(&thread_id))
375}
376
377async fn negotiated_guardian(
378    lifecycle: &GuardianLifecycle,
379    cache: &Mutex<HashMap<PathBuf, CachedGuardian>>,
380    gates: &Mutex<HashMap<PathBuf, GuardianNegotiationGate>>,
381    thread_id: &str,
382    socket: &Path,
383    create_if_missing: bool,
384) -> Result<HelloResult> {
385    if let Some(hello) = cached_guardian(cache, socket).await {
386        return Ok(hello);
387    }
388    let negotiation_gate = guardian_negotiation_gate(gates, socket).await?;
389    let _single_flight = negotiation_gate.lock().await;
390    if let Some(hello) = cached_guardian(cache, socket).await {
391        return Ok(hello);
392    }
393    if !create_if_missing && !tokio::fs::try_exists(socket).await? {
394        return Err(WinxError::ShellInitializationError(format!(
395            "guardian at {} is unavailable",
396            socket.display()
397        )));
398    }
399    let hello = lifecycle.ensure_guardian(thread_id, socket).await?;
400    cache_guardian(cache, socket.to_path_buf(), hello.clone()).await;
401    Ok(hello)
402}
403
404async fn cached_guardian(
405    cache: &Mutex<HashMap<PathBuf, CachedGuardian>>,
406    socket: &Path,
407) -> Option<HelloResult> {
408    let socket_identity = socket_identity(socket).await;
409    let now = Instant::now();
410    let mut cache = cache.lock().await;
411    prune_guardian_cache(&mut cache, now);
412    if let Some(entry) = cache
413        .get_mut(socket)
414        .filter(|entry| socket_identity.is_some() && entry.socket_identity == socket_identity)
415    {
416        entry.last_seen = now;
417        return Some(entry.hello.clone());
418    }
419    cache.remove(socket);
420    None
421}
422
423fn prune_guardian_cache(cache: &mut HashMap<PathBuf, CachedGuardian>, now: Instant) {
424    cache.retain(|_, entry| now.duration_since(entry.last_seen) <= GUARDIAN_NEGOTIATION_TTL);
425}
426
427async fn guardian_negotiation_gate(
428    gates: &Mutex<HashMap<PathBuf, GuardianNegotiationGate>>,
429    socket: &Path,
430) -> Result<Arc<Mutex<()>>> {
431    let now = Instant::now();
432    let mut gates = gates.lock().await;
433    gates.retain(|_, entry| {
434        now.duration_since(entry.last_seen) <= GUARDIAN_NEGOTIATION_TTL
435            || Arc::strong_count(&entry.gate) > 1
436    });
437    if let Some(entry) = gates.get_mut(socket) {
438        entry.last_seen = now;
439        return Ok(Arc::clone(&entry.gate));
440    }
441    if gates.len() >= MAX_GUARDIAN_NEGOTIATIONS {
442        let oldest = gates
443            .iter()
444            .filter(|(_, entry)| Arc::strong_count(&entry.gate) == 1)
445            .min_by_key(|(_, entry)| entry.last_seen)
446            .map(|(path, _)| path.clone());
447        if let Some(oldest) = oldest {
448            gates.remove(&oldest);
449        }
450    }
451    if gates.len() >= MAX_GUARDIAN_NEGOTIATIONS {
452        return Err(WinxError::ResourceAllocationError {
453            message: format!(
454                "all {MAX_GUARDIAN_NEGOTIATIONS} guardian negotiation slots are active"
455            ),
456        });
457    }
458    let gate = Arc::new(Mutex::new(()));
459    gates.insert(
460        socket.to_path_buf(),
461        GuardianNegotiationGate { gate: Arc::clone(&gate), last_seen: now },
462    );
463    Ok(gate)
464}
465
466async fn cache_guardian(
467    cache: &Mutex<HashMap<PathBuf, CachedGuardian>>,
468    socket: PathBuf,
469    hello: HelloResult,
470) {
471    // Read filesystem identity before taking the global cache mutex. Besides
472    // avoiding I/O under the lock, this makes an unlinked/recreated guardian
473    // socket invalidate the old epoch immediately instead of waiting for TTL.
474    let socket_identity = socket_identity(&socket).await;
475    let now = Instant::now();
476    let mut cache = cache.lock().await;
477    prune_guardian_cache(&mut cache, now);
478    if !cache.contains_key(&socket) && cache.len() >= MAX_GUARDIAN_NEGOTIATIONS {
479        if let Some(oldest) =
480            cache.iter().min_by_key(|(_, entry)| entry.last_seen).map(|(path, _)| path.clone())
481        {
482            cache.remove(&oldest);
483        }
484    }
485    cache.insert(socket, CachedGuardian { hello, last_seen: now, socket_identity });
486}
487
488async fn socket_identity(socket: &Path) -> Option<SocketIdentity> {
489    tokio::fs::metadata(socket).await.ok().map(|metadata| SocketIdentity {
490        device: metadata.dev(),
491        inode: metadata.ino(),
492        ctime_seconds: metadata.ctime(),
493        ctime_nanoseconds: metadata.ctime_nsec(),
494        mtime_seconds: metadata.mtime(),
495        mtime_nanoseconds: metadata.mtime_nsec(),
496    })
497}
498
499fn normalize_guardian_request(request: &mut RpcRequest, hello: &HelloResult) -> Result<()> {
500    let has = |capability: &str| hello.capabilities.iter().any(|candidate| candidate == capability);
501    if request.method == "shell.run_action" {
502        let mut params = decode::<RunActionParams>(request.params.clone())?;
503        if !has(TYPED_ACTION_RESULT_CAPABILITY) {
504            return Err(WinxError::ConfigurationError(format!(
505                "guardian pid {} does not advertise {TYPED_ACTION_RESULT_CAPABILITY}; terminate this durable session and initialize it again before running another BashCommand",
506                hello.daemon_pid
507            )));
508        }
509        if params
510            .options
511            .expected_guardian_epoch
512            .as_deref()
513            .is_some_and(|expected| expected != hello.daemon_epoch)
514            || params
515                .options
516                .expected_execution
517                .as_ref()
518                .is_some_and(|expected| expected.guardian_epoch != hello.daemon_epoch)
519        {
520            return Err(WinxError::InvalidInput(
521                "shell action precondition refers to a different effective guardian epoch"
522                    .to_string(),
523            ));
524        }
525        if (params.options.expected_generation.is_some()
526            || params.options.expected_execution.is_some()
527            || params.options.require_generation_binding)
528            && !has(GENERATION_BOUND_ACTIONS_CAPABILITY)
529        {
530            return Err(WinxError::InvalidInput(
531                "the running guardian does not support generation-bound shell actions".to_string(),
532            ));
533        }
534        if params.options.cancellation_key.is_some()
535            && !has(CANCELLABLE_ACTION_RESERVATIONS_CAPABILITY)
536        {
537            return Err(WinxError::InvalidInput(
538                "the running guardian does not support cancellable action reservations".to_string(),
539            ));
540        }
541        if !has(COMPACT_ACTION_OUTPUT_CAPABILITY) {
542            params.options.compact_output = false;
543        }
544        request.params = serde_json::to_value(params)
545            .map_err(|error| WinxError::SerializationError(error.to_string()))?;
546    } else if request.method == "session.interrupt" {
547        let params = decode::<SessionParams>(request.params.clone())?;
548        if params
549            .expected_guardian_epoch
550            .as_deref()
551            .is_some_and(|expected| expected != hello.daemon_epoch)
552            || params
553                .expected_execution
554                .as_ref()
555                .is_some_and(|expected| expected.guardian_epoch != hello.daemon_epoch)
556        {
557            return Err(WinxError::InvalidInput(
558                "interrupt precondition refers to a different effective guardian epoch".to_string(),
559            ));
560        }
561        if (params.expected_generation.is_some() || params.expected_execution.is_some())
562            && !has(GENERATION_BOUND_ACTIONS_CAPABILITY)
563        {
564            return Err(WinxError::InvalidInput(
565                "the running guardian does not support generation-bound interruption".to_string(),
566            ));
567        }
568    } else if request.method == "shell.cancel_action" {
569        let params = decode::<CancelActionParams>(request.params.clone())?;
570        if !has(CANCELLABLE_ACTION_RESERVATIONS_CAPABILITY) {
571            return Err(WinxError::InvalidInput(
572                "the running guardian does not support cancellable action reservations".to_string(),
573            ));
574        }
575        if params
576            .expected_guardian_epoch
577            .as_deref()
578            .is_some_and(|expected| expected != hello.daemon_epoch)
579        {
580            return Err(WinxError::InvalidInput(
581                "cancel precondition refers to a different effective guardian epoch".to_string(),
582            ));
583        }
584    }
585    Ok(())
586}
587
588fn request_requires_live_guardian(request: &RpcRequest) -> Result<bool> {
589    match request.method.as_str() {
590        "shell.run_action" => {
591            let params = decode::<RunActionParams>(request.params.clone())?;
592            Ok(params.options.require_generation_binding
593                || params.options.expected_generation.is_some()
594                || params.options.expected_execution.is_some()
595                || params.options.expected_guardian_epoch.is_some()
596                || params.options.cancellation_key.is_some())
597        }
598        "session.interrupt" => {
599            let params = decode::<SessionParams>(request.params.clone())?;
600            Ok(params.expected_generation.is_some()
601                || params.expected_execution.is_some()
602                || params.expected_guardian_epoch.is_some())
603        }
604        "shell.cancel_action" => Ok(true),
605        _ => Ok(false),
606    }
607}
608
609async fn relay(socket: &Path, mut request: RpcRequest) -> Result<(RpcResponse, HelloResult)> {
610    let mut stream = UnixStream::connect(socket).await.map_err(|error| {
611        WinxError::ShellInitializationError(format!(
612            "guardian at {} is unavailable: {error}",
613            socket.display()
614        ))
615    })?;
616    let hello_id = rand::random::<u64>();
617    write_json_frame(
618        &mut stream,
619        &RpcRequest {
620            jsonrpc: "2.0".to_string(),
621            id: hello_id,
622            method: "winx.hello".to_string(),
623            params: serde_json::json!({ "protocol_major": PROTOCOL_MAJOR }),
624        },
625    )
626    .await?;
627    let hello_response: RpcResponse = read_json_frame(&mut stream).await?;
628    let hello: HelloResult = decode(hello_response.result.ok_or_else(|| {
629        WinxError::ConfigurationError("guardian handshake omitted result".to_string())
630    })?)?;
631    if hello.protocol_major != PROTOCOL_MAJOR {
632        return Err(WinxError::ConfigurationError(format!(
633            "guardian protocol major {} is incompatible with control {}",
634            hello.protocol_major, PROTOCOL_MAJOR
635        )));
636    }
637    if request.method == "shell.run_action"
638        && !hello.capabilities.iter().any(|capability| capability == TYPED_ACTION_RESULT_CAPABILITY)
639    {
640        return Err(WinxError::ConfigurationError(format!(
641            "guardian pid {} does not advertise {TYPED_ACTION_RESULT_CAPABILITY}; terminate this durable session and initialize it again before running another BashCommand",
642            hello.daemon_pid
643        )));
644    }
645    normalize_guardian_request(&mut request, &hello)?;
646    write_json_frame(&mut stream, &request).await?;
647    let response: RpcResponse = read_json_frame(&mut stream).await?;
648    Ok((response, hello))
649}
650
651async fn relay_negotiated(
652    socket: &Path,
653    request: RpcRequest,
654    hello: &HelloResult,
655) -> Result<RpcResponse> {
656    let mut stream = UnixStream::connect(socket).await.map_err(|error| {
657        WinxError::ShellInitializationError(format!(
658            "guardian at {} is unavailable: {error}",
659            socket.display()
660        ))
661    })?;
662    write_json_frame(&mut stream, &request).await?;
663    let response: RpcResponse = read_json_frame(&mut stream).await?;
664    if response.id != request.id || response.jsonrpc != "2.0" {
665        return Err(WinxError::ParseError(format!(
666            "guardian pid {} returned a mismatched JSON-RPC response",
667            hello.daemon_pid
668        )));
669    }
670    Ok(response)
671}
672
673async fn list_sessions(guardian_dir: &Path) -> Result<Vec<SessionInfo>> {
674    let mut sessions = Vec::new();
675    let mut entries = tokio::fs::read_dir(guardian_dir).await?;
676    while let Some(entry) = entries.next_entry().await? {
677        let path = entry.path();
678        if path.extension().and_then(|extension| extension.to_str()) != Some("sock") {
679            continue;
680        }
681        let request = RpcRequest {
682            jsonrpc: "2.0".to_string(),
683            id: rand::random::<u64>(),
684            method: "session.list".to_string(),
685            params: serde_json::json!({}),
686        };
687        let Ok((response, hello)) = relay(&path, request).await else { continue };
688        let Some(result) = response.result else { continue };
689        if let Ok(mut guardian_sessions) = serde_json::from_value::<Vec<SessionInfo>>(result) {
690            for session in &mut guardian_sessions {
691                session.runtime = Some(hello.clone());
692            }
693            sessions.append(&mut guardian_sessions);
694        }
695    }
696    sessions.sort_by(|left, right| left.thread_id.cmp(&right.thread_id));
697    Ok(sessions)
698}
699
700fn decode<T: serde::de::DeserializeOwned>(value: serde_json::Value) -> Result<T> {
701    serde_json::from_value(value)
702        .map_err(|error| WinxError::DeserializationError(error.to_string()))
703}
704
705fn guardian_binary() -> Result<PathBuf> {
706    if let Some(path) = std::env::var_os("WINX_GUARDIAN_BIN") {
707        return Ok(PathBuf::from(path));
708    }
709    let executable = std::env::current_exe()?;
710    let sibling = executable.with_file_name("winx-guardian");
711    if sibling.is_file() {
712        Ok(sibling)
713    } else {
714        Err(WinxError::ConfigurationError(format!(
715            "winx-guardian not found beside {} (set WINX_GUARDIAN_BIN)",
716            executable.display()
717        )))
718    }
719}
720
721fn rpc_result<T: serde::Serialize>(id: u64, result: &T) -> RpcResponse {
722    match serde_json::to_value(result) {
723        Ok(result) => {
724            RpcResponse { jsonrpc: "2.0".to_string(), id, result: Some(result), error: None }
725        }
726        Err(error) => rpc_error(id, -32603, &error.to_string()),
727    }
728}
729
730fn rpc_error(id: u64, code: i32, message: &str) -> RpcResponse {
731    RpcResponse {
732        jsonrpc: "2.0".to_string(),
733        id,
734        result: None,
735        error: Some(RpcError { code, message: message.to_string() }),
736    }
737}
738
739fn same_uid(stream: &UnixStream) -> Result<bool> {
740    let credentials = stream.peer_cred()?;
741    Ok(credentials.uid() == crate::os::unix::effective_uid())
742}
743
744#[cfg(test)]
745mod tests {
746    #![allow(clippy::expect_used)]
747
748    use super::*;
749    use crate::runtime::ShellActionOptions;
750    use crate::state::bash_state::BashState;
751    use crate::types::BashCommand;
752
753    fn guardian_1_4() -> HelloResult {
754        HelloResult {
755            protocol_major: PROTOCOL_MAJOR,
756            protocol_minor: 4,
757            capabilities: vec![TYPED_ACTION_RESULT_CAPABILITY.to_string()],
758            max_frame_bytes: crate::daemon::protocol::MAX_FRAME_BYTES,
759            daemon_epoch: "guardian-14".to_string(),
760            daemon_pid: 14,
761            process_role: None,
762            build: None,
763        }
764    }
765
766    #[test]
767    fn guardian_1_4_normalization_preserves_adapter_wait_policy_semantics() {
768        let command: BashCommand = serde_json::from_value(serde_json::json!({
769            "command": "printf compatible",
770            "wait_policy": "until_complete",
771            "thread_id": "guardian14"
772        }))
773        .expect("adapter command");
774        let mut request = RpcRequest {
775            jsonrpc: "2.0".to_string(),
776            id: 14,
777            method: "shell.run_action".to_string(),
778            params: serde_json::to_value(RunActionParams {
779                snapshot: BashState::new().snapshot(),
780                command,
781                request_key: "request14".to_string(),
782                consumer_id: "consumer14".to_string(),
783                options: ShellActionOptions {
784                    compact_output: true,
785                    ..ShellActionOptions::default()
786                },
787            })
788            .expect("run params"),
789        };
790
791        normalize_guardian_request(&mut request, &guardian_1_4()).expect("normalization");
792        let wire = request.params.as_object().expect("params object");
793        assert!(wire.get("options").is_none());
794        assert!(wire["command"].get("wait_policy").is_none());
795    }
796
797    #[test]
798    fn guardian_1_4_rejects_generation_bound_action_before_relay() {
799        let command: BashCommand = serde_json::from_value(serde_json::json!({
800            "command": "printf compatible",
801            "thread_id": "guardian14"
802        }))
803        .expect("adapter command");
804        let mut request = RpcRequest {
805            jsonrpc: "2.0".to_string(),
806            id: 15,
807            method: "shell.run_action".to_string(),
808            params: serde_json::to_value(RunActionParams {
809                snapshot: BashState::new().snapshot(),
810                command,
811                request_key: "request15".to_string(),
812                consumer_id: "consumer15".to_string(),
813                options: ShellActionOptions {
814                    expected_generation: Some(7),
815                    ..ShellActionOptions::default()
816                },
817            })
818            .expect("run params"),
819        };
820        assert!(matches!(
821            normalize_guardian_request(&mut request, &guardian_1_4()),
822            Err(WinxError::InvalidInput(_))
823        ));
824    }
825
826    #[tokio::test]
827    async fn stale_1_5_precondition_sends_zero_action_frames_to_1_4_guardian() {
828        let temp = tempfile::tempdir().expect("temporary directory");
829        let socket = temp.path().join("guardian.sock");
830        let listener = UnixListener::bind(&socket).expect("mock guardian");
831        let guardian = tokio::spawn(async move {
832            let (mut stream, _) = listener.accept().await.expect("control connection");
833            let hello: RpcRequest = read_json_frame(&mut stream).await.expect("hello frame");
834            assert_eq!(hello.method, "winx.hello");
835            write_json_frame(&mut stream, &rpc_result(hello.id, &guardian_1_4()))
836                .await
837                .expect("hello response");
838            tokio::time::timeout(
839                Duration::from_millis(100),
840                read_json_frame::<_, RpcRequest>(&mut stream),
841            )
842            .await
843            .is_ok_and(|frame| frame.is_ok())
844        });
845        let command: BashCommand = serde_json::from_value(serde_json::json!({
846            "command": "touch must-not-run",
847            "thread_id": "stale-guardian"
848        }))
849        .expect("command");
850        let request = RpcRequest {
851            jsonrpc: "2.0".to_string(),
852            id: 16,
853            method: "shell.run_action".to_string(),
854            params: serde_json::to_value(RunActionParams {
855                snapshot: BashState::new().snapshot(),
856                command,
857                request_key: "stale-request".to_string(),
858                consumer_id: "stale-consumer".to_string(),
859                options: ShellActionOptions {
860                    require_generation_binding: true,
861                    expected_guardian_epoch: Some("guardian-15".to_string()),
862                    ..ShellActionOptions::default()
863                },
864            })
865            .expect("params"),
866        };
867
868        assert!(relay(&socket, request).await.is_err());
869        assert!(!guardian.await.expect("guardian task"));
870    }
871
872    #[tokio::test]
873    async fn guardian_negotiation_cache_is_bounded_under_churn() {
874        let cache = Mutex::new(HashMap::new());
875        for index in 0..(MAX_GUARDIAN_NEGOTIATIONS + 50) {
876            let mut hello = guardian_1_4();
877            hello.daemon_epoch = format!("epoch-{index}");
878            cache_guardian(&cache, PathBuf::from(format!("guardian-{index}.sock")), hello).await;
879        }
880        assert_eq!(cache.lock().await.len(), MAX_GUARDIAN_NEGOTIATIONS);
881    }
882
883    #[tokio::test]
884    async fn concurrent_cold_guardian_negotiation_uses_one_gate() {
885        let gates = Mutex::new(HashMap::new());
886        let socket = PathBuf::from("same-guardian.sock");
887        let (first, second) = tokio::join!(
888            guardian_negotiation_gate(&gates, &socket),
889            guardian_negotiation_gate(&gates, &socket)
890        );
891        assert!(Arc::ptr_eq(
892            &first.expect("first negotiation gate"),
893            &second.expect("concurrent negotiation gate")
894        ));
895        assert_eq!(gates.lock().await.len(), 1);
896    }
897
898    #[tokio::test]
899    async fn guardian_negotiation_gates_apply_backpressure_without_evicting_active_slots() {
900        let gates = Mutex::new(HashMap::new());
901        let mut active = Vec::with_capacity(MAX_GUARDIAN_NEGOTIATIONS);
902        for index in 0..MAX_GUARDIAN_NEGOTIATIONS {
903            active.push(
904                guardian_negotiation_gate(
905                    &gates,
906                    &PathBuf::from(format!("active-guardian-{index}.sock")),
907                )
908                .await
909                .expect("active gate"),
910            );
911        }
912
913        let overflow =
914            guardian_negotiation_gate(&gates, &PathBuf::from("overflow-guardian.sock")).await;
915        assert!(matches!(overflow, Err(WinxError::ResourceAllocationError { .. })));
916        assert_eq!(gates.lock().await.len(), MAX_GUARDIAN_NEGOTIATIONS);
917
918        drop(active.pop());
919        guardian_negotiation_gate(&gates, &PathBuf::from("replacement-guardian.sock"))
920            .await
921            .expect("inactive slot can be replaced");
922        assert_eq!(gates.lock().await.len(), MAX_GUARDIAN_NEGOTIATIONS);
923    }
924
925    #[tokio::test]
926    async fn recreated_guardian_socket_invalidates_negotiation_cache() {
927        let temp = tempfile::tempdir().expect("temporary directory");
928        let socket = temp.path().join("guardian.sock");
929        let first_listener = UnixListener::bind(&socket).expect("first guardian socket");
930        let cache = Mutex::new(HashMap::new());
931        let hello = guardian_1_4();
932        cache_guardian(&cache, socket.clone(), hello.clone()).await;
933
934        assert_eq!(
935            cached_guardian(&cache, &socket).await.expect("cached first guardian").daemon_epoch,
936            hello.daemon_epoch
937        );
938
939        drop(first_listener);
940        tokio::fs::remove_file(&socket).await.expect("remove first socket");
941        let _second_listener = UnixListener::bind(&socket).expect("recreated guardian socket");
942
943        assert!(cached_guardian(&cache, &socket).await.is_none());
944        assert!(cache.lock().await.is_empty());
945    }
946}