cbcl-parser 0.3.0

CBCL pure parser and pipeline
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
//! SPEC-019 R.7: the state-layer exports, as one implementation every
//! binding wraps (SPEC-010 REQ-002: a binding adds term translation and
//! crash containment, never semantics).
//!
//! Frames are S-expressions, like every other export; state, schema, and
//! rejections come back as canonical JSON (SPEC-019 R.3), a canonical act as
//! its wire text, and a self-address as `f1220<hex>`.
//!
//! ```text
//! (fold               <dialect> <thread> (acts (<signer> <message>) …))        → state JSON
//! (intend             <dialect> <thread> (acts …) <signer> <verb> (:k v …))    → canonical act
//! (verify-state-shape <dialect> <message>)                                     → "ok"
//! (state-schema       <dialect>)                                               → schema JSON
//! (may-send           <dialect> <thread> (acts …) <signer>)                    → JSON array of verbs
//! (frontier           <dialect> <thread> (acts …))                             → {"instance","frontier"}
//! (admit              <dialect> <thread> (acts …) (<signer> <message>))        → {"verdict":…}
//! (define …)                                                                   → f1220<hex>   (dialect_hash)
//! ```
//!
//! `<dialect>` is a `(define …)` or a `(dialects <ancestor>* <leaf>)` chain,
//! installed through the full R1–R7 pipeline by [`parse_and_install_dialect`];
//! the leaf is the dialect judged. Each act entry is the complete received
//! message with the signer the host authenticated; the cast is read from the
//! root among the acts and never supplied.

#![forbid(unsafe_code)]

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use cbcl_core::blame::ViolationError;
use cbcl_core::canonical::{dialect_hash, dialect_name};
use cbcl_core::dialect::{Dialect, DialectRegistry};
use cbcl_core::intend::{canonical_text, cast_of, intend, may_send, render_reject, Instance};
use cbcl_core::projection::verify_causal_for_role;
use cbcl_core::protocol::{verify_causal, VerificationResult};
use cbcl_core::role::{AgentKey, Endpoint};
use cbcl_core::serializer::serialize;
use cbcl_core::sexpr::{Atom, SExpr};
use cbcl_core::state::{frontier, render_json, render_schema, state_schema, Act, Value};
use cbcl_core::store::{ContentHash, MessageStore, ThreadId};

/// Parse a dialect S-expression, or a `(dialects <ancestor>* <leaf>)` chain,
/// and install each into a fresh registry through the full R1–R7 pipeline,
/// checking a declared `:hash` against the canonical hash of the installed
/// dialect. Ancestors precede the leaf so R5 resolves parent performatives.
///
/// Shared by every binding's dialect-taking export so no caller can bypass
/// install-time well-formedness.
pub fn parse_and_install_dialect(dialect_sexpr: &SExpr) -> Result<DialectRegistry, String> {
    let forms: Vec<&SExpr> = match dialect_sexpr {
        SExpr::List(xs) if matches!(xs.first(), Some(SExpr::Atom(Atom::Symbol(s))) if s == "dialects") =>
        {
            if xs.len() < 2 {
                return Err(String::from(
                    "(dialects ...) must contain at least one (define ...) form",
                ));
            }
            xs[1..].iter().collect()
        }
        _ => alloc::vec![dialect_sexpr],
    };
    let mut registry = DialectRegistry::new();
    for form in &forms {
        let dialect =
            crate::parse_dialect(form).map_err(|e| format!("dialect parse error: {e}"))?;
        registry
            .install(dialect)
            .map_err(|e| format!("dialect verification failed: {e}"))?;
        // A declared `:hash` must be the canonical hash of what was installed;
        // blame attribution surfaces it, so an unchecked claim could mislabel
        // which dialect signed a verdict. Checked on every link of a chain.
        let installed = registry
            .get(registry.len() - 1)
            .ok_or_else(|| String::from("internal: just-installed dialect not found"))?;
        if let Some(claimed) = &installed.hash {
            let computed = dialect_hash(installed);
            if claimed != &computed {
                return Err(format!(
                    "dialect verification failed: declared :hash {claimed} does not match canonical hash {computed}"
                ));
            }
        }
    }
    Ok(registry)
}

fn leaf(registry: &DialectRegistry) -> Result<Dialect, String> {
    registry
        .iter()
        .last()
        .cloned()
        .ok_or_else(|| String::from("no dialect installed"))
}

fn atom_text(s: &SExpr, what: &str) -> Result<String, String> {
    match s {
        SExpr::Atom(Atom::Str(x)) | SExpr::Atom(Atom::Symbol(x)) => Ok(x.clone()),
        other => Err(format!("{what} must be a string or symbol, got {other}")),
    }
}

