micromux-control 0.3.0

Micromux is a local process supervisor with a terminal UI
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! The control wire protocol: newline-delimited JSON request/response envelopes.
//!
//! Domain payloads (`ServiceSnapshot`, `HealthAttempt`, `LogLine`, `SessionChange`,
//! `ServiceCommandAck`, `DynamicServiceAck`, `ReconcileReceipt`, `ServiceEvent`, and
//! `DynamicServiceParams`) are the stable core types reused directly — no DTO mirror. The session
//! and the proxy accept peers that speak the same major protocol version, so additive payload
//! changes do not orphan already-running sessions.

use micromux::{
    DynamicServiceAck, DynamicServiceParams, HealthAttempt, Lease, LogLine, LogRunSummary,
    ReconcileReceipt, ServiceCommandAck, ServiceEvent, ServiceID, ServiceSnapshot, SessionChange,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// The current control protocol version.
///
/// Bump the minor for additive changes (new optional/defaulted fields, new tools that reuse
/// existing requests), and bump the major for incompatible request/response semantics.
pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 10);

pub(crate) const fn supports_versioned_subscriptions(version: ProtocolVersion) -> bool {
    version.major() == PROTOCOL_VERSION.major() && version.minor() >= 7
}

/// A typed control protocol version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProtocolVersion {
    major: u16,
    minor: u16,
}

impl ProtocolVersion {
    /// Build a protocol version from major/minor components.
    #[must_use]
    pub const fn new(major: u16, minor: u16) -> Self {
        Self { major, minor }
    }

    /// Major compatibility line.
    #[must_use]
    pub const fn major(self) -> u16 {
        self.major
    }

    /// Additive revision within one major line.
    #[must_use]
    pub const fn minor(self) -> u16 {
        self.minor
    }

    /// Return whether two peers can speak the same protocol.
    #[must_use]
    pub const fn is_compatible_with(self, peer: Self) -> bool {
        self.major == peer.major
    }
}

impl std::fmt::Display for ProtocolVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}", self.major(), self.minor())
    }
}

/// A request from a client (the `micromux ctl` CLI or the MCP proxy) to a session's control server.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Request {
    /// Return session identity and metadata.
    Describe,
    /// List every service with its current snapshot.
    ///
    /// This response is not paged. A roster that exceeds the protocol frame budget returns
    /// [`ErrorCode::LimitExceeded`].
    ListServices,
    /// Return one service by stable id or human-readable name.
    ///
    /// Exact ids take precedence; duplicate display names resolve to the first service.
    GetService {
        /// Service id or display name.
        service: ServiceID,
    },
    /// Return recent log records for a service.
    GetLogs {
        /// Target service.
        service: ServiceID,
        /// Specific disk-retained run generation to read. Omit to read the bounded visible log
        /// stream.
        run_generation: Option<u64>,
        /// Bound the result to the most recent records.
        tail: Option<usize>,
    },
    /// Return log records strictly after a monotonic cursor, for gap-free incremental following.
    FollowLogs {
        /// Target service.
        service: ServiceID,
        /// Specific disk-retained run generation to follow. Omit to follow the bounded visible log
        /// stream.
        run_generation: Option<u64>,
        /// Return only records with `seq` greater than this cursor (all retained records if
        /// `None`).
        after: Option<u64>,
    },
    /// Return summaries of retained log runs for a service.
    ///
    /// This response is not paged. A run index that exceeds the protocol frame budget returns
    /// [`ErrorCode::LimitExceeded`].
    ListLogRuns {
        /// Target service.
        service: ServiceID,
    },
    /// Return the latest healthcheck attempt for a service's current live run.
    GetHealth {
        /// Target service.
        service: ServiceID,
    },
    /// Return retained healthcheck attempts for a service's current or latest run.
    GetHealthHistory {
        /// Target service.
        service: ServiceID,
    },
    /// Return retained scheduler lifecycle events for a service.
    GetEvents {
        /// Target service.
        service: ServiceID,
        /// Return events with a sequence strictly greater than this cursor.
        after: Option<u64>,
        /// Bound the result; when `after` is absent this selects the newest events.
        tail: Option<usize>,
    },
    /// Restart a single service.
    Restart {
        /// Target service.
        service: ServiceID,
    },
    /// Restart all enabled services.
    RestartAll,
    /// Enable (and start) a single service.
    Enable {
        /// Target service.
        service: ServiceID,
    },
    /// Disable a single service.
    Disable {
        /// Target service.
        service: ServiceID,
    },
    /// Create and start a dynamic service.
    StartDynamicService {
        /// Definition, clone source, and lease request.
        params: DynamicServiceParams,
    },
    /// Replace or revive a dynamic service.
    ReplaceDynamicService {
        /// Existing dynamic service id.
        service: ServiceID,
        /// Required current revision.
        expected_revision: u64,
        /// Replacement definition, clone source, and lease request.
        params: DynamicServiceParams,
    },
    /// Renew a live dynamic service's lease without restarting it.
    RenewDynamicService {
        /// Existing dynamic service id.
        service: ServiceID,
        /// Required current revision.
        expected_revision: u64,
        /// Requested replacement lease; omission uses the session policy default.
        expires_after: Option<Lease>,
    },
    /// Retire a dynamic service.
    StopDynamicService {
        /// Dynamic service id.
        service: ServiceID,
    },
    /// Reconcile configured services against the session's on-disk config.
    ///
    /// The config file is the authority, so this operation has no dynamic-service capability gate.
    ReconcileConfig {
        /// Compute the semantic diff without mutating the session. Deliberately a required
        /// field: omission must never silently mean "apply".
        dry_run: bool,
    },
    /// Stop the whole session: stop every service and exit the session process (graceful, like the
    /// operator pressing Ctrl-C), freeing its ports. Acknowledged with [`Response::ShuttingDown`]
    /// just before the endpoint goes away.
    Shutdown,
    /// Stream [`SessionChange`] notifications until the client disconnects.
    Subscribe,
    /// Stream change notifications and negotiate additive subscription behavior.
    SubscribeWithVersion {
        /// Protocol version spoken by the subscribing client.
        protocol_version: ProtocolVersion,
    },
}

