lean-ctx-cloud 3.12.13

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// SPDX-License-Identifier: Apache-2.0
//! Durable workers (SPEC-ENGINE §3.6, C0 2.0 section 2): the identity an
//! agent has on Cloud instead of its process id.
//!
//! - Workspace places see `wkr_` ids derived from the instance UUID, host
//!   app and role, which the server recomputes.
//! - Public vaults and swarms see place-scoped aliases keyed by the
//!   `worker_alias_key`, derived in memory from the instance signing seed
//!   and never written or sent, so co-members who know the instance UUID
//!   can neither reproduce an alias nor link two places.

pub mod attach;
pub mod card;
pub mod keys;
pub mod register;
pub mod roster;

use ed25519_dalek::SigningKey;
use unicode_normalization::UnicodeNormalization as _;
use zeroize::Zeroizing;

use super::instance_key::InstanceKeys;

/// HKDF salt of the `worker_alias_key` (info empty).
const WORKER_ALIAS_SALT: &str = "leanctx.cloud.worker-alias.v1";
/// HKDF salt of a per-place alias signing seed (info = place ref).
const ALIAS_SIGNING_SALT: &str = "leanctx.cloud.alias.v1";

/// Role used when none is given or nothing survives normalisation.
pub const GENERAL_ROLE: &str = "general";
/// Longest normalised role.
const ROLE_MAX: usize = 32;
/// Longest worker name, in Unicode scalar values after NFKC.
const NAME_MAX: usize = 64;
/// Case-insensitive substrings no worker name may carry.
const RESERVED: [&str; 4] = ["cloud", "thinkery", "leanctx", "moderator"];

/// Lowercase; every character outside `[a-z0-9-]` becomes `-`; runs
/// collapsed and trimmed; at most 32 characters; empty → `general`.
pub fn normalize_role(role: &str) -> String {
    let mut out = String::new();
    for c in role.to_lowercase().chars() {
        let c = if c.is_ascii_lowercase() || c.is_ascii_digit() {
            c
        } else {
            '-'
        };
        if !(c == '-' && out.ends_with('-')) {
            out.push(c);
        }
    }
    let cut: String = out.trim_matches('-').chars().take(ROLE_MAX).collect();
    match cut.trim_end_matches('-') {
        "" => GENERAL_ROLE.to_string(),
        kept => kept.to_string(),
    }
}

/// Length of the session tag in a per-session role.
const SESSION_TAG_LEN: usize = 8;
/// Domain of the session tag hash.
const SESSION_TAG_DOMAIN: &str = "leanctx.cloud.session-agent.v1|";

/// The role a session's worker is registered under. Without an app session
/// it is the normalised role, so every session of that role on this
/// instance shares one worker. With an app session (`LEAN_CTX_SESSION_ID`,
/// recorded as the presence's `app_session_id`) it is
/// `<role>-s<tag>`, where `tag` is base32(blake3(domain ‖ session))[..8] and
/// the role is cut so the whole fits the 32-character role limit. Each
/// session then gets its own durable worker (`wkr_` id), stable for the
/// life of that app session. Cloud recomputes the id from the role as sent,
/// so this needs nothing new on Cloud, and Cloud's `self_verify` check
/// (worker id of the verdict == worker id of the result) then tells a
/// worker session apart from a separate reviewer session on the same host.
pub fn session_role(role: &str, app_session: Option<&str>) -> String {
    let role = normalize_role(role);
    let Some(session) = app_session.map(str::trim).filter(|s| !s.is_empty()) else {
        return role;
    };
    let digest = blake3::hash(format!("{SESSION_TAG_DOMAIN}{session}").as_bytes());
    let tag = &base32_lower(digest.as_bytes())[..SESSION_TAG_LEN];
    let base: String = role.chars().take(ROLE_MAX - 2 - SESSION_TAG_LEN).collect();
    format!("{}-s{tag}", base.trim_end_matches('-'))
}

/// The instance id as the server hashes it: the dashed lowercase UUID. A
/// 1.x enrolment stores `inst_<32 hex>`; the same id in another spelling
/// would give another worker id (E10 `worker_not_owned`, dogfood 25.10.).
pub fn canonical_instance_id(instance_id: &str) -> String {
    let hex = instance_id
        .strip_prefix("inst_")
        .unwrap_or(instance_id)
        .replace('-', "")
        .to_ascii_lowercase();
    if hex.len() == 32 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        format!(
            "{}-{}-{}-{}-{}",
            &hex[..8],
            &hex[8..12],
            &hex[12..16],
            &hex[16..20],
            &hex[20..]
        )
    } else {
        instance_id.to_string()
    }
}

