Skip to main content

lean_ctx_cloud/bus/
person_rules.rs

1// SPDX-License-Identifier: Apache-2.0
2//! What an agent may never say on the bus (process v1 §7): no approval or
3//! decision in a person's name, no refused action passed on to another
4//! agent, and only the registered Queen appears as the Queen.
5//!
6//! Every check refuses with a named rule and explains it; nothing is
7//! rewritten. A message that fails one is not sent (the one exception is
8//! `queen_identity` in `warn`, below).
9//!
10//! - **`on_behalf_of`** (`400 invalid_field`): a message that names a
11//!   person it speaks for — the contract's marker `on_behalf_of` as a field,
12//!   or plainly in its text ("on behalf of …", "in the name of …").
13//! - **`approval_on_behalf`** (`403 forbidden_right`): decision fields with a
14//!   person as decider (`by`/`checker`/`answered_by` of kind person,
15//!   `approval`, `consent`), a handoff of a person's decision (an Inbox
16//!   item, a consent, a G2/G9/G10 approval, a release, deploy, secret or
17//!   rights decision), or a sentence that states a person approved
18//!   ("the owner approved …", "approved by the person"). The text check is
19//!   secondary and conservative: questions, negations and "waiting for"
20//!   sentences never match; `progress` and `finding` are never checked.
21//! - **`denied_forwarded`** (`403 forbidden_right`): a question, offer or
22//!   handoff whose refs (or resource) name what was refused for the sender:
23//!   a place Cloud denied (`StateV2::denied`), a publish Cloud refused, a
24//!   vetoed lock or handoff, or a refusal recorded with [`note_refused`].
25//! - **`queen_identity`** (`403 forbidden_right` in `enforce`): a sender that
26//!   presents itself as the Queen (role `queen`, a display name "Queen", a
27//!   "From the Queen:" label) without being a Queen session the app
28//!   registered ([`crate::queens`]).
29//!
30//!   Labels, marks, roles and display names are matched on their folded
31//!   form ([`fold`]: NFKC, every default-ignorable character such as
32//!   zero-width spaces, the combining grapheme joiner and variation
33//!   selectors removed, visible blanks such as the Hangul fillers read as a
34//!   space and as nothing, Cyrillic or Greek look-alike letters read as
35//!   their Latin letter), so fullwidth, invisible-character or
36//!   cross-script look-alikes count as written.
37//!
38//! The first three are always enforced. `queen_identity` has a rollout
39//! switch, `[cloud] queen_identity` (env `LEAN_CTX_CLOUD_QUEEN_IDENTITY`,
40//! which wins), [`QueenMode`]:
41//!
42//! - `warn` (the default): the message passes, is logged in
43//!   `bus/queen-warnings.json` (rule `queen_identity`, mode `warn`; its own
44//!   file and cap, so warnings never evict a refused action from
45//!   `bus/refused.json`) and carries a visible mark for its receiver,
46//!   `[unverified Queen sender: <name>, agent <id>, role <role>]`, in front
47//!   of its text. The mark is always built from the authenticated sender
48//!   and always put in front; a mark-like part the sender wrote is
49//!   neutralised ("[text of the sender, not a mark: …"), so nobody can write
50//!   a mark naming someone else. Apart from that the sender's text is kept.
51//! - `enforce`: the message is refused. Any other value counts as
52//!   `enforce` (fail closed).
53//!
54//! Switch to `enforce` only once `queen-sessions.json` on the host Instance
55//! lists every Queen session (check it read-only): today Queens that run on
56//! another machine are not registered with the host, so `enforce` would
57//! silence them.
58//!
59//! Before enforce (open, not part of this change):
60//! - register the Queens that run on another machine with the Instance that
61//!   serves their bus (today Desktop registers only local Queen sessions);
62//! - Desktop calls `/v1/local/queens/remove` when a Queen session ends (it
63//!   does not yet, so an ended session stays registered);
64//! - child processes inherit `LEAN_CTX_SESSION_ID`, so a process a Queen
65//!   session starts carries her session id; a subagent presence is already
66//!   never the Queen, other children are not told apart yet;
67//! - app session messages (`cloud_message_session`, an app tool, not the
68//!   bus) are not covered until the app identifies the caller; when the app
69//!   can't prove the sender, it must deliver the message with the same
70//!   unverified-Queen-sender mark. The interface the app should reuse is
71//!   public: [`marked`] with [`Speaker::mark`] (and [`Speaker::of_registry`]
72//!   for the sender, [`neutralise_marks`] for a sender's text), as
73//!   `lean_ctx_cloud::bus::person_rules::*`;
74//! - the mark is applied on the sending Instance only: a message from an
75//!   older or modified Instance arrives unmarked, which only the Cloud can
76//!   close by checking and marking (or refusing) on publish (an HC task).
77
78use 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
95/// The refusal of `rule`, in the contract's wording, with why.
96pub 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
115// --- structured fields -------------------------------------------------
116
117/// Body fields that carry a decision; a bus message has none of them.
118const 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
140/// The resource of a handoff that only a person decides.
141pub 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
152// --- free text ---------------------------------------------------------
153
154const 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
177/// Words that make a sentence a report of what is still open, never a claim.
178static 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
185/// The sentences of `text` that are no question.
186fn 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
201/// The secondary text check: `Some(rule)` when `text` plainly speaks for a
202/// person or states a person's approval.
203pub 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
213/// The free-text fields of an agent's conversational message.
214fn 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
224/// The person rules of an agent's publish, checked before its body shape
225/// (`Publish::validate`), so the refusal names the rule.
226pub 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
261// --- the Queen ---------------------------------------------------------
262
263/// `text` as the Queen rule reads it: a character that looks like printable
264/// ASCII that ASCII, by its UTS #39 skeleton (`latin_skeleton`, the whole
265/// Unicode `confusables.txt`), so `Quеen` with a Cyrillic `е` or `Qᴜeen`
266/// with a small capital `ᴜ` reads `Queen`; every other character in its
267/// NFKC compatibility form (fullwidth `[` is `[`, a no-break space a
268/// space); every invisible character removed (the full Unicode
269/// `Default_Ignorable_Code_Point` set — zero-width spaces and joiners, soft
270/// hyphens, bidi controls, the combining grapheme joiner, variation
271/// selectors — and the other format characters, `Cf`); and a visible blank
272/// that is no `\s` (the Hangul fillers, the braille blank) a space.
273pub fn fold(text: &str) -> String {
274    Folded::of(text, Blank::Space).text
275}
276
277/// What a visible blank that is no `\s` becomes in a folded text: a space
278/// between words, or nothing inside one. The Queen rule reads both.
279#[derive(Debug, Clone, Copy)]
280enum Blank {
281    Space,
282    Drop,
283}
284
285/// A blank that renders as empty space but is no `\s`: the Hangul fillers
286/// (also after NFKC: U+3164 and U+FFA0 become U+1160) and the braille blank.
287fn is_visible_blank(c: char) -> bool {
288    matches!(
289        c,
290        '\u{115F}' | '\u{1160}' | '\u{3164}' | '\u{FFA0}' | '\u{2800}'
291    )
292}
293
294/// Every `Default_Ignorable_Code_Point` (the Unicode set, from the regex
295/// crate's Unicode tables) and every other format character (`Cf`).
296fn 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
306/// What a non-ASCII character `c` reads as when it looks like printable
307/// ASCII: its UTS #39 skeleton (`confusables.txt` of the Unicode version
308/// [`unicode_security::UNICODE_VERSION`], through
309/// [`unicode_security::skeleton`]) when that is printable ASCII, so the
310/// Cyrillic `е`, the Armenian `գ`, the small capital `ᴜ` and the Coptic `Ⲛ`
311/// read `e`, `q`, `u` and `N`. A character whose skeleton keeps a non-ASCII
312/// part (a letter with a visible accent, a Cyrillic or Greek letter with no
313/// Latin twin) is no look-alike: `None`.
314///
315/// The skeleton writes a glyph by its prototype, and two prototypes are no
316/// letter of the words the Queen rule matches: `rn` is the prototype of `m`
317/// (a fullwidth `m` reads `m`), and `l` that of `l`, `I`, `1` and `|` (no
318/// matched word has an `l`, so it reads `I`: a capital iota or palochka in
319/// `UNVERIFIED` is the `I` it looks like).
320fn 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
338/// [`fold`] with the way back: for each byte of the folded text, the byte
339/// range of the character of `text` it came from.
340struct 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            // The look-alike first: NFKC reads the long `ſ` as `s`, but it
355            // looks like the `f` its skeleton names.
356            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                // The blanks first: the Hangul fillers are default ignorable.
365                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    /// Appends `folded`, which came from the original bytes `range`.
381    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    /// Both readings of `text` the Queen rule checks: a visible blank as a
387    /// space (between words) and as nothing (inside a word).
388    fn both(text: &str) -> [Self; 2] {
389        [Self::of(text, Blank::Space), Self::of(text, Blank::Drop)]
390    }
391
392    /// The range of the original text a match `start..end` of the folded
393    /// text covers (whole original characters).
394    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/// Who sends, as far as the Queen rule needs it.
416#[derive(Debug, Clone, Copy, Default)]
417pub struct Speaker<'a> {
418    /// The local agent id (`None`: an unregistered sender).
419    pub agent_id: Option<&'a str>,
420    pub role: Option<&'a str>,
421    pub display_name: Option<&'a str>,
422    /// The sender is a Queen session the app registered ([`registered_queen`]).
423    pub registered_queen: bool,
424}
425
426impl<'a> Speaker<'a> {
427    /// The speaker `agent` is (none: an unregistered sender, never the Queen).
428    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    /// The speaker `agent_id` is in `registry`: its name and role from its
438    /// entry, and the registered Queen only while that presence is active
439    /// (`AgentRegistry::list_active`: not finished, its process identity
440    /// current, its durable identity active).
441    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    /// The receiver's mark of an unverified Queen sender: its real name,
454    /// agent id and role, each on one line, without a bracket that could end
455    /// the mark early and at most [`MARK_FIELD_MAX`] characters long
456    /// (`mark_field`).
457    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
468/// The longest a name, agent id or role is in a mark ([`Speaker::mark`]).
469pub const MARK_FIELD_MAX: usize = 80;
470
471/// `field` as a mark carries it: trimmed; a bracket (also a look-alike,
472/// [`fold`]) a parenthesis; a line break, control or other blank a space;
473/// cut to [`MARK_FIELD_MAX`] characters with `…` at the cut.
474fn 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/// How the Queen rule applies (`[cloud] queen_identity`).
498#[derive(Debug, Clone, Copy, PartialEq, Eq)]
499pub enum QueenMode {
500    /// Pass, log and mark (the rollout default).
501    Warn,
502    /// Refuse.
503    Enforce,
504}
505
506/// The env override of `[cloud] queen_identity`.
507pub const QUEEN_MODE_ENV: &str = "LEAN_CTX_CLOUD_QUEEN_IDENTITY";
508/// The start of the receiver's mark ([`Speaker::mark`]).
509pub const MARK_PREFIX: &str = "[unverified Queen sender: ";
510
511impl QueenMode {
512    /// The mode of a configured value and an env value (the env wins):
513    /// none set is `warn`; `warn` or `enforce` as written (case and
514    /// surrounding blanks aside); anything else is `enforce` (fail closed).
515    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    /// The mode now: the env override, else `[cloud] queen_identity`.
524    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
538/// Anything that reads like the receiver's mark ([`MARK_PREFIX`]), in any
539/// case or spacing (matched on the [`fold`]ed text; a zero-width character
540/// in place of a space leaves no space, so none is required). An `i` of
541/// `unverified` is also the ASCII `l`, `1` or `|` it looks like in many
542/// fonts (`[UNVERlFIED`); only the mark widens so, never a role or name.
543static 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
547/// What a mark-like text of the sender becomes: it can no longer be read
548/// as a mark.
549const NEUTRALISED: &str = "[text of the sender, not a mark: unverified Queen sender:";
550
551/// `text` with every mark-like part neutralised: only Cloud writes a mark.
552/// A look-alike (fullwidth, zero-width characters, [`fold`]) is found too;
553/// the rest of the text is kept as written.
554pub fn neutralise_marks(text: &str) -> String {
555    // Both readings of a visible blank ([`Folded::both`]); the second pass
556    // reads the first one's result, whose neutralised parts no longer match.
557    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        // An NFKC expansion can map two matches onto one original
568        // character: never slice behind what is already kept.
569        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
578/// `text` behind the real `mark` (built from the authenticated sender,
579/// [`Speaker::mark`]). Any mark-like part the sender wrote is neutralised,
580/// so a sender cannot write a mark naming someone else. A text that already
581/// starts with exactly this `mark` (marked by the sending tool, checked
582/// again by the relay) is marked only once.
583pub 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
590/// The refusal name of a text that does not fit its message type.
591pub const TEXT_TOO_LONG: &str = "text_too_long";
592
593/// Refuses, before it is sent, a `kind` message whose text as sent (`sent`:
594/// `written` itself, or behind the receiver's mark) is over the type's limit
595/// ([`super::v2::text_max`]). The mark's characters count: the refusal says
596/// how many the mark takes and how many to cut, so a message is never
597/// withheld later for its length without the sender knowing.
598pub 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    // Counted as the relay sends it: trimmed.
603    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
622/// `text` cut to at most `max` characters, with a visible note of the cut at
623/// its end: for a post the relay sends that was queued before its sending
624/// tool checked its length ([`check_sent_length`]), so it is delivered
625/// shortened instead of withheld. A text that fits is returned as it is; a
626/// mark in front stays whole.
627pub 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    // The note's length depends on the count it names: shrink what is kept
634    // until text and note fit together.
635    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(&note(n - keep));
645    out
646}
647
648/// Whether `text` labels its sender as the Queen ("From the Queen: …"), also
649/// as a look-alike ([`fold`]).
650pub fn labels_queen(text: &str) -> bool {
651    Folded::both(text).iter().any(|folded| {
652        let text = &folded.text;
653        // A mark-like text names a Queen sender too: only Cloud writes a mark.
654        MARK_LIKE.is_match(text) || QUEEN_LABEL.iter().any(|re| re.is_match(text))
655    })
656}
657
658/// Whether a role or display name says Queen, also as a look-alike.
659fn says_queen(name: &str) -> bool {
660    Folded::both(name)
661        .iter()
662        .any(|folded| QUEEN_WORD.is_match(&folded.text))
663}
664
665/// Refuses a sender that presents itself as the Queen without being the
666/// registered Queen: by role, display name, or a label in `texts`.
667pub 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
683/// Whether `agent` is a Queen session the app registered in `dir`: its own
684/// launching session id is registered. A presence registered next to
685/// another in the same process (a subagent) is never the Queen.
686pub 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
695/// [`registered_queen_in`] in this Instance's data dir; unreadable is no.
696pub 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
700/// The Queen rule in `mode`: `Ok(None)` passes as written, `Ok(Some(mark))`
701/// passes with the receiver's mark (`warn`), `Err` refuses (`enforce`).
702pub 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
714/// [`queen_rule`] for a sending tool: the text to send — `text` itself, or
715/// marked and logged in `data_dir`'s `bus/queen-warnings.json` under `warn`. A
716/// warning that cannot be logged refuses the message (fail closed). With
717/// `limit`, the text to send must fit that type, mark included
718/// ([`check_sent_length`]).
719pub 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    // Refused for its length before it is logged: a refused text never went.
735    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
749/// The type whose length limit a local post of `category` to `to` must
750/// meet: a question to a vault bus leaves as a question (its text at most
751/// [`super::v2::TEXT_MAX`], the mark included). Other posts stay local or
752/// leave as a progress step the relay shortens itself.
753fn 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
763/// The checks of a local `ctx_agent post`; the text to post. The person
764/// rules apply when its category is a conversational bus type (a post to a
765/// vault bus leaves as that type; `progress` and `finding` stay free); then
766/// the Queen rule in `mode` ([`apply_queen_rule`], logged in `data_dir`).
767///
768/// A question, offer or handoff post is also checked for a refused action
769/// it passes on ([`check_not_refused_in`], `data_dir`'s records, fail
770/// closed), like the same message sent typed.
771pub 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
782/// [`check_local_post_in`] of a post addressed `to`: a question to a vault
783/// bus is also refused when its text, with the receiver's mark, is over the
784/// limit ([`check_sent_length`]), so the relay never withholds it for that.
785pub 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
815/// [`check_local_post_to_in`] for `agent_id` of `registry`, in this
816/// Instance's Cloud data dir and the configured [`QueenMode`]. Without a data
817/// dir a check that needs it refuses.
818pub 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        // Only the person rules apply: no record is read or written.
830        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
860/// The bus body a local post of `category` leaves as, for the conversational
861/// types the person rules check; `None` for a status, progress or finding.
862pub 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
873/// Refuses a question, offer or handoff that names an action refused for
874/// `agent_id` (speaking as `worker_id`), from the records in `data_dir`
875/// (`denied_forwarded`). Records that cannot be read refuse it too: what
876/// was refused is unknown, so nothing that asks another agent goes.
877pub 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        // Every record counts for a refusal, whichever Cloud resolved it:
895        // more refused, never less (nothing is sent from this view).
896        &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/// The refused records the relay's outgoing pass checks posts against
912/// (its `StateV2` and vault map it holds itself). `ledger: None`: the
913/// ledger could not be read; posts that ask another agent wait.
914#[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
938// --- refused actions ---------------------------------------------------
939
940const REFUSED_FILE: &str = "refused.json";
941/// Refusals remembered at most (the newest stay).
942const MAX_REFUSED: usize = 1000;
943/// A refusal is remembered this long.
944const KEPT: lean_ctx_time::Duration = lean_ctx_time::Duration::days(7);
945
946/// One action refused for a sender.
947#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
948pub struct RefusedAction {
949    /// The local agent id or worker id it was refused for; `None`: refused
950    /// on this machine, for every sender.
951    #[serde(default, skip_serializing_if = "Option::is_none")]
952    pub sender: Option<String>,
953    /// The refusal's code (`place_denied`, `forbidden_right`, …).
954    pub code: String,
955    pub at: String,
956}
957
958/// `<data>/cloud/bus/refused.json`: what was refused, by its reference
959/// (a `client_msg_id`, a `msg_…` id, `task:<n>`, a path …).
960#[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    /// The ledger; missing is empty. Damaged or unreadable is `Err`: the
972    /// caller refuses what it would have checked (fail closed). A damaged
973    /// file is moved aside on this read, so only this one check fails and
974    /// the next one reads an empty ledger.
975    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
980/// Remember that `reference` was refused for `sender` (`None`: for every
981/// sender on this machine) with `code`, under the ledger's lock. A damaged
982/// file is moved aside first (never overwritten).
983pub 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        // Only real refusals are ever in this ledger, so only other real
1006        // refusals evict one (warnings are kept apart, [`QueenWarnings`]).
1007        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
1021/// Load, change and save the JSON file `name` of `data_dir/bus` under its
1022/// lock. Damaged and moved aside: start over (the older content is kept in
1023/// the moved copy). Unreadable and still there: never overwritten.
1024fn 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
1048// --- warnings of an unverified Queen sender ------------------------------
1049
1050const QUEEN_WARNINGS_FILE: &str = "queen-warnings.json";
1051/// Warnings remembered at most (the newest stay); their own cap, apart from
1052/// the refused actions, so no number of warnings evicts a refusal.
1053const MAX_QUEEN_WARNINGS: usize = 1000;
1054
1055/// One message sent under `warn` by a sender presenting as the Queen.
1056#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1057pub struct QueenWarning {
1058    /// The local agent id (`None`: an unregistered sender).
1059    #[serde(default, skip_serializing_if = "Option::is_none")]
1060    pub sender: Option<String>,
1061    /// Always `queen_identity`.
1062    pub rule: String,
1063    /// Always `warn`: the message went, marked.
1064    pub mode: String,
1065    /// The receiver's mark it carried.
1066    pub mark: String,
1067    pub at: String,
1068}
1069
1070/// `<data>/cloud/bus/queen-warnings.json`, oldest first.
1071#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1072pub struct QueenWarnings {
1073    #[serde(default)]
1074    pub warnings: Vec<QueenWarning>,
1075}
1076
1077impl QueenWarnings {
1078    /// The warnings; missing is empty, damaged is moved aside and `Err`.
1079    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
1088/// Log that `agent_id` sent as an unverified Queen sender under `warn`, with
1089/// the receiver's `mark`: rule `queen_identity`, mode `warn`, in
1090/// `bus/queen-warnings.json` (never in the refused-actions ledger).
1091pub 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/// The references refused for one sender, from every record this machine
1113/// keeps.
1114#[derive(Debug, Clone, Default, PartialEq, Eq)]
1115pub struct Refused {
1116    ids: BTreeSet<String>,
1117}
1118
1119/// Ids shorter than this match a ref only exactly, longer ones also inside
1120/// it (a `msg_…` id in a URL).
1121const 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    /// The refused id `target` names, if any.
1132    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    /// What was refused for `agent_id` (speaking as `worker_id`): places Cloud
1143    /// denied (by key, id and vault address), vetoed locks and handoffs, the
1144    /// agent's vetoed handoffs, and the ledger's refusals for it or for
1145    /// every sender.
1146    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
1194/// Refuses a question, offer or handoff whose refs or resource name an
1195/// action refused for its sender.
1196pub 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    // Refs and the resource by id; the text only by a long id inside it.
1206    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
1221/// The kinds [`check_forwarding`] checks: a question, offer or handoff can
1222/// ask another agent to act.
1223pub 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;