1use 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
42pub const ALL_AGENTS: &str = "*";
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Refusal {
48 pub target: String,
50 pub action: ControlAction,
51 pub reason: String,
52 pub issued_by: String,
53}
54
55impl Refusal {
56 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 "Cloud control: {who} is {what} (by {}: {}). Cloud traffic waits; local tools keep working.",
71 self.issued_by, self.reason
72 )
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ActiveControl {
79 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum Inactive {
91 NotEnrolled,
93 LeaseLapsed,
95}
96
97impl Inactive {
98 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
107fn 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
135const REBUILD_REASON: &str =
137 "the local control state was damaged; waiting for the Cloud to resend the controls";
138const REBUILD_ISSUER: &str = "lean-ctx";
140
141#[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 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
166pub 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
200fn 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
208pub 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
233pub 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 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
263fn 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
281pub 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 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
347pub 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
363fn cloud_traffic(tool: &str) -> bool {
367 crate::CLOUD_TOOLS.contains(&tool)
368}
369
370pub 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
381pub fn veto_refusal(refs: &[&str]) -> Option<String> {
386 let store = CloudStore::open().ok()?;
387 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#[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#[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#[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 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 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 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 #[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("Cloud traffic waits");
592 assert!(refused.contains("local tools keep working"), "{refused}");
593 }
594
595 #[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 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 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 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 #[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}