1use std::collections::{BTreeMap, BTreeSet};
79use std::path::Path;
80use std::sync::LazyLock;
81
82use regex::Regex;
83use serde::{Deserialize, Serialize};
84use serde_json::Value;
85
86use super::v2::{Invalid, MessageType, Ref};
87use crate::CloudError;
88use crate::state::{load_or_quarantine, lock_state, write_private};
89
90pub const ON_BEHALF_OF: &str = "on_behalf_of";
91pub const APPROVAL_ON_BEHALF: &str = "approval_on_behalf";
92pub const DENIED_FORWARDED: &str = "denied_forwarded";
93pub const QUEEN_IDENTITY: &str = "queen_identity";
94
95pub fn refusal(rule: &str, why: &str) -> Invalid {
97 let status = if rule == ON_BEHALF_OF {
98 "400 invalid_field"
99 } else {
100 "403 forbidden_right"
101 };
102 Invalid(format!("{status} reason: {rule}: {why}"))
103}
104
105const PERSON_DECISION: &str = "an agent never grants, claims or relays an approval or decision \
106 for a person; only the person's own answer from a human session counts. Report what waits \
107 for the person instead (the app's coordinator session puts it in the person's Inbox)";
108const SPEAKS_FOR: &str = "an agent speaks only for itself; a message naming a person it speaks \
109 for is not sent";
110const FORWARDED: &str = "this was refused for you; report the refusal (the person decides if \
111 needed), never ask another agent to do it instead";
112const NOT_QUEEN: &str = "only the coordinator session the app registered presents as the coordinator; send \
113 under your own name and role";
114
115const DECISION_FIELDS: &[&str] = &[
119 "approval",
120 "approved_by",
121 "answered_by",
122 "by",
123 "checker",
124 "consent",
125 "decided_by",
126 "decision",
127];
128
129fn names_person(value: &Value) -> bool {
130 match value {
131 Value::Object(map) => {
132 map.get("kind").and_then(Value::as_str) == Some("person")
133 || map.values().any(names_person)
134 }
135 Value::Array(items) => items.iter().any(names_person),
136 _ => false,
137 }
138}
139
140pub fn is_person_subject(resource: &str) -> bool {
142 let r = resource.trim().to_ascii_lowercase();
143 let (head, rest) = r.split_once(':').unwrap_or((r.as_str(), ""));
144 match head.trim() {
145 "inbox" | "consent" | "approval" | "spec_approval" | "release" | "deploy" | "secret"
146 | "rights" => true,
147 "gate" => matches!(rest.trim(), "g2" | "g9" | "g10"),
148 _ => false,
149 }
150}
151
152const PERSON: &str =
155 r"(?:the\s+|a\s+|our\s+|my\s+)?(?:person|owner|user|human|maintainer)(?:'s|s)?";
156
157static SPEAKS_FOR_TEXT: LazyLock<Regex> = LazyLock::new(|| {
158 Regex::new(r"(?i)\b(?:on\s+behalf\s+of|in\s+the\s+name\s+of|speaking\s+for)\s+\S")
159 .expect("static pattern")
160});
161
162static PERSON_APPROVED: LazyLock<Vec<Regex>> = LazyLock::new(|| {
163 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))";
164 [
165 format!(r"(?i)\b{PERSON}\s+(?:has\s+|have\s+|just\s+|already\s+)*{verbs}"),
166 format!(r"(?i)\b(?:approved|authori[sz]ed|signed\s+off|okayed|green-?lit)\s+by\s+{PERSON}\b"),
167 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"),
168 format!(r"(?i)\bwith\s+{PERSON}\s+(?:approval|consent|go-ahead|sign-off|blessing|ok)\b"),
169 format!(r"(?i)\b(?:approve[sd]?|consent(?:ed)?|authori[sz]e[sd]?)\s+(?:this\s+|it\s+)?(?:for|as)\s+{PERSON}\b"),
170 r"(?i)\b(?:owner|person)(?:'s)?\s+go\b".to_owned(),
171 ]
172 .iter()
173 .map(|p| Regex::new(p).expect("static pattern"))
174 .collect()
175});
176
177static OPEN: LazyLock<Regex> = LazyLock::new(|| {
179 Regex::new(
180 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",
181 )
182 .expect("static pattern")
183});
184
185fn statements(text: &str) -> impl Iterator<Item = &str> {
187 let mut out = Vec::new();
188 let mut start = 0;
189 for (i, c) in text.char_indices() {
190 if matches!(c, '.' | '!' | '?' | ';' | '\n') {
191 if c != '?' {
192 out.push(&text[start..i]);
193 }
194 start = i + c.len_utf8();
195 }
196 }
197 out.push(&text[start..]);
198 out.into_iter().filter(|s| !s.trim().is_empty())
199}
200
201pub fn text_rule(text: &str) -> Option<&'static str> {
204 if SPEAKS_FOR_TEXT.is_match(text) {
205 return Some(ON_BEHALF_OF);
206 }
207 statements(text)
208 .filter(|s| !OPEN.is_match(s))
209 .any(|s| PERSON_APPROVED.iter().any(|re| re.is_match(s)))
210 .then_some(APPROVAL_ON_BEHALF)
211}
212
213fn texts(kind: MessageType, body: &Value) -> Vec<&str> {
215 let fields: &[&str] = match kind {
216 MessageType::Question | MessageType::Answer => &["text"],
217 MessageType::Offer => &["what"],
218 MessageType::Handoff => &["note", "resource"],
219 MessageType::Finding | MessageType::Progress => &[],
220 };
221 fields.iter().filter_map(|f| body[*f].as_str()).collect()
222}
223
224pub fn check_agent_body(kind: MessageType, body: &Value) -> Result<(), Invalid> {
227 if let Some(map) = body.as_object() {
228 if map.contains_key(ON_BEHALF_OF) {
229 return Err(refusal(ON_BEHALF_OF, SPEAKS_FOR));
230 }
231 if let Some(field) = DECISION_FIELDS.iter().find(|f| {
232 map.get(**f).is_some_and(|v| {
233 !v.is_null()
234 && (matches!(**f, "approval" | "approved_by" | "answered_by" | "consent")
235 || names_person(v))
236 })
237 }) {
238 return Err(refusal(
239 APPROVAL_ON_BEHALF,
240 &format!("{field}: {PERSON_DECISION}"),
241 ));
242 }
243 }
244 if kind == MessageType::Handoff && body["resource"].as_str().is_some_and(is_person_subject) {
245 return Err(refusal(
246 APPROVAL_ON_BEHALF,
247 &format!("a person's decision is not handed over: {PERSON_DECISION}"),
248 ));
249 }
250 if let Some(rule) = texts(kind, body).into_iter().find_map(text_rule) {
251 let why = if rule == ON_BEHALF_OF {
252 SPEAKS_FOR
253 } else {
254 PERSON_DECISION
255 };
256 return Err(refusal(rule, why));
257 }
258 Ok(())
259}
260
261pub fn fold(text: &str) -> String {
274 Folded::of(text, Blank::Space).text
275}
276
277#[derive(Debug, Clone, Copy)]
280enum Blank {
281 Space,
282 Drop,
283}
284
285fn is_visible_blank(c: char) -> bool {
288 matches!(
289 c,
290 '\u{115F}' | '\u{1160}' | '\u{3164}' | '\u{FFA0}' | '\u{2800}'
291 )
292}
293
294fn is_invisible(c: char) -> bool {
297 use unicode_general_category::{GeneralCategory, get_general_category};
298 static IGNORABLE: LazyLock<Regex> = LazyLock::new(|| {
299 Regex::new(r"^\p{Default_Ignorable_Code_Point}$").expect("static pattern")
300 });
301 let mut buf = [0u8; 4];
302 get_general_category(c) == GeneralCategory::Format
303 || IGNORABLE.is_match(c.encode_utf8(&mut buf))
304}
305
306fn latin_skeleton(c: char) -> Option<String> {
321 if c.is_ascii() {
322 return None;
323 }
324 let mut buf = [0u8; 4];
325 let mut out = String::new();
326 for d in unicode_security::skeleton(c.encode_utf8(&mut buf)) {
327 if !d.is_ascii_graphic() {
328 return None;
329 }
330 out.push(if d == 'l' { 'I' } else { d });
331 }
332 if out.is_empty() {
333 return None;
334 }
335 Some(out.replace("rn", "m"))
336}
337
338struct Folded {
341 text: String,
342 origin: Vec<(usize, usize)>,
343}
344
345impl Folded {
346 fn of(text: &str, blanks: Blank) -> Self {
347 use unicode_normalization::UnicodeNormalization as _;
348 let mut out = Self {
349 text: String::with_capacity(text.len()),
350 origin: Vec::with_capacity(text.len()),
351 };
352 for (at, c) in text.char_indices() {
353 let range = (at, at + c.len_utf8());
354 if !is_visible_blank(c)
357 && !is_invisible(c)
358 && let Some(ascii) = latin_skeleton(c)
359 {
360 out.push_str(&ascii, range);
361 continue;
362 }
363 for d in std::iter::once(c).nfkc() {
364 if is_visible_blank(d) {
366 if matches!(blanks, Blank::Space) {
367 out.push_str(" ", range);
368 }
369 } else if !is_invisible(d) {
370 match latin_skeleton(d) {
371 Some(ascii) => out.push_str(&ascii, range),
372 None => out.push_str(d.encode_utf8(&mut [0u8; 4]), range),
373 }
374 }
375 }
376 }
377 out
378 }
379
380 fn push_str(&mut self, folded: &str, range: (usize, usize)) {
382 self.text.push_str(folded);
383 self.origin.extend(std::iter::repeat_n(range, folded.len()));
384 }
385
386 fn both(text: &str) -> [Self; 2] {
389 [Self::of(text, Blank::Space), Self::of(text, Blank::Drop)]
390 }
391
392 fn original(&self, start: usize, end: usize) -> (usize, usize) {
395 (self.origin[start].0, self.origin[end - 1].1)
396 }
397}
398
399static QUEEN_WORD: LazyLock<Regex> =
400 LazyLock::new(|| Regex::new(r"(?i)\bqueen\b").expect("static pattern"));
401
402static QUEEN_LABEL: LazyLock<Vec<Regex>> = LazyLock::new(|| {
403 [
404 r"(?im)^\s*[\[(]?\s*(?:a\s+)?(?:message|note|word|instruction|order)?\s*from\s+(?:the\s+)?queen\b",
405 r"(?im)^\s*[\[(]?\s*(?:the\s+)?queen\s*[\])]?\s*(?::|—|–|\s-\s)",
406 r"(?im)^\s*[\[(]\s*(?:the\s+)?queen\s*[\])]",
407 r"(?i)\b(?:i\s+am|i'm|this\s+is|speaking\s+as|signed,?)\s+(?:the\s+)?queen\b",
408 r"(?im)\s[—–-]\s*(?:the\s+)?queen\s*$",
409 ]
410 .iter()
411 .map(|p| Regex::new(p).expect("static pattern"))
412 .collect()
413});
414
415#[derive(Debug, Clone, Copy, Default)]
417pub struct Speaker<'a> {
418 pub agent_id: Option<&'a str>,
420 pub role: Option<&'a str>,
421 pub display_name: Option<&'a str>,
422 pub registered_queen: bool,
424}
425
426impl<'a> Speaker<'a> {
427 pub fn of(agent: Option<&'a lean_ctx::core::agents::AgentEntry>) -> Self {
429 Self {
430 agent_id: agent.map(|a| a.agent_id.as_str()),
431 role: agent.and_then(|a| a.role.as_deref()),
432 display_name: agent.and_then(|a| a.display_name.as_deref()),
433 registered_queen: agent.is_some_and(registered_queen),
434 }
435 }
436
437 pub fn of_registry(
442 registry: &'a lean_ctx::core::agents::AgentRegistry,
443 agent_id: Option<&str>,
444 ) -> Self {
445 let entry = agent_id.and_then(|id| registry.agents.iter().find(|a| a.agent_id == id));
446 let mut speaker = Self::of(entry);
447 speaker.registered_queen = speaker.registered_queen
448 && agent_id
449 .is_some_and(|id| registry.list_active(None).iter().any(|a| a.agent_id == id));
450 speaker
451 }
452
453 pub fn mark(&self) -> String {
458 let agent = self.agent_id.unwrap_or("unregistered");
459 format!(
460 "{MARK_PREFIX}{}, agent {}, role {}]",
461 mark_field(self.display_name.unwrap_or(agent)),
462 mark_field(agent),
463 mark_field(self.role.unwrap_or("none"))
464 )
465 }
466}
467
468pub const MARK_FIELD_MAX: usize = 80;
470
471fn mark_field(field: &str) -> String {
475 let mut out = String::new();
476 for (n, c) in field.trim().chars().enumerate() {
477 if n == MARK_FIELD_MAX {
478 out.pop();
479 out.push('…');
480 break;
481 }
482 let folded = fold(c.encode_utf8(&mut [0u8; 4]));
483 let c = if folded.contains('[') {
484 '('
485 } else if folded.contains(']') {
486 ')'
487 } else if c.is_control() || c.is_whitespace() {
488 ' '
489 } else {
490 c
491 };
492 out.push(c);
493 }
494 out
495}
496
497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
499pub enum QueenMode {
500 Warn,
502 Enforce,
504}
505
506pub const QUEEN_MODE_ENV: &str = "LEAN_CTX_CLOUD_QUEEN_IDENTITY";
508pub const MARK_PREFIX: &str = "[unverified Queen sender: ";
510
511impl QueenMode {
512 pub fn parse(config: Option<&str>, env: Option<&str>) -> Self {
516 match env.or(config).map(|v| v.trim().to_ascii_lowercase()) {
517 None => Self::Warn,
518 Some(v) if v == "warn" => Self::Warn,
519 Some(_) => Self::Enforce,
520 }
521 }
522
523 pub fn current() -> Self {
525 let env = std::env::var(QUEEN_MODE_ENV).ok();
526 let config = lean_ctx::core::config::Config::load().cloud.queen_identity;
527 Self::parse(config.as_deref(), env.as_deref())
528 }
529
530 pub fn as_str(self) -> &'static str {
531 match self {
532 Self::Warn => "warn",
533 Self::Enforce => "enforce",
534 }
535 }
536}
537
538static MARK_LIKE: LazyLock<Regex> = LazyLock::new(|| {
544 Regex::new(r"(?i)\[\s*unver[il1|]f[il1|]ed\s*queen\s*sender\s*:").expect("static pattern")
545});
546
547const NEUTRALISED: &str = "[text of the sender, not a mark: unverified Queen sender:";
550
551pub fn neutralise_marks(text: &str) -> String {
555 let spaced = neutralise_in(text, Blank::Space);
558 neutralise_in(&spaced, Blank::Drop)
559}
560
561fn neutralise_in(text: &str, blanks: Blank) -> String {
562 let folded = Folded::of(text, blanks);
563 let mut out = String::with_capacity(text.len());
564 let mut kept = 0;
565 for m in MARK_LIKE.find_iter(&folded.text) {
566 let (start, end) = folded.original(m.start(), m.end());
567 let start = start.max(kept);
570 out.push_str(&text[kept..start]);
571 out.push_str(NEUTRALISED);
572 kept = end.max(kept);
573 }
574 out.push_str(&text[kept..]);
575 out
576}
577
578pub fn marked(mark: &str, text: &str) -> String {
584 let rest = text
585 .strip_prefix(mark)
586 .map_or(text, |rest| rest.strip_prefix(' ').unwrap_or(rest));
587 format!("{mark} {}", neutralise_marks(rest))
588}
589
590pub const TEXT_TOO_LONG: &str = "text_too_long";
592
593pub fn check_sent_length(kind: MessageType, written: &str, sent: &str) -> Result<(), Invalid> {
599 let Some(max) = super::v2::text_max(kind) else {
600 return Ok(());
601 };
602 let (written, sent) = (written.trim(), sent.trim());
604 let n = sent.chars().count();
605 if n <= max {
606 return Ok(());
607 }
608 let mark = if sent == written {
609 String::new()
610 } else {
611 let share = n.saturating_sub(written.chars().count());
612 format!(" with the receiver's mark in front ({share} of them)")
613 };
614 Err(Invalid(format!(
615 "400 invalid_field reason: {TEXT_TOO_LONG}: the text is {n} characters{mark}; a {} \
616 carries at most {max}: shorten it by {} and send it again",
617 format!("{kind:?}").to_ascii_lowercase(),
618 n - max
619 )))
620}
621
622pub fn cut_to_fit(text: &str, max: usize) -> String {
628 let n = text.chars().count();
629 if n <= max {
630 return text.to_owned();
631 }
632 let note = |cut: usize| format!(" [cut on sending: {cut} more characters did not fit]");
633 let mut keep = max;
636 loop {
637 let fits = max.saturating_sub(note(n - keep).chars().count());
638 if fits >= keep {
639 break;
640 }
641 keep = fits;
642 }
643 let mut out: String = text.chars().take(keep).collect();
644 out.push_str(¬e(n - keep));
645 out
646}
647
648pub fn labels_queen(text: &str) -> bool {
651 Folded::both(text).iter().any(|folded| {
652 let text = &folded.text;
653 MARK_LIKE.is_match(text) || QUEEN_LABEL.iter().any(|re| re.is_match(text))
655 })
656}
657
658fn says_queen(name: &str) -> bool {
660 Folded::both(name)
661 .iter()
662 .any(|folded| QUEEN_WORD.is_match(&folded.text))
663}
664
665pub fn check_queen(sender: Speaker<'_>, texts: &[&str]) -> Result<(), Invalid> {
668 if sender.registered_queen {
669 return Ok(());
670 }
671 let what = if sender.role.is_some_and(says_queen) {
672 "role queen"
673 } else if sender.display_name.is_some_and(says_queen) {
674 "the display name Queen"
675 } else if texts.iter().any(|t| labels_queen(t)) {
676 "a \"from the Queen\" label"
677 } else {
678 return Ok(());
679 };
680 Err(refusal(QUEEN_IDENTITY, &format!("{what}: {NOT_QUEEN}")))
681}
682
683pub fn registered_queen_in(dir: &Path, agent: &lean_ctx::core::agents::AgentEntry) -> bool {
687 agent.parent.is_none()
688 && agent.status != lean_ctx::core::agents::AgentStatus::Finished
689 && agent
690 .app_session_id
691 .as_deref()
692 .is_some_and(|id| crate::queens::is_queen_in(dir, id))
693}
694
695pub fn registered_queen(agent: &lean_ctx::core::agents::AgentEntry) -> bool {
697 crate::queens::data_dir().is_ok_and(|dir| registered_queen_in(&dir, agent))
698}
699
700pub fn queen_rule(
703 sender: Speaker<'_>,
704 texts: &[&str],
705 mode: QueenMode,
706) -> Result<Option<String>, Invalid> {
707 match (check_queen(sender, texts), mode) {
708 (Ok(()), _) => Ok(None),
709 (Err(refused), QueenMode::Enforce) => Err(refused),
710 (Err(_), QueenMode::Warn) => Ok(Some(sender.mark())),
711 }
712}
713
714pub fn apply_queen_rule(
720 data_dir: &Path,
721 sender: Speaker<'_>,
722 texts: &[&str],
723 text: &str,
724 limit: Option<MessageType>,
725 mode: QueenMode,
726) -> Result<String, Invalid> {
727 let Some(mark) = queen_rule(sender, texts, mode)? else {
728 if let Some(kind) = limit {
729 check_sent_length(kind, text, text)?;
730 }
731 return Ok(text.to_owned());
732 };
733 let sent = marked(&mark, text);
734 if let Some(kind) = limit {
736 check_sent_length(kind, text, &sent)?;
737 }
738 note_queen_warning(data_dir, sender.agent_id, &mark).map_err(|error| {
739 refusal(
740 QUEEN_IDENTITY,
741 &format!(
742 "an unverified coordinator sender is logged before it is sent; not logged: {error}"
743 ),
744 )
745 })?;
746 Ok(sent)
747}
748
749fn relayed_kind(category: &str, to: Option<&str>) -> Option<MessageType> {
754 let kind = post_body(category, "")?.0;
755 (kind == MessageType::Question
756 && matches!(
757 super::address::Address::parse(to),
758 Ok(super::address::Address::Vault { .. })
759 ))
760 .then_some(kind)
761}
762
763pub fn check_local_post_in(
772 data_dir: &Path,
773 sender: Speaker<'_>,
774 worker_id: Option<&str>,
775 category: &str,
776 text: &str,
777 mode: QueenMode,
778) -> Result<String, Invalid> {
779 check_local_post_to_in(data_dir, sender, worker_id, category, None, text, mode)
780}
781
782pub fn check_local_post_to_in(
786 data_dir: &Path,
787 sender: Speaker<'_>,
788 worker_id: Option<&str>,
789 category: &str,
790 to: Option<&str>,
791 text: &str,
792 mode: QueenMode,
793) -> Result<String, Invalid> {
794 if let Some((kind, body)) = post_body(category, text) {
795 check_agent_body(kind, &body)?;
796 check_not_refused_in(
797 data_dir,
798 kind,
799 &[],
800 &body,
801 sender.agent_id.unwrap_or_default(),
802 worker_id.unwrap_or_default(),
803 )?;
804 }
805 apply_queen_rule(
806 data_dir,
807 sender,
808 &[text],
809 text,
810 relayed_kind(category, to),
811 mode,
812 )
813}
814
815pub fn check_local_post(
819 registry: &lean_ctx::core::agents::AgentRegistry,
820 agent_id: Option<&str>,
821 category: &str,
822 to: Option<&str>,
823 text: &str,
824) -> Result<String, Invalid> {
825 let sender = Speaker::of_registry(registry, agent_id);
826 let mode = QueenMode::current();
827 let needs_records = post_body(category, text).is_some_and(|(kind, _)| asks_to_act(kind));
828 if !needs_records && queen_rule(sender, &[text], mode)?.is_none() {
829 if let Some((kind, body)) = post_body(category, text) {
831 check_agent_body(kind, &body)?;
832 }
833 if let Some(kind) = relayed_kind(category, to) {
834 check_sent_length(kind, text, text)?;
835 }
836 return Ok(text.to_owned());
837 }
838 let store = crate::CloudStore::open().map_err(|error| {
839 refusal(
840 if needs_records {
841 DENIED_FORWARDED
842 } else {
843 QUEEN_IDENTITY
844 },
845 &format!("the Cloud records cannot be opened, so this post is not sent: {error}"),
846 )
847 })?;
848 let worker_id = agent_id.and_then(|id| super::messages_v2::known_worker_of(&store, id));
849 check_local_post_to_in(
850 store.data_dir(),
851 sender,
852 worker_id.as_deref(),
853 category,
854 to,
855 text,
856 mode,
857 )
858}
859
860pub fn post_body(category: &str, text: &str) -> Option<(MessageType, Value)> {
863 let kind = MessageType::parse(&category.trim().to_ascii_lowercase())?;
864 let field = match kind {
865 MessageType::Question | MessageType::Answer => "text",
866 MessageType::Offer => "what",
867 MessageType::Handoff => "note",
868 MessageType::Finding | MessageType::Progress => return None,
869 };
870 Some((kind, serde_json::json!({ field: text })))
871}
872
873pub fn check_not_refused_in(
878 data_dir: &Path,
879 kind: MessageType,
880 refs: &[Ref],
881 body: &Value,
882 agent_id: &str,
883 worker_id: &str,
884) -> Result<(), Invalid> {
885 if !asks_to_act(kind) {
886 return Ok(());
887 }
888 let state = super::relay_v2::StateV2::read(data_dir).map_err(|_| records_unknown())?;
889 let ledger = RefusedLedger::read(data_dir).map_err(|_| records_unknown())?;
890 let refused = Refused::for_sender(
891 &state,
892 &super::handoff::Handoffs::load(data_dir),
893 &ledger,
894 &crate::resolution::current_view(data_dir, None),
897 agent_id,
898 worker_id,
899 );
900 check_forwarding(kind, refs, body, &refused)
901}
902
903fn records_unknown() -> Invalid {
904 refusal(
905 DENIED_FORWARDED,
906 "the record of refused actions cannot be read right now, so a message that asks another \
907 agent is not sent; retry shortly",
908 )
909}
910
911#[derive(Debug, Clone)]
915pub struct Records {
916 pub handoffs: super::handoff::Handoffs,
917 pub ledger: Option<RefusedLedger>,
918}
919
920impl Default for Records {
921 fn default() -> Self {
922 Self {
923 handoffs: super::handoff::Handoffs::default(),
924 ledger: Some(RefusedLedger::default()),
925 }
926 }
927}
928
929impl Records {
930 pub fn load(data_dir: &Path) -> Self {
931 Self {
932 handoffs: super::handoff::Handoffs::load(data_dir),
933 ledger: RefusedLedger::read(data_dir).ok(),
934 }
935 }
936}
937
938const REFUSED_FILE: &str = "refused.json";
941const MAX_REFUSED: usize = 1000;
943const KEPT: lean_ctx_time::Duration = lean_ctx_time::Duration::days(7);
945
946#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
948pub struct RefusedAction {
949 #[serde(default, skip_serializing_if = "Option::is_none")]
952 pub sender: Option<String>,
953 pub code: String,
955 pub at: String,
956}
957
958#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
961pub struct RefusedLedger {
962 #[serde(default)]
963 pub refused: BTreeMap<String, RefusedAction>,
964}
965
966impl RefusedLedger {
967 fn path(data_dir: &Path) -> std::path::PathBuf {
968 data_dir.join("bus").join(REFUSED_FILE)
969 }
970
971 pub fn read(data_dir: &Path) -> Result<Self, CloudError> {
976 load_or_quarantine(&Self::path(data_dir), |_: &Self| true).map(Option::unwrap_or_default)
977 }
978}
979
980pub fn note_refused(
984 data_dir: &Path,
985 reference: &str,
986 sender: Option<&str>,
987 code: &str,
988) -> Result<(), CloudError> {
989 let reference = reference.trim();
990 if reference.is_empty() {
991 return Ok(());
992 }
993 let now = lean_ctx_time::UtcDateTime::now();
994 let oldest = (now - KEPT).to_rfc3339();
995 change_file(data_dir, REFUSED_FILE, |ledger: &mut RefusedLedger| {
996 ledger.refused.retain(|_, r| r.at >= oldest);
997 ledger.refused.insert(
998 reference.to_owned(),
999 RefusedAction {
1000 sender: sender.map(str::to_owned),
1001 code: code.to_owned(),
1002 at: now.to_rfc3339(),
1003 },
1004 );
1005 while ledger.refused.len() > MAX_REFUSED {
1008 let Some(first) = ledger
1009 .refused
1010 .iter()
1011 .min_by(|a, b| a.1.at.cmp(&b.1.at))
1012 .map(|(k, _)| k.clone())
1013 else {
1014 break;
1015 };
1016 ledger.refused.remove(&first);
1017 }
1018 })
1019}
1020
1021fn change_file<T>(
1025 data_dir: &Path,
1026 name: &str,
1027 change: impl FnOnce(&mut T),
1028) -> Result<(), CloudError>
1029where
1030 T: Default + Serialize + serde::de::DeserializeOwned,
1031{
1032 let dir = data_dir.join("bus");
1033 let _lock = lock_state(&dir, name)?;
1034 let path = dir.join(name);
1035 let mut value: T = match load_or_quarantine(&path, |_: &T| true) {
1036 Ok(value) => value.unwrap_or_default(),
1037 Err(error) if path.exists() => return Err(error),
1038 Err(error) => {
1039 tracing::warn!("cloud bus: {error}");
1040 T::default()
1041 }
1042 };
1043 change(&mut value);
1044 let bytes = serde_json::to_vec(&value).map_err(|e| CloudError::Local(e.to_string()))?;
1045 write_private(&dir, name, &bytes)
1046}
1047
1048const QUEEN_WARNINGS_FILE: &str = "queen-warnings.json";
1051const MAX_QUEEN_WARNINGS: usize = 1000;
1054
1055#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1057pub struct QueenWarning {
1058 #[serde(default, skip_serializing_if = "Option::is_none")]
1060 pub sender: Option<String>,
1061 pub rule: String,
1063 pub mode: String,
1065 pub mark: String,
1067 pub at: String,
1068}
1069
1070#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1072pub struct QueenWarnings {
1073 #[serde(default)]
1074 pub warnings: Vec<QueenWarning>,
1075}
1076
1077impl QueenWarnings {
1078 pub fn read(data_dir: &Path) -> Result<Self, CloudError> {
1080 load_or_quarantine(
1081 &data_dir.join("bus").join(QUEEN_WARNINGS_FILE),
1082 |_: &Self| true,
1083 )
1084 .map(Option::unwrap_or_default)
1085 }
1086}
1087
1088pub fn note_queen_warning(
1092 data_dir: &Path,
1093 agent_id: Option<&str>,
1094 mark: &str,
1095) -> Result<(), CloudError> {
1096 let now = lean_ctx_time::UtcDateTime::now();
1097 let oldest = (now - KEPT).to_rfc3339();
1098 change_file(data_dir, QUEEN_WARNINGS_FILE, |log: &mut QueenWarnings| {
1099 log.warnings.retain(|w| w.at >= oldest);
1100 log.warnings.push(QueenWarning {
1101 sender: agent_id.map(str::to_owned),
1102 rule: QUEEN_IDENTITY.to_owned(),
1103 mode: QueenMode::Warn.as_str().to_owned(),
1104 mark: mark.to_owned(),
1105 at: now.to_rfc3339(),
1106 });
1107 let over = log.warnings.len().saturating_sub(MAX_QUEEN_WARNINGS);
1108 log.warnings.drain(..over);
1109 })
1110}
1111
1112#[derive(Debug, Clone, Default, PartialEq, Eq)]
1115pub struct Refused {
1116 ids: BTreeSet<String>,
1117}
1118
1119const CONTAINED_MIN: usize = 16;
1122
1123impl Refused {
1124 pub fn insert(&mut self, id: &str) {
1125 let id = id.trim();
1126 if !id.is_empty() {
1127 self.ids.insert(id.to_owned());
1128 }
1129 }
1130
1131 pub fn named_by(&self, target: &str) -> Option<&str> {
1133 let target = target.trim();
1134 self.ids
1135 .iter()
1136 .find(|id| {
1137 target == id.as_str() || (id.len() >= CONTAINED_MIN && target.contains(id.as_str()))
1138 })
1139 .map(String::as_str)
1140 }
1141
1142 pub fn for_sender(
1147 state: &super::relay_v2::StateV2,
1148 handoffs: &super::handoff::Handoffs,
1149 ledger: &RefusedLedger,
1150 map: &crate::vault::VaultMap,
1151 agent_id: &str,
1152 worker_id: &str,
1153 ) -> Self {
1154 let mut out = Self::default();
1155 for place in state.denied.keys() {
1156 out.insert(place);
1157 if let Some((_, id)) = place.split_once(':') {
1158 out.insert(id);
1159 if let Some(record) = map.vaults.values().find(|r| r.vault_id == id) {
1160 out.insert(&super::relay_v2::address_of(record));
1161 }
1162 }
1163 }
1164 for control in state.controls.values() {
1165 if control.action == super::v2::ControlAction::Veto
1166 && let Some(r) = &control.target_ref
1167 {
1168 out.insert(&r.id);
1169 }
1170 }
1171 for (client_msg_id, offer) in &handoffs.offers {
1172 if offer.from == agent_id
1173 && matches!(offer.state, super::handoff::OfferState::Vetoed { .. })
1174 {
1175 out.insert(client_msg_id);
1176 if let Some(id) = &offer.msg_id {
1177 out.insert(id);
1178 }
1179 }
1180 }
1181 for (reference, action) in &ledger.refused {
1182 if action
1183 .sender
1184 .as_deref()
1185 .is_none_or(|s| s == agent_id || s == worker_id)
1186 {
1187 out.insert(reference);
1188 }
1189 }
1190 out
1191 }
1192}
1193
1194pub fn check_forwarding(
1197 kind: MessageType,
1198 refs: &[Ref],
1199 body: &Value,
1200 refused: &Refused,
1201) -> Result<(), Invalid> {
1202 if !asks_to_act(kind) {
1203 return Ok(());
1204 }
1205 let named = refs
1207 .iter()
1208 .map(|r| r.target.as_str())
1209 .chain(body["resource"].as_str())
1210 .chain(texts(kind, body))
1211 .find_map(|t| refused.named_by(t));
1212 match named {
1213 Some(id) => Err(refusal(
1214 DENIED_FORWARDED,
1215 &format!("{id} was refused: {FORWARDED}"),
1216 )),
1217 None => Ok(()),
1218 }
1219}
1220
1221pub fn asks_to_act(kind: MessageType) -> bool {
1224 matches!(
1225 kind,
1226 MessageType::Question | MessageType::Offer | MessageType::Handoff
1227 )
1228}
1229
1230#[cfg(test)]
1231#[path = "person_rules_tests.rs"]
1232mod tests;