/// Workspace worker id: `wkr_` + base32(blake3(instance ‖ "|" ‖ host ‖ "|" ‖ role))[..20],
/// over the canonical instance id.
pub fn workspace_worker_id(instance_id: &str, host_app: &str, role: &str) -> String {
    let instance_id = canonical_instance_id(instance_id);
    worker_id_of(blake3::hash(format!("{instance_id}|{host_app}|{role}").as_bytes()).as_bytes())
}

fn worker_id_of(digest: &[u8; 32]) -> String {
    let mut id = String::from("wkr_");
    id.push_str(&base32_lower(digest)[..20]);
    id
}

/// RFC 4648 base32, lowercase, without padding.
fn base32_lower(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
    let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
    let (mut buffer, mut bits) = (0u32, 0u32);
    for &byte in bytes {
        buffer = (buffer << 8) | u32::from(byte);
        bits += 8;
        while bits >= 5 {
            bits -= 5;
            out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
        }
    }
    if bits > 0 {
        out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);
    }
    out
}

/// The secret that keys place-scoped worker aliases and `hlc.node`.
pub struct WorkerAliasKey(Zeroizing<[u8; 32]>);

impl WorkerAliasKey {
    pub fn of(keys: &InstanceKeys) -> Self {
        Self(keys.derive_from_signing_seed(WORKER_ALIAS_SALT, b""))
    }

    #[cfg(test)]
    fn from_seed(seed: &[u8; 32]) -> Self {
        Self(super::instance_key::derive_from_seed(
            seed,
            WORKER_ALIAS_SALT,
            b"",
        ))
    }

    /// `wkr_` + base32(blake3_keyed(key, host ‖ "|" ‖ role ‖ "|" ‖ place_ref))[..20].
    pub fn worker_id(&self, host_app: &str, role: &str, place_ref: &str) -> String {
        let input = format!("{host_app}|{role}|{place_ref}");
        worker_id_of(blake3::keyed_hash(&self.0, input.as_bytes()).as_bytes())
    }

    /// `hex(blake3_keyed(key, place_ref))[..16]`.
    pub fn hlc_node(&self, place_ref: &str) -> String {
        blake3::keyed_hash(&self.0, place_ref.as_bytes()).to_hex()[..16].to_string()
    }
}

/// Ed25519 key that signs this instance's events in a public vault or swarm
/// (RESOLUTIONS R38). `place_ref` is `"{kind}:{id}"`.
pub fn alias_signing_key(keys: &InstanceKeys, place_ref: &str) -> SigningKey {
    let seed = keys.derive_from_signing_seed(ALIAS_SIGNING_SALT, place_ref.as_bytes());
    SigningKey::from_bytes(&seed)
}

/// `hlc.node` of this instance's events in a public vault or swarm.
pub fn alias_hlc_node(keys: &InstanceKeys, place_ref: &str) -> String {
    WorkerAliasKey::of(keys).hlc_node(place_ref)
}

/// C0 `key_id`: `hex(blake3(public key))[..16]`.
pub fn key_id(key: &SigningKey) -> String {
    blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
}

/// Why a worker name is refused (C0 2.0 `name` vectors), checked in this order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameRefusal {
    Length,
    Charset,
    Confusable,
    Reserved,
}

impl NameRefusal {
    pub fn code(self) -> &'static str {
        match self {
            Self::Length => "length",
            Self::Charset => "charset",
            Self::Confusable => "confusable",
            Self::Reserved => "reserved",
        }
    }

    /// The text the person sees (SPEC-ENGINE §3.6, WEB §4.4).
    pub fn message(self) -> &'static str {
        match self {
            Self::Length | Self::Charset => {
                "Use 1 to 64 letters, digits, spaces and . _ · - from one alphabet."
            }
            Self::Confusable => "This name mixes alphabets. Use one alphabet.",
            Self::Reserved => {
                "Names may not contain cloud, thinkery, leanctx or moderator. Pick another name."
            }
        }
    }
}

/// Scripts told apart by the single-script rule; any other script counts
/// as one more (C0 2.0 server rule).
const SCRIPTS: [&str; 14] = [
    "Latin",
    "Greek",
    "Cyrillic",
    "Armenian",
    "Hebrew",
    "Arabic",
    "Devanagari",
    "Bengali",
    "Thai",
    "Georgian",
    "Hangul",
    "Hiragana",
    "Katakana",
    "Han",
];

struct NameRules {
    charset: regex::Regex,
    letter: regex::Regex,
    scripts: Vec<regex::Regex>,
}