impl Request {
    /// Whether a client may repeat the request after losing the connection before its response.
    ///
    /// Mutations are deliberately excluded even when they are usually idempotent: a lost
    /// acknowledgement does not prove whether the scheduler accepted the first request.
    #[must_use]
    pub const fn is_retry_safe(&self) -> bool {
        matches!(
            self,
            Self::Describe
                | Self::ListServices
                | Self::GetService { .. }
                | Self::GetLogs { .. }
                | Self::FollowLogs { .. }
                | Self::ListLogRuns { .. }
                | Self::GetHealth { .. }
                | Self::GetHealthHistory { .. }
                | Self::GetEvents { .. }
                | Self::ReconcileConfig { dry_run: true }
        )
    }
}

/// A brief, identity-only view of a service for [`SessionInfo`].
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServiceBrief {
    /// Stable service identifier.
    pub id: ServiceID,
    /// Human-readable service name.
    #[serde(default)]
    pub name: String,
}

/// Live session identity returned by [`Request::Describe`]. Never stored on disk.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SessionInfo {
    /// The protocol version this session speaks.
    pub protocol_version: ProtocolVersion,
    /// Deterministic session id: the endpoint hash of the canonical config path.
    pub id: String,
    /// Process id of the session.
    pub pid: u32,
    /// Monotonic session start token as Unix nanoseconds. With `pid`, forms a start token.
    pub start_time: u64,
    /// Session name (config `name:` if set, else `basename(working_dir)`).
    #[serde(default)]
    pub name: String,
    /// The directory the session was launched in.
    #[serde(default)]
    pub working_dir: String,
    /// The canonical config path that keys this session's endpoint.
    #[serde(default)]
    pub config_path: String,
    /// The services this session supervises.
    #[serde(default)]
    pub services: Vec<ServiceBrief>,
    /// Whether the service index was shortened to fit the control frame.
    ///
    /// Use [`Request::GetService`] for targeted lookup when this is true.
    #[serde(default)]
    pub services_truncated: bool,
    /// The micromux version of the session binary.
    #[serde(default)]
    pub micromux_version: String,
    /// Optional capabilities advertised by newer sessions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<SessionCapabilities>,
}

