Skip to main content

lean_ctx_cloud/workers/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Durable workers (SPEC-ENGINE §3.6, C0 2.0 section 2): the identity an
3//! agent has on Cloud instead of its process id.
4//!
5//! - Workspace places see `wkr_` ids derived from the instance UUID, host
6//!   app and role, which the server recomputes.
7//! - Public vaults and swarms see place-scoped aliases keyed by the
8//!   `worker_alias_key`, derived in memory from the instance signing seed
9//!   and never written or sent, so co-members who know the instance UUID
10//!   can neither reproduce an alias nor link two places.
11
12pub mod attach;
13pub mod card;
14pub mod keys;
15pub mod register;
16pub mod roster;
17
18use ed25519_dalek::SigningKey;
19use unicode_normalization::UnicodeNormalization as _;
20use zeroize::Zeroizing;
21
22use super::instance_key::InstanceKeys;
23
24/// HKDF salt of the `worker_alias_key` (info empty).
25const WORKER_ALIAS_SALT: &str = "leanctx.cloud.worker-alias.v1";
26/// HKDF salt of a per-place alias signing seed (info = place ref).
27const ALIAS_SIGNING_SALT: &str = "leanctx.cloud.alias.v1";
28
29/// Role used when none is given or nothing survives normalisation.
30pub const GENERAL_ROLE: &str = "general";
31/// Longest normalised role.
32const ROLE_MAX: usize = 32;
33/// Longest worker name, in Unicode scalar values after NFKC.
34const NAME_MAX: usize = 64;
35/// Case-insensitive substrings no worker name may carry.
36const RESERVED: [&str; 4] = ["cloud", "thinkery", "leanctx", "moderator"];
37
38/// Lowercase; every character outside `[a-z0-9-]` becomes `-`; runs
39/// collapsed and trimmed; at most 32 characters; empty → `general`.
40pub fn normalize_role(role: &str) -> String {
41    let mut out = String::new();
42    for c in role.to_lowercase().chars() {
43        let c = if c.is_ascii_lowercase() || c.is_ascii_digit() {
44            c
45        } else {
46            '-'
47        };
48        if !(c == '-' && out.ends_with('-')) {
49            out.push(c);
50        }
51    }
52    let cut: String = out.trim_matches('-').chars().take(ROLE_MAX).collect();
53    match cut.trim_end_matches('-') {
54        "" => GENERAL_ROLE.to_string(),
55        kept => kept.to_string(),
56    }
57}
58
59/// Length of the session tag in a per-session role.
60const SESSION_TAG_LEN: usize = 8;
61/// Domain of the session tag hash.
62const SESSION_TAG_DOMAIN: &str = "leanctx.cloud.session-agent.v1|";
63
64/// The role a session's worker is registered under. Without an app session
65/// it is the normalised role, so every session of that role on this
66/// instance shares one worker. With an app session (`LEAN_CTX_SESSION_ID`,
67/// recorded as the presence's `app_session_id`) it is
68/// `<role>-s<tag>`, where `tag` is base32(blake3(domain ‖ session))[..8] and
69/// the role is cut so the whole fits the 32-character role limit. Each
70/// session then gets its own durable worker (`wkr_` id), stable for the
71/// life of that app session. Cloud recomputes the id from the role as sent,
72/// so this needs nothing new on Cloud, and Cloud's `self_verify` check
73/// (worker id of the verdict == worker id of the result) then tells a
74/// worker session apart from a separate reviewer session on the same host.
75pub fn session_role(role: &str, app_session: Option<&str>) -> String {
76    let role = normalize_role(role);
77    let Some(session) = app_session.map(str::trim).filter(|s| !s.is_empty()) else {
78        return role;
79    };
80    let digest = blake3::hash(format!("{SESSION_TAG_DOMAIN}{session}").as_bytes());
81    let tag = &base32_lower(digest.as_bytes())[..SESSION_TAG_LEN];
82    let base: String = role.chars().take(ROLE_MAX - 2 - SESSION_TAG_LEN).collect();
83    format!("{}-s{tag}", base.trim_end_matches('-'))
84}
85
86/// The instance id as the server hashes it: the dashed lowercase UUID. A
87/// 1.x enrolment stores `inst_<32 hex>`; the same id in another spelling
88/// would give another worker id (E10 `worker_not_owned`, dogfood 25.10.).
89pub fn canonical_instance_id(instance_id: &str) -> String {
90    let hex = instance_id
91        .strip_prefix("inst_")
92        .unwrap_or(instance_id)
93        .replace('-', "")
94        .to_ascii_lowercase();
95    if hex.len() == 32 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
96        format!(
97            "{}-{}-{}-{}-{}",
98            &hex[..8],
99            &hex[8..12],
100            &hex[12..16],
101            &hex[16..20],
102            &hex[20..]
103        )
104    } else {
105        instance_id.to_string()
106    }
107}
108
109/// Workspace worker id: `wkr_` + base32(blake3(instance ‖ "|" ‖ host ‖ "|" ‖ role))[..20],
110/// over the canonical instance id.
111pub fn workspace_worker_id(instance_id: &str, host_app: &str, role: &str) -> String {
112    let instance_id = canonical_instance_id(instance_id);
113    worker_id_of(blake3::hash(format!("{instance_id}|{host_app}|{role}").as_bytes()).as_bytes())
114}
115
116fn worker_id_of(digest: &[u8; 32]) -> String {
117    let mut id = String::from("wkr_");
118    id.push_str(&base32_lower(digest)[..20]);
119    id
120}
121
122/// RFC 4648 base32, lowercase, without padding.
123fn base32_lower(bytes: &[u8]) -> String {
124    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
125    let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
126    let (mut buffer, mut bits) = (0u32, 0u32);
127    for &byte in bytes {
128        buffer = (buffer << 8) | u32::from(byte);
129        bits += 8;
130        while bits >= 5 {
131            bits -= 5;
132            out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
133        }
134    }
135    if bits > 0 {
136        out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);
137    }
138    out
139}
140
141/// The secret that keys place-scoped worker aliases and `hlc.node`.
142pub struct WorkerAliasKey(Zeroizing<[u8; 32]>);
143
144impl WorkerAliasKey {
145    pub fn of(keys: &InstanceKeys) -> Self {
146        Self(keys.derive_from_signing_seed(WORKER_ALIAS_SALT, b""))
147    }
148
149    #[cfg(test)]
150    fn from_seed(seed: &[u8; 32]) -> Self {
151        Self(super::instance_key::derive_from_seed(
152            seed,
153            WORKER_ALIAS_SALT,
154            b"",
155        ))
156    }
157
158    /// `wkr_` + base32(blake3_keyed(key, host ‖ "|" ‖ role ‖ "|" ‖ place_ref))[..20].
159    pub fn worker_id(&self, host_app: &str, role: &str, place_ref: &str) -> String {
160        let input = format!("{host_app}|{role}|{place_ref}");
161        worker_id_of(blake3::keyed_hash(&self.0, input.as_bytes()).as_bytes())
162    }
163
164    /// `hex(blake3_keyed(key, place_ref))[..16]`.
165    pub fn hlc_node(&self, place_ref: &str) -> String {
166        blake3::keyed_hash(&self.0, place_ref.as_bytes()).to_hex()[..16].to_string()
167    }
168}
169
170/// Ed25519 key that signs this instance's events in a public vault or swarm
171/// (RESOLUTIONS R38). `place_ref` is `"{kind}:{id}"`.
172pub fn alias_signing_key(keys: &InstanceKeys, place_ref: &str) -> SigningKey {
173    let seed = keys.derive_from_signing_seed(ALIAS_SIGNING_SALT, place_ref.as_bytes());
174    SigningKey::from_bytes(&seed)
175}
176
177/// `hlc.node` of this instance's events in a public vault or swarm.
178pub fn alias_hlc_node(keys: &InstanceKeys, place_ref: &str) -> String {
179    WorkerAliasKey::of(keys).hlc_node(place_ref)
180}
181
182/// C0 `key_id`: `hex(blake3(public key))[..16]`.
183pub fn key_id(key: &SigningKey) -> String {
184    blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
185}
186
187/// Why a worker name is refused (C0 2.0 `name` vectors), checked in this order.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum NameRefusal {
190    Length,
191    Charset,
192    Confusable,
193    Reserved,
194}
195
196impl NameRefusal {
197    pub fn code(self) -> &'static str {
198        match self {
199            Self::Length => "length",
200            Self::Charset => "charset",
201            Self::Confusable => "confusable",
202            Self::Reserved => "reserved",
203        }
204    }
205
206    /// The text the person sees (SPEC-ENGINE §3.6, WEB §4.4).
207    pub fn message(self) -> &'static str {
208        match self {
209            Self::Length | Self::Charset => {
210                "Use 1 to 64 letters, digits, spaces and . _ · - from one alphabet."
211            }
212            Self::Confusable => "This name mixes alphabets. Use one alphabet.",
213            Self::Reserved => {
214                "Names may not contain cloud, thinkery, leanctx or moderator. Pick another name."
215            }
216        }
217    }
218}
219
220/// Scripts told apart by the single-script rule; any other script counts
221/// as one more (C0 2.0 server rule).
222const SCRIPTS: [&str; 14] = [
223    "Latin",
224    "Greek",
225    "Cyrillic",
226    "Armenian",
227    "Hebrew",
228    "Arabic",
229    "Devanagari",
230    "Bengali",
231    "Thai",
232    "Georgian",
233    "Hangul",
234    "Hiragana",
235    "Katakana",
236    "Han",
237];
238
239struct NameRules {
240    charset: regex::Regex,
241    letter: regex::Regex,
242    scripts: Vec<regex::Regex>,
243}
244
245fn name_rules() -> &'static NameRules {
246    static RULES: std::sync::OnceLock<NameRules> = std::sync::OnceLock::new();
247    RULES.get_or_init(|| NameRules {
248        charset: regex::Regex::new(r"^[\p{L}\p{N} ._·-]+$").expect("static regex"),
249        letter: regex::Regex::new(r"^\p{L}$").expect("static regex"),
250        scripts: SCRIPTS
251            .iter()
252            .map(|sc| regex::Regex::new(&format!(r"^\p{{sc={sc}}}$")).expect("static regex"))
253            .collect(),
254    })
255}
256
257/// The C0 2.0 worker-name rule, applied before a name leaves the engine.
258/// Returns the NFKC form that is sent.
259pub fn check_name(name: &str) -> Result<String, NameRefusal> {
260    let name: String = name.nfkc().collect();
261    let len = name.chars().count();
262    if len == 0 || len > NAME_MAX {
263        return Err(NameRefusal::Length);
264    }
265    let rules = name_rules();
266    if !rules.charset.is_match(&name) {
267        return Err(NameRefusal::Charset);
268    }
269    let mut script = None;
270    let mut buf = [0u8; 4];
271    for ch in name.chars() {
272        let text = ch.encode_utf8(&mut buf);
273        if !rules.letter.is_match(text) {
274            continue;
275        }
276        let this = rules.scripts.iter().position(|r| r.is_match(text));
277        match script {
278            None => script = Some(this),
279            Some(seen) if seen != this => return Err(NameRefusal::Confusable),
280            Some(_) => {}
281        }
282    }
283    let lower = name.to_lowercase();
284    if RESERVED.iter().any(|r| lower.contains(r)) {
285        return Err(NameRefusal::Reserved);
286    }
287    Ok(name)
288}
289
290/// Default name `<computer> · <Host app> · <role>`, built to pass
291/// [`check_name`] (rc4-39):
292/// - the computer is the instance label as a team sees it
293///   ([`crate::bus::v2::machine_name`]: `yves-mac.local` → `yves-mac`);
294///   apostrophes go (`Ada’s MacBook` → `Adas MacBook`, as macOS spells
295///   its own host name) and every other character outside the rule
296///   becomes a space, so no two words are glued together; a label that
297///   still fails is left out;
298/// - an app the engine could not tell (`None`, see
299///   [`attach::named_host_display`]) is left out, never "unknown".
300pub fn default_name(instance_label: &str, host_display: Option<&str>, role: &str) -> String {
301    let host = host_display.map(str::trim).filter(|h| !h.is_empty());
302    let tail = match host {
303        Some(host) => format!("{host} · {role}"),
304        None => role.to_string(),
305    };
306    let label = name_label(instance_label);
307    let full = format!("{label} · {tail}");
308    if !label.is_empty() && check_name(&full).is_ok() {
309        full
310    } else {
311        tail
312    }
313}
314
315/// The computer part of a default name: see [`default_name`].
316fn name_label(instance_label: &str) -> String {
317    let machine =
318        crate::bus::v2::machine_name(instance_label).unwrap_or_else(|| instance_label.to_string());
319    let label: String = machine
320        .nfkc()
321        .filter(|c| !matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{02BC}' | '`'))
322        .filter(|c| !is_format_char(*c))
323        .map(|c| {
324            if c.is_alphanumeric() || matches!(c, '.' | '_' | '-') {
325                c
326            } else {
327                ' '
328            }
329        })
330        .collect();
331    label.split_whitespace().collect::<Vec<_>>().join(" ")
332}
333
334/// The role as a worker name shows it: a per-session worker's role
335/// (`<role>-s<tag>`, [`session_role`]) without its session tag, which is
336/// an internal id; any other role as it is (`dev-storybook` stays).
337pub fn display_role(role: &str, per_session: bool) -> String {
338    if per_session
339        && let Some((base, tag)) = role.rsplit_once("-s")
340        && tag.len() == SESSION_TAG_LEN
341        && tag
342            .bytes()
343            .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
344        && !base.is_empty()
345    {
346        return base.to_string();
347    }
348    role.to_string()
349}
350
351/// A Unicode format character (general category `Cf`: bidi controls,
352/// zero-width spaces and joiners, the BOM): invisible, and able to reorder
353/// what a terminal or page shows, so never part of a label or a name.
354pub fn is_format_char(c: char) -> bool {
355    use unicode_general_category::{GeneralCategory, get_general_category};
356    get_general_category(c) == GeneralCategory::Format
357}
358
359/// The default name of `worker`, one of this instance's workers in
360/// `book`: [`default_name`] over its host app and its role as people read
361/// them. Two workers that would read the same (two sessions of one role
362/// on one instance, rc4-39 review) are told apart by an ordinal on the
363/// role (`backend`, `backend 2`, …): names Cloud already accepted are
364/// taken, and the rest are named in book order, so the first keeps the
365/// plain name and a single worker never gets a number. Only siblings an
366/// active session holds (`live`, `(host_app, role)` keys) count: an ended
367/// or crashed session never pushes a new one to `backend 2` (bd 5!678).
368pub fn worker_default_name(
369    instance_label: &str,
370    worker: &attach::LocalWorker,
371    book: &[attach::LocalWorker],
372    live: &std::collections::BTreeSet<(String, String)>,
373) -> String {
374    let fold = |name: &str| name.to_lowercase();
375    let counts = |w: &attach::LocalWorker| {
376        w.worker_id != worker.worker_id && live.contains(&(w.host_app.clone(), w.role.clone()))
377    };
378    let mut taken: std::collections::BTreeSet<String> = book
379        .iter()
380        .filter(|w| counts(w))
381        .filter_map(|w| w.name.as_deref().map(fold))
382        .collect();
383    let mut pick = |w: &attach::LocalWorker| {
384        let host = attach::named_host_display(&w.host_app);
385        let role = display_role(&w.role, w.per_session);
386        let mut ordinal = 1_usize;
387        loop {
388            let shown = if ordinal == 1 {
389                role.clone()
390            } else {
391                format!("{role} {ordinal}")
392            };
393            let name = default_name(instance_label, host.as_deref(), &shown);
394            if taken.insert(fold(&name)) {
395                return name;
396            }
397            ordinal += 1;
398        }
399    };
400    for earlier in book {
401        if earlier.worker_id == worker.worker_id {
402            break;
403        }
404        if earlier.name.is_none() && counts(earlier) {
405            pick(earlier);
406        }
407    }
408    pick(worker)
409}
410
411/// The `(host_app, role)` keys of the active local sessions that worker
412/// names count ([`worker_default_name`]). An agent registry that cannot be
413/// read is logged and names as if no sibling were live (bd 5!678: never
414/// swallowed silently).
415pub fn live_keys_for_names() -> std::collections::BTreeSet<(String, String)> {
416    attach::live_worker_keys().unwrap_or_else(|error| {
417        tracing::warn!("cloud: worker names ignore sibling sessions: {error}");
418        std::collections::BTreeSet::new()
419    })
420}
421
422/// The names `cloud worker list` shows for `workers`, one per worker in
423/// order: the name Cloud accepted, else the default over the live siblings.
424pub fn shown_names(instance_label: &str, workers: &[attach::LocalWorker]) -> Vec<String> {
425    let live = live_keys_for_names();
426    workers
427        .iter()
428        .map(|w| {
429            w.name
430                .clone()
431                .unwrap_or_else(|| worker_default_name(instance_label, w, workers, &live))
432        })
433        .collect()
434}
435
436/// The name `worker` must (re)register with, or `None` to keep the one it
437/// has. A worker without a name gets its default ([`worker_default_name`]).
438/// A worker that comes back with a default name a live sibling holds (a
439/// resumed session 1 while session 3 took the plain `backend` during its
440/// absence, bd 5!678) yields and takes the next free ordinal. Of two live
441/// workers with one name, the later registration keeps it: it claimed the
442/// name while the earlier one was gone. A name the person chose (not one of
443/// this worker's default names) is never changed.
444pub fn reattach_name(
445    instance_label: &str,
446    worker: &attach::LocalWorker,
447    book: &[attach::LocalWorker],
448    live: &std::collections::BTreeSet<(String, String)>,
449) -> Option<String> {
450    let Some(name) = worker.name.as_deref() else {
451        return Some(worker_default_name(instance_label, worker, book, live));
452    };
453    let fold = name.to_lowercase();
454    let mine = (worker.registered_at, worker.worker_id.as_str());
455    let held = book.iter().any(|w| {
456        w.worker_id != worker.worker_id
457            && live.contains(&(w.host_app.clone(), w.role.clone()))
458            && w.name.as_deref().is_some_and(|n| n.to_lowercase() == fold)
459            && (w.registered_at, w.worker_id.as_str()) > mine
460    });
461    (held && reads_as_default(instance_label, worker, &fold))
462        .then(|| worker_default_name(instance_label, worker, book, live))
463}
464
465/// Whether `folded` (a lower-cased name) is one of the default names of
466/// `worker`: its plain role or the role with an ordinal.
467fn reads_as_default(instance_label: &str, worker: &attach::LocalWorker, folded: &str) -> bool {
468    let host = attach::named_host_display(&worker.host_app);
469    let role = display_role(&worker.role, worker.per_session);
470    (1..=attach::WORKER_CAP + 1).any(|ordinal| {
471        let shown = if ordinal == 1 {
472            role.clone()
473        } else {
474            format!("{role} {ordinal}")
475        };
476        default_name(instance_label, host.as_deref(), &shown).to_lowercase() == folded
477    })
478}
479
480#[cfg(test)]
481mod tests;