Skip to main content

lean_ctx_cloud/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Errors of the Cloud connector. Messages are safe to print: they never
3//! carry tokens, keys, device codes or request bodies.
4
5use std::fmt;
6
7use lean_ctx_protocol::cloud::lease::CloudPlan;
8use lean_ctx_protocol::cloud::{
9    CloudErrorBody, CloudErrorCode, CloudErrorDetailV1, CloudUploadKind,
10};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum CloudError {
14    /// Cloud could not be reached (DNS, connect, TLS, timeout, reset).
15    Offline(String),
16    /// The instance is not enrolled on this machine.
17    NotConnected,
18    /// The service refused the instance's credentials.
19    Unauthorized,
20    /// `402 plan_required`: the plan lacks a feature (C0 2.x names it), or,
21    /// from a 1.x Cloud that names none, Cloud itself (an engine seat).
22    PlanRequired(Box<PlanNeed>),
23    /// Every instance seat of the organization is taken (`409
24    /// instance_limit`): registered instances, or those connected at once.
25    InstanceLimit(Box<InstanceCap>),
26    /// A Release B quota is used up (`409`/`429 quota_exceeded`, Cloud API
27    /// §8.1). Nothing is charged; monthly quotas are waited out (the outbox
28    /// keeps local work), counted ones need a person.
29    QuotaExceeded(Box<Quota>),
30    /// The workspace's Cloud storage is full (`403
31    /// storage_quota_exceeded`). Waiting does not free it: the background
32    /// sync parks the vault until a person frees storage or syncs by hand.
33    StorageFull(Box<StorageFull>),
34    /// The sliding-hour upload allowance is used up (`429
35    /// upload_rate_limited`). Transient: the rest goes out after
36    /// `retry_after` seconds (`retry_after_s` or the `Retry-After` header).
37    UploadRateLimited {
38        retry_after: Option<u64>,
39        /// The allowance per hour in bytes, when the service names it.
40        per_hour: Option<u64>,
41    },
42    /// Cloud' own enforcement of a policy member refused (`403
43    /// policy_denied`, API §7.2). Never retried until the policy changes.
44    PolicyDenied(PolicyDenial),
45    /// The lease is past `grace_until`; reconnect.
46    LeaseLapsed,
47    /// A workspace admin revoked this instance (`401 instance_revoked`, C0
48    /// 2.0 E12). Recorded locally; no Cloud call is made until a new
49    /// connect (fail closed, never retried).
50    Revoked(Revocation),
51    /// The lease lacks the right this request needs.
52    Forbidden,
53    /// An organization veto bars this lease or handoff (`forbidden_right`,
54    /// `reason: vetoed`; C5c). Never retried until the veto is lifted.
55    Vetoed,
56    /// The organization switched this upload off; stop it and drop its
57    /// queue until a lease allows it again (never retried).
58    UploadDisabled(CloudUploadKind),
59    /// The operator switched a feature off on this Cloud (`404
60    /// feature_disabled`, e.g. `instance_metrics`). Not an error of this
61    /// instance: what waits stays local, tried again much later.
62    FeatureDisabled {
63        feature: Option<String>,
64    },
65    NotFound,
66    Conflict {
67        expected: Option<u64>,
68        actual: Option<u64>,
69    },
70    ScreeningBlocked,
71    UpgradeRequired {
72        min: Option<String>,
73    },
74    RateLimited {
75        retry_after: Option<u64>,
76    },
77    /// The device flow ended without approval.
78    DeviceFlow(String),
79    /// `cloud connect --trial` against a Cloud that does not take the trial
80    /// members of the device code request yet (`400 invalid_request`). Never
81    /// retried without them: the person starts the trial on the web.
82    TrialUnsupported {
83        /// The Cloud web origin to start the trial on.
84        origin: String,
85    },
86    /// A response or stored artifact broke the contract (bad signature,
87    /// wrong shape, unknown key).
88    Protocol(String),
89    /// Configuration that cannot work (URL scheme, root key).
90    Config(String),
91    /// Local storage failed.
92    Local(String),
93    /// A local rule refused the request before it left (worker gate,
94    /// outgoing screening); the message carries no content.
95    Refused(String),
96    /// Cloud refused a task request (C0 1.9 §1); `number` names the task.
97    Task {
98        refusal: TaskRefusal,
99        number: Option<u64>,
100        /// The roles a `not_permitted` refusal names (Cloud task #17).
101        detail: Option<String>,
102    },
103    /// Any other service answer.
104    Server {
105        status: u16,
106        code: String,
107    },
108}
109
110/// A used-up quota as far as it is shown and acted on (API §8.1).
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct Quota {
113    /// HTTP status: 409 counted, 429 monthly.
114    pub status: u16,
115    /// `[a-z_]` token (`transfer_bytes`, `bus_messages`,
116    /// `registered_instances`, `private_vaults`, or a newer one).
117    pub resource: String,
118    pub limit: Option<u64>,
119    pub used: Option<u64>,
120    /// When it frees, second precision `Z` (`None`: nothing frees by itself).
121    pub reset_at: Option<String>,
122    /// `retry_after_s` (or the `Retry-After` header).
123    pub retry_after: Option<u64>,
124    /// `registered_instances` in Personal: the slot cool-down.
125    pub cooldown_days: Option<u32>,
126    /// What helps, when the service says so.
127    pub next_step: Option<NextStep>,
128}
129
130/// An `instance_limit` refusal as far as it is shown.
131#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct InstanceCap {
133    /// `connected_instances` (connected at once) or `registered_instances`
134    /// (`None` from an older service: registered).
135    pub resource: Option<String>,
136    pub limit: Option<u64>,
137    pub used: Option<u64>,
138    /// Team: the workspace's seats and the allowance of each.
139    pub seats: Option<u64>,
140    pub per_seat: Option<u64>,
141    pub next_step: Option<NextStep>,
142}
143
144/// A full Cloud storage (`storage_quota_exceeded`), in bytes.
145#[derive(Debug, Clone, PartialEq, Eq, Default)]
146pub struct StorageFull {
147    pub limit: Option<u64>,
148    pub used: Option<u64>,
149    pub next_step: Option<NextStep>,
150}
151
152/// What helps with a limit refusal (`next_step` of the service).
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum NextStep {
155    Subscribe,
156    TopUp,
157    UpgradeTeam,
158    AddSeats,
159    Contact,
160    Wait,
161}
162
163impl NextStep {
164    /// The service's `next_step` word; an unknown one is `None`.
165    #[must_use]
166    pub fn of_wire(value: Option<&str>) -> Option<Self> {
167        Some(match value? {
168            "subscribe" => Self::Subscribe,
169            "top_up" => Self::TopUp,
170            "upgrade_team" => Self::UpgradeTeam,
171            "add_seats" => Self::AddSeats,
172            "contact" => Self::Contact,
173            "wait" => Self::Wait,
174            _ => return None,
175        })
176    }
177
178    /// The short hint shown after the refusal (`None`: the line already
179    /// says to wait).
180    #[must_use]
181    pub fn hint(self) -> Option<&'static str> {
182        Some(match self {
183            Self::Subscribe => "choose a plan in the Cloud",
184            Self::TopUp => "a top-up in the Cloud adds more",
185            Self::UpgradeTeam => "Team gives every seat its own allowance",
186            Self::AddSeats => "every seat you add in the Cloud brings its own allowance",
187            Self::Contact => "contact us to extend your Enterprise contract",
188            Self::Wait => return None,
189        })
190    }
191}
192
193/// `; <hint>` of a `next_step`, when there is one to show.
194fn write_hint(f: &mut fmt::Formatter<'_>, next: Option<NextStep>) -> fmt::Result {
195    match next.and_then(NextStep::hint) {
196        Some(hint) => write!(f, "; {hint}"),
197        None => Ok(()),
198    }
199}
200
201/// Bytes in words: `1 GiB`, `256 MiB`, `1.5 GiB`.
202fn bytes_text(bytes: u64) -> String {
203    const UNITS: [(&str, u64); 4] = [
204        ("TiB", 1 << 40),
205        ("GiB", 1 << 30),
206        ("MiB", 1 << 20),
207        ("KiB", 1 << 10),
208    ];
209    for (unit, size) in UNITS {
210        if bytes >= size {
211            let tenths = u128::from(bytes) * 10 / u128::from(size);
212            return if tenths % 10 == 0 {
213                format!("{} {unit}", tenths / 10)
214            } else {
215                format!("{}.{} {unit}", tenths / 10, tenths % 10)
216            };
217        }
218    }
219    format!("{bytes} B")
220}
221
222/// A quota amount in its resource's unit: GiB for bytes, $ for model
223/// credit, a count otherwise.
224#[must_use]
225pub fn amount_text(resource: &str, value: u64) -> String {
226    if resource.ends_with("_bytes") {
227        bytes_text(value)
228    } else if resource.ends_with("_usd_micros") {
229        format!("${}.{:02}", value / 1_000_000, value % 1_000_000 / 10_000)
230    } else {
231        value.to_string()
232    }
233}
234
235/// What a `402 plan_required` says, as far as it is shown.
236#[derive(Debug, Clone, PartialEq, Eq, Default)]
237pub struct PlanNeed {
238    /// `[a-z_]` feature token (`repos`, `internal_vaults`, …);
239    /// `None` from a 1.x Cloud: Cloud itself (the engine-seat text).
240    pub feature: Option<String>,
241    /// The lowest plan that includes it (`pro`, `team`, `enterprise`).
242    pub plan_needed: Option<String>,
243    /// A counted feature's limit and use (`repos`).
244    pub limit: Option<u64>,
245    pub used: Option<u64>,
246    /// The service's own words, terminal-safe.
247    pub message: Option<String>,
248    /// The workspace's plan as this engine's lease names it (set by the
249    /// session that made the call, [`CloudError::with_plan`]).
250    pub plan: Option<CloudPlan>,
251    /// Why the workspace is locked (`trial_ended`, `plan_ended`, `no_plan`;
252    /// `[a-z_]`, Cloud API §1a), or `trial_used`: a one-step trial asked
253    /// for a trial this address already had.
254    pub reason: Option<String>,
255    /// What helps, when the service says so.
256    pub next_step: Option<NextStep>,
257    /// `trial_used`: where to choose a plan (an `http(s)://` URL, or a path
258    /// on the Cloud's origin until [`CloudError::with_origin`]; else `None`).
259    pub plans_url: Option<String>,
260    /// `trial_used`: why no trial starts, as the service names it
261    /// (`trial_used`, `trial_ended`, `no_plan`; `[a-z_]`, else `None`).
262    pub trial_reason: Option<String>,
263}
264
265/// The part every locked-workspace line shares; `cloud sync` prints such a
266/// refusal once per run.
267pub const LOCKED_MARK: &str = "this workspace is locked (read and export only)";
268
269/// The 1.x engine-seat text: the limits worded as everywhere (E10; plan
270/// limits of 17.11.: an Enterprise seat gets what a Team seat gets), in the
271/// two host counts of the web (rc4-58): registered and connected at once.
272pub const PLAN_LIMITS: &str = "Personal up to 3 hosts registered, up to 2 connected at once; Team and Enterprise up to 3 hosts registered, up to 2 connected at once per seat";
273
274/// The label of `registered_instances`: hosts that connected at least once
275/// and are not revoked (the web's "Registered", rc4-58).
276pub const HOSTS_REGISTERED: &str = "hosts registered";
277
278/// The label of `connected_instances`: hosts connected now, against the
279/// plan's limit of hosts connected at once (rc4-58).
280pub const HOSTS_CONNECTED: &str = "hosts connected at once";
281
282/// How a full registered count frees (rc4-62): one revoked host frees its
283/// registration (in Personal after the cool-down or a recovery).
284pub const FREE_REGISTERED: &str = "to free one, revoke a host you no longer use on the Hosts page";
285
286/// How a full connected-at-once count frees (rc4-58).
287pub const FREE_CONNECTED: &str =
288    "to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)";
289
290impl PlanNeed {
291    /// `trial_ended` or `plan_ended`: the workspace is locked.
292    #[must_use]
293    pub fn locked(&self) -> Option<&str> {
294        self.reason
295            .as_deref()
296            .filter(|r| matches!(*r, "trial_ended" | "plan_ended"))
297    }
298
299    /// `402 trial_used`: this address already had the trial it asked for.
300    #[must_use]
301    pub fn trial_used(&self) -> bool {
302        self.reason.as_deref() == Some(TRIAL_USED)
303    }
304
305    /// Team wording when the refusal or the lease says team.
306    fn plan_word(&self) -> &'static str {
307        let team = self.plan_needed.as_deref() == Some("team")
308            || matches!(self.plan, Some(CloudPlan::Team | CloudPlan::Enterprise));
309        if team { "Team" } else { "Personal" }
310    }
311}
312
313/// The one line of a locked workspace (`reason` `trial_ended`/`plan_ended`).
314#[must_use]
315pub fn locked_line(reason: &str, plan_word: &str) -> String {
316    let what = if reason == "trial_ended" {
317        format!("Your {plan_word} trial has ended")
318    } else {
319        "Your plan has ended".to_string()
320    };
321    format!("{what}: {LOCKED_MARK}. Choose a plan in the Cloud to sync again.")
322}
323
324/// The plans that include a feature whose lowest plan is `needed`.
325fn plans_from(needed: &str) -> Option<&'static str> {
326    Some(match needed {
327        "personal" => "Personal, Team and Enterprise",
328        "team" => "Team and Enterprise",
329        "enterprise" => "Enterprise",
330        _ => return None,
331    })
332}
333
334fn write_plan_need(f: &mut fmt::Formatter<'_>, need: &PlanNeed) -> fmt::Result {
335    if need.trial_used() {
336        let plan = need.plan_word();
337        match need.trial_reason.as_deref() {
338            Some("trial_ended") => write!(
339                f,
340                "the {plan} trial of this address has ended; no second trial starts. Choose a plan"
341            )?,
342            Some("no_plan") => write!(
343                f,
344                "this address has no {plan} trial left and no plan; no second trial starts. Choose a plan"
345            )?,
346            _ => write!(
347                f,
348                "this address already had its {plan} trial; no second trial starts. Choose a plan"
349            )?,
350        }
351        return match need.plans_url.as_deref().filter(|u| u.starts_with("http")) {
352            Some(url) => write!(f, " at {url}, then run `lean-ctx cloud connect`"),
353            None => f.write_str(" in the Cloud, then run `lean-ctx cloud connect`"),
354        };
355    }
356    // A locked workspace is one line, whatever the feature (E9).
357    if let Some(reason) = need.locked() {
358        return f.write_str(&locked_line(reason, need.plan_word()));
359    }
360    let Some(feature) = need.feature.as_deref() else {
361        // 1.x: the plan does not include Cloud (an engine seat).
362        return write!(
363            f,
364            "your plan does not include the Cloud on this machine ({PLAN_LIMITS})"
365        );
366    };
367    let plans = need.plan_needed.as_deref().and_then(plans_from);
368    let on = need
369        .plan
370        .filter(|p| *p != CloudPlan::Unknown)
371        .map(|p| match p {
372            CloudPlan::NoPlan => "; this workspace has no plan".to_string(),
373            p => format!("; this workspace is on {}", p.display_name()),
374        })
375        .unwrap_or_default();
376    match feature {
377        "repos" | "vaults" | "private_vaults" => {
378            f.write_str("this workspace has used all its vaults")?;
379            if let (Some(used), Some(limit)) = (need.used, need.limit) {
380                write!(f, " ({used} of {limit})")?;
381            }
382            if let Some(plans) = plans {
383                write!(f, "; more are included in {plans}")?;
384            }
385            write!(
386                f,
387                "{on}; remove or publish a vault in the Cloud, or upgrade the plan"
388            )
389        }
390        other => {
391            match (&need.message, plans) {
392                (Some(message), _) => f.write_str(message.trim_end_matches('.'))?,
393                (None, Some(plans)) => {
394                    write!(f, "{} is included in {plans}", other.replace('_', " "))?;
395                }
396                (None, None) => write!(
397                    f,
398                    "this workspace's plan does not include {}",
399                    other.replace('_', " ")
400                )?,
401            }
402            f.write_str(&on)
403        }
404    }
405}
406
407/// Monthly quotas reset at the start of the next calendar month (UTC).
408pub const MONTHLY_RESOURCES: &[&str] =
409    &["transfer_bytes", "bus_messages", "model_credit_usd_micros"];
410
411impl Quota {
412    /// Whether waiting frees it (a monthly quota, or any 429).
413    #[must_use]
414    pub fn waits(&self) -> bool {
415        self.status == 429 || MONTHLY_RESOURCES.contains(&self.resource.as_str())
416    }
417
418    /// A Personal engine slot that frees after its cool-down (P7).
419    #[must_use]
420    pub fn cooling_slot(&self) -> bool {
421        self.resource == "registered_instances"
422            && self.cooldown_days.is_some_and(|d| d > 0)
423            && self.reset_at.is_some()
424    }
425}
426
427/// A server-enforced policy refusal (`policy_denied`, API §7.2).
428#[derive(Debug, Clone, PartialEq, Eq, Default)]
429pub struct PolicyDenial {
430    /// Dotted member path (`sharing.allowed_vaults`).
431    pub member: Option<String>,
432    /// `org`, `workspace`, `vault` or `engine`.
433    pub level: Option<String>,
434    /// `consent_required_for`: the action that needs a person.
435    pub action: Option<String>,
436}
437
438/// A value of the service shown on a terminal: `[a-z0-9_.-]`, 1..=max.
439fn wire_token(value: Option<&str>, max: usize) -> Option<String> {
440    value
441        .filter(|s| {
442            (1..=max).contains(&s.len())
443                && s.bytes().all(|b| {
444                    b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
445                })
446        })
447        .map(str::to_string)
448}
449
450/// An RFC 3339 time of the service in second-precision `Z` form.
451pub(crate) fn wire_time(value: Option<&str>) -> Option<String> {
452    let parsed = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(value?).ok()?;
453    Some(
454        parsed
455            .to_utc()
456            .to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
457    )
458}
459
460/// The code of a one-step trial refusal (`402 trial_used`).
461pub const TRIAL_USED: &str = "trial_used";
462/// `409 not_ready`: Cloud cannot serve a signed answer yet (plans without
463/// a control key, contract §37.2). Kept as the code of a `Server` error.
464pub const NOT_READY: &str = "not_ready";
465/// `403 vault_create_forbidden`: the caller's role may not add a new vault
466/// to the team (rc4-71); read as [`CloudError::Forbidden`].
467pub const VAULT_CREATE_FORBIDDEN: &str = "vault_create_forbidden";
468
469/// A web address of the service shown on a terminal: `http(s)://` or a
470/// path on the Cloud's own origin (`/o/…`, resolved by
471/// [`CloudError::with_origin`]), at most 512 characters, no spaces,
472/// control, format (`Cf`, bidi overrides among them) or other invisible
473/// characters.
474fn web_url(value: Option<&str>) -> Option<String> {
475    value
476        .filter(|s| {
477            (s.starts_with("https://")
478                || s.starts_with("http://")
479                || (s.starts_with('/') && !s.starts_with("//")))
480                && s.len() <= 512
481                && !s.chars().any(hidden_in_url)
482        })
483        .map(str::to_string)
484}
485
486/// A character a person cannot see or that reorders what a terminal shows.
487fn hidden_in_url(c: char) -> bool {
488    use unicode_general_category::{GeneralCategory, get_general_category};
489    c.is_control()
490        || c.is_whitespace()
491        || get_general_category(c) == GeneralCategory::Format
492        || lean_ctx_protocol::cloud::invisible(c)
493}
494
495/// Whether the absolute `url` has the origin `base` (`scheme://host[:port]`,
496/// compared without case): no other host, port or scheme, no userinfo.
497fn same_origin(url: &str, base: &str) -> bool {
498    let Some(start) = url.find("://").map(|i| i + 3) else {
499        return false;
500    };
501    let end = url[start..]
502        .find(['/', '?', '#'])
503        .map_or(url.len(), |i| start + i);
504    url[..end].eq_ignore_ascii_case(base)
505}
506
507/// What a revocation statement says, as far as it is shown (E12).
508#[derive(Debug, Clone, PartialEq, Eq, Default)]
509pub struct Revocation {
510    /// The workspace that revoked it, when the engine knows its name.
511    pub workspace: Option<String>,
512    /// `web_revoke`, `admin` or `key_compromise` (`[a-z_]`, ≤ 32).
513    pub reason: Option<String>,
514    /// `revoked_at` of the statement (ms).
515    pub revoked_at: Option<u64>,
516    /// `instance_id` of the statement.
517    pub instance_id: Option<String>,
518}
519
520impl Revocation {
521    /// The statement of an `instance_revoked` error body; values that are
522    /// not of the contract's shape are left out (they reach a terminal).
523    fn of_statement(statement: &serde_json::Value) -> Self {
524        let token = |v: &serde_json::Value, max: usize| {
525            v.as_str()
526                .filter(|s| {
527                    (1..=max).contains(&s.len())
528                        && s.bytes().all(|b| {
529                            b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
530                        })
531                })
532                .map(str::to_string)
533        };
534        Self {
535            workspace: None,
536            reason: token(&statement["reason"], 32),
537            revoked_at: statement["revoked_at"].as_u64(),
538            instance_id: token(&statement["instance_id"], 36),
539        }
540    }
541}
542
543/// Which check refused a `not_permitted` claim (Cloud task #17).
544#[derive(Debug, Clone, Copy, PartialEq, Eq)]
545pub enum PermitCheck {
546    /// The agent has no live presence on the bus.
547    Presence,
548    /// The agent is present in another role than the task's.
549    Role,
550    /// A Cloud that does not say.
551    Unknown,
552}
553
554/// Why Cloud refused a task request (the `reason` of C0 1.9 §1).
555#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum TaskRefusal {
557    /// Another claim holds the task.
558    Claimed,
559    /// A claim on a task that is not `open`.
560    NotOpen,
561    /// The lease id or fencing token is not the current claim's.
562    StaleClaim,
563    /// A write to a `done`, `rejected` or `cancelled` task.
564    Closed,
565    /// C0 2.2 E48: the agent that did the work checked its own result.
566    SelfVerify,
567    /// C0 2.2 E48: a verdict on a task that is not `submitted`.
568    NotSubmitted,
569    /// The task's role or the owner's worker consent does not allow this agent.
570    NotPermitted(PermitCheck),
571    /// The engine's opt-in does not cover this vault or network (§4,
572    /// `optin_scope`).
573    OptinScope,
574    /// The claim named an older `optin_id`: read the opt-in again (§4,
575    /// `optin_changed`).
576    OptinChanged,
577    /// No opt-in, or the owner stopped it: every claim of the engine ended
578    /// (§4, `optin_inactive`).
579    OptinInactive,
580    /// The opt-in's daily budget is used up until 00:00 UTC (§4,
581    /// `daily_budget`); never retried before `retry_after`.
582    DailyBudget { retry_after: Option<u64> },
583    /// C0 2.2 E47: a priority or labels write named an older
584    /// `fields_version` (`stale_base`): read the task again.
585    StaleBase,
586    /// rc4-67: a person's proposal whose app signature the Cloud did not
587    /// accept (`forbidden_right`, `person_unproven`); never sent again.
588    PersonUnproven,
589    /// rc4-67: a person's proposal signed too long ago or ahead
590    /// (`forbidden_right`, `signature_expired`); never sent again.
591    SignatureExpired,
592}
593
594impl TaskRefusal {
595    fn from_reason(
596        code: CloudErrorCode,
597        reason: Option<&str>,
598        retry_after: Option<u64>,
599        check: Option<&str>,
600    ) -> Option<Self> {
601        Some(match (code, reason?) {
602            (CloudErrorCode::InvalidState, "task_claimed") => Self::Claimed,
603            (CloudErrorCode::InvalidState, "task_not_open") => Self::NotOpen,
604            (CloudErrorCode::InvalidState, "stale_claim") => Self::StaleClaim,
605            (CloudErrorCode::InvalidState, "task_closed") => Self::Closed,
606            (CloudErrorCode::ForbiddenRight, "self_verify") => Self::SelfVerify,
607            (CloudErrorCode::InvalidState, "not_submitted") => Self::NotSubmitted,
608            (CloudErrorCode::ForbiddenRight, "not_permitted") => Self::NotPermitted(match check {
609                Some("presence") => PermitCheck::Presence,
610                Some("role") => PermitCheck::Role,
611                _ => PermitCheck::Unknown,
612            }),
613            (CloudErrorCode::ForbiddenRight, "optin_scope") => Self::OptinScope,
614            (CloudErrorCode::ForbiddenRight, "person_unproven") => Self::PersonUnproven,
615            (CloudErrorCode::ForbiddenRight, "signature_expired") => Self::SignatureExpired,
616            (CloudErrorCode::InvalidState, "optin_changed") => Self::OptinChanged,
617            (CloudErrorCode::InvalidState, "optin_inactive") => Self::OptinInactive,
618            (CloudErrorCode::RateLimited, "daily_budget") => Self::DailyBudget { retry_after },
619            (CloudErrorCode::InvalidState | CloudErrorCode::RevisionConflict, "stale_base") => {
620                Self::StaleBase
621            }
622            _ => return None,
623        })
624    }
625
626    /// Whether the claim this request acted under is gone for good (a stop
627    /// of the opt-in ends every claim of the engine).
628    #[must_use]
629    pub fn ends_claim(self) -> bool {
630        matches!(self, Self::StaleClaim | Self::Closed | Self::OptinInactive)
631    }
632}
633
634impl fmt::Display for TaskRefusal {
635    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636        match self {
637            Self::Claimed => f.write_str("another agent holds the task"),
638            Self::NotOpen => f.write_str("the task is not open"),
639            Self::StaleClaim => f.write_str("this claim is no longer the task's claim"),
640            Self::Closed => f.write_str("the task is closed"),
641            Self::SelfVerify => f.write_str(
642                "the agent that did the work does not check its own result; another agent verifies it",
643            ),
644            Self::NotSubmitted => f.write_str("the task has no result waiting for a check"),
645            Self::NotPermitted(PermitCheck::Presence) => f.write_str(
646                "this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role",
647            ),
648            Self::NotPermitted(PermitCheck::Role) => {
649                f.write_str("this agent is on the bus in another role than the task needs")
650            }
651            Self::NotPermitted(PermitCheck::Unknown) => f.write_str(
652                "the task's role or the owner's worker consent does not allow this agent",
653            ),
654            Self::OptinScope => f.write_str("this instance's opt-in does not cover this vault"),
655            Self::OptinChanged => f.write_str("the opt-in changed; it is read again"),
656            Self::OptinInactive => f.write_str(
657                "this instance is not opted in (or the owner stopped worker mode on the web)",
658            ),
659            Self::StaleBase => f.write_str(
660                "the task's priority or labels changed meanwhile; read it again and retry",
661            ),
662            Self::PersonUnproven => f.write_str(
663                "the app's signature on this task did not check out; propose it again in the app",
664            ),
665            Self::SignatureExpired => f.write_str(
666                "the app's signature on this task is too old; propose it again in the app",
667            ),
668            Self::DailyBudget { retry_after } => match retry_after {
669                Some(s) => write!(f, "today's task budget is used up (resets in {s} s)"),
670                None => f.write_str("today's task budget is used up"),
671            },
672        }
673    }
674}
675
676/// A role as the bus names it, or nothing: only `[a-z0-9-]`, 1-64 chars,
677/// so a service answer cannot put anything else on the terminal.
678fn bus_role(role: Option<&String>) -> Option<&str> {
679    role.map(String::as_str).filter(|r| {
680        (1..=64).contains(&r.len())
681            && r.bytes()
682                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
683    })
684}
685
686/// The service's own words, safe for a terminal: no control characters
687/// (escape sequences), at most 300 characters; `None` when nothing is left.
688pub(crate) fn safe_message(message: &str) -> Option<String> {
689    let text: String = message
690        .chars()
691        .map(|c| if c.is_control() { ' ' } else { c })
692        .take(300)
693        .collect();
694    let text = text.trim();
695    (!text.is_empty()).then(|| text.to_string())
696}
697
698/// The whole line of a `not_permitted` refusal: Cloud's message (it names
699/// the agent and the roles), the check that failed and, when the agent is
700/// not on the bus, how to put it there.
701fn permit_line(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
702    let TaskRefusal::NotPermitted(check) = refusal else {
703        return None;
704    };
705    let mut line =
706        safe_message(&detail.message).unwrap_or_else(|| match permit_roles(refusal, detail) {
707            Some(roles) => format!("{refusal} ({roles})"),
708            None => refusal.to_string(),
709        });
710    match check {
711        PermitCheck::Presence => line.push_str(
712            " [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. The Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs.",
713        ),
714        PermitCheck::Role => line.push_str(" [check: role]"),
715        PermitCheck::Unknown => {}
716    }
717    Some(line)
718}
719
720/// The roles of a `not_permitted` refusal, in words (Cloud task #17).
721fn permit_roles(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
722    let role = bus_role(detail.role.as_ref())?;
723    match refusal {
724        TaskRefusal::NotPermitted(PermitCheck::Presence) => {
725            Some(format!("the task needs role {role}"))
726        }
727        TaskRefusal::NotPermitted(PermitCheck::Role) => {
728            Some(match bus_role(detail.agent_role.as_ref()) {
729                Some(agent_role) => {
730                    format!("the agent works as {agent_role}, the task needs {role}")
731                }
732                None => format!("the task needs role {role}"),
733            })
734        }
735        _ => None,
736    }
737}
738
739/// A non-negative integer, also when a service sent it as a decimal string.
740fn lenient_u64(value: &serde_json::Value) -> Option<u64> {
741    value
742        .as_u64()
743        .or_else(|| value.as_str().and_then(|s| s.trim().parse().ok()))
744}
745
746/// The `error` object of an answer whose typed decode failed (a member of
747/// an unexpected type, e.g. `number` as a string): the code, message and
748/// every member that decodes on its own are kept, a numeric string is read
749/// as its number, the rest is dropped. `None` without a string `code`.
750fn lenient_detail(error: &serde_json::Value) -> Option<CloudErrorDetailV1> {
751    let object = error.as_object()?;
752    let code = object.get("code").filter(|c| c.is_string())?.clone();
753    let message = object
754        .get("message")
755        .filter(|m| m.is_string())
756        .cloned()
757        .unwrap_or_else(|| serde_json::Value::String(String::new()));
758    let base = || {
759        let mut kept = serde_json::Map::new();
760        kept.insert("code".into(), code.clone());
761        kept.insert("message".into(), message.clone());
762        kept
763    };
764    let decodes = |kept: &serde_json::Map<String, serde_json::Value>| {
765        serde_json::from_value::<CloudErrorDetailV1>(serde_json::Value::Object(kept.clone()))
766            .is_ok()
767    };
768    let mut kept = base();
769    for (name, value) in object {
770        if matches!(name.as_str(), "code" | "message") {
771            continue;
772        }
773        let candidates = [
774            Some(value.clone()),
775            lenient_u64(value).map(serde_json::Value::from),
776        ];
777        for candidate in candidates.into_iter().flatten() {
778            let mut probe = base();
779            probe.insert(name.clone(), candidate.clone());
780            if decodes(&probe) {
781                kept.insert(name.clone(), candidate);
782                break;
783            }
784        }
785    }
786    serde_json::from_value(serde_json::Value::Object(kept)).ok()
787}
788
789/// The pairing refusals of a task-propose key (rc4-67): `400 invalid_field`
790/// on `task_propose_key` ([`TASK_KEY_INVALID`]), and `409 invalid_state`
791/// with reason `task_propose_key_bound` or `task_propose_key_cleared`.
792fn task_key_refusal(status: u16, body: &serde_json::Value) -> Option<String> {
793    let error = &body["error"];
794    let code = error["code"].as_str()?;
795    let reason = error["reason"].as_str();
796    match (status, code) {
797        (400, "invalid_field") if error["field"].as_str() == Some("task_propose_key") => {
798            Some(TASK_KEY_INVALID.into())
799        }
800        (409, "invalid_state") => reason
801            .filter(|r| matches!(*r, TASK_KEY_BOUND | TASK_KEY_CLEARED))
802            .map(str::to_owned),
803        _ => None,
804    }
805}
806
807/// The pairing refusals of an opt-in key (rc4-16): `400 invalid_field` on
808/// `optin_key` or `optin_key.bind_signature` ([`OPTIN_KEY_INVALID`]), and a
809/// `409` whose code or reason is `optin_key_bound` or `optin_key_cleared`.
810fn optin_key_refusal(status: u16, body: &serde_json::Value) -> Option<String> {
811    let error = &body["error"];
812    let code = error["code"].as_str()?;
813    match (status, code) {
814        (400, "invalid_field")
815            if matches!(
816                error["field"].as_str(),
817                Some("optin_key" | "optin_key.bind_signature")
818            ) =>
819        {
820            Some(OPTIN_KEY_INVALID.into())
821        }
822        (409, _) => [code, error["reason"].as_str().unwrap_or_default()]
823            .into_iter()
824            .find(|name| matches!(*name, OPTIN_KEY_BOUND | OPTIN_KEY_CLEARED))
825            .map(str::to_owned),
826        _ => None,
827    }
828}
829
830/// `CloudError::Server` code: the Cloud refused the offered opt-in key.
831pub const OPTIN_KEY_INVALID: &str = "optin_key_invalid";
832/// `CloudError::Server` code: another opt-in key is bound already.
833pub const OPTIN_KEY_BOUND: &str = "optin_key_bound";
834/// `CloudError::Server` code: this opt-in key was removed on the web.
835pub const OPTIN_KEY_CLEARED: &str = "optin_key_cleared";
836
837/// `CloudError::Server` code (f3129): the offered app keys are not exactly
838/// the ones announced at the device code.
839pub const APP_KEY_NOT_ANNOUNCED: &str = "app_key_not_announced";
840/// `CloudError::Server` code (f3129): `app_keys_bind_signature` is missing
841/// or does not verify.
842pub const APP_KEY_BIND_INVALID: &str = "app_key_bind_invalid";
843/// `CloudError::Server` code (f3129): the Cloud refused the announced
844/// `app_keys` at the device code (`400 invalid_field`, field `app_keys`).
845pub const APP_KEYS_INVALID: &str = "app_keys_invalid";
846/// `CloudError::Server` code: the Cloud refused the offered task-propose key.
847pub const TASK_KEY_INVALID: &str = "task_propose_key_invalid";
848/// `CloudError::Server` code: another task-propose key is bound already.
849pub const TASK_KEY_BOUND: &str = "task_propose_key_bound";
850/// `CloudError::Server` code: this task-propose key was removed on the web.
851pub const TASK_KEY_CLEARED: &str = "task_propose_key_cleared";
852
853/// The longest `retry_after_s` an answer may ask for (32 days); a larger one
854/// (up to `u64::MAX`) is shortened to this before any time arithmetic.
855pub const RETRY_AFTER_CAP_S: u64 = 32 * 86_400;
856
857impl CloudError {
858    /// Map a non-2xx answer to an error.
859    pub(crate) fn from_response(status: u16, body: &serde_json::Value) -> Self {
860        let value_reason = body["error"]["reason"].clone();
861        let revocation = body["error"]["revocation"].clone();
862        let trial_used = body["error"]["code"].as_str() == Some(TRIAL_USED);
863        let plans_url = web_url(body["error"]["plans_url"].as_str());
864        let decoded = serde_json::from_value::<CloudErrorBody>(body.clone())
865            .map(|body| body.error)
866            .ok()
867            .or_else(|| lenient_detail(&body["error"]));
868        // f3129: offers that are not the announced set, or a bind signature
869        // that does not verify, keep their reason; checked first, before the
870        // task key, whose `field` the same answer may name.
871        if status == 400
872            && body["error"]["code"].as_str() == Some("invalid_field")
873            && let Some(reason @ (APP_KEY_NOT_ANNOUNCED | APP_KEY_BIND_INVALID)) =
874                body["error"]["reason"].as_str()
875        {
876            return Self::Server {
877                status,
878                code: reason.into(),
879            };
880        }
881        // f3129: an announcement the Cloud cannot parse, kept apart from
882        // other `invalid_field` answers by its field.
883        if status == 400
884            && body["error"]["code"].as_str() == Some("invalid_field")
885            && body["error"]["field"].as_str() == Some("app_keys")
886        {
887            return Self::Server {
888                status,
889                code: APP_KEYS_INVALID.into(),
890            };
891        }
892        // rc4-67: a pairing whose task-propose key the Cloud refused, named
893        // so the pairing can say why in plain words. Checked before the
894        // re-pair reasons: its `field`/`reason` names the task key exactly,
895        // while a re-pair `reason` below may ride along on the same answer.
896        if let Some(code) = task_key_refusal(status, body) {
897            return Self::Server { status, code };
898        }
899        // rc4-16: the same for the opt-in key (§46.4 texts).
900        if let Some(code) = optin_key_refusal(status, body) {
901            return Self::Server { status, code };
902        }
903        // rc4-32 re-pair refusals (p37 §3.18.1), named by `reason` or `code`:
904        // kept so the connect says which one, never dropped as `unknown`.
905        if matches!(status, 400 | 409)
906            && let Some(name) = [&body["error"]["reason"], &body["error"]["code"]]
907                .iter()
908                .filter_map(|v| v.as_str())
909                .find(|name| crate::auth::CHAT_KEY_REPAIR_REASONS.contains(name))
910        {
911            return Self::Server {
912                status,
913                code: name.to_owned(),
914            };
915        }
916        // A code this protocol version does not name, kept so a caller can
917        // tell "not available yet" from a failure.
918        if status == 409 && body["error"]["code"].as_str() == Some(NOT_READY) {
919            return Self::Server {
920                status,
921                code: NOT_READY.into(),
922            };
923        }
924        // rc4-71: a contributor's first share of a vault the team has not
925        // added yet; the role refuses it as `forbidden_right` does.
926        if status == 403 && body["error"]["code"].as_str() == Some(VAULT_CREATE_FORBIDDEN) {
927            return Self::Forbidden;
928        }
929        let Some(mut detail) = decoded else {
930            return Self::of_status(status, lenient_u64(&body["error"]["retry_after_s"]));
931        };
932        // A wait beyond the cap is a broken or hostile answer; every later
933        // `now + retry_after` stays inside the time range (overflow panics).
934        detail.retry_after_s = detail.retry_after_s.map(|s| s.min(RETRY_AFTER_CAP_S));
935        if let Some(refusal) = TaskRefusal::from_reason(
936            detail.code,
937            detail.reason.as_deref(),
938            detail.retry_after_s,
939            detail.check.as_deref(),
940        ) {
941            return Self::Task {
942                refusal,
943                number: detail.number,
944                detail: permit_line(refusal, &detail),
945            };
946        }
947        let next_step = NextStep::of_wire(detail.next_step.as_deref());
948        // One-step trial (`402 trial_used`, a code this protocol version
949        // does not name): a plan refusal that says which trial was used.
950        if trial_used {
951            return Self::PlanRequired(Box::new(PlanNeed {
952                plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
953                message: safe_message(&detail.message),
954                reason: Some(TRIAL_USED.into()),
955                next_step,
956                plans_url,
957                trial_reason: wire_token(detail.reason.as_deref(), 32),
958                ..PlanNeed::default()
959            }));
960        }
961        match detail.code {
962            CloudErrorCode::Unauthorized => Self::Unauthorized,
963            CloudErrorCode::LeaseExpired => Self::LeaseLapsed,
964            CloudErrorCode::InstanceRevoked => Self::Revoked(Revocation::of_statement(&revocation)),
965            CloudErrorCode::PlanRequired => Self::PlanRequired(Box::new(PlanNeed {
966                feature: wire_token(detail.feature.as_deref(), 64),
967                plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
968                limit: detail.limit,
969                used: detail.used,
970                message: safe_message(&detail.message),
971                plan: None,
972                reason: wire_token(detail.reason.as_deref(), 32),
973                next_step,
974                plans_url: None,
975                trial_reason: None,
976            })),
977            CloudErrorCode::InstanceLimit => Self::InstanceLimit(Box::new(InstanceCap {
978                resource: wire_token(detail.resource.as_deref(), 64),
979                limit: detail.limit,
980                used: detail.used,
981                seats: detail.seats,
982                per_seat: detail.per_seat,
983                next_step,
984            })),
985            CloudErrorCode::QuotaExceeded => Self::QuotaExceeded(Box::new(Quota {
986                status,
987                resource: wire_token(detail.resource.as_deref(), 64)
988                    .unwrap_or_else(|| "unknown".into()),
989                limit: detail.limit,
990                used: detail.used,
991                reset_at: wire_time(detail.reset_at.as_deref()),
992                retry_after: detail.retry_after_s,
993                cooldown_days: detail.cooldown_days,
994                next_step,
995            })),
996            CloudErrorCode::StorageQuotaExceeded => Self::StorageFull(Box::new(StorageFull {
997                limit: detail.limit_bytes.or(detail.limit),
998                used: detail.used_bytes.or(detail.used),
999                next_step,
1000            })),
1001            CloudErrorCode::UploadRateLimited => Self::UploadRateLimited {
1002                retry_after: detail.retry_after_s,
1003                per_hour: detail.limit_bytes_per_hour,
1004            },
1005            // Engine metrics v2 name the member `field` and the level
1006            // `reason` (`metrics_hours.error.policy_denied.json`).
1007            CloudErrorCode::PolicyDenied => Self::PolicyDenied(PolicyDenial {
1008                member: wire_token(detail.member.as_deref().or(detail.field.as_deref()), 80),
1009                level: wire_token(
1010                    detail.level.as_deref().or(detail
1011                        .reason
1012                        .as_deref()
1013                        .filter(|r| matches!(*r, "org" | "workspace" | "vault" | "instance"))),
1014                    16,
1015                ),
1016                action: wire_token(detail.action.as_deref(), 64),
1017            }),
1018            CloudErrorCode::ForbiddenRight if value_reason.as_str() == Some("vetoed") => {
1019                Self::Vetoed
1020            }
1021            CloudErrorCode::ForbiddenRight => Self::Forbidden,
1022            CloudErrorCode::UploadDisabled => {
1023                Self::UploadDisabled(detail.kind.unwrap_or(CloudUploadKind::Unknown))
1024            }
1025            CloudErrorCode::NotFound => Self::NotFound,
1026            CloudErrorCode::FeatureDisabled => Self::FeatureDisabled {
1027                feature: wire_token(detail.feature.as_deref(), 64),
1028            },
1029            CloudErrorCode::RevisionConflict => Self::Conflict {
1030                expected: detail.expected,
1031                actual: detail.actual,
1032            },
1033            CloudErrorCode::ScreeningRequired => Self::ScreeningBlocked,
1034            CloudErrorCode::UpgradeRequired => Self::UpgradeRequired {
1035                min: detail.min_instance,
1036            },
1037            CloudErrorCode::RateLimited => Self::RateLimited {
1038                retry_after: detail.retry_after_s,
1039            },
1040            CloudErrorCode::ExpiredToken => Self::DeviceFlow(CODE_EXPIRED.into()),
1041            CloudErrorCode::AccessDenied => Self::DeviceFlow(CODE_DENIED.into()),
1042            // Any other code on a 429 (`server_busy`, a newer one) is a rate
1043            // limit: back off, never give up.
1044            _ if status == 429 => Self::RateLimited {
1045                retry_after: detail.retry_after_s,
1046            },
1047            CloudErrorCode::Unknown => Self::of_status(status, detail.retry_after_s),
1048            other => Self::Server {
1049                status,
1050                code: serde_json::to_value(other)
1051                    .ok()
1052                    .and_then(|v| v.as_str().map(str::to_string))
1053                    .unwrap_or_else(|| "unknown".into()),
1054            },
1055        }
1056    }
1057
1058    /// A plans page the service named as a path on its own origin
1059    /// (`402 trial_used`, `"/o/…"`) becomes a full address on `origin`, the
1060    /// Cloud that answered. A full address is kept only on that same
1061    /// origin (another host or an https→http downgrade is dropped like an
1062    /// invalid one); without an `http(s)` origin nothing is shown.
1063    #[must_use]
1064    pub fn with_origin(mut self, origin: &str) -> Self {
1065        if let Self::PlanRequired(need) = &mut self
1066            && let Some(url) = need.plans_url.take()
1067        {
1068            let base = origin.trim_end_matches('/');
1069            need.plans_url = if !(base.starts_with("https://") || base.starts_with("http://")) {
1070                None
1071            } else if url.starts_with('/') {
1072                Some(format!("{base}{url}"))
1073            } else if same_origin(&url, base) {
1074                Some(url)
1075            } else {
1076                None
1077            };
1078        }
1079        self
1080    }
1081
1082    /// A device code of a `--trial` connect that ran out: with a Cloud
1083    /// that refuses a used trial only in the browser, the code just
1084    /// expires, so the hint names the plans page instead of a new code.
1085    #[must_use]
1086    pub fn for_trial(self) -> Self {
1087        match self {
1088            Self::DeviceFlow(why) if why == CODE_EXPIRED => {
1089                Self::DeviceFlow(TRIAL_CODE_EXPIRED.into())
1090            }
1091            other => other,
1092        }
1093    }
1094
1095    /// An answer that names no code this engine can use (an edge proxy's
1096    /// HTML page, an unknown code), classified by its HTTP status.
1097    fn of_status(status: u16, retry_after: Option<u64>) -> Self {
1098        match status {
1099            429 => Self::RateLimited {
1100                retry_after: retry_after.map(|s| s.min(RETRY_AFTER_CAP_S)),
1101            },
1102            413 => Self::Server {
1103                status,
1104                code: "payload_too_large".into(),
1105            },
1106            _ => Self::Server {
1107                status,
1108                code: "unknown".into(),
1109            },
1110        }
1111    }
1112
1113    /// A `plan_required` of a feature names the workspace's plan as the
1114    /// lease of the calling session says it; every other error is kept.
1115    #[must_use]
1116    pub fn with_plan(mut self, plan: CloudPlan) -> Self {
1117        if let Self::PlanRequired(need) = &mut self
1118            && (need.feature.is_some() || need.locked().is_some())
1119            && plan != CloudPlan::Unknown
1120        {
1121            need.plan.get_or_insert(plan);
1122        }
1123        self
1124    }
1125
1126    /// Whether retrying later can help (a 408 request timeout counts: the
1127    /// request never reached a verdict).
1128    pub fn is_transient(&self) -> bool {
1129        match self {
1130            Self::QuotaExceeded(q) => q.waits(),
1131            other => matches!(
1132                other,
1133                Self::Offline(_)
1134                    | Self::RateLimited { .. }
1135                    | Self::UploadRateLimited { .. }
1136                    | Self::Server {
1137                        status: 408 | 500..,
1138                        ..
1139                    }
1140            ),
1141        }
1142    }
1143
1144    /// Seconds to wait before this may be tried again, when Cloud said so:
1145    /// `retry_after_s`/`Retry-After` of a 429, else the time until a
1146    /// waiting quota's `reset_at` (seen from `now`).
1147    pub fn retry_after_at(&self, now: lean_ctx_time::UtcDateTime) -> Option<u64> {
1148        match self {
1149            Self::RateLimited { retry_after } | Self::UploadRateLimited { retry_after, .. } => {
1150                *retry_after
1151            }
1152            Self::QuotaExceeded(q) if q.waits() => q.retry_after.or_else(|| {
1153                let reset =
1154                    lean_ctx_time::OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
1155                        .ok()?;
1156                u64::try_from((reset.to_utc() - now).num_seconds().max(1)).ok()
1157            }),
1158            _ => None,
1159        }
1160    }
1161}
1162
1163impl fmt::Display for CloudError {
1164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165        match self {
1166            Self::Offline(why) => write!(f, "The Cloud is not reachable ({why})"),
1167            Self::NotConnected => f.write_str("not connected to the Cloud (run `lean-ctx cloud connect`)"),
1168            Self::Unauthorized => f.write_str(
1169                "The Cloud does not accept this instance any more (run `lean-ctx cloud connect` again)",
1170            ),
1171            Self::PlanRequired(need) => {
1172                write_plan_need(f, need)?;
1173                // A locked or trial_used line already says to choose a plan.
1174                if need.locked().is_none() && !need.trial_used() {
1175                    write_hint(f, need.next_step)?;
1176                }
1177                Ok(())
1178            }
1179            Self::InstanceLimit(cap) => write_instance_cap(f, cap),
1180            Self::QuotaExceeded(q) => write_quota(f, q),
1181            Self::StorageFull(s) => {
1182                f.write_str("this workspace's Cloud storage is full")?;
1183                if let (Some(used), Some(limit)) = (s.used, s.limit) {
1184                    write!(f, " ({} of {})", bytes_text(used), bytes_text(limit))?;
1185                }
1186                f.write_str(
1187                    "; nothing is charged for more; uploads stop until storage frees (remove vaults or files in the Cloud)",
1188                )?;
1189                write_hint(f, s.next_step)
1190            }
1191            Self::UploadRateLimited {
1192                retry_after,
1193                per_hour,
1194            } => {
1195                f.write_str("The Cloud's upload allowance for this hour is used up")?;
1196                if let Some(per_hour) = per_hour {
1197                    write!(f, " ({} per hour)", bytes_text(*per_hour))?;
1198                }
1199                match retry_after {
1200                    Some(s) => write!(f, "; the rest goes out in {s} s")?,
1201                    None => f.write_str("; the rest goes out later")?,
1202                }
1203                f.write_str(" (a large first sync can take a few hours)")
1204            }
1205            Self::PolicyDenied(d) => {
1206                f.write_str("Cloud policy refuses this")?;
1207                if let Some(member) = &d.member {
1208                    write!(f, " ({member}")?;
1209                    if let Some(level) = &d.level {
1210                        write!(f, ", set at the {level} level")?;
1211                    }
1212                    f.write_str(")")?;
1213                }
1214                match &d.action {
1215                    Some(action) => write!(
1216                        f,
1217                        "; a person does this on the Cloud website ({})",
1218                        action.replace('_', " ")
1219                    ),
1220                    None => f.write_str(
1221                        "; it is not retried until an admin changes the policy in the Cloud",
1222                    ),
1223                }
1224            }
1225            Self::LeaseLapsed => {
1226                f.write_str("the Cloud lease has lapsed (run `lean-ctx cloud connect` again)")
1227            }
1228            Self::Revoked(r) => {
1229                f.write_str("this instance was revoked by ")?;
1230                match &r.workspace {
1231                    Some(workspace) => f.write_str(workspace)?,
1232                    None => f.write_str("its workspace")?,
1233                }
1234                if let Some(reason) = &r.reason {
1235                    write!(f, " ({})", reason.replace('_', " "))?;
1236                }
1237                f.write_str("; reconnect with `lean-ctx cloud connect` after an admin allows it")
1238            }
1239            Self::Forbidden => f.write_str("The Cloud does not allow this for your account"),
1240            Self::Vetoed => f.write_str("a workspace veto bars it until the veto is lifted"),
1241            Self::UploadDisabled(kind) => match kind {
1242                CloudUploadKind::Metrics => {
1243                    f.write_str("the workspace has switched metrics upload off")
1244                }
1245                CloudUploadKind::Receipts => {
1246                    f.write_str("the workspace has switched receipts upload off")
1247                }
1248                CloudUploadKind::Unknown => {
1249                    f.write_str("the workspace has switched this upload off")
1250                }
1251            },
1252            Self::NotFound => f.write_str("The Cloud does not know that item"),
1253            Self::FeatureDisabled { feature } => match feature.as_deref() {
1254                Some("instance_metrics") | None => f.write_str(
1255                    "this Cloud server has switched off instance metrics; nothing was sent",
1256                ),
1257                Some(other) => write!(
1258                    f,
1259                    "this Cloud server has switched off {}; nothing was sent",
1260                    other.replace('_', " ")
1261                ),
1262            },
1263            Self::Conflict { expected, actual } => match (expected, actual) {
1264                (Some(e), Some(a)) => {
1265                    write!(f, "knowledge moved on (expected revision {e}, now {a})")
1266                }
1267                _ => f.write_str("knowledge moved on"),
1268            },
1269            Self::ScreeningBlocked => f.write_str("Cloud screening refused the content"),
1270            Self::UpgradeRequired { min } => match min {
1271                Some(min) => write!(f, "The Cloud needs lean-ctx {min} or newer (run `lean-ctx update`)"),
1272                None => f.write_str("The Cloud needs a newer lean-ctx (run `lean-ctx update`)"),
1273            },
1274            Self::RateLimited { retry_after } => match retry_after {
1275                Some(s) => write!(f, "The Cloud asks to try again in {s} s"),
1276                None => f.write_str("The Cloud asks to try again later"),
1277            },
1278            Self::DeviceFlow(why) => write!(f, "connection not approved: {why}"),
1279            Self::TrialUnsupported { origin } => write!(
1280                f,
1281                "LeanCTX does not offer the one-step trial here yet. Start the trial on {origin}, or sign in with `lean-ctx cloud connect`"
1282            ),
1283            Self::Protocol(why) => write!(f, "unexpected answer from Cloud: {why}"),
1284            Self::Config(why) => write!(f, "Cloud configuration: {why}"),
1285            Self::Local(why) => write!(f, "local Cloud state: {why}"),
1286            Self::Refused(why) => f.write_str(why),
1287            Self::Task {
1288                refusal,
1289                number,
1290                detail,
1291            } => {
1292                if let Some(number) = number {
1293                    write!(f, "task #{number}: ")?;
1294                }
1295                match detail {
1296                    // A not_permitted detail is the whole line (`permit_line`).
1297                    Some(detail) if matches!(refusal, TaskRefusal::NotPermitted(_)) => {
1298                        f.write_str(detail)
1299                    }
1300                    Some(detail) => write!(f, "{refusal} ({detail})"),
1301                    None => write!(f, "{refusal}"),
1302                }
1303            }
1304            Self::Server { status, code } => write!(f, "The Cloud answered {status} ({code})"),
1305        }
1306    }
1307}
1308
1309impl std::error::Error for CloudError {}
1310
1311/// A device code that ran out before anyone approved it.
1312pub const CODE_EXPIRED: &str =
1313    "the code expired before it was approved; run `lean-ctx cloud connect` again for a new one";
1314
1315/// A `--trial` device code that ran out ([`CloudError::for_trial`]).
1316pub const TRIAL_CODE_EXPIRED: &str = "the code expired before it was approved. If the browser said this address already had its trial, choose a plan in the Cloud, then run `lean-ctx cloud connect`; otherwise run `lean-ctx cloud connect --trial` again for a new code";
1317
1318/// A device code the person refused in the browser.
1319pub const CODE_DENIED: &str =
1320    "you chose \"Not mine\" in the browser; nothing changed on this machine";
1321
1322impl CloudError {
1323    /// The `code` of a `cloud connect --json` error event: `trial_used`,
1324    /// `trial_unsupported`, `expired`, `denied`, `plan_required`,
1325    /// `instance_limit`, `offline`, `unauthorized`, `rate_limited`,
1326    /// `upgrade_required`, `config`, `protocol`, `local`, the service's own
1327    /// code for any other answer, else `error`.
1328    #[must_use]
1329    pub fn event_code(&self) -> String {
1330        match self {
1331            Self::PlanRequired(need) if need.trial_used() => TRIAL_USED.into(),
1332            Self::PlanRequired(_) => "plan_required".into(),
1333            Self::TrialUnsupported { .. } => "trial_unsupported".into(),
1334            Self::DeviceFlow(why) if why == CODE_EXPIRED || why == TRIAL_CODE_EXPIRED => {
1335                "expired".into()
1336            }
1337            Self::DeviceFlow(why) if why == CODE_DENIED => "denied".into(),
1338            // rc4-67: a refused task-propose key keeps its own reason.
1339            Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_REFUSED => {
1340                TASK_KEY_INVALID.into()
1341            }
1342            Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_ALREADY_BOUND => {
1343                TASK_KEY_BOUND.into()
1344            }
1345            Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_WAS_REMOVED => {
1346                TASK_KEY_CLEARED.into()
1347            }
1348            // rc4-16: a refused opt-in key keeps its own reason (§46.4).
1349            Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_REFUSED => {
1350                OPTIN_KEY_INVALID.into()
1351            }
1352            Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_ALREADY_BOUND => {
1353                OPTIN_KEY_BOUND.into()
1354            }
1355            Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_WAS_REMOVED => {
1356                OPTIN_KEY_CLEARED.into()
1357            }
1358            Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_TOKEN_ENROLLMENT => {
1359                "token_enrollment".into()
1360            }
1361            // f3129 §11: either app-key refusal reads "Pairing failed"; the
1362            // app keeps telling it apart by this code.
1363            Self::DeviceFlow(why) if why == crate::auth::APP_KEY_PAIRING_FAILED => {
1364                APP_KEY_NOT_ANNOUNCED.into()
1365            }
1366            Self::DeviceFlow(_) => "not_approved".into(),
1367            Self::InstanceLimit(_) => "instance_limit".into(),
1368            Self::QuotaExceeded(_) => "quota_exceeded".into(),
1369            Self::Offline(_) => "offline".into(),
1370            Self::Unauthorized => "unauthorized".into(),
1371            Self::Revoked(_) => "instance_revoked".into(),
1372            Self::RateLimited { .. } => "rate_limited".into(),
1373            Self::UpgradeRequired { .. } => "upgrade_required".into(),
1374            Self::Config(_) => "config".into(),
1375            Self::Protocol(_) => "protocol".into(),
1376            Self::Local(_) => "local".into(),
1377            Self::Server { code, .. } if wire_token(Some(code), 64).is_some() => code.clone(),
1378            _ => "error".into(),
1379        }
1380    }
1381}
1382
1383/// Where a person frees or recovers an engine slot (P7): the recovery
1384/// route (`POST /api/v1/orgs/{o}/instances/{id}/recover`, owner with a
1385/// second factor) is on the web only.
1386pub const RECOVER_HINT: &str = "for a lost or broken device, recover its slot now on the Cloud website (Hosts › Recover the slot now, with your second factor; once per 30 days)";
1387
1388/// The head of a full host count, in the web's words (rc4-58, rc4-62).
1389fn host_cap_head(resource: &str) -> Option<&'static str> {
1390    match resource {
1391        "registered_instances" => Some("all hosts the plan includes are registered"),
1392        "connected_instances" => Some("all hosts that may be connected at once are connected"),
1393        _ => None,
1394    }
1395}
1396
1397/// An `instance_limit` refusal: connected at once is freed by disconnecting
1398/// one, registered by revoking one.
1399fn write_instance_cap(f: &mut fmt::Formatter<'_>, cap: &InstanceCap) -> fmt::Result {
1400    let connected = cap.resource.as_deref() == Some("connected_instances");
1401    let resource = if connected {
1402        "connected_instances"
1403    } else {
1404        "registered_instances"
1405    };
1406    f.write_str(host_cap_head(resource).unwrap_or_default())?;
1407    if let (Some(used), Some(limit)) = (cap.used, cap.limit) {
1408        write!(f, " ({used} of {limit}")?;
1409        if let (Some(seats), Some(per_seat)) = (cap.seats, cap.per_seat) {
1410            write!(f, ": {seats} seats, {per_seat} per seat")?;
1411        }
1412        f.write_str(")")?;
1413    }
1414    if connected {
1415        write!(f, "; {FREE_CONNECTED}, or upgrade the plan")?;
1416    } else {
1417        write!(f, "; {FREE_REGISTERED}, or upgrade the plan")?;
1418    }
1419    write_hint(f, cap.next_step)
1420}
1421
1422/// A quota resource as people read it (`storage_bytes` is "storage").
1423#[must_use]
1424pub fn quota_label(resource: &str) -> &str {
1425    match resource {
1426        "transfer_bytes" => "monthly transfer",
1427        "bus_messages" => "monthly bus messages",
1428        "registered_instances" => HOSTS_REGISTERED,
1429        "private_vaults" => "private vaults",
1430        "connected_instances" => HOSTS_CONNECTED,
1431        "storage_bytes" => "storage",
1432        "model_credit_usd_micros" => "model credit",
1433        other => other,
1434    }
1435}
1436
1437fn write_quota(f: &mut fmt::Formatter<'_>, q: &Quota) -> fmt::Result {
1438    let what = quota_label(&q.resource);
1439    if let Some(head) = host_cap_head(&q.resource) {
1440        f.write_str(head)?;
1441        if let (Some(used), Some(limit)) = (q.used, q.limit) {
1442            write!(f, " ({used} of {limit})")?;
1443        }
1444    } else {
1445        write!(f, "this workspace has used all its {what}")?;
1446        if let (Some(used), Some(limit)) = (q.used, q.limit) {
1447            write!(
1448                f,
1449                " ({} of {})",
1450                amount_text(&q.resource, used),
1451                amount_text(&q.resource, limit)
1452            )?;
1453        }
1454    }
1455    f.write_str("; nothing is charged for more")?;
1456    match q.resource.as_str() {
1457        "registered_instances" if q.cooling_slot() => write!(
1458            f,
1459            "; a revoked host stays registered until {} ({}-day cool-down), or {RECOVER_HINT}",
1460            q.reset_at.as_deref().unwrap_or("?"),
1461            q.cooldown_days.unwrap_or(0)
1462        )?,
1463        "registered_instances" => write!(f, "; {FREE_REGISTERED}, or upgrade the plan")?,
1464        "connected_instances" => write!(f, "; {FREE_CONNECTED}")?,
1465        "private_vaults" => {
1466            f.write_str("; remove or publish a vault in the Cloud, or upgrade the plan")?;
1467        }
1468        // Model credit holds like a monthly quota (mz6) but queues no upload.
1469        "model_credit_usd_micros" => {}
1470        _ if q.waits() => match &q.reset_at {
1471            Some(at) => write!(f, "; uploads wait in the local outbox until {at}")?,
1472            None => f.write_str("; uploads wait in the local outbox until it frees")?,
1473        },
1474        _ => {}
1475    }
1476    write_hint(f, q.next_step)
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481    use super::*;
1482    use serde_json::json;
1483
1484    /// p37 `402 trial_used` (browser approve of a second trial): a plan
1485    /// refusal that says no second trial starts and where to choose a plan.
1486    #[test]
1487    fn trial_used_refusal_names_the_used_trial_and_the_plans_page() {
1488        let body = json!({"error": {
1489            "code": "trial_used",
1490            "message": "This address already had a trial.",
1491            "plan_needed": "team",
1492            "next_step": "subscribe",
1493            "plans_url": "https://cloud.leanctx.com/app/plans"
1494        }});
1495        let error = CloudError::from_response(402, &body);
1496        let CloudError::PlanRequired(need) = &error else {
1497            panic!("{error:?}");
1498        };
1499        assert!(need.trial_used());
1500        assert_eq!(need.plan_needed.as_deref(), Some("team"));
1501        assert_eq!(
1502            need.plans_url.as_deref(),
1503            Some("https://cloud.leanctx.com/app/plans")
1504        );
1505        assert_eq!(error.event_code(), "trial_used");
1506        assert!(!error.is_transient());
1507        assert_eq!(
1508            error.to_string(),
1509            "this address already had its Team trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/app/plans, then run `lean-ctx cloud connect`"
1510        );
1511        // The service's reason words the refusal; the event code stays.
1512        let ended = CloudError::from_response(
1513            402,
1514            &json!({"error": {"code": "trial_used", "reason": "trial_ended", "message": "",
1515                "plan_needed": "personal", "plans_url": "https://cloud.leanctx.com/app/plans"}}),
1516        );
1517        assert_eq!(ended.event_code(), "trial_used");
1518        assert_eq!(
1519            ended.to_string(),
1520            "the Personal trial of this address has ended; no second trial starts. Choose a plan at https://cloud.leanctx.com/app/plans, then run `lean-ctx cloud connect`"
1521        );
1522        let no_plan = CloudError::from_response(
1523            402,
1524            &json!({"error": {"code": "trial_used", "reason": "no_plan", "message": "",
1525                "plan_needed": "team"}}),
1526        );
1527        assert_eq!(no_plan.event_code(), "trial_used");
1528        assert!(no_plan.to_string().starts_with(
1529            "this address has no Team trial left and no plan; no second trial starts."
1530        ));
1531        // p37 !134 contract fixture: the plans page is a path on the
1532        // Cloud's origin, shown once the origin is known.
1533        let path = format!(
1534            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.trial_used.json",
1535            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1536        );
1537        let fixture: serde_json::Value =
1538            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
1539        let refused = CloudError::from_response(402, &fixture);
1540        assert_eq!(refused.event_code(), "trial_used");
1541        assert_eq!(
1542            refused.to_string(),
1543            "this address already had its Personal trial; no second trial starts. Choose a plan in the Cloud, then run `lean-ctx cloud connect`"
1544        );
1545        assert_eq!(
1546            refused
1547                .with_origin("https://cloud.leanctx.com/")
1548                .to_string(),
1549            "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/o/bob/billing/?plan=personal, then run `lean-ctx cloud connect`"
1550        );
1551        // A plans URL that is no web address is never shown.
1552        let hostile = CloudError::from_response(
1553            402,
1554            &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1555                "plans_url": "javascript:alert(1)"}}),
1556        );
1557        assert_eq!(
1558            hostile.to_string(),
1559            "this address already had its Personal trial; no second trial starts. Choose a plan in the Cloud, then run `lean-ctx cloud connect`"
1560        );
1561        // An ordinary plan refusal keeps its own code.
1562        let plain = CloudError::from_response(
1563            402,
1564            &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
1565        );
1566        assert_eq!(plain.event_code(), "plan_required");
1567    }
1568
1569    fn trial_used_with(plans_url: &str) -> CloudError {
1570        CloudError::from_response(
1571            402,
1572            &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1573                "plans_url": plans_url}}),
1574        )
1575    }
1576
1577    const NO_PAGE: &str = "this address already had its Personal trial; no second trial starts. Choose a plan in the Cloud, then run `lean-ctx cloud connect`";
1578
1579    /// An absolute plans page is shown only on the origin of the Cloud
1580    /// that answered; another host, port or scheme is dropped.
1581    #[test]
1582    fn trial_plans_url_on_another_origin_is_not_shown() {
1583        let origin = "https://cloud.leanctx.com";
1584        assert_eq!(
1585            trial_used_with("https://Cloud.LeanCTX.com/app/plans?plan=personal")
1586                .with_origin(origin)
1587                .to_string(),
1588            "this address already had its Personal trial; no second trial starts. Choose a plan at https://Cloud.LeanCTX.com/app/plans?plan=personal, then run `lean-ctx cloud connect`"
1589        );
1590        for foreign in [
1591            "http://cloud.leanctx.com/app/plans",
1592            "https://evil.example/app/plans",
1593            "https://cloud.leanctx.com.evil.example/app/plans",
1594            "https://cloud.leanctx.com@evil.example/app/plans",
1595            "https://cloud.leanctx.com:8443/app/plans",
1596            "https://cloud.leanctx.com",
1597        ] {
1598            let shown = trial_used_with(foreign).with_origin(origin).to_string();
1599            let expected = if foreign == "https://cloud.leanctx.com" {
1600                "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com, then run `lean-ctx cloud connect`"
1601            } else {
1602                NO_PAGE
1603            };
1604            assert_eq!(shown, expected, "{foreign}");
1605        }
1606        // Without a web origin nothing is shown, a full address neither.
1607        assert_eq!(
1608            trial_used_with("https://cloud.leanctx.com/app/plans")
1609                .with_origin("file:///tmp")
1610                .to_string(),
1611            NO_PAGE
1612        );
1613    }
1614
1615    /// Bidi overrides, isolates and other format or invisible characters
1616    /// make a plans page unsafe to print; it is dropped like an invalid one.
1617    #[test]
1618    fn trial_plans_url_with_format_characters_is_not_shown() {
1619        for c in [
1620            '\u{202E}',
1621            '\u{202A}',
1622            '\u{2066}',
1623            '\u{2069}',
1624            '\u{200B}',
1625            '\u{200D}',
1626            '\u{200E}',
1627            '\u{061C}',
1628            '\u{00AD}',
1629            '\u{FEFF}',
1630            '\u{E0041}',
1631            '\u{3164}',
1632        ] {
1633            let url = format!("/o/bob/billing/{c}?plan=personal");
1634            assert_eq!(
1635                trial_used_with(&url)
1636                    .with_origin("https://cloud.leanctx.com")
1637                    .to_string(),
1638                NO_PAGE,
1639                "U+{:04X}",
1640                c as u32
1641            );
1642        }
1643        assert_eq!(
1644            trial_used_with("/o/bob/billing/?plan=personal")
1645                .with_origin("https://cloud.leanctx.com")
1646                .to_string(),
1647            "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/o/bob/billing/?plan=personal, then run `lean-ctx cloud connect`"
1648        );
1649    }
1650
1651    /// A Cloud that refuses a used trial only in the browser lets the
1652    /// code expire: the trial hint names the plans page, the event code
1653    /// stays `expired`, other errors are kept.
1654    #[test]
1655    fn trial_code_expiry_points_to_the_plans_page() {
1656        let expired = CloudError::DeviceFlow(CODE_EXPIRED.into()).for_trial();
1657        assert_eq!(expired, CloudError::DeviceFlow(TRIAL_CODE_EXPIRED.into()));
1658        assert_eq!(expired.event_code(), "expired");
1659        assert!(expired.to_string().contains("choose a plan in the Cloud"));
1660        assert!(
1661            !expired
1662                .to_string()
1663                .contains("run `lean-ctx cloud connect` again")
1664        );
1665        let denied = CloudError::DeviceFlow(CODE_DENIED.into());
1666        assert_eq!(denied.clone().for_trial(), denied);
1667        assert_eq!(
1668            CloudError::Offline("reset".into()).for_trial(),
1669            CloudError::Offline("reset".into())
1670        );
1671    }
1672
1673    #[test]
1674    fn trial_event_codes_name_the_device_flow_outcomes() {
1675        assert_eq!(
1676            CloudError::DeviceFlow(CODE_EXPIRED.into()).event_code(),
1677            "expired"
1678        );
1679        assert_eq!(
1680            CloudError::from_response(
1681                400,
1682                &json!({"error": {"code": "access_denied", "message": ""}})
1683            )
1684            .event_code(),
1685            "denied"
1686        );
1687        assert_eq!(
1688            CloudError::Server {
1689                status: 400,
1690                code: "invalid_request".into()
1691            }
1692            .event_code(),
1693            "invalid_request"
1694        );
1695        assert_eq!(
1696            CloudError::Server {
1697                status: 500,
1698                code: "Bad Code\n".into()
1699            }
1700            .event_code(),
1701            "error"
1702        );
1703        assert_eq!(CloudError::Offline("reset".into()).event_code(), "offline");
1704        // f3129 §11: "Pairing failed" keeps its own code for the app.
1705        assert_eq!(
1706            CloudError::DeviceFlow(crate::auth::APP_KEY_PAIRING_FAILED.into()).event_code(),
1707            APP_KEY_NOT_ANNOUNCED
1708        );
1709        assert_eq!(APP_KEY_NOT_ANNOUNCED, "app_key_not_announced");
1710        // Both app-key reasons are kept from the answer, others are not.
1711        for reason in [APP_KEY_NOT_ANNOUNCED, APP_KEY_BIND_INVALID] {
1712            let body = serde_json::json!({"error": {"code": "invalid_field",
1713                "field": "app_keys_bind_signature", "reason": reason, "message": "x"}});
1714            assert!(matches!(
1715                CloudError::from_response(400, &body),
1716                CloudError::Server { status: 400, code } if code == reason
1717            ));
1718        }
1719    }
1720
1721    /// f3129: `invalid_field` is a named protocol code now; it keeps its
1722    /// wire name instead of collapsing to `unknown`.
1723    #[test]
1724    fn invalid_field_keeps_its_code() {
1725        assert_eq!(
1726            CloudError::from_response(
1727                400,
1728                &json!({"error": {"code": "invalid_field", "message": "x",
1729                    "field": "chat_key.bind_signature"}}),
1730            ),
1731            CloudError::Server {
1732                status: 400,
1733                code: "invalid_field".into()
1734            }
1735        );
1736    }
1737
1738    /// Review fix: one member of an unexpected type no longer collapses the
1739    /// answer to `Server { "unknown" }`; code, reason and retry stay.
1740    #[test]
1741    fn a_detail_with_a_mistyped_member_keeps_its_code_and_retry() {
1742        let limited = CloudError::from_response(
1743            429,
1744            &json!({"error": {"code": "rate_limited", "message": "slow down",
1745                "retry_after_s": 12, "number": "seventeen"}}),
1746        );
1747        assert_eq!(
1748            limited,
1749            CloudError::RateLimited {
1750                retry_after: Some(12)
1751            }
1752        );
1753        // A numeric string is read as its number; the task refusal survives.
1754        let claimed = CloudError::from_response(
1755            409,
1756            &json!({"error": {"code": "invalid_state", "message": "x",
1757                "reason": "task_claimed", "number": "17", "limit": {"odd": true}}}),
1758        );
1759        assert!(
1760            matches!(
1761                claimed,
1762                CloudError::Task {
1763                    refusal: TaskRefusal::Claimed,
1764                    number: Some(17),
1765                    ..
1766                }
1767            ),
1768            "{claimed:?}"
1769        );
1770        let quota = CloudError::from_response(
1771            429,
1772            &json!({"error": {"code": "quota_exceeded", "message": "x",
1773                "resource": "bus_messages", "retry_after_s": "60", "used": -1}}),
1774        );
1775        let CloudError::QuotaExceeded(quota) = quota else {
1776            panic!("{quota:?}");
1777        };
1778        assert_eq!(
1779            (quota.resource.as_str(), quota.retry_after, quota.used),
1780            ("bus_messages", Some(60), None)
1781        );
1782        // No code at all: the status decides.
1783        assert_eq!(
1784            CloudError::from_response(400, &json!({"error": {"code": 7}})),
1785            CloudError::Server {
1786                status: 400,
1787                code: "unknown".into()
1788            }
1789        );
1790    }
1791
1792    /// Review fix: an edge's answer (no JSON, an unknown code) is classified
1793    /// by status: every 429 backs off, 5xx stays transient, 413 is named.
1794    #[test]
1795    fn edge_answers_are_classified_by_status() {
1796        let busy = CloudError::from_response(
1797            429,
1798            &json!({"error": {"code": "server_busy", "message": "x", "retry_after_s": 5}}),
1799        );
1800        assert_eq!(
1801            busy,
1802            CloudError::RateLimited {
1803                retry_after: Some(5)
1804            }
1805        );
1806        // The transport turns a bare `Retry-After` into this body.
1807        let header_only = CloudError::from_response(429, &json!({"error": {"retry_after_s": 9}}));
1808        assert_eq!(
1809            header_only,
1810            CloudError::RateLimited {
1811                retry_after: Some(9)
1812            }
1813        );
1814        assert_eq!(
1815            CloudError::from_response(429, &serde_json::Value::Null),
1816            CloudError::RateLimited { retry_after: None }
1817        );
1818        // 408: the server or an edge gave up waiting for the request; a retry can pass.
1819        for status in [408, 500, 502, 503, 504] {
1820            let down = CloudError::from_response(status, &serde_json::Value::Null);
1821            assert!(down.is_transient(), "{status}: {down:?}");
1822        }
1823        let too_large = CloudError::from_response(413, &serde_json::Value::Null);
1824        assert_eq!(
1825            too_large,
1826            CloudError::Server {
1827                status: 413,
1828                code: "payload_too_large".into()
1829            }
1830        );
1831        assert!(!too_large.is_transient());
1832    }
1833
1834    #[test]
1835    fn instance_limit_carries_the_seat_numbers() {
1836        let error = CloudError::from_response(
1837            409,
1838            &json!({"error": {"code": "instance_limit", "message": "x", "limit": 2, "used": 2}}),
1839        );
1840        assert_eq!(
1841            error,
1842            CloudError::InstanceLimit(Box::new(InstanceCap {
1843                limit: Some(2),
1844                used: Some(2),
1845                ..InstanceCap::default()
1846            }))
1847        );
1848        assert_eq!(
1849            error.to_string(),
1850            "all hosts the plan includes are registered (2 of 2); to free one, revoke a host you no longer use on the Hosts page, or upgrade the plan"
1851        );
1852    }
1853
1854    /// `connected_instances` is freed by disconnecting one, not removing it;
1855    /// a Team refusal names seats and the next step.
1856    #[test]
1857    fn a_connected_limit_says_disconnect_and_names_the_seats() {
1858        let error = CloudError::from_response(
1859            409,
1860            &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1861                              "limit": 4, "used": 4, "plan": "team", "next_step": "add_seats",
1862                              "seats": 2, "per_seat": 2}}),
1863        );
1864        assert_eq!(
1865            error,
1866            CloudError::InstanceLimit(Box::new(InstanceCap {
1867                resource: Some("connected_instances".into()),
1868                limit: Some(4),
1869                used: Some(4),
1870                seats: Some(2),
1871                per_seat: Some(2),
1872                next_step: Some(NextStep::AddSeats),
1873            }))
1874        );
1875        assert_eq!(
1876            error.to_string(),
1877            "all hosts that may be connected at once are connected (4 of 4: 2 seats, 2 per seat); to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine), or upgrade the plan; every seat you add in the Cloud brings its own allowance"
1878        );
1879        assert!(!error.is_transient());
1880        let personal = CloudError::from_response(
1881            409,
1882            &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1883                              "limit": 2, "used": 2, "plan": "personal", "next_step": "upgrade_team"}}),
1884        );
1885        assert!(
1886            personal
1887                .to_string()
1888                .ends_with("; Team gives every seat its own allowance"),
1889            "{personal}"
1890        );
1891    }
1892
1893    #[test]
1894    fn storage_full_decodes_with_bytes_and_is_not_retried() {
1895        let error = CloudError::from_response(
1896            403,
1897            &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "resource": "storage_bytes",
1898                              "limit": 1_073_741_824_u64, "used": 1_073_741_824_u64,
1899                              "limit_bytes": 1_073_741_824_u64, "used_bytes": 1_073_741_824_u64,
1900                              "plan": "personal", "next_step": "upgrade_team"}}),
1901        );
1902        assert_eq!(
1903            error,
1904            CloudError::StorageFull(Box::new(StorageFull {
1905                limit: Some(1 << 30),
1906                used: Some(1 << 30),
1907                next_step: Some(NextStep::UpgradeTeam),
1908            }))
1909        );
1910        assert!(!error.is_transient(), "waiting does not free storage");
1911        assert_eq!(
1912            error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1913            None
1914        );
1915        assert_eq!(
1916            error.to_string(),
1917            "this workspace's Cloud storage is full (1 GiB of 1 GiB); nothing is charged for more; uploads stop until storage frees (remove vaults or files in the Cloud); Team gives every seat its own allowance"
1918        );
1919        assert!(!error.to_string().contains("unknown"));
1920        // Without the byte fields, `limit`/`used` stand in; an unknown next
1921        // step adds nothing.
1922        let bare = CloudError::from_response(
1923            403,
1924            &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "limit": 1536, "used": 2048,
1925                              "next_step": "something_new"}}),
1926        );
1927        assert_eq!(
1928            bare,
1929            CloudError::StorageFull(Box::new(StorageFull {
1930                limit: Some(1536),
1931                used: Some(2048),
1932                next_step: None,
1933            }))
1934        );
1935        assert!(bare.to_string().contains("(2 KiB of 1.5 KiB)"), "{bare}");
1936    }
1937
1938    #[test]
1939    fn upload_rate_limited_is_transient_and_honours_retry_after() {
1940        let error = CloudError::from_response(
1941            429,
1942            &json!({"error": {"code": "upload_rate_limited", "message": "x",
1943                              "limit_bytes_per_hour": 268_435_456_u64, "plan": "personal",
1944                              "next_step": "wait", "retry_after_s": 1200}}),
1945        );
1946        assert_eq!(
1947            error,
1948            CloudError::UploadRateLimited {
1949                retry_after: Some(1200),
1950                per_hour: Some(256 << 20),
1951            }
1952        );
1953        assert!(error.is_transient());
1954        assert_eq!(
1955            error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1956            Some(1200)
1957        );
1958        assert_eq!(
1959            error.to_string(),
1960            "The Cloud's upload allowance for this hour is used up (256 MiB per hour); the rest goes out in 1200 s (a large first sync can take a few hours)"
1961        );
1962        // A huge wait is capped on the way in, like every retry_after_s.
1963        let huge = CloudError::from_response(
1964            429,
1965            &json!({"error": {"code": "upload_rate_limited", "message": "x", "retry_after_s": u64::MAX}}),
1966        );
1967        assert_eq!(
1968            huge.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1969            Some(RETRY_AFTER_CAP_S)
1970        );
1971    }
1972
1973    #[test]
1974    fn quota_hints_and_new_resource_labels() {
1975        let quota = |resource: &str, limit: u64, next: &str| {
1976            CloudError::from_response(
1977                409,
1978                &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": resource,
1979                                  "limit": limit, "used": limit, "plan": "personal", "next_step": next}}),
1980            )
1981            .to_string()
1982        };
1983        assert_eq!(
1984            quota("storage_bytes", 1 << 30, "upgrade_team"),
1985            "this workspace has used all its storage (1 GiB of 1 GiB); nothing is charged for more; Team gives every seat its own allowance"
1986        );
1987        assert_eq!(
1988            quota("model_credit_usd_micros", 8_000_000, "top_up"),
1989            "this workspace has used all its model credit ($8.00 of $8.00); nothing is charged for more; a top-up in the Cloud adds more"
1990        );
1991        assert!(
1992            quota("registered_instances", 3, "contact")
1993                .ends_with("; contact us to extend your Enterprise contract")
1994        );
1995        // rc4-58/rc4-62: the host counts in the web's words, with how to free one.
1996        assert_eq!(
1997            quota("registered_instances", 3, "upgrade_team"),
1998            "all hosts the plan includes are registered (3 of 3); nothing is charged for more; \
1999             to free one, revoke a host you no longer use on the Hosts page, or upgrade the plan; \
2000             Team gives every seat its own allowance"
2001        );
2002        assert_eq!(
2003            quota("connected_instances", 2, "wait"),
2004            "all hosts that may be connected at once are connected (2 of 2); \
2005             nothing is charged for more; to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)"
2006        );
2007        // The counts never say "slot" (the web dropped "Host slots"); only the
2008        // recovery names the web's menu item "Recover the slot now" (RECOVER_HINT).
2009        for resource in ["registered_instances", "connected_instances"] {
2010            let line = quota(resource, 2, "upgrade_team");
2011            for word in ["instance", "slot", "workspace"] {
2012                assert!(!line.contains(word), "{word} in {line}");
2013            }
2014        }
2015        // `wait` adds no hint: the line already says the outbox waits.
2016        let monthly = CloudError::from_response(
2017            429,
2018            &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": "bus_messages",
2019                              "limit": 200_000, "used": 200_000, "next_step": "wait",
2020                              "reset_at": "2026-12-01T00:00:00Z", "retry_after_s": 60}}),
2021        );
2022        assert_eq!(
2023            monthly.to_string(),
2024            "this workspace has used all its monthly bus messages (200000 of 200000); nothing is charged for more; uploads wait in the local outbox until 2026-12-01T00:00:00Z"
2025        );
2026        // A feature refusal shows its next step; a locked line does not add one.
2027        let feature = CloudError::from_response(
2028            402,
2029            &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export",
2030                              "plan_needed": "team", "next_step": "upgrade_team"}}),
2031        );
2032        assert_eq!(
2033            feature.to_string(),
2034            "audit export is included in Team and Enterprise; Team gives every seat its own allowance"
2035        );
2036        let locked = CloudError::from_response(
2037            402,
2038            &json!({"error": {"code": "plan_required", "message": "x", "feature": "read_only",
2039                              "reason": "trial_ended", "plan": "locked", "next_step": "subscribe",
2040                              "plan_needed": "personal"}}),
2041        );
2042        assert_eq!(
2043            locked.to_string(),
2044            "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again."
2045        );
2046    }
2047
2048    #[test]
2049    fn bytes_are_worded_in_binary_units() {
2050        assert_eq!(bytes_text(0), "0 B");
2051        assert_eq!(bytes_text(1023), "1023 B");
2052        assert_eq!(bytes_text(256 << 20), "256 MiB");
2053        assert_eq!(bytes_text(40 << 30), "40 GiB");
2054        assert_eq!(bytes_text(3 << 29), "1.5 GiB");
2055        assert_eq!(bytes_text(u64::MAX), "16777215.9 TiB");
2056    }
2057
2058    #[test]
2059    fn a_huge_retry_after_is_capped_on_the_way_in() {
2060        for huge in [u64::MAX, i64::MAX.unsigned_abs(), RETRY_AFTER_CAP_S + 1] {
2061            let error = CloudError::from_response(
2062                429,
2063                &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": huge}}),
2064            );
2065            assert_eq!(
2066                error,
2067                CloudError::RateLimited {
2068                    retry_after: Some(RETRY_AFTER_CAP_S)
2069                }
2070            );
2071        }
2072        let small = CloudError::from_response(
2073            429,
2074            &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": 90}}),
2075        );
2076        assert_eq!(
2077            small,
2078            CloudError::RateLimited {
2079                retry_after: Some(90)
2080            }
2081        );
2082    }
2083
2084    #[test]
2085    fn upload_disabled_names_the_kind_and_is_not_retried() {
2086        let error = CloudError::from_response(
2087            403,
2088            &json!({"error": {"code": "upload_disabled", "message": "x", "kind": "metrics"}}),
2089        );
2090        assert_eq!(error, CloudError::UploadDisabled(CloudUploadKind::Metrics));
2091        assert!(!error.is_transient());
2092        assert!(error.to_string().contains("metrics upload off"));
2093    }
2094
2095    #[test]
2096    fn task_reasons_become_task_refusals_and_others_stay() {
2097        let refusal = |status, code: &str, reason: &str| {
2098            CloudError::from_response(
2099                status,
2100                &json!({"error": {"code": code, "message": "x", "reason": reason, "number": 7, "retry_after_s": 60}}),
2101            )
2102        };
2103        assert_eq!(
2104            refusal(409, "invalid_state", "stale_claim"),
2105            CloudError::Task {
2106                refusal: TaskRefusal::StaleClaim,
2107                number: Some(7),
2108                detail: None
2109            }
2110        );
2111        assert_eq!(
2112            refusal(403, "forbidden_right", "optin_scope"),
2113            CloudError::Task {
2114                refusal: TaskRefusal::OptinScope,
2115                number: Some(7),
2116                detail: None
2117            }
2118        );
2119        // Cloud task #17: a not_permitted refusal says which check failed and the roles.
2120        let permit_said = |check: &str, agent_role: Option<&str>, message: &str| {
2121            let mut e = json!({"error": {"code": "forbidden_right", "message": message,
2122                                         "reason": "not_permitted", "number": 7, "check": check,
2123                                         "role": "backend"}});
2124            if let Some(r) = agent_role {
2125                e["error"]["agent_role"] = r.into();
2126            }
2127            CloudError::from_response(403, &e).to_string()
2128        };
2129        let permit = |check: &str, agent_role: Option<&str>| permit_said(check, agent_role, "");
2130        assert_eq!(
2131            permit("presence", None),
2132            "task #7: this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role (the task needs role backend) [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. The Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs."
2133        );
2134        assert_eq!(
2135            permit("role", Some("web")),
2136            "task #7: this agent is on the bus in another role than the task needs (the agent works as web, the task needs backend) [check: role]"
2137        );
2138        assert!(
2139            permit("role", Some("web\u{1b}[31m"))
2140                .ends_with("(the task needs role backend) [check: role]"),
2141            "a role that is not a bus identifier is not printed"
2142        );
2143        // The service's own message is printed, with the check and the hint.
2144        assert_eq!(
2145            permit_said(
2146                "presence",
2147                None,
2148                "Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again."
2149            ),
2150            "task #7: Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again. [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. The Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs."
2151        );
2152        assert_eq!(
2153            permit_said(
2154                "role",
2155                Some("web"),
2156                "Agent coder-1 works as role web;\u{1b}[31m this task needs role backend."
2157            ),
2158            "task #7: Agent coder-1 works as role web; [31m this task needs role backend. [check: role]",
2159            "control characters of the service's message never reach the terminal"
2160        );
2161        // A Cloud that names no check still has its message printed.
2162        assert_eq!(
2163            permit_said("", None, "Agent coder-1 may not take this task."),
2164            "task #7: Agent coder-1 may not take this task."
2165        );
2166        let inactive = refusal(409, "invalid_state", "optin_inactive");
2167        assert!(matches!(inactive, CloudError::Task { refusal, .. } if refusal.ends_claim()));
2168        assert!(matches!(
2169            refusal(409, "invalid_state", "optin_changed"),
2170            CloudError::Task {
2171                refusal: TaskRefusal::OptinChanged,
2172                ..
2173            }
2174        ));
2175        let budget = refusal(429, "rate_limited", "daily_budget");
2176        assert_eq!(
2177            budget,
2178            CloudError::Task {
2179                refusal: TaskRefusal::DailyBudget {
2180                    retry_after: Some(60)
2181                },
2182                number: Some(7),
2183                detail: None
2184            }
2185        );
2186        assert!(!budget.is_transient(), "a used-up budget is not retried");
2187        assert!(
2188            budget
2189                .to_string()
2190                .starts_with("task #7: today's task budget")
2191        );
2192        // The contract's own error fixtures decode to the same refusals.
2193        for (fixture, expected) in [
2194            ("error.optin_scope.json", TaskRefusal::OptinScope),
2195            ("error.optin_changed.json", TaskRefusal::OptinChanged),
2196            ("error.optin_inactive.json", TaskRefusal::OptinInactive),
2197            (
2198                "error.daily_budget.json",
2199                TaskRefusal::DailyBudget {
2200                    retry_after: Some(43200),
2201                },
2202            ),
2203            ("error.task_claimed.json", TaskRefusal::Claimed),
2204            (
2205                "error.task_not_permitted.json",
2206                TaskRefusal::NotPermitted(PermitCheck::Unknown),
2207            ),
2208            (
2209                "error.task_not_permitted_role.json",
2210                TaskRefusal::NotPermitted(PermitCheck::Role),
2211            ),
2212        ] {
2213            let path = format!(
2214                "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/{fixture}",
2215                concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2216            );
2217            let body: serde_json::Value =
2218                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2219            let code: CloudErrorCode =
2220                serde_json::from_value(body["error"]["code"].clone()).unwrap();
2221            assert!(
2222                matches!(
2223                    CloudError::from_response(code.http_status(), &body),
2224                    CloudError::Task { refusal, .. } if refusal == expected
2225                ),
2226                "{fixture}"
2227            );
2228        }
2229        // C0 2.2 E48: the verify refusals of the cloud-v2 contract.
2230        for (fixture, expected) in [
2231            (
2232                "task_verify.error.self_verify.json",
2233                TaskRefusal::SelfVerify,
2234            ),
2235            (
2236                "task_verify.error.not_submitted.json",
2237                TaskRefusal::NotSubmitted,
2238            ),
2239        ] {
2240            let path = format!(
2241                "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes/{fixture}",
2242                concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2243            );
2244            let body: serde_json::Value =
2245                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2246            let code: CloudErrorCode =
2247                serde_json::from_value(body["error"]["code"].clone()).unwrap();
2248            assert!(
2249                matches!(
2250                    CloudError::from_response(code.http_status(), &body),
2251                    CloudError::Task { refusal, .. } if refusal == expected
2252                ),
2253                "{fixture}"
2254            );
2255        }
2256        assert_eq!(
2257            refusal(403, "forbidden_right", "vetoed"),
2258            CloudError::Vetoed
2259        );
2260        assert_eq!(
2261            refusal(409, "invalid_state", "code_graph_disabled"),
2262            CloudError::Server {
2263                status: 409,
2264                code: "invalid_state".into()
2265            },
2266            "a reason of another section keeps its old meaning"
2267        );
2268    }
2269
2270    /// The `plan_required` example of a C0 2.x web fixture, by feature.
2271    fn plan_required_example(file: &str, feature: &str) -> (u16, serde_json::Value) {
2272        let path = format!(
2273            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/web/{file}",
2274            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2275        );
2276        let fixture: serde_json::Value =
2277            serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2278        let example = fixture["errors"]
2279            .as_array()
2280            .expect("errors")
2281            .iter()
2282            .find(|e| {
2283                e["body"]["error"]["code"] == "plan_required"
2284                    && e["body"]["error"]["feature"] == feature
2285            })
2286            .unwrap_or_else(|| panic!("{file}: no plan_required {feature}"));
2287        (
2288            u16::try_from(example["status"].as_u64().unwrap()).unwrap(),
2289            example["body"].clone(),
2290        )
2291    }
2292
2293    #[test]
2294    fn plan_required_keeps_the_feature_and_words_it() {
2295        // A vault limit (W11 transfer into a no-plan workspace).
2296        let (status, body) = plan_required_example("vault-transfer.json", "repos");
2297        assert_eq!(status, 402);
2298        let error = CloudError::from_response(status, &body);
2299        assert!(
2300            matches!(&error, CloudError::PlanRequired(need) if need.feature.as_deref() == Some("repos"))
2301        );
2302        assert_eq!(
2303            error.clone().with_plan(CloudPlan::Unknown),
2304            error,
2305            "an unknown plan is not named"
2306        );
2307        assert!(!error.is_transient());
2308        let repos = error.with_plan(CloudPlan::NoPlan);
2309        assert!(!repos.to_string().contains("engine"));
2310        assert_eq!(
2311            repos.to_string(),
2312            "this workspace has used all its vaults (3 of 3); more are included in Personal, Team and Enterprise; this workspace has no plan; remove or publish a vault in the Cloud, or upgrade the plan"
2313        );
2314
2315        // Any other feature: the service's words (a company comes with Enterprise).
2316        let (status, body) = plan_required_example("organisation-create.json", "company");
2317        let org = CloudError::from_response(status, &body).with_plan(CloudPlan::Team);
2318        assert_eq!(
2319            org.to_string(),
2320            "A company comes with Enterprise, on request: send a request and we set it up with you; this workspace is on Team"
2321        );
2322        let unnamed = CloudError::from_response(
2323            402,
2324            &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
2325        );
2326        assert_eq!(
2327            unnamed.to_string(),
2328            "audit export is included in Team and Enterprise"
2329        );
2330        let hostile = CloudError::from_response(
2331            402,
2332            &json!({"error": {"code": "plan_required", "message": "x\u{1b}[2J", "feature": "Comp\u{1b}"}}),
2333        );
2334        assert_eq!(
2335            hostile,
2336            CloudError::PlanRequired(Box::new(PlanNeed {
2337                message: Some("x [2J".into()),
2338                ..PlanNeed::default()
2339            })),
2340            "a feature that is not a wire token is dropped, the message is terminal-safe"
2341        );
2342    }
2343
2344    #[test]
2345    fn plan_required_without_a_feature_keeps_the_1x_seat_text() {
2346        let path = format!(
2347            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.plan_required.json",
2348            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2349        );
2350        let body: serde_json::Value =
2351            serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2352        let error = CloudError::from_response(402, &body).with_plan(CloudPlan::NoPlan);
2353        assert_eq!(
2354            error.to_string(),
2355            "your plan does not include the Cloud on this machine (Personal up to 3 hosts registered, up to 2 connected at once; Team and Enterprise up to 3 hosts registered, up to 2 connected at once per seat)"
2356        );
2357        assert!(
2358            matches!(&error, CloudError::PlanRequired(need) if need.plan.is_none()),
2359            "a 1.x refusal is about the Cloud itself, not a feature of the plan"
2360        );
2361    }
2362
2363    #[test]
2364    fn a_locked_workspace_is_one_line_whatever_the_feature() {
2365        let locked = |reason: &str, feature: Option<&str>, needed: &str| {
2366            let mut body = json!({"error": {"code": "plan_required", "message": "Your trial has ended: this workspace is locked.",
2367                                            "plan_needed": needed, "reason": reason}});
2368            if let Some(f) = feature {
2369                body["error"]["feature"] = f.into();
2370            }
2371            CloudError::from_response(402, &body)
2372        };
2373        let trial = "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again.";
2374        for feature in [None, Some("read_only")] {
2375            let e = locked("trial_ended", feature, "personal");
2376            assert_eq!(e.to_string(), trial);
2377            assert!(matches!(&e, CloudError::PlanRequired(n) if n.locked() == Some("trial_ended")));
2378            assert_eq!(
2379                e.with_plan(CloudPlan::Personal).to_string(),
2380                trial,
2381                "the lease's plan adds nothing to the line"
2382            );
2383        }
2384        assert_eq!(
2385            locked("plan_ended", Some("read_only"), "team").to_string(),
2386            "Your plan has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again."
2387        );
2388        assert_eq!(
2389            locked("trial_ended", None, "team").to_string(),
2390            "Your Team trial has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again."
2391        );
2392        // no_plan is not a lock of an ended plan: the feature's words stay.
2393        let no_plan = locked("no_plan", None, "personal");
2394        assert!(
2395            no_plan.to_string().contains("2 connected at once"),
2396            "{no_plan}"
2397        );
2398        assert!(!no_plan.to_string().contains(LOCKED_MARK));
2399    }
2400
2401    #[test]
2402    fn non_contract_bodies_become_server_errors() {
2403        assert_eq!(
2404            CloudError::from_response(502, &json!("<html>")),
2405            CloudError::Server {
2406                status: 502,
2407                code: "unknown".into()
2408            }
2409        );
2410        assert!(
2411            CloudError::Server {
2412                status: 502,
2413                code: "unknown".into()
2414            }
2415            .is_transient()
2416        );
2417    }
2418
2419    #[test]
2420    fn a_role_that_may_not_add_a_vault_is_forbidden() {
2421        let body = json!({"error": {
2422            "code": "vault_create_forbidden",
2423            "message": "Only an owner, admin or maintainer of this team can add a new vault.",
2424            "role_needed": "maintainer",
2425        }});
2426        assert_eq!(CloudError::from_response(403, &body), CloudError::Forbidden);
2427        // Another status with that code is no role refusal.
2428        assert_ne!(CloudError::from_response(500, &body), CloudError::Forbidden);
2429    }
2430}