fn parse_frame(input: &str, head: &str) -> Result<Vec<SExpr>, String> {
    let sexpr = crate::parser::parse(input).map_err(|e| format!("parse error: {e}"))?;
    match sexpr {
        SExpr::List(items) if matches!(items.first(), Some(SExpr::Atom(Atom::Symbol(s))) if s == head) => {
            Ok(items[1..].to_vec())
        }
        _ => Err(format!("expected ({head} …)")),
    }
}

fn parse_acts(sexpr: &SExpr) -> Result<Vec<Act>, String> {
    let items = match sexpr {
        SExpr::List(items) if matches!(items.first(), Some(SExpr::Atom(Atom::Symbol(s))) if s == "acts") => {
            &items[1..]
        }
        _ => return Err(String::from("expected (acts (<signer> <message>) …)")),
    };
    let mut acts = Vec::new();
    for entry in items {
        let SExpr::List(pair) = entry else {
            return Err(String::from("an act entry is (<signer> <message>)"));
        };
        if pair.len() != 2 {
            return Err(String::from("an act entry is (<signer> <message>)"));
        }
        let signer = atom_text(&pair[0], "signer")?;
        let message =
            crate::parse_message(&pair[1]).map_err(|e| format!("message parse error: {e}"))?;
        acts.push(Act::from_message(message, &signer)?);
    }
    Ok(acts)
}

type InstanceFrame = (Dialect, ThreadId, Vec<Act>, Vec<SExpr>);

fn instance_frame(input: &str, head: &str) -> Result<InstanceFrame, String> {
    let items = parse_frame(input, head)?;
    if items.len() < 3 {
        return Err(format!("expected ({head} <dialect> <thread> (acts …) …)"));
    }
    let registry = parse_and_install_dialect(&items[0])?;
    let dialect = leaf(&registry)?;
    let thread = ThreadId(atom_text(&items[1], "thread")?);
    let acts = parse_acts(&items[2])?;
    Ok((dialect, thread, acts, items[3..].to_vec()))
}

/// `(fold <dialect> <thread> (acts …))` → the state as canonical JSON.
pub fn fold_str(input: &str) -> Result<String, String> {
    let (d, thread, acts, rest) = instance_frame(input, "fold")?;
    if !rest.is_empty() {
        return Err("fold takes dialect, thread and acts".into());
    }
    if d.state.is_none() {
        return Err("dialect has no state clause".into());
    }
    Ok(render_json(&cbcl_core::escrow::fold_instance(
        &d, &thread.0, &acts,
    )))
}

/// `(intend <dialect> <thread> (acts …) <signer> <verb> (:k v …))` → the
/// canonical act for the host to sign, or `Err` with a JSON rejection.
pub fn intend_str(input: &str) -> Result<String, String> {
    let (d, thread, acts, rest) = instance_frame(input, "intend")?;
    if rest.len() != 3 {
        return Err(String::from(
            "expected (intend <dialect> <thread> (acts …) <signer> <verb> (:k v …))",
        ));
    }
    let signer = AgentKey(atom_text(&rest[0], "signer")?);
    let verb = atom_text(&rest[1], "verb")?;
    let SExpr::List(kv) = &rest[2] else {
        return Err(String::from(
            "fields must be a list of :keyword value pairs",
        ));
    };
    let mut fields = BTreeMap::new();
    let mut i = 0;
    while i + 1 < kv.len() {
        if let SExpr::Atom(Atom::Keyword(k)) = &kv[i] {
            fields.insert(k.clone(), kv[i + 1].clone());
        }
        i += 2;
    }
    let inst = Instance::new(&d, thread, &acts)?;
    match intend(&inst, &signer, &verb, fields) {
        Ok(m) => Ok(canonical_text(&m)),
        Err(r) => Err(render_reject(&r)),
    }
}

/// `(verify-state-shape <dialect> <message>)` → `"ok"`, or `Err` with a
/// REQ-233 blame S-expression.
pub fn verify_state_shape_str(input: &str) -> Result<String, String> {
    let items = parse_frame(input, "verify-state-shape")?;
    if items.len() != 2 {
        return Err(String::from(
            "expected (verify-state-shape <dialect> <message>)",
        ));
    }
    let registry = parse_and_install_dialect(&items[0])?;
    let d = leaf(&registry)?;
    let message =
        crate::parse_message(&items[1]).map_err(|e| format!("message parse error: {e}"))?;
    match cbcl_core::r7::verify_state_shape(&d, &message) {
        Ok(()) => Ok(String::from("ok")),
        Err(v) => {
            let blame = ViolationError::from_shape_violation(&v, None, None, None)
                .with_dialect_context(
                    &d.name,
                    d.author.as_deref(),
                    d.hash.as_deref(),
                    message
                        .innermost_simple()
                        .and_then(|m| m.performative())
                        .map(|p| p.name()),
                );
            Err(serialize(&blame.to_sexpr()))
        }
    }
}

