Skip to main content

lean_ctx_cloud/events/
build.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Building signed C0 2.0 events from what the capture gate let through
3//! (SPEC-ENGINE §3.1.2 step 6, §3.3.1).
4//!
5//! A claim becomes one `node.add` whose target is its keyed node id. Its
6//! valid references go into `applies_to` (contract form, at most 5 × 120
7//! characters); every `file:`/`sym:` entry gets a code anchor with the
8//! sha256 of the anchored bytes at `HEAD` and that commit, as the contract
9//! requires for facts.
10
11use ed25519_dalek::SigningKey;
12use serde_json::{Map, Value, json};
13use sha2::{Digest as _, Sha256};
14
15use super::{hlc::Stamp, ids, sign};
16use crate::CloudError;
17use crate::capture::refs::{Checkout, Reference};
18use crate::capture::{CaptureCandidate, GATE_VERSION, dedupe};
19use lean_ctx::core::knowledge::NodeType;
20
21pub const EVENT_SCHEMA: &str = "leanctx.cloud.event/v2";
22/// `applies_to` limits of a v4 claim body.
23pub const MAX_APPLIES_TO: usize = 5;
24const MAX_APPLIES_TO_CHARS: usize = 120;
25/// Anchors per node.
26const MAX_ANCHORS: usize = 16;
27
28/// The place an event is written to.
29#[derive(Debug, Clone)]
30pub struct Place {
31    /// `vault`, the only place kind.
32    pub kind: String,
33    pub id: String,
34    /// The place id key (`id_salt`): node ids and body commitments.
35    pub pk_id: [u8; 32],
36    /// Last server `seq` folded here.
37    pub causal_base: u64,
38}
39
40/// Who signs: the instance key (workspace places) or an alias key, with the
41/// matching HLC node and worker id. Production paths build it with
42/// [`Signer::workspace`] or [`Signer::alias`], never field by field: the
43/// maintain CLI once set `hlc.node` to the raw `inst_<hex>` id and Cloud
44/// refused every event (`invalid_event shape /hlc/node`, dogfood 25.10.).
45pub struct Signer<'a> {
46    pub key: &'a SigningKey,
47    pub hlc_node: String,
48    pub worker_id: String,
49}
50
51impl<'a> Signer<'a> {
52    /// A workspace place's signer: the instance key, and as `hlc.node` the
53    /// instance id as C0 2.0 names it (the hyphenated UUID; a 1.x enrolment
54    /// stores `inst_<32 hex>`, which the event schema refuses).
55    pub fn workspace(key: &'a SigningKey, instance_id: &str, worker_id: &str) -> Self {
56        Self {
57            key,
58            hlc_node: crate::workers::canonical_instance_id(instance_id),
59            worker_id: worker_id.to_string(),
60        }
61    }
62
63    /// An alias signer (alias places, R38): the alias key of
64    /// `place_ref` and its keyed 16-hex `hlc.node`.
65    pub fn alias(
66        alias_key: &'a SigningKey,
67        keys: &crate::instance_key::InstanceKeys,
68        place_ref: &str,
69        worker_id: &str,
70    ) -> Self {
71        Self {
72            key: alias_key,
73            hlc_node: crate::workers::alias_hlc_node(keys, place_ref),
74            worker_id: worker_id.to_string(),
75        }
76    }
77}
78
79fn local(e: impl std::fmt::Display) -> CloudError {
80    CloudError::Local(e.to_string())
81}
82
83/// `reasons_passed_hash`: which gate version and rules a node passed.
84pub fn reasons_passed_hash(node_type: NodeType) -> String {
85    let rules = if node_type == NodeType::Procedure {
86        "G1,G10,G11,G12,procedure"
87    } else {
88        "G1,G2,G3,G4,G5,G6,G7,G8,G9,G10,G11,G12"
89    };
90    blake3::hash(format!("leanctx.cloud.capture.v{GATE_VERSION}:{rules}").as_bytes())
91        .to_hex()
92        .to_string()
93}
94
95/// `applies_to` and the code anchors for a candidate's valid references.
96pub fn applies_and_anchors(refs: &[String], checkout: &mut Checkout) -> (Vec<String>, Vec<Value>) {
97    applies_and_anchors_within(refs, checkout, MAX_APPLIES_TO)
98}
99
100/// [`applies_and_anchors`] with at most `max` `applies_to` entries: a fact
101/// keeps one slot for its subject reference ([`crate::capture::conflicts`]).
102pub fn applies_and_anchors_within(
103    refs: &[String],
104    checkout: &mut Checkout,
105    max: usize,
106) -> (Vec<String>, Vec<Value>) {
107    let head = checkout.head();
108    let mut applies = Vec::new();
109    let mut anchors = Vec::new();
110    for raw in refs {
111        if applies.len() >= max {
112            break;
113        }
114        let Some(r) = crate::capture::refs::parse(raw) else {
115            continue;
116        };
117        let text = r.to_contract();
118        if text.chars().count() > MAX_APPLIES_TO_CHARS {
119            continue;
120        }
121        let (anchor_ref, bytes) = match &r {
122            Reference::File { path, .. } => (
123                format!("file:{path}"),
124                checkout.blob_bytes(path).map(<[u8]>::to_vec),
125            ),
126            Reference::Symbol { path, symbol } => {
127                (text.clone(), checkout.symbol_span(path, symbol))
128            }
129            _ => {
130                applies.push(text);
131                continue;
132            }
133        };
134        // A code entry without an anchor would break the contract rule
135        // (anchors required for file:/sym: entries); such an entry is left
136        // out rather than shared unanchored.
137        let (Some(bytes), Some(commit)) = (bytes, head.clone()) else {
138            continue;
139        };
140        let applies_text = if matches!(r, Reference::File { .. }) {
141            anchor_ref.clone()
142        } else {
143            text
144        };
145        if !applies.contains(&applies_text) {
146            applies.push(applies_text);
147        }
148        if anchors.len() < MAX_ANCHORS
149            && !anchors
150                .iter()
151                .any(|a: &Value| a["ref"] == anchor_ref.as_str())
152        {
153            anchors.push(json!({
154                "ref": anchor_ref,
155                "digest": hex::encode(Sha256::digest(&bytes)),
156                "commit": commit,
157            }));
158        }
159    }
160    (applies, anchors)
161}
162
163/// The body of a claim node (`fact`, `decision`, `gotcha`, `finding`) or a
164/// procedure. A decision carries its anchors only on a C0 2.2 Cloud
165/// (`decision_anchors`, §4.1); before that `decision_body` has none.
166pub fn claim_body(
167    c: &CaptureCandidate,
168    applies_to: &[String],
169    anchors: Vec<Value>,
170    decision_anchors: bool,
171) -> Result<Value, CloudError> {
172    let mut body = Map::new();
173    body.insert("body_nonce".into(), Value::String(sign::new_body_nonce()?));
174    body.insert("evidence".into(), Value::from(c.evidence.as_str()));
175    match c.node_type {
176        NodeType::Procedure => {
177            body.insert("title".into(), Value::from(c.statement.clone()));
178            body.insert("steps".into(), json!(c.steps));
179            if !c.commands.is_empty() {
180                body.insert(
181                    "commands".into(),
182                    serde_json::to_value(&c.commands).map_err(local)?,
183                );
184            }
185        }
186        _ => {
187            body.insert("statement".into(), Value::from(c.statement.clone()));
188        }
189    }
190    // C0 `decision_body` requires `status`; a captured decision is in force
191    // (`superseded`/`reverted` come later as their own events). Without it
192    // Cloud refused every captured decision (`invalid_event shape
193    // /body/status`), so a vault never received one.
194    if c.node_type == NodeType::Decision {
195        body.insert("status".into(), Value::from("active"));
196    }
197    if c.node_type == NodeType::Fact {
198        if !applies_to.is_empty() {
199            body.insert("applies_to".into(), json!(applies_to));
200        }
201        body.insert("sensitivity".into(), Value::from("public"));
202    }
203    let anchored = match c.node_type {
204        NodeType::Fact | NodeType::Gotcha | NodeType::Procedure => true,
205        NodeType::Decision => decision_anchors,
206        NodeType::Finding => false,
207    };
208    if anchored && !anchors.is_empty() {
209        body.insert("anchors".into(), Value::Array(anchors));
210    }
211    Ok(Value::Object(body))
212}
213
214/// V9: the largest `session_ref` an event envelope carries.
215pub const MAX_SESSION_REF: usize = 64;
216
217/// Whether `s` is a valid envelope `session_ref` (V9, `event.schema.json`):
218/// 1-64 characters of `[A-Za-z0-9._:-]`.
219pub fn valid_session_ref(s: &str) -> bool {
220    !s.is_empty()
221        && s.len() <= MAX_SESSION_REF
222        && s.bytes()
223            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'))
224}
225
226/// Put the opaque session (V9) into an unsigned envelope, so the signature
227/// covers it; a missing or invalid value leaves the envelope as it was.
228pub(crate) fn set_session(event: &mut Value, session: Option<&str>) {
229    if let Some(s) = session.filter(|s| valid_session_ref(s)) {
230        event["session_ref"] = Value::from(s);
231    }
232}
233
234/// A signed `node.add` for a gated candidate. Returns the event and its
235/// target node id.
236pub fn node_add(
237    c: &CaptureCandidate,
238    body: &Value,
239    place: &Place,
240    stamp: Stamp,
241    signer: &Signer<'_>,
242) -> Result<(Value, String), CloudError> {
243    node_add_in(c, body, place, stamp, signer, None)
244}
245
246/// [`node_add`] written inside the session `session` (V9 `session_ref`,
247/// signed with the envelope; `None` outside a session).
248pub fn node_add_in(
249    c: &CaptureCandidate,
250    body: &Value,
251    place: &Place,
252    stamp: Stamp,
253    signer: &Signer<'_>,
254    session: Option<&str>,
255) -> Result<(Value, String), CloudError> {
256    let target = if c.node_type == NodeType::Procedure {
257        ids::new_random_id("n")?
258    } else {
259        ids::claim_node_id(&dedupe::exact_key(&place.pk_id, c.node_type, &c.statement))
260    };
261    let body_commit = sign::body_commit(&place.pk_id, body).map_err(local)?;
262    let mut event = json!({
263        "schema": EVENT_SCHEMA,
264        "event_id": ids::new_event_id(stamp.wall_ms)?,
265        "place": {"kind": place.kind, "id": place.id},
266        "op": "node.add",
267        "target": target,
268        "node_type": c.node_type.as_str(),
269        "body": body,
270        "body_commit": body_commit,
271        "hlc": {"wall_ms": stamp.wall_ms, "counter": stamp.counter, "node": signer.hlc_node},
272        "causal_base": place.causal_base,
273        "actor": {"kind": "worker"},
274        "worker_id": signer.worker_id,
275        "provenance_claim": "own",
276        "capture": {
277            "gate_version": GATE_VERSION,
278            "evidence": c.evidence.as_str(),
279            "reasons_passed_hash": reasons_passed_hash(c.node_type),
280        },
281        "screening": {
282            "counts": {"forbidden": 0, "local_path": 0, "pii": 0, "redaction": 0, "secret": 0},
283            "scanner_version": crate::knowledge::screening::SCANNER_VERSION,
284        },
285    });
286    if c.node_type == NodeType::Procedure {
287        event["flags"] = json!({"commands": !c.commands.is_empty()});
288    }
289    set_session(&mut event, session);
290    sign::sign(&mut event, signer.key).map_err(local)?;
291    Ok((event, target))
292}
293
294/// A signed `edge.add` `from` a claim this engine captured `to` a node it
295/// builds on (v5 2.2.2, [`crate::capture::derived`]): written
296/// like the claim itself (provenance `own`, the claim's evidence).
297pub fn edge_add(
298    kind: &str,
299    from: &str,
300    to: &str,
301    evidence: &str,
302    place: &Place,
303    stamp: Stamp,
304    signer: &Signer<'_>,
305) -> Result<Value, CloudError> {
306    edge_add_in(kind, from, to, evidence, place, stamp, signer, None)
307}
308
309/// [`edge_add`] written inside the session `session` (V9, as
310/// [`node_add_in`]).
311#[allow(clippy::too_many_arguments)]
312pub fn edge_add_in(
313    kind: &str,
314    from: &str,
315    to: &str,
316    evidence: &str,
317    place: &Place,
318    stamp: Stamp,
319    signer: &Signer<'_>,
320    session: Option<&str>,
321) -> Result<Value, CloudError> {
322    let edge_id = ids::new_random_id("e")?;
323    edge_add_at_in(
324        &edge_id, kind, from, to, evidence, place, stamp, signer, session,
325    )
326}
327
328/// [`edge_add`] with the edge id `edge_id` (the sync's conflict detection
329/// names its `supersedes` edges deterministically, [`crate::capture::conflicts`]).
330#[allow(clippy::too_many_arguments)]
331pub fn edge_add_at(
332    edge_id: &str,
333    kind: &str,
334    from: &str,
335    to: &str,
336    evidence: &str,
337    place: &Place,
338    stamp: Stamp,
339    signer: &Signer<'_>,
340) -> Result<Value, CloudError> {
341    edge_add_at_in(
342        edge_id, kind, from, to, evidence, place, stamp, signer, None,
343    )
344}
345
346#[allow(clippy::too_many_arguments)]
347fn edge_add_at_in(
348    edge_id: &str,
349    kind: &str,
350    from: &str,
351    to: &str,
352    evidence: &str,
353    place: &Place,
354    stamp: Stamp,
355    signer: &Signer<'_>,
356    session: Option<&str>,
357) -> Result<Value, CloudError> {
358    let body = json!({
359        "body_nonce": sign::new_body_nonce()?,
360        "from": from,
361        "kind": kind,
362        "to": to,
363    });
364    let body_commit = sign::body_commit(&place.pk_id, &body).map_err(local)?;
365    let mut event = json!({
366        "schema": EVENT_SCHEMA,
367        "event_id": ids::new_event_id(stamp.wall_ms)?,
368        "place": {"kind": place.kind, "id": place.id},
369        "op": "edge.add",
370        "target": edge_id,
371        "body": body,
372        "body_commit": body_commit,
373        "hlc": {"wall_ms": stamp.wall_ms, "counter": stamp.counter, "node": signer.hlc_node},
374        "causal_base": place.causal_base,
375        "actor": {"kind": "worker"},
376        "worker_id": signer.worker_id,
377        "provenance_claim": "own",
378        "capture": {
379            "gate_version": GATE_VERSION,
380            "evidence": evidence,
381            "reasons_passed_hash": blake3::hash(
382                format!("leanctx.cloud.capture.v{GATE_VERSION}:edge:{kind}").as_bytes()
383            )
384            .to_hex()
385            .to_string(),
386        },
387        "screening": {
388            "counts": {"forbidden": 0, "local_path": 0, "pii": 0, "redaction": 0, "secret": 0},
389            "scanner_version": crate::knowledge::screening::SCANNER_VERSION,
390        },
391    });
392    set_session(&mut event, session);
393    sign::sign(&mut event, signer.key).map_err(local)?;
394    Ok(event)
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400    use lean_ctx::core::knowledge::EvidenceLevel;
401    use lean_ctx::core::sensitivity::SensitivityLevel;
402
403    #[test]
404    fn a_claim_becomes_a_signed_node_add_with_anchors() {
405        let dir = crate::capture::tests::repo();
406        let mut checkout = Checkout::new(dir.path());
407        let c = CaptureCandidate {
408            node_type: NodeType::Fact,
409            statement: "The relay drops frames when the link is slow.".into(),
410            steps: vec![],
411            commands: vec![],
412            refs: vec![],
413            evidence: EvidenceLevel::Observed,
414            sensitivity: SensitivityLevel::Public,
415        };
416        let refs = vec![
417            "file:src/lib.rs".to_string(),
418            "sym:src/lib.rs::relay".to_string(),
419            "https://docs.rs/blake3/".to_string(),
420        ];
421        let (applies, anchors) = applies_and_anchors(&refs, &mut checkout);
422        assert_eq!(applies, refs);
423        assert_eq!(anchors.len(), 2);
424        let content = std::fs::read(dir.path().join("src/lib.rs")).unwrap();
425        assert_eq!(anchors[0]["digest"], hex::encode(Sha256::digest(&content)));
426        assert_eq!(anchors[0]["commit"].as_str().unwrap().len(), 40);
427
428        let body = claim_body(&c, &applies, anchors, false).unwrap();
429        let key = SigningKey::from_bytes(&[0x49; 32]);
430        let place = Place {
431            kind: "vault".into(),
432            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
433            pk_id: [0; 32],
434            causal_base: 7,
435        };
436        let signer = Signer {
437            key: &key,
438            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
439            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
440        };
441        let (event, target) = node_add(
442            &c,
443            &body,
444            &place,
445            Stamp {
446                wall_ms: 1_792_800_001_000,
447                counter: 0,
448            },
449            &signer,
450        )
451        .unwrap();
452        assert_eq!(event["target"], target.as_str());
453        assert!(target.starts_with("n_") && target.len() == 28);
454        assert!(sign::verify(&event, key.verifying_key().as_bytes()));
455        assert_eq!(
456            event["body_commit"],
457            sign::body_commit(&place.pk_id, &event["body"]).unwrap()
458        );
459        assert_eq!(event["event_id"].as_str().unwrap().len(), 26);
460        // Same statement, same place key → same node on every engine.
461        assert_eq!(
462            target,
463            ids::claim_node_id(&dedupe::exact_key(
464                &[0; 32],
465                NodeType::Fact,
466                "the relay drops frames when the link is slow"
467            ))
468        );
469    }
470
471    /// Every claim body the engine builds has exactly the shape C0
472    /// `event.schema.json` names for its node type: each required member,
473    /// no member outside `properties`, enum members within their enum. A
474    /// captured decision without `status` was refused by Cloud
475    /// (`invalid_event shape /body/status`, live 26.10.).
476    #[test]
477    fn every_claim_body_has_its_c0_shape() {
478        let path = format!(
479            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/schemas/event.schema.json",
480            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
481        );
482        let schema: Value = serde_json::from_slice(&std::fs::read(&path).expect(&path)).unwrap();
483        for (node_type, def) in [
484            (NodeType::Fact, "fact_body"),
485            (NodeType::Decision, "decision_body"),
486            (NodeType::Gotcha, "gotcha_body"),
487            (NodeType::Finding, "finding_body"),
488            (NodeType::Procedure, "procedure_body"),
489        ] {
490            let c = CaptureCandidate {
491                node_type,
492                statement: "Releases are tagged from main after the smoke test passes.".into(),
493                steps: vec!["Run the smoke test against staging.".into()],
494                commands: vec![],
495                refs: vec![],
496                evidence: EvidenceLevel::Stated,
497                sensitivity: SensitivityLevel::Public,
498            };
499            let body = claim_body(&c, &["file:docs/deploy.md".into()], Vec::new(), false).unwrap();
500            let def = &schema["$defs"][def];
501            let props = def["properties"].as_object().unwrap();
502            for required in def["required"].as_array().unwrap() {
503                let name = required.as_str().unwrap();
504                assert!(body.get(name).is_some(), "{node_type:?}: {name} missing");
505            }
506            for (name, value) in body.as_object().unwrap() {
507                let prop = props
508                    .get(name)
509                    .unwrap_or_else(|| panic!("{node_type:?}: {name} not in C0"));
510                if let Some(allowed) = prop["enum"].as_array() {
511                    assert!(allowed.contains(value), "{node_type:?}: {name} = {value}");
512                }
513            }
514        }
515    }
516}