Skip to main content

lean_ctx/core/hive/bus/
control.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Control frames from Hive (`hold`, `veto`, `stop`, `resume`) and the
3//! admission answers derived from them.
4//!
5//! The relay records every `control` frame in `<data>/hive/bus/control.json`
6//! ([`record`]); tool admission and the lease/handoff paths only read it
7//! ([`admission`], [`vetoed`]). Rules:
8//!
9//! - State is kept per target: an agent id, or `*` for every agent of this
10//!   instance. A frame whose `seq` is not newer than the target's last one is
11//!   ignored, so a replay after reconnect never undoes a later control.
12//! - `hold` and `stop` set the target's mode; `resume` without `target_ref`
13//!   clears it. `veto` refuses the lease or handoff named by `target_ref`;
14//!   `resume` with that `target_ref` lifts it.
15//! - An agent is refused when its own entry or `*` refuses it; `stop` wins
16//!   over `hold`. Resuming one agent does not lift a control on `*`.
17//! - The state belongs to the enrolled instance it arrived for: after
18//!   `hive disconnect --keep-local` or a new enrollment it no longer applies,
19//!   and while the lease is lapsed it is inactive (plan C rule 2: local work
20//!   never depends on Hive state). `hive status` names the reason.
21//!
22//! Bus controls are org coordination between cooperating agents, not a
23//! security boundary: whoever controls this machine can edit these files.
24//! Enforcement that must hold belongs to the runtime/policy path (org policy,
25//! role and policy guards). That is also why the lapse check reads the
26//! stored lease without re-verifying its signature: it can only switch
27//! controls off, never on.
28//!
29//! Network-free and deterministic; the file is read only when it exists.
30//!
31//! A damaged `control.json`, or one of a version this build does not know,
32//! is moved aside and never read as "no controls" (RB8 M12): until the relay
33//! has received Hive's replay of the active controls after its `hello`
34//! ([`rebuilt`]), every mutating tool, lease and handoff is refused with a
35//! "waiting for Hive" hold. Changes go through `control.json.lock` (M11).
36
37use std::collections::{BTreeMap, BTreeSet};
38use std::path::Path;
39
40use serde::{Deserialize, Serialize};
41
42use crate::core::hive::HiveError;
43use crate::core::hive::state::{HiveStore, load_or_quarantine, lock_state, write_private};
44use lean_ctx_protocol::UtcTimestamp;
45use lean_ctx_protocol::hive::bus::{BusFrameV1, ControlAction};
46use lean_ctx_protocol::hive::lease::LeaseState;
47
48const CONTROL_DIR: &str = "bus";
49const CONTROL_FILE: &str = "control.json";
50const CONTROL_VERSION: u32 = 1;
51/// Target of a control without `target_agent`.
52pub const ALL_AGENTS: &str = "*";
53
54/// One control as it arrived.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct ControlEntry {
57    pub action: ControlAction,
58    pub control_id: String,
59    pub reason: String,
60    pub issued_by: String,
61    pub seq: u64,
62    pub server_time: UtcTimestamp,
63}
64
65/// State of one target (an agent id or [`ALL_AGENTS`]).
66#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
67pub struct TargetControl {
68    /// The active `hold` or `stop`.
69    #[serde(default)]
70    pub mode: Option<ControlEntry>,
71    /// Active vetoes by lease or handoff id.
72    #[serde(default)]
73    pub vetoes: BTreeMap<String, ControlEntry>,
74    #[serde(default)]
75    pub last_seq: u64,
76}
77
78/// `control.json`.
79#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
80pub struct ControlState {
81    pub version: u32,
82    /// The instance the controls were issued for.
83    #[serde(default)]
84    pub instance_id: Option<String>,
85    #[serde(default)]
86    pub targets: BTreeMap<String, TargetControl>,
87    /// Since when the file was found damaged: refuse until the relay has
88    /// the replay (M12).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub rebuild_pending: Option<UtcTimestamp>,
91    /// While a rebuild is pending: the agents (agent id, project id) of the
92    /// hellos whose replay Hive has confirmed since. Hive replays a
93    /// project's controls only for the hello that first announces it, so
94    /// these agents run again while the others wait for theirs; the rebuild
95    /// ends once every announced project is confirmed.
96    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
97    pub rebuilt_for: BTreeSet<(String, String)>,
98}
99
100fn stamp_now() -> UtcTimestamp {
101    UtcTimestamp::new(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string())
102        .expect("a formatted UTC time is a valid timestamp")
103}
104
105/// What a pending rebuild refuses with.
106const REBUILD_REASON: &str =
107    "the local control state was damaged; waiting for Hive to resend the controls";
108
109/// Why a call is refused.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct Refusal {
112    /// `*` or the agent id the control names.
113    pub target: String,
114    pub entry: ControlEntry,
115}
116
117impl Refusal {
118    /// One line for the agent, without internal ids.
119    pub fn message(&self) -> String {
120        let who = if self.target == ALL_AGENTS {
121            "every agent on this machine".to_string()
122        } else {
123            format!("agent {}", self.target)
124        };
125        let what = match self.entry.action {
126            ControlAction::Stop => "stopped: end the current task",
127            ControlAction::Hold => "on hold until resumed",
128            ControlAction::Veto => "vetoed",
129            ControlAction::Resume => "resumed",
130        };
131        format!(
132            "Hive control: {who} is {what} (by {}: {}). Read-only tools still work.",
133            self.entry.issued_by, self.entry.reason
134        )
135    }
136}
137
138/// A control that is in force, for `hive status`.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct ActiveControl {
141    /// `None`: every agent of this instance.
142    pub target_agent: Option<String>,
143    pub action: ControlAction,
144    pub target_ref: Option<String>,
145    pub reason: String,
146    pub issued_by: String,
147    pub since: UtcTimestamp,
148}
149
150impl ControlState {
151    /// Read `<data>/bus/control.json` without changing anything (the tool
152    /// side): missing = empty; damaged, an unknown version or unreadable =
153    /// `Err` with the file's change time, which the caller treats as a
154    /// pending rebuild since then (M12).
155    fn read(data_dir: &Path) -> Result<Self, Option<UtcTimestamp>> {
156        let path = data_dir.join(CONTROL_DIR).join(CONTROL_FILE);
157        let changed = || {
158            let at: chrono::DateTime<chrono::Utc> =
159                std::fs::metadata(&path).ok()?.modified().ok()?.into();
160            UtcTimestamp::new(at.format("%Y-%m-%dT%H:%M:%SZ").to_string()).ok()
161        };
162        match std::fs::read(&path) {
163            Ok(bytes) => serde_json::from_slice::<Self>(&bytes)
164                .ok()
165                .filter(|state| state.version == CONTROL_VERSION)
166                .ok_or_else(changed),
167            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
168            Err(_) => Err(changed()),
169        }
170    }
171
172    /// Load `<data>/bus/control.json` for a change (under the lock):
173    /// missing = empty; a damaged file or an unknown version is moved aside
174    /// and an error (M12): see `load_for`.
175    pub fn load(data_dir: &Path) -> Result<Self, HiveError> {
176        load_or_quarantine(
177            &data_dir.join(CONTROL_DIR).join(CONTROL_FILE),
178            |state: &Self| state.version == CONTROL_VERSION,
179        )
180        .map(Option::unwrap_or_default)
181    }
182
183    pub fn save(&self, data_dir: &Path) -> Result<(), HiveError> {
184        let mut bytes =
185            serde_json::to_vec_pretty(self).map_err(|e| HiveError::Local(e.to_string()))?;
186        bytes.push(b'\n');
187        write_private(&data_dir.join(CONTROL_DIR), CONTROL_FILE, &bytes)
188    }
189
190    /// Apply one `control` frame for `instance_id`; `false` when it changed
191    /// nothing (not a control frame, or not newer than the target's last).
192    pub fn apply(&mut self, instance_id: Option<&str>, frame: &BusFrameV1) -> bool {
193        let BusFrameV1::Control {
194            control_id,
195            target_agent,
196            target_ref,
197            action,
198            reason,
199            issued_by,
200            seq,
201            server_time,
202        } = frame
203        else {
204            return false;
205        };
206        if self.instance_id.as_deref() != instance_id {
207            // Controls of an earlier enrollment do not carry over.
208            self.targets.clear();
209            self.instance_id = instance_id.map(str::to_string);
210        }
211        self.version = CONTROL_VERSION;
212        let target = self
213            .targets
214            .entry(target_agent.clone().unwrap_or_else(|| ALL_AGENTS.into()))
215            .or_default();
216        if *seq <= target.last_seq {
217            return false;
218        }
219        target.last_seq = *seq;
220        let entry = ControlEntry {
221            action: *action,
222            control_id: control_id.clone(),
223            reason: reason.clone(),
224            issued_by: issued_by.clone(),
225            seq: *seq,
226            server_time: server_time.clone(),
227        };
228        match (action, target_ref) {
229            (ControlAction::Hold | ControlAction::Stop, _) => target.mode = Some(entry),
230            (ControlAction::Veto, Some(reference)) => {
231                target.vetoes.insert(reference.clone(), entry);
232            }
233            // A veto must name what it refuses; without one there is nothing to apply.
234            (ControlAction::Veto, None) => {}
235            (ControlAction::Resume, Some(reference)) => {
236                target.vetoes.remove(reference);
237            }
238            (ControlAction::Resume, None) => target.mode = None,
239        }
240        true
241    }
242
243    /// The targets that apply to `agent_id`: `*`, then the agent itself.
244    fn targets_for<'a>(
245        &'a self,
246        agent_id: Option<&'a str>,
247    ) -> impl Iterator<Item = (&'a str, &'a TargetControl)> {
248        std::iter::once(ALL_AGENTS)
249            .chain(agent_id.filter(|id| *id != ALL_AGENTS))
250            .filter_map(|name| self.targets.get(name).map(|t| (name, t)))
251    }
252
253    /// The hold of a pending rebuild, for every agent.
254    fn pending(&self) -> Option<Refusal> {
255        self.rebuild_pending.clone().map(|since| Refusal {
256            target: ALL_AGENTS.into(),
257            entry: ControlEntry {
258                action: ControlAction::Hold,
259                control_id: "local".into(),
260                reason: REBUILD_REASON.into(),
261                issued_by: "lean-ctx".into(),
262                seq: 0,
263                server_time: since,
264            },
265        })
266    }
267
268    /// The pending rebuild's hold for `agent_id`, unless its replay is
269    /// confirmed already.
270    fn pending_for(&self, agent_id: Option<&str>) -> Option<Refusal> {
271        if agent_id.is_some_and(|id| self.rebuilt_for.iter().any(|(agent, _)| agent == id)) {
272            return None;
273        }
274        self.pending()
275    }
276
277    /// Whether `agent_id` (`None`: an unknown caller, bound by `*` only) may
278    /// run a mutating tool. `stop` wins over `hold`; a pending rebuild
279    /// refuses unless a stop already does.
280    pub fn admission(&self, agent_id: Option<&str>) -> Option<Refusal> {
281        self.targets_for(agent_id)
282            .filter_map(|(name, target)| {
283                target.mode.as_ref().map(|entry| Refusal {
284                    target: name.to_string(),
285                    entry: entry.clone(),
286                })
287            })
288            .chain(self.pending_for(agent_id))
289            .max_by_key(|refusal| {
290                (
291                    refusal.entry.action == ControlAction::Stop,
292                    refusal.entry.seq,
293                )
294            })
295    }
296
297    /// Whether the lease or handoff `target_ref` is vetoed for `agent_id`.
298    pub fn vetoed(&self, agent_id: Option<&str>, target_ref: &str) -> Option<Refusal> {
299        self.targets_for(agent_id)
300            .filter_map(|(name, target)| {
301                target.vetoes.get(target_ref).map(|entry| Refusal {
302                    target: name.to_string(),
303                    entry: entry.clone(),
304                })
305            })
306            .max_by_key(|refusal| refusal.entry.seq)
307            .or_else(|| self.pending_for(agent_id))
308    }
309
310    /// Every control in force, `*` first, then by agent and `target_ref`.
311    pub fn active(&self) -> Vec<ActiveControl> {
312        let mut out: Vec<ActiveControl> = self
313            .pending()
314            .map(|p| ActiveControl {
315                target_agent: None,
316                action: p.entry.action,
317                target_ref: None,
318                reason: p.entry.reason,
319                issued_by: p.entry.issued_by,
320                since: p.entry.server_time,
321            })
322            .into_iter()
323            .collect();
324        for (name, target) in &self.targets {
325            let target_agent = (name != ALL_AGENTS).then(|| name.clone());
326            let view = |entry: &ControlEntry, target_ref: Option<&String>| ActiveControl {
327                target_agent: target_agent.clone(),
328                action: entry.action,
329                target_ref: target_ref.cloned(),
330                reason: entry.reason.clone(),
331                issued_by: entry.issued_by.clone(),
332                since: entry.server_time.clone(),
333            };
334            if let Some(entry) = &target.mode {
335                out.push(view(entry, None));
336            }
337            for (reference, entry) in &target.vetoes {
338                out.push(view(entry, Some(reference)));
339            }
340        }
341        out
342    }
343}
344
345/// The controls on disk for the enrolled instance. A damaged file becomes
346/// a saved pending rebuild for that instance (M12), so the refusal survives
347/// the next read instead of reading as "no controls".
348fn load_for(store: &HiveStore) -> Result<ControlState, HiveError> {
349    match ControlState::load(store.data_dir()) {
350        Ok(state) => Ok(state),
351        Err(damaged) => {
352            tracing::warn!("hive bus controls: {damaged}");
353            let state = ControlState {
354                version: CONTROL_VERSION,
355                instance_id: store.instance()?.map(|i| i.instance_id),
356                targets: BTreeMap::new(),
357                rebuild_pending: Some(stamp_now()),
358                rebuilt_for: BTreeSet::new(),
359            };
360            state.save(store.data_dir())?;
361            Ok(state)
362        }
363    }
364}
365
366/// Load, change and save the controls under their lock (M11).
367fn mutate<T>(
368    store: &HiveStore,
369    change: impl FnOnce(&mut ControlState) -> (bool, T),
370) -> Result<T, HiveError> {
371    let _lock = lock_state(&store.data_dir().join(CONTROL_DIR), CONTROL_FILE)?;
372    let mut state = load_for(store)?;
373    let (changed, out) = change(&mut state);
374    if changed {
375        state.save(store.data_dir())?;
376    }
377    Ok(out)
378}
379
380/// The relay's write path: apply `frame` and persist when it changed.
381pub fn record(store: &HiveStore, frame: &BusFrameV1) -> Result<bool, HiveError> {
382    let instance = store.instance()?.map(|i| i.instance_id);
383    mutate(store, |state| {
384        let changed = state.apply(instance.as_deref(), frame);
385        (changed, changed)
386    })
387}
388
389/// Hive confirmed (pong to the barrier ping behind a `hello`) that it sent
390/// the replay of the active controls for the agents that hello announced
391/// (`confirmed`: agent id, project id). Those agents run again; a pending
392/// rebuild (M12) ends once every project the socket announces (`projects`)
393/// is confirmed. Only those: a project without a local agent is never
394/// announced and would hold callers without an agent id for good. `true`
395/// when it ended.
396pub fn rebuilt(
397    store: &HiveStore,
398    confirmed: &BTreeSet<(String, String)>,
399    projects: &BTreeSet<String>,
400) -> Result<bool, HiveError> {
401    mutate(store, |state| {
402        if state.rebuild_pending.is_none() {
403            return (false, false);
404        }
405        let before = state.rebuilt_for.len();
406        state.rebuilt_for.extend(confirmed.iter().cloned());
407        let covered: BTreeSet<&str> = state.rebuilt_for.iter().map(|(_, p)| p.as_str()).collect();
408        if !projects.iter().all(|p| covered.contains(p.as_str())) {
409            return (state.rebuilt_for.len() != before, false);
410        }
411        state.rebuild_pending = None;
412        state.rebuilt_for.clear();
413        (true, true)
414    })
415}
416
417/// Why recorded controls do not apply.
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub enum Inactive {
420    /// Disconnected, or enrolled anew since they arrived.
421    NotEnrolled,
422    /// The lease is lapsed (or missing/damaged): rule 2.
423    LeaseLapsed,
424}
425
426impl Inactive {
427    /// The `hive status` line.
428    pub fn status_line(self) -> &'static str {
429        match self {
430            Self::NotEnrolled => "controls inactive: not enrolled",
431            Self::LeaseLapsed => "controls inactive: lease lapsed",
432        }
433    }
434}
435
436/// Whether the stored lease is lapsed at `local_now` (service clock via the
437/// stored offset). Not signature-verified on purpose; see the module docs.
438fn lease_lapsed(store: &HiveStore, local_now: chrono::DateTime<chrono::Utc>) -> bool {
439    let record = store
440        .read_config::<crate::core::hive::state::LeaseRecord>(crate::core::hive::state::LEASE_FILE)
441        .ok()
442        .flatten();
443    let Some(record) = record else {
444        return true;
445    };
446    let lease = serde_json::from_value::<lean_ctx_protocol::hive::lease::HiveLeaseEnvelopeV1>(
447        record.envelope,
448    )
449    .ok()
450    .and_then(|envelope| {
451        serde_json::from_value::<lean_ctx_protocol::hive::lease::HiveLeaseV1>(envelope.lease).ok()
452    });
453    let Some(lease) = lease else {
454        return true;
455    };
456    let service = (local_now + chrono::Duration::seconds(record.offset_seconds)).fixed_offset();
457    !matches!(
458        lease.state_at(service),
459        Ok(LeaseState::Valid | LeaseState::Grace)
460    )
461}
462
463/// The controls recorded for this machine and whether they apply at
464/// `local_now`. Empty and active when nothing was recorded.
465pub fn current_at(
466    store: &HiveStore,
467    local_now: chrono::DateTime<chrono::Utc>,
468) -> (ControlState, Option<Inactive>) {
469    if !store
470        .data_dir()
471        .join(CONTROL_DIR)
472        .join(CONTROL_FILE)
473        .exists()
474    {
475        return (ControlState::default(), None);
476    }
477    // Damaged, unknown or unreadable: refuse rather than allow. Only the
478    // relay's next change moves the file aside (under the lock).
479    let state = ControlState::read(store.data_dir()).unwrap_or_else(|since| ControlState {
480        version: CONTROL_VERSION,
481        instance_id: store.instance().ok().flatten().map(|i| i.instance_id),
482        targets: BTreeMap::new(),
483        rebuild_pending: Some(since.unwrap_or_else(stamp_now)),
484        rebuilt_for: BTreeSet::new(),
485    });
486    if state.targets.is_empty() && state.rebuild_pending.is_none() {
487        return (state, None);
488    }
489    let enrolled = store.instance().ok().flatten().map(|i| i.instance_id);
490    if state.instance_id.is_none() || state.instance_id != enrolled {
491        return (state, Some(Inactive::NotEnrolled));
492    }
493    if lease_lapsed(store, local_now) {
494        return (state, Some(Inactive::LeaseLapsed));
495    }
496    (state, None)
497}
498
499/// The state in force now; empty when it does not apply.
500pub fn current(store: &HiveStore) -> ControlState {
501    match current_at(store, chrono::Utc::now()) {
502        (state, None) => state,
503        (_, Some(_)) => ControlState::default(),
504    }
505}
506
507/// Admission for a mutating tool of `agent_id` on this machine.
508pub fn admission(store: &HiveStore, agent_id: Option<&str>) -> Option<Refusal> {
509    current(store).admission(agent_id)
510}
511
512/// Veto check for acquiring/renewing a lease or accepting a handoff.
513pub fn vetoed(store: &HiveStore, agent_id: Option<&str>, target_ref: &str) -> Option<Refusal> {
514    current(store).vetoed(agent_id, target_ref)
515}
516
517/// Controls in force, for `hive status`.
518pub fn active(store: &HiveStore) -> Vec<ActiveControl> {
519    current(store).active()
520}
521
522/// For `hive status`: the controls in force, or why recorded ones are not
523/// (`None` when there is nothing to say).
524pub fn status_at(
525    store: &HiveStore,
526    local_now: chrono::DateTime<chrono::Utc>,
527) -> (Vec<ActiveControl>, Option<Inactive>) {
528    match current_at(store, local_now) {
529        (state, None) => (state.active(), None),
530        (state, Some(reason)) => (Vec::new(), (!state.active().is_empty()).then_some(reason)),
531    }
532}
533
534impl From<Inactive> for lean_ctx_protocol::hive::status::HiveBusControlsInactiveV1 {
535    fn from(reason: Inactive) -> Self {
536        match reason {
537            Inactive::NotEnrolled => Self::NotEnrolled,
538            Inactive::LeaseLapsed => Self::LeaseLapsed,
539        }
540    }
541}
542
543impl From<ActiveControl> for lean_ctx_protocol::hive::status::HiveStatusBusControlV1 {
544    fn from(c: ActiveControl) -> Self {
545        use lean_ctx_protocol::hive::status::HiveBusControlActionV1 as Action;
546        Self {
547            target_agent: c.target_agent,
548            action: match c.action {
549                ControlAction::Hold => Action::Hold,
550                ControlAction::Stop => Action::Stop,
551                ControlAction::Veto => Action::Veto,
552                // Never kept as active; mapped for completeness.
553                ControlAction::Resume => Action::Unknown,
554            },
555            target_ref: c.target_ref,
556            reason: c.reason,
557            issued_by: c.issued_by,
558            since: c.since,
559        }
560    }
561}
562
563/// `hive status --json`: the controls in force, or why recorded ones are not.
564pub fn status_view(
565    store: &HiveStore,
566    local_now: chrono::DateTime<chrono::Utc>,
567) -> (
568    Vec<lean_ctx_protocol::hive::status::HiveStatusBusControlV1>,
569    Option<lean_ctx_protocol::hive::status::HiveBusControlsInactiveV1>,
570) {
571    let (active, inactive) = status_at(store, local_now);
572    (
573        active.into_iter().map(Into::into).collect(),
574        inactive.map(Into::into),
575    )
576}
577
578/// Tools that stay available under `hold` and `stop`: the read-only ones,
579/// the bus itself (to read the control and report back) and the session
580/// record (to save progress before ending).
581fn exempt(tool: &str) -> bool {
582    crate::tool_defs::READONLY_TOOL_NAMES.contains(&tool)
583        || matches!(tool, "ctx_agent" | "ctx_session")
584}
585
586/// The admission hook of the tool pipeline: `Some(message)` refuses `tool`
587/// for `agent_id`. Missing or unreadable local state never refuses.
588pub fn tool_refusal(agent_id: Option<&str>, tool: &str) -> Option<String> {
589    if exempt(tool) {
590        return None;
591    }
592    let store = HiveStore::open().ok()?;
593    admission(&store, agent_id).map(|refusal| refusal.message())
594}
595
596/// The veto hook of lease acquisition/renewal and handoffs: refused when
597/// any of `refs` (lease ref, resource ref, handoff id) is vetoed.
598pub fn veto_refusal(agent_id: Option<&str>, refs: &[&str]) -> Option<String> {
599    let store = HiveStore::open().ok()?;
600    let state = current(&store);
601    refs.iter()
602        .find_map(|reference| state.vetoed(agent_id, reference))
603        .map(|refusal| refusal.message())
604        // C0 2.0: a verified veto control on the lock or handoff (V9.5).
605        .or_else(|| {
606            refs.iter()
607                .find_map(|reference| super::veto::vetoed_v2(&store, reference))
608        })
609}
610
611/// Test enrollment: the protocol fixture's instance and lease, with the
612/// stored clock offset placing "now" `hours_after_issue` after it was issued
613/// (24 h: valid until; 168 h: grace until; later: lapsed).
614#[cfg(test)]
615pub(crate) fn enroll_for_tests(store: &HiveStore, hours_after_issue: i64) -> String {
616    use crate::core::hive::state::{INSTANCE_FILE, InstanceRecord, LEASE_FILE, LeaseRecord};
617    let envelope: serde_json::Value = serde_json::from_str(include_str!(
618        "../../../../crates/lean-ctx-protocol/tests/fixtures/hive/lease_envelope.response.json"
619    ))
620    .unwrap();
621    let lease = &envelope["lease"];
622    let instance_id = lease["instance_id"].as_str().unwrap().to_string();
623    let issued = chrono::DateTime::parse_from_rfc3339(lease["issued_at"].as_str().unwrap())
624        .unwrap()
625        .with_timezone(&chrono::Utc);
626    let offset = (issued + chrono::Duration::hours(hours_after_issue)) - chrono::Utc::now();
627    store
628        .write_config(
629            INSTANCE_FILE,
630            &InstanceRecord {
631                instance_id: instance_id.clone(),
632                org_id: lease["org_id"].as_str().unwrap().into(),
633                org_name: "Acme AG".into(),
634                label: "test-box".into(),
635                url: "https://hive.example".into(),
636                org_salt_id: "salt".into(),
637                enrolled_at: "2026-10-20T12:00:00Z".into(),
638                web_url: None,
639                org_kind: None,
640                company_name: None,
641            },
642        )
643        .unwrap();
644    store
645        .write_config(
646            LEASE_FILE,
647            &LeaseRecord {
648                envelope: envelope.clone(),
649                offset_seconds: offset.num_seconds(),
650                received_at: "2026-10-20T12:00:00Z".into(),
651            },
652        )
653        .unwrap();
654    instance_id
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660
661    #[test]
662    fn a_lapsed_lease_voids_controls_and_status_says_so() {
663        let dir = tempfile::tempdir().unwrap();
664        let store = HiveStore::at(dir.path().join("c"), dir.path().join("d"));
665        enroll_for_tests(&store, 1);
666        assert!(record(&store, &frame(1, None, ControlAction::Stop, None)).unwrap());
667        assert_eq!(
668            admission(&store, Some("a")).unwrap().entry.action,
669            ControlAction::Stop
670        );
671        // Grace still counts as connected.
672        enroll_for_tests(&store, 30);
673        assert!(admission(&store, Some("a")).is_some());
674        let (active_now, inactive) = status_at(&store, chrono::Utc::now());
675        assert_eq!((active_now.len(), inactive), (1, None));
676        // Past grace_until: lapsed, controls off, status names the reason.
677        enroll_for_tests(&store, 24 * 8);
678        assert!(admission(&store, Some("a")).is_none());
679        let (active_now, inactive) = status_at(&store, chrono::Utc::now());
680        assert!(active_now.is_empty());
681        assert_eq!(inactive, Some(Inactive::LeaseLapsed));
682        assert_eq!(
683            inactive.unwrap().status_line(),
684            "controls inactive: lease lapsed"
685        );
686        // A missing lease counts as lapsed.
687        std::fs::remove_file(dir.path().join("c/lease.json")).unwrap();
688        assert!(admission(&store, Some("a")).is_none());
689    }
690
691    #[test]
692    fn damaged_or_newer_controls_hold_every_agent_until_hive_replays() {
693        let dir = tempfile::tempdir().unwrap();
694        let store = HiveStore::at(dir.path().join("c"), dir.path().join("d"));
695        enroll_for_tests(&store, 1);
696        assert!(record(&store, &frame(1, None, ControlAction::Stop, None)).unwrap());
697        let path = dir.path().join("d/bus/control.json");
698        for broken in [&b"{ not json"[..], br#"{"version": 2, "targets": {}}"#] {
699            std::fs::write(&path, broken).unwrap();
700            // Never "no controls": a hold for every agent, also on leases.
701            let refusal = admission(&store, Some("a")).expect("fails closed");
702            assert_eq!(refusal.entry.reason, REBUILD_REASON);
703            assert!(admission(&store, None).is_some());
704            assert!(vetoed(&store, Some("a"), "lease_1").is_some());
705            let (shown, inactive) = status_at(&store, chrono::Utc::now());
706            assert_eq!((shown.len(), inactive), (1, None), "status names it");
707            // The replay after a hello re-applies what is in force; Hive's
708            // pong to the barrier behind it frees the agents that hello
709            // announced, and the rebuild ends once every project is covered.
710            assert!(record(&store, &frame(9, Some("b"), ControlAction::Hold, None)).unwrap());
711            assert!(admission(&store, Some("a")).is_some(), "still pending");
712            let pair = |agent: &str, project: &str| (agent.to_string(), project.to_string());
713            let projects = BTreeSet::from(["p1".to_string(), "p2".to_string()]);
714            let first = BTreeSet::from([pair("a", "p1")]);
715            assert!(!rebuilt(&store, &first, &projects).unwrap(), "p2 not yet");
716            assert!(
717                admission(&store, Some("a")).is_none(),
718                "a's replay is confirmed"
719            );
720            assert!(vetoed(&store, Some("a"), "lease_1").is_none());
721            assert!(admission(&store, Some("c")).is_some(), "c's project is not");
722            assert!(admission(&store, None).is_some());
723            // A later hello (an agent of the other project) completes it.
724            let later = BTreeSet::from([pair("c", "p2")]);
725            assert!(rebuilt(&store, &later, &projects).unwrap());
726            assert!(!rebuilt(&store, &later, &projects).unwrap(), "once");
727            assert!(admission(&store, Some("c")).is_none());
728            assert!(admission(&store, None).is_none());
729            assert!(admission(&store, Some("b")).is_some(), "the replayed hold");
730        }
731        // Both damaged copies are kept beside it.
732        assert!(dir.path().join("d/bus/control.json.damaged-1").exists());
733        assert!(dir.path().join("d/bus/control.json.damaged-2").exists());
734    }
735
736    fn frame(
737        seq: u64,
738        target_agent: Option<&str>,
739        action: ControlAction,
740        target_ref: Option<&str>,
741    ) -> BusFrameV1 {
742        BusFrameV1::Control {
743            control_id: format!("ctl_{seq}"),
744            target_agent: target_agent.map(str::to_string),
745            target_ref: target_ref.map(str::to_string),
746            action,
747            reason: "Owner review.".into(),
748            issued_by: "admin@acme".into(),
749            seq,
750            server_time: UtcTimestamp::new("2026-10-21T12:00:00Z").unwrap(),
751        }
752    }
753
754    const I: Option<&str> = Some("inst_1");
755
756    #[test]
757    fn hold_and_stop_refuse_until_resume_and_stop_wins() {
758        let mut state = ControlState::default();
759        assert!(state.apply(I, &frame(1, Some("claude-a"), ControlAction::Hold, None)));
760        assert_eq!(
761            state.admission(Some("claude-a")).unwrap().entry.action,
762            ControlAction::Hold
763        );
764        assert!(state.admission(Some("claude-b")).is_none());
765        assert!(state.admission(None).is_none());
766        assert!(state.apply(I, &frame(2, None, ControlAction::Stop, None)));
767        let refusal = state.admission(Some("claude-a")).unwrap();
768        assert_eq!(refusal.entry.action, ControlAction::Stop, "stop beats hold");
769        assert_eq!(refusal.target, ALL_AGENTS);
770        assert!(
771            state.admission(None).is_some(),
772            "unknown callers are bound by *"
773        );
774        // Resuming one agent leaves the control on every agent in force.
775        assert!(state.apply(I, &frame(3, Some("claude-a"), ControlAction::Resume, None)));
776        assert_eq!(
777            state.admission(Some("claude-a")).unwrap().target,
778            ALL_AGENTS
779        );
780        assert!(state.apply(I, &frame(4, None, ControlAction::Resume, None)));
781        assert!(state.admission(Some("claude-a")).is_none());
782    }
783
784    #[test]
785    fn replayed_or_older_frames_never_undo_a_newer_control() {
786        let mut state = ControlState::default();
787        assert!(state.apply(I, &frame(10, None, ControlAction::Resume, None)));
788        assert!(state.apply(I, &frame(11, None, ControlAction::Hold, None)));
789        // Redelivered after reconnect: the earlier resume and the hold itself.
790        assert!(!state.apply(I, &frame(10, None, ControlAction::Resume, None)));
791        assert!(!state.apply(I, &frame(11, None, ControlAction::Hold, None)));
792        assert!(state.admission(Some("x")).is_some());
793    }
794
795    #[test]
796    fn a_veto_names_one_lease_and_does_not_replace_a_hold() {
797        let mut state = ControlState::default();
798        state.apply(I, &frame(1, None, ControlAction::Hold, None));
799        state.apply(I, &frame(2, None, ControlAction::Veto, Some("lease_7")));
800        assert!(
801            state.admission(Some("a")).is_some(),
802            "hold survives the veto"
803        );
804        assert!(state.vetoed(Some("a"), "lease_7").is_some());
805        assert!(state.vetoed(Some("a"), "lease_8").is_none());
806        // A veto without a target_ref refuses nothing.
807        state.apply(I, &frame(3, Some("a"), ControlAction::Veto, None));
808        assert!(state.vetoed(Some("a"), "").is_none());
809        state.apply(I, &frame(4, None, ControlAction::Resume, Some("lease_7")));
810        assert!(state.vetoed(Some("a"), "lease_7").is_none());
811        assert!(
812            state.admission(Some("a")).is_some(),
813            "resume of a veto keeps the hold"
814        );
815    }
816
817    #[test]
818    fn active_lists_modes_and_vetoes_for_status() {
819        let mut state = ControlState::default();
820        state.apply(I, &frame(1, Some("codex-9"), ControlAction::Stop, None));
821        state.apply(I, &frame(2, None, ControlAction::Veto, Some("handoff_1")));
822        let active = state.active();
823        assert_eq!(active.len(), 2);
824        assert_eq!(active[0].target_agent, None);
825        assert_eq!(active[0].target_ref.as_deref(), Some("handoff_1"));
826        assert_eq!(active[1].target_agent.as_deref(), Some("codex-9"));
827        assert_eq!(active[1].action, ControlAction::Stop);
828        assert_eq!(active[1].since.as_str(), "2026-10-21T12:00:00Z");
829    }
830
831    #[test]
832    fn controls_belong_to_the_enrollment_and_persist_privately() {
833        let dir = tempfile::tempdir().unwrap();
834        let store = HiveStore::at(dir.path().join("c"), dir.path().join("d"));
835        // Not enrolled: recorded for no instance, and nothing applies.
836        assert!(record(&store, &frame(1, None, ControlAction::Stop, None)).unwrap());
837        assert!(admission(&store, Some("a")).is_none());
838        assert!(active(&store).is_empty());
839        assert_eq!(
840            status_at(&store, chrono::Utc::now()),
841            (Vec::new(), Some(Inactive::NotEnrolled))
842        );
843        let path = dir.path().join("d/bus/control.json");
844        #[cfg(unix)]
845        {
846            use std::os::unix::fs::PermissionsExt as _;
847            let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
848            assert_eq!(mode, 0o600);
849        }
850        // The flat pre-v1 shape (latest frame per target) is no state of
851        // this build: moved aside, never read as "no controls" (RB8 M12).
852        std::fs::write(&path, br#"{"*":{"t":"control","action":"stop"}}"#).unwrap();
853        assert!(ControlState::load(&dir.path().join("d")).is_err());
854        assert!(dir.path().join("d/bus/control.json.damaged-1").exists());
855        // A different instance's state resets on the next frame.
856        let mut state = ControlState::default();
857        state.apply(Some("inst_old"), &frame(5, None, ControlAction::Stop, None));
858        state.apply(
859            Some("inst_new"),
860            &frame(1, Some("a"), ControlAction::Hold, None),
861        );
862        assert_eq!(state.instance_id.as_deref(), Some("inst_new"));
863        assert_eq!(
864            state.admission(Some("a")).unwrap().entry.action,
865            ControlAction::Hold
866        );
867        assert!(state.admission(Some("b")).is_none());
868    }
869
870    #[test]
871    fn read_only_tools_the_bus_and_the_session_stay_available() {
872        assert!(exempt("ctx_read") && exempt("ctx_search") && exempt("ctx_agent"));
873        assert!(exempt("ctx_session"));
874        assert!(!exempt("ctx_edit") && !exempt("ctx_shell") && !exempt("ctx_patch"));
875    }
876
877    #[test]
878    fn the_refusal_message_names_the_issuer_and_reason_but_no_ids() {
879        let mut state = ControlState::default();
880        state.apply(I, &frame(1, None, ControlAction::Stop, None));
881        let message = state.admission(Some("a")).unwrap().message();
882        assert!(message.contains("stopped"), "{message}");
883        assert!(message.contains("admin@acme") && message.contains("Owner review."));
884        assert!(!message.contains("ctl_1"));
885    }
886}