lean-ctx-cloud 3.12.13

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// SPDX-License-Identifier: Apache-2.0
//! Typed agent messages on a C0 2.0 Cloud (bus v2, E14): `ctx_agent send` and
//! `reply` become `place.publish` frames to the vault bus of the checkout.
//!
//! - A message for one agent names its worker in `body.to_worker` (`wkr_…`,
//!   as `ctx_agent list` shows the workers of other machines); the vault's
//!   present agents all receive it, the addressed one sees it is for them.
//! - A reply names the message it answers (`reply_to`, its `msg_…` id); Cloud
//!   keeps the thread (`thread_id`) and its state (answered, accepted, …).
//! - A handoff offers a resource to one worker; the addressee answers it
//!   with `accept` true or false.
//!
//! Agents talk to agents here: Cloud carries no person answers (owner,
//! 01.11.). No network in the tool call: the publish is queued and the
//! relay sends it ([`super::relay_v2::queue_publish`]).

use serde_json::{Map, Value};

use super::v2::{BUS_SCHEMA, MessageType, Publish, Ref, RefKind, ulid_for};
use super::{exchange, person_rules};
use crate::CloudStore;
use crate::knowledge::screening::Screen;

/// What a typed message carries beyond its text.
#[derive(Debug, Clone, Copy, Default)]
pub struct Extras<'a> {
    /// The addressed worker (`wkr_…`).
    pub to_worker: Option<&'a str>,
    /// The `msg_…` id answered.
    pub reply_to: Option<&'a str>,
    /// An answer to a handoff: take it (`true`) or decline it.
    pub accept: Option<bool>,
    /// A handoff's resource (a path, `task:<n>`, …); the text otherwise.
    pub resource: Option<&'a str>,
    /// `file:<path>`, `commit:<sha>`, `node:<id>`, `msg:<id>`, `url:<url>`,
    /// `test:<name>`: what the message rests on (a finding needs one).
    pub refs: &'a [String],
}

/// The bus v2 refs among `raw` (`kind:target`); other entries are ignored.
pub fn refs_of(raw: &[String]) -> Vec<Ref> {
    raw.iter()
        .filter_map(|r| {
            let (kind, target) = r.split_once(':')?;
            let kind = match kind {
                "file" => RefKind::File,
                "commit" => RefKind::Commit,
                "node" => RefKind::Node,
                "msg" => RefKind::Msg,
                "url" => RefKind::Url,
                "test" => RefKind::Test,
                _ => return None,
            };
            (!target.is_empty()).then(|| Ref {
                kind,
                target: target.to_owned(),
            })
        })
        .collect()
}

/// The body of a `kind` message with `text`, or why it cannot be sent.
pub fn body(
    kind: MessageType,
    text: &str,
    from_worker: &str,
    x: Extras<'_>,
) -> Result<Value, String> {
    let to_worker = x.to_worker.map(str::to_owned);
    if let Some(w) = &to_worker {
        if !w.starts_with("wkr_") {
            return Err(format!(
                "address another machine's agent by its worker id (wkr_…), as ctx_agent action=list shows it; {w:?} is not one"
            ));
        }
    }
    let mut b = Map::new();
    match kind {
        MessageType::Question => {
            b.insert("text".into(), text.into());
            if let Some(w) = to_worker {
                b.insert("to_worker".into(), w.into());
            }
        }
        MessageType::Answer => {
            if x.reply_to.is_none() {
                return Err("an answer needs reply_to (the msg_… id it answers)".into());
            }
            b.insert("text".into(), text.into());
            if let Some(accept) = x.accept {
                b.insert("accept".into(), accept.into());
            }
        }
        MessageType::Handoff => {
            // The sender is the publishing worker; Cloud knows it.
            let to = to_worker.ok_or("a handoff needs to_agent (the worker that takes over)")?;
            if to == from_worker {
                return Err("a handoff goes to another worker".into());
            }
            b.insert("to_worker".into(), to.into());
            b.insert("resource".into(), x.resource.unwrap_or(text).into());
            b.insert("note".into(), text.into());
        }
        MessageType::Finding => {
            if refs_of(x.refs).is_empty() {
                return Err(
                    "a finding needs references (file:<path>, commit:<sha>, node:<id>, …)".into(),
                );
            }
            if !(24..=300).contains(&text.chars().count()) {
                return Err("a finding is one statement of 24 to 300 characters".into());
            }
            b.insert("statement".into(), text.into());
            b.insert("evidence".into(), "stated".into());
        }
        MessageType::Offer => {
            b.insert("what".into(), text.into());
            b.insert("capability".into(), "general".into());
            b.insert("eta_minutes".into(), 60.into());
        }
        MessageType::Progress => {
            return Err(
                "progress is a plain status post (ctx_agent post); send question|offer|handoff|answer|finding"
                    .into(),
            );
        }
    }
    Ok(Value::Object(b))
}

