Skip to main content

lean_ctx_cloud/workers/
register.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Worker registration and the instance card on Cloud (C0 2.0 §3.17.1,
3//! §3.18.1): E10 `POST /v1/workers` and E44 `PATCH /v1/instances/{id}/card`
4//! are signed by the instance key as `domain ‖ canonical_json(body)`;
5//! E11 `PATCH /v1/workers/{wkr}` rides on the instance token alone.
6
7use base64::Engine as _;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
9use ed25519_dalek::Signer as _;
10use serde::{Deserialize, Serialize};
11use serde_json::{Value, json};
12
13use super::super::CloudError;
14use super::super::instance_key::InstanceKeys;
15use super::super::transport::CloudClient;
16use super::card::WorkerCard;
17use super::{WorkerAliasKey, alias_signing_key, check_name, key_id};
18
19pub const WORKER_DOMAIN: &str = "leanctx.cloud.worker.v1\n";
20pub const INSTANCE_CARD_DOMAIN: &str = "leanctx.cloud.instance_card.v1\n";
21
22/// Who is registered: the workspace worker, or its alias in one public
23/// vault or swarm (`place_ref` = `"{kind}:{id}"`).
24pub struct Registration<'a> {
25    pub instance_id: &'a str,
26    pub host_app: &'a str,
27    pub role: &'a str,
28    pub name: &'a str,
29    pub card: &'a WorkerCard,
30    pub alias_place: Option<&'a str>,
31}
32
33/// Add `key_id` and the instance signature over the body without them.
34fn sign(keys: &InstanceKeys, domain: &str, mut body: Value) -> Result<Value, CloudError> {
35    let signer = keys.signing_key();
36    body["key_id"] = key_id(signer).into();
37    let input = lean_ctx_protocol::cloud::signing_input(domain, &body)
38        .map_err(|e| CloudError::Local(e.to_string()))?;
39    body["signature"] = hex::encode(signer.sign(&input).to_bytes()).into();
40    Ok(body)
41}
42
43/// The signed E10 body. The name passes the local rule first
44/// (`invalid_name`, SPEC-ENGINE §3.6).
45pub fn register_body(keys: &InstanceKeys, reg: &Registration<'_>) -> Result<Value, CloudError> {
46    let name = check_name(reg.name)
47        .map_err(|refusal| CloudError::Config(format!("invalid_name: {}", refusal.message())))?;
48    let card = serde_json::to_value(reg.card).map_err(|e| CloudError::Local(e.to_string()))?;
49    let mut body = json!({
50        "host_app": reg.host_app,
51        "role": reg.role,
52        "name": name,
53        "card": card,
54    });
55    match reg.alias_place {
56        None => {
57            body["worker_id"] =
58                super::workspace_worker_id(reg.instance_id, reg.host_app, reg.role).into();
59        }
60        Some(place) => {
61            let alias = WorkerAliasKey::of(keys);
62            body["worker_id"] = alias.worker_id(reg.host_app, reg.role, place).into();
63            body["place"] = place.into();
64            body["alias_pubkey"] = B64URL
65                .encode(alias_signing_key(keys, place).verifying_key().as_bytes())
66                .into();
67            body["hlc_node"] = alias.hlc_node(place).into();
68        }
69    }
70    sign(keys, WORKER_DOMAIN, body)
71}
72
73/// Consent channel the engine reports; the server derives the real one
74/// from the bound presence key and a card can only downgrade it.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ConsentChannel {
78    OsPresence,
79    TtyOnly,
80}
81
82/// The signed E44 body. `clear_presence_key` sends `presence_key: null`,
83/// which drops the bound key (e.g. after the helper was removed); a card
84/// can never set or replace one.
85pub fn instance_card_body(
86    keys: &InstanceKeys,
87    instance_version: &str,
88    consent_channel: ConsentChannel,
89    clear_presence_key: bool,
90) -> Result<Value, CloudError> {
91    let mut body = json!({
92        "instance_version": instance_version,
93        "consent_channel": consent_channel,
94    });
95    if clear_presence_key {
96        body["presence_key"] = Value::Null;
97    }
98    sign(keys, INSTANCE_CARD_DOMAIN, body)
99}
100
101/// E10 response: the worker as Cloud stored it.
102#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
103pub struct RegisteredWorker {
104    pub id: String,
105    pub name: String,
106    pub place: Option<String>,
107    pub status: String,
108    pub registered_at: u64,
109}
110
111#[derive(Deserialize)]
112struct WorkerEnvelope {
113    worker: RegisteredWorker,
114}
115
116/// The bound presence key, as E44 returns it.
117#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
118pub struct PresenceKey {
119    pub alg: String,
120    pub key_id: String,
121    pub hardware: bool,
122    pub bound_at: u64,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Account {
127    pub user_id: String,
128    /// C0 says string; a Cloud that answers `null` for an account without
129    /// a handle must not stop the card from being read.
130    #[serde(default)]
131    pub handle: Option<String>,
132    /// rc3-9: the owner's sign-in address; only Clouds since p37 !543 send it.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub email: Option<String>,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
138pub struct CardState {
139    pub instance_version: String,
140    pub consent_channel: ConsentChannel,
141    pub updated_at: u64,
142}
143
144/// E44 response.
145#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
146pub struct InstanceCard {
147    pub card: CardState,
148    pub account: Account,
149    pub presence_key: Option<PresenceKey>,
150}
151
152/// Largest answer of these routes.
153const MAX_ANSWER: usize = 64 * 1024;
154
155/// A C0 2.0 refusal in the person's words (SPEC-ENGINE §3.6, WEB §4.4);
156/// `None` leaves it to the generic mapping.
157fn worded(code: &str, reason: &str) -> Option<String> {
158    Some(match (code, reason) {
159        (_, "confusable") => "This name mixes alphabets. Use one alphabet.".into(),
160        (_, "reserved") => {
161            "Names may not contain cloud, thinkery, leanctx or moderator. Pick another name.".into()
162        }
163        ("worker_not_owned", _) => {
164            "worker_not_owned: the Cloud has bound this worker id to another instance.".into()
165        }
166        (_, "worker_cap_reached") => {
167            "worker_cap_reached: this instance already has 32 workers on the Cloud.".into()
168        }
169        (_, "presence_key_locked") => "The presence key can only be cleared here; bind a new one with `lean-ctx cloud connect --bind-presence-key`.".into(),
170        _ => return None,
171    })
172}
173
174/// Send, then parse a 2xx answer or word the refusal.
175fn call<T: for<'de> Deserialize<'de>>(
176    client: &CloudClient,
177    method: &str,
178    path: &str,
179    body: &Value,
180    what: &str,
181) -> Result<T, CloudError> {
182    let (status, answer) = client.send_answer(method, path, Some(body), MAX_ANSWER)?;
183    if !(200..300).contains(&status) {
184        let code = answer["error"]["code"].as_str().unwrap_or_default();
185        let reason = answer["error"]["reason"].as_str().unwrap_or_default();
186        return Err(worded(code, reason).map_or_else(
187            || CloudError::from_response(status, &answer),
188            CloudError::Config,
189        ));
190    }
191    parse(answer, what)
192}
193
194fn parse<T: for<'de> Deserialize<'de>>(value: Value, what: &str) -> Result<T, CloudError> {
195    serde_json::from_value(value).map_err(|e| CloudError::Protocol(format!("{what}: {e}")))
196}
197
198/// E10.
199pub fn register(
200    client: &CloudClient,
201    keys: &InstanceKeys,
202    reg: &Registration<'_>,
203) -> Result<RegisteredWorker, CloudError> {
204    let body = register_body(keys, reg)?;
205    Ok(call::<WorkerEnvelope>(client, "POST", "/workers", &body, "worker registration")?.worker)
206}
207
208/// E44 for the enrolled instance, at `cloud connect` and engine start.
209/// The engine reports `os_presence` only with a bound presence key
210/// (§3.8.4); the server derives the real channel.
211pub fn announce_instance(session: &crate::auth::Session) -> Result<InstanceCard, CloudError> {
212    let keys = InstanceKeys::load(&session.store)?;
213    let channel = if crate::consent::broker::bound_presence_key(&session.store).is_some() {
214        ConsentChannel::OsPresence
215    } else {
216        ConsentChannel::TtyOnly
217    };
218    let minor = std::cell::Cell::new(None);
219    let exchanged = session.with_client(|client| {
220        let (status, answer) =
221            card_exchange(client, &keys, &session.instance.instance_id, channel, false)?;
222        minor.set(client.answered_minor());
223        if status == 401 {
224            // The session renews the token and asks once more.
225            return Err(CloudError::from_response(status, &answer));
226        }
227        Ok((status, answer))
228    });
229    // E44 exists only on a C0 2.0 Cloud: its status (not the body, whose
230    // details may change) tells the relay which bus protocol to speak, and
231    // the answer's `Cloud-Protocol` minor which 2.x writes it takes.
232    let speaks = match &exchanged {
233        Ok((status, _)) if (200..300).contains(status) => Some(true),
234        Ok((404, _)) | Err(CloudError::NotFound) => Some(false),
235        _ => None,
236    };
237    if let Some(v2) = speaks {
238        crate::bus::relay_v2::record_protocol_minor(&session.store, v2, minor.get())?;
239    }
240    // V9: what the server accepts (`session_ref`), cached for this origin.
241    // A failure keeps the last answer and never fails the card.
242    let _ = session.with_client(|client| {
243        crate::session_ref::refresh(&session.store, &session.instance.url, client)
244    });
245    let result = exchanged.and_then(|(status, answer)| card_from(status, answer));
246    // The owner account web consents are checked against (§3.8.2 step 6).
247    if let Ok(card) = &result {
248        session
249            .store
250            .write_config(crate::consent::broker::ACCOUNT_FILE, &card.account)?;
251    }
252    result
253}
254
255/// Retire one worker of this instance on Cloud (C0 2.2
256/// `DELETE /v1/workers/{id}`): it no longer counts against the 32-worker
257/// cap. Done as well when Cloud says it does not know the worker (404
258/// `not_found`) or that another instance owns it (409
259/// `worker_not_owned`): nothing of this instance is left to free. A 404
260/// without that code (a Cloud that has no such route) is not done: the
261/// worker still counts there.
262pub fn retire(client: &CloudClient, worker_id: &str) -> Result<(), CloudError> {
263    if !crate::bus::address::is_worker_id(worker_id) {
264        return Err(CloudError::Config(format!(
265            "{worker_id} is not a worker id"
266        )));
267    }
268    let (status, answer) =
269        client.send_answer("DELETE", &format!("/workers/{worker_id}"), None, MAX_ANSWER)?;
270    let code = answer["error"]["code"].as_str().unwrap_or_default();
271    if (200..300).contains(&status)
272        || (status == 404 && code == "not_found")
273        || code == "worker_not_owned"
274    {
275        return Ok(());
276    }
277    Err(CloudError::from_response(status, &answer))
278}
279
280/// Retire on Cloud the workers the book gave up for new ones (see
281/// `attach::attach`), so a registration is not refused with
282/// `worker_cap_reached`. Every queued worker is tried; one Cloud could not
283/// retire now stays queued, and the first such error is returned.
284pub fn retire_evicted(session: &crate::auth::Session) -> Result<(), CloudError> {
285    let instance_id = &session.instance.instance_id;
286    let mut first_error = None;
287    for worker_id in super::attach::retired(&session.store, instance_id)? {
288        match session.with_client(|client| retire(client, &worker_id)) {
289            Ok(()) => super::attach::retirement_done(&session.store, instance_id, &worker_id)?,
290            Err(error) => {
291                first_error.get_or_insert(error);
292            }
293        }
294    }
295    first_error.map_or(Ok(()), Err)
296}
297
298/// How long a worker no session used stays before the sync retires it
299/// (`lean-ctx cloud worker retire --idle` defaults to the same).
300pub const IDLE_RETIRE: std::time::Duration = std::time::Duration::from_hours(24);
301/// How long the worker of an ended app session stays (its role is never
302/// attached again once the session is gone).
303pub const SESSION_IDLE_RETIRE: std::time::Duration = std::time::Duration::from_secs(3600);
304/// See [`on_session_end`].
305const SESSION_END_GRACE: std::time::Duration = std::time::Duration::from_secs(600);
306
307/// The sync's sweep (owner 09.11.: workers that are not active do not
308/// count): give up the workers idle for [`IDLE_RETIRE`] and those of ended
309/// app sessions idle for [`SESSION_IDLE_RETIRE`], then retire on Cloud every
310/// worker queued so far. The ids given up now.
311pub fn sweep(session: &crate::auth::Session) -> Result<Vec<String>, CloudError> {
312    let instance_id = &session.instance.instance_id;
313    let mut gone = super::attach::give_up_idle(&session.store, instance_id, IDLE_RETIRE, false)?;
314    gone.extend(super::attach::give_up_idle(
315        &session.store,
316        instance_id,
317        SESSION_IDLE_RETIRE,
318        true,
319    )?);
320    retire_evicted(session)?;
321    Ok(gone)
322}
323
324/// When an agent session ends: give up the workers of app sessions that no
325/// active session holds and none attached in the last `SESSION_END_GRACE`
326/// (a session still starting up). No request; Cloud hears of them with the
327/// next sync or registration ([`retire_evicted`]). A worker the ending
328/// session still holds goes with the sync's [`sweep`].
329pub fn on_session_end(store: &crate::state::CloudStore) {
330    let Ok(Some(instance)) = store.instance() else {
331        return;
332    };
333    match super::attach::give_up_idle(store, &instance.instance_id, SESSION_END_GRACE, true) {
334        Ok(gone) if !gone.is_empty() => {
335            tracing::debug!("cloud: workers of ended sessions given up: {gone:?}");
336        }
337        Ok(_) => {}
338        Err(error) => tracing::debug!("cloud: workers of ended sessions not given up: {error}"),
339    }
340}
341
342/// Register the worker a session attached to, once (E10 on the first
343/// event or bus post, SPEC-ENGINE §3.6), and remember it in the book.
344/// An already registered worker costs no request, unless it came back
345/// under a name a live sibling holds: then it is renamed (E11,
346/// [`super::reattach_name`]). Workers the book gave
347/// up are retired on Cloud first; one that cannot be retired now (offline,
348/// a Cloud without the route) is recorded and tried again next time, and
349/// the registration goes ahead (Cloud may still have room).
350pub fn ensure_registered(
351    session: &crate::auth::Session,
352    attached: &super::attach::LocalWorker,
353    card: &WorkerCard,
354) -> Result<super::attach::LocalWorker, CloudError> {
355    let instance = &session.instance;
356    let renamed = name_to_register(
357        &session.store,
358        &instance.instance_id,
359        &instance.label,
360        attached,
361    );
362    if attached.registered_at.is_some() {
363        return Ok(match renamed {
364            Some(name) => rename_on_reattach(session, attached, &name),
365            None => attached.clone(),
366        });
367    }
368    if let Err(error) = retire_evicted(session) {
369        session
370            .store
371            .record_error(&format!("worker retirement: {error}"));
372    }
373    let keys = InstanceKeys::load(&session.store)?;
374    let Some(name) = renamed.or_else(|| attached.name.clone()) else {
375        return Err(CloudError::Local(format!(
376            "{} has no name to register",
377            attached.worker_id
378        )));
379    };
380    let reg = Registration {
381        instance_id: &instance.instance_id,
382        host_app: &attached.host_app,
383        role: &attached.role,
384        name: &name,
385        card,
386        alias_place: None,
387    };
388    let worker = session.with_client(|client| register(client, &keys, &reg))?;
389    if worker.id != attached.worker_id {
390        return Err(CloudError::Protocol(format!(
391            "The Cloud registered {} for {}",
392            worker.id, attached.worker_id
393        )));
394    }
395    super::attach::update_book(&session.store, &instance.instance_id, |workers| {
396        let entry = workers.iter_mut().find(|w| w.worker_id == worker.id)?;
397        entry.registered_at = Some(worker.registered_at);
398        entry.name = Some(worker.name.clone());
399        Some(entry.clone())
400    })?
401    .ok_or_else(|| CloudError::Local(format!("{} left the worker book", worker.id)))
402}
403
404/// The name `attached` must (re)register with, or `None` to keep its own
405/// ([`super::reattach_name`] over this instance's book and the live local
406/// sessions). A book or agent registry that cannot be read is logged and
407/// names the worker as if it had no live sibling.
408pub(super) fn name_to_register(
409    store: &crate::state::CloudStore,
410    instance_id: &str,
411    instance_label: &str,
412    attached: &super::attach::LocalWorker,
413) -> Option<String> {
414    let book = super::attach::list(store, instance_id).unwrap_or_else(|error| {
415        tracing::warn!("cloud: worker book unreadable, worker names ignore siblings: {error}");
416        Vec::new()
417    });
418    let live = super::live_keys_for_names();
419    super::reattach_name(instance_label, attached, &book, &live)
420}
421
422/// E11 rename of a registered worker that came back under a name a live
423/// sibling holds (bd 5!678), remembered in the book. A rename Cloud does
424/// not take now (offline) is logged and the worker keeps its name until
425/// the next registration pass.
426fn rename_on_reattach(
427    session: &crate::auth::Session,
428    attached: &super::attach::LocalWorker,
429    name: &str,
430) -> super::attach::LocalWorker {
431    let instance_id = &session.instance.instance_id;
432    let renamed = session
433        .with_client(|client| patch(client, &attached.worker_id, Some(name), None))
434        .and_then(|worker| {
435            super::attach::update_book(&session.store, instance_id, |workers| {
436                let entry = workers.iter_mut().find(|w| w.worker_id == worker.id)?;
437                entry.name = Some(worker.name.clone());
438                Some(entry.clone())
439            })
440        });
441    match renamed {
442        Ok(Some(worker)) => worker,
443        Ok(None) => attached.clone(),
444        Err(error) => {
445            tracing::warn!(
446                "cloud: {} keeps a name a sibling holds: {error}",
447                attached.worker_id
448            );
449            session
450                .store
451                .record_error(&format!("worker rename: {error}"));
452            attached.clone()
453        }
454    }
455}
456
457/// E11: rename and/or a new card.
458pub fn patch(
459    client: &CloudClient,
460    worker_id: &str,
461    name: Option<&str>,
462    card: Option<&WorkerCard>,
463) -> Result<RegisteredWorker, CloudError> {
464    if !crate::bus::address::is_worker_id(worker_id) {
465        return Err(CloudError::Config(format!(
466            "{worker_id} is not a worker id"
467        )));
468    }
469    let mut body = json!({});
470    if let Some(name) = name {
471        body["name"] = check_name(name)
472            .map_err(|r| CloudError::Config(format!("invalid_name: {}", r.message())))?
473            .into();
474    }
475    if let Some(card) = card {
476        body["card"] = serde_json::to_value(card).map_err(|e| CloudError::Local(e.to_string()))?;
477    }
478    if body.as_object().is_none_or(serde_json::Map::is_empty) {
479        return Err(CloudError::Config("nothing to change".into()));
480    }
481    let path = format!("/workers/{worker_id}");
482    Ok(call::<WorkerEnvelope>(client, "PATCH", &path, &body, "worker update")?.worker)
483}
484
485/// E44.
486pub fn send_instance_card(
487    client: &CloudClient,
488    keys: &InstanceKeys,
489    instance_id: &str,
490    consent_channel: ConsentChannel,
491    clear_presence_key: bool,
492) -> Result<InstanceCard, CloudError> {
493    let (status, answer) = card_exchange(
494        client,
495        keys,
496        instance_id,
497        consent_channel,
498        clear_presence_key,
499    )?;
500    card_from(status, answer)
501}
502
503fn card_exchange(
504    client: &CloudClient,
505    keys: &InstanceKeys,
506    instance_id: &str,
507    consent_channel: ConsentChannel,
508    clear_presence_key: bool,
509) -> Result<(u16, Value), CloudError> {
510    let body = instance_card_body(
511        keys,
512        env!("CARGO_PKG_VERSION"),
513        consent_channel,
514        clear_presence_key,
515    )?;
516    let path = format!("/instances/{instance_id}/card");
517    client.send_answer("PATCH", &path, Some(&body), MAX_ANSWER)
518}
519
520fn card_from(status: u16, answer: Value) -> Result<InstanceCard, CloudError> {
521    if !(200..300).contains(&status) {
522        let code = answer["error"]["code"].as_str().unwrap_or_default();
523        let reason = answer["error"]["reason"].as_str().unwrap_or_default();
524        return Err(worded(code, reason).map_or_else(
525            || CloudError::from_response(status, &answer),
526            CloudError::Config,
527        ));
528    }
529    parse(answer, "instance card")
530}
531
532#[cfg(test)]
533mod tests {
534    use super::super::card::{Availability, Budget};
535    use super::*;
536
537    const FIXTURES: &str = concat!(
538        concat!(env!("CARGO_MANIFEST_DIR"), "/../.."),
539        "/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/"
540    );
541
542    fn fixture(name: &str) -> Value {
543        let text = std::fs::read_to_string(format!("{FIXTURES}{name}")).unwrap();
544        serde_json::from_str(&text).unwrap()
545    }
546
547    fn instance_a() -> InstanceKeys {
548        InstanceKeys::from_seeds([0x49; 32], [0x01; 32])
549    }
550
551    #[test]
552    fn workspace_registration_matches_the_fixture_byte_for_byte() {
553        let card = WorkerCard::new(
554            "claude-code",
555            Some("claude-opus-5-5"),
556            ["ctx_read", "ctx_search", "ctx_shell"].map(String::from),
557            Budget {
558                tasks_per_day: Some(20),
559                usd_cents_per_day: None,
560            },
561            Availability::Online,
562        );
563        let body = register_body(
564            &instance_a(),
565            &Registration {
566                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
567                host_app: "claude-code",
568                role: "backend",
569                name: "yves-mac · Claude Code · backend",
570                card: &card,
571                alias_place: None,
572            },
573        )
574        .unwrap();
575        assert_eq!(body, fixture("routes/worker_register.request.json"));
576    }
577
578    #[test]
579    fn alias_registration_matches_the_fixture_byte_for_byte() {
580        let card = WorkerCard::new(
581            "codex",
582            None,
583            Vec::new(),
584            Budget::default(),
585            Availability::Idle,
586        );
587        let body = register_body(
588            &instance_a(),
589            &Registration {
590                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
591                host_app: "codex",
592                role: "general",
593                name: "Codex · general",
594                card: &card,
595                alias_place: Some("vault:3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01"),
596            },
597        )
598        .unwrap();
599        let want = fixture("routes/worker_register.alias.request.json");
600        assert_eq!(body, want);
601        // Nothing in the alias body names the instance.
602        assert!(!body.to_string().contains("6f2b9c4e"));
603    }
604
605    #[test]
606    fn instance_cards_match_the_fixtures_and_can_only_clear() {
607        let keys = instance_a();
608        assert_eq!(
609            instance_card_body(&keys, "3.12.0", ConsentChannel::OsPresence, false).unwrap(),
610            fixture("routes/instance_card.request.json")
611        );
612        assert_eq!(
613            instance_card_body(&keys, "3.12.0", ConsentChannel::TtyOnly, true).unwrap(),
614            fixture("routes/instance_card.clear.request.json")
615        );
616        let card: InstanceCard =
617            parse(fixture("routes/instance_card.response.json"), "card").unwrap();
618        assert_eq!(card.presence_key.unwrap().key_id, "ef1bd9c792ccc768");
619        assert_eq!(card.account.handle.as_deref(), Some("yves"));
620        // An account without a handle (dogfood finding 25.10.) still reads,
621        // and only the status decides the protocol.
622        let mut nameless = fixture("routes/instance_card.response.json");
623        nameless["account"]["handle"] = Value::Null;
624        let card = card_from(200, nameless).unwrap();
625        assert_eq!(card.account.handle, None);
626        assert_eq!(card.account.email, None);
627        // rc3-9: a Cloud since p37 !543 names the owner's sign-in address.
628        let mut named = fixture("routes/instance_card.response.json");
629        named["account"]["email"] = json!("dana@example.test");
630        let card = card_from(200, named).unwrap();
631        assert_eq!(card.account.email.as_deref(), Some("dana@example.test"));
632        assert!(card_from(404, json!({"error": {"code": "not_found"}})).is_err());
633    }
634
635    #[test]
636    fn a_mixed_alphabet_name_is_refused_before_it_leaves() {
637        let card = WorkerCard::new(
638            "codex",
639            None,
640            Vec::new(),
641            Budget::default(),
642            Availability::Idle,
643        );
644        let err = register_body(
645            &instance_a(),
646            &Registration {
647                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
648                host_app: "codex",
649                role: "general",
650                name: "аdmin",
651                card: &card,
652                alias_place: None,
653            },
654        )
655        .unwrap_err();
656        assert!(err.to_string().contains("invalid_name"), "{err}");
657    }
658
659    #[test]
660    fn refusals_reach_the_person_in_their_words() {
661        let locked = fixture("routes/instance_card.error.presence_key_locked.json");
662        let text = worded(
663            locked["error"]["code"].as_str().unwrap(),
664            locked["error"]["reason"].as_str().unwrap(),
665        )
666        .unwrap();
667        assert!(text.contains("--bind-presence-key"), "{text}");
668        assert_eq!(
669            worded("invalid_request", "confusable").unwrap(),
670            "This name mixes alphabets. Use one alphabet."
671        );
672        assert!(
673            worded("worker_not_owned", "")
674                .unwrap()
675                .starts_with("worker_not_owned")
676        );
677        assert_eq!(worded("invalid_request", "other"), None);
678    }
679
680    #[test]
681    fn responses_parse() {
682        let w: WorkerEnvelope =
683            parse(fixture("routes/worker_register.response.json"), "w").unwrap();
684        assert_eq!(w.worker.id, "wkr_vk4oelpv5lzjmev44hun");
685        let p: WorkerEnvelope = parse(fixture("routes/worker_patch.response.json"), "p").unwrap();
686        assert!(p.worker.name.contains("payments"));
687        // A retired worker registered again comes back like any other.
688        let r: WorkerEnvelope = parse(
689            fixture("routes/worker_register.reactivated.response.json"),
690            "r",
691        )
692        .unwrap();
693        assert!(r.worker.id.starts_with("wkr_"));
694    }
695
696    /// A one-request-per-connection Cloud that answers `DELETE /v1/workers/*`
697    /// with `(status, body)` and records the request lines.
698    fn retiring_cloud(
699        status: u16,
700        body: String,
701    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
702        use std::io::{BufRead as _, BufReader, Write as _};
703        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
704        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
705        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
706        let recorded = std::sync::Arc::clone(&seen);
707        std::thread::spawn(move || {
708            for stream in listener.incoming().flatten() {
709                let mut writer = stream.try_clone().unwrap();
710                let mut reader = BufReader::new(stream);
711                let mut line = String::new();
712                if reader.read_line(&mut line).unwrap_or(0) == 0 {
713                    continue;
714                }
715                loop {
716                    let mut header = String::new();
717                    reader.read_line(&mut header).unwrap();
718                    if header.trim_end().is_empty() {
719                        break;
720                    }
721                }
722                recorded.lock().unwrap().push(line.trim_end().to_string());
723                let _ = write!(
724                    writer,
725                    "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
726                    body.len()
727                );
728            }
729        });
730        (origin, seen)
731    }
732
733    /// `DELETE /v1/workers/{id}` as C0 2.2 fixes it (`routes/worker_retire.*`):
734    /// 204, an unknown or placed worker (404 not_found) and one of another
735    /// instance (409 worker_not_owned) are all done for this instance;
736    /// anything else keeps the worker queued.
737    #[test]
738    fn retiring_a_worker_is_done_unless_cloud_could_not_answer() {
739        let route = fixture("routes/worker_retire.request.json");
740        let id = route["path"]
741            .as_str()
742            .unwrap()
743            .strip_prefix("/v1/workers/")
744            .unwrap()
745            .to_string();
746        assert_eq!(route["method"], "DELETE");
747        assert_eq!(route["response"]["status"], 204);
748        for (status, body) in [
749            (204, String::new()),
750            (
751                404,
752                fixture("routes/worker_retire.error.not_found.json").to_string(),
753            ),
754            (
755                409,
756                fixture("routes/worker_retire.error.not_owned.json").to_string(),
757            ),
758        ] {
759            let (origin, seen) = retiring_cloud(status, body);
760            let client = CloudClient::new(&origin).unwrap();
761            retire(&client, &id).unwrap_or_else(|e| panic!("{status}: {e}"));
762            assert_eq!(
763                seen.lock().unwrap().as_slice(),
764                [format!("DELETE /v1/workers/{id} HTTP/1.1")]
765            );
766        }
767        let (origin, _) = retiring_cloud(503, r#"{"error":{"code":"unavailable"}}"#.into());
768        assert!(retire(&CloudClient::new(&origin).unwrap(), &id).is_err());
769        // A Cloud without the route: its 404 frees nothing there.
770        let (origin, _) = retiring_cloud(404, String::new());
771        assert!(retire(&CloudClient::new(&origin).unwrap(), &id).is_err());
772        assert!(retire(&CloudClient::new(&origin).unwrap(), "../admin").is_err());
773    }
774}