Skip to main content

lean_ctx_cloud/bus/
veto.rs

1// SPDX-License-Identifier: Apache-2.0
2//! A maintainer's veto of a host handoff or lock (SPEC-ENGINE §3.7.4, V9.5
3//! phase A): a verified `control` frame with `action = veto` and a `ref` of
4//! kind `lease` (a bus lock) or `handoff`.
5//!
6//! On receipt the host engine drops what it holds locally — the lock's
7//! binding and the local lease behind it, or the open handoff offer
8//! ([`super::handoff`]) — and
9//! the holding agent's next `ctx_tasks`/`ctx_agent` call is refused once
10//! with `claim_vetoed` ([`take_refusal`]). A `progress` `"vetoed: <reason>"`
11//! goes to the place bus. Later references to the vetoed lock or handoff
12//! are refused by [`super::control::veto_refusal`] while the veto stands.
13//!
14//! A control whose signature fails never gets here: `StateV2::apply_control`
15//! ignores it and counts it `sig_invalid`.
16//!
17//! Kept in `<data>/cloud/bus/vetoes.json` (pending notices per agent), under
18//! its lock; shared by the relay (writer) and tool calls (readers).
19
20use std::collections::BTreeMap;
21use std::path::Path;
22
23use serde::{Deserialize, Serialize};
24use serde_json::json;
25
26use super::v2::{self, Control, ControlAction, MessageType, Publish};
27use crate::CloudError;
28use crate::state::{CloudStore, load_or_quarantine, lock_state, write_private};
29
30const VETOES_FILE: &str = "vetoes.json";
31/// A `progress` step is at most this long (C0 2.0 bus body).
32const STEP_MAX: usize = 300;
33
34/// The refusal an agent gets once after a veto took its lock or handoff.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct Notice {
37    /// `lease` or `handoff`.
38    pub kind: String,
39    pub ref_id: String,
40    pub reason: String,
41    pub control_id: String,
42}
43
44impl Notice {
45    /// `claim_vetoed`, the maintainer's reason fenced as untrusted text.
46    pub fn message(&self) -> String {
47        format!(
48            "claim_vetoed: A maintainer vetoed this claim ({} {}): {}",
49            self.kind,
50            self.ref_id,
51            crate::untrusted::wrap(
52                crate::untrusted::UntrustedKind::BusMessage,
53                "maintainer",
54                &self.reason,
55            )
56        )
57    }
58}
59
60#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
61struct Vetoes {
62    /// Agent id → notices not yet delivered.
63    #[serde(default)]
64    pending: BTreeMap<String, Vec<Notice>>,
65}
66
67fn mutate<T>(data_dir: &Path, change: impl FnOnce(&mut Vetoes) -> T) -> Result<T, CloudError> {
68    let dir = data_dir.join("bus");
69    let _lock = lock_state(&dir, VETOES_FILE)?;
70    let mut state = load_or_quarantine::<Vetoes>(&dir.join(VETOES_FILE), |_| true)
71        .ok()
72        .flatten()
73        .unwrap_or_default();
74    let before = state.clone();
75    let out = change(&mut state);
76    if state != before {
77        let bytes = serde_json::to_vec(&state).map_err(|e| CloudError::Local(e.to_string()))?;
78        write_private(&dir, VETOES_FILE, &bytes)?;
79    }
80    Ok(out)
81}
82
83/// What a veto did on this machine.
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
85pub struct Applied {
86    /// Local agents whose lock or handoff it took.
87    pub agents: Vec<String>,
88    pub progress_queued: bool,
89}
90
91/// Apply a verified, issued (not lifted) veto. `worker_of` maps a local
92/// agent id to its worker id on the place (for the `progress` post).
93pub fn apply(
94    store: &CloudStore,
95    control: &Control,
96    worker_of: &dyn Fn(&str) -> Option<String>,
97) -> Result<Applied, CloudError> {
98    let mut applied = Applied::default();
99    let Some(target) = control.target_ref.as_ref() else {
100        return Ok(applied);
101    };
102    if control.action != ControlAction::Veto {
103        return Ok(applied);
104    }
105    let data = store.data_dir();
106    match target.kind.as_str() {
107        "lease" => {
108            let local_refs = super::leases::Bindings::mutate(data, |b| {
109                let refs: Vec<String> = b
110                    .leases
111                    .iter()
112                    .filter(|(_, binding)| binding.lease_id == target.id)
113                    .map(|(local, _)| local.clone())
114                    .collect();
115                for local in &refs {
116                    b.leases.remove(local);
117                }
118                refs
119            })?;
120            for local in local_refs {
121                if let Ok(Some(lease)) = lean_ctx::core::agent_lease::revoke_shared(&local) {
122                    applied.agents.push(lease.request.owner_agent_id);
123                }
124            }
125        }
126        "handoff" => {
127            let from =
128                super::handoff::Handoffs::mutate(data, |h| h.veto(&target.id, &control.reason))?;
129            applied.agents.extend(from);
130        }
131        _ => return Ok(applied),
132    }
133    applied.agents.sort();
134    applied.agents.dedup();
135    let notice = Notice {
136        kind: target.kind.clone(),
137        ref_id: target.id.clone(),
138        reason: control.reason.clone(),
139        control_id: control.id.clone(),
140    };
141    mutate(data, |v| {
142        for agent in &applied.agents {
143            let list = v.pending.entry(agent.clone()).or_default();
144            if !list.iter().any(|n| n.control_id == notice.control_id) {
145                list.push(notice.clone());
146            }
147        }
148    })?;
149    // `progress` "vetoed: <reason>" on the place bus, as the holding worker.
150    let address = place_address(data, &control.place);
151    let worker = applied.agents.iter().find_map(|a| worker_of(a));
152    if let (Some(to), Some(worker_id)) = (address, worker) {
153        let step: String = format!("vetoed: {}", control.reason)
154            .chars()
155            .take(STEP_MAX)
156            .collect();
157        let now =
158            u64::try_from(lean_ctx_time::UtcDateTime::now().timestamp_millis()).unwrap_or_default();
159        super::relay_v2::queue_publish(
160            store,
161            Publish {
162                schema: v2::BUS_SCHEMA.to_string(),
163                client_msg_id: v2::new_ulid(now),
164                to,
165                kind: MessageType::Progress,
166                worker_id,
167                thread_id: None,
168                reply_to: None,
169                refs: Vec::new(),
170                body: json!({ "step": step }),
171                ck_wrapped: None,
172                epoch: None,
173                about: None,
174                counts: None,
175                window: None,
176            },
177        )?;
178        applied.progress_queued = true;
179    }
180    Ok(applied)
181}
182
183/// `#ws/vault` of the linked vault behind a place ref `vault:<id>`.
184fn place_address(data_dir: &Path, place: &str) -> Option<String> {
185    let id = place.strip_prefix("vault:")?;
186    crate::vault::VaultMap::load(data_dir)
187        .vaults
188        .values()
189        .find(|r| r.vault_id == id)
190        .map(super::relay_v2::address_of)
191}
192
193/// The tools a veto notice answers: the claim and bus tools of §3.7.4.
194fn answers(tool: &str) -> bool {
195    matches!(tool, "ctx_tasks" | "ctx_agent")
196}
197
198/// The `claim_vetoed` refusal for `agent_id`'s next `ctx_tasks`/`ctx_agent`
199/// call, delivered once. Missing or unreadable state never refuses.
200pub fn take_refusal(agent_id: Option<&str>, tool: &str) -> Option<String> {
201    let agent = agent_id?;
202    if !answers(tool) {
203        return None;
204    }
205    let store = CloudStore::open().ok()?;
206    take_refusal_in(&store, agent)
207}
208
209pub(crate) fn take_refusal_in(store: &CloudStore, agent: &str) -> Option<String> {
210    if !store.data_dir().join("bus").join(VETOES_FILE).exists() {
211        return None;
212    }
213    mutate(store.data_dir(), |v| {
214        let list = v.pending.get_mut(agent)?;
215        let notice = (!list.is_empty()).then(|| list.remove(0));
216        if list.is_empty() {
217            v.pending.remove(agent);
218        }
219        notice
220    })
221    .ok()
222    .flatten()
223    .map(|n| n.message())
224}
225
226/// Whether a verified v2 veto stands for `ref_id` (a lock or handoff).
227pub fn vetoed_v2(store: &CloudStore, ref_id: &str) -> Option<String> {
228    let state = super::relay_v2::StateV2::read(store.data_dir()).unwrap_or_default();
229    state.vetoed(ref_id).map(|c| {
230        Notice {
231            kind: c
232                .target_ref
233                .as_ref()
234                .map_or_else(String::new, |r| r.kind.clone()),
235            ref_id: ref_id.to_string(),
236            reason: c.reason.clone(),
237            control_id: c.id.clone(),
238        }
239        .message()
240    })
241}
242
243#[cfg(test)]
244#[path = "veto_tests.rs"]
245mod tests;