/// Optional session features and their current limits.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SessionCapabilities {
    /// Dynamic-service limits, or `None` when runtime creation is not permitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dynamic_services: Option<DynamicServicesCaps>,
    /// Capacity and health of the bounded disk-log read pool.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk_log_reads: Option<DiskLogReadHealth>,
}

/// Current capacity, occupancy, and timeout history of the disk-log read pool.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct DiskLogReadHealth {
    /// Whether the pool has started its workers.
    #[serde(default = "default_initialized_disk_log_pool")]
    pub initialized: bool,
    /// Whether the pool can initialize or has an unoccupied worker.
    pub available: bool,
    /// Worker slots configured for the pool.
    pub workers: usize,
    /// Worker threads currently executing a filesystem read.
    pub active: usize,
    /// Maximum reads that may wait for a worker.
    pub queue_capacity: usize,
    /// Reads currently waiting for a worker.
    pub queued: usize,
    /// Reads whose callers timed out or disconnected while the filesystem call remained blocked.
    #[serde(default)]
    pub abandoned: usize,
    /// Requests that have exceeded the read deadline since this session started.
    #[serde(default)]
    pub timed_out_requests: usize,
}

impl Default for DiskLogReadHealth {
    fn default() -> Self {
        Self {
            initialized: default_initialized_disk_log_pool(),
            available: false,
            workers: 0,
            active: 0,
            queue_capacity: 0,
            queued: 0,
            abandoned: 0,
            timed_out_requests: 0,
        }
    }
}

const fn default_initialized_disk_log_pool() -> bool {
    // Protocol 3.8 created the pool while building `Describe`, before this field existed.
    true
}

/// Dynamic-service limits and current usage advertised by a session.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DynamicServicesCaps {
    /// Maximum non-retired dynamic services.
    pub max_services: usize,
    /// Current non-retired dynamic-service count.
    pub live_services: usize,
    /// Maximum and default lease duration in seconds, or `None` for session-lifetime leases.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_lifetime_secs: Option<u64>,
    /// Canonical working-directory roots accepted by the session.
    pub allowed_working_roots: Vec<String>,
}

impl SessionInfo {
    /// Return whether another `Describe` response names the same running session instance.
    #[must_use]
    pub fn is_same_instance(&self, other: &Self) -> bool {
        self.id == other.id && self.pid == other.pid && self.start_time == other.start_time
    }
}

/// A typed error code shared by the protocol and the proxy diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ErrorCode {
    /// No service with the given id exists.
    UnknownService,
    /// The requested service run is no longer retained or never existed.
    UnknownRun,
    /// No session answered the request.
    NoSession,
    /// More than one live session matched the selector.
    Ambiguous,
    /// A live session is busy (connect/reply timeout); never a reason to delete it.
    Busy,
    /// A request timed out.
    Timeout,
    /// The command is invalid in the service's current state.
    InvalidState,
    /// The latest config could not be reloaded before a restart/enable command.
    ConfigReload,
    /// The target session's policy denied the operation.
    PolicyDenied,
    /// A target-session resource limit was reached.
    LimitExceeded,
    /// An optimistic-concurrency revision was stale.
    RevisionMismatch,
    /// A dynamic service definition was invalid.
    InvalidSpec,
    /// The scheduler stopped before acknowledging a command.
    SchedulerStopped,
    /// The control plane is not supported on this platform.
    UnsupportedPlatform,
    /// The peer speaks an incompatible protocol version.
    ProtocolVersionMismatch,
    /// The request could not be parsed.
    BadRequest,
    /// An unexpected internal error.
    Internal,
    /// A newer peer returned an error code this binary does not know yet.
    #[serde(other)]
    Unknown,
}

