Skip to main content

lean_ctx_cloud/bus/
plan_events.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Plan updates to running agents (contract §37). A person changes the plan
3//! or a team decision in LeanCTX Code; Cloud tells every engine of the vault
4//! with a text-free frame:
5//!
6//! - `plan.advanced {vault, plan_id, version}`: the engine pulls the plan
7//!   document (`GET /v1/vaults/{id}/plans/{plan_id}?version=n`), checks its
8//!   `content_sha256` and its Cloud `control` signature, keeps the last good
9//!   version in `<cloud data>/plans/<plan_id>.json`, and gives each local
10//!   agent the plan names a directive (`core::agents::DirectiveStore`);
11//!   every other active agent of the checkout gets a plan-wide one.
12//! - `decision.changed {vault, decision_id, status, superseded_by?}`:
13//!   Cloud sends it only after the person's confirmed "Send to agents" on a
14//!   team decision in LeanCTX Code, so the frame is the release: each active
15//!   agent of the checkout gets the decision directive on the bus at once
16//!   (`deliver_decision`). The same decision, status and successor again (a
17//!   frame delivered twice) posts nothing. Only the frame posts a bus
18//!   directive: no catch-up, sync or list does. Agents that start later get
19//!   the sent text from `crate::team_decisions` (rc4-69): a sync keeps a
20//!   decision only when the same list entry is `active` with a Cloud
21//!   `sent_at`, which Cloud clears on every later change, so text edited
22//!   after the send is never delivered.
23//!
24//! Agents get a plan update only after a person clicked "Send to agents" in
25//! LeanCTX Code and confirmed it (owner decision). A plan frame or a pulled
26//! version only **offers** directives: they are recorded, invisible to the
27//! agents (no bus entry, no pending line). Code releases each one with the
28//! local CLI `lean-ctx cloud plan release` (release id on stdin); nothing in
29//! this module, the bus or a Cloud frame can release one (`apply` gets the
30//! registry read-only). Delivering means posting a `cloud` directive on the
31//! local agent bus, which an agent reads with `ctx_agent`: nothing is typed
32//! into an agent's terminal and no agent is started or restarted. Both
33//! frames are taken only when `hello.ack` names [`PLAN_UPDATES`].
34//!
35//! A version that fails the checks is never shown as an instruction; the
36//! engine refuses it to Cloud with a reason code. Plan versions only move
37//! forward ([`PlansSeen`]); a frame missed while offline is caught up after
38//! each hello from `GET …/plans?state=active`. The agents' answers go back
39//! per version (`POST …/plans/{plan_id}/ack`), with an HMAC of the local
40//! agent id, never the id or any free text.
41//!
42//! Cloud keeps the plan body encrypted at rest and serves it as plain text
43//! (`body`). The engine opens it only after its digest and the signature
44//! checked out, and checks that every session the document routes names a
45//! slot of the body whose brief has the session's `brief_sha256`
46//! ([`super::plan_body`]). The goal and the brief an agent reads come from
47//! that verified body alone; the offered directive keeps their digests, and
48//! the person's release from Code is checked against them.
49
50use std::collections::BTreeMap;
51#[cfg(feature = "http-server")]
52use std::path::Path;
53
54use ed25519_dalek::Signature;
55use serde::{Deserialize, Serialize};
56use serde_json::{Value, json};
57use sha2::{Digest as _, Sha256};
58
59use super::plan_body::PlanBody;
60use super::v2::ControlKeys;
61#[cfg(feature = "http-server")]
62use lean_ctx::core::agents::{AgentEntry, AgentRegistry, DirectiveStore};
63use lean_ctx::core::agents::{Directive, DirectiveIssue, DirectiveKind, DirectiveState};
64
65#[cfg(feature = "http-server")]
66use super::address::Address;
67#[cfg(feature = "http-server")]
68use crate::vault::{VaultMap, VaultRecord};
69
70/// The `hello.ack` feature of a Cloud that serves the plan routes.
71pub const PLAN_UPDATES: &str = "plan_updates";
72/// Signature domain of a plan version (`domain ‖ canonical_json(statement)`,
73/// see [`plan_statement`]), as controls are signed.
74pub const PLAN_DOMAIN: &str = "leanctx.cloud.plan.v1\n";
75pub const PLAN_SCHEMA: &str = "leanctx.cloud.plan/v1";
76/// Schema of the statement Cloud signs for a plan version.
77pub const PLAN_STATEMENT_SCHEMA: &str = "leanctx.cloud.plan-statement/v1";
78/// Agents per ack request (the route's `maxItems`).
79const MAX_ACK_AGENTS: usize = 64;
80/// Sessions per plan.
81const MAX_SESSIONS: usize = 32;
82/// Plans remembered per vault.
83#[cfg(any(test, feature = "http-server"))]
84const MAX_PLANS: usize = 200;
85
86fn chars_ok(text: &str, min: usize, max: usize, ok: impl Fn(char) -> bool) -> bool {
87    (min..=max).contains(&text.chars().count()) && text.chars().all(ok)
88}
89
90pub(crate) fn plan_id_ok(id: &str) -> bool {
91    id.strip_prefix("plan_")
92        .is_some_and(|rest| chars_ok(rest, 8, 40, |c| c.is_ascii_alphanumeric()))
93}
94
95/// Cloud's decision id: `dec-` and lowercase kebab segments (`[a-z0-9]+`
96/// joined by single `-`), at most 80 characters in all. The engine checks
97/// an id it sends to the Cloud by the same rule.
98pub fn decision_id_ok(id: &str) -> bool {
99    id.len() <= 80
100        && id.strip_prefix("dec-").is_some_and(|rest| {
101            rest.split('-').all(|segment| {
102                !segment.is_empty()
103                    && segment
104                        .chars()
105                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
106            })
107        })
108}
109
110pub(crate) fn slot_ok(slot: &str) -> bool {
111    slot != ALL_SLOT
112        && chars_ok(slot, 1, 32, |c| {
113            c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'
114        })
115}
116
117pub(crate) fn task_id_ok(id: &str) -> bool {
118    chars_ok(id, 1, 128, |c| {
119        c.is_ascii_alphanumeric() || "._:-".contains(c)
120    })
121}
122
123fn sha_ok(digest: &str) -> bool {
124    digest.strip_prefix("sha256:").is_some_and(|hex| {
125        hex.len() == 64
126            && hex
127                .chars()
128                .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
129    })
130}
131
132/// One `plan.advanced` frame (or a plan a catch-up found newer).
133#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
134#[serde(deny_unknown_fields)]
135pub struct PlanAdvanced {
136    #[serde(default)]
137    t: Option<String>,
138    pub vault: String,
139    pub plan_id: String,
140    pub version: u64,
141}
142
143impl PlanAdvanced {
144    pub fn new(vault: &str, plan_id: &str, version: u64) -> Self {
145        Self {
146            t: None,
147            vault: vault.to_string(),
148            plan_id: plan_id.to_string(),
149            version,
150        }
151    }
152
153    pub fn parse(frame: &Value) -> Option<Self> {
154        serde_json::from_value(frame.clone())
155            .ok()
156            .filter(|e: &Self| e.version >= 1 && plan_id_ok(&e.plan_id))
157            .map(|e| Self { t: None, ..e })
158    }
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
162#[serde(rename_all = "snake_case")]
163pub enum DecisionStatus {
164    Active,
165    Superseded,
166    Revoked,
167}
168
169impl DecisionStatus {
170    pub fn as_str(self) -> &'static str {
171        match self {
172            DecisionStatus::Active => "active",
173            DecisionStatus::Superseded => "superseded",
174            DecisionStatus::Revoked => "revoked",
175        }
176    }
177}
178
179/// One `decision.changed` frame.
180#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
181#[serde(deny_unknown_fields)]
182pub struct DecisionChanged {
183    #[serde(default)]
184    t: Option<String>,
185    pub vault: String,
186    pub decision_id: String,
187    pub status: DecisionStatus,
188    #[serde(default)]
189    pub superseded_by: Option<String>,
190}
191
192impl DecisionChanged {
193    pub fn parse(frame: &Value) -> Option<Self> {
194        serde_json::from_value(frame.clone())
195            .ok()
196            .filter(|e: &Self| {
197                decision_id_ok(&e.decision_id)
198                    && e.superseded_by.as_deref().is_none_or(decision_id_ok)
199            })
200            .map(|e| Self { t: None, ..e })
201    }
202}
203
204// The pulled document tolerates fields it does not know (a later Cloud
205// may add some); they are not kept, signed or shown.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct PlanSignature {
208    pub key_id: String,
209    pub sig: String,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct PlanSession {
214    pub slot: String,
215    pub task_id: Option<String>,
216    #[serde(default)]
217    pub worker_id: Option<String>,
218    pub brief_sha256: String,
219    #[serde(default)]
220    pub changed: bool,
221}
222
223/// A plan document `leanctx.cloud.plan/v1` (§37.3).
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
225pub struct PlanDoc {
226    pub schema: String,
227    pub plan_id: String,
228    pub vault: String,
229    pub version: u64,
230    #[serde(default)]
231    pub supersedes_version: Option<u64>,
232    pub content_sha256: String,
233    pub issued_by: String,
234    /// When the person published this version (RFC 3339), as Cloud sets it.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub published_at: Option<String>,
237    #[serde(default)]
238    pub signature: Option<PlanSignature>,
239    /// The plan body `leanctx.plan-body/v1` as standard base64 with
240    /// padding (1 B–256 KiB decoded); `content_sha256` is its digest.
241    pub body: String,
242    pub sessions: Vec<PlanSession>,
243}
244
245/// Why the engine did not take a version (the ack's `refused.reason_code`).
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum PlanRefusal {
248    DigestMismatch,
249    SignatureInvalid,
250    OlderThanApplied,
251    /// Reserved (the ack route's enum): Cloud serves the body as plain
252    /// text, so nothing is decrypted and this code is never sent.
253    DecryptFailed,
254}
255
256impl PlanRefusal {
257    pub fn code(self) -> &'static str {
258        match self {
259            PlanRefusal::DigestMismatch => "digest_mismatch",
260            PlanRefusal::SignatureInvalid => "signature_invalid",
261            PlanRefusal::OlderThanApplied => "older_than_applied",
262            PlanRefusal::DecryptFailed => "decrypt_failed",
263        }
264    }
265}
266
267/// A plan document that was not taken.
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub enum Rejected {
270    /// Refused to Cloud (the document is a plan, but not this one's).
271    Refuse {
272        refusal: PlanRefusal,
273        content_sha256: String,
274    },
275    /// Not a plan document of the requested version; recorded locally.
276    Invalid(String),
277}
278
279fn invalid(what: &str) -> Rejected {
280    Rejected::Invalid(format!("plan document: {what}"))
281}
282
283/// A vault id compared by its 32 hex digits: lowercase, without `-`.
284pub fn vault_key(id: &str) -> String {
285    id.chars()
286        .filter(|c| *c != '-')
287        .map(|c| c.to_ascii_lowercase())
288        .collect()
289}
290
291/// Check one pulled document against the frame that announced it, the
292/// enrolled vault it was read from (`vault_id`, the id of the GET), its
293/// digest and its signature. The frame's `vault` is the subscription
294/// address and only routes; the document's `vault` is the vault id Cloud
295/// signed (32 hex), bound to the enrolled one.
296pub fn verify(
297    raw: &Value,
298    expect: &PlanAdvanced,
299    vault_id: &str,
300    keys: &ControlKeys,
301) -> Result<PlanDoc, Rejected> {
302    let doc: PlanDoc =
303        serde_json::from_value(raw.clone()).map_err(|e| invalid(&format!("shape: {e}")))?;
304    if doc.schema != PLAN_SCHEMA {
305        return Err(invalid("schema"));
306    }
307    if doc.plan_id != expect.plan_id || doc.version != expect.version {
308        return Err(invalid("not the announced plan version"));
309    }
310    let enrolled = vault_key(vault_id);
311    let is_id = enrolled.len() == 32
312        && enrolled
313            .chars()
314            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c));
315    if !is_id || vault_key(&doc.vault) != enrolled {
316        return Err(invalid("not the enrolled vault"));
317    }
318    let shape_ok = plan_id_ok(&doc.plan_id)
319        && doc.version >= 1
320        && sha_ok(&doc.content_sha256)
321        && !doc.issued_by.trim().is_empty()
322        && doc.sessions.len() <= MAX_SESSIONS
323        && doc.sessions.iter().all(|s| {
324            (s.slot == ALL_SLOT || slot_ok(&s.slot))
325                && sha_ok(&s.brief_sha256)
326                && s.worker_id.as_deref().is_none_or(task_id_ok)
327                && s.task_id.as_deref().is_none_or(task_id_ok)
328        });
329    if !shape_ok {
330        return Err(invalid("fields"));
331    }
332    let refuse = |refusal| Rejected::Refuse {
333        refusal,
334        content_sha256: doc.content_sha256.clone(),
335    };
336    let body = super::plan_body::decode_body(&doc.body).map_err(|e| invalid(&e))?;
337    if super::plan_body::sha256_of(&body) != doc.content_sha256 {
338        return Err(refuse(PlanRefusal::DigestMismatch));
339    }
340    let signature = doc
341        .signature
342        .as_ref()
343        .ok_or_else(|| refuse(PlanRefusal::SignatureInvalid))?;
344    let key = keys
345        .get(&signature.key_id)
346        .ok_or_else(|| refuse(PlanRefusal::SignatureInvalid))?;
347    let mut sig = [0u8; 64];
348    hex::decode_to_slice(&signature.sig, &mut sig)
349        .map_err(|_| refuse(PlanRefusal::SignatureInvalid))?;
350    let input = lean_ctx_protocol::cloud::signing_input_without_signature(
351        PLAN_DOMAIN,
352        &plan_statement(&doc, &signature.key_id),
353    )
354    .map_err(|_| invalid("not signable"))?;
355    key.verify_strict(&input, &Signature::from_bytes(&sig))
356        .map_err(|_| refuse(PlanRefusal::SignatureInvalid))?;
357    // Signed, so Cloud vouches for the bytes; a body that is no plan body
358    // is a publisher's fault, noted locally.
359    let opened = PlanBody::parse(&body).map_err(|e| invalid(&e))?;
360    // The routing must match the verified text: every routed slot is a
361    // slot of the body (or `all`) with that brief. Otherwise nothing is
362    // offered (Cloud does not check this).
363    let routed_ok = doc.sessions.iter().all(|s| {
364        s.slot == ALL_SLOT
365            || opened
366                .session(&s.slot)
367                .is_some_and(|b| super::plan_body::sha256_of(b.brief.as_bytes()) == s.brief_sha256)
368    });
369    if !routed_ok {
370        return Err(refuse(PlanRefusal::DigestMismatch));
371    }
372    Ok(doc)
373}
374
375impl PlanDoc {
376    /// The body of a verified document ([`verify`]); `None` for a document
377    /// whose body does not open (never one that verified).
378    pub fn opened(&self) -> Option<PlanBody> {
379        self.open().ok()
380    }
381
382    /// The verified body, or why it does not open: `invalid` (no base64 of
383    /// 1 B–256 KiB, or no `leanctx.plan-body/v1`) or `digest_mismatch`.
384    /// The signature was checked when the version was taken (§37.3); only
385    /// verified versions are kept.
386    pub fn open(&self) -> Result<PlanBody, &'static str> {
387        let bytes = super::plan_body::decode_body(&self.body).map_err(|_| "invalid")?;
388        if super::plan_body::sha256_of(&bytes) != self.content_sha256 {
389            return Err(PlanRefusal::DigestMismatch.code());
390        }
391        PlanBody::parse(&bytes).map_err(|_| "invalid")
392    }
393}
394
395/// The statement Cloud signs for a version (§37.3): ids, version, body
396/// digest, issuer and signing key, never the body or the sessions. Rebuilt
397/// from the received document, so a changed vault, version, digest or issuer
398/// no longer verifies.
399pub fn plan_statement(doc: &PlanDoc, key_id: &str) -> Value {
400    json!({
401        "schema": PLAN_STATEMENT_SCHEMA,
402        "vault": doc.vault,
403        "plan_id": doc.plan_id,
404        "version": doc.version,
405        "content_sha256": doc.content_sha256,
406        "issued_by": doc.issued_by,
407        "key_id": key_id,
408    })
409}
410
411/// Vault address (`#ws/vault`) → `plan_id` → the version applied.
412pub type PlansSeen = BTreeMap<String, BTreeMap<String, u64>>;
413
414/// The version of `plan_id` applied in `vault`, if any.
415pub fn applied(seen: &PlansSeen, vault: &str, plan_id: &str) -> Option<u64> {
416    seen.get(vault)
417        .and_then(|plans| plans.get(plan_id))
418        .copied()
419}
420
421/// Record `version` as applied; false when it or a newer one already is.
422#[cfg(any(test, feature = "http-server"))]
423fn admit(seen: &mut PlansSeen, vault: &str, plan_id: &str, version: u64) -> bool {
424    let plans = seen.entry(vault.to_string()).or_default();
425    if plans.get(plan_id).is_some_and(|known| *known >= version) {
426        return false;
427    }
428    plans.insert(plan_id.to_string(), version);
429    while plans.len() > MAX_PLANS {
430        let Some(first) = plans.keys().next().cloned() else {
431            break;
432        };
433        plans.remove(&first);
434    }
435    true
436}
437
438fn ack_hint(directive_id: &str) -> String {
439    lean_ctx::core::agents::ack_hint(directive_id)
440}
441
442/// The slot of the directive for an agent no session of the plan names
443/// (`<plan_id>:<version>:all`), and of a session routed to every agent
444/// (`slot: "all"`): no part of the body names it, so it has no brief.
445pub const ALL_SLOT: &str = "all";
446
447/// The directive each local agent gets for a verified plan: per named
448/// session (its worker id is the session's `worker_id`), or one plan-wide
449/// `…:all` directive for an agent no session names. `local` are the
450/// project's active agents with their Cloud worker ids. Each directive
451/// keeps the digest of the verified body's goal; a document whose body
452/// does not open offers nothing.
453pub fn plan_directives(
454    doc: &PlanDoc,
455    vault_id: &str,
456    local: &[(String, Option<String>)],
457) -> Vec<(String, DirectiveIssue)> {
458    let mut out = Vec::new();
459    let Some(body) = doc.opened() else {
460        return out;
461    };
462    let goal_sha256 = super::plan_body::sha256_of(body.goal.as_bytes());
463    for (agent, worker) in local {
464        let session = worker.as_deref().and_then(|w| {
465            doc.sessions
466                .iter()
467                .find(|s| s.worker_id.as_deref() == Some(w))
468        });
469        let brief_sha256 = session
470            .filter(|s| s.slot != ALL_SLOT)
471            .map(|s| s.brief_sha256.clone());
472        let (slot, task_id) = match session {
473            Some(session) => (session.slot.clone(), session.task_id.clone()),
474            None => (ALL_SLOT.to_string(), None),
475        };
476        let directive_id = format!("{}:{}:{slot}", doc.plan_id, doc.version);
477        out.push((
478            agent.clone(),
479            DirectiveIssue {
480                directive_id,
481                kind: DirectiveKind::Plan,
482                subject: doc.plan_id.clone(),
483                version: doc.version,
484                slot: Some(slot),
485                worker_id: session.and_then(|s| s.worker_id.clone()),
486                task_id,
487                vault_id: vault_id.to_string(),
488                digest: doc.content_sha256.clone(),
489                brief_sha256,
490                goal_sha256: Some(goal_sha256.clone()),
491                // No plan text before the person's release (37.4).
492                text: String::new(),
493            },
494        ));
495    }
496    out
497}
498
499/// The directive id of a decision change, `<decision_id>:<status>:<n>`: `n`
500/// numbers the decision's changes this Instance saw (`known`, the kept
501/// records). The same status and successor again (a frame delivered twice)
502/// keeps the last id; a change back (superseded, then active again) or
503/// another successor gets a new one, so it is never taken for the earlier
504/// directive.
505pub fn decision_directive_id(known: &[Directive], event: &DecisionChanged) -> String {
506    let prefix = format!("{}:", event.decision_id);
507    let last = known
508        .iter()
509        .filter(|d| d.kind == DirectiveKind::Decision && d.subject == event.decision_id)
510        .filter_map(|d| {
511            let (status, n) = d.directive_id.strip_prefix(&prefix)?.split_once(':')?;
512            Some((n.parse::<u64>().ok()?, status.to_string(), d.digest.clone()))
513        })
514        .max();
515    match last {
516        Some((n, status, successor))
517            if status == event.status.as_str() && successor == decision_successor(event) =>
518        {
519            format!("{prefix}{status}:{n}")
520        }
521        Some((n, _, _)) => format!("{prefix}{}:{}", event.status.as_str(), n + 1),
522        None => format!("{prefix}{}:1", event.status.as_str()),
523    }
524}
525
526/// What a decision directive keeps as its `digest`: the decision that
527/// superseded it, empty without one.
528fn decision_successor(event: &DecisionChanged) -> String {
529    event.superseded_by.clone().unwrap_or_default()
530}
531
532/// The directive a decision change asks of every local agent of its vault.
533/// `known` are the kept records ([`decision_directive_id`]).
534pub fn decision_directive(
535    event: &DecisionChanged,
536    vault_id: &str,
537    known: &[Directive],
538) -> DirectiveIssue {
539    let directive_id = decision_directive_id(known, event);
540    let id = &event.decision_id;
541    let what = match (event.status, event.superseded_by.as_deref()) {
542        (DecisionStatus::Superseded, Some(by)) => {
543            format!("was superseded by {by}; work that relies on {id} may no longer apply")
544        }
545        (DecisionStatus::Superseded, None) => {
546            format!("was superseded; work that relies on {id} may no longer apply")
547        }
548        (DecisionStatus::Revoked, _) => {
549            format!("was revoked; work that relies on {id} may no longer apply")
550        }
551        (DecisionStatus::Active, _) => format!("is now active; follow {id} from here on"),
552    };
553    let text = format!(
554        "Cloud: team decision {id} {what}. Re-read the project's decisions before you go on. {hint}",
555        hint = ack_hint(&directive_id),
556    );
557    DirectiveIssue {
558        directive_id,
559        kind: DirectiveKind::Decision,
560        subject: event.decision_id.clone(),
561        version: 0,
562        slot: None,
563        worker_id: None,
564        task_id: None,
565        vault_id: vault_id.to_string(),
566        digest: decision_successor(event),
567        brief_sha256: None,
568        goal_sha256: None,
569        text,
570    }
571}
572
573/// Deliver one `decision.changed` frame: post its directive to every active
574/// local agent of the vault's checkout. Called only from the frame (Cloud
575/// sends it only after the person's confirmed "Send to agents"); a frame
576/// delivered twice posts nothing. Returns how many agents got it. An agent
577/// that cannot take it does not stop the others: their errors are collected
578/// and reported together once every agent was tried.
579#[cfg(feature = "http-server")]
580pub(crate) fn deliver_decision(
581    registry: &mut AgentRegistry,
582    store: &mut DirectiveStore,
583    map: &VaultMap,
584    event: &DecisionChanged,
585) -> Result<usize, String> {
586    let Some((record, root)) = record_of(map, &event.vault) else {
587        return Ok(0);
588    };
589    let issue = decision_directive(event, &record.vault_id, &store.directives);
590    let agents: Vec<String> = registry
591        .list_active(Some(root))
592        .into_iter()
593        .map(|agent| agent.agent_id.clone())
594        .collect();
595    let mut delivered = 0;
596    let mut errors = Vec::new();
597    for agent in agents {
598        match store.deliver_decision(registry, root, &agent, &issue) {
599            Ok(true) => delivered += 1,
600            Ok(false) => {}
601            Err(error) => errors.push(format!("agent {agent}: {error}")),
602        }
603    }
604    if errors.is_empty() {
605        Ok(delivered)
606    } else {
607        Err(format!(
608            "decision {} reached {delivered} agent(s); {}",
609            event.decision_id,
610            errors.join("; ")
611        ))
612    }
613}
614
615/// The ack route's `agent_type` for a local agent type.
616pub fn agent_type(local: &str) -> &'static str {
617    let local = local.to_ascii_lowercase();
618    if local.contains("claude") {
619        "claude"
620    } else if local.contains("codex") {
621        "codex"
622    } else if local.contains("cursor") {
623        "cursor"
624    } else {
625        "other"
626    }
627}
628
629/// One `POST …/plans/{plan_id}/ack` and what it reports.
630#[derive(Debug, Clone, PartialEq)]
631pub struct AckRequest {
632    pub vault_id: String,
633    pub plan_id: String,
634    pub body: Value,
635    /// The idempotency key: changes whenever a reported state does.
636    pub key: String,
637    pub covers: Vec<(String, String, DirectiveState)>,
638}
639
640/// The ack requests for `due` directives, one per vault, plan, version and
641/// 64 agents, in a stable order. `agent_ref` hides the local agent id;
642/// `agent_type_of` names its host.
643pub fn ack_requests(
644    due: &[&Directive],
645    agent_ref: &dyn Fn(&str) -> String,
646    agent_type_of: &dyn Fn(&str) -> &'static str,
647) -> Vec<AckRequest> {
648    let mut groups: BTreeMap<(&str, &str, u64, &str), Vec<&Directive>> = BTreeMap::new();
649    for d in due.iter().filter(|d| d.kind == DirectiveKind::Plan) {
650        groups
651            .entry((&d.vault_id, &d.subject, d.version, &d.digest))
652            .or_default()
653            .push(d);
654    }
655    let mut out = Vec::new();
656    for ((vault_id, plan_id, version, digest), mut members) in groups {
657        members.sort_by(|a, b| (&a.agent_id, &a.directive_id).cmp(&(&b.agent_id, &b.directive_id)));
658        for chunk in members.chunks(MAX_ACK_AGENTS) {
659            let agents: Vec<Value> = chunk
660                .iter()
661                .filter_map(|d| {
662                    Some(json!({
663                        "agent_ref": agent_ref(&d.agent_id),
664                        "worker_id": d.worker_id,
665                        "slot": d.slot,
666                        "agent_type": agent_type_of(&d.agent_id),
667                        "state": d.state.wire()?,
668                        "reason_code": d.reason_code,
669                    }))
670                })
671                .collect();
672            let body = json!({
673                "version": version,
674                "content_sha256": digest,
675                "agents": agents,
676                "refused": null,
677            });
678            out.push(AckRequest {
679                vault_id: vault_id.to_string(),
680                plan_id: plan_id.to_string(),
681                key: ack_key(plan_id, version, &body),
682                body,
683                covers: chunk
684                    .iter()
685                    .map(|d| (d.agent_id.clone(), d.directive_id.clone(), d.state))
686                    .collect(),
687            });
688        }
689    }
690    out
691}
692
693/// The engine-level refusal of one version.
694pub fn refusal_request(
695    vault_id: &str,
696    plan_id: &str,
697    version: u64,
698    content_sha256: &str,
699    refusal: PlanRefusal,
700    applied_version: Option<u64>,
701) -> AckRequest {
702    let body = json!({
703        "version": version,
704        "content_sha256": content_sha256,
705        "agents": [],
706        "refused": {"reason_code": refusal.code(), "applied_version": applied_version},
707    });
708    AckRequest {
709        vault_id: vault_id.to_string(),
710        plan_id: plan_id.to_string(),
711        key: ack_key(plan_id, version, &body),
712        body,
713        covers: Vec::new(),
714    }
715}
716
717fn ack_key(plan_id: &str, version: u64, body: &Value) -> String {
718    let digest = hex::encode(Sha256::digest(body.to_string().as_bytes()));
719    format!("plan-ack:{plan_id}:{version}:{}", &digest[..32])
720}
721
722// ----- the relay's side: HTTP and the local bus (feature `http-server`) -----
723
724/// Cloud has no control key yet, so it publishes and serves no plans
725/// (`409 not_ready`, §37.2): plan updates are not available. Not an error
726/// to retry; nothing is applied.
727pub const PLANS_NOT_READY: &str = "plan updates not available (the Cloud has no signing key yet)";
728
729/// Whether a `hello.ack` names [`PLAN_UPDATES`]: without it the relay
730/// ignores `plan.advanced` and `decision.changed` and pulls nothing (§37.1).
731pub fn frames_taken(ack: &Value) -> bool {
732    super::relay_v2::acks_feature(ack, PLAN_UPDATES)
733}
734
735/// Whether `error` is Cloud's `409 not_ready` for plans.
736pub fn plans_not_ready(error: &crate::CloudError) -> bool {
737    matches!(error, crate::CloudError::Server { status: 409, code } if code == crate::error::NOT_READY)
738}
739
740/// What one pull gave.
741#[cfg(feature = "http-server")]
742#[derive(Debug)]
743pub(crate) enum PlanOutcome {
744    /// A verified version, to apply on the relay's loop.
745    Verified {
746        vault: String,
747        vault_id: String,
748        root: String,
749        doc: Box<PlanDoc>,
750    },
751    /// Nothing to apply; a note for the error record.
752    Note(String),
753}
754
755#[cfg(feature = "http-server")]
756fn record_of<'a>(map: &'a VaultMap, address: &str) -> Option<(&'a VaultRecord, &'a str)> {
757    let Ok(Address::Vault { workspace, vault }) = Address::parse(Some(address)) else {
758        return None;
759    };
760    let record = map
761        .vaults
762        .values()
763        .find(|r| r.ns == workspace && r.name == vault)?;
764    let root = record.roots.iter().find(|root| Path::new(root).is_dir())?;
765    Some((record, root.as_str()))
766}
767
768#[cfg(feature = "http-server")]
769fn post_ack(root: &str, request: &AckRequest) -> Result<(), String> {
770    let conn = super::leases::connected(Path::new(root))?;
771    let path = format!("/vaults/{}/plans/{}/ack", conn.vault_id, request.plan_id);
772    match conn
773        .session
774        .with_client(|c| c.post_idempotent(&path, &request.body, &request.key))
775    {
776        // `409` (`stale_version` or the key's earlier answer): a newer
777        // version exists or Cloud has this answer; it counts as delivered.
778        Ok(_)
779        | Err(crate::CloudError::Conflict { .. } | crate::CloudError::Server { status: 409, .. }) => {
780            Ok(())
781        }
782        Err(error) => Err(format!("plan ack {}: {error}", request.plan_id)),
783    }
784}
785
786/// Pull, verify and keep the announced versions. Blocking (HTTP); the relay
787/// runs it off its session loop. A version equal to the applied one is not
788/// pulled; an older one, or one that fails its checks, is refused to Cloud
789/// and never applied.
790#[cfg(feature = "http-server")]
791pub(crate) fn fetch(
792    map: &VaultMap,
793    data_dir: &Path,
794    seen: &PlansSeen,
795    keys: &ControlKeys,
796    events: &[PlanAdvanced],
797) -> Vec<PlanOutcome> {
798    let mut out = Vec::new();
799    for event in events {
800        let applied_version = applied(seen, &event.vault, &event.plan_id);
801        // An equal version is a no-op; an older one announced as new is
802        // pulled, checked and refused `older_than_applied` (§37.3 step 4).
803        if applied_version == Some(event.version) {
804            continue;
805        }
806        let older = applied_version.is_some_and(|v| v > event.version);
807        let Some((record, root)) = record_of(map, &event.vault) else {
808            continue;
809        };
810        let note = |what: String| {
811            PlanOutcome::Note(format!("{} v{}: {what}", event.plan_id, event.version))
812        };
813        let conn = match super::leases::connected(Path::new(root)) {
814            Ok(conn) => conn,
815            Err(error) => {
816                out.push(note(error));
817                continue;
818            }
819        };
820        let path = format!(
821            "/vaults/{}/plans/{}?version={}",
822            conn.vault_id, event.plan_id, event.version
823        );
824        let raw = match conn.session.with_client(|c| c.get(&path)) {
825            Ok(raw) => raw,
826            Err(error) if plans_not_ready(&error) => {
827                out.push(note(PLANS_NOT_READY.to_string()));
828                continue;
829            }
830            Err(error) => {
831                out.push(note(error.to_string()));
832                continue;
833            }
834        };
835        match verify(&raw, event, &conn.vault_id, keys) {
836            Ok(doc) if older => {
837                let request = refusal_request(
838                    &record.vault_id,
839                    &event.plan_id,
840                    event.version,
841                    &doc.content_sha256,
842                    PlanRefusal::OlderThanApplied,
843                    applied_version,
844                );
845                let sent = post_ack(root, &request).err().map(|e| format!("; {e}"));
846                out.push(note(format!(
847                    "refused ({}){}",
848                    PlanRefusal::OlderThanApplied.code(),
849                    sent.unwrap_or_default()
850                )));
851            }
852            Ok(doc) => {
853                let dir = data_dir.join("plans");
854                let saved = std::fs::create_dir_all(&dir)
855                    .map_err(|e| e.to_string())
856                    .and_then(|()| {
857                        lean_ctx::config_io::write_atomic(
858                            &dir.join(format!("{}.json", doc.plan_id)),
859                            &raw.to_string(),
860                        )
861                    });
862                if let Err(error) = saved {
863                    out.push(note(format!("keep: {error}")));
864                }
865                out.push(PlanOutcome::Verified {
866                    vault: event.vault.clone(),
867                    vault_id: record.vault_id.clone(),
868                    root: root.to_string(),
869                    doc: Box::new(doc),
870                });
871            }
872            Err(Rejected::Refuse {
873                refusal,
874                content_sha256,
875            }) => {
876                let request = refusal_request(
877                    &record.vault_id,
878                    &event.plan_id,
879                    event.version,
880                    &content_sha256,
881                    refusal,
882                    applied_version,
883                );
884                let sent = post_ack(root, &request).err().map(|e| format!("; {e}"));
885                out.push(note(format!(
886                    "refused ({}){}",
887                    refusal.code(),
888                    sent.unwrap_or_default()
889                )));
890            }
891            Err(Rejected::Invalid(why)) => out.push(note(why)),
892        }
893    }
894    out
895}
896
897/// The active plans of the `subscribed` vaults newer than applied, for
898/// [`fetch`], and what could not be read. Blocking (HTTP).
899#[cfg(feature = "http-server")]
900pub(crate) fn catch_up(
901    map: &VaultMap,
902    subscribed: &[String],
903    seen: &PlansSeen,
904) -> (Vec<PlanAdvanced>, Vec<String>) {
905    let (mut events, mut errors) = (Vec::new(), Vec::new());
906    for record in map.vaults.values() {
907        let vault = super::relay_v2::address_of(record);
908        if !subscribed.contains(&vault) {
909            continue;
910        }
911        let Some(root) = record.roots.iter().find(|root| Path::new(root).is_dir()) else {
912            continue;
913        };
914        let listed = super::leases::connected(Path::new(root)).and_then(|conn| {
915            let path = format!("/vaults/{}/plans?state=active", conn.vault_id);
916            conn.session.with_client(|c| c.get(&path)).map_err(|e| {
917                if plans_not_ready(&e) {
918                    PLANS_NOT_READY.to_string()
919                } else {
920                    e.to_string()
921                }
922            })
923        });
924        let listed = match listed {
925            Ok(listed) => listed,
926            Err(error) => {
927                errors.push(format!("{vault}: {error}"));
928                continue;
929            }
930        };
931        events.extend(active_newer(&listed, &vault, seen));
932    }
933    (events, errors)
934}
935
936/// The plans of a `GET …/plans?state=active` answer newer than applied, by
937/// plan id.
938pub fn active_newer(listed: &Value, vault: &str, seen: &PlansSeen) -> Vec<PlanAdvanced> {
939    // Cloud answers `items`; `plans` is the earlier contract name.
940    let mut events: Vec<PlanAdvanced> = listed["items"]
941        .as_array()
942        .or_else(|| listed["plans"].as_array())
943        .into_iter()
944        .flatten()
945        .filter_map(|plan| {
946            let plan_id = plan["plan_id"].as_str()?;
947            let version = plan["version"].as_u64()?;
948            (plan_id_ok(plan_id)
949                && version >= 1
950                && applied(seen, vault, plan_id).is_none_or(|v| v < version))
951            .then(|| PlanAdvanced::new(vault, plan_id, version))
952        })
953        .collect();
954    events.sort_by(|a, b| a.plan_id.cmp(&b.plan_id));
955    events
956}
957
958/// Apply one verified version: record it and offer its directives (no bus
959/// entry; the person releases them from Code). False when it or a newer one
960/// already was.
961/// `worker_of` names a local agent's Cloud worker id.
962#[cfg(feature = "http-server")]
963pub(crate) fn apply(
964    registry: &AgentRegistry,
965    store: &mut DirectiveStore,
966    seen: &mut PlansSeen,
967    outcome: (&str, &str, &str, &PlanDoc),
968    worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
969) -> Result<bool, String> {
970    let (vault, vault_id, root, doc) = outcome;
971    if !admit(seen, vault, &doc.plan_id, doc.version) {
972        return Ok(false);
973    }
974    let local: Vec<(String, Option<String>)> = registry
975        .list_active(Some(root))
976        .into_iter()
977        .map(|agent| (agent.agent_id.clone(), worker_of(agent)))
978        .collect();
979    for (agent, issue) in plan_directives(doc, vault_id, &local) {
980        store.issue(root, &agent, &issue)?;
981    }
982    Ok(true)
983}
984
985/// Send the agents' answers Cloud has not recorded yet and note what it
986/// recorded. Blocking (HTTP). Returns the errors; an unsent state stays
987/// due for the next pass.
988#[cfg(feature = "http-server")]
989pub(crate) fn report(map: &VaultMap, data_dir: &Path) -> Vec<String> {
990    let store = DirectiveStore::load();
991    let due = store.unreported_plans();
992    if due.is_empty() {
993        return Vec::new();
994    }
995    let Some(key) = crate::receipts::ReceiptKey::load_or_create(data_dir) else {
996        return vec!["plan ack: no local HMAC key".to_string()];
997    };
998    let registry = AgentRegistry::load_or_create();
999    let agent_ref =
1000        |agent: &str| format!("ag-{}", &key.mac_hex("leanctx.plan-ack.agent", agent)[..32]);
1001    let agent_type_of = |agent: &str| {
1002        registry
1003            .agents
1004            .iter()
1005            .find(|a| a.agent_id == agent)
1006            .map_or("other", |a| agent_type(&a.agent_type))
1007    };
1008    let mut errors = Vec::new();
1009    let mut done = Vec::new();
1010    for request in ack_requests(&due, &agent_ref, &agent_type_of) {
1011        let Some(root) = map
1012            .vaults
1013            .values()
1014            .find(|r| r.vault_id == request.vault_id)
1015            .and_then(|r| r.roots.iter().find(|root| Path::new(root).is_dir()))
1016        else {
1017            continue;
1018        };
1019        match post_ack(root, &request) {
1020            Ok(()) => done.extend(request.covers),
1021            Err(error) => errors.push(error),
1022        }
1023    }
1024    if !done.is_empty()
1025        && let Err(error) = DirectiveStore::mutate(|_, store| {
1026            store.mark_reported(&done);
1027            Ok(())
1028        })
1029    {
1030        errors.push(format!("plan ack record: {error}"));
1031    }
1032    errors
1033}
1034
1035#[cfg(test)]
1036#[path = "plan_events_tests.rs"]
1037mod tests;