Skip to main content

lean_ctx/core/hive/
conductor.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Conductor of a swarm, engine side (SPEC-ENGINE §3.13 "Conductor", V7.5;
3//! CONTRACT §3.20.4, RESOLUTIONS R107).
4//!
5//! Only the swarm owner's conductor workers and named delegates conduct.
6//! The engine offers conductor actions only when the server's role says so:
7//! the participant worker is listed in E22 `swarm.conductor_workers` or
8//! `swarm.delegates`. Every call carries the instance token of the worker's
9//! own instance and the worker id; the server refuses a worker of another
10//! instance (`403 forbidden reason: worker_not_owned`) and an ineligible
11//! one (`403 forbidden reason: not_conductor`).
12//!
13//! E28: `POST /swarms/{id}/conductor/lease {worker_id}` → `{epoch,
14//! expires_at, holder}` (10 min; `409 conductor_busy` with the holder),
15//! `POST …/lease/renew {worker_id, epoch}` (every ≤ 5 min; `409
16//! stale_epoch`), `DELETE …/lease?epoch=&worker_id=`. E29: `POST
17//! /swarms/{id}/conductor/actions {worker_id, epoch, action, …}` with the
18//! actions `split`, `assign`, `synthesize`, `block`, `unblock`, `drop`,
19//! `reopen`, `edit`.
20
21use serde::{Deserialize, Serialize};
22use serde_json::{Value, json};
23
24use super::HiveError;
25use super::convert::ConvertApi;
26
27/// Children of one `split` (C0 `split{children[1..50]}`).
28pub const MAX_SPLIT_CHILDREN: usize = 50;
29
30/// Whether `worker_id` may conduct the swarm an E22 goal answer describes.
31pub fn eligible(goal: &Value, worker_id: &str) -> bool {
32    ["conductor_workers", "delegates"].iter().any(|list| {
33        goal["swarm"][list]
34            .as_array()
35            .is_some_and(|ids| ids.iter().any(|id| id.as_str() == Some(worker_id)))
36    })
37}
38
39/// The conductor lease this worker holds.
40#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
41pub struct Lease {
42    pub epoch: u64,
43    pub expires_at: u64,
44    pub holder: Holder,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
48pub struct Holder {
49    pub worker_id: String,
50    pub name: String,
51}
52
53/// One child goal of a `split`.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Child {
56    pub title: String,
57    pub text: String,
58    pub acceptance: Vec<String>,
59    /// `subgoal` or `task`.
60    pub kind: String,
61}
62
63/// An E29 action (C0 `routes/conductor_action.*.request.json`).
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
66pub enum Action {
67    Split {
68        parent: String,
69        children: Vec<Child>,
70    },
71    Assign {
72        goal: String,
73        assignee: String,
74    },
75    Synthesize {
76        parent: String,
77        title: String,
78    },
79    Block {
80        goal: String,
81        reason: String,
82    },
83    Unblock {
84        goal: String,
85    },
86    Drop {
87        goal: String,
88        reason: String,
89    },
90    Reopen {
91        goal: String,
92        reason: String,
93    },
94    Edit {
95        goal: String,
96        #[serde(skip_serializing_if = "Option::is_none")]
97        title: Option<String>,
98        #[serde(skip_serializing_if = "Option::is_none")]
99        text: Option<String>,
100        #[serde(skip_serializing_if = "Option::is_none")]
101        acceptance: Option<Vec<String>>,
102    },
103}
104
105/// Why a conductor call did not go through.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum Refusal {
108    /// Checked locally before any call: the role does not allow it.
109    NotConductor,
110    /// The worker belongs to another instance.
111    WorkerNotOwned,
112    /// Another conductor holds the lease.
113    Busy { holder: Option<String> },
114    /// The lease moved on: take it again.
115    StaleEpoch,
116    /// Paused or archived swarm, or another refusal (`code`/`reason`).
117    Other { status: u16, code: String },
118}
119
120impl Refusal {
121    pub fn code(&self) -> &str {
122        match self {
123            Self::NotConductor => "not_conductor",
124            Self::WorkerNotOwned => "worker_not_owned",
125            Self::Busy { .. } => "conductor_busy",
126            Self::StaleEpoch => "stale_epoch",
127            Self::Other { code, .. } => code,
128        }
129    }
130
131    fn of(status: u16, body: &Value) -> Self {
132        let e = &body["error"];
133        let reason = e["reason"].as_str().unwrap_or_default();
134        let code = e["code"].as_str().unwrap_or_default();
135        match (status, code, reason) {
136            (403, _, "not_conductor") => Self::NotConductor,
137            (403, _, "worker_not_owned") => Self::WorkerNotOwned,
138            (409, _, "conductor_busy") => Self::Busy {
139                holder: e["holder"]["worker_id"].as_str().map(str::to_string),
140            },
141            (409, "stale_epoch", _) => Self::StaleEpoch,
142            _ => Self::Other {
143                status,
144                code: if reason.is_empty() { code } else { reason }.to_string(),
145            },
146        }
147    }
148}
149
150impl From<Refusal> for HiveError {
151    fn from(r: Refusal) -> Self {
152        HiveError::Refused(format!("conductor: {}", r.code()))
153    }
154}
155
156/// A conductor session of one participant worker in one swarm.
157pub struct Conductor<'a> {
158    pub api: &'a dyn ConvertApi,
159    pub swarm_id: &'a str,
160    pub worker_id: &'a str,
161    /// From E22: the role the server gave this worker.
162    pub eligible: bool,
163}
164
165fn ok_or(status: u16, body: Value) -> Result<Value, Result<Refusal, HiveError>> {
166    if (200..300).contains(&status) {
167        Ok(body)
168    } else {
169        Err(Ok(Refusal::of(status, &body)))
170    }
171}
172
173/// `Err(Ok(refusal))` for a contract refusal, `Err(Err(_))` for transport
174/// or shape errors.
175pub type Answer<T> = Result<T, Result<Refusal, HiveError>>;
176
177impl Conductor<'_> {
178    fn gate(&self) -> Answer<()> {
179        if self.eligible {
180            Ok(())
181        } else {
182            // No conductor action for a worker the server does not list.
183            Err(Ok(Refusal::NotConductor))
184        }
185    }
186
187    fn base(&self) -> String {
188        format!("/swarms/{}/conductor", self.swarm_id)
189    }
190
191    fn lease_from(body: Value) -> Answer<Lease> {
192        serde_json::from_value(body)
193            .map_err(|e| Err(HiveError::Protocol(format!("conductor lease: {e}"))))
194    }
195
196    /// E28 acquire.
197    pub fn acquire(&self) -> Answer<Lease> {
198        self.gate()?;
199        let (status, body) = self
200            .api
201            .answer(
202                "POST",
203                &format!("{}/lease", self.base()),
204                Some(&json!({ "worker_id": self.worker_id })),
205            )
206            .map_err(Err)?;
207        Self::lease_from(ok_or(status, body)?)
208    }
209
210    /// E28 renew (every ≤ 5 min).
211    pub fn renew(&self, epoch: u64) -> Answer<Lease> {
212        self.gate()?;
213        let (status, body) = self
214            .api
215            .answer(
216                "POST",
217                &format!("{}/lease/renew", self.base()),
218                Some(&json!({ "worker_id": self.worker_id, "epoch": epoch })),
219            )
220            .map_err(Err)?;
221        Self::lease_from(ok_or(status, body)?)
222    }
223
224    /// E28 release.
225    pub fn release(&self, epoch: u64) -> Answer<()> {
226        self.gate()?;
227        let (status, body) = self
228            .api
229            .answer(
230                "DELETE",
231                &format!(
232                    "{}/lease?epoch={epoch}&worker_id={}",
233                    self.base(),
234                    self.worker_id
235                ),
236                None,
237            )
238            .map_err(Err)?;
239        ok_or(status, body).map(|_| ())
240    }
241
242    /// The E29 body of `action` under the lease `epoch`.
243    pub fn action_body(&self, epoch: u64, action: &Action) -> Result<Value, HiveError> {
244        if let Action::Split { children, .. } = action
245            && !(1..=MAX_SPLIT_CHILDREN).contains(&children.len())
246        {
247            return Err(HiveError::Config(format!(
248                "a split has 1 to {MAX_SPLIT_CHILDREN} children"
249            )));
250        }
251        let mut body = serde_json::to_value(action).map_err(|e| HiveError::Local(e.to_string()))?;
252        body["worker_id"] = self.worker_id.into();
253        body["epoch"] = epoch.into();
254        Ok(body)
255    }
256
257    /// E29: one action; the answer carries the changed goal nodes and the
258    /// swarm log seqs it appended.
259    pub fn act(&self, epoch: u64, action: &Action) -> Answer<Value> {
260        self.gate()?;
261        let body = self.action_body(epoch, action).map_err(Err)?;
262        let (status, answer) = self
263            .api
264            .answer("POST", &format!("{}/actions", self.base()), Some(&body))
265            .map_err(Err)?;
266        ok_or(status, answer)
267    }
268}
269
270/// `lean-ctx hive swarm plan <swarm> --worker <wkr_…> lease | renew <epoch>
271/// | release <epoch> | act <epoch> --action '<json>'` (SPEC-ENGINE §3.18
272/// entry point, run by the person in a terminal). The role is read with
273/// E22 first; a worker the server does not list gets no conductor action.
274pub fn cli(
275    session: &crate::core::hive::auth::Session,
276    args: &[String],
277) -> Result<String, HiveError> {
278    let usage = || {
279        HiveError::Config(
280            "usage: lean-ctx hive swarm plan <swarm> --worker <wkr_…> lease | renew <epoch> | release <epoch> | act <epoch> --action '<json>'"
281                .into(),
282        )
283    };
284    let mut positional = Vec::new();
285    let (mut worker, mut action) = (None, None);
286    let mut it = args.iter();
287    while let Some(a) = it.next() {
288        match a.as_str() {
289            "--worker" => worker = it.next().cloned(),
290            "--action" => action = it.next().cloned(),
291            _ => positional.push(a.clone()),
292        }
293    }
294    let (Some(swarm), Some(worker)) = (positional.first(), worker) else {
295        return Err(usage());
296    };
297    let epoch = |i: usize| -> Result<u64, HiveError> {
298        positional
299            .get(i)
300            .and_then(|e| e.parse().ok())
301            .ok_or_else(usage)
302    };
303    let goal =
304        session.with_client(|c| c.get(&format!("/swarms/{swarm}/goal?worker_id={worker}")))?;
305    let c = Conductor {
306        api: session,
307        swarm_id: swarm,
308        worker_id: &worker,
309        eligible: eligible(&goal, &worker),
310    };
311    let flat = |r: Result<Refusal, HiveError>| match r {
312        Ok(refusal) => HiveError::from(refusal),
313        Err(e) => e,
314    };
315    match positional.get(1).map(String::as_str) {
316        Some("lease") => {
317            let l = c.acquire().map_err(flat)?;
318            Ok(format!(
319                "Conductor lease epoch {} until {} (renew within 5 min)",
320                l.epoch, l.expires_at
321            ))
322        }
323        Some("renew") => {
324            let l = c.renew(epoch(2)?).map_err(flat)?;
325            Ok(format!(
326                "Conductor lease epoch {} until {}",
327                l.epoch, l.expires_at
328            ))
329        }
330        Some("release") => {
331            c.release(epoch(2)?).map_err(flat)?;
332            Ok("Conductor lease released".into())
333        }
334        Some("act") => {
335            let action: Action = serde_json::from_str(action.as_deref().ok_or_else(usage)?)
336                .map_err(|e| HiveError::Config(format!("--action: {e}")))?;
337            let answer = c.act(epoch(2)?, &action).map_err(flat)?;
338            Ok(format!(
339                "Done: {} goal node(s) changed, swarm log seq(s) {}",
340                answer["nodes"].as_array().map_or(0, Vec::len),
341                answer["seqs"]
342            ))
343        }
344        _ => Err(usage()),
345    }
346}
347
348#[cfg(test)]
349#[path = "conductor_tests.rs"]
350mod tests;