Skip to main content

lean_ctx_protocol/cloud/
status.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! `lean-ctx cloud status --json`: the one shape the local cockpit reads.
4//!
5//! It is built from local state only (no network) and prints `available:
6//! true` whenever the engine has the Cloud connector, connected or not.
7//! The six fields of 1.0 are always printed; 1.2 adds `drafts`, `policy`,
8//! `filter_packs` and `policy_refusal` (readers treat them as "not
9//! reported" when an older engine leaves them out).
10
11use serde::{Deserialize, Serialize};
12
13use super::CLOUD_DEFAULT_URL;
14use crate::UtcTimestamp;
15
16/// Instance shown in the cockpit.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct CloudStatusInstanceV1 {
20    pub id: String,
21    pub label: String,
22}
23
24/// Organization shown in the cockpit.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct CloudStatusOrgV1 {
28    pub name: String,
29}
30
31/// Session drafts not yet in Cloud (1.2).
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct CloudStatusDraftsV1 {
35    /// Queued in the outbox, sent with the next sync.
36    pub queued: u32,
37    /// Refused by Cloud for good; kept on this machine.
38    pub refused: u32,
39}
40
41/// An active filter pack (1.2). Bundles verify as a whole, so every listed
42/// pack is active; a refused bundle leaves the previous list in place.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct CloudStatusFilterPackV1 {
46    pub pack_id: String,
47    pub version: u64,
48}
49
50/// What a bus control asks of an agent (1.5).
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum CloudBusControlActionV1 {
54    Hold,
55    Stop,
56    Veto,
57    #[serde(other)]
58    Unknown,
59}
60
61/// A bus control in force on this machine (1.5).
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct CloudStatusBusControlV1 {
65    /// The agent it targets; `null`: every agent of this instance.
66    pub target_agent: Option<String>,
67    pub action: CloudBusControlActionV1,
68    /// What a veto names (a lease or handoff reference).
69    pub target_ref: Option<String>,
70    pub reason: String,
71    pub issued_by: String,
72    pub since: UtcTimestamp,
73}
74
75/// Why recorded bus controls do not apply right now (1.5).
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum CloudBusControlsInactiveV1 {
79    NotEnrolled,
80    LeaseLapsed,
81    #[serde(other)]
82    Unknown,
83}
84
85/// Output of `lean-ctx cloud status --json`. `null` fields are printed.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct CloudCliStatusV1 {
89    /// The engine build has the Cloud connector.
90    pub available: bool,
91    /// Enrolled and the lease is not lapsed.
92    pub connected: bool,
93    pub instance: Option<CloudStatusInstanceV1>,
94    pub org: Option<CloudStatusOrgV1>,
95    /// Last successful exchange with Cloud.
96    pub last_seen: Option<UtcTimestamp>,
97    /// Cloud web origin (the configured `[cloud] url`, default hosted).
98    pub url: String,
99    /// 1.2.
100    #[serde(default)]
101    pub drafts: CloudStatusDraftsV1,
102    /// 1.2.
103    #[serde(default)]
104    pub filter_packs: Vec<CloudStatusFilterPackV1>,
105    /// 1.2: why the newest policy bundle was refused (the last verified one stays).
106    #[serde(default)]
107    pub policy_refusal: Option<String>,
108    /// 1.3: origin of the LeanCTX Cloud web app (its "Open" link): the one enrollment
109    /// named, else `url`.
110    #[serde(default)]
111    pub web_url: Option<String>,
112    /// 1.5: bus controls in force. Left out when empty, so readers of
113    /// earlier shapes see unchanged output.
114    #[serde(default, skip_serializing_if = "Vec::is_empty")]
115    pub bus_controls: Vec<CloudStatusBusControlV1>,
116    /// 1.5: why recorded controls do not apply; left out when they do or
117    /// none are recorded.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub bus_controls_inactive: Option<CloudBusControlsInactiveV1>,
120    /// Engine metrics v2 (telemetry SPEC §4); left out when not connected.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub metrics_v2: Option<CloudStatusMetricsV2>,
123    /// 1.6: the project here was resolved to a vault its link file or its
124    /// identity no longer backs. Left out when they agree, so readers of
125    /// earlier shapes see unchanged output.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub vault_mismatch: Option<CloudStatusVaultMismatchV1>,
128    /// 1.7: this machine carries a managed configuration
129    /// (`leanctx.managed-config/v1`). Left out when it carries none, so
130    /// readers of earlier shapes see unchanged output.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub managed: Option<CloudStatusManagedV1>,
133    /// 1.8: the team stop (kill switch) as the Cloud last answered it. Left
134    /// out when not connected or the Cloud does not offer it, so readers of
135    /// earlier shapes see unchanged output; `null` (`Some(None)`) when
136    /// connected but no answer is kept yet, so nothing reads as "running".
137    #[serde(
138        default,
139        skip_serializing_if = "Option::is_none",
140        deserialize_with = "present"
141    )]
142    pub team_stop: Option<Option<CloudStatusTeamStopV1>>,
143    /// 1.8: the linked person's acting role in the team (the Cloud's word).
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub role: Option<String>,
146    /// 1.8: the team's slug (what `cloud stop --release --confirm` names).
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub org_slug: Option<String>,
149    /// 1.8: the person's standing in the team's company, when the Cloud names it.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub company: Option<CloudStatusCompanyV1>,
152    /// 1.8: the browser page that confirms a release (admin, two-factor);
153    /// only while the team is stopped and this person may release it.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub step_up_url: Option<String>,
156}
157
158/// A member that is present, even as `null` (`Some(None)`); absent is `None`.
159fn present<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
160where
161    D: serde::Deserializer<'de>,
162    T: Deserialize<'de>,
163{
164    Option::<T>::deserialize(deserializer).map(Some)
165}
166
167/// `team_stop` of `cloud status --json` (1.8): the last answer the tick or
168/// a `cloud stop` command kept; status never asks the Cloud. Unknown
169/// members a newer engine adds are ignored when read.
170#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(default)]
172pub struct CloudStatusTeamStopV1 {
173    pub active: bool,
174    pub reason: Option<String>,
175    /// When the stop began (RFC 3339, the Cloud's).
176    pub since: Option<String>,
177    /// Who stopped it (display name, else email).
178    pub by: Option<String>,
179    /// The Cloud's count of stops and releases.
180    pub generation: u64,
181    pub may_stop: bool,
182    pub may_release: bool,
183    /// `fresh`, or `stale` (older than two pull intervals, or of unknown
184    /// age). No answer kept yet is `team_stop: null`, not an object.
185    pub cache: String,
186    /// Seconds since the Cloud answered; `null` when unknown.
187    pub age_s: Option<u64>,
188}
189
190/// `company` of `cloud status --json` (1.8).
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct CloudStatusCompanyV1 {
193    /// The person administers the company (stops and releases its teams).
194    pub admin: bool,
195}
196
197/// `managed` of `cloud status --json` (1.7).
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(deny_unknown_fields)]
200pub struct CloudStatusManagedV1 {
201    pub carrier: super::managed::ManagedCarrierKindV1,
202    /// Where the carrier lives (a path, or `HKLM\…`).
203    pub location: String,
204    /// The members in force, in schema order; empty when `error` is set.
205    pub members: Vec<CloudStatusManagedMemberV1>,
206    /// `managed_digest` of the members; `null` when `error` is set.
207    pub digest: Option<String>,
208    /// Why the carrier was refused: the engine fails closed (Cloud calls
209    /// and, with nothing to go by, `cloud.*` settings refuse).
210    pub error: Option<String>,
211}
212
213/// One managed member (`cloud.url`, …) and its value as text.
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(deny_unknown_fields)]
216pub struct CloudStatusManagedMemberV1 {
217    pub member: String,
218    pub value: String,
219}
220
221/// `vault_mismatch` of `cloud status --json` (1.6). That resolution is not
222/// used: the next connect or sync resolves the project again.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224#[serde(deny_unknown_fields)]
225pub struct CloudStatusVaultMismatchV1 {
226    /// The checkout root on this machine.
227    pub project_root: String,
228    /// `ns/name` this machine resolved it to.
229    pub resolved: String,
230    /// `ns/name` its link file names; `null` when the identity changed.
231    pub linked: Option<String>,
232    /// `link` or `identity`.
233    pub reason: String,
234}
235
236/// `metrics_v2` of `cloud status --json` (telemetry SPEC §4).
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(deny_unknown_fields)]
239pub struct CloudStatusMetricsV2 {
240    /// The workspace's sharing state as Cloud last answered it (or the plan
241    /// default before the first answer).
242    pub sharing: super::metrics_v2::SharingStateV2,
243    pub last_sent_at: Option<String>,
244    pub buffered_buckets: u64,
245    pub dropped_buckets: u64,
246    /// `false` while engine metrics are not released: nothing is shared,
247    /// whatever `sharing` says. Older engines omit it.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub released: Option<bool>,
250}
251
252impl CloudCliStatusV1 {
253    /// Status of an engine that was never connected.
254    pub fn not_connected(url: Option<&str>) -> Self {
255        Self {
256            available: true,
257            connected: false,
258            instance: None,
259            org: None,
260            last_seen: None,
261            url: url.unwrap_or(CLOUD_DEFAULT_URL).to_string(),
262            drafts: CloudStatusDraftsV1::default(),
263            filter_packs: Vec::new(),
264            policy_refusal: None,
265            web_url: Some(url.unwrap_or(CLOUD_DEFAULT_URL).to_string()),
266            bus_controls: Vec::new(),
267            bus_controls_inactive: None,
268            metrics_v2: None,
269            vault_mismatch: None,
270            managed: None,
271            team_stop: None,
272            role: None,
273            org_slug: None,
274            company: None,
275            step_up_url: None,
276        }
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn not_connected_prints_nulls() {
286        assert_eq!(
287            serde_json::to_string(&CloudCliStatusV1::not_connected(None)).unwrap(),
288            r#"{"available":true,"connected":false,"instance":null,"org":null,"last_seen":null,"url":"https://cloud.leanctx.com","drafts":{"queued":0,"refused":0},"filter_packs":[],"policy_refusal":null,"web_url":"https://cloud.leanctx.com"}"#
289        );
290    }
291
292    #[test]
293    fn bus_controls_appear_only_when_present() {
294        let mut status = CloudCliStatusV1::not_connected(None);
295        let quiet = serde_json::to_string(&status).unwrap();
296        assert!(!quiet.contains("bus_controls"));
297        status.bus_controls_inactive = Some(CloudBusControlsInactiveV1::LeaseLapsed);
298        assert!(
299            serde_json::to_string(&status)
300                .unwrap()
301                .contains(r#""bus_controls_inactive":"lease_lapsed""#)
302        );
303    }
304
305    #[test]
306    fn a_1_0_status_still_reads() {
307        let old = r#"{"available":true,"connected":false,"instance":null,"org":null,"last_seen":null,"url":"https://cloud.leanctx.com"}"#;
308        let status: CloudCliStatusV1 = serde_json::from_str(old).unwrap();
309        assert_eq!(
310            status,
311            CloudCliStatusV1 {
312                web_url: None,
313                ..CloudCliStatusV1::not_connected(None)
314            }
315        );
316    }
317}