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