/// The worker a local agent speaks as: its host app and role, attached to
/// this instance's book (local; the relay registers it with Cloud).
fn worker_of(store: &CloudStore, agent_id: &str) -> Result<String, String> {
    let (instance_id, host, role) = host_and_role(store, agent_id)?;
    crate::workers::attach::attach(store, &instance_id, &host, &role)
        .map(|a| a.worker.worker_id)
        .map_err(|e| e.to_string())
}

/// The worker `agent_id` speaks as, without adding it to the book: tool
/// admission reads which worker a Cloud control names (`None` when this
/// machine is not enrolled or the agent is unknown).
pub(crate) fn known_worker_of(store: &CloudStore, agent_id: &str) -> Option<String> {
    known_worker_and_role_of(store, agent_id).map(|(worker_id, _)| worker_id)
}

/// [`known_worker_of`] and that worker's role (normalised; past the
/// worker cap it may be `general`, not the agent's own).
pub(crate) fn known_worker_and_role_of(
    store: &CloudStore,
    agent_id: &str,
) -> Option<(String, String)> {
    use crate::workers::attach;
    let (instance_id, host, role) = host_and_role(store, agent_id).ok()?;
    let mut workers = attach::list(store, &instance_id).ok()?;
    let worker = attach::attach_in(&mut workers, &instance_id, &host, &role).worker;
    Some((worker.worker_id, worker.role))
}

/// The enrolled instance and the host app and role `agent_id` attaches with.
fn host_and_role(store: &CloudStore, agent_id: &str) -> Result<(String, String, String), String> {
    use crate::workers::attach;
    use lean_ctx::core::agents::AgentRegistry;
    let instance = store
        .instance()
        .map_err(|e| e.to_string())?
        .ok_or("this machine is not connected to the Cloud")?;
    let registry = AgentRegistry::load_or_create();
    let agent = registry
        .agents
        .iter()
        .find(|a| a.agent_id == agent_id)
        .ok_or("agent must be registered first (use action=register)")?;
    let (host, role) = attach::agent_worker_key(agent);
    Ok((instance.instance_id, host, role))
}

/// Queue a typed message from `agent_id` in `project_root`; its
/// `client_msg_id`.
pub fn send(
    project_root: &str,
    agent_id: &str,
    message_type: Option<&str>,
    text: &str,
    extras: Extras<'_>,
) -> Result<String, String> {
    let store = CloudStore::open().map_err(|e| e.to_string())?;
    send_in(&store, project_root, agent_id, message_type, text, extras)
}

