Skip to main content

lean_ctx_cloud/workers/
attach.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Which worker a session belongs to (SPEC-ENGINE §3.6): host app
3//! detection, role normalisation, the 32-worker cap and the local book of
4//! durable workers. Sessions (`mcp-<pid>-<uuid>`) are only a detail of the
5//! worker they attach to.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use serde::{Deserialize, Serialize};
10
11use super::super::CloudError;
12use super::super::state::{CloudStore, load_or_quarantine, lock_state, write_private};
13use super::{GENERAL_ROLE, normalize_role, workspace_worker_id};
14
15/// Durable workers one instance may have (workspace ids).
16pub const WORKER_CAP: usize = 32;
17const BOOK_FILE: &str = "workers.json";
18const BOOK_SCHEMA: u32 = 1;
19
20/// Host app of a session, from the hints in order of trust: the MCP
21/// handshake's identified host, the `ctx_agent` agent type, the process
22/// environment, then `mcp-client:<clientInfo.name>`.
23pub fn detect_host_app<I, K, V>(
24    transport_host: Option<&str>,
25    agent_type: Option<&str>,
26    env: I,
27    client_name: Option<&str>,
28) -> String
29where
30    I: IntoIterator<Item = (K, V)>,
31    K: AsRef<str>,
32    V: AsRef<str>,
33{
34    transport_host
35        .and_then(known_host)
36        .or_else(|| agent_type.and_then(known_host))
37        .or_else(|| host_from_env(env))
38        .or_else(|| client_name.and_then(known_host))
39        .map_or_else(|| mcp_client(client_name), str::to_string)
40}
41
42/// SPEC-ENGINE §3.6 host table on a host or client name.
43fn known_host(name: &str) -> Option<&'static str> {
44    let name = name.trim().to_ascii_lowercase();
45    Some(match name.as_str() {
46        "claude" | "claude-code" | "claude code" => "claude-code",
47        "codex" | "codex-cli" | "codex-mcp-client" => "codex",
48        "cursor" | "cursor-agent" | "cursor-vscode" => "cursor",
49        "gemini" | "gemini-cli" => "gemini-cli",
50        "copilot" | "gh copilot" | "github-copilot" => "copilot",
51        "opencode" => "opencode",
52        _ => return None,
53    })
54}
55
56/// SPEC-ENGINE §3.6 environment markers.
57fn host_from_env<I, K, V>(env: I) -> Option<&'static str>
58where
59    I: IntoIterator<Item = (K, V)>,
60    K: AsRef<str>,
61    V: AsRef<str>,
62{
63    let vars: BTreeMap<String, String> = env
64        .into_iter()
65        .filter(|(_, v)| !v.as_ref().trim().is_empty())
66        .map(|(k, v)| (k.as_ref().to_string(), v.as_ref().to_string()))
67        .collect();
68    let any_prefix = |prefix: &str| vars.keys().any(|k| k.starts_with(prefix));
69    if vars.get("CLAUDECODE").is_some_and(|v| v.trim() == "1") {
70        Some("claude-code")
71    } else if any_prefix("CODEX_") {
72        Some("codex")
73    } else if vars.contains_key("CURSOR_TRACE_ID") || vars.contains_key("CURSOR_TASK_ID") {
74        Some("cursor")
75    } else if vars.contains_key("GEMINI_CLI") {
76        Some("gemini-cli")
77    } else if any_prefix("COPILOT_") {
78        Some("copilot")
79    } else if any_prefix("OPENCODE") {
80        Some("opencode")
81    } else {
82        None
83    }
84}
85
86/// `mcp-client:<name>` with the name reduced to `[A-Za-z0-9._ -]{1,64}`.
87fn mcp_client(client_name: Option<&str>) -> String {
88    let name: String = client_name
89        .unwrap_or_default()
90        .chars()
91        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ' ' | '-'))
92        .take(64)
93        .collect();
94    let name = name.trim();
95    format!(
96        "mcp-client:{}",
97        if name.is_empty() { "unknown" } else { name }
98    )
99}
100
101/// Display name of a host app in default worker names.
102pub fn host_display(host_app: &str) -> String {
103    match host_app {
104        "claude-code" => "Claude Code".to_string(),
105        "codex" => "Codex".to_string(),
106        "cursor" => "Cursor".to_string(),
107        "gemini-cli" => "Gemini CLI".to_string(),
108        "copilot" => "Copilot".to_string(),
109        "opencode" => "OpenCode".to_string(),
110        other => other
111            .strip_prefix("mcp-client:")
112            .unwrap_or(other)
113            .to_string(),
114    }
115}
116
117/// A durable worker of this instance as the engine remembers it.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct LocalWorker {
120    pub worker_id: String,
121    pub host_app: String,
122    pub role: String,
123    /// Name last accepted by Cloud or set locally; `None` → default name.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub name: Option<String>,
126    /// Ms timestamp of the E10 registration; `None` until registered.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub registered_at: Option<u64>,
129    /// Place-scoped aliases registered through E10 (`place_ref` → alias id).
130    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
131    pub aliases: BTreeMap<String, String>,
132    /// Ms timestamp of the last session that attached to it; `None` in a
133    /// book written before it was kept (oldest first when one must go).
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub last_attached: Option<u64>,
136    /// The worker of one app session (`<role>-s<tag>`, [`super::session_role`]),
137    /// recorded when a live session with an app session id attached to it:
138    /// it ends with that session. A role that merely looks like a tagged
139    /// one (`dev-storybook`) is never marked.
140    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
141    pub per_session: bool,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
145struct WorkerBook {
146    schema: u32,
147    instance_id: String,
148    workers: Vec<LocalWorker>,
149    /// Registered workers evicted from the book that Cloud still counts:
150    /// the relay retires them (`DELETE /v1/workers/{id}`) before the next
151    /// registration.
152    #[serde(default, skip_serializing_if = "Vec::is_empty")]
153    retired: Vec<String>,
154}
155
156/// The worker a session attaches to.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Attachment {
159    pub worker: LocalWorker,
160    /// The requested `(host_app, role)` did not fit under [`WORKER_CAP`]
161    /// and every worker is in use: the session shares another worker
162    /// (`cloud status` warns `worker_cap_reached`).
163    pub cap_reached: bool,
164}
165
166/// Pure attachment rule over the known workers: an existing `(host, role)`
167/// is reused; a new one is added while fewer than [`WORKER_CAP`] exist;
168/// past the cap the session maps to role `general` (of its host when that
169/// worker exists, else the first `general` worker, else the first worker).
170/// [`attach`] makes room first, so this fallback only happens when every
171/// worker is in use.
172pub fn attach_in(
173    workers: &mut Vec<LocalWorker>,
174    instance_id: &str,
175    host_app: &str,
176    role: &str,
177) -> Attachment {
178    let role = normalize_role(role);
179    let find = |workers: &[LocalWorker], host: &str, role: &str| {
180        workers
181            .iter()
182            .position(|w| w.host_app == host && w.role == role)
183    };
184    if let Some(i) = find(workers, host_app, &role) {
185        return Attachment {
186            worker: workers[i].clone(),
187            cap_reached: false,
188        };
189    }
190    if workers.len() < WORKER_CAP {
191        let worker = new_worker(instance_id, host_app, &role);
192        workers.push(worker.clone());
193        return Attachment {
194            worker,
195            cap_reached: false,
196        };
197    }
198    let fallback = find(workers, host_app, GENERAL_ROLE)
199        .or_else(|| workers.iter().position(|w| w.role == GENERAL_ROLE))
200        .unwrap_or(0);
201    Attachment {
202        worker: workers[fallback].clone(),
203        cap_reached: true,
204    }
205}
206
207fn new_worker(instance_id: &str, host_app: &str, role: &str) -> LocalWorker {
208    LocalWorker {
209        worker_id: workspace_worker_id(instance_id, host_app, role),
210        host_app: host_app.to_string(),
211        role: role.to_string(),
212        name: None,
213        registered_at: None,
214        aliases: BTreeMap::new(),
215        last_attached: None,
216        per_session: false,
217    }
218}
219
220/// Make room for a new `(host_app, role)` in a full book: the worker that
221/// no session in `in_use` holds and that was attached longest ago leaves
222/// the book (a registered one is queued in `retired` for Cloud). The
223/// connector's own workers (host [`CAPTURE_HOST`]: capture, friction,
224/// CLI) never leave. `false` when every worker is in use.
225///
226/// [`CAPTURE_HOST`]: crate::sync::place::CAPTURE_HOST
227pub(super) fn evict_one(
228    workers: &mut Vec<LocalWorker>,
229    retired: &mut Vec<String>,
230    in_use: &BTreeSet<(String, String)>,
231) -> bool {
232    let Some(i) = workers
233        .iter()
234        .enumerate()
235        .filter(|(_, w)| w.host_app != crate::sync::place::CAPTURE_HOST)
236        .filter(|(_, w)| !in_use.contains(&(w.host_app.clone(), w.role.clone())))
237        .min_by_key(|(_, w)| (w.last_attached, w.registered_at))
238        .map(|(i, _)| i)
239    else {
240        return false;
241    };
242    let gone = workers.remove(i);
243    if gone.registered_at.is_some() && !retired.contains(&gone.worker_id) {
244        retired.push(gone.worker_id);
245    }
246    true
247}
248
249/// [`attach_in`] on a book that makes room first (see [`evict_one`]) and
250/// stamps the worker it attaches with `now_ms`. Without `live` (the agent
251/// registry could not be read) no worker is evicted: every one may be in
252/// use, so a full book shares as when every worker is.
253fn attach_making_room(
254    book: &mut WorkerBook,
255    instance_id: &str,
256    host_app: &str,
257    role: &str,
258    live: Option<&LiveSessions>,
259    now_ms: u64,
260) -> Attachment {
261    let role = normalize_role(role);
262    let known = book
263        .workers
264        .iter()
265        .any(|w| w.host_app == host_app && w.role == role);
266    let full = !known && book.workers.len() >= WORKER_CAP;
267    if let Some(live) = live.filter(|_| full) {
268        let mut in_use = live.in_use.clone();
269        in_use.insert((host_app.to_string(), role.clone()));
270        evict_one(&mut book.workers, &mut book.retired, &in_use);
271    }
272    let per_session = live.is_some_and(|live| {
273        live.per_session
274            .contains(&(host_app.to_string(), role.clone()))
275    });
276    let attached = attach_in(&mut book.workers, instance_id, host_app, &role);
277    // A worker that comes back is no longer to be retired.
278    book.retired.retain(|id| *id != attached.worker.worker_id);
279    let worker = book
280        .workers
281        .iter_mut()
282        .find(|w| w.worker_id == attached.worker.worker_id);
283    match worker {
284        Some(worker) => {
285            worker.last_attached = Some(now_ms);
286            // Only the worker attached under its own `(host, role)` (not a
287            // shared fallback past the cap) is the session's.
288            if per_session && worker.host_app == host_app && worker.role == role {
289                worker.per_session = true;
290            }
291            Attachment {
292                worker: worker.clone(),
293                cap_reached: attached.cap_reached,
294            }
295        }
296        None => attached,
297    }
298}
299
300/// The workers the active local sessions hold.
301#[derive(Debug, Default)]
302struct LiveSessions {
303    /// `(host_app, role)` of every active session: these stay in the book.
304    in_use: BTreeSet<(String, String)>,
305    /// Those of sessions with an app session id (`<role>-s<tag>`).
306    per_session: BTreeSet<(String, String)>,
307}
308
309/// The workers of every active local session, from the agent registry read
310/// strictly: a registry that exists but cannot be read or parsed is an
311/// error, never "no session" (review 5!246: an empty fallback made every
312/// live session's worker look idle to the sweeps). Logged once per process.
313fn live_sessions() -> Result<LiveSessions, CloudError> {
314    static WARNED: std::sync::Once = std::sync::Once::new();
315    let registry = lean_ctx::core::agents::AgentRegistry::load_checked().map_err(|error| {
316        WARNED.call_once(|| {
317            tracing::warn!("cloud: agent registry unreadable, no worker is retired: {error}");
318        });
319        CloudError::Local(format!(
320            "agent registry unreadable ({error}): which workers are in use is unknown"
321        ))
322    })?;
323    let mut live = LiveSessions::default();
324    for agent in registry.list_active(None) {
325        let key = agent_worker_key(agent);
326        if agent
327            .app_session_id
328            .as_deref()
329            .is_some_and(|s| !s.trim().is_empty())
330        {
331            live.per_session.insert(key.clone());
332        }
333        live.in_use.insert(key);
334    }
335    Ok(live)
336}
337
338/// The `(host_app, role)` of the worker a local presence speaks as: the
339/// host app from its transport or agent type, and its `ctx_agent` role
340/// made per session when the launching app named one
341/// ([`super::session_role`]). Two sessions of one role on one instance are
342/// two agents on Cloud; a subagent in the same session with the same role
343/// is the same agent.
344pub fn agent_worker_key(agent: &lean_ctx::core::agents::AgentEntry) -> (String, String) {
345    let transport = agent.transport.as_ref();
346    let host = detect_host_app(
347        transport.map(|t| t.host.as_str()),
348        Some(agent.agent_type.as_str()),
349        std::iter::empty::<(&str, &str)>(),
350        transport.and_then(|t| t.name.as_deref()),
351    );
352    let role = super::session_role(
353        agent.role.as_deref().unwrap_or_default(),
354        agent.app_session_id.as_deref(),
355    );
356    (host, role)
357}
358
359/// Attach a session of `host_app` with `role` to a durable worker of the
360/// enrolled instance, adding it to the book when new. A full book (32,
361/// as Cloud allows per instance) gives up the longest-unused worker no
362/// active session holds, so a new role gets its own worker instead of
363/// sharing another one's.
364pub fn attach(
365    store: &CloudStore,
366    instance_id: &str,
367    host_app: &str,
368    role: &str,
369) -> Result<Attachment, CloudError> {
370    let live = live_sessions().ok();
371    let now_ms =
372        u64::try_from(lean_ctx_time::UtcDateTime::now().timestamp_millis()).unwrap_or_default();
373    update_whole_book(store, instance_id, |book| {
374        attach_making_room(book, instance_id, host_app, role, live.as_ref(), now_ms)
375    })
376}
377
378/// The worker of `(host_app, role)` if the book has one, without adding
379/// or stamping anything (for sessions that have ended).
380pub fn known(
381    store: &CloudStore,
382    instance_id: &str,
383    host_app: &str,
384    role: &str,
385) -> Option<LocalWorker> {
386    let role = normalize_role(role);
387    read_book(store, instance_id)
388        .ok()?
389        .workers
390        .into_iter()
391        .find(|w| w.host_app == host_app && w.role == role)
392}
393
394/// Every durable worker of the enrolled instance.
395pub fn list(store: &CloudStore, instance_id: &str) -> Result<Vec<LocalWorker>, CloudError> {
396    Ok(read_book(store, instance_id)?.workers)
397}
398
399/// Workers evicted from the book that Cloud still counts.
400pub fn retired(store: &CloudStore, instance_id: &str) -> Result<Vec<String>, CloudError> {
401    Ok(read_book(store, instance_id)?.retired)
402}
403
404/// Forget `worker_id` as pending retirement (Cloud retired it, or never knew it).
405pub fn retirement_done(
406    store: &CloudStore,
407    instance_id: &str,
408    worker_id: &str,
409) -> Result<(), CloudError> {
410    update_whole_book(store, instance_id, |book| {
411        book.retired.retain(|id| id != worker_id);
412    })
413}
414
415/// When a session last attached to `worker` (ms), else when it was
416/// registered; `None` when neither is known (a book from before either).
417#[must_use]
418pub fn last_seen_ms(worker: &LocalWorker) -> Option<u64> {
419    worker.last_attached.or(worker.registered_at)
420}
421
422/// The workers that may retire (owner 09.11.: workers that are not active
423/// do not count and are switched off): not the connector's own (host
424/// `CAPTURE_HOST`), held by no active session in `in_use`, and last seen
425/// before `cutoff_ms` (never seen: idle). With `session_only`, only the
426/// workers recorded as one app session's ([`LocalWorker::per_session`]),
427/// which end with it.
428#[must_use]
429pub fn idle_workers(
430    workers: &[LocalWorker],
431    in_use: &BTreeSet<(String, String)>,
432    cutoff_ms: u64,
433    session_only: bool,
434) -> Vec<String> {
435    workers
436        .iter()
437        .filter(|w| w.host_app != crate::sync::place::CAPTURE_HOST)
438        .filter(|w| !in_use.contains(&(w.host_app.clone(), w.role.clone())))
439        .filter(|w| !session_only || w.per_session)
440        .filter(|w| last_seen_ms(w).is_none_or(|seen| seen < cutoff_ms))
441        .map(|w| w.worker_id.clone())
442        .collect()
443}
444
445/// Take `ids` out of the book; each one Cloud may still count (registered,
446/// or not in the book at all) is queued for retirement on Cloud
447/// ([`super::register::retire_evicted`]). The ids taken, in order.
448fn give_up_in(book: &mut WorkerBook, ids: &[String]) -> Vec<String> {
449    let mut taken = Vec::new();
450    for id in ids {
451        let registered = match book.workers.iter().position(|w| &w.worker_id == id) {
452            Some(i) => book.workers.remove(i).registered_at.is_some(),
453            None => crate::bus::address::is_worker_id(id),
454        };
455        if registered && !book.retired.contains(id) {
456            book.retired.push(id.clone());
457        }
458        taken.push(id.clone());
459    }
460    taken
461}
462
463/// The ids in `ids` whose worker an active session in `in_use` holds: a
464/// worker of the book under a `(host, role)` in use, or (for an id the
465/// book does not have) the deterministic workspace id of a `(host, role)`
466/// in use on this instance.
467fn busy_ids(
468    book: &WorkerBook,
469    instance_id: &str,
470    ids: &[String],
471    in_use: &BTreeSet<(String, String)>,
472) -> Vec<String> {
473    let mut busy: BTreeSet<String> = in_use
474        .iter()
475        .map(|(host, role)| workspace_worker_id(instance_id, host, role))
476        .collect();
477    busy.extend(
478        book.workers
479            .iter()
480            .filter(|w| in_use.contains(&(w.host_app.clone(), w.role.clone())))
481            .map(|w| w.worker_id.clone()),
482    );
483    ids.iter()
484        .filter(|id| busy.contains(*id))
485        .cloned()
486        .collect()
487}
488
489/// `give_up_in` on the book of `instance_id`, for an explicit retirement
490/// (`lean-ctx cloud worker retire <wkr_…>`). Refused when an active local
491/// session holds one of `ids` (Cloud would delete a worker that keeps
492/// posting), or when the agent registry cannot be read to tell; `force`
493/// skips that check.
494pub fn give_up(
495    store: &CloudStore,
496    instance_id: &str,
497    ids: &[String],
498    force: bool,
499) -> Result<Vec<String>, CloudError> {
500    let in_use = if force {
501        BTreeSet::new()
502    } else {
503        live_sessions()?.in_use
504    };
505    update_whole_book(store, instance_id, |book| {
506        let busy = busy_ids(book, instance_id, ids, &in_use);
507        if busy.is_empty() {
508            Ok(give_up_in(book, ids))
509        } else {
510            Err(CloudError::Config(format!(
511                "{} in use by an active session; end that session first, or retire with --force",
512                busy.join(", ")
513            )))
514        }
515    })?
516}
517
518/// Give up every worker idle for `idle` or longer ([`idle_workers`]),
519/// under the book's lock. No request: Cloud hears of them with
520/// [`super::register::retire_evicted`] (the sync, the next registration).
521/// Fails closed: when the agent registry cannot be read, nothing is given
522/// up (which workers live sessions hold is unknown).
523pub fn give_up_idle(
524    store: &CloudStore,
525    instance_id: &str,
526    idle: std::time::Duration,
527    session_only: bool,
528) -> Result<Vec<String>, CloudError> {
529    let in_use = live_sessions()?.in_use;
530    let now_ms =
531        u64::try_from(lean_ctx_time::UtcDateTime::now().timestamp_millis()).unwrap_or_default();
532    let cutoff_ms = now_ms.saturating_sub(u64::try_from(idle.as_millis()).unwrap_or(u64::MAX));
533    update_whole_book(store, instance_id, |book| {
534        let ids = idle_workers(&book.workers, &in_use, cutoff_ms, session_only);
535        give_up_in(book, &ids)
536    })
537}
538
539/// Read-modify-write the book under its lock.
540pub fn update_book<T>(
541    store: &CloudStore,
542    instance_id: &str,
543    change: impl FnOnce(&mut Vec<LocalWorker>) -> T,
544) -> Result<T, CloudError> {
545    update_whole_book(store, instance_id, |book| change(&mut book.workers))
546}
547
548fn update_whole_book<T>(
549    store: &CloudStore,
550    instance_id: &str,
551    change: impl FnOnce(&mut WorkerBook) -> T,
552) -> Result<T, CloudError> {
553    let dir = store.data_dir();
554    let _lock = lock_state(dir, BOOK_FILE)?;
555    let mut book = read_book(store, instance_id)?;
556    let out = change(&mut book);
557    let bytes = serde_json::to_vec(&book).map_err(|e| CloudError::Local(e.to_string()))?;
558    write_private(dir, BOOK_FILE, &bytes)?;
559    Ok(out)
560}
561
562/// The book of `instance_id`; a book of another (earlier) instance is
563/// replaced, since its ids are bound to that instance. Books are keyed by
564/// the canonical id, so a book from before the canonical form (whose ids
565/// were derived from `inst_<hex>`) is replaced as well.
566fn read_book(store: &CloudStore, instance_id: &str) -> Result<WorkerBook, CloudError> {
567    let path = store.data_dir().join(BOOK_FILE);
568    let book = load_or_quarantine::<WorkerBook>(&path, |b| b.schema == BOOK_SCHEMA)?;
569    let canonical = super::canonical_instance_id(instance_id);
570    Ok(book
571        .filter(|b| b.instance_id == canonical)
572        .unwrap_or_else(|| WorkerBook {
573            schema: BOOK_SCHEMA,
574            instance_id: canonical,
575            workers: Vec::new(),
576            retired: Vec::new(),
577        }))
578}
579
580#[cfg(test)]
581mod retire_tests {
582    use super::*;
583
584    fn worker(
585        id: &str,
586        host: &str,
587        role: &str,
588        seen: Option<u64>,
589        registered: bool,
590    ) -> LocalWorker {
591        LocalWorker {
592            worker_id: id.into(),
593            host_app: host.into(),
594            role: role.into(),
595            name: None,
596            registered_at: registered.then_some(1),
597            aliases: BTreeMap::new(),
598            last_attached: seen,
599            per_session: false,
600        }
601    }
602
603    #[test]
604    fn idle_workers_spare_active_recent_and_connector_workers() {
605        let workers = vec![
606            worker("wkr_old", "claude", "reviewer", Some(100), true),
607            worker("wkr_new", "claude", "builder", Some(5_000), true),
608            worker("wkr_busy", "codex", "queen", Some(100), true),
609            worker(
610                "wkr_cap",
611                crate::sync::place::CAPTURE_HOST,
612                "capture",
613                Some(100),
614                true,
615            ),
616            worker("wkr_never", "cursor", "general", None, false),
617        ];
618        let in_use: BTreeSet<_> = [("codex".to_string(), "queen".to_string())].into();
619        assert_eq!(
620            idle_workers(&workers, &in_use, 1_000, false),
621            vec!["wkr_old".to_string(), "wkr_never".to_string()]
622        );
623    }
624
625    /// Review 5!246 #5: only workers recorded as an app session's are
626    /// session workers; `dev-storybook` looks like `<role>-s<tag>` (base
627    /// `dev`, tag `torybook`) but is a plain role and keeps the 24 h sweep.
628    #[test]
629    fn session_only_takes_the_workers_of_ended_app_sessions() {
630        let per_session = super::super::session_role("worker", Some("app-session-1"));
631        let mut tagged = worker("wkr_a", "claude", &per_session, Some(5_000), true);
632        tagged.per_session = true;
633        let workers = vec![
634            tagged,
635            worker("wkr_b", "claude", "worker", Some(100), true),
636            worker("wkr_c", "claude", "dev-storybook", Some(100), true),
637        ];
638        let none = BTreeSet::new();
639        assert_eq!(
640            idle_workers(&workers, &none, u64::MAX, true),
641            vec!["wkr_a".to_string()]
642        );
643    }
644
645    /// Review 5!246 #5: attaching marks the worker of a live session with
646    /// an app session id, and only that one.
647    #[test]
648    fn attaching_records_which_workers_are_per_session() {
649        let tagged = super::super::session_role("worker", Some("app-session-1"));
650        let live = LiveSessions {
651            in_use: [("claude".to_string(), tagged.clone())].into(),
652            per_session: [("claude".to_string(), tagged.clone())].into(),
653        };
654        let mut book = WorkerBook {
655            schema: BOOK_SCHEMA,
656            instance_id: "i".into(),
657            workers: Vec::new(),
658            retired: Vec::new(),
659        };
660        let a = attach_making_room(&mut book, "i", "claude", &tagged, Some(&live), 1);
661        assert!(a.worker.per_session);
662        let b = attach_making_room(&mut book, "i", "claude", "dev-storybook", Some(&live), 1);
663        assert!(!b.worker.per_session);
664        let c = attach_making_room(&mut book, "i", "codex", "x", None, 1);
665        assert!(
666            !c.worker.per_session,
667            "an unreadable registry marks nothing"
668        );
669    }
670
671    /// Review 5!246 #1: an id a live session holds is busy, whether the
672    /// book has it or not (worker ids are deterministic per host and role).
673    #[test]
674    fn busy_ids_cover_book_workers_and_unknown_ids_in_use() {
675        let book = WorkerBook {
676            schema: BOOK_SCHEMA,
677            instance_id: "i".into(),
678            workers: vec![
679                worker("wkr_queen", "codex", "queen", Some(1), true),
680                worker("wkr_idle", "codex", "idle", Some(1), true),
681            ],
682            retired: Vec::new(),
683        };
684        let in_use: BTreeSet<_> = [
685            ("codex".to_string(), "queen".to_string()),
686            ("claude-code".to_string(), "ops".to_string()),
687        ]
688        .into();
689        let unbooked = workspace_worker_id("i", "claude-code", "ops");
690        let stranger = format!("wkr_{}", "a".repeat(20));
691        let ids = vec![
692            "wkr_queen".to_string(),
693            "wkr_idle".to_string(),
694            unbooked.clone(),
695            stranger,
696        ];
697        assert_eq!(
698            busy_ids(&book, "i", &ids, &in_use),
699            vec!["wkr_queen".to_string(), unbooked]
700        );
701    }
702
703    #[test]
704    fn giving_up_queues_what_cloud_counts_and_drops_the_rest() {
705        let mut book = WorkerBook {
706            schema: BOOK_SCHEMA,
707            instance_id: "i".into(),
708            workers: vec![
709                worker("wkr_registered", "claude", "a", Some(1), true),
710                worker("wkr_local", "claude", "b", Some(1), false),
711                worker("wkr_kept", "claude", "c", Some(1), true),
712            ],
713            retired: Vec::new(),
714        };
715        let unknown = format!("wkr_{}", "a".repeat(20));
716        let ids = vec![
717            "wkr_registered".to_string(),
718            "wkr_local".to_string(),
719            unknown.clone(),
720        ];
721        assert_eq!(give_up_in(&mut book, &ids), ids);
722        assert_eq!(book.workers.len(), 1);
723        assert_eq!(book.workers[0].worker_id, "wkr_kept");
724        // A worker Cloud may know though the book does not is retired there
725        // too; a local, never registered one only leaves the book.
726        assert_eq!(book.retired, vec!["wkr_registered".to_string(), unknown]);
727    }
728}