fn name_rules() -> &'static NameRules {
    static RULES: std::sync::OnceLock<NameRules> = std::sync::OnceLock::new();
    RULES.get_or_init(|| NameRules {
        charset: regex::Regex::new(r"^[\p{L}\p{N} ._·-]+$").expect("static regex"),
        letter: regex::Regex::new(r"^\p{L}$").expect("static regex"),
        scripts: SCRIPTS
            .iter()
            .map(|sc| regex::Regex::new(&format!(r"^\p{{sc={sc}}}$")).expect("static regex"))
            .collect(),
    })
}

/// The C0 2.0 worker-name rule, applied before a name leaves the engine.
/// Returns the NFKC form that is sent.
pub fn check_name(name: &str) -> Result<String, NameRefusal> {
    let name: String = name.nfkc().collect();
    let len = name.chars().count();
    if len == 0 || len > NAME_MAX {
        return Err(NameRefusal::Length);
    }
    let rules = name_rules();
    if !rules.charset.is_match(&name) {
        return Err(NameRefusal::Charset);
    }
    let mut script = None;
    let mut buf = [0u8; 4];
    for ch in name.chars() {
        let text = ch.encode_utf8(&mut buf);
        if !rules.letter.is_match(text) {
            continue;
        }
        let this = rules.scripts.iter().position(|r| r.is_match(text));
        match script {
            None => script = Some(this),
            Some(seen) if seen != this => return Err(NameRefusal::Confusable),
            Some(_) => {}
        }
    }
    let lower = name.to_lowercase();
    if RESERVED.iter().any(|r| lower.contains(r)) {
        return Err(NameRefusal::Reserved);
    }
    Ok(name)
}

/// Default name `<computer> · <Host app> · <role>`, built to pass
/// [`check_name`] (rc4-39):
/// - the computer is the instance label as a team sees it
///   ([`crate::bus::v2::machine_name`]: `yves-mac.local` → `yves-mac`);
///   apostrophes go (`Ada’s MacBook` → `Adas MacBook`, as macOS spells
///   its own host name) and every other character outside the rule
///   becomes a space, so no two words are glued together; a label that
///   still fails is left out;
/// - an app the engine could not tell (`None`, see
///   [`attach::named_host_display`]) is left out, never "unknown".
pub fn default_name(instance_label: &str, host_display: Option<&str>, role: &str) -> String {
    let host = host_display.map(str::trim).filter(|h| !h.is_empty());
    let tail = match host {
        Some(host) => format!("{host} · {role}"),
        None => role.to_string(),
    };
    let label = name_label(instance_label);
    let full = format!("{label} · {tail}");
    if !label.is_empty() && check_name(&full).is_ok() {
        full
    } else {
        tail
    }
}