/// `(state-schema <dialect>)` → the schema as JSON.
pub fn state_schema_str(input: &str) -> Result<String, String> {
    let items = parse_frame(input, "state-schema")?;
    if items.len() != 1 {
        return Err(String::from("expected (state-schema <dialect>)"));
    }
    let registry = parse_and_install_dialect(&items[0])?;
    let d = leaf(&registry)?;
    let clause = d
        .state
        .as_ref()
        .ok_or_else(|| String::from("dialect has no state clause"))?;
    Ok(render_schema(&state_schema(clause, &d.shapes)))
}

/// `(may-send <dialect> <thread> (acts …) <signer>)` → a JSON array of verbs.
pub fn may_send_str(input: &str) -> Result<String, String> {
    let (d, thread, acts, rest) = instance_frame(input, "may-send")?;
    if rest.len() != 1 {
        return Err(String::from(
            "expected (may-send <dialect> <thread> (acts …) <signer>)",
        ));
    }
    let signer = AgentKey(atom_text(&rest[0], "signer")?);
    let inst = Instance::new(&d, thread, &acts)?;
    Ok(Value::Set(
        may_send(&inst, &signer)
            .into_iter()
            .map(Value::Str)
            .collect(),
    )
    .render())
}

/// `(frontier <dialect> <thread> (acts …))` → `{"instance":…,"frontier":[…]}`.
pub fn frontier_str(input: &str) -> Result<String, String> {
    let (d, thread, acts, _) = instance_frame(input, "frontier")?;
    let inst = Instance::new(&d, thread, &acts)?;
    let instance = match inst.instance_id() {
        Some(a) => Value::Str(String::from(a)),
        None => Value::Absent,
    };
    let f = Value::List(frontier(&acts).into_iter().map(Value::Str).collect());
    Ok(format!(
        "{{\"instance\":{},\"frontier\":{}}}",
        instance.render(),
        f.render()
    ))
}

/// One message's admission verdict against an accepted set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
    /// Shape-valid and causally valid against the accepted set.
    Accepted,
    /// Shape-valid; a predecessor it names is not yet accepted (retry as the
    /// set grows).
    Pending,
    /// Blamed on the sender, with the reason.
    Rejected(String),
}

/// Admission as a consumer runs it (SPEC-019 R.4; SPEC-002 R5; SPEC-014 R6):
/// the shape stage judges the message alone (R5 shape, R7 state shape); the
/// causal stage judges it against the accepted set of its thread, under the
/// cast when the thread has an accepted root, and is `Pending` while a
/// predecessor is missing. `accepted` is the accepted set so far; the caller
/// retries `Pending` messages as it grows. One implementation for every
/// binding and for the corpus runner, so the accepted set a consumer folds is
/// the one the corpus expects.
pub fn admit(d: &Dialect, thread: &ThreadId, accepted: &[Act], act: &Act) -> Admission {
    if let Err(reason) = act.validate_identity() {
        return Admission::Rejected(format!("act identity: {reason}"));
    }
    let Some(protocol) = d.causal_protocol.as_ref() else {
        return Admission::Rejected(String::from("dialect has no protocol clause"));
    };
    if let Err(v) = cbcl_core::r7::verify_state_shape(d, &act.message) {
        return Admission::Rejected(format!("state shape: {v}"));
    }
    for shape in d.shapes.iter().filter(|s| s.performative == act.verb) {
        if let Err(v) = shape.check(&SExpr::from(act.simple())) {
            return Admission::Rejected(format!("shape: {v}"));
        }
    }
    let inst = match Instance::new(d, thread.clone(), accepted) {
        Ok(i) => i,
        Err(e) => return Admission::Rejected(e),
    };
    let mut store = inst.store();
    store.append(
        ContentHash(act.address.clone()),
        thread.clone(),
        act.message.clone(),
    );
    let endpoint = Endpoint {
        role: String::new(),
        occupant: Some(AgentKey(act.signer.clone())),
    };
    let verdict = match (&inst.cast, inst.root) {
        (Some(cast), Some(root)) => verify_causal_for_role(
            &act.message,
            &endpoint,
            d,
            cast,
            &store,
            thread,
            &ContentHash(root.address.clone()),
        ),
        _ if d.roles.is_empty() => verify_causal(
            &act.verb,
            act.simple().caused_by(),
            &store,
            protocol,
            thread,
        ),
        // A role-declaring dialect with no accepted root yet: only the root
        // itself, which carries its own cast, can be judged.
        _ if act.predecessors.is_empty() => match cast_of(&act.message, d) {
            Ok(cast) => verify_causal_for_role(
                &act.message,
                &endpoint,
                d,
                &cast,
                &store,
                thread,
                &ContentHash(act.address.clone()),
            ),
            Err(e) => return Admission::Rejected(format!("root: {e}")),
        },
        _ => VerificationResult::Unknown,
    };
    match verdict {
        VerificationResult::Valid => Admission::Accepted,
        VerificationResult::Unknown => Admission::Pending,
        VerificationResult::Violation(v) => Admission::Rejected(format!("{v}")),
    }
}