/// [`send`] with the Cloud state of `store`.
pub(crate) fn send_in(
    store: &CloudStore,
    project_root: &str,
    agent_id: &str,
    message_type: Option<&str>,
    text: &str,
    extras: Extras<'_>,
) -> Result<String, String> {
    // A folder the person stopped sharing sends nothing, not even through
    // its main checkout or another checkout's record (rc4-6, bd 39657).
    if crate::unlinked::contains(store.data_dir(), std::path::Path::new(project_root)) {
        return Err(crate::unlinked::refusal(store.data_dir()));
    }
    if let Some(refusal) = super::control::admission(store, Some(agent_id)) {
        return Err(refusal.message());
    }
    let raw = message_type.ok_or("type is required (question|offer|handoff|answer|finding)")?;
    let kind = MessageType::parse(&raw.trim().to_ascii_lowercase()).ok_or_else(|| {
        format!("unknown type {raw:?}; use question|offer|handoff|answer|finding")
    })?;
    let map = crate::vault::connected_map(store);
    let record = crate::resolution::vault_in(&map, std::path::Path::new(project_root))
        .map_err(|e| e.to_string())?
        .ok_or("this repository is not linked to a vault (`lean-ctx cloud link <team>/<vault>`)")?;
    // §40: from here on it is an exchange with another machine; every
    // outcome leaves an audit record, and none that cannot be recorded
    // leaves the machine.
    let address = super::relay_v2::address_of(record);
    let now = lean_ctx_time::UtcDateTime::now();
    let audit = |outcome: &str| {
        let mut entry = exchange::Entry::now(now, "out", outcome, kind, &address);
        entry.agent = Some(agent_id.to_owned());
        entry.peer = extras.to_worker.map(str::to_owned);
        entry
    };
    let publish = match checked_publish(store, record, agent_id, kind, text, extras, now) {
        Ok(publish) => publish,
        Err(refusal) => {
            exchange::record(store.data_dir(), &audit("refused").refused_by(&refusal))
                .map_err(|e| format!("not sent: the exchange audit cannot be written: {e}"))?;
            return Err(format!("not sent: {}", refusal.why));
        }
    };
    let id = publish.client_msg_id.clone();
    let mut queued = audit("queued");
    queued.msg_id = Some(id.clone());
    queued.digest = Some(exchange::digest(&publish.body));
    exchange::record(store.data_dir(), &queued)
        .map_err(|e| format!("not sent: the exchange audit cannot be written: {e}"))?;
    // A handoff is remembered with its offering agent, so a maintainer's
    // veto of it reaches that agent ([`super::handoff`]).
    let offered = if kind == MessageType::Handoff
        && let Some(to) = extras.to_worker
    {
        super::handoff::offered(store.data_dir(), &id, agent_id, to)
    } else {
        Ok(())
    };
    if let Err(error) = offered.and_then(|()| super::relay_v2::queue_publish(store, publish)) {
        // The queued record stands for a message that never left: a second
        // record says so (best effort: the send is refused either way).
        let refusal = exchange::Refusal::new("queue", error.to_string());
        let mut unsent = queued.refused_by(&refusal);
        unsent.outcome = "refused".into();
        if let Err(audit) = exchange::record(store.data_dir(), &unsent) {
            tracing::warn!("cloud exchange audit: {audit}");
        }
        return Err(format!("not sent: {error}"));
    }
    Ok(id)
}