/// A response from a session's control server.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Response {
    /// Reply to [`Request::Describe`].
    Description(SessionInfo),
    /// Reply to [`Request::ListServices`].
    Services(Vec<ServiceSnapshot>),
    /// Reply to [`Request::GetService`].
    Service(Box<ServiceSnapshot>),
    /// Reply to [`Request::GetLogs`].
    Logs {
        /// The recent log records.
        lines: Vec<LogLine>,
        /// Whether the session had to drop older records to respect server response limits.
        #[serde(default)]
        truncated: bool,
        /// First sequence still retained by the visible in-memory stream.
        ///
        /// Present only for visible-stream responses. A cursor whose next expected sequence is
        /// below this value has crossed a retention gap and should resume here.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        first_retained_seq: Option<u64>,
    },
    /// Reply to [`Request::ListLogRuns`].
    LogRuns {
        /// Retained runs, oldest first.
        runs: Vec<LogRunSummary>,
    },
    /// Reply to [`Request::GetHealth`].
    Health(Option<HealthAttempt>),
    /// Reply to [`Request::GetHealthHistory`].
    HealthHistory {
        /// Retained attempts in oldest-first order.
        attempts: Vec<HealthAttempt>,
    },
    /// Reply to [`Request::GetEvents`].
    Events {
        /// Retained lifecycle events in ascending sequence order.
        events: Vec<ServiceEvent>,
        /// Whether matching events were omitted by the response bound.
        truncated: bool,
    },
    /// A mutation was *accepted* (validated + queued), not necessarily completed. Carries each
    /// affected service's latched generation.
    Accepted {
        /// Per-service acknowledgements.
        services: Vec<ServiceCommandAck>,
    },
    /// Reply to a dynamic-service mutation.
    DynamicService(DynamicServiceAck),
    /// Reply to a config reconciliation.
    Reconcile(ReconcileReceipt),
    /// A streamed change notification (only after [`Request::Subscribe`]).
    Change(SessionChange),
    /// Acknowledgement of [`Request::Shutdown`], written just before the session begins exiting.
    ShuttingDown,
    /// A typed error.
    Error {
        /// The error code.
        code: ErrorCode,
        /// A human-readable message.
        message: String,
    },
}

