Skip to main content

lean_ctx_cloud/bus/
messages_v2.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Typed agent messages on a C0 2.0 Cloud (bus v2, E14): `ctx_agent send` and
3//! `reply` become `place.publish` frames to the vault bus of the checkout.
4//!
5//! - A message for one agent names its worker in `body.to_worker` (`wkr_…`,
6//!   as `ctx_agent list` shows the workers of other machines); the vault's
7//!   present agents all receive it, the addressed one sees it is for them.
8//! - A reply names the message it answers (`reply_to`, its `msg_…` id); Cloud
9//!   keeps the thread (`thread_id`) and its state (answered, accepted, …).
10//! - A handoff offers a resource to one worker; the addressee answers it
11//!   with `accept` true or false.
12//!
13//! Agents talk to agents here: Cloud carries no person answers (owner,
14//! 01.11.). No network in the tool call: the publish is queued and the
15//! relay sends it ([`super::relay_v2::queue_publish`]).
16
17use serde_json::{Map, Value};
18
19use super::v2::{BUS_SCHEMA, MessageType, Publish, Ref, RefKind, ulid_for};
20use super::{exchange, person_rules};
21use crate::CloudStore;
22use crate::knowledge::screening::Screen;
23
24/// What a typed message carries beyond its text.
25#[derive(Debug, Clone, Copy, Default)]
26pub struct Extras<'a> {
27    /// The addressed worker (`wkr_…`).
28    pub to_worker: Option<&'a str>,
29    /// The `msg_…` id answered.
30    pub reply_to: Option<&'a str>,
31    /// An answer to a handoff: take it (`true`) or decline it.
32    pub accept: Option<bool>,
33    /// A handoff's resource (a path, `task:<n>`, …); the text otherwise.
34    pub resource: Option<&'a str>,
35    /// `file:<path>`, `commit:<sha>`, `node:<id>`, `msg:<id>`, `url:<url>`,
36    /// `test:<name>`: what the message rests on (a finding needs one).
37    pub refs: &'a [String],
38}
39
40/// The bus v2 refs among `raw` (`kind:target`); other entries are ignored.
41pub fn refs_of(raw: &[String]) -> Vec<Ref> {
42    raw.iter()
43        .filter_map(|r| {
44            let (kind, target) = r.split_once(':')?;
45            let kind = match kind {
46                "file" => RefKind::File,
47                "commit" => RefKind::Commit,
48                "node" => RefKind::Node,
49                "msg" => RefKind::Msg,
50                "url" => RefKind::Url,
51                "test" => RefKind::Test,
52                _ => return None,
53            };
54            (!target.is_empty()).then(|| Ref {
55                kind,
56                target: target.to_owned(),
57            })
58        })
59        .collect()
60}
61
62/// The body of a `kind` message with `text`, or why it cannot be sent.
63pub fn body(
64    kind: MessageType,
65    text: &str,
66    from_worker: &str,
67    x: Extras<'_>,
68) -> Result<Value, String> {
69    let to_worker = x.to_worker.map(str::to_owned);
70    if let Some(w) = &to_worker {
71        if !w.starts_with("wkr_") {
72            return Err(format!(
73                "address another machine's agent by its worker id (wkr_…), as ctx_agent action=list shows it; {w:?} is not one"
74            ));
75        }
76    }
77    let mut b = Map::new();
78    match kind {
79        MessageType::Question => {
80            b.insert("text".into(), text.into());
81            if let Some(w) = to_worker {
82                b.insert("to_worker".into(), w.into());
83            }
84        }
85        MessageType::Answer => {
86            if x.reply_to.is_none() {
87                return Err("an answer needs reply_to (the msg_… id it answers)".into());
88            }
89            b.insert("text".into(), text.into());
90            if let Some(accept) = x.accept {
91                b.insert("accept".into(), accept.into());
92            }
93        }
94        MessageType::Handoff => {
95            // The sender is the publishing worker; Cloud knows it.
96            let to = to_worker.ok_or("a handoff needs to_agent (the worker that takes over)")?;
97            if to == from_worker {
98                return Err("a handoff goes to another worker".into());
99            }
100            b.insert("to_worker".into(), to.into());
101            b.insert("resource".into(), x.resource.unwrap_or(text).into());
102            b.insert("note".into(), text.into());
103        }
104        MessageType::Finding => {
105            if refs_of(x.refs).is_empty() {
106                return Err(
107                    "a finding needs references (file:<path>, commit:<sha>, node:<id>, …)".into(),
108                );
109            }
110            if !(24..=300).contains(&text.chars().count()) {
111                return Err("a finding is one statement of 24 to 300 characters".into());
112            }
113            b.insert("statement".into(), text.into());
114            b.insert("evidence".into(), "stated".into());
115        }
116        MessageType::Offer => {
117            b.insert("what".into(), text.into());
118            b.insert("capability".into(), "general".into());
119            b.insert("eta_minutes".into(), 60.into());
120        }
121        MessageType::Progress => {
122            return Err(
123                "progress is a plain status post (ctx_agent post); send question|offer|handoff|answer|finding"
124                    .into(),
125            );
126        }
127    }
128    Ok(Value::Object(b))
129}
130
131/// The worker a local agent speaks as: its host app and role, attached to
132/// this instance's book (local; the relay registers it with Cloud).
133fn worker_of(store: &CloudStore, agent_id: &str) -> Result<String, String> {
134    let (instance_id, host, role) = host_and_role(store, agent_id)?;
135    crate::workers::attach::attach(store, &instance_id, &host, &role)
136        .map(|a| a.worker.worker_id)
137        .map_err(|e| e.to_string())
138}
139
140/// The worker `agent_id` speaks as, without adding it to the book: tool
141/// admission reads which worker a Cloud control names (`None` when this
142/// machine is not enrolled or the agent is unknown).
143pub(crate) fn known_worker_of(store: &CloudStore, agent_id: &str) -> Option<String> {
144    known_worker_and_role_of(store, agent_id).map(|(worker_id, _)| worker_id)
145}
146
147/// [`known_worker_of`] and that worker's role (normalised; past the
148/// worker cap it may be `general`, not the agent's own).
149pub(crate) fn known_worker_and_role_of(
150    store: &CloudStore,
151    agent_id: &str,
152) -> Option<(String, String)> {
153    use crate::workers::attach;
154    let (instance_id, host, role) = host_and_role(store, agent_id).ok()?;
155    let mut workers = attach::list(store, &instance_id).ok()?;
156    let worker = attach::attach_in(&mut workers, &instance_id, &host, &role).worker;
157    Some((worker.worker_id, worker.role))
158}
159
160/// The enrolled instance and the host app and role `agent_id` attaches with.
161fn host_and_role(store: &CloudStore, agent_id: &str) -> Result<(String, String, String), String> {
162    use crate::workers::attach;
163    use lean_ctx::core::agents::AgentRegistry;
164    let instance = store
165        .instance()
166        .map_err(|e| e.to_string())?
167        .ok_or("this machine is not connected to the Cloud")?;
168    let registry = AgentRegistry::load_or_create();
169    let agent = registry
170        .agents
171        .iter()
172        .find(|a| a.agent_id == agent_id)
173        .ok_or("agent must be registered first (use action=register)")?;
174    let (host, role) = attach::agent_worker_key(agent);
175    Ok((instance.instance_id, host, role))
176}
177
178/// Queue a typed message from `agent_id` in `project_root`; its
179/// `client_msg_id`.
180pub fn send(
181    project_root: &str,
182    agent_id: &str,
183    message_type: Option<&str>,
184    text: &str,
185    extras: Extras<'_>,
186) -> Result<String, String> {
187    let store = CloudStore::open().map_err(|e| e.to_string())?;
188    send_in(&store, project_root, agent_id, message_type, text, extras)
189}
190
191/// [`send`] with the Cloud state of `store`.
192pub(crate) fn send_in(
193    store: &CloudStore,
194    project_root: &str,
195    agent_id: &str,
196    message_type: Option<&str>,
197    text: &str,
198    extras: Extras<'_>,
199) -> Result<String, String> {
200    // A folder the person stopped sharing sends nothing, not even through
201    // its main checkout or another checkout's record (rc4-6, bd 39657).
202    if crate::unlinked::contains(store.data_dir(), std::path::Path::new(project_root)) {
203        return Err(crate::unlinked::refusal(store.data_dir()));
204    }
205    if let Some(refusal) = super::control::admission(store, Some(agent_id)) {
206        return Err(refusal.message());
207    }
208    let raw = message_type.ok_or("type is required (question|offer|handoff|answer|finding)")?;
209    let kind = MessageType::parse(&raw.trim().to_ascii_lowercase()).ok_or_else(|| {
210        format!("unknown type {raw:?}; use question|offer|handoff|answer|finding")
211    })?;
212    let map = crate::vault::connected_map(store);
213    let record = crate::resolution::vault_in(&map, std::path::Path::new(project_root))
214        .map_err(|e| e.to_string())?
215        .ok_or("this repository is not linked to a vault (`lean-ctx cloud link <team>/<vault>`)")?;
216    // §40: from here on it is an exchange with another machine; every
217    // outcome leaves an audit record, and none that cannot be recorded
218    // leaves the machine.
219    let address = super::relay_v2::address_of(record);
220    let now = lean_ctx_time::UtcDateTime::now();
221    let audit = |outcome: &str| {
222        let mut entry = exchange::Entry::now(now, "out", outcome, kind, &address);
223        entry.agent = Some(agent_id.to_owned());
224        entry.peer = extras.to_worker.map(str::to_owned);
225        entry
226    };
227    let publish = match checked_publish(store, record, agent_id, kind, text, extras, now) {
228        Ok(publish) => publish,
229        Err(refusal) => {
230            exchange::record(store.data_dir(), &audit("refused").refused_by(&refusal))
231                .map_err(|e| format!("not sent: the exchange audit cannot be written: {e}"))?;
232            return Err(format!("not sent: {}", refusal.why));
233        }
234    };
235    let id = publish.client_msg_id.clone();
236    let mut queued = audit("queued");
237    queued.msg_id = Some(id.clone());
238    queued.digest = Some(exchange::digest(&publish.body));
239    exchange::record(store.data_dir(), &queued)
240        .map_err(|e| format!("not sent: the exchange audit cannot be written: {e}"))?;
241    // A handoff is remembered with its offering agent, so a maintainer's
242    // veto of it reaches that agent ([`super::handoff`]).
243    let offered = if kind == MessageType::Handoff
244        && let Some(to) = extras.to_worker
245    {
246        super::handoff::offered(store.data_dir(), &id, agent_id, to)
247    } else {
248        Ok(())
249    };
250    if let Err(error) = offered.and_then(|()| super::relay_v2::queue_publish(store, publish)) {
251        // The queued record stands for a message that never left: a second
252        // record says so (best effort: the send is refused either way).
253        let refusal = exchange::Refusal::new("queue", error.to_string());
254        let mut unsent = queued.refused_by(&refusal);
255        unsent.outcome = "refused".into();
256        if let Err(audit) = exchange::record(store.data_dir(), &unsent) {
257            tracing::warn!("cloud exchange audit: {audit}");
258        }
259        return Err(format!("not sent: {error}"));
260    }
261    Ok(id)
262}
263
264/// The publish of an exchange from `agent_id` to the vault of `record`,
265/// after every outbound rule (§40: account, team policy, content, person
266/// rules, C0 validation), or the rule that refuses it.
267fn checked_publish(
268    store: &CloudStore,
269    record: &crate::vault::VaultRecord,
270    agent_id: &str,
271    kind: MessageType,
272    text: &str,
273    extras: Extras<'_>,
274    now: lean_ctx_time::UtcDateTime,
275) -> Result<Publish, exchange::Refusal> {
276    use exchange::Refusal;
277    let instance = store
278        .instance()
279        .map_err(|e| Refusal::new("account", e.to_string()))?
280        .ok_or_else(|| Refusal::new("account", "this machine is not connected to the Cloud"))?;
281    if let Some(refusal) = exchange::account_refusal(instance.org_kind.as_deref()) {
282        return Err(refusal);
283    }
284    if let Some(refusal) = exchange::floor_refusal(store.data_dir(), &record.vault_id, kind, now) {
285        return Err(refusal);
286    }
287    // Every field that leaves is screened, not only the text.
288    let mut fields = vec![text, extras.resource.unwrap_or_default()];
289    fields.extend(extras.refs.iter().map(String::as_str));
290    exchange::screen_fields(&mut Screen::for_installation(), &fields)?;
291    let message = |e: String| Refusal::new("message", e);
292    let person = |e: String| Refusal::new("person_rules", e);
293    let worker_id = worker_of(store, agent_id).map_err(message)?;
294    // A handoff's resource is what the sender named, never a marked text.
295    let extras = Extras {
296        resource: extras
297            .resource
298            .or((kind == MessageType::Handoff).then_some(text)),
299        ..extras
300    };
301    let refs = refs_of(extras.refs);
302    // The always-enforced person rules first, on what the sender wrote.
303    let written = body(kind, text, &worker_id, extras).map_err(message)?;
304    person_rules::check_agent_body(kind, &written).map_err(|e| person(e.to_string()))?;
305    person_rules::check_not_refused_in(
306        store.data_dir(),
307        kind,
308        &refs,
309        &written,
310        agent_id,
311        &worker_id,
312    )
313    .map_err(|e| person(e.to_string()))?;
314    // Only the registered Queen appears as the Queen (process v1 §7): under
315    // `warn` the text goes marked for its receiver, under `enforce` not at
316    // all. The sender is looked up among the active presences.
317    let sent = {
318        let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
319        person_rules::apply_queen_rule(
320            store.data_dir(),
321            person_rules::Speaker::of_registry(&registry, Some(agent_id)),
322            &[text, extras.resource.unwrap_or_default()],
323            text,
324            Some(kind),
325            person_rules::QueenMode::current(),
326        )
327        .map_err(|e| person(e.to_string()))?
328    };
329    let body = if sent == text {
330        written
331    } else {
332        body(kind, &sent, &worker_id, extras).map_err(message)?
333    };
334    let now_ms = now.timestamp_millis().unsigned_abs();
335    let publish = Publish {
336        schema: BUS_SCHEMA.into(),
337        client_msg_id: ulid_for(
338            now_ms,
339            &format!("{agent_id}:{}", uuid::Uuid::new_v4().simple()),
340        ),
341        to: super::relay_v2::address_of(record),
342        kind,
343        worker_id,
344        thread_id: None,
345        reply_to: extras.reply_to.map(str::to_owned),
346        refs,
347        body,
348        ck_wrapped: None,
349        epoch: None,
350        about: None,
351        counts: None,
352        window: None,
353    };
354    // Refused before anything is remembered (a refused handoff is no offer).
355    publish.validate().map_err(|e| message(e.to_string()))?;
356    Ok(publish)
357}
358
359/// How a delivered typed message reads on the local bus: its type and id
360/// (to reply to), thread and state, who it is for, then the text.
361pub fn delivered_line(message: &Value) -> Option<String> {
362    let kind = message["type"].as_str()?;
363    if kind == "progress" {
364        return None;
365    }
366    let body = &message["body"];
367    let mut head = format!("{kind} {}", message["id"].as_str().unwrap_or("?"));
368    if let Some(thread) = message["thread_id"]
369        .as_str()
370        .filter(|t| Some(*t) != message["id"].as_str())
371    {
372        head.push_str(&format!(" in thread {thread}"));
373    }
374    if let Some(status) = message["thread_status"].as_str() {
375        head.push_str(&format!(" [{status}]"));
376    }
377    if let Some(to) = body["to_worker"].as_str() {
378        head.push_str(&format!(" for {to}"));
379    }
380    if let Some(accept) = body["accept"].as_bool() {
381        head.push_str(if accept { " (accepted)" } else { " (declined)" });
382    }
383    let text = match kind {
384        "handoff" => format!(
385            "hands over {} to {}: {}",
386            body["resource"].as_str().unwrap_or("?"),
387            body["to_worker"].as_str().unwrap_or("?"),
388            body["note"].as_str().unwrap_or_default()
389        ),
390        "finding" => body["statement"].as_str().unwrap_or_default().to_owned(),
391        "offer" => body["what"].as_str().unwrap_or_default().to_owned(),
392        _ => body["text"]
393            .as_str()
394            .map_or_else(|| body.to_string(), str::to_owned),
395    };
396    Some(format!(
397        "{head} — reply with ctx_agent action=reply reply_to={}: {text}",
398        message["id"].as_str().unwrap_or("?")
399    ))
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use serde_json::json;
406
407    const ME: &str = "wkr_aaaaaaaaaaaaaaaaaaaa";
408    const YOU: &str = "wkr_bbbbbbbbbbbbbbbbbbbb";
409
410    fn x<'a>() -> Extras<'a> {
411        Extras::default()
412    }
413
414    #[test]
415    fn bodies_follow_the_bus_v2_schema() {
416        let question = body(
417            MessageType::Question,
418            "Retry budget?",
419            ME,
420            Extras {
421                to_worker: Some(YOU),
422                ..x()
423            },
424        )
425        .unwrap();
426        assert_eq!(question, json!({"text": "Retry budget?", "to_worker": YOU}));
427        let answer = body(
428            MessageType::Answer,
429            "Yes.",
430            ME,
431            Extras {
432                reply_to: Some("msg_1"),
433                accept: Some(true),
434                ..x()
435            },
436        )
437        .unwrap();
438        assert_eq!(answer, json!({"text": "Yes.", "accept": true}));
439        let handoff = body(
440            MessageType::Handoff,
441            "Take the tests.",
442            ME,
443            Extras {
444                to_worker: Some(YOU),
445                resource: Some("tests/auth"),
446                ..x()
447            },
448        )
449        .unwrap();
450        assert_eq!(
451            handoff,
452            json!({"to_worker": YOU, "resource": "tests/auth", "note": "Take the tests."})
453        );
454        let cites = ["file:src/retry.rs".to_owned(), "tests/auth".to_owned()];
455        assert_eq!(
456            refs_of(&cites).len(),
457            1,
458            "only kind:target entries are refs"
459        );
460        assert!(
461            body(MessageType::Finding, "The cap is 3.", ME, x()).is_err(),
462            "a finding needs a ref"
463        );
464        let finding = body(
465            MessageType::Finding,
466            "The retry cap is three attempts in retry().",
467            ME,
468            Extras {
469                refs: &cites,
470                ..x()
471            },
472        )
473        .unwrap();
474        assert_eq!(finding["evidence"], "stated");
475        let offer = body(MessageType::Offer, "I can review retry().", ME, x()).unwrap();
476        // Every body passes the engine's own bus v2 check before it is queued.
477        for (kind, message_body, reply_to) in [
478            (MessageType::Question, question, None),
479            (MessageType::Answer, answer, Some("msg_00000000000000a1")),
480            (MessageType::Handoff, handoff, None),
481            (MessageType::Finding, finding, None),
482            (MessageType::Offer, offer, None),
483        ] {
484            let publish = Publish {
485                schema: BUS_SCHEMA.into(),
486                client_msg_id: "01M5NKA2Z8B000000000000009".into(),
487                to: "#acme/payments".into(),
488                kind,
489                worker_id: ME.into(),
490                thread_id: None,
491                reply_to: reply_to.map(Into::into),
492                refs: if kind == MessageType::Finding {
493                    refs_of(&cites)
494                } else {
495                    Vec::new()
496                },
497                body: message_body,
498                ck_wrapped: None,
499                epoch: None,
500                about: None,
501                counts: None,
502                window: None,
503            };
504            assert!(
505                publish.validate().is_ok(),
506                "{kind:?}: {:?}",
507                publish.validate()
508            );
509        }
510    }
511
512    #[test]
513    fn refusals_name_what_is_missing() {
514        assert!(
515            body(MessageType::Answer, "x", ME, x())
516                .unwrap_err()
517                .contains("reply_to")
518        );
519        assert!(
520            body(MessageType::Handoff, "x", ME, x())
521                .unwrap_err()
522                .contains("to_agent")
523        );
524        let local = body(
525            MessageType::Question,
526            "x",
527            ME,
528            Extras {
529                to_worker: Some("mcp-1-abc"),
530                ..x()
531            },
532        )
533        .unwrap_err();
534        assert!(local.contains("worker id"), "{local}");
535        assert!(body(MessageType::Progress, "x", ME, x()).is_err());
536    }
537
538    #[test]
539    fn a_delivery_shows_how_to_reply() {
540        let m = json!({
541            "id": "msg_2", "type": "answer", "thread_id": "msg_1", "thread_status": "answered",
542            "body": {"text": "Three attempts."}
543        });
544        let line = delivered_line(&m).unwrap();
545        assert!(
546            line.starts_with("answer msg_2 in thread msg_1 [answered]"),
547            "{line}"
548        );
549        assert!(line.contains("reply_to=msg_2") && line.ends_with("Three attempts."));
550        let h = json!({"id": "msg_3", "type": "handoff", "body": {"to_worker": YOU, "resource": "tests/auth", "note": "please"}});
551        assert!(
552            delivered_line(&h)
553                .unwrap()
554                .contains("hands over tests/auth to")
555        );
556        assert!(delivered_line(&json!({"type": "progress", "body": {"step": "x"}})).is_none());
557    }
558}