/// `(admit <dialect> <thread> (acts …) (<signer> <message>))` → JSON
/// `{"verdict":"accepted"}`, `{"verdict":"pending"}`, or
/// `{"verdict":"rejected","reason":…}`. The acts are the accepted set so far.
pub fn admit_str(input: &str) -> Result<String, String> {
    let (d, thread, accepted, rest) = instance_frame(input, "admit")?;
    if rest.len() != 1 {
        return Err(String::from(
            "expected (admit <dialect> <thread> (acts …) (<signer> <message>))",
        ));
    }
    let one = SExpr::List(alloc::vec![
        SExpr::Atom(Atom::Symbol(String::from("acts"))),
        rest[0].clone(),
    ]);
    let mut acts = parse_acts(&one)?;
    let act = acts
        .pop()
        .ok_or_else(|| String::from("expected (<signer> <message>)"))?;
    Ok(match admit(&d, &thread, &accepted, &act) {
        Admission::Accepted => String::from("{\"verdict\":\"accepted\"}"),
        Admission::Pending => String::from("{\"verdict\":\"pending\"}"),
        Admission::Rejected(reason) => format!(
            "{{\"verdict\":\"rejected\",\"reason\":{}}}",
            Value::Str(reason).render()
        ),
    })
}

/// A `(define …)` → its self-addressed name `f1220<hex>` (SPEC-019 R.6).
pub fn dialect_hash_str(input: &str) -> Result<String, String> {
    let sexpr = crate::parser::parse(input).map_err(|e| format!("parse error: {e}"))?;
    let d = crate::parse_dialect(&sexpr).map_err(|e| format!("dialect parse error: {e}"))?;
    Ok(dialect_name(&d))
}

/// Pure escrow authorization, separate from `admit`. Both are required before
/// an external effect. Supplied history and signer identities must already be
/// authenticated by the host. A locally ready result does not rule out a fork
/// that a remote owner has withheld.
pub fn resource_check_str(input: &str) -> Result<String, String> {
    resource_check_value(input).map(|value| value.render())
}

/// The native result before JSON rendering, for hosts with limited integer precision.
pub fn resource_check_value(input: &str) -> Result<Value, String> {
    use cbcl_core::escrow::{self, Outcome};
    let (d, thread, accepted, rest) = instance_frame(input, "resource-check")?;
    if rest.len() != 1 {
        return Err("expected (resource-check dialect thread (acts ...) (signer message))".into());
    }
    let one = SExpr::List(alloc::vec![
        SExpr::Atom(Atom::Symbol("acts".into())),
        rest[0].clone()
    ]);
    let candidate = parse_acts(&one)?.pop().ok_or("missing candidate")?;
    let (_, c) = escrow::rule_for(&d, &candidate.verb)
        .ok_or("candidate is not a bounded-counter operation")?;
    let rejected = |reason: String, evidence: Vec<String>| {
        Value::Map(alloc::vec![
            (Value::Str("status".into()), Value::Str("rejected".into())),
            (Value::Str("reason".into()), Value::Str(reason)),
            (
                Value::Str("evidence".into()),
                Value::List(evidence.into_iter().map(Value::Str).collect())
            )
        ])
    };
    match escrow::observe_in(&d, &thread.0, c, &accepted) {
        Outcome::Ready(_) => {}
        other => return Ok(other.value()),
    }
    if candidate.simple().thread() != Some(thread.0.as_str()) {
        return Ok(rejected(
            "candidate thread mismatch".into(),
            alloc::vec![candidate.address.clone()],
        ));
    }
    if let Err(e) = cbcl_core::r7::verify_state_shape(&d, &candidate.message) {
        return Ok(rejected(
            e.to_string(),
            alloc::vec![candidate.address.clone()],
        ));
    }
    for shape in d.shapes.iter().filter(|s| s.performative == candidate.verb) {
        if let Err(e) = shape.check(&SExpr::from(candidate.simple())) {
            return Ok(rejected(
                e.to_string(),
                alloc::vec![candidate.address.clone()],
            ));
        }
    }
    let mut with = accepted.clone();
    with.push(candidate);
    Ok(match escrow::observe_in(&d, &thread.0, c, &with) {
        Outcome::Fault { reason, evidence } => rejected(reason, evidence),
        other => other.value(),
    })
}