/// The computer part of a default name: see [`default_name`].
fn name_label(instance_label: &str) -> String {
    let machine =
        crate::bus::v2::machine_name(instance_label).unwrap_or_else(|| instance_label.to_string());
    let label: String = machine
        .nfkc()
        .filter(|c| !matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{02BC}' | '`'))
        .filter(|c| !is_format_char(*c))
        .map(|c| {
            if c.is_alphanumeric() || matches!(c, '.' | '_' | '-') {
                c
            } else {
                ' '
            }
        })
        .collect();
    label.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// The role as a worker name shows it: a per-session worker's role
/// (`<role>-s<tag>`, [`session_role`]) without its session tag, which is
/// an internal id; any other role as it is (`dev-storybook` stays).
pub fn display_role(role: &str, per_session: bool) -> String {
    if per_session
        && let Some((base, tag)) = role.rsplit_once("-s")
        && tag.len() == SESSION_TAG_LEN
        && tag
            .bytes()
            .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
        && !base.is_empty()
    {
        return base.to_string();
    }
    role.to_string()
}

/// A Unicode format character (general category `Cf`: bidi controls,
/// zero-width spaces and joiners, the BOM): invisible, and able to reorder
/// what a terminal or page shows, so never part of a label or a name.
pub fn is_format_char(c: char) -> bool {
    use unicode_general_category::{GeneralCategory, get_general_category};
    get_general_category(c) == GeneralCategory::Format
}

/// The default name of `worker`, one of this instance's workers in
/// `book`: [`default_name`] over its host app and its role as people read
/// them. Two workers that would read the same (two sessions of one role
/// on one instance, rc4-39 review) are told apart by an ordinal on the
/// role (`backend`, `backend 2`, …): names Cloud already accepted are
/// taken, and the rest are named in book order, so the first keeps the
/// plain name and a single worker never gets a number. Only siblings an
/// active session holds (`live`, `(host_app, role)` keys) count: an ended
/// or crashed session never pushes a new one to `backend 2` (bd 5!678).
pub fn worker_default_name(
    instance_label: &str,
    worker: &attach::LocalWorker,
    book: &[attach::LocalWorker],
    live: &std::collections::BTreeSet<(String, String)>,
) -> String {
    let fold = |name: &str| name.to_lowercase();
    let counts = |w: &attach::LocalWorker| {
        w.worker_id != worker.worker_id && live.contains(&(w.host_app.clone(), w.role.clone()))
    };
    let mut taken: std::collections::BTreeSet<String> = book
        .iter()
        .filter(|w| counts(w))
        .filter_map(|w| w.name.as_deref().map(fold))
        .collect();
    let mut pick = |w: &attach::LocalWorker| {
        let host = attach::named_host_display(&w.host_app);
        let role = display_role(&w.role, w.per_session);
        let mut ordinal = 1_usize;
        loop {
            let shown = if ordinal == 1 {
                role.clone()
            } else {
                format!("{role} {ordinal}")
            };
            let name = default_name(instance_label, host.as_deref(), &shown);
            if taken.insert(fold(&name)) {
                return name;
            }
            ordinal += 1;
        }
    };
    for earlier in book {
        if earlier.worker_id == worker.worker_id {
            break;
        }
        if earlier.name.is_none() && counts(earlier) {
            pick(earlier);
        }
    }
    pick(worker)
}

/// The `(host_app, role)` keys of the active local sessions that worker
/// names count ([`worker_default_name`]). An agent registry that cannot be
/// read is logged and names as if no sibling were live (bd 5!678: never
/// swallowed silently).
pub fn live_keys_for_names() -> std::collections::BTreeSet<(String, String)> {
    attach::live_worker_keys().unwrap_or_else(|error| {
        tracing::warn!("cloud: worker names ignore sibling sessions: {error}");
        std::collections::BTreeSet::new()
    })
}

/// The names `cloud worker list` shows for `workers`, one per worker in
/// order: the name Cloud accepted, else the default over the live siblings.
pub fn shown_names(instance_label: &str, workers: &[attach::LocalWorker]) -> Vec<String> {
    let live = live_keys_for_names();
    workers
        .iter()
        .map(|w| {
            w.name
                .clone()
                .unwrap_or_else(|| worker_default_name(instance_label, w, workers, &live))
        })
        .collect()
}

/// The name `worker` must (re)register with, or `None` to keep the one it
/// has. A worker without a name gets its default ([`worker_default_name`]).
/// A worker that comes back with a default name a live sibling holds (a
/// resumed session 1 while session 3 took the plain `backend` during its
/// absence, bd 5!678) yields and takes the next free ordinal. Of two live
/// workers with one name, the later registration keeps it: it claimed the
/// name while the earlier one was gone. A name the person chose (not one of
/// this worker's default names) is never changed.
pub fn reattach_name(
    instance_label: &str,
    worker: &attach::LocalWorker,
    book: &[attach::LocalWorker],
    live: &std::collections::BTreeSet<(String, String)>,
) -> Option<String> {
    let Some(name) = worker.name.as_deref() else {
        return Some(worker_default_name(instance_label, worker, book, live));
    };
    let fold = name.to_lowercase();
    let mine = (worker.registered_at, worker.worker_id.as_str());
    let held = book.iter().any(|w| {
        w.worker_id != worker.worker_id
            && live.contains(&(w.host_app.clone(), w.role.clone()))
            && w.name.as_deref().is_some_and(|n| n.to_lowercase() == fold)
            && (w.registered_at, w.worker_id.as_str()) > mine
    });
    (held && reads_as_default(instance_label, worker, &fold))
        .then(|| worker_default_name(instance_label, worker, book, live))
}

/// Whether `folded` (a lower-cased name) is one of the default names of
/// `worker`: its plain role or the role with an ordinal.
fn reads_as_default(instance_label: &str, worker: &attach::LocalWorker, folded: &str) -> bool {
    let host = attach::named_host_display(&worker.host_app);
    let role = display_role(&worker.role, worker.per_session);
    (1..=attach::WORKER_CAP + 1).any(|ordinal| {
        let shown = if ordinal == 1 {
            role.clone()
        } else {
            format!("{role} {ordinal}")
        };
        default_name(instance_label, host.as_deref(), &shown).to_lowercase() == folded
    })
}

#[cfg(test)]
mod tests;