Skip to main content

lean_ctx_cloud/bus/
control.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bus controls from Cloud (`hold`, `stop`, `veto`, `resume`) and the
3//! admission answers derived from them.
4//!
5//! The relay keeps the controls whose signature verifies against a Cloud
6//! key of purpose `control` in `state_v2.json` ([`StateV2`]); tool
7//! admission, the lease and handoff paths and `cloud status` only read
8//! them. Rules:
9//!
10//! - `hold` and `stop` pause an agent: a worker control the agents
11//!   attached to that worker, a bus control every agent here (a tool call
12//!   names no vault). `stop` wins over `hold`; `resume` ends both.
13//! - `veto` refuses the lease or handoff its `ref` names ([`super::veto`]).
14//! - A control only pauses Cloud traffic: Cloud tools (`ctx_tasks`), bus
15//!   messages, the Cloud side of a lease and a handoff through Cloud. Local
16//!   tools, local leases and handoffs on this machine are never refused
17//!   (connector rule "local work is never gated"), online or offline.
18//! - Controls apply only while this machine is enrolled and its lease is
19//!   valid (plan C rule 2: local work never depends on Cloud state);
20//!   `cloud status` names the reason when they do not.
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//! A damaged `state_v2.json`, or one of a version this build does not know,
30//! is never read as "no controls" (RB8 M12): until Cloud's replay of the
31//! controls in force after the relay's next hello is complete, Cloud traffic waits under
32//! a "waiting for Cloud" hold; local work goes on.
33//!
34//! Network-free and deterministic.
35
36use super::relay_v2::StateV2;
37use super::v2::{Control, ControlAction, ControlTarget};
38use crate::state::CloudStore;
39use lean_ctx_protocol::UtcTimestamp;
40use lean_ctx_protocol::cloud::lease::LeaseState;
41
42/// Target of a control on every agent of this machine.
43pub const ALL_AGENTS: &str = "*";
44
45/// Why a call is refused.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Refusal {
48    /// `*` or the agent id the control holds.
49    pub target: String,
50    pub action: ControlAction,
51    pub reason: String,
52    pub issued_by: String,
53}
54
55impl Refusal {
56    /// One line for the agent, without internal ids.
57    pub fn message(&self) -> String {
58        let who = if self.target == ALL_AGENTS {
59            "every agent on this machine".to_string()
60        } else {
61            format!("agent {}", self.target)
62        };
63        let what = match self.action {
64            ControlAction::Stop => "stopped: end the current task",
65            ControlAction::Hold => "on hold until resumed",
66            ControlAction::Veto => "vetoed",
67            ControlAction::Resume => "resumed",
68        };
69        format!(
70            "LeanCTX Cloud control: {who} is {what} (by {}: {}). LeanCTX Cloud traffic waits; local tools keep working.",
71            self.issued_by, self.reason
72        )
73    }
74}
75
76/// A control that is in force, for `cloud status`.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ActiveControl {
79    /// The worker it holds (`wkr_…`); `None`: every agent of this machine.
80    pub target_agent: Option<String>,
81    pub action: ControlAction,
82    pub target_ref: Option<String>,
83    pub reason: String,
84    pub issued_by: String,
85    pub since: UtcTimestamp,
86}
87
88/// Why the controls kept here do not apply.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum Inactive {
91    /// This machine is not enrolled (disconnected).
92    NotEnrolled,
93    /// The lease is lapsed (or missing/damaged): rule 2.
94    LeaseLapsed,
95}
96
97impl Inactive {
98    /// The `cloud status` line.
99    pub fn status_line(self) -> &'static str {
100        match self {
101            Self::NotEnrolled => "controls inactive: not enrolled",
102            Self::LeaseLapsed => "controls inactive: lease lapsed",
103        }
104    }
105}
106
107/// Whether the stored lease is lapsed at `local_now` (service clock via the
108/// stored offset). Not signature-verified on purpose; see the module docs.
109fn lease_lapsed(store: &CloudStore, local_now: lean_ctx_time::UtcDateTime) -> bool {
110    let record = store
111        .read_config::<crate::state::LeaseRecord>(crate::state::LEASE_FILE)
112        .ok()
113        .flatten();
114    let Some(record) = record else {
115        return true;
116    };
117    let lease = serde_json::from_value::<lean_ctx_protocol::cloud::lease::CloudLeaseEnvelopeV1>(
118        record.envelope,
119    )
120    .ok()
121    .and_then(|envelope| {
122        serde_json::from_value::<lean_ctx_protocol::cloud::lease::CloudLeaseV1>(envelope.lease).ok()
123    });
124    let Some(lease) = lease else {
125        return true;
126    };
127    let service =
128        (local_now + lean_ctx_time::Duration::seconds(record.offset_seconds)).fixed_offset();
129    !matches!(
130        lease.state_at(service),
131        Ok(LeaseState::Valid | LeaseState::Grace)
132    )
133}
134
135/// What the refusals of a pending rebuild say (M12).
136const REBUILD_REASON: &str =
137    "the local control state was damaged; waiting for LeanCTX Cloud to resend the controls";
138/// Who a pending rebuild's hold is from.
139const REBUILD_ISSUER: &str = "lean-ctx";
140
141/// The controls kept for this machine (a `resume` is never kept, oldest
142/// first) and, while `state_v2.json` was found damaged or of an unknown
143/// version and Cloud has not answered a hello since, since when (M12).
144#[derive(Debug, Clone, Default, PartialEq, Eq)]
145pub struct Kept {
146    pub controls: Vec<Control>,
147    pub rebuild_since: Option<u64>,
148}
149
150impl Kept {
151    fn is_empty(&self) -> bool {
152        self.controls.is_empty() && self.rebuild_since.is_none()
153    }
154
155    /// The hold of a pending rebuild, for every agent.
156    fn pending(&self) -> Option<Refusal> {
157        self.rebuild_since.map(|_| Refusal {
158            target: ALL_AGENTS.into(),
159            action: ControlAction::Hold,
160            reason: REBUILD_REASON.into(),
161            issued_by: REBUILD_ISSUER.into(),
162        })
163    }
164}
165
166/// The controls kept for this machine and whether they apply at
167/// `local_now`. Empty and active when there are none. A damaged or unknown
168/// file is read, without changing it, as a pending rebuild: never as "no
169/// controls".
170pub fn current_at(
171    store: &CloudStore,
172    local_now: lean_ctx_time::UtcDateTime,
173) -> (Kept, Option<Inactive>) {
174    let state = StateV2::read(store.data_dir()).unwrap_or_else(|since| StateV2 {
175        rebuild_pending: Some(since),
176        ..StateV2::default()
177    });
178    let mut controls: Vec<Control> = state
179        .controls
180        .into_values()
181        .filter(|c| c.action != ControlAction::Resume)
182        .collect();
183    controls.sort_by_key(|c| c.created_at);
184    let kept = Kept {
185        controls,
186        rebuild_since: state.rebuild_pending,
187    };
188    if kept.is_empty() {
189        return (kept, None);
190    }
191    if !matches!(store.instance(), Ok(Some(_))) {
192        return (kept, Some(Inactive::NotEnrolled));
193    }
194    if lease_lapsed(store, local_now) {
195        return (kept, Some(Inactive::LeaseLapsed));
196    }
197    (kept, None)
198}
199
200/// What is in force at `local_now`; nothing when it does not apply.
201fn in_force(store: &CloudStore, local_now: lean_ctx_time::UtcDateTime) -> Kept {
202    match current_at(store, local_now) {
203        (kept, None) => kept,
204        (_, Some(_)) => Kept::default(),
205    }
206}
207
208/// Admission for a mutating tool of `agent_id` on this machine: a hold or
209/// stop on its worker or on a whole vault bus, or the hold of a pending
210/// rebuild. The tool call names no vault, so a bus control of any vault
211/// linked here holds the Cloud traffic of every agent; a stop wins over a
212/// hold.
213pub fn admission(store: &CloudStore, agent_id: Option<&str>) -> Option<Refusal> {
214    admission_at(store, agent_id, lean_ctx_time::UtcDateTime::now())
215}
216
217fn admission_at(
218    store: &CloudStore,
219    agent_id: Option<&str>,
220    local_now: lean_ctx_time::UtcDateTime,
221) -> Option<Refusal> {
222    let kept = in_force(store, local_now);
223    let controlled = held(store, agent_id, &kept.controls);
224    if controlled
225        .as_ref()
226        .is_some_and(|r| r.action == ControlAction::Stop)
227    {
228        return controlled;
229    }
230    kept.pending().or(controlled)
231}
232
233/// The hold or stop of `controls` on `agent_id`'s worker or on a bus.
234pub fn held(store: &CloudStore, agent_id: Option<&str>, controls: &[Control]) -> Option<Refusal> {
235    let holds = || {
236        controls
237            .iter()
238            .filter(|c| matches!(c.action, ControlAction::Hold | ControlAction::Stop))
239    };
240    // The worker is looked up only when a control names one.
241    let worker = holds()
242        .any(|c| c.target == ControlTarget::Worker)
243        .then(|| agent_id.and_then(|a| super::messages_v2::known_worker_of(store, a)))
244        .flatten();
245    let control = holds()
246        .filter(|c| match c.target {
247            ControlTarget::Bus => true,
248            ControlTarget::Worker => worker.is_some() && c.worker_id == worker,
249        })
250        .max_by_key(|c| (c.action == ControlAction::Stop, c.created_at))?;
251    let target = match control.target {
252        ControlTarget::Bus => ALL_AGENTS.to_string(),
253        ControlTarget::Worker => agent_id.unwrap_or(ALL_AGENTS).to_string(),
254    };
255    Some(Refusal {
256        target,
257        action: control.action,
258        reason: control.reason.clone(),
259        issued_by: issuer(control),
260    })
261}
262
263/// Who issued `control`, as its signed label says, else their user id.
264fn issuer(control: &Control) -> String {
265    control
266        .issued_by
267        .label
268        .clone()
269        .unwrap_or_else(|| control.issued_by.user_id.clone())
270}
271
272fn stamp_ms(ms: u64) -> UtcTimestamp {
273    let at = i64::try_from(ms)
274        .ok()
275        .and_then(lean_ctx_time::UtcDateTime::from_timestamp_millis)
276        .unwrap_or_else(lean_ctx_time::UtcDateTime::now);
277    UtcTimestamp::new(at.format("%Y-%m-%dT%H:%M:%SZ").to_string())
278        .expect("a formatted UTC time is a valid timestamp")
279}
280
281/// For `cloud status`: a pending rebuild's hold first, then the controls in
282/// force, oldest first (a worker control names its worker, a bus control
283/// every agent), or why the ones kept here do not apply (`None` when there
284/// is nothing to say).
285pub fn status_at(
286    store: &CloudStore,
287    local_now: lean_ctx_time::UtcDateTime,
288) -> (Vec<ActiveControl>, Option<Inactive>) {
289    let (kept, inactive) = current_at(store, local_now);
290    if inactive.is_some() {
291        return (Vec::new(), inactive);
292    }
293    let rebuild = kept.rebuild_since.map(|since| ActiveControl {
294        target_agent: None,
295        action: ControlAction::Hold,
296        target_ref: None,
297        reason: REBUILD_REASON.into(),
298        issued_by: REBUILD_ISSUER.into(),
299        since: stamp_ms(since),
300    });
301    let active = rebuild
302        .into_iter()
303        .chain(kept.controls.iter().map(|c| ActiveControl {
304            target_agent: match c.target {
305                ControlTarget::Bus => None,
306                ControlTarget::Worker => c.worker_id.clone(),
307            },
308            action: c.action,
309            target_ref: c.target_ref.as_ref().map(|r| r.id.clone()),
310            reason: c.reason.clone(),
311            issued_by: issuer(c),
312            since: stamp_ms(c.created_at),
313        }))
314        .collect();
315    (active, None)
316}
317
318impl From<Inactive> for lean_ctx_protocol::cloud::status::CloudBusControlsInactiveV1 {
319    fn from(reason: Inactive) -> Self {
320        match reason {
321            Inactive::NotEnrolled => Self::NotEnrolled,
322            Inactive::LeaseLapsed => Self::LeaseLapsed,
323        }
324    }
325}
326
327impl From<ActiveControl> for lean_ctx_protocol::cloud::status::CloudStatusBusControlV1 {
328    fn from(c: ActiveControl) -> Self {
329        use lean_ctx_protocol::cloud::status::CloudBusControlActionV1 as Action;
330        Self {
331            target_agent: c.target_agent,
332            action: match c.action {
333                ControlAction::Hold => Action::Hold,
334                ControlAction::Stop => Action::Stop,
335                ControlAction::Veto => Action::Veto,
336                // Never kept as active; mapped for completeness.
337                ControlAction::Resume => Action::Unknown,
338            },
339            target_ref: c.target_ref,
340            reason: c.reason,
341            issued_by: c.issued_by,
342            since: c.since,
343        }
344    }
345}
346
347/// `cloud status --json`: the controls in force, or why the ones kept here
348/// do not apply.
349pub fn status_view(
350    store: &CloudStore,
351    local_now: lean_ctx_time::UtcDateTime,
352) -> (
353    Vec<lean_ctx_protocol::cloud::status::CloudStatusBusControlV1>,
354    Option<lean_ctx_protocol::cloud::status::CloudBusControlsInactiveV1>,
355) {
356    let (active, inactive) = status_at(store, local_now);
357    (
358        active.into_iter().map(Into::into).collect(),
359        inactive.map(Into::into),
360    )
361}
362
363/// The tools `hold` and `stop` pause: those whose every call is Cloud
364/// traffic. Every other tool is local work and is never refused; the bus
365/// (`ctx_agent`) pauses only its Cloud side ([`veto_refusal`], `messages_v2`).
366fn cloud_traffic(tool: &str) -> bool {
367    crate::CLOUD_TOOLS.contains(&tool)
368}
369
370/// The admission hook of the tool pipeline: `Some(message)` refuses `tool`
371/// for `agent_id`. Only Cloud tools are ever refused; missing or unreadable
372/// local state never refuses.
373pub fn tool_refusal(agent_id: Option<&str>, tool: &str) -> Option<String> {
374    if !cloud_traffic(tool) {
375        return None;
376    }
377    let store = CloudStore::open().ok()?;
378    admission(&store, agent_id).map(|refusal| refusal.message())
379}
380
381/// The veto hook of the Cloud side of a lease (acquire, renew) and of a
382/// handoff through Cloud: `Some` when a verified veto names any of `refs`
383/// (lease id, resource ref, handoff id; V9.5). The caller then skips the
384/// Cloud request; the local lease or handoff goes ahead.
385pub fn veto_refusal(refs: &[&str]) -> Option<String> {
386    let store = CloudStore::open().ok()?;
387    // A pending rebuild may have lost a veto: the Cloud side waits too.
388    if let Some(pending) = in_force(&store, lean_ctx_time::UtcDateTime::now()).pending() {
389        return Some(pending.message());
390    }
391    refs.iter()
392        .find_map(|reference| super::veto::vetoed_v2(&store, reference))
393}
394
395/// Test enrollment: the protocol fixture's instance and lease, with the
396/// stored clock offset placing "now" `hours_after_issue` after it was issued
397/// (24 h: valid until; 168 h: grace until; later: lapsed).
398#[cfg(any(test, feature = "test-support"))]
399#[allow(clippy::unwrap_used)]
400pub fn enroll_for_tests(store: &CloudStore, hours_after_issue: i64) -> String {
401    use crate::state::{INSTANCE_FILE, InstanceRecord, LEASE_FILE, LeaseRecord};
402    let envelope: serde_json::Value = serde_json::from_str(include_str!(
403        "../../../../crates/lean-ctx-protocol/tests/fixtures/cloud/lease_envelope.response.json"
404    ))
405    .unwrap();
406    let lease = &envelope["lease"];
407    let instance_id = lease["instance_id"].as_str().unwrap().to_string();
408    let issued =
409        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(lease["issued_at"].as_str().unwrap())
410            .unwrap()
411            .to_utc();
412    let offset = (issued + lean_ctx_time::Duration::hours(hours_after_issue))
413        - lean_ctx_time::UtcDateTime::now();
414    store
415        .write_config(
416            INSTANCE_FILE,
417            &InstanceRecord {
418                instance_id: instance_id.clone(),
419                org_id: lease["org_id"].as_str().unwrap().into(),
420                org_name: "Acme AG".into(),
421                label: "test-box".into(),
422                url: "https://cloud.example".into(),
423                org_salt_id: "salt".into(),
424                enrolled_at: "2026-10-20T12:00:00Z".into(),
425                web_url: None,
426                org_kind: None,
427                company_name: None,
428            },
429        )
430        .unwrap();
431    store
432        .write_config(
433            LEASE_FILE,
434            &LeaseRecord {
435                envelope: envelope.clone(),
436                offset_seconds: offset.num_seconds(),
437                received_at: "2026-10-20T12:00:00Z".into(),
438            },
439        )
440        .unwrap();
441    instance_id
442}
443
444/// Keep `controls` as the relay does after verifying them (tests).
445#[cfg(any(test, feature = "test-support"))]
446#[allow(clippy::unwrap_used)]
447pub fn keep_for_tests(store: &CloudStore, controls: Vec<Control>) {
448    let mut state = StateV2::load(store.data_dir());
449    state.controls.clear();
450    for control in controls {
451        state.controls.insert(control.id.clone(), control);
452    }
453    state.save(store.data_dir()).unwrap();
454}
455
456/// The C0 hold fixture as a `target` (`bus` or `worker`) `action` control
457/// with `id` (tests; kept unverified, as admission reads it).
458#[cfg(any(test, feature = "test-support"))]
459#[allow(clippy::unwrap_used)]
460pub fn control_for_tests(target: &str, action: &str, id: &str) -> Control {
461    let path = format!(
462        "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/bus/control.hold.json",
463        concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
464    );
465    let mut control: serde_json::Value =
466        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
467    control["target"] = target.into();
468    control["action"] = action.into();
469    control["id"] = id.into();
470    if target == "bus" {
471        control.as_object_mut().unwrap().remove("worker_id");
472    }
473    serde_json::from_value(control).unwrap()
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479
480    fn store() -> (tempfile::TempDir, CloudStore) {
481        let dir = tempfile::tempdir().unwrap();
482        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
483        (dir, store)
484    }
485
486    #[test]
487    fn a_lapsed_lease_voids_controls_and_status_says_so() {
488        let (dir, store) = store();
489        enroll_for_tests(&store, 1);
490        keep_for_tests(&store, vec![control_for_tests("bus", "stop", "ctl_1")]);
491        assert_eq!(
492            admission(&store, Some("a")).unwrap().action,
493            ControlAction::Stop
494        );
495        // Grace still counts as connected.
496        enroll_for_tests(&store, 30);
497        assert!(admission(&store, Some("a")).is_some());
498        let (active_now, inactive) = status_at(&store, lean_ctx_time::UtcDateTime::now());
499        assert_eq!((active_now.len(), inactive), (1, None));
500        // Past grace_until: lapsed, controls off, status names the reason.
501        enroll_for_tests(&store, 24 * 8);
502        assert!(admission(&store, Some("a")).is_none());
503        let (active_now, inactive) = status_at(&store, lean_ctx_time::UtcDateTime::now());
504        assert!(active_now.is_empty());
505        assert_eq!(inactive, Some(Inactive::LeaseLapsed));
506        assert_eq!(
507            inactive.unwrap().status_line(),
508            "controls inactive: lease lapsed"
509        );
510        // A missing lease counts as lapsed.
511        std::fs::remove_file(dir.path().join("c/lease.json")).unwrap();
512        assert!(admission(&store, Some("a")).is_none());
513    }
514
515    #[test]
516    fn controls_apply_only_while_enrolled() {
517        let (_dir, store) = store();
518        assert_eq!(
519            status_at(&store, lean_ctx_time::UtcDateTime::now()),
520            (Vec::new(), None)
521        );
522        keep_for_tests(&store, vec![control_for_tests("bus", "hold", "ctl_1")]);
523        assert!(admission(&store, Some("a")).is_none(), "not enrolled");
524        assert_eq!(
525            status_at(&store, lean_ctx_time::UtcDateTime::now()),
526            (Vec::new(), Some(Inactive::NotEnrolled))
527        );
528        enroll_for_tests(&store, 1);
529        let refusal = admission(&store, Some("a")).expect("bus hold");
530        assert_eq!(refusal.target, ALL_AGENTS);
531        assert_eq!(refusal.action, ControlAction::Hold);
532        assert!(admission(&store, None).is_some(), "an unknown caller too");
533        let (active_now, inactive) = status_at(&store, lean_ctx_time::UtcDateTime::now());
534        assert_eq!((active_now.len(), inactive), (1, None));
535        assert_eq!(active_now[0].target_agent, None);
536    }
537
538    #[test]
539    fn a_stop_wins_over_a_hold() {
540        let (_dir, store) = store();
541        enroll_for_tests(&store, 1);
542        keep_for_tests(
543            &store,
544            vec![
545                control_for_tests("bus", "hold", "ctl_1"),
546                control_for_tests("bus", "stop", "ctl_2"),
547            ],
548        );
549        assert_eq!(
550            admission(&store, Some("a")).unwrap().action,
551            ControlAction::Stop
552        );
553        assert_eq!(
554            status_at(&store, lean_ctx_time::UtcDateTime::now()).0.len(),
555            2
556        );
557    }
558
559    #[test]
560    fn a_worker_hold_spares_agents_of_other_workers() {
561        let _data = lean_ctx::core::data_dir::isolated_data_dir();
562        let (_dir, store) = store();
563        enroll_for_tests(&store, 1);
564        keep_for_tests(&store, vec![control_for_tests("worker", "hold", "ctl_1")]);
565        assert!(admission(&store, None).is_none());
566        assert!(admission(&store, Some("unregistered")).is_none());
567        let (active_now, _) = status_at(&store, lean_ctx_time::UtcDateTime::now());
568        assert_eq!(
569            active_now[0].target_agent.as_deref(),
570            Some("wkr_gawyravj36igdp3irdfo")
571        );
572    }
573
574    /// Local work is never gated: a stop on every agent pauses Cloud tools
575    /// only, never a local mutating tool.
576    #[test]
577    fn controls_pause_cloud_tools_only() {
578        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
579        let store = CloudStore::open().unwrap();
580        enroll_for_tests(&store, 1);
581        keep_for_tests(&store, vec![control_for_tests("bus", "stop", "ctl_1")]);
582        for tool in [
583            "ctx_edit",
584            "ctx_shell",
585            "ctx_patch",
586            "ctx_agent",
587            "ctx_read",
588        ] {
589            assert_eq!(tool_refusal(Some("a"), tool), None, "{tool}");
590        }
591        let refused = tool_refusal(Some("a"), "ctx_tasks").expect("LeanCTX Cloud traffic waits");
592        assert!(refused.contains("local tools keep working"), "{refused}");
593    }
594
595    /// RB8 M12: a damaged or unknown `state_v2.json` holds Cloud traffic
596    /// (never "no controls") while local tools go on; `cloud status` names
597    /// it; the relay's load keeps the hold, and Cloud's complete replay ends it
598    /// (`relay_v2::note_replay`).
599    #[test]
600    fn a_damaged_control_state_holds_cloud_traffic_until_cloud_answers_a_hello() {
601        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
602        let store = CloudStore::open().unwrap();
603        enroll_for_tests(&store, 1);
604        let path = store.data_dir().join("bus/state_v2.json");
605        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
606        for broken in [&b"{ not json"[..], br#"{"version": 7, "controls": {}}"#] {
607            std::fs::write(&path, broken).unwrap();
608            let waiting = tool_refusal(Some("a"), "ctx_tasks").expect("fails closed");
609            assert!(waiting.contains(REBUILD_REASON), "{waiting}");
610            assert!(waiting.contains("local tools keep working"), "{waiting}");
611            assert!(
612                tool_refusal(None, "ctx_tasks").is_some(),
613                "unknown callers too"
614            );
615            for tool in ["ctx_edit", "ctx_shell", "ctx_agent", "ctx_read"] {
616                assert_eq!(tool_refusal(Some("a"), tool), None, "{tool}");
617            }
618            assert!(
619                veto_refusal(&["bl_7"]).is_some(),
620                "the LeanCTX Cloud side of a lease"
621            );
622            let (shown, inactive) = status_at(&store, lean_ctx_time::UtcDateTime::now());
623            assert_eq!((shown.len(), inactive), (1, None), "status names it");
624            assert_eq!(shown[0].reason, REBUILD_REASON);
625            assert_eq!(
626                std::fs::read(&path).unwrap(),
627                broken,
628                "a reader changes nothing"
629            );
630
631            // The relay's load moves the file aside and keeps the hold.
632            let mut state = StateV2::load(store.data_dir());
633            assert!(state.rebuild_pending.is_some());
634            assert!(
635                tool_refusal(Some("a"), "ctx_tasks").is_some(),
636                "still waiting"
637            );
638            // Cloud's replay after the next hello is complete: the hold ends.
639            state.rebuild_pending = None;
640            state.save(store.data_dir()).unwrap();
641            assert_eq!(tool_refusal(Some("a"), "ctx_tasks"), None);
642            assert_eq!(veto_refusal(&["bl_7"]), None);
643            assert!(
644                status_at(&store, lean_ctx_time::UtcDateTime::now())
645                    .0
646                    .is_empty()
647            );
648        }
649        assert!(
650            store
651                .data_dir()
652                .join("bus/state_v2.json.damaged-1")
653                .exists()
654        );
655        assert!(
656            store
657                .data_dir()
658                .join("bus/state_v2.json.damaged-2")
659                .exists()
660        );
661    }
662
663    /// A stop Cloud replayed already wins over the hold of a pending rebuild.
664    #[test]
665    fn a_stop_wins_over_a_pending_rebuild() {
666        let (_dir, store) = store();
667        enroll_for_tests(&store, 1);
668        let mut state = StateV2 {
669            rebuild_pending: Some(1),
670            ..StateV2::default()
671        };
672        let stop = control_for_tests("bus", "stop", "ctl_1");
673        state.controls.insert(stop.id.clone(), stop);
674        state.save(store.data_dir()).unwrap();
675        assert_eq!(
676            admission(&store, Some("a")).unwrap().action,
677            ControlAction::Stop
678        );
679        let (_, inactive) = status_at(&store, lean_ctx_time::UtcDateTime::now());
680        assert_eq!(inactive, None);
681        assert_eq!(
682            status_at(&store, lean_ctx_time::UtcDateTime::now()).0.len(),
683            2
684        );
685    }
686
687    #[test]
688    fn the_refusal_message_names_the_issuer_and_reason_but_no_ids() {
689        let (_dir, store) = store();
690        enroll_for_tests(&store, 1);
691        keep_for_tests(&store, vec![control_for_tests("bus", "stop", "ctl_1")]);
692        let message = admission(&store, Some("a")).unwrap().message();
693        assert!(message.contains("stopped"), "{message}");
694        assert!(
695            message.contains("by yves: Pausing the reviewer"),
696            "{message}"
697        );
698        assert!(!message.contains("ctl_1"));
699    }
700}