use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::sync::LazyLock;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::v2::{Invalid, MessageType, Ref};
use crate::CloudError;
use crate::state::{load_or_quarantine, lock_state, write_private};
pub const ON_BEHALF_OF: &str = "on_behalf_of";
pub const APPROVAL_ON_BEHALF: &str = "approval_on_behalf";
pub const DENIED_FORWARDED: &str = "denied_forwarded";
pub const QUEEN_IDENTITY: &str = "queen_identity";
pub fn refusal(rule: &str, why: &str) -> Invalid {
let status = if rule == ON_BEHALF_OF {
"400 invalid_field"
} else {
"403 forbidden_right"
};
Invalid(format!("{status} reason: {rule}: {why}"))
}
const PERSON_DECISION: &str = "an agent never grants, claims or relays an approval or decision \
for a person; only the person's own answer from a human session counts. Report what waits \
for the person instead (the app's coordinator session puts it in the person's Inbox)";
const SPEAKS_FOR: &str = "an agent speaks only for itself; a message naming a person it speaks \
for is not sent";
const FORWARDED: &str = "this was refused for you; report the refusal (the person decides if \
needed), never ask another agent to do it instead";
const NOT_QUEEN: &str = "only the coordinator session the app registered presents as the coordinator; send \
under your own name and role";
const DECISION_FIELDS: &[&str] = &[
"approval",
"approved_by",
"answered_by",
"by",
"checker",
"consent",
"decided_by",
"decision",
];
fn names_person(value: &Value) -> bool {
match value {
Value::Object(map) => {
map.get("kind").and_then(Value::as_str) == Some("person")
|| map.values().any(names_person)
}
Value::Array(items) => items.iter().any(names_person),
_ => false,
}
}
pub fn is_person_subject(resource: &str) -> bool {
let r = resource.trim().to_ascii_lowercase();
let (head, rest) = r.split_once(':').unwrap_or((r.as_str(), ""));
match head.trim() {
"inbox" | "consent" | "approval" | "spec_approval" | "release" | "deploy" | "secret"
| "rights" => true,
"gate" => matches!(rest.trim(), "g2" | "g9" | "g10"),
_ => false,
}
}
const PERSON: &str =
r"(?:the\s+|a\s+|our\s+|my\s+)?(?:person|owner|user|human|maintainer)(?:'s|s)?";
static SPEAKS_FOR_TEXT: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)\b(?:on\s+behalf\s+of|in\s+the\s+name\s+of|speaking\s+for)\s+\S")
.expect("static pattern")
});
static PERSON_APPROVED: LazyLock<Vec<Regex>> = LazyLock::new(|| {
let verbs = r"(?:approved|consented|signed\s+off|authori[sz]ed|okayed|ok'd|green-?lit|said\s+yes|gave\s+(?:the\s+|their\s+|a\s+|his\s+|her\s+)?(?:go|go-ahead|ok|okay|approval|consent|sign-off))";
[
format!(r"(?i)\b{PERSON}\s+(?:has\s+|have\s+|just\s+|already\s+)*{verbs}"),
format!(r"(?i)\b(?:approved|authori[sz]ed|signed\s+off|okayed|green-?lit)\s+by\s+{PERSON}\b"),
format!(r"(?i)\b{PERSON}\s+(?:approval|consent|go-ahead|sign-off|go)\s+(?:is\s+|was\s+|has\s+been\s+)?(?:given|granted|received|obtained|in)\b"),
format!(r"(?i)\bwith\s+{PERSON}\s+(?:approval|consent|go-ahead|sign-off|blessing|ok)\b"),
format!(r"(?i)\b(?:approve[sd]?|consent(?:ed)?|authori[sz]e[sd]?)\s+(?:this\s+|it\s+)?(?:for|as)\s+{PERSON}\b"),
r"(?i)\b(?:owner|person)(?:'s)?\s+go\b".to_owned(),
]
.iter()
.map(|p| Regex::new(p).expect("static pattern"))
.collect()
});
static OPEN: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?i)\b(?:not|never|no|without|wait|waits|waiting|await|awaits|awaiting|need|needs|needed|require|requires|required|pending|missing|ask|asks|asking|request|requests|requested|until|before|unless|if|whether|once)\b|n't\b",
)
.expect("static pattern")
});
fn statements(text: &str) -> impl Iterator<Item = &str> {
let mut out = Vec::new();
let mut start = 0;
for (i, c) in text.char_indices() {
if matches!(c, '.' | '!' | '?' | ';' | '\n') {
if c != '?' {
out.push(&text[start..i]);
}
start = i + c.len_utf8();
}
}
out.push(&text[start..]);
out.into_iter().filter(|s| !s.trim().is_empty())
}
pub fn text_rule(text: &str) -> Option<&'static str> {
if SPEAKS_FOR_TEXT.is_match(text) {
return Some(ON_BEHALF_OF);
}
statements(text)
.filter(|s| !OPEN.is_match(s))
.any(|s| PERSON_APPROVED.iter().any(|re| re.is_match(s)))
.then_some(APPROVAL_ON_BEHALF)
}
fn texts(kind: MessageType, body: &Value) -> Vec<&str> {
let fields: &[&str] = match kind {
MessageType::Question | MessageType::Answer => &["text"],
MessageType::Offer => &["what"],
MessageType::Handoff => &["note", "resource"],
MessageType::Finding | MessageType::Progress => &[],
};
fields.iter().filter_map(|f| body[*f].as_str()).collect()
}
pub fn check_agent_body(kind: MessageType, body: &Value) -> Result<(), Invalid> {
if let Some(map) = body.as_object() {
if map.contains_key(ON_BEHALF_OF) {
return Err(refusal(ON_BEHALF_OF, SPEAKS_FOR));
}
if let Some(field) = DECISION_FIELDS.iter().find(|f| {
map.get(**f).is_some_and(|v| {
!v.is_null()
&& (matches!(**f, "approval" | "approved_by" | "answered_by" | "consent")
|| names_person(v))
})
}) {
return Err(refusal(
APPROVAL_ON_BEHALF,
&format!("{field}: {PERSON_DECISION}"),
));
}
}
if kind == MessageType::Handoff && body["resource"].as_str().is_some_and(is_person_subject) {
return Err(refusal(
APPROVAL_ON_BEHALF,
&format!("a person's decision is not handed over: {PERSON_DECISION}"),
));
}
if let Some(rule) = texts(kind, body).into_iter().find_map(text_rule) {
let why = if rule == ON_BEHALF_OF {
SPEAKS_FOR
} else {
PERSON_DECISION
};
return Err(refusal(rule, why));
}
Ok(())
}
pub fn fold(text: &str) -> String {
Folded::of(text, Blank::Space).text
}
#[derive(Debug, Clone, Copy)]
enum Blank {
Space,
Drop,
}
fn is_visible_blank(c: char) -> bool {
matches!(
c,
'\u{115F}' | '\u{1160}' | '\u{3164}' | '\u{FFA0}' | '\u{2800}'
)
}
fn is_invisible(c: char) -> bool {
use unicode_general_category::{GeneralCategory, get_general_category};
static IGNORABLE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^\p{Default_Ignorable_Code_Point}$").expect("static pattern")
});
let mut buf = [0u8; 4];
get_general_category(c) == GeneralCategory::Format
|| IGNORABLE.is_match(c.encode_utf8(&mut buf))
}
fn latin_skeleton(c: char) -> Option<String> {
if c.is_ascii() {
return None;
}
let mut buf = [0u8; 4];
let mut out = String::new();
for d in unicode_security::skeleton(c.encode_utf8(&mut buf)) {
if !d.is_ascii_graphic() {
return None;
}
out.push(if d == 'l' { 'I' } else { d });
}
if out.is_empty() {
return None;
}
Some(out.replace("rn", "m"))
}
struct Folded {
text: String,
origin: Vec<(usize, usize)>,
}
impl Folded {
fn of(text: &str, blanks: Blank) -> Self {
use unicode_normalization::UnicodeNormalization as _;
let mut out = Self {
text: String::with_capacity(text.len()),
origin: Vec::with_capacity(text.len()),
};
for (at, c) in text.char_indices() {
let range = (at, at + c.len_utf8());
if !is_visible_blank(c)
&& !is_invisible(c)
&& let Some(ascii) = latin_skeleton(c)
{
out.push_str(&ascii, range);
continue;
}
for d in std::iter::once(c).nfkc() {
if is_visible_blank(d) {
if matches!(blanks, Blank::Space) {
out.push_str(" ", range);
}
} else if !is_invisible(d) {
match latin_skeleton(d) {
Some(ascii) => out.push_str(&ascii, range),
None => out.push_str(d.encode_utf8(&mut [0u8; 4]), range),
}
}
}
}
out
}
fn push_str(&mut self, folded: &str, range: (usize, usize)) {
self.text.push_str(folded);
self.origin.extend(std::iter::repeat_n(range, folded.len()));
}
fn both(text: &str) -> [Self; 2] {
[Self::of(text, Blank::Space), Self::of(text, Blank::Drop)]
}
fn original(&self, start: usize, end: usize) -> (usize, usize) {
(self.origin[start].0, self.origin[end - 1].1)
}
}
static QUEEN_WORD: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)\bqueen\b").expect("static pattern"));
static QUEEN_LABEL: LazyLock<Vec<Regex>> = LazyLock::new(|| {
[
r"(?im)^\s*[\[(]?\s*(?:a\s+)?(?:message|note|word|instruction|order)?\s*from\s+(?:the\s+)?queen\b",
r"(?im)^\s*[\[(]?\s*(?:the\s+)?queen\s*[\])]?\s*(?::|—|–|\s-\s)",
r"(?im)^\s*[\[(]\s*(?:the\s+)?queen\s*[\])]",
r"(?i)\b(?:i\s+am|i'm|this\s+is|speaking\s+as|signed,?)\s+(?:the\s+)?queen\b",
r"(?im)\s[—–-]\s*(?:the\s+)?queen\s*$",
]
.iter()
.map(|p| Regex::new(p).expect("static pattern"))
.collect()
});
#[derive(Debug, Clone, Copy, Default)]
pub struct Speaker<'a> {
pub agent_id: Option<&'a str>,
pub role: Option<&'a str>,
pub display_name: Option<&'a str>,
pub registered_queen: bool,
}
impl<'a> Speaker<'a> {
pub fn of(agent: Option<&'a lean_ctx::core::agents::AgentEntry>) -> Self {
Self {
agent_id: agent.map(|a| a.agent_id.as_str()),
role: agent.and_then(|a| a.role.as_deref()),
display_name: agent.and_then(|a| a.display_name.as_deref()),
registered_queen: agent.is_some_and(registered_queen),
}
}
pub fn of_registry(
registry: &'a lean_ctx::core::agents::AgentRegistry,
agent_id: Option<&str>,
) -> Self {
let entry = agent_id.and_then(|id| registry.agents.iter().find(|a| a.agent_id == id));
let mut speaker = Self::of(entry);
speaker.registered_queen = speaker.registered_queen
&& agent_id
.is_some_and(|id| registry.list_active(None).iter().any(|a| a.agent_id == id));
speaker
}
pub fn mark(&self) -> String {
let agent = self.agent_id.unwrap_or("unregistered");
format!(
"{MARK_PREFIX}{}, agent {}, role {}]",
mark_field(self.display_name.unwrap_or(agent)),
mark_field(agent),
mark_field(self.role.unwrap_or("none"))
)
}
}
pub const MARK_FIELD_MAX: usize = 80;
fn mark_field(field: &str) -> String {
let mut out = String::new();
for (n, c) in field.trim().chars().enumerate() {
if n == MARK_FIELD_MAX {
out.pop();
out.push('…');
break;
}
let folded = fold(c.encode_utf8(&mut [0u8; 4]));
let c = if folded.contains('[') {
'('
} else if folded.contains(']') {
')'
} else if c.is_control() || c.is_whitespace() {
' '
} else {
c
};
out.push(c);
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueenMode {
Warn,
Enforce,
}
pub const QUEEN_MODE_ENV: &str = "LEAN_CTX_CLOUD_QUEEN_IDENTITY";
pub const MARK_PREFIX: &str = "[unverified Queen sender: ";
impl QueenMode {
pub fn parse(config: Option<&str>, env: Option<&str>) -> Self {
match env.or(config).map(|v| v.trim().to_ascii_lowercase()) {
None => Self::Warn,
Some(v) if v == "warn" => Self::Warn,
Some(_) => Self::Enforce,
}
}
pub fn current() -> Self {
let env = std::env::var(QUEEN_MODE_ENV).ok();
let config = lean_ctx::core::config::Config::load().cloud.queen_identity;
Self::parse(config.as_deref(), env.as_deref())
}
pub fn as_str(self) -> &'static str {
match self {
Self::Warn => "warn",
Self::Enforce => "enforce",
}
}
}
static MARK_LIKE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)\[\s*unver[il1|]f[il1|]ed\s*queen\s*sender\s*:").expect("static pattern")
});
const NEUTRALISED: &str = "[text of the sender, not a mark: unverified Queen sender:";
pub fn neutralise_marks(text: &str) -> String {
let spaced = neutralise_in(text, Blank::Space);
neutralise_in(&spaced, Blank::Drop)
}
fn neutralise_in(text: &str, blanks: Blank) -> String {
let folded = Folded::of(text, blanks);
let mut out = String::with_capacity(text.len());
let mut kept = 0;
for m in MARK_LIKE.find_iter(&folded.text) {
let (start, end) = folded.original(m.start(), m.end());
let start = start.max(kept);
out.push_str(&text[kept..start]);
out.push_str(NEUTRALISED);
kept = end.max(kept);
}
out.push_str(&text[kept..]);
out
}
pub fn marked(mark: &str, text: &str) -> String {
let rest = text
.strip_prefix(mark)
.map_or(text, |rest| rest.strip_prefix(' ').unwrap_or(rest));
format!("{mark} {}", neutralise_marks(rest))
}
pub const TEXT_TOO_LONG: &str = "text_too_long";
pub fn check_sent_length(kind: MessageType, written: &str, sent: &str) -> Result<(), Invalid> {
let Some(max) = super::v2::text_max(kind) else {
return Ok(());
};
let (written, sent) = (written.trim(), sent.trim());
let n = sent.chars().count();
if n <= max {
return Ok(());
}
let mark = if sent == written {
String::new()
} else {
let share = n.saturating_sub(written.chars().count());
format!(" with the receiver's mark in front ({share} of them)")
};
Err(Invalid(format!(
"400 invalid_field reason: {TEXT_TOO_LONG}: the text is {n} characters{mark}; a {} \
carries at most {max}: shorten it by {} and send it again",
format!("{kind:?}").to_ascii_lowercase(),
n - max
)))
}
pub fn cut_to_fit(text: &str, max: usize) -> String {
let n = text.chars().count();
if n <= max {
return text.to_owned();
}
let note = |cut: usize| format!(" [cut on sending: {cut} more characters did not fit]");
let mut keep = max;
loop {
let fits = max.saturating_sub(note(n - keep).chars().count());
if fits >= keep {
break;
}
keep = fits;
}
let mut out: String = text.chars().take(keep).collect();
out.push_str(¬e(n - keep));
out
}
pub fn labels_queen(text: &str) -> bool {
Folded::both(text).iter().any(|folded| {
let text = &folded.text;
MARK_LIKE.is_match(text) || QUEEN_LABEL.iter().any(|re| re.is_match(text))
})
}
fn says_queen(name: &str) -> bool {
Folded::both(name)
.iter()
.any(|folded| QUEEN_WORD.is_match(&folded.text))
}
pub fn check_queen(sender: Speaker<'_>, texts: &[&str]) -> Result<(), Invalid> {
if sender.registered_queen {
return Ok(());
}
let what = if sender.role.is_some_and(says_queen) {
"role queen"
} else if sender.display_name.is_some_and(says_queen) {
"the display name Queen"
} else if texts.iter().any(|t| labels_queen(t)) {
"a \"from the Queen\" label"
} else {
return Ok(());
};
Err(refusal(QUEEN_IDENTITY, &format!("{what}: {NOT_QUEEN}")))
}
pub fn registered_queen_in(dir: &Path, agent: &lean_ctx::core::agents::AgentEntry) -> bool {
agent.parent.is_none()
&& agent.status != lean_ctx::core::agents::AgentStatus::Finished
&& agent
.app_session_id
.as_deref()
.is_some_and(|id| crate::queens::is_queen_in(dir, id))
}
pub fn registered_queen(agent: &lean_ctx::core::agents::AgentEntry) -> bool {
crate::queens::data_dir().is_ok_and(|dir| registered_queen_in(&dir, agent))
}
pub fn queen_rule(
sender: Speaker<'_>,
texts: &[&str],
mode: QueenMode,
) -> Result<Option<String>, Invalid> {
match (check_queen(sender, texts), mode) {
(Ok(()), _) => Ok(None),
(Err(refused), QueenMode::Enforce) => Err(refused),
(Err(_), QueenMode::Warn) => Ok(Some(sender.mark())),
}
}
pub fn apply_queen_rule(
data_dir: &Path,
sender: Speaker<'_>,
texts: &[&str],
text: &str,
limit: Option<MessageType>,
mode: QueenMode,
) -> Result<String, Invalid> {
let Some(mark) = queen_rule(sender, texts, mode)? else {
if let Some(kind) = limit {
check_sent_length(kind, text, text)?;
}
return Ok(text.to_owned());
};
let sent = marked(&mark, text);
if let Some(kind) = limit {
check_sent_length(kind, text, &sent)?;
}
note_queen_warning(data_dir, sender.agent_id, &mark).map_err(|error| {
refusal(
QUEEN_IDENTITY,
&format!(
"an unverified coordinator sender is logged before it is sent; not logged: {error}"
),
)
})?;
Ok(sent)
}
fn relayed_kind(category: &str, to: Option<&str>) -> Option<MessageType> {
let kind = post_body(category, "")?.0;
(kind == MessageType::Question
&& matches!(
super::address::Address::parse(to),
Ok(super::address::Address::Vault { .. })
))
.then_some(kind)
}
pub fn check_local_post_in(
data_dir: &Path,
sender: Speaker<'_>,
worker_id: Option<&str>,
category: &str,
text: &str,
mode: QueenMode,
) -> Result<String, Invalid> {
check_local_post_to_in(data_dir, sender, worker_id, category, None, text, mode)
}
pub fn check_local_post_to_in(
data_dir: &Path,
sender: Speaker<'_>,
worker_id: Option<&str>,
category: &str,
to: Option<&str>,
text: &str,
mode: QueenMode,
) -> Result<String, Invalid> {
if let Some((kind, body)) = post_body(category, text) {
check_agent_body(kind, &body)?;
check_not_refused_in(
data_dir,
kind,
&[],
&body,
sender.agent_id.unwrap_or_default(),
worker_id.unwrap_or_default(),
)?;
}
apply_queen_rule(
data_dir,
sender,
&[text],
text,
relayed_kind(category, to),
mode,
)
}
pub fn check_local_post(
registry: &lean_ctx::core::agents::AgentRegistry,
agent_id: Option<&str>,
category: &str,
to: Option<&str>,
text: &str,
) -> Result<String, Invalid> {
let sender = Speaker::of_registry(registry, agent_id);
let mode = QueenMode::current();
let needs_records = post_body(category, text).is_some_and(|(kind, _)| asks_to_act(kind));
if !needs_records && queen_rule(sender, &[text], mode)?.is_none() {
if let Some((kind, body)) = post_body(category, text) {
check_agent_body(kind, &body)?;
}
if let Some(kind) = relayed_kind(category, to) {
check_sent_length(kind, text, text)?;
}
return Ok(text.to_owned());
}
let store = crate::CloudStore::open().map_err(|error| {
refusal(
if needs_records {
DENIED_FORWARDED
} else {
QUEEN_IDENTITY
},
&format!("the Cloud records cannot be opened, so this post is not sent: {error}"),
)
})?;
let worker_id = agent_id.and_then(|id| super::messages_v2::known_worker_of(&store, id));
check_local_post_to_in(
store.data_dir(),
sender,
worker_id.as_deref(),
category,
to,
text,
mode,
)
}
pub fn post_body(category: &str, text: &str) -> Option<(MessageType, Value)> {
let kind = MessageType::parse(&category.trim().to_ascii_lowercase())?;
let field = match kind {
MessageType::Question | MessageType::Answer => "text",
MessageType::Offer => "what",
MessageType::Handoff => "note",
MessageType::Finding | MessageType::Progress => return None,
};
Some((kind, serde_json::json!({ field: text })))
}
pub fn check_not_refused_in(
data_dir: &Path,
kind: MessageType,
refs: &[Ref],
body: &Value,
agent_id: &str,
worker_id: &str,
) -> Result<(), Invalid> {
if !asks_to_act(kind) {
return Ok(());
}
let state = super::relay_v2::StateV2::read(data_dir).map_err(|_| records_unknown())?;
let ledger = RefusedLedger::read(data_dir).map_err(|_| records_unknown())?;
let refused = Refused::for_sender(
&state,
&super::handoff::Handoffs::load(data_dir),
&ledger,
&crate::resolution::current_view(data_dir, None),
agent_id,
worker_id,
);
check_forwarding(kind, refs, body, &refused)
}
fn records_unknown() -> Invalid {
refusal(
DENIED_FORWARDED,
"the record of refused actions cannot be read right now, so a message that asks another \
agent is not sent; retry shortly",
)
}
#[derive(Debug, Clone)]
pub struct Records {
pub handoffs: super::handoff::Handoffs,
pub ledger: Option<RefusedLedger>,
}
impl Default for Records {
fn default() -> Self {
Self {
handoffs: super::handoff::Handoffs::default(),
ledger: Some(RefusedLedger::default()),
}
}
}
impl Records {
pub fn load(data_dir: &Path) -> Self {
Self {
handoffs: super::handoff::Handoffs::load(data_dir),
ledger: RefusedLedger::read(data_dir).ok(),
}
}
}
const REFUSED_FILE: &str = "refused.json";
const MAX_REFUSED: usize = 1000;
const KEPT: lean_ctx_time::Duration = lean_ctx_time::Duration::days(7);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefusedAction {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender: Option<String>,
pub code: String,
pub at: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefusedLedger {
#[serde(default)]
pub refused: BTreeMap<String, RefusedAction>,
}
impl RefusedLedger {
fn path(data_dir: &Path) -> std::path::PathBuf {
data_dir.join("bus").join(REFUSED_FILE)
}
pub fn read(data_dir: &Path) -> Result<Self, CloudError> {
load_or_quarantine(&Self::path(data_dir), |_: &Self| true).map(Option::unwrap_or_default)
}
}
pub fn note_refused(
data_dir: &Path,
reference: &str,
sender: Option<&str>,
code: &str,
) -> Result<(), CloudError> {
let reference = reference.trim();
if reference.is_empty() {
return Ok(());
}
let now = lean_ctx_time::UtcDateTime::now();
let oldest = (now - KEPT).to_rfc3339();
change_file(data_dir, REFUSED_FILE, |ledger: &mut RefusedLedger| {
ledger.refused.retain(|_, r| r.at >= oldest);
ledger.refused.insert(
reference.to_owned(),
RefusedAction {
sender: sender.map(str::to_owned),
code: code.to_owned(),
at: now.to_rfc3339(),
},
);
while ledger.refused.len() > MAX_REFUSED {
let Some(first) = ledger
.refused
.iter()
.min_by(|a, b| a.1.at.cmp(&b.1.at))
.map(|(k, _)| k.clone())
else {
break;
};
ledger.refused.remove(&first);
}
})
}
fn change_file<T>(
data_dir: &Path,
name: &str,
change: impl FnOnce(&mut T),
) -> Result<(), CloudError>
where
T: Default + Serialize + serde::de::DeserializeOwned,
{
let dir = data_dir.join("bus");
let _lock = lock_state(&dir, name)?;
let path = dir.join(name);
let mut value: T = match load_or_quarantine(&path, |_: &T| true) {
Ok(value) => value.unwrap_or_default(),
Err(error) if path.exists() => return Err(error),
Err(error) => {
tracing::warn!("cloud bus: {error}");
T::default()
}
};
change(&mut value);
let bytes = serde_json::to_vec(&value).map_err(|e| CloudError::Local(e.to_string()))?;
write_private(&dir, name, &bytes)
}
const QUEEN_WARNINGS_FILE: &str = "queen-warnings.json";
const MAX_QUEEN_WARNINGS: usize = 1000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueenWarning {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender: Option<String>,
pub rule: String,
pub mode: String,
pub mark: String,
pub at: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueenWarnings {
#[serde(default)]
pub warnings: Vec<QueenWarning>,
}
impl QueenWarnings {
pub fn read(data_dir: &Path) -> Result<Self, CloudError> {
load_or_quarantine(
&data_dir.join("bus").join(QUEEN_WARNINGS_FILE),
|_: &Self| true,
)
.map(Option::unwrap_or_default)
}
}
pub fn note_queen_warning(
data_dir: &Path,
agent_id: Option<&str>,
mark: &str,
) -> Result<(), CloudError> {
let now = lean_ctx_time::UtcDateTime::now();
let oldest = (now - KEPT).to_rfc3339();
change_file(data_dir, QUEEN_WARNINGS_FILE, |log: &mut QueenWarnings| {
log.warnings.retain(|w| w.at >= oldest);
log.warnings.push(QueenWarning {
sender: agent_id.map(str::to_owned),
rule: QUEEN_IDENTITY.to_owned(),
mode: QueenMode::Warn.as_str().to_owned(),
mark: mark.to_owned(),
at: now.to_rfc3339(),
});
let over = log.warnings.len().saturating_sub(MAX_QUEEN_WARNINGS);
log.warnings.drain(..over);
})
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Refused {
ids: BTreeSet<String>,
}
const CONTAINED_MIN: usize = 16;
impl Refused {
pub fn insert(&mut self, id: &str) {
let id = id.trim();
if !id.is_empty() {
self.ids.insert(id.to_owned());
}
}
pub fn named_by(&self, target: &str) -> Option<&str> {
let target = target.trim();
self.ids
.iter()
.find(|id| {
target == id.as_str() || (id.len() >= CONTAINED_MIN && target.contains(id.as_str()))
})
.map(String::as_str)
}
pub fn for_sender(
state: &super::relay_v2::StateV2,
handoffs: &super::handoff::Handoffs,
ledger: &RefusedLedger,
map: &crate::vault::VaultMap,
agent_id: &str,
worker_id: &str,
) -> Self {
let mut out = Self::default();
for place in state.denied.keys() {
out.insert(place);
if let Some((_, id)) = place.split_once(':') {
out.insert(id);
if let Some(record) = map.vaults.values().find(|r| r.vault_id == id) {
out.insert(&super::relay_v2::address_of(record));
}
}
}
for control in state.controls.values() {
if control.action == super::v2::ControlAction::Veto
&& let Some(r) = &control.target_ref
{
out.insert(&r.id);
}
}
for (client_msg_id, offer) in &handoffs.offers {
if offer.from == agent_id
&& matches!(offer.state, super::handoff::OfferState::Vetoed { .. })
{
out.insert(client_msg_id);
if let Some(id) = &offer.msg_id {
out.insert(id);
}
}
}
for (reference, action) in &ledger.refused {
if action
.sender
.as_deref()
.is_none_or(|s| s == agent_id || s == worker_id)
{
out.insert(reference);
}
}
out
}
}
pub fn check_forwarding(
kind: MessageType,
refs: &[Ref],
body: &Value,
refused: &Refused,
) -> Result<(), Invalid> {
if !asks_to_act(kind) {
return Ok(());
}
let named = refs
.iter()
.map(|r| r.target.as_str())
.chain(body["resource"].as_str())
.chain(texts(kind, body))
.find_map(|t| refused.named_by(t));
match named {
Some(id) => Err(refusal(
DENIED_FORWARDED,
&format!("{id} was refused: {FORWARDED}"),
)),
None => Ok(()),
}
}
pub fn asks_to_act(kind: MessageType) -> bool {
matches!(
kind,
MessageType::Question | MessageType::Offer | MessageType::Handoff
)
}
#[cfg(test)]
#[path = "person_rules_tests.rs"]
mod tests;