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