#![cfg_attr(not(feature = "http-server"), allow(dead_code))]
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::address::Address;
use super::v2::{
BUS_SCHEMA, Control, ControlAction, ControlKeys, ControlRejection, ControlTarget, MessageType,
PERSON_VALIDATION_WORKER, PresenceEntry, PresenceState, Publish, ulid_for,
};
use crate::CloudError;
use crate::knowledge::screening::Screen;
use crate::state::{load_or_quarantine, write_private};
use crate::vault::{VaultMap, VaultRecord};
use lean_ctx::core::a2a::message::{MessagePriority, PrivacyLevel};
use lean_ctx::core::agents::{AgentEntry, AgentRegistry};
const STATE_FILE: &str = "state_v2.json";
pub const MAX_SUBSCRIBE: usize = 64;
const MAX_DECIDED: usize = 5000;
pub(crate) use lean_ctx::core::agents::CLOUD_INBOUND_KEY_PREFIX as INBOUND_KEY_PREFIX;
const STEP_MAX: usize = 300;
pub fn is_inbound(entry: &lean_ctx::core::agents::ScratchpadEntry) -> bool {
entry.is_cloud_inbound()
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StateV2 {
#[serde(default)]
pub cursors: BTreeMap<String, u64>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub bound: BTreeMap<String, CursorBinding>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub legacy_until: BTreeMap<String, u64>,
#[serde(skip)]
pub legacy_tally: BTreeMap<String, LegacyTally>,
#[serde(default)]
pub decided: VecDeque<String>,
#[serde(default)]
pub in_flight: BTreeMap<String, String>,
#[serde(default)]
pub withheld: u64,
#[serde(default)]
pub controls: BTreeMap<String, Control>,
#[serde(default)]
pub sig_invalid: u64,
#[serde(default)]
pub denied: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub tasks: super::task_events::TasksSeen,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub plans: super::plan_events::PlansSeen,
#[serde(default, skip_serializing_if = "is_zero")]
pub version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rebuild_pending: Option<u64>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub person_publish: bool,
#[serde(skip)]
pub budget: super::queen_kinds::RelayBudget,
}
fn is_zero(n: &u32) -> bool {
*n == 0
}
pub const PERSON_SENDER: &str = "cloud-person";
pub const PERSON_PUBLISH: &str = "person_publish";
pub const POLICY_ADVANCED: &str = "policy_advanced";
pub const POLICY_APPLIED: &str = "policy_applied";
pub const PRESENCE_IDENTITY: &str = "presence_identity";
pub const HELLO_FEATURES: &[&str] = &[
POLICY_ADVANCED,
POLICY_APPLIED,
PRESENCE_IDENTITY,
super::plan_events::PLAN_UPDATES,
];
pub fn acks_feature(ack: &Value, feature: &str) -> bool {
ack["features"]
.as_array()
.into_iter()
.flatten()
.any(|f| f.as_str() == Some(feature))
}
pub fn acks_person_publish(ack: &Value) -> bool {
acks_feature(ack, PERSON_PUBLISH)
}
impl StateV2 {
fn path(data_dir: &Path) -> std::path::PathBuf {
data_dir.join("bus").join(STATE_FILE)
}
pub fn load(data_dir: &Path) -> Self {
match load_or_quarantine(&Self::path(data_dir), |s: &Self| s.version == 0) {
Ok(state) => state.unwrap_or_default(),
Err(error) => {
tracing::warn!("cloud bus v2 state: {error}");
let state = Self {
rebuild_pending: Some(now_ms()),
..Self::default()
};
if let Err(error) = state.save(data_dir) {
tracing::warn!("cloud bus v2 state: {error}");
}
state
}
}
}
pub fn read(data_dir: &Path) -> Result<Self, u64> {
let path = Self::path(data_dir);
let changed = || {
std::fs::metadata(&path)
.and_then(|m| m.modified())
.ok()
.map(|t| lean_ctx_time::UtcDateTime::from(t).timestamp_millis())
.and_then(|ms| u64::try_from(ms).ok())
.unwrap_or_else(now_ms)
};
match std::fs::read(&path) {
Ok(bytes) => serde_json::from_slice::<Self>(&bytes)
.ok()
.filter(|s| s.version == 0)
.ok_or_else(changed),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(_) => Err(changed()),
}
}
pub fn save(&self, data_dir: &Path) -> Result<(), CloudError> {
let bytes = serde_json::to_vec(self).map_err(|e| CloudError::Local(e.to_string()))?;
write_private(&data_dir.join("bus"), STATE_FILE, &bytes)
}
fn decide(&mut self, entry_id: &str) {
if !self.decided.iter().any(|id| id == entry_id) {
self.decided.push_back(entry_id.to_string());
while self.decided.len() > MAX_DECIDED {
self.decided.pop_front();
}
}
}
fn was_decided(&self, entry_id: &str) -> bool {
self.decided.iter().any(|id| id == entry_id)
}
pub fn begin_connection(&mut self) {
self.in_flight.clear();
self.person_publish = false;
}
pub fn stored(&mut self, client_msg_id: &str) {
if let Some(entry) = self.in_flight.remove(client_msg_id) {
self.decide(&entry);
}
}
pub fn refused(&mut self, client_msg_id: &str) {
if let Some(entry) = self.in_flight.remove(client_msg_id) {
self.decide(&entry);
self.withheld += 1;
}
}
pub fn apply_control(&mut self, lifted: bool, control: Control, keys: &ControlKeys) -> bool {
match control.verify(lifted, keys) {
Ok(()) => {}
Err(ControlRejection::SigInvalid) => {
self.sig_invalid += 1;
return false;
}
Err(ControlRejection::Invalid) => return false,
}
if lifted || control.action == ControlAction::Resume {
self.controls.remove(&control.id);
if control.action == ControlAction::Resume {
self.controls.retain(|_, c| {
!(c.place == control.place
&& c.target == control.target
&& c.worker_id == control.worker_id
&& matches!(c.action, ControlAction::Hold | ControlAction::Stop))
});
}
} else {
self.controls.insert(control.id.clone(), control);
}
true
}
pub fn held(&self, place_ref: Option<&str>, worker_id: &str) -> Option<&Control> {
self.controls
.values()
.filter(|c| matches!(c.action, ControlAction::Hold | ControlAction::Stop))
.filter(|c| place_ref.is_none_or(|p| c.place == p))
.filter(|c| match c.target {
ControlTarget::Bus => true,
ControlTarget::Worker => c.worker_id.as_deref() == Some(worker_id),
})
.max_by_key(|c| (c.action == ControlAction::Stop, c.created_at))
}
pub fn holds_person_posts(&self) -> bool {
self.rebuild_pending.is_some() || self.held(None, PERSON_VALIDATION_WORKER).is_some()
}
pub fn vetoed(&self, ref_id: &str) -> Option<&Control> {
self.controls.values().find(|c| {
c.action == ControlAction::Veto && c.target_ref.as_ref().is_some_and(|r| r.id == ref_id)
})
}
}
fn now_ms() -> u64 {
u64::try_from(lean_ctx_time::UtcDateTime::now().timestamp_millis()).unwrap_or_default()
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum Replay {
#[default]
AwaitingAck,
Running,
Done,
}
pub(crate) fn note_replay(
state: &mut StateV2,
replay: &mut Replay,
frame: &super::v2::Inbound,
subscribed_any: bool,
) {
use super::v2::Inbound;
*replay = match (*replay, frame) {
(Replay::AwaitingAck, Inbound::HelloAck(_)) if subscribed_any => Replay::Running,
(Replay::AwaitingAck, Inbound::HelloAck(_)) | (Replay::Running, _)
if !matches!(frame, Inbound::Control { .. }) =>
{
Replay::Done
}
(other, _) => other,
};
if *replay == Replay::Done {
state.rebuild_pending = None;
}
}
const QUEUE_FILE: &str = "publish_queue.json";
const MAX_QUEUE: usize = 1000;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct PublishQueue {
items: Vec<Publish>,
}
fn read_queue(data_dir: &Path) -> PublishQueue {
load_or_quarantine(
&data_dir.join("bus").join(QUEUE_FILE),
|_: &PublishQueue| true,
)
.ok()
.flatten()
.unwrap_or_default()
}
fn change_queue<T>(
data_dir: &Path,
change: impl FnOnce(&mut PublishQueue) -> T,
) -> Result<T, CloudError> {
let dir = data_dir.join("bus");
let _lock = crate::state::lock_state(&dir, QUEUE_FILE)?;
let mut queue = read_queue(data_dir);
let out = change(&mut queue);
let bytes = serde_json::to_vec(&queue).map_err(|e| CloudError::Local(e.to_string()))?;
write_private(&dir, QUEUE_FILE, &bytes)?;
Ok(out)
}
pub fn queue_publish(store: &crate::CloudStore, publish: Publish) -> Result<(), CloudError> {
publish
.validate()
.map_err(|e| CloudError::Config(e.to_string()))?;
change_queue(store.data_dir(), |queue| {
if queue
.items
.iter()
.any(|p| p.client_msg_id == publish.client_msg_id)
{
return Ok(());
}
if queue.items.len() >= MAX_QUEUE {
return Err(CloudError::Local(format!(
"{MAX_QUEUE} bus messages are still waiting for LeanCTX Cloud"
)));
}
queue.items.push(publish);
Ok(())
})?
}
pub(crate) fn queued_frames(data_dir: &Path, state: &mut StateV2) -> Vec<Value> {
let mut out = Vec::new();
for publish in read_queue(data_dir).items {
if state.in_flight.contains_key(&publish.client_msg_id)
|| state.held(None, &publish.worker_id).is_some()
{
continue;
}
let Ok(Value::Object(mut frame)) = serde_json::to_value(&publish) else {
continue;
};
frame.insert("t".into(), "place.publish".into());
state.in_flight.insert(
publish.client_msg_id.clone(),
format!("queue:{}", publish.client_msg_id),
);
out.push(Value::Object(frame));
}
out
}
pub(crate) fn queued_worker(data_dir: &Path, client_msg_id: &str) -> Option<String> {
read_queue(data_dir)
.items
.into_iter()
.find(|p| p.client_msg_id == client_msg_id)
.map(|p| p.worker_id)
}
pub(crate) fn settle_queued(data_dir: &Path, client_msg_id: &str) -> Result<bool, CloudError> {
change_queue(data_dir, |queue| {
let before = queue.items.len();
queue.items.retain(|p| p.client_msg_id != client_msg_id);
before != queue.items.len()
})
}
const PROTOCOL_FILE: &str = "bus_protocol.json";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct ProtocolRecord {
bus: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
minor: Option<u16>,
}
pub fn record_protocol(store: &crate::CloudStore, v2: bool) -> Result<(), CloudError> {
record_protocol_minor(store, v2, None)
}
pub fn record_protocol_minor(
store: &crate::CloudStore,
v2: bool,
minor: Option<u16>,
) -> Result<(), CloudError> {
store.write_config(
PROTOCOL_FILE,
&ProtocolRecord {
bus: if v2 { 2 } else { 1 },
minor: minor.filter(|_| v2),
},
)
}
pub fn protocol_minor(store: &crate::CloudStore) -> Option<u16> {
store
.read_config::<ProtocolRecord>(PROTOCOL_FILE)
.ok()
.flatten()
.filter(|r| r.bus == 2)
.and_then(|r| r.minor)
}
pub fn speaks_2_2(store: &crate::CloudStore) -> bool {
protocol_minor(store).is_some_and(|minor| minor >= 2)
}
pub fn speaks_v2(store: &crate::CloudStore) -> bool {
store
.read_config::<ProtocolRecord>(PROTOCOL_FILE)
.ok()
.flatten()
.is_some_and(|r| r.bus == 2)
}
pub fn address_of(record: &VaultRecord) -> String {
format!("#{}/{}", record.ns, record.name)
}
pub(crate) fn record_for<'a>(map: &'a VaultMap, root: &str) -> Option<&'a VaultRecord> {
map.vaults.values().find(|record| {
record
.roots
.iter()
.any(|known| lean_ctx::core::pathutil::same_project(known, root))
})
}
pub(crate) fn subscriptions(map: &VaultMap, agents: &[&AgentEntry]) -> Vec<String> {
let set: BTreeSet<String> = agents
.iter()
.filter_map(|agent| record_for(map, &agent.project_root))
.map(address_of)
.filter(|address| Address::parse(Some(address)).is_ok_and(|a| a.is_remote()))
.collect();
set.into_iter().take(MAX_SUBSCRIBE).collect()
}
pub fn hello(subscribe: &[String], state: &StateV2, presence: &[PresenceEntry]) -> Value {
let cursors: BTreeMap<&String, u64> = subscribe
.iter()
.filter_map(|a| state.cursors.get(a).map(|seq| (a, *seq)))
.collect();
json!({
"t": "hello",
"protocol": "2.0",
"subscribe": subscribe,
"cursors": cursors,
"presence": presence,
"features": HELLO_FEATURES,
})
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct AckCursors {
pub changed: bool,
pub resubscribe: bool,
}
pub(crate) fn adopt_ack_cursors(
state: &mut StateV2,
subscribe: &[String],
ack: &Value,
) -> AckCursors {
let subscribed: BTreeSet<&str> = ack["subscribed"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let mut out = AckCursors::default();
for address in subscribe {
if !subscribed.contains(address.as_str()) {
continue;
}
let Some(now) = ack_binding(ack, address) else {
continue;
};
let held = state.cursors.get(address).copied();
let start = ack["cursors"][address.as_str()].as_u64();
let next = match (state.bound.get(address), held) {
(Some(bound), Some(_)) if *bound == now => continue,
(Some(bound), None) if *bound == now => start,
(None, None) => start,
(None, Some(_)) if start.is_none() => continue,
(bound, held) => {
let legacy = held.filter(|seq| bound.is_none() && *seq > 0);
let marker = state.legacy_until.get(address).copied();
if marker != legacy {
match legacy {
Some(seq) => state.legacy_until.insert(address.clone(), seq),
None => state.legacy_until.remove(address),
};
state.legacy_tally.remove(address);
out.changed = true;
}
out.resubscribe |= held != Some(0);
Some(0)
}
};
let Some(next) = next else {
continue;
};
if held != Some(next) {
state.cursors.insert(address.clone(), next);
out.changed = true;
}
if state.bound.get(address) != Some(&now) {
state.bound.insert(address.clone(), now);
out.changed = true;
}
}
out
}
fn ack_binding(ack: &Value, address: &str) -> Option<CursorBinding> {
let place = ack["places"][address].as_str()?;
let epoch = ack["epochs"][place].as_u64()?;
Some(CursorBinding {
place: place.to_string(),
epoch,
})
}
pub(crate) fn local_places(map: &VaultMap) -> BTreeMap<String, String> {
map.vaults
.values()
.map(|r| (address_of(r), format!("vault:{}", r.vault_id)))
.collect()
}
pub(crate) fn drop_moved_cursors(state: &mut StateV2, local: &BTreeMap<String, String>) -> bool {
let moved: Vec<String> = state
.bound
.iter()
.filter(|(address, held)| local.get(*address).is_some_and(|p| *p != held.place))
.map(|(address, _)| address.clone())
.collect();
for address in &moved {
state.cursors.insert(address.clone(), 0);
state.bound.remove(address);
state.legacy_until.remove(address);
state.legacy_tally.remove(address);
}
!moved.is_empty()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CursorBinding {
pub place: String,
pub epoch: u64,
}
fn legacy_key(address: &str, seq: u64) -> String {
format!("{INBOUND_KEY_PREFIX}{address}:{seq}")
}
pub(crate) fn inbound_key(state: &StateV2, address: &str, seq: u64) -> String {
match state.bound.get(address) {
Some(binding) => {
let tag = blake3::hash(format!("{}\0{}", binding.place, binding.epoch).as_bytes());
let tag = tag.to_hex();
format!("{INBOUND_KEY_PREFIX}{address}:{}.{seq}", &tag[..16])
}
None => legacy_key(address, seq),
}
}
pub fn presence_state(state: &StateV2, worker_id: &str, any_active: bool) -> PresenceState {
if state.held(None, worker_id).is_some() {
PresenceState::Held
} else if any_active {
PresenceState::Active
} else {
PresenceState::Idle
}
}
fn publish_for(
entry: &lean_ctx::core::agents::ScratchpadEntry,
text: &str,
to: &str,
worker_id: &str,
) -> Option<Publish> {
let kind = MessageType::parse(&entry.category.to_ascii_lowercase());
let text = text.trim();
let (kind, body) = match kind {
Some(MessageType::Question) => (MessageType::Question, json!({"text": text})),
Some(
MessageType::Answer | MessageType::Finding | MessageType::Offer | MessageType::Handoff,
) => return None,
Some(MessageType::Progress) | None => {
let step: String = text.chars().take(STEP_MAX).collect();
(MessageType::Progress, json!({"step": step}))
}
};
let publish = Publish {
schema: BUS_SCHEMA.into(),
client_msg_id: ulid_for(
u64::try_from(entry.timestamp.timestamp_millis()).unwrap_or_default(),
&entry.id,
),
to: to.to_string(),
kind,
worker_id: worker_id.to_string(),
thread_id: None,
reply_to: None,
refs: Vec::new(),
body,
ck_wrapped: None,
epoch: None,
about: None,
counts: None,
window: None,
};
publish.validate().ok().map(|()| publish)
}
#[derive(Debug, Clone, PartialEq)]
pub struct OutgoingV2 {
pub entry_id: String,
pub frame: Value,
}
pub(crate) fn outgoing(
registry: &AgentRegistry,
map: &VaultMap,
state: &mut StateV2,
screen: &mut Screen,
worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
records: &super::person_rules::Records,
) -> Vec<OutgoingV2> {
let now = lean_ctx_time::UtcDateTime::now();
let queen_mode = super::person_rules::QueenMode::current();
let mut entries: Vec<_> = registry
.scratchpad
.iter()
.filter(|e| e.expires_at.is_none_or(|at| at > now))
.filter(|e| !is_inbound(e))
.filter(|e| !state.was_decided(&e.id))
.filter(|e| !state.in_flight.values().any(|id| id == &e.id))
.collect();
entries.sort_by_key(|e| e.timestamp);
let mut out = Vec::new();
for entry in entries {
let agent = registry
.agents
.iter()
.find(|a| a.agent_id == entry.from_agent);
let person = agent.is_none() && entry.from_agent == PERSON_SENDER;
if agent.is_none() && !person {
continue;
}
let record = match Address::parse(entry.to_agent.as_deref()) {
Ok(Address::Vault { workspace, vault }) => map
.vaults
.values()
.find(|r| r.ns == workspace && r.name == vault),
Ok(Address::Worker(_)) => continue,
Ok(Address::Local | Address::LocalAgent(_)) | Err(_) => {
state.decide(&entry.id);
continue;
}
};
let denied =
record.is_some_and(|r| state.denied.contains_key(&format!("vault:{}", r.vault_id)));
let Some(record) = record.filter(|_| entry.privacy != PrivacyLevel::Private && !denied)
else {
state.decide(&entry.id);
state.withheld += 1;
continue;
};
if let Some(agent) = agent
&& !super::person_rules::Speaker::of_registry(registry, Some(&agent.agent_id))
.registered_queen
{
state.decide(&entry.id);
if entry.metadata.contains_key(super::queen_kinds::KIND_KEY) {
state.withheld += 1;
}
continue;
}
if entry.metadata.contains_key(super::queen_kinds::KIND_KEY) {
match lean_ctx::core::policy::cloud_orchestrator::vault_network_refusal(
&record.vault_id,
) {
Ok(None) => {}
Ok(Some(_)) => {
state.decide(&entry.id);
state.withheld += 1;
continue;
}
Err(_) => continue,
}
}
let worker_id = match agent {
Some(agent) => match worker_of(agent) {
Some(worker_id) => worker_id,
None => continue,
},
None if state.person_publish => PERSON_VALIDATION_WORKER.to_owned(),
None => continue,
};
if state.held(None, &worker_id).is_some() {
continue;
}
let queen = agent.map_or(Ok(None), |agent| {
let sender = super::person_rules::Speaker::of_registry(registry, Some(&agent.agent_id));
super::person_rules::queen_rule(sender, &[&entry.message], queen_mode)
});
if let Some(agent) = agent
&& let Some((kind, body)) =
super::person_rules::post_body(&entry.category, &entry.message)
&& super::person_rules::asks_to_act(kind)
{
let Some(ledger) = &records.ledger else {
continue;
};
let refused = super::person_rules::Refused::for_sender(
state,
&records.handoffs,
ledger,
map,
&agent.agent_id,
&worker_id,
);
if super::person_rules::check_forwarding(kind, &[], &body, &refused).is_err() {
state.decide(&entry.id);
state.withheld += 1;
continue;
}
}
let (Ok(queen), Ok(())) = (queen, screen.check(&entry.message)) else {
state.decide(&entry.id);
state.withheld += 1;
continue;
};
let text = queen.map_or_else(
|| entry.message.clone(),
|mark| super::person_rules::marked(&mark, &entry.message),
);
let text = if MessageType::parse(&entry.category.trim().to_ascii_lowercase())
== Some(MessageType::Question)
{
super::person_rules::cut_to_fit(text.trim(), super::v2::TEXT_MAX)
} else {
text
};
let Some(publish) = publish_for(entry, &text, &address_of(record), &worker_id) else {
state.decide(&entry.id);
state.withheld += 1;
continue;
};
if !state.budget.take(&worker_id, now.timestamp_millis()) {
continue;
}
let Ok(Value::Object(mut frame)) = serde_json::to_value(&publish) else {
continue;
};
if let Some(fields) = super::queen_kinds::frame_fields(
&entry.metadata,
entry.task_id.as_deref(),
entry
.metadata
.get(super::queen_kinds::THREAD_KEY)
.map(String::as_str),
) {
frame.extend(fields);
}
if person {
frame.remove("worker_id");
frame.insert("sender".into(), json!({"kind": "person"}));
}
frame.insert("t".into(), "place.publish".into());
state
.in_flight
.insert(publish.client_msg_id.clone(), entry.id.clone());
out.push(OutgoingV2 {
entry_id: entry.id.clone(),
frame: Value::Object(frame),
});
}
out
}
fn delivered_text(message: &Value) -> String {
let body = &message["body"];
if let Some(line) = super::messages_v2::delivered_line(message) {
return line;
}
["text", "statement", "step", "summary", "what"]
.iter()
.find_map(|field| body[*field].as_str())
.map_or_else(|| body.to_string(), str::to_string)
}
fn sender_label(message: &Value) -> String {
let sender = &message["sender"];
match sender["kind"].as_str() {
Some("worker") => sender["worker_id"].as_str().unwrap_or("worker").to_string(),
Some("person") => format!("person:{}", sender["handle"].as_str().unwrap_or("?")),
_ => "cloud".into(),
}
}
pub(crate) fn new_delivery<'a>(
map: &'a VaultMap,
state: &StateV2,
message: &Value,
) -> Option<(String, u64, Option<&'a VaultRecord>)> {
let address = message["to"].as_str()?.to_string();
let seq = message["seq"].as_u64()?;
if state.cursors.get(&address).is_some_and(|last| seq <= *last) {
return None;
}
let record = match Address::parse(Some(&address)) {
Ok(Address::Vault { workspace, vault }) => map
.vaults
.values()
.find(|r| r.ns == workspace && r.name == vault),
_ => None,
};
Some((address, seq, record))
}
pub(crate) fn skip_delivery(state: &mut StateV2, address: &str, seq: u64) {
state.cursors.insert(address.to_string(), seq);
}
pub(crate) fn apply_delivery(
registry: &mut AgentRegistry,
map: &VaultMap,
state: &mut StateV2,
message: &Value,
local_workers: &BTreeSet<String>,
worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
) -> Result<Option<(String, u64)>, String> {
let applied = deliver_one(registry, map, state, message, local_workers, worker_of)?;
if let Some((address, seq)) = &applied {
end_legacy_window(state, address, *seq);
}
Ok(applied)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LegacyTally {
pub matched: u64,
pub skipped: u64,
}
fn end_legacy_window(state: &mut StateV2, address: &str, seq: u64) {
if state
.legacy_until
.get(address)
.is_some_and(|until| seq >= *until)
{
state.legacy_until.remove(address);
let tally = state.legacy_tally.remove(address).unwrap_or_default();
tracing::info!(
"bus relay: the first replay of {address} after binding ended: {} posts already landed, {} stale posts not posted again",
tally.matched,
tally.skipped
);
}
}
fn stale_for_legacy_window(message: &Value, ttl_hours: u64) -> bool {
if message["purged"].as_bool() == Some(true) {
return true;
}
let Some(received_ms) = message["received_at"].as_u64() else {
return false;
};
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
let ttl_ms = ttl_hours.saturating_mul(3_600_000);
now_ms.saturating_sub(received_ms) > ttl_ms
}
fn deliver_one(
registry: &mut AgentRegistry,
map: &VaultMap,
state: &mut StateV2,
message: &Value,
local_workers: &BTreeSet<String>,
worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
) -> Result<Option<(String, u64)>, String> {
let address = message["to"]
.as_str()
.ok_or("deliver without to")?
.to_string();
let seq = message["seq"].as_u64().ok_or("deliver without seq")?;
if state.cursors.get(&address).is_some_and(|last| seq <= *last) {
return Ok(None);
}
let legacy = state
.legacy_until
.get(&address)
.is_some_and(|until| seq <= *until);
if legacy
&& stale_for_legacy_window(
message,
lean_ctx::core::config::Config::load()
.agents
.scratchpad_default_ttl_hours,
)
{
state
.legacy_tally
.entry(address.clone())
.or_default()
.skipped += 1;
state.cursors.insert(address.clone(), seq);
return Ok(Some((address, seq)));
}
let Ok(Address::Vault { workspace, vault }) = Address::parse(Some(&address)) else {
state.cursors.insert(address.clone(), seq);
return Ok(Some((address, seq)));
};
if super::v2::sender_of(message).is_err() {
state.cursors.insert(address.clone(), seq);
return Ok(Some((address, seq)));
}
let record = map
.vaults
.values()
.find(|r| r.ns == workspace && r.name == vault);
if let Some(record) = record
&& super::queen_kinds::delivered_fields(message).0.is_some()
&& !matches!(
lean_ctx::core::policy::cloud_orchestrator::vault_network_refusal(&record.vault_id),
Ok(None)
)
{
state.cursors.insert(address.clone(), seq);
return Ok(Some((address, seq)));
}
let root = record.and_then(|r| r.roots.iter().find(|root| Path::new(root).is_dir()));
let from = sender_label(message);
let spoofed = registry.agents.iter().any(|a| a.agent_id == from);
if let Some(root) = root.filter(|_| !spoofed && !local_workers.contains(&from)) {
let kind = message["type"].as_str().unwrap_or("progress");
let key = inbound_key(state, &address, seq);
let text = delivered_text(message);
let (queen_kind, task_id, thread) = super::queen_kinds::delivered_fields(message);
let to_worker = message["body"]["to_worker"].as_str();
let addressed: Vec<String> = to_worker.map_or_else(Vec::new, |w| {
registry
.list_active(None)
.into_iter()
.filter(|agent| worker_of(agent).as_deref() == Some(w))
.map(|agent| agent.agent_id.clone())
.collect()
});
let targets: Vec<Option<&str>> = match to_worker {
None => vec![None],
Some(_) if !addressed.is_empty() => {
addressed.iter().map(|a| Some(a.as_str())).collect()
}
Some(w) if local_workers.contains(w) => vec![None],
Some(_) => Vec::new(),
};
let old_key = legacy.then(|| legacy_key(&address, seq));
let mut matched = false;
for to in targets {
let per_target = |key: &str| {
to.map_or_else(
|| key.to_string(),
|agent| format!("{key}@{}", agent.replace(':', "_")),
)
};
let key = per_target(&key);
let landed = old_key
.as_deref()
.map(per_target)
.filter(|old| registry.holds_request_id(Some(root), &from, old));
let mut post = |key: &str| {
registry.post_message_keyed(
Some(root),
&from,
to,
kind,
&text,
PrivacyLevel::Team,
MessagePriority::Normal,
None,
Some(key),
)
};
let id = match landed.map(|old| post(&old)) {
Some(Ok(id)) => {
matched = true;
id
}
Some(Err(e)) if e == lean_ctx::core::agents::request_id_conflict() => post(&key)?,
Some(Err(e)) => return Err(e),
None => post(&key)?,
};
if let Some(entry) = registry.scratchpad.iter_mut().find(|e| e.id == id) {
if let Some(queen_kind) = queen_kind {
entry.metadata.insert(
super::queen_kinds::KIND_KEY.into(),
queen_kind.as_str().into(),
);
}
if let Some(thread) = &thread {
entry
.metadata
.insert(super::queen_kinds::THREAD_KEY.into(), thread.clone());
}
if task_id.is_some() {
entry.task_id.clone_from(&task_id);
}
}
}
if matched {
state
.legacy_tally
.entry(address.clone())
.or_default()
.matched += 1;
}
}
state.cursors.insert(address.clone(), seq);
Ok(Some((address, seq)))
}
#[cfg(test)]
#[path = "relay_v2_tests.rs"]
mod tests;