/// The publish of an exchange from `agent_id` to the vault of `record`,
/// after every outbound rule (§40: account, team policy, content, person
/// rules, C0 validation), or the rule that refuses it.
fn checked_publish(
    store: &CloudStore,
    record: &crate::vault::VaultRecord,
    agent_id: &str,
    kind: MessageType,
    text: &str,
    extras: Extras<'_>,
    now: lean_ctx_time::UtcDateTime,
) -> Result<Publish, exchange::Refusal> {
    use exchange::Refusal;
    let instance = store
        .instance()
        .map_err(|e| Refusal::new("account", e.to_string()))?
        .ok_or_else(|| Refusal::new("account", "this machine is not connected to the Cloud"))?;
    if let Some(refusal) = exchange::account_refusal(instance.org_kind.as_deref()) {
        return Err(refusal);
    }
    if let Some(refusal) = exchange::floor_refusal(store.data_dir(), &record.vault_id, kind, now) {
        return Err(refusal);
    }
    // Every field that leaves is screened, not only the text.
    let mut fields = vec![text, extras.resource.unwrap_or_default()];
    fields.extend(extras.refs.iter().map(String::as_str));
    exchange::screen_fields(&mut Screen::for_installation(), &fields)?;
    let message = |e: String| Refusal::new("message", e);
    let person = |e: String| Refusal::new("person_rules", e);
    let worker_id = worker_of(store, agent_id).map_err(message)?;
    // A handoff's resource is what the sender named, never a marked text.
    let extras = Extras {
        resource: extras
            .resource
            .or((kind == MessageType::Handoff).then_some(text)),
        ..extras
    };
    let refs = refs_of(extras.refs);
    // The always-enforced person rules first, on what the sender wrote.
    let written = body(kind, text, &worker_id, extras).map_err(message)?;
    person_rules::check_agent_body(kind, &written).map_err(|e| person(e.to_string()))?;
    person_rules::check_not_refused_in(
        store.data_dir(),
        kind,
        &refs,
        &written,
        agent_id,
        &worker_id,
    )
    .map_err(|e| person(e.to_string()))?;
    // Only the registered Queen appears as the Queen (process v1 §7): under
    // `warn` the text goes marked for its receiver, under `enforce` not at
    // all. The sender is looked up among the active presences.
    let sent = {
        let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
        person_rules::apply_queen_rule(
            store.data_dir(),
            person_rules::Speaker::of_registry(&registry, Some(agent_id)),
            &[text, extras.resource.unwrap_or_default()],
            text,
            Some(kind),
            person_rules::QueenMode::current(),
        )
        .map_err(|e| person(e.to_string()))?
    };
    let body = if sent == text {
        written
    } else {
        body(kind, &sent, &worker_id, extras).map_err(message)?
    };
    let now_ms = now.timestamp_millis().unsigned_abs();
    let publish = Publish {
        schema: BUS_SCHEMA.into(),
        client_msg_id: ulid_for(
            now_ms,
            &format!("{agent_id}:{}", uuid::Uuid::new_v4().simple()),
        ),
        to: super::relay_v2::address_of(record),
        kind,
        worker_id,
        thread_id: None,
        reply_to: extras.reply_to.map(str::to_owned),
        refs,
        body,
        ck_wrapped: None,
        epoch: None,
        about: None,
        counts: None,
        window: None,
    };
    // Refused before anything is remembered (a refused handoff is no offer).
    publish.validate().map_err(|e| message(e.to_string()))?;
    Ok(publish)
}

