1#![forbid(unsafe_code)]
27
28use alloc::collections::BTreeMap;
29use alloc::format;
30use alloc::string::{String, ToString};
31use alloc::vec::Vec;
32use cbcl_core::blame::ViolationError;
33use cbcl_core::canonical::{dialect_hash, dialect_name};
34use cbcl_core::dialect::{Dialect, DialectRegistry};
35use cbcl_core::intend::{canonical_text, cast_of, intend, may_send, render_reject, Instance};
36use cbcl_core::projection::verify_causal_for_role;
37use cbcl_core::protocol::{verify_causal, VerificationResult};
38use cbcl_core::role::{AgentKey, Endpoint};
39use cbcl_core::serializer::serialize;
40use cbcl_core::sexpr::{Atom, SExpr};
41use cbcl_core::state::{frontier, render_json, render_schema, state_schema, Act, Value};
42use cbcl_core::store::{ContentHash, MessageStore, ThreadId};
43
44pub fn parse_and_install_dialect(dialect_sexpr: &SExpr) -> Result<DialectRegistry, String> {
52 let forms: Vec<&SExpr> = match dialect_sexpr {
53 SExpr::List(xs) if matches!(xs.first(), Some(SExpr::Atom(Atom::Symbol(s))) if s == "dialects") =>
54 {
55 if xs.len() < 2 {
56 return Err(String::from(
57 "(dialects ...) must contain at least one (define ...) form",
58 ));
59 }
60 xs[1..].iter().collect()
61 }
62 _ => alloc::vec![dialect_sexpr],
63 };
64 let mut registry = DialectRegistry::new();
65 for form in &forms {
66 let dialect =
67 crate::parse_dialect(form).map_err(|e| format!("dialect parse error: {e}"))?;
68 registry
69 .install(dialect)
70 .map_err(|e| format!("dialect verification failed: {e}"))?;
71 let installed = registry
75 .get(registry.len() - 1)
76 .ok_or_else(|| String::from("internal: just-installed dialect not found"))?;
77 if let Some(claimed) = &installed.hash {
78 let computed = dialect_hash(installed);
79 if claimed != &computed {
80 return Err(format!(
81 "dialect verification failed: declared :hash {claimed} does not match canonical hash {computed}"
82 ));
83 }
84 }
85 }
86 Ok(registry)
87}
88
89fn leaf(registry: &DialectRegistry) -> Result<Dialect, String> {
90 registry
91 .iter()
92 .last()
93 .cloned()
94 .ok_or_else(|| String::from("no dialect installed"))
95}
96
97fn atom_text(s: &SExpr, what: &str) -> Result<String, String> {
98 match s {
99 SExpr::Atom(Atom::Str(x)) | SExpr::Atom(Atom::Symbol(x)) => Ok(x.clone()),
100 other => Err(format!("{what} must be a string or symbol, got {other}")),
101 }
102}
103
104fn parse_frame(input: &str, head: &str) -> Result<Vec<SExpr>, String> {
105 let sexpr = crate::parser::parse(input).map_err(|e| format!("parse error: {e}"))?;
106 match sexpr {
107 SExpr::List(items) if matches!(items.first(), Some(SExpr::Atom(Atom::Symbol(s))) if s == head) => {
108 Ok(items[1..].to_vec())
109 }
110 _ => Err(format!("expected ({head} …)")),
111 }
112}
113
114fn parse_acts(sexpr: &SExpr) -> Result<Vec<Act>, String> {
115 let items = match sexpr {
116 SExpr::List(items) if matches!(items.first(), Some(SExpr::Atom(Atom::Symbol(s))) if s == "acts") => {
117 &items[1..]
118 }
119 _ => return Err(String::from("expected (acts (<signer> <message>) …)")),
120 };
121 let mut acts = Vec::new();
122 for entry in items {
123 let SExpr::List(pair) = entry else {
124 return Err(String::from("an act entry is (<signer> <message>)"));
125 };
126 if pair.len() != 2 {
127 return Err(String::from("an act entry is (<signer> <message>)"));
128 }
129 let signer = atom_text(&pair[0], "signer")?;
130 let message =
131 crate::parse_message(&pair[1]).map_err(|e| format!("message parse error: {e}"))?;
132 acts.push(Act::from_message(message, &signer)?);
133 }
134 Ok(acts)
135}
136
137type InstanceFrame = (Dialect, ThreadId, Vec<Act>, Vec<SExpr>);
138
139fn instance_frame(input: &str, head: &str) -> Result<InstanceFrame, String> {
140 let items = parse_frame(input, head)?;
141 if items.len() < 3 {
142 return Err(format!("expected ({head} <dialect> <thread> (acts …) …)"));
143 }
144 let registry = parse_and_install_dialect(&items[0])?;
145 let dialect = leaf(®istry)?;
146 let thread = ThreadId(atom_text(&items[1], "thread")?);
147 let acts = parse_acts(&items[2])?;
148 Ok((dialect, thread, acts, items[3..].to_vec()))
149}
150
151pub fn fold_str(input: &str) -> Result<String, String> {
153 let (d, thread, acts, rest) = instance_frame(input, "fold")?;
154 if !rest.is_empty() {
155 return Err("fold takes dialect, thread and acts".into());
156 }
157 if d.state.is_none() {
158 return Err("dialect has no state clause".into());
159 }
160 Ok(render_json(&cbcl_core::escrow::fold_instance(
161 &d, &thread.0, &acts,
162 )))
163}
164
165pub fn intend_str(input: &str) -> Result<String, String> {
168 let (d, thread, acts, rest) = instance_frame(input, "intend")?;
169 if rest.len() != 3 {
170 return Err(String::from(
171 "expected (intend <dialect> <thread> (acts …) <signer> <verb> (:k v …))",
172 ));
173 }
174 let signer = AgentKey(atom_text(&rest[0], "signer")?);
175 let verb = atom_text(&rest[1], "verb")?;
176 let SExpr::List(kv) = &rest[2] else {
177 return Err(String::from(
178 "fields must be a list of :keyword value pairs",
179 ));
180 };
181 let mut fields = BTreeMap::new();
182 let mut i = 0;
183 while i + 1 < kv.len() {
184 if let SExpr::Atom(Atom::Keyword(k)) = &kv[i] {
185 fields.insert(k.clone(), kv[i + 1].clone());
186 }
187 i += 2;
188 }
189 let inst = Instance::new(&d, thread, &acts)?;
190 match intend(&inst, &signer, &verb, fields) {
191 Ok(m) => Ok(canonical_text(&m)),
192 Err(r) => Err(render_reject(&r)),
193 }
194}
195
196pub fn verify_state_shape_str(input: &str) -> Result<String, String> {
199 let items = parse_frame(input, "verify-state-shape")?;
200 if items.len() != 2 {
201 return Err(String::from(
202 "expected (verify-state-shape <dialect> <message>)",
203 ));
204 }
205 let registry = parse_and_install_dialect(&items[0])?;
206 let d = leaf(®istry)?;
207 let message =
208 crate::parse_message(&items[1]).map_err(|e| format!("message parse error: {e}"))?;
209 match cbcl_core::r7::verify_state_shape(&d, &message) {
210 Ok(()) => Ok(String::from("ok")),
211 Err(v) => {
212 let blame = ViolationError::from_shape_violation(&v, None, None, None)
213 .with_dialect_context(
214 &d.name,
215 d.author.as_deref(),
216 d.hash.as_deref(),
217 message
218 .innermost_simple()
219 .and_then(|m| m.performative())
220 .map(|p| p.name()),
221 );
222 Err(serialize(&blame.to_sexpr()))
223 }
224 }
225}
226
227pub fn state_schema_str(input: &str) -> Result<String, String> {
229 let items = parse_frame(input, "state-schema")?;
230 if items.len() != 1 {
231 return Err(String::from("expected (state-schema <dialect>)"));
232 }
233 let registry = parse_and_install_dialect(&items[0])?;
234 let d = leaf(®istry)?;
235 let clause = d
236 .state
237 .as_ref()
238 .ok_or_else(|| String::from("dialect has no state clause"))?;
239 Ok(render_schema(&state_schema(clause, &d.shapes)))
240}
241
242pub fn may_send_str(input: &str) -> Result<String, String> {
244 let (d, thread, acts, rest) = instance_frame(input, "may-send")?;
245 if rest.len() != 1 {
246 return Err(String::from(
247 "expected (may-send <dialect> <thread> (acts …) <signer>)",
248 ));
249 }
250 let signer = AgentKey(atom_text(&rest[0], "signer")?);
251 let inst = Instance::new(&d, thread, &acts)?;
252 Ok(Value::Set(
253 may_send(&inst, &signer)
254 .into_iter()
255 .map(Value::Str)
256 .collect(),
257 )
258 .render())
259}
260
261pub fn frontier_str(input: &str) -> Result<String, String> {
263 let (d, thread, acts, _) = instance_frame(input, "frontier")?;
264 let inst = Instance::new(&d, thread, &acts)?;
265 let instance = match inst.instance_id() {
266 Some(a) => Value::Str(String::from(a)),
267 None => Value::Absent,
268 };
269 let f = Value::List(frontier(&acts).into_iter().map(Value::Str).collect());
270 Ok(format!(
271 "{{\"instance\":{},\"frontier\":{}}}",
272 instance.render(),
273 f.render()
274 ))
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum Admission {
280 Accepted,
282 Pending,
285 Rejected(String),
287}
288
289pub fn admit(d: &Dialect, thread: &ThreadId, accepted: &[Act], act: &Act) -> Admission {
298 if let Err(reason) = act.validate_identity() {
299 return Admission::Rejected(format!("act identity: {reason}"));
300 }
301 let Some(protocol) = d.causal_protocol.as_ref() else {
302 return Admission::Rejected(String::from("dialect has no protocol clause"));
303 };
304 if let Err(v) = cbcl_core::r7::verify_state_shape(d, &act.message) {
305 return Admission::Rejected(format!("state shape: {v}"));
306 }
307 for shape in d.shapes.iter().filter(|s| s.performative == act.verb) {
308 if let Err(v) = shape.check(&SExpr::from(act.simple())) {
309 return Admission::Rejected(format!("shape: {v}"));
310 }
311 }
312 let inst = match Instance::new(d, thread.clone(), accepted) {
313 Ok(i) => i,
314 Err(e) => return Admission::Rejected(e),
315 };
316 let mut store = inst.store();
317 store.append(
318 ContentHash(act.address.clone()),
319 thread.clone(),
320 act.message.clone(),
321 );
322 let endpoint = Endpoint {
323 role: String::new(),
324 occupant: Some(AgentKey(act.signer.clone())),
325 };
326 let verdict = match (&inst.cast, inst.root) {
327 (Some(cast), Some(root)) => verify_causal_for_role(
328 &act.message,
329 &endpoint,
330 d,
331 cast,
332 &store,
333 thread,
334 &ContentHash(root.address.clone()),
335 ),
336 _ if d.roles.is_empty() => verify_causal(
337 &act.verb,
338 act.simple().caused_by(),
339 &store,
340 protocol,
341 thread,
342 ),
343 _ if act.predecessors.is_empty() => match cast_of(&act.message, d) {
346 Ok(cast) => verify_causal_for_role(
347 &act.message,
348 &endpoint,
349 d,
350 &cast,
351 &store,
352 thread,
353 &ContentHash(act.address.clone()),
354 ),
355 Err(e) => return Admission::Rejected(format!("root: {e}")),
356 },
357 _ => VerificationResult::Unknown,
358 };
359 match verdict {
360 VerificationResult::Valid => Admission::Accepted,
361 VerificationResult::Unknown => Admission::Pending,
362 VerificationResult::Violation(v) => Admission::Rejected(format!("{v}")),
363 }
364}
365
366pub fn admit_str(input: &str) -> Result<String, String> {
370 let (d, thread, accepted, rest) = instance_frame(input, "admit")?;
371 if rest.len() != 1 {
372 return Err(String::from(
373 "expected (admit <dialect> <thread> (acts …) (<signer> <message>))",
374 ));
375 }
376 let one = SExpr::List(alloc::vec![
377 SExpr::Atom(Atom::Symbol(String::from("acts"))),
378 rest[0].clone(),
379 ]);
380 let mut acts = parse_acts(&one)?;
381 let act = acts
382 .pop()
383 .ok_or_else(|| String::from("expected (<signer> <message>)"))?;
384 Ok(match admit(&d, &thread, &accepted, &act) {
385 Admission::Accepted => String::from("{\"verdict\":\"accepted\"}"),
386 Admission::Pending => String::from("{\"verdict\":\"pending\"}"),
387 Admission::Rejected(reason) => format!(
388 "{{\"verdict\":\"rejected\",\"reason\":{}}}",
389 Value::Str(reason).render()
390 ),
391 })
392}
393
394pub fn dialect_hash_str(input: &str) -> Result<String, String> {
396 let sexpr = crate::parser::parse(input).map_err(|e| format!("parse error: {e}"))?;
397 let d = crate::parse_dialect(&sexpr).map_err(|e| format!("dialect parse error: {e}"))?;
398 Ok(dialect_name(&d))
399}
400
401pub fn resource_check_str(input: &str) -> Result<String, String> {
406 resource_check_value(input).map(|value| value.render())
407}
408
409pub fn resource_check_value(input: &str) -> Result<Value, String> {
411 use cbcl_core::escrow::{self, Outcome};
412 let (d, thread, accepted, rest) = instance_frame(input, "resource-check")?;
413 if rest.len() != 1 {
414 return Err("expected (resource-check dialect thread (acts ...) (signer message))".into());
415 }
416 let one = SExpr::List(alloc::vec![
417 SExpr::Atom(Atom::Symbol("acts".into())),
418 rest[0].clone()
419 ]);
420 let candidate = parse_acts(&one)?.pop().ok_or("missing candidate")?;
421 let (_, c) = escrow::rule_for(&d, &candidate.verb)
422 .ok_or("candidate is not a bounded-counter operation")?;
423 let rejected = |reason: String, evidence: Vec<String>| {
424 Value::Map(alloc::vec![
425 (Value::Str("status".into()), Value::Str("rejected".into())),
426 (Value::Str("reason".into()), Value::Str(reason)),
427 (
428 Value::Str("evidence".into()),
429 Value::List(evidence.into_iter().map(Value::Str).collect())
430 )
431 ])
432 };
433 match escrow::observe_in(&d, &thread.0, c, &accepted) {
434 Outcome::Ready(_) => {}
435 other => return Ok(other.value()),
436 }
437 if candidate.simple().thread() != Some(thread.0.as_str()) {
438 return Ok(rejected(
439 "candidate thread mismatch".into(),
440 alloc::vec![candidate.address.clone()],
441 ));
442 }
443 if let Err(e) = cbcl_core::r7::verify_state_shape(&d, &candidate.message) {
444 return Ok(rejected(
445 e.to_string(),
446 alloc::vec![candidate.address.clone()],
447 ));
448 }
449 for shape in d.shapes.iter().filter(|s| s.performative == candidate.verb) {
450 if let Err(e) = shape.check(&SExpr::from(candidate.simple())) {
451 return Ok(rejected(
452 e.to_string(),
453 alloc::vec![candidate.address.clone()],
454 ));
455 }
456 }
457 let mut with = accepted.clone();
458 with.push(candidate);
459 Ok(match escrow::observe_in(&d, &thread.0, c, &with) {
460 Outcome::Fault { reason, evidence } => rejected(reason, evidence),
461 other => other.value(),
462 })
463}