impl Response {
    /// Build an [`Response::Error`] from a code and message.
    #[must_use]
    pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
        Self::Error {
            code,
            message: message.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;
    use serde_json::json;
    use similar_asserts::assert_eq;

    fn session(id: &str, pid: u32, start_time: u64, name: &str) -> SessionInfo {
        SessionInfo {
            protocol_version: PROTOCOL_VERSION,
            id: id.to_string(),
            pid,
            start_time,
            name: name.to_string(),
            working_dir: ".".to_string(),
            config_path: "/project/micromux.yaml".to_string(),
            services: Vec::new(),
            services_truncated: false,
            micromux_version: env!("CARGO_PKG_VERSION").to_string(),
            capabilities: None,
        }
    }

    #[test]
    fn session_instance_identity_uses_stable_start_token() {
        let first = session("aaa", 42, 100, "app");
        let alias = session("aaa", 42, 100, "renamed");
        let replacement = session("aaa", 42, 101, "app");

        assert!(first.is_same_instance(&alias));
        assert!(!first.is_same_instance(&replacement));
    }

    #[test]
    fn protocol_version_uses_major_minor_shape_and_accepts_same_major() {
        assert_eq!(
            serde_json::to_value(PROTOCOL_VERSION).unwrap(),
            json!({ "major": 3, "minor": 10 })
        );
        assert_eq!(
            serde_json::from_value::<ProtocolVersion>(json!({ "major": 1, "minor": 0 })).unwrap(),
            ProtocolVersion::new(1, 0)
        );

        assert!(PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(3, 11)));
        assert!(!PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(2, 9)));
        assert!(!supports_versioned_subscriptions(ProtocolVersion::new(
            3, 6
        )));
        assert!(supports_versioned_subscriptions(ProtocolVersion::new(3, 7)));
    }

    #[test]
    fn protocol_version_rejects_plain_integer_shape() {
        let err = serde_json::from_value::<ProtocolVersion>(json!(5)).unwrap_err();

        assert!(
            err.to_string().contains("invalid type"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn protocol_version_rejects_missing_minor() {
        let err = serde_json::from_value::<ProtocolVersion>(json!({ "major": 5 })).unwrap_err();

        assert!(
            err.to_string().contains("missing field `minor`"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn unknown_error_codes_degrade_without_deserialize_failure() {
        let code = serde_json::from_str::<ErrorCode>("\"FutureError\"").unwrap();

        assert_eq!(code, ErrorCode::Unknown);
    }

    #[test]
    fn session_info_accepts_missing_additive_fields() {
        let info = serde_json::from_value::<SessionInfo>(json!({
            "protocol_version": { "major": 3, "minor": 2 },
            "id": "abc",
            "pid": 42,
            "start_time": 99
        }))
        .unwrap();

        assert_eq!(info.protocol_version, ProtocolVersion::new(3, 2));
        assert_eq!(info.name, "");
        assert!(info.services.is_empty());
        assert!(!info.services_truncated);
        assert_eq!(info.micromux_version, "");
        assert!(info.capabilities.is_none());
    }

    #[test]
    fn disk_log_read_health_accepts_missing_timeout_history() {
        let health = serde_json::from_value::<DiskLogReadHealth>(json!({
            "available": true,
            "workers": 4,
            "active": 1,
            "queue_capacity": 4,
            "queued": 2
        }))
        .unwrap();

        assert!(health.initialized);
        assert_eq!(health.abandoned, 0);
        assert_eq!(health.timed_out_requests, 0);
        assert_eq!(health.initialized, DiskLogReadHealth::default().initialized);
    }

    #[test]
    fn dynamic_service_ack_round_trips_and_accepts_missing_additive_fields() {
        let ack = DynamicServiceAck {
            service: "debug".to_string(),
            revision: 2,
            observed_generation: 1,
            expires_at_unix_ms: Some(1234),
            command: vec!["true".to_string()],
            working_dir: None,
            ports: vec![3201],
            env_keys: vec!["RUST_LOG".to_string()],
            restart: micromux::RestartPolicy::Never,
            healthcheck_configured: false,
            already_retired: false,
            idempotent_replay: true,
        };
        let encoded = serde_json::to_value(Response::DynamicService(ack.clone())).unwrap();
        let decoded = serde_json::from_value::<Response>(encoded).unwrap();
        let Response::DynamicService(decoded) = decoded else {
            panic!("expected a dynamic-service response");
        };
        assert_eq!(decoded.service, ack.service);
        assert_eq!(decoded.revision, ack.revision);
        assert!(decoded.idempotent_replay);

        // The defaulted fields are additive: a minimal older payload still deserializes.
        let minimal = serde_json::from_value::<DynamicServiceAck>(json!({
            "service": "debug",
            "revision": 1,
            "observed_generation": 0,
            "command": ["true"],
            "restart": "Never",
            "healthcheck_configured": false
        }))
        .unwrap();
        assert_eq!(minimal.expires_at_unix_ms, None);
        assert!(minimal.ports.is_empty());
        assert!(!minimal.already_retired);
    }

    #[test]
    fn reconcile_request_and_receipt_round_trip() {
        let request = Request::ReconcileConfig { dry_run: true };
        let encoded = serde_json::to_value(&request).unwrap();
        assert_matches!(
            serde_json::from_value::<Request>(encoded).unwrap(),
            Request::ReconcileConfig { dry_run: true }
        );

        let receipt = micromux::ReconcileReceipt {
            config_path: "/project/micromux.yaml".to_string(),
            dry_run: true,
            actions: vec![micromux::ReconcileAction {
                service: "worker".to_string(),
                action: micromux::ReconcileActionKind::Changed,
                detail: "changed service spec".to_string(),
            }],
        };
        let encoded = serde_json::to_value(Response::Reconcile(receipt.clone())).unwrap();
        let Response::Reconcile(decoded) = serde_json::from_value::<Response>(encoded).unwrap()
        else {
            panic!("expected a reconcile response");
        };
        assert_eq!(decoded, receipt);
    }

    #[test]
    fn versioned_subscription_carries_the_client_protocol() {
        let request = Request::SubscribeWithVersion {
            protocol_version: PROTOCOL_VERSION,
        };

        let encoded = serde_json::to_value(&request).unwrap();

        assert_matches!(
            serde_json::from_value::<Request>(encoded).unwrap(),
            Request::SubscribeWithVersion { protocol_version }
                if protocol_version == PROTOCOL_VERSION
        );
    }

    #[test]
    fn health_history_request_and_response_round_trip() -> serde_json::Result<()> {
        let request = Request::GetHealthHistory {
            service: "api".to_string(),
        };
        let encoded = serde_json::to_value(&request)?;
        assert_matches!(
            serde_json::from_value::<Request>(encoded)?,
            Request::GetHealthHistory { service } if service == "api"
        );

        let response = Response::HealthHistory {
            attempts: vec![HealthAttempt {
                run_generation: 2,
                attempt: 3,
                command: "probe".to_string(),
                output: Vec::new(),
                result: None,
            }],
        };
        let encoded = serde_json::to_value(response)?;
        let Response::HealthHistory { attempts } = serde_json::from_value::<Response>(encoded)?
        else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected health-history response variant",
            )));
        };
        assert_eq!(attempts.len(), 1);
        assert_eq!(attempts.first().map(|attempt| attempt.attempt), Some(3));
        Ok(())
    }

    #[test]
    fn logs_response_accepts_missing_truncated_flag() {
        let response = serde_json::from_value::<Response>(json!({
            "Logs": {
                "lines": []
            }
        }))
        .unwrap();

        match response {
            Response::Logs {
                lines,
                truncated,
                first_retained_seq,
            } => {
                assert!(lines.is_empty());
                assert!(!truncated);
                assert_eq!(first_retained_seq, None);
            }
            other => panic!("unexpected response: {other:?}"),
        }
    }

    #[test]
    fn protocol_version_ignores_additive_fields() {
        let version = serde_json::from_value::<ProtocolVersion>(json!({
            "major": 3,
            "minor": 10,
            "future_capability": true
        }))
        .unwrap();

        assert_eq!(version, PROTOCOL_VERSION);
    }

    #[test]
    fn only_observations_are_safe_to_retry_after_a_lost_response() {
        assert!(Request::ListServices.is_retry_safe());
        assert!(
            Request::GetService {
                service: "api".to_string(),
            }
            .is_retry_safe()
        );
        assert!(Request::ReconcileConfig { dry_run: true }.is_retry_safe());
        assert!(!Request::RestartAll.is_retry_safe());
        assert!(!Request::ReconcileConfig { dry_run: false }.is_retry_safe());
        assert!(!Request::Shutdown.is_retry_safe());
    }

    #[test]
    fn dynamic_request_round_trips_flat_spec_and_humantime_lease() -> serde_json::Result<()> {
        let value = json!({
            "StartDynamicService": {
                "params": {
                    "service": "debug",
                    "command": ["CMD-SHELL", "echo ready"],
                    "environment": {"MODE": "debug"},
                    "healthcheck": null,
                    "expires_after": "90s",
                    "idempotency_key": "request-1"
                }
            }
        });
        let request = serde_json::from_value::<Request>(value.clone())?;
        let Request::StartDynamicService { params } = &request else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected request variant",
            )));
        };
        assert_eq!(
            params.expires_after,
            Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
        );
        assert_eq!(params.spec.healthcheck, micromux::SpecField::Clear);
        let encoded = serde_json::to_value(&request)?;
        assert_eq!(
            encoded.pointer("/StartDynamicService/params/expires_after"),
            Some(&json!("1m 30s"))
        );
        assert_eq!(
            encoded.pointer("/StartDynamicService/params/extra_args"),
            Some(&json!([]))
        );
        let Request::StartDynamicService { params } = serde_json::from_value(encoded)? else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected round-trip request variant",
            )));
        };
        assert_eq!(
            params.expires_after,
            Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
        );
        Ok(())
    }

    #[test]
    fn dynamic_request_round_trips_an_unbounded_or_omitted_lease() -> serde_json::Result<()> {
        let unbounded = json!({
            "StartDynamicService": {
                "params": {
                    "service": "debug",
                    "command": ["true"],
                    "expires_after": "none"
                }
            }
        });
        let request = serde_json::from_value::<Request>(unbounded)?;
        let Request::StartDynamicService { params } = request else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected request variant",
            )));
        };
        assert_eq!(params.expires_after, Some(micromux::Lease::Unbounded));

        let omitted = json!({
            "StartDynamicService": {
                "params": {
                    "service": "debug",
                    "command": ["true"]
                }
            }
        });
        let Request::StartDynamicService { params } = serde_json::from_value(omitted)? else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected request variant",
            )));
        };
        assert_eq!(params.expires_after, None);
        Ok(())
    }
}