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    /// 1.9 (rc3-9): the linked account as the Cloud's instance card names it;
157    /// absent before the first card, after a disconnect and from older Clouds.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub user: Option<CloudStatusUserV1>,
160}
161
162/// A member that is present, even as `null` (`Some(None)`); absent is `None`.
163fn present<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
164where
165    D: serde::Deserializer<'de>,
166    T: Deserialize<'de>,
167{
168    Option::<T>::deserialize(deserializer).map(Some)
169}
170
171/// `team_stop` of `cloud status --json` (1.8): the last answer the tick or
172/// a `cloud stop` command kept; status never asks the Cloud. Unknown
173/// members a newer engine adds are ignored when read.
174#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(default)]
176pub struct CloudStatusTeamStopV1 {
177    pub active: bool,
178    pub reason: Option<String>,
179    /// When the stop began (RFC 3339, the Cloud's).
180    pub since: Option<String>,
181    /// Who stopped it (display name, else email).
182    pub by: Option<String>,
183    /// The Cloud's count of stops and releases.
184    pub generation: u64,
185    pub may_stop: bool,
186    pub may_release: bool,
187    /// `fresh`, or `stale` (older than two pull intervals, or of unknown
188    /// age). No answer kept yet is `team_stop: null`, not an object.
189    pub cache: String,
190    /// Seconds since the Cloud answered; `null` when unknown.
191    pub age_s: Option<u64>,
192}
193
194/// `user` of `cloud status --json` (1.9, rc3-9).
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub struct CloudStatusUserV1 {
197    /// The account's sign-in address (C0 E44 `account.email`).
198    pub email: String,
199}
200
201/// `company` of `cloud status --json` (1.8).
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct CloudStatusCompanyV1 {
204    /// The person administers the company (stops and releases its teams).
205    pub admin: bool,
206}
207
208/// `managed` of `cloud status --json` (1.7).
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211pub struct CloudStatusManagedV1 {
212    pub carrier: super::managed::ManagedCarrierKindV1,
213    /// Where the carrier lives (a path, or `HKLM\…`).
214    pub location: String,
215    /// The members in force, in schema order; empty when `error` is set.
216    pub members: Vec<CloudStatusManagedMemberV1>,
217    /// `managed_digest` of the members; `null` when `error` is set.
218    pub digest: Option<String>,
219    /// Why the carrier was refused: the engine fails closed (Cloud calls
220    /// and, with nothing to go by, `cloud.*` settings refuse).
221    pub error: Option<String>,
222}
223
224/// One managed member (`cloud.url`, …) and its value as text.
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[serde(deny_unknown_fields)]
227pub struct CloudStatusManagedMemberV1 {
228    pub member: String,
229    pub value: String,
230}
231
232/// `vault_mismatch` of `cloud status --json` (1.6). That resolution is not
233/// used: the next connect or sync resolves the project again.
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct CloudStatusVaultMismatchV1 {
237    /// The checkout root on this machine.
238    pub project_root: String,
239    /// `ns/name` this machine resolved it to.
240    pub resolved: String,
241    /// `ns/name` its link file names; `null` when the identity changed.
242    pub linked: Option<String>,
243    /// `link` or `identity`.
244    pub reason: String,
245}
246
247/// `metrics_v2` of `cloud status --json` (telemetry SPEC §4).
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(deny_unknown_fields)]
250pub struct CloudStatusMetricsV2 {
251    /// The workspace's sharing state as Cloud last answered it (or the plan
252    /// default before the first answer).
253    pub sharing: super::metrics_v2::SharingStateV2,
254    pub last_sent_at: Option<String>,
255    pub buffered_buckets: u64,
256    pub dropped_buckets: u64,
257    /// `false` while engine metrics are not released: nothing is shared,
258    /// whatever `sharing` says. Older engines omit it.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub released: Option<bool>,
261}
262
263impl CloudCliStatusV1 {
264    /// Status of an engine that was never connected.
265    pub fn not_connected(url: Option<&str>) -> Self {
266        Self {
267            available: true,
268            connected: false,
269            instance: None,
270            org: None,
271            last_seen: None,
272            url: url.unwrap_or(CLOUD_DEFAULT_URL).to_string(),
273            drafts: CloudStatusDraftsV1::default(),
274            filter_packs: Vec::new(),
275            policy_refusal: None,
276            web_url: Some(url.unwrap_or(CLOUD_DEFAULT_URL).to_string()),
277            bus_controls: Vec::new(),
278            bus_controls_inactive: None,
279            metrics_v2: None,
280            vault_mismatch: None,
281            managed: None,
282            team_stop: None,
283            role: None,
284            org_slug: None,
285            company: None,
286            step_up_url: None,
287            user: None,
288        }
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    #[test]
297    fn not_connected_prints_nulls() {
298        assert_eq!(
299            serde_json::to_string(&CloudCliStatusV1::not_connected(None)).unwrap(),
300            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"}"#
301        );
302    }
303
304    #[test]
305    fn bus_controls_appear_only_when_present() {
306        let mut status = CloudCliStatusV1::not_connected(None);
307        let quiet = serde_json::to_string(&status).unwrap();
308        assert!(!quiet.contains("bus_controls"));
309        status.bus_controls_inactive = Some(CloudBusControlsInactiveV1::LeaseLapsed);
310        assert!(
311            serde_json::to_string(&status)
312                .unwrap()
313                .contains(r#""bus_controls_inactive":"lease_lapsed""#)
314        );
315    }
316
317    #[test]
318    fn a_1_0_status_still_reads() {
319        let old = r#"{"available":true,"connected":false,"instance":null,"org":null,"last_seen":null,"url":"https://cloud.leanctx.com"}"#;
320        let status: CloudCliStatusV1 = serde_json::from_str(old).unwrap();
321        assert_eq!(
322            status,
323            CloudCliStatusV1 {
324                web_url: None,
325                ..CloudCliStatusV1::not_connected(None)
326            }
327        );
328    }
329}