Skip to main content

lean_ctx_cloud/bus/
plan_body.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The plan body `leanctx.plan-body/v1` (contract §37.3) and its publish
3//! (`lean-ctx cloud plan publish`, §37.10).
4//!
5//! Cloud keeps a plan's body encrypted at rest and serves it as plain text
6//! (`body`, standard base64 with padding) next to its signed digest. An
7//! engine opens the body only after the digest and the signature checked
8//! out ([`super::plan_events::verify`]); the goal and the briefs an agent
9//! reads come from that verified body alone, the document's `sessions`
10//! only route.
11//!
12//! Publishing is LeanCTX Code's: the engine serializes the body in
13//! schema order, computes its digest and each session's `brief_sha256`, and
14//! posts it over the vault's connection. Cloud assigns the version. No
15//! plan text is written to argv, a log or a local file on the way.
16
17use std::collections::BTreeSet;
18use std::path::Path;
19
20use base64::Engine as _;
21use base64::engine::general_purpose::STANDARD;
22use serde::{Deserialize, Serialize};
23use serde_json::{Map, Value, json};
24use sha2::{Digest as _, Sha256};
25
26use super::plan_events::{ALL_SLOT, plan_id_ok, slot_ok, task_id_ok};
27
28/// `$id` of the body schema.
29pub const PLAN_BODY_SCHEMA: &str = "leanctx.plan-body/v1";
30/// Schema of the publish request (Cloud route `POST …/plans`).
31pub const PLAN_PUBLISH_SCHEMA: &str = "leanctx.cloud.plan-publish/v1";
32/// Schema of Cloud's `201` answer to a publish.
33pub const PLAN_PUBLISHED_SCHEMA: &str = "leanctx.cloud.plan-published/v1";
34/// Decoded body bytes of a plan document (1 B–256 KiB).
35pub const MAX_BODY_BYTES: usize = 256 * 1024;
36/// Bytes of a publish request.
37const MAX_REQUEST_BYTES: usize = 400 * 1024;
38/// Bytes of Cloud's answer to a publish.
39const MAX_ANSWER_BYTES: usize = 64 * 1024;
40const MAX_TITLE_CHARS: usize = 200;
41const MAX_GOAL_CHARS: usize = 4_000;
42const MAX_ROLE_CHARS: usize = 64;
43const MAX_BRIEF_CHARS: usize = 8_000;
44const MAX_FOLDER_CHARS: usize = 512;
45const MAX_SESSIONS: usize = 32;
46
47/// One session of the body: the slot, the role and the brief an agent of
48/// that slot reads, and an optional folder.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct BodySession {
52    pub slot: String,
53    pub role: String,
54    pub brief: String,
55    #[serde(default)]
56    pub folder: Option<String>,
57}
58
59/// A plan body `leanctx.plan-body/v1`, checked ([`PlanBody::parse`]).
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(deny_unknown_fields)]
62pub struct PlanBody {
63    /// `leanctx.plan-body/v1`; a body without it is read as v1, a publish
64    /// always writes it.
65    #[serde(default = "plan_body_schema")]
66    pub schema: String,
67    pub title: String,
68    pub goal: String,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub decisions: Option<Vec<String>>,
71    pub sessions: Vec<BodySession>,
72}
73
74fn plan_body_schema() -> String {
75    PLAN_BODY_SCHEMA.to_owned()
76}
77
78/// `sha256:<64 hex>` of `bytes`.
79pub fn sha256_of(bytes: &[u8]) -> String {
80    format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
81}
82
83/// Text an agent reads: within `max` characters, no control character but
84/// newline and tab, no invisible or bidi character; `required` text is not
85/// blank. The same rules as a release (`DirectiveStore::release_text`).
86fn text_ok(field: &str, text: &str, max: usize, required: bool) -> Result<(), String> {
87    if required && text.trim().is_empty() {
88        return Err(format!("{field} is empty"));
89    }
90    if text.chars().count() > max {
91        return Err(format!("{field} is longer than {max} characters"));
92    }
93    if text
94        .chars()
95        .any(|c| c.is_control() && c != '\n' && c != '\t')
96    {
97        return Err(format!("{field} carries a control character"));
98    }
99    if text.chars().any(lean_ctx_protocol::cloud::invisible) {
100        return Err(format!("{field} carries an invisible or bidi character"));
101    }
102    Ok(())
103}
104
105/// `^dec-[A-Za-z0-9-]{1,64}$`
106fn decision_ok(id: &str) -> bool {
107    id.strip_prefix("dec-").is_some_and(|rest| {
108        (1..=64).contains(&rest.len())
109            && rest.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
110    })
111}
112
113impl PlanBody {
114    /// The body of `bytes` (UTF-8 JSON), checked against the schema: no
115    /// unknown field, the length limits, unique slots (lowercase,
116    /// `[a-z0-9-]`, never `all`), decision ids, readable text.
117    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
118        let body: Self = serde_json::from_slice(bytes).map_err(|e| format!("plan body: {e}"))?;
119        body.check()?;
120        Ok(body)
121    }
122
123    fn check(&self) -> Result<(), String> {
124        if self.schema != PLAN_BODY_SCHEMA {
125            return Err(format!("schema is not {PLAN_BODY_SCHEMA}"));
126        }
127        text_ok("title", &self.title, MAX_TITLE_CHARS, true)?;
128        text_ok("goal", &self.goal, MAX_GOAL_CHARS, true)?;
129        if let Some(decisions) = &self.decisions
130            && let Some(bad) = decisions.iter().find(|d| !decision_ok(d))
131        {
132            return Err(format!("decisions: {bad:?} is not a decision id"));
133        }
134        if self.sessions.len() > MAX_SESSIONS {
135            return Err(format!("more than {MAX_SESSIONS} sessions"));
136        }
137        let mut slots = BTreeSet::new();
138        for session in &self.sessions {
139            if !slot_ok(&session.slot) {
140                return Err(format!(
141                    "slot {:?}: 1–32 of [a-z0-9-], and not {ALL_SLOT:?}",
142                    session.slot
143                ));
144            }
145            if !slots.insert(session.slot.as_str()) {
146                return Err(format!("slot {:?} is used twice", session.slot));
147            }
148            let at = |field: &str| format!("sessions[{}].{field}", session.slot);
149            text_ok(&at("role"), &session.role, MAX_ROLE_CHARS, true)?;
150            text_ok(&at("brief"), &session.brief, MAX_BRIEF_CHARS, true)?;
151            if let Some(folder) = &session.folder {
152                text_ok(&at("folder"), folder, MAX_FOLDER_CHARS, false)?;
153            }
154        }
155        Ok(())
156    }
157
158    /// The session of `slot`.
159    pub fn session(&self, slot: &str) -> Option<&BodySession> {
160        self.sessions.iter().find(|s| s.slot == slot)
161    }
162
163    /// The bytes that are encoded, digested and published: compact JSON
164    /// in schema order (`schema`, `title`, `goal`, `decisions` when given,
165    /// `sessions` with `slot`, `role`, `brief`, `folder`), the same for any
166    /// key order of the input (contract §37.10).
167    pub fn wire_bytes(&self) -> Result<Vec<u8>, String> {
168        serde_json::to_vec(self).map_err(|e| format!("plan body: {e}"))
169    }
170}
171
172/// The body of a document's `body` (standard base64 with padding): its
173/// decoded bytes, 1 B–256 KiB.
174pub fn decode_body(encoded: &str) -> Result<Vec<u8>, String> {
175    if encoded.len() > MAX_BODY_BYTES.div_ceil(3) * 4 {
176        return Err("body is larger than 256 KiB".to_owned());
177    }
178    let bytes = STANDARD
179        .decode(encoded.as_bytes())
180        .map_err(|_| "body is not base64".to_owned())?;
181    if bytes.is_empty() || bytes.len() > MAX_BODY_BYTES {
182        return Err("body is not 1 B to 256 KiB".to_owned());
183    }
184    Ok(bytes)
185}
186
187/// The routing of one session in a publish: never text, only the slot,
188/// optional task and worker ids and the brief's digest.
189#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
190#[serde(deny_unknown_fields)]
191struct Routing {
192    #[serde(default)]
193    task_id: Option<String>,
194    #[serde(default)]
195    worker_id: Option<String>,
196}
197
198/// `lean-ctx cloud plan publish` stdin:
199/// `{"idempotency_key", "plan_id"?, "supersedes_version"?, "body"}`.
200#[derive(Debug, Deserialize)]
201#[serde(deny_unknown_fields)]
202struct PublishInput {
203    idempotency_key: String,
204    #[serde(default)]
205    plan_id: Option<String>,
206    #[serde(default)]
207    supersedes_version: Option<u64>,
208    body: Value,
209}
210
211/// A checked publish, ready to post.
212#[derive(Debug, Clone, PartialEq)]
213pub struct Publish {
214    /// The `Idempotency-Key` header (a UUID).
215    pub idempotency_key: String,
216    pub content_sha256: String,
217    /// The `leanctx.cloud.plan-publish/v1` request.
218    pub request: Value,
219}
220
221/// The publish of stdin `text`. A body session may carry its routing
222/// (`task_id`, `worker_id`); it is taken out of the body before the body
223/// is serialized, so the published text holds none of it.
224pub fn publish_request(text: &str) -> Result<Publish, String> {
225    let input: PublishInput = serde_json::from_str(text).map_err(|e| format!("publish: {e}"))?;
226    let key = uuid::Uuid::parse_str(&input.idempotency_key)
227        .map_err(|_| "idempotency_key is not a UUID".to_owned())?
228        .hyphenated()
229        .to_string();
230    if let Some(plan_id) = &input.plan_id
231        && !plan_id_ok(plan_id)
232    {
233        return Err("plan_id is not a plan id (plan_ and 8–40 letters or digits)".to_owned());
234    }
235    if input.supersedes_version == Some(0) {
236        return Err("supersedes_version starts at 1".to_owned());
237    }
238    if input.supersedes_version.is_some() && input.plan_id.is_none() {
239        return Err("supersedes_version needs plan_id".to_owned());
240    }
241    let Value::Object(mut body) = input.body else {
242        return Err("body is not a JSON object".to_owned());
243    };
244    let mut routing = Vec::new();
245    if let Some(Value::Array(sessions)) = body.get_mut("sessions") {
246        for session in sessions.iter_mut() {
247            let Value::Object(fields) = session else {
248                return Err("a body session is not a JSON object".to_owned());
249            };
250            let mut route = Map::new();
251            for name in ["task_id", "worker_id"] {
252                if let Some(value) = fields.remove(name) {
253                    route.insert(name.to_owned(), value);
254                }
255            }
256            let route: Routing = serde_json::from_value(Value::Object(route))
257                .map_err(|e| format!("session routing: {e}"))?;
258            for id in [&route.task_id, &route.worker_id].into_iter().flatten() {
259                if !task_id_ok(id) {
260                    return Err(format!(
261                        "{id:?} is not a task or worker id (1–128 of [A-Za-z0-9._:-])"
262                    ));
263                }
264            }
265            routing.push(route);
266        }
267    }
268    let body: PlanBody =
269        serde_json::from_value(Value::Object(body)).map_err(|e| format!("plan body: {e}"))?;
270    body.check()?;
271    let bytes = body.wire_bytes()?;
272    if bytes.len() > MAX_BODY_BYTES {
273        return Err("the body is larger than 256 KiB".to_owned());
274    }
275    let content_sha256 = sha256_of(&bytes);
276    let sessions: Vec<Value> = body
277        .sessions
278        .iter()
279        .zip(routing.iter().chain(std::iter::repeat(&Routing::default())))
280        .map(|(session, route)| {
281            json!({
282                "slot": session.slot,
283                "task_id": route.task_id,
284                "worker_id": route.worker_id,
285                "brief_sha256": sha256_of(session.brief.as_bytes()),
286            })
287        })
288        .collect();
289    let request = json!({
290        "schema": PLAN_PUBLISH_SCHEMA,
291        "plan_id": input.plan_id,
292        "supersedes_version": input.supersedes_version,
293        "content_sha256": content_sha256,
294        "body": STANDARD.encode(&bytes),
295        "sessions": sessions,
296    });
297    let size = serde_json::to_vec(&request).map_or(usize::MAX, |b| b.len());
298    if size > MAX_REQUEST_BYTES {
299        return Err("the publish request is larger than 400 KiB".to_owned());
300    }
301    Ok(Publish {
302        idempotency_key: key,
303        content_sha256,
304        request,
305    })
306}
307
308/// A version Cloud took.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct Published {
311    pub plan_id: String,
312    pub version: u64,
313    pub content_sha256: String,
314}
315
316/// A publish Cloud or the engine refused: a `[a-z_]` code, a message
317/// without plan text, and the current version of a `stale_version`.
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct PublishRefused {
320    pub code: String,
321    pub message: String,
322    pub current_version: Option<u64>,
323}
324
325impl PublishRefused {
326    fn new(code: &str, message: impl Into<String>) -> Self {
327        Self {
328            code: code.to_owned(),
329            message: message.into(),
330            current_version: None,
331        }
332    }
333}
334
335/// Cloud's answer `(status, body)` to `publish`.
336pub fn publish_answer(
337    publish: &Publish,
338    status: u16,
339    answer: &Value,
340) -> Result<Published, PublishRefused> {
341    if (200..300).contains(&status) {
342        let plan_id = answer["plan_id"].as_str().filter(|id| plan_id_ok(id));
343        let version = answer["version"].as_u64().filter(|v| *v >= 1);
344        let (Some(plan_id), Some(version)) = (plan_id, version) else {
345            return Err(PublishRefused::new(
346                "protocol",
347                "The Cloud answered the publish without a plan id and version",
348            ));
349        };
350        if answer["schema"].as_str() != Some(PLAN_PUBLISHED_SCHEMA)
351            || answer["content_sha256"].as_str() != Some(publish.content_sha256.as_str())
352        {
353            return Err(PublishRefused::new(
354                "protocol",
355                "The Cloud answered the publish with another body digest",
356            ));
357        }
358        return Ok(Published {
359            plan_id: plan_id.to_owned(),
360            version,
361            content_sha256: publish.content_sha256.clone(),
362        });
363    }
364    let code = answer["error"]["code"]
365        .as_str()
366        .filter(|c| {
367            (1..=64).contains(&c.len()) && c.chars().all(|c| c.is_ascii_lowercase() || c == '_')
368        })
369        .map_or_else(
370            || match status {
371                401 => "unauthorized".to_owned(),
372                403 => "forbidden".to_owned(),
373                404 => "not_found".to_owned(),
374                413 => "payload_too_large".to_owned(),
375                429 => "rate_limited".to_owned(),
376                _ => format!("http_{status}"),
377            },
378            str::to_owned,
379        );
380    let message = match code.as_str() {
381        "stale_version" => {
382            "a newer version of this plan was published; publish on top of current_version"
383        }
384        "plan_exists" => {
385            "a plan with this id exists; pass supersedes_version to publish a new version"
386        }
387        "not_found" => "The Cloud does not know this plan or vault",
388        "not_ready" => "The Cloud does not take plans for this vault yet",
389        "idempotency_key_reused" => "this idempotency_key was used for another publish",
390        "invalid" | "invalid_request" => "The Cloud refused the publish as invalid",
391        "forbidden" | "not_permitted" | "unauthorized" => {
392            "this account may not publish plans to this vault"
393        }
394        "rate_limited" => "too many publishes; try again later",
395        _ => "The Cloud refused the publish",
396    };
397    let mut refused = PublishRefused::new(&code, format!("{message} ({status})"));
398    if code == "stale_version" {
399        refused.current_version = answer["error"]["current_version"]
400            .as_u64()
401            .or_else(|| answer["current_version"].as_u64());
402    }
403    Err(refused)
404}
405
406/// The refusal code when the project root is bound to no vault.
407pub const NOT_BOUND: &str = "not_bound";
408
409/// Post `publish` for the vault `project_root` is bound to (as every
410/// `cloud` command resolves it). Blocking (HTTP).
411pub fn publish(project_root: &Path, publish: &Publish) -> Result<Published, PublishRefused> {
412    let bound = crate::state::CloudStore::open()
413        .ok()
414        .and_then(|store| {
415            crate::resolution::vault_for_root(&store, project_root)
416                .ok()
417                .flatten()
418        })
419        .is_some();
420    if !bound {
421        return Err(PublishRefused::new(
422            NOT_BOUND,
423            "this repository is not bound to a Cloud vault",
424        ));
425    }
426    let conn = super::leases::connected(project_root).map_err(|_| {
427        PublishRefused::new(
428            "not_connected",
429            "this machine is not connected to the Cloud (see `lean-ctx cloud status`)",
430        )
431    })?;
432    let path = format!("/vaults/{}/plans", conn.vault_id);
433    let (status, answer) = conn
434        .session
435        .with_client(|c| {
436            c.send_answer_with(
437                "POST",
438                &path,
439                Some(&publish.request),
440                &[("Idempotency-Key", publish.idempotency_key.as_str())],
441                MAX_ANSWER_BYTES,
442            )
443        })
444        .map_err(|e| PublishRefused::new("offline", e.to_string()))?;
445    publish_answer(publish, status, &answer)
446}
447
448#[cfg(test)]
449#[path = "plan_body_tests.rs"]
450mod tests;