/// How a delivered typed message reads on the local bus: its type and id
/// (to reply to), thread and state, who it is for, then the text.
pub fn delivered_line(message: &Value) -> Option<String> {
    let kind = message["type"].as_str()?;
    if kind == "progress" {
        return None;
    }
    let body = &message["body"];
    let mut head = format!("{kind} {}", message["id"].as_str().unwrap_or("?"));
    if let Some(thread) = message["thread_id"]
        .as_str()
        .filter(|t| Some(*t) != message["id"].as_str())
    {
        head.push_str(&format!(" in thread {thread}"));
    }
    if let Some(status) = message["thread_status"].as_str() {
        head.push_str(&format!(" [{status}]"));
    }
    if let Some(to) = body["to_worker"].as_str() {
        head.push_str(&format!(" for {to}"));
    }
    if let Some(accept) = body["accept"].as_bool() {
        head.push_str(if accept { " (accepted)" } else { " (declined)" });
    }
    let text = match kind {
        "handoff" => format!(
            "hands over {} to {}: {}",
            body["resource"].as_str().unwrap_or("?"),
            body["to_worker"].as_str().unwrap_or("?"),
            body["note"].as_str().unwrap_or_default()
        ),
        "finding" => body["statement"].as_str().unwrap_or_default().to_owned(),
        "offer" => body["what"].as_str().unwrap_or_default().to_owned(),
        _ => body["text"]
            .as_str()
            .map_or_else(|| body.to_string(), str::to_owned),
    };
    Some(format!(
        "{head} — reply with ctx_agent action=reply reply_to={}: {text}",
        message["id"].as_str().unwrap_or("?")
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    const ME: &str = "wkr_aaaaaaaaaaaaaaaaaaaa";
    const YOU: &str = "wkr_bbbbbbbbbbbbbbbbbbbb";

    fn x<'a>() -> Extras<'a> {
        Extras::default()
    }

    #[test]
    fn bodies_follow_the_bus_v2_schema() {
        let question = body(
            MessageType::Question,
            "Retry budget?",
            ME,
            Extras {
                to_worker: Some(YOU),
                ..x()
            },
        )
        .unwrap();
        assert_eq!(question, json!({"text": "Retry budget?", "to_worker": YOU}));
        let answer = body(
            MessageType::Answer,
            "Yes.",
            ME,
            Extras {
                reply_to: Some("msg_1"),
                accept: Some(true),
                ..x()
            },
        )
        .unwrap();
        assert_eq!(answer, json!({"text": "Yes.", "accept": true}));
        let handoff = body(
            MessageType::Handoff,
            "Take the tests.",
            ME,
            Extras {
                to_worker: Some(YOU),
                resource: Some("tests/auth"),
                ..x()
            },
        )
        .unwrap();
        assert_eq!(
            handoff,
            json!({"to_worker": YOU, "resource": "tests/auth", "note": "Take the tests."})
        );
        let cites = ["file:src/retry.rs".to_owned(), "tests/auth".to_owned()];
        assert_eq!(
            refs_of(&cites).len(),
            1,
            "only kind:target entries are refs"
        );
        assert!(
            body(MessageType::Finding, "The cap is 3.", ME, x()).is_err(),
            "a finding needs a ref"
        );
        let finding = body(
            MessageType::Finding,
            "The retry cap is three attempts in retry().",
            ME,
            Extras {
                refs: &cites,
                ..x()
            },
        )
        .unwrap();
        assert_eq!(finding["evidence"], "stated");
        let offer = body(MessageType::Offer, "I can review retry().", ME, x()).unwrap();
        // Every body passes the engine's own bus v2 check before it is queued.
        for (kind, message_body, reply_to) in [
            (MessageType::Question, question, None),
            (MessageType::Answer, answer, Some("msg_00000000000000a1")),
            (MessageType::Handoff, handoff, None),
            (MessageType::Finding, finding, None),
            (MessageType::Offer, offer, None),
        ] {
            let publish = Publish {
                schema: BUS_SCHEMA.into(),
                client_msg_id: "01M5NKA2Z8B000000000000009".into(),
                to: "#acme/payments".into(),
                kind,
                worker_id: ME.into(),
                thread_id: None,
                reply_to: reply_to.map(Into::into),
                refs: if kind == MessageType::Finding {
                    refs_of(&cites)
                } else {
                    Vec::new()
                },
                body: message_body,
                ck_wrapped: None,
                epoch: None,
                about: None,
                counts: None,
                window: None,
            };
            assert!(
                publish.validate().is_ok(),
                "{kind:?}: {:?}",
                publish.validate()
            );
        }
    }

    #[test]
    fn refusals_name_what_is_missing() {
        assert!(
            body(MessageType::Answer, "x", ME, x())
                .unwrap_err()
                .contains("reply_to")
        );
        assert!(
            body(MessageType::Handoff, "x", ME, x())
                .unwrap_err()
                .contains("to_agent")
        );
        let local = body(
            MessageType::Question,
            "x",
            ME,
            Extras {
                to_worker: Some("mcp-1-abc"),
                ..x()
            },
        )
        .unwrap_err();
        assert!(local.contains("worker id"), "{local}");
        assert!(body(MessageType::Progress, "x", ME, x()).is_err());
    }

    #[test]
    fn a_delivery_shows_how_to_reply() {
        let m = json!({
            "id": "msg_2", "type": "answer", "thread_id": "msg_1", "thread_status": "answered",
            "body": {"text": "Three attempts."}
        });
        let line = delivered_line(&m).unwrap();
        assert!(
            line.starts_with("answer msg_2 in thread msg_1 [answered]"),
            "{line}"
        );
        assert!(line.contains("reply_to=msg_2") && line.ends_with("Three attempts."));
        let h = json!({"id": "msg_3", "type": "handoff", "body": {"to_worker": YOU, "resource": "tests/auth", "note": "please"}});
        assert!(
            delivered_line(&h)
                .unwrap()
                .contains("hands over tests/auth to")
        );
        assert!(delivered_line(&json!({"type": "progress", "body": {"step": "x"}})).is_none());
    }
}