Skip to main content

lean_ctx/core/hive/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;
8
9use serde::{Deserialize, Serialize};
10
11use super::super::HiveError;
12use super::super::state::{HiveStore, 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 Hive 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}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
135struct WorkerBook {
136    schema: u32,
137    instance_id: String,
138    workers: Vec<LocalWorker>,
139}
140
141/// The worker a session attaches to.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Attachment {
144    pub worker: LocalWorker,
145    /// The requested `(host_app, role)` did not fit under [`WORKER_CAP`];
146    /// `hive status` warns `worker_cap_reached`.
147    pub cap_reached: bool,
148}
149
150/// Pure attachment rule over the known workers: an existing `(host, role)`
151/// is reused; a new one is added while fewer than [`WORKER_CAP`] exist;
152/// past the cap the session maps to role `general` (of its host when that
153/// worker exists, else the first `general` worker, else the first worker).
154pub fn attach_in(
155    workers: &mut Vec<LocalWorker>,
156    instance_id: &str,
157    host_app: &str,
158    role: &str,
159) -> Attachment {
160    let role = normalize_role(role);
161    let find = |workers: &[LocalWorker], host: &str, role: &str| {
162        workers
163            .iter()
164            .position(|w| w.host_app == host && w.role == role)
165    };
166    if let Some(i) = find(workers, host_app, &role) {
167        return Attachment {
168            worker: workers[i].clone(),
169            cap_reached: false,
170        };
171    }
172    if workers.len() < WORKER_CAP {
173        let worker = new_worker(instance_id, host_app, &role);
174        workers.push(worker.clone());
175        return Attachment {
176            worker,
177            cap_reached: false,
178        };
179    }
180    let fallback = find(workers, host_app, GENERAL_ROLE)
181        .or_else(|| workers.iter().position(|w| w.role == GENERAL_ROLE))
182        .unwrap_or(0);
183    Attachment {
184        worker: workers[fallback].clone(),
185        cap_reached: true,
186    }
187}
188
189fn new_worker(instance_id: &str, host_app: &str, role: &str) -> LocalWorker {
190    LocalWorker {
191        worker_id: workspace_worker_id(instance_id, host_app, role),
192        host_app: host_app.to_string(),
193        role: role.to_string(),
194        name: None,
195        registered_at: None,
196        aliases: BTreeMap::new(),
197    }
198}
199
200/// Attach a session of `host_app` with `role` to a durable worker of the
201/// enrolled instance, adding it to the book when new.
202pub fn attach(
203    store: &HiveStore,
204    instance_id: &str,
205    host_app: &str,
206    role: &str,
207) -> Result<Attachment, HiveError> {
208    update_book(store, instance_id, |workers| {
209        attach_in(workers, instance_id, host_app, role)
210    })
211}
212
213/// Every durable worker of the enrolled instance.
214pub fn list(store: &HiveStore, instance_id: &str) -> Result<Vec<LocalWorker>, HiveError> {
215    Ok(read_book(store, instance_id)?.workers)
216}
217
218/// Read-modify-write the book under its lock.
219pub(crate) fn update_book<T>(
220    store: &HiveStore,
221    instance_id: &str,
222    change: impl FnOnce(&mut Vec<LocalWorker>) -> T,
223) -> Result<T, HiveError> {
224    let dir = store.data_dir();
225    let _lock = lock_state(dir, BOOK_FILE)?;
226    let mut book = read_book(store, instance_id)?;
227    let out = change(&mut book.workers);
228    let bytes = serde_json::to_vec(&book).map_err(|e| HiveError::Local(e.to_string()))?;
229    write_private(dir, BOOK_FILE, &bytes)?;
230    Ok(out)
231}
232
233/// The book of `instance_id`; a book of another (earlier) instance is
234/// replaced, since its ids are bound to that instance. Books are keyed by
235/// the canonical id, so a book from before the canonical form (whose ids
236/// were derived from `inst_<hex>`) is replaced as well.
237fn read_book(store: &HiveStore, instance_id: &str) -> Result<WorkerBook, HiveError> {
238    let path = store.data_dir().join(BOOK_FILE);
239    let book = load_or_quarantine::<WorkerBook>(&path, |b| b.schema == BOOK_SCHEMA)?;
240    let canonical = super::canonical_instance_id(instance_id);
241    Ok(book
242        .filter(|b| b.instance_id == canonical)
243        .unwrap_or_else(|| WorkerBook {
244            schema: BOOK_SCHEMA,
245            instance_id: canonical,
246            workers: Vec::new(),
247        }))
248}