@knolo/cli 6.2.5 → 6.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,887 @@
1
+ //! KITE certificate replay.
2
+ //! The world snapshot is the derivation input. This module does not search an image.
3
+ //! A passing replay means the certificate matches the declared rules and changes.
4
+
5
+ use crate::kar::json::{parse_json, Json};
6
+ use crate::{digest_domain, encode_cbor, CborValue};
7
+
8
+ #[derive(Debug, Clone, PartialEq)]
9
+ pub struct KiteDerivation {
10
+ pub verdict: String,
11
+ pub base_world: Option<String>,
12
+ pub question: String,
13
+ pub as_of: Option<String>,
14
+ pub state_root: String,
15
+ pub semantic_root: Option<String>,
16
+ pub agrees: bool,
17
+ pub witness: Option<Vec<String>>,
18
+ pub worlds_checked: u64,
19
+ pub variants_checked: u64,
20
+ pub counterfactual_changes: u64,
21
+ pub invariance_root: Option<String>,
22
+ pub negative_collections: Vec<String>,
23
+ pub obligation_ids: Vec<String>,
24
+ pub source_partitions: Vec<String>,
25
+ pub met: Vec<String>,
26
+ pub unmet: Vec<String>,
27
+ }
28
+
29
+ #[derive(Debug, Clone, PartialEq)]
30
+ pub struct KiteVerification {
31
+ pub ok: bool,
32
+ pub code: String,
33
+ pub message: String,
34
+ }
35
+
36
+ #[derive(Clone)]
37
+ struct Obligation {
38
+ id: String,
39
+ kind: String,
40
+ met: bool,
41
+ hit_ids: Vec<String>,
42
+ sources: Vec<String>,
43
+ }
44
+
45
+ struct Change {
46
+ id: String,
47
+ kind: String,
48
+ obligation_id: String,
49
+ }
50
+
51
+ struct Conflict {
52
+ left: String,
53
+ right: String,
54
+ }
55
+
56
+ struct CompletenessRule {
57
+ id: String,
58
+ collection: String,
59
+ obligation_id: String,
60
+ }
61
+
62
+ struct Declaration {
63
+ id: String,
64
+ collection: String,
65
+ signed: bool,
66
+ }
67
+
68
+ struct Rules {
69
+ format: String,
70
+ proposition: String,
71
+ support: Vec<String>,
72
+ oppose: Vec<String>,
73
+ require: Vec<String>,
74
+ conflicts: Vec<Conflict>,
75
+ completeness: Vec<CompletenessRule>,
76
+ }
77
+
78
+ struct Bounds {
79
+ max_graph_nodes: u64,
80
+ max_variants: u64,
81
+ max_counterfactual_changes: u64,
82
+ max_retrievals: u64,
83
+ }
84
+
85
+ struct World {
86
+ format: String,
87
+ question: String,
88
+ as_of: Option<String>,
89
+ state_root: String,
90
+ semantic_root: Option<String>,
91
+ obligations: Vec<Obligation>,
92
+ rules: Rules,
93
+ declarations: Vec<Declaration>,
94
+ changes: Vec<Change>,
95
+ bounds: Bounds,
96
+ }
97
+
98
+ pub fn derive_kite_world(world_json: &str) -> Result<KiteDerivation, String> {
99
+ let world = parse_world(&parse_json(world_json)?)?;
100
+ Ok(derive_world(&world))
101
+ }
102
+
103
+ pub fn verify_kite_certificate(world_json: &str, certificate_json: &str) -> KiteVerification {
104
+ let derived = match derive_kite_world(world_json) {
105
+ Ok(value) => value,
106
+ Err(message) => {
107
+ return KiteVerification {
108
+ ok: false,
109
+ code: "KITE_CERTIFICATE_MISMATCH".into(),
110
+ message,
111
+ }
112
+ }
113
+ };
114
+ let claimed = match parse_json(certificate_json).and_then(|value| parse_certificate(&value)) {
115
+ Ok(value) => value,
116
+ Err(message) => {
117
+ return KiteVerification {
118
+ ok: false,
119
+ code: "KITE_CERTIFICATE_MISMATCH".into(),
120
+ message,
121
+ }
122
+ }
123
+ };
124
+ if derived.verdict == "BOUND_EXCEEDED" || derived.invariance_root.is_none() {
125
+ return KiteVerification {
126
+ ok: false,
127
+ code: "KITE_CERTIFICATE_MISMATCH".into(),
128
+ message: "An unfinished search is not a certificate.".into(),
129
+ };
130
+ }
131
+ if claimed != derived {
132
+ return KiteVerification {
133
+ ok: false,
134
+ code: "KITE_CERTIFICATE_MISMATCH".into(),
135
+ message: "Certificate does not match a fresh derivation.".into(),
136
+ };
137
+ }
138
+ KiteVerification {
139
+ ok: true,
140
+ code: String::new(),
141
+ message: String::new(),
142
+ }
143
+ }
144
+
145
+ fn derive_world(world: &World) -> KiteDerivation {
146
+ let mut obligation_ids: Vec<String> = world.obligations.iter().map(|item| item.id.clone()).collect();
147
+ obligation_ids.sort();
148
+ let mut source_partitions: Vec<String> = world
149
+ .obligations
150
+ .iter()
151
+ .filter(|item| item.met)
152
+ .flat_map(|item| item.sources.clone())
153
+ .collect();
154
+ source_partitions.sort();
155
+ source_partitions.dedup();
156
+ let mut negative_collections: Vec<String> = world
157
+ .rules
158
+ .completeness
159
+ .iter()
160
+ .map(|rule| rule.collection.clone())
161
+ .collect();
162
+ negative_collections.sort();
163
+ negative_collections.dedup();
164
+ let met = world
165
+ .obligations
166
+ .iter()
167
+ .filter(|item| item.met)
168
+ .map(|item| item.id.clone())
169
+ .collect::<Vec<_>>();
170
+ let unmet = world
171
+ .obligations
172
+ .iter()
173
+ .filter(|item| !item.met)
174
+ .map(|item| item.id.clone())
175
+ .collect::<Vec<_>>();
176
+ let count = match subset_count(world.changes.len() as u64, world.bounds.max_counterfactual_changes) {
177
+ Ok(value) => value,
178
+ Err(_) => {
179
+ return empty_bound(
180
+ obligation_ids,
181
+ source_partitions,
182
+ negative_collections,
183
+ met,
184
+ unmet,
185
+ )
186
+ }
187
+ };
188
+ if count > world.bounds.max_variants {
189
+ return empty_bound(
190
+ obligation_ids,
191
+ source_partitions,
192
+ negative_collections,
193
+ met,
194
+ unmet,
195
+ );
196
+ }
197
+ let limit = world.bounds.max_counterfactual_changes.min(world.changes.len() as u64);
198
+ let mut worlds = Vec::new();
199
+ for size in 0..=limit {
200
+ for subset in combinations(&world.changes, size as usize) {
201
+ let met_now = apply(&world.obligations, &subset);
202
+ worlds.push((
203
+ subset.iter().map(|change| change.id.clone()).collect::<Vec<_>>(),
204
+ label(world, &met_now),
205
+ ));
206
+ }
207
+ }
208
+ let base = worlds.first().map(|item| item.1.clone()).unwrap_or_else(|| "UNDERDETERMINED".into());
209
+ let agrees = worlds.iter().all(|item| item.1 == base);
210
+ let witness = worlds.iter().find(|item| item.1 != base).map(|item| item.0.clone());
211
+ let verdict = scope_verdict(&base, agrees);
212
+ KiteDerivation {
213
+ verdict,
214
+ base_world: Some(base),
215
+ question: world.question.clone(),
216
+ as_of: world.as_of.clone(),
217
+ state_root: world.state_root.clone(),
218
+ semantic_root: world.semantic_root.clone(),
219
+ agrees,
220
+ counterfactual_changes: witness.as_ref().map(|ids| ids.len() as u64).unwrap_or(0),
221
+ witness,
222
+ worlds_checked: worlds.len() as u64,
223
+ variants_checked: worlds.len() as u64,
224
+ invariance_root: Some(invariance_root(world)),
225
+ negative_collections,
226
+ obligation_ids,
227
+ source_partitions,
228
+ met,
229
+ unmet,
230
+ }
231
+ }
232
+
233
+ fn empty_bound(
234
+ obligation_ids: Vec<String>,
235
+ source_partitions: Vec<String>,
236
+ negative_collections: Vec<String>,
237
+ met: Vec<String>,
238
+ unmet: Vec<String>,
239
+ ) -> KiteDerivation {
240
+ KiteDerivation {
241
+ verdict: "BOUND_EXCEEDED".into(),
242
+ base_world: None,
243
+ question: String::new(),
244
+ as_of: None,
245
+ state_root: String::new(),
246
+ semantic_root: None,
247
+ agrees: false,
248
+ witness: None,
249
+ worlds_checked: 0,
250
+ variants_checked: 0,
251
+ counterfactual_changes: 0,
252
+ invariance_root: None,
253
+ negative_collections,
254
+ obligation_ids,
255
+ source_partitions,
256
+ met,
257
+ unmet,
258
+ }
259
+ }
260
+
261
+ fn label(world: &World, met: &std::collections::HashSet<String>) -> String {
262
+ let support = world.rules.support.iter().any(|id| met.contains(id));
263
+ let oppose = world.rules.oppose.iter().any(|id| met.contains(id));
264
+ let signed: std::collections::HashSet<&str> = world.declarations.iter().map(|item| item.id.as_str()).collect();
265
+ let mut covered = std::collections::HashSet::new();
266
+ for rule in &world.rules.completeness {
267
+ if !met.contains(&rule.obligation_id) && signed.contains(rule.id.as_str()) {
268
+ covered.insert(rule.obligation_id.clone());
269
+ }
270
+ }
271
+ let open_require = world
272
+ .rules
273
+ .require
274
+ .iter()
275
+ .any(|id| !met.contains(id) && !covered.contains(id));
276
+ if oppose && !support {
277
+ return "REFUTED".into();
278
+ }
279
+ if open_require {
280
+ return "UNDERDETERMINED".into();
281
+ }
282
+ let paired = world
283
+ .rules
284
+ .conflicts
285
+ .iter()
286
+ .any(|pair| met.contains(&pair.left) && met.contains(&pair.right));
287
+ if (support && oppose) || paired {
288
+ return "CONFLICTED".into();
289
+ }
290
+ let known_absent = world
291
+ .rules
292
+ .require
293
+ .iter()
294
+ .any(|id| !met.contains(id) && covered.contains(id));
295
+ if known_absent {
296
+ return "REFUTED".into();
297
+ }
298
+ let gap = world.rules.completeness.iter().any(|rule| !signed.contains(rule.id.as_str()));
299
+ if support && gap {
300
+ return "SUPPORTED_OPEN_WORLD".into();
301
+ }
302
+ if support {
303
+ return "SUPPORTED_CLOSED".into();
304
+ }
305
+ "UNDERDETERMINED".into()
306
+ }
307
+
308
+ fn scope_verdict(base: &str, agrees: bool) -> String {
309
+ if agrees && base == "SUPPORTED_CLOSED" {
310
+ return "WARRANTED_IN_SCOPE".into();
311
+ }
312
+ if agrees && base == "REFUTED" {
313
+ return "REFUTED_IN_SCOPE".into();
314
+ }
315
+ if !agrees && base == "SUPPORTED_CLOSED" {
316
+ return "SUPPORTED_OPEN_WORLD".into();
317
+ }
318
+ if !agrees && base == "REFUTED" {
319
+ return "UNDERDETERMINED".into();
320
+ }
321
+ match base {
322
+ "SUPPORTED_CLOSED" => "WARRANTED_IN_SCOPE".into(),
323
+ "REFUTED" => "REFUTED_IN_SCOPE".into(),
324
+ other => other.to_string(),
325
+ }
326
+ }
327
+
328
+ fn apply(obligations: &[Obligation], changes: &[&Change]) -> std::collections::HashSet<String> {
329
+ let mut met: std::collections::HashSet<String> = obligations
330
+ .iter()
331
+ .filter(|item| item.met)
332
+ .map(|item| item.id.clone())
333
+ .collect();
334
+ for change in changes {
335
+ if change.kind == "retract" {
336
+ met.remove(&change.obligation_id);
337
+ } else {
338
+ met.insert(change.obligation_id.clone());
339
+ }
340
+ }
341
+ met
342
+ }
343
+
344
+ fn combinations(changes: &[Change], size: usize) -> Vec<Vec<&Change>> {
345
+ let mut found = Vec::new();
346
+ let mut current = Vec::new();
347
+ fn walk<'a>(
348
+ changes: &'a [Change],
349
+ size: usize,
350
+ start: usize,
351
+ current: &mut Vec<&'a Change>,
352
+ found: &mut Vec<Vec<&'a Change>>,
353
+ ) {
354
+ if current.len() == size {
355
+ found.push(current.clone());
356
+ return;
357
+ }
358
+ for index in start..changes.len() {
359
+ current.push(&changes[index]);
360
+ walk(changes, size, index + 1, current, found);
361
+ current.pop();
362
+ }
363
+ }
364
+ if size == 0 {
365
+ return vec![Vec::new()];
366
+ }
367
+ walk(changes, size, 0, &mut current, &mut found);
368
+ found
369
+ }
370
+
371
+ fn subset_count(change_count: u64, max_changes: u64) -> Result<u64, String> {
372
+ let limit = max_changes.min(change_count);
373
+ let mut total: u64 = 0;
374
+ for size in 0..=limit {
375
+ total = total
376
+ .checked_add(binomial(change_count, size)?)
377
+ .ok_or_else(|| "variant count overflow".to_string())?;
378
+ }
379
+ Ok(total)
380
+ }
381
+
382
+ fn binomial(n: u64, k: u64) -> Result<u64, String> {
383
+ if k > n {
384
+ return Ok(0);
385
+ }
386
+ let mut result: u128 = 1;
387
+ for index in 1..=k {
388
+ let next = result
389
+ .checked_mul((n - k + index) as u128)
390
+ .ok_or_else(|| "variant count overflow".to_string())?;
391
+ if next % index as u128 != 0 {
392
+ return Err("variant count is not an integer".into());
393
+ }
394
+ result = next / index as u128;
395
+ }
396
+ u64::try_from(result).map_err(|_| "variant count overflow".to_string())
397
+ }
398
+
399
+ fn invariance_root(world: &World) -> String {
400
+ digest_domain("kite-invariance", &encode_cbor(&invariance_value(world)))
401
+ }
402
+
403
+ fn invariance_value(world: &World) -> CborValue {
404
+ let mut obligations = world.obligations.clone();
405
+ obligations.sort_by(|left, right| left.id.cmp(&right.id));
406
+ CborValue::Map(vec![
407
+ ("asOf".into(), optional_text(&world.as_of)),
408
+ (
409
+ "bounds".into(),
410
+ CborValue::Map(vec![
411
+ ("maxCounterfactualChanges".into(), CborValue::UInt(world.bounds.max_counterfactual_changes)),
412
+ ("maxGraphNodes".into(), CborValue::UInt(world.bounds.max_graph_nodes)),
413
+ ("maxRetrievals".into(), CborValue::UInt(world.bounds.max_retrievals)),
414
+ ("maxVariants".into(), CborValue::UInt(world.bounds.max_variants)),
415
+ ]),
416
+ ),
417
+ (
418
+ "changes".into(),
419
+ CborValue::Array(
420
+ world
421
+ .changes
422
+ .iter()
423
+ .map(|change| {
424
+ CborValue::Map(vec![
425
+ ("id".into(), CborValue::Text(change.id.clone())),
426
+ ("kind".into(), CborValue::Text(change.kind.clone())),
427
+ ("obligationId".into(), CborValue::Text(change.obligation_id.clone())),
428
+ ])
429
+ })
430
+ .collect(),
431
+ ),
432
+ ),
433
+ (
434
+ "completeness".into(),
435
+ CborValue::Array(
436
+ world
437
+ .declarations
438
+ .iter()
439
+ .map(|item| {
440
+ CborValue::Map(vec![
441
+ ("collection".into(), CborValue::Text(item.collection.clone())),
442
+ ("id".into(), CborValue::Text(item.id.clone())),
443
+ ("signed".into(), CborValue::Bool(item.signed)),
444
+ ])
445
+ })
446
+ .collect(),
447
+ ),
448
+ ),
449
+ ("format".into(), CborValue::Text(world.format.clone())),
450
+ (
451
+ "obligations".into(),
452
+ CborValue::Array(
453
+ obligations
454
+ .iter()
455
+ .map(|item| {
456
+ let mut sources = item.sources.clone();
457
+ sources.sort();
458
+ CborValue::Map(vec![
459
+ ("hitIds".into(), text_array(&item.hit_ids)),
460
+ ("id".into(), CborValue::Text(item.id.clone())),
461
+ ("kind".into(), CborValue::Text(item.kind.clone())),
462
+ ("met".into(), CborValue::Bool(item.met)),
463
+ ("sources".into(), text_array(&sources)),
464
+ ])
465
+ })
466
+ .collect(),
467
+ ),
468
+ ),
469
+ ("question".into(), CborValue::Text(world.question.clone())),
470
+ (
471
+ "rules".into(),
472
+ CborValue::Map(vec![
473
+ (
474
+ "completeness".into(),
475
+ CborValue::Array(
476
+ world
477
+ .rules
478
+ .completeness
479
+ .iter()
480
+ .map(|rule| {
481
+ CborValue::Map(vec![
482
+ ("collection".into(), CborValue::Text(rule.collection.clone())),
483
+ ("id".into(), CborValue::Text(rule.id.clone())),
484
+ ("obligationId".into(), CborValue::Text(rule.obligation_id.clone())),
485
+ ])
486
+ })
487
+ .collect(),
488
+ ),
489
+ ),
490
+ (
491
+ "conflicts".into(),
492
+ CborValue::Array(
493
+ world
494
+ .rules
495
+ .conflicts
496
+ .iter()
497
+ .map(|pair| {
498
+ CborValue::Map(vec![
499
+ ("left".into(), CborValue::Text(pair.left.clone())),
500
+ ("right".into(), CborValue::Text(pair.right.clone())),
501
+ ])
502
+ })
503
+ .collect(),
504
+ ),
505
+ ),
506
+ ("format".into(), CborValue::Text(world.rules.format.clone())),
507
+ ("oppose".into(), text_array(&world.rules.oppose)),
508
+ ("proposition".into(), CborValue::Text(world.rules.proposition.clone())),
509
+ ("require".into(), text_array(&world.rules.require)),
510
+ ("support".into(), text_array(&world.rules.support)),
511
+ ]),
512
+ ),
513
+ ("semanticRoot".into(), optional_text(&world.semantic_root)),
514
+ ("stateRoot".into(), CborValue::Text(world.state_root.clone())),
515
+ ])
516
+ }
517
+
518
+ fn text_array(values: &[String]) -> CborValue {
519
+ CborValue::Array(values.iter().cloned().map(CborValue::Text).collect())
520
+ }
521
+
522
+ fn optional_text(value: &Option<String>) -> CborValue {
523
+ match value {
524
+ Some(text) => CborValue::Text(text.clone()),
525
+ None => CborValue::Null,
526
+ }
527
+ }
528
+
529
+ fn parse_world(value: &Json) -> Result<World, String> {
530
+ expect_keys(
531
+ value,
532
+ &[
533
+ "asOf",
534
+ "bounds",
535
+ "changes",
536
+ "completeness",
537
+ "format",
538
+ "obligations",
539
+ "question",
540
+ "rules",
541
+ "semanticRoot",
542
+ "stateRoot",
543
+ ],
544
+ )?;
545
+ if text(value, "format")? != "knolo-kite-world-1" {
546
+ return Err("world format is not knolo-kite-world-1".into());
547
+ }
548
+ let bounds_json = get(value, "bounds")?;
549
+ expect_keys(
550
+ bounds_json,
551
+ &[
552
+ "maxCounterfactualChanges",
553
+ "maxGraphNodes",
554
+ "maxRetrievals",
555
+ "maxVariants",
556
+ ],
557
+ )?;
558
+ let rules_json = get(value, "rules")?;
559
+ expect_keys(
560
+ rules_json,
561
+ &[
562
+ "completeness",
563
+ "conflicts",
564
+ "format",
565
+ "oppose",
566
+ "proposition",
567
+ "require",
568
+ "support",
569
+ ],
570
+ )?;
571
+ let completeness_json = get(value, "completeness")?;
572
+ expect_keys(completeness_json, &["declarations", "format"])?;
573
+ Ok(World {
574
+ format: text(value, "format")?,
575
+ question: text(value, "question")?,
576
+ as_of: optional_text_json(get(value, "asOf")?)?,
577
+ state_root: text(value, "stateRoot")?,
578
+ semantic_root: optional_text_json(get(value, "semanticRoot")?)?,
579
+ obligations: array(get(value, "obligations")?)?
580
+ .iter()
581
+ .map(parse_obligation)
582
+ .collect::<Result<Vec<_>, _>>()?,
583
+ rules: Rules {
584
+ format: text(rules_json, "format")?,
585
+ proposition: text(rules_json, "proposition")?,
586
+ support: string_array(get(rules_json, "support")?)?,
587
+ oppose: string_array(get(rules_json, "oppose")?)?,
588
+ require: string_array(get(rules_json, "require")?)?,
589
+ conflicts: array(get(rules_json, "conflicts")?)?
590
+ .iter()
591
+ .map(|pair| {
592
+ expect_keys(pair, &["left", "right"])?;
593
+ Ok(Conflict {
594
+ left: text(pair, "left")?,
595
+ right: text(pair, "right")?,
596
+ })
597
+ })
598
+ .collect::<Result<Vec<_>, String>>()?,
599
+ completeness: array(get(rules_json, "completeness")?)?
600
+ .iter()
601
+ .map(|rule| {
602
+ expect_keys(rule, &["collection", "id", "obligationId"])?;
603
+ Ok(CompletenessRule {
604
+ id: text(rule, "id")?,
605
+ collection: text(rule, "collection")?,
606
+ obligation_id: text(rule, "obligationId")?,
607
+ })
608
+ })
609
+ .collect::<Result<Vec<_>, String>>()?,
610
+ },
611
+ declarations: array(get(completeness_json, "declarations")?)?
612
+ .iter()
613
+ .map(|item| {
614
+ expect_keys(item, &["collection", "id", "signed"])?;
615
+ Ok(Declaration {
616
+ id: text(item, "id")?,
617
+ collection: text(item, "collection")?,
618
+ signed: boolean(item, "signed")?,
619
+ })
620
+ })
621
+ .collect::<Result<Vec<_>, String>>()?,
622
+ changes: array(get(value, "changes")?)?
623
+ .iter()
624
+ .map(|change| {
625
+ expect_keys(change, &["id", "kind", "obligationId"])?;
626
+ Ok(Change {
627
+ id: text(change, "id")?,
628
+ kind: text(change, "kind")?,
629
+ obligation_id: text(change, "obligationId")?,
630
+ })
631
+ })
632
+ .collect::<Result<Vec<_>, String>>()?,
633
+ bounds: Bounds {
634
+ max_graph_nodes: integer(bounds_json, "maxGraphNodes")?,
635
+ max_variants: integer(bounds_json, "maxVariants")?,
636
+ max_counterfactual_changes: integer(bounds_json, "maxCounterfactualChanges")?,
637
+ max_retrievals: integer(bounds_json, "maxRetrievals")?,
638
+ },
639
+ })
640
+ }
641
+
642
+ fn parse_obligation(value: &Json) -> Result<Obligation, String> {
643
+ expect_keys(value, &["hitIds", "id", "kind", "met", "sources"])?;
644
+ Ok(Obligation {
645
+ id: text(value, "id")?,
646
+ kind: text(value, "kind")?,
647
+ met: boolean(value, "met")?,
648
+ hit_ids: string_array(get(value, "hitIds")?)?,
649
+ sources: string_array(get(value, "sources")?)?,
650
+ })
651
+ }
652
+
653
+ fn parse_certificate(value: &Json) -> Result<KiteDerivation, String> {
654
+ expect_keys(
655
+ value,
656
+ &[
657
+ "agrees",
658
+ "asOf",
659
+ "baseWorld",
660
+ "counterfactualChanges",
661
+ "format",
662
+ "invarianceRoot",
663
+ "met",
664
+ "negativeCollections",
665
+ "obligationIds",
666
+ "question",
667
+ "semanticRoot",
668
+ "sourcePartitions",
669
+ "stateRoot",
670
+ "unmet",
671
+ "variantsChecked",
672
+ "verdict",
673
+ "witness",
674
+ "worldsChecked",
675
+ ],
676
+ )?;
677
+ if text(value, "format")? != "knolo-kite-certificate-1" {
678
+ return Err("certificate format is not knolo-kite-certificate-1".into());
679
+ }
680
+ let verdict = text(value, "verdict")?;
681
+ if verdict == "BOUND_EXCEEDED" {
682
+ return Err("An unfinished search is not a certificate.".into());
683
+ }
684
+ Ok(KiteDerivation {
685
+ verdict,
686
+ base_world: Some(text(value, "baseWorld")?),
687
+ question: text(value, "question")?,
688
+ as_of: optional_text_json(get(value, "asOf")?)?,
689
+ state_root: text(value, "stateRoot")?,
690
+ semantic_root: optional_text_json(get(value, "semanticRoot")?)?,
691
+ agrees: boolean(value, "agrees")?,
692
+ witness: optional_string_array(get(value, "witness")?)?,
693
+ worlds_checked: integer(value, "worldsChecked")?,
694
+ variants_checked: integer(value, "variantsChecked")?,
695
+ counterfactual_changes: integer(value, "counterfactualChanges")?,
696
+ invariance_root: Some(text(value, "invarianceRoot")?),
697
+ negative_collections: string_array(get(value, "negativeCollections")?)?,
698
+ obligation_ids: string_array(get(value, "obligationIds")?)?,
699
+ source_partitions: string_array(get(value, "sourcePartitions")?)?,
700
+ met: string_array(get(value, "met")?)?,
701
+ unmet: string_array(get(value, "unmet")?)?,
702
+ })
703
+ }
704
+
705
+ fn expect_keys(value: &Json, expected: &[&str]) -> Result<(), String> {
706
+ let mut keys = value
707
+ .as_object()
708
+ .ok_or_else(|| "expected an object".to_string())?
709
+ .iter()
710
+ .map(|(key, _)| key.as_str())
711
+ .collect::<Vec<_>>();
712
+ keys.sort();
713
+ let actual = keys.join(",");
714
+ let wanted = expected.join(",");
715
+ if actual != wanted {
716
+ return Err(format!("fields must be {wanted}"));
717
+ }
718
+ Ok(())
719
+ }
720
+
721
+ fn get<'a>(value: &'a Json, key: &str) -> Result<&'a Json, String> {
722
+ value.get(key).ok_or_else(|| format!("missing {key}"))
723
+ }
724
+
725
+ fn text(value: &Json, key: &str) -> Result<String, String> {
726
+ get(value, key)?
727
+ .as_str()
728
+ .map(ToString::to_string)
729
+ .ok_or_else(|| format!("{key} must be a string"))
730
+ }
731
+
732
+ fn boolean(value: &Json, key: &str) -> Result<bool, String> {
733
+ match get(value, key)? {
734
+ Json::Bool(item) => Ok(*item),
735
+ _ => Err(format!("{key} must be a boolean")),
736
+ }
737
+ }
738
+
739
+ fn integer(value: &Json, key: &str) -> Result<u64, String> {
740
+ let number = get(value, key)?.as_int().ok_or_else(|| format!("{key} must be an integer"))?;
741
+ u64::try_from(number).map_err(|_| format!("{key} must be unsigned"))
742
+ }
743
+
744
+ fn optional_text_json(value: &Json) -> Result<Option<String>, String> {
745
+ match value {
746
+ Json::Null => Ok(None),
747
+ Json::String(text) => Ok(Some(text.clone())),
748
+ _ => Err("expected a string or null".into()),
749
+ }
750
+ }
751
+
752
+ fn array(value: &Json) -> Result<&[Json], String> {
753
+ match value {
754
+ Json::Array(items) => Ok(items),
755
+ _ => Err("expected an array".into()),
756
+ }
757
+ }
758
+
759
+ fn string_array(value: &Json) -> Result<Vec<String>, String> {
760
+ array(value)?
761
+ .iter()
762
+ .map(|item| item.as_str().map(ToString::to_string).ok_or_else(|| "expected a string".to_string()))
763
+ .collect()
764
+ }
765
+
766
+ fn optional_string_array(value: &Json) -> Result<Option<Vec<String>>, String> {
767
+ if matches!(value, Json::Null) {
768
+ return Ok(None);
769
+ }
770
+ Ok(Some(string_array(value)?))
771
+ }
772
+
773
+ #[cfg(test)]
774
+ mod tests {
775
+ use super::*;
776
+
777
+ #[test]
778
+ fn typescript_fixtures_replay() {
779
+ let text = include_str!("../../tests/fixtures/kite-v1/cases.json");
780
+ let parsed = parse_json(text).expect("fixtures");
781
+ assert_eq!(parsed.get("format").and_then(Json::as_str), Some("kite-replay-v1"));
782
+ let cases = match parsed.get("cases") {
783
+ Some(Json::Array(items)) => items,
784
+ _ => panic!("cases"),
785
+ };
786
+ assert!(cases.len() >= 8);
787
+ for case in cases {
788
+ let id = case.get("id").and_then(Json::as_str).unwrap();
789
+ let world = case.get("world").unwrap();
790
+ let world_text = crate::kar::json::stringify(world);
791
+ let derived = derive_kite_world(&world_text).unwrap_or_else(|error| panic!("{id} {error}"));
792
+ let expected = case.get("expected").unwrap();
793
+ assert_eq!(derived.verdict, text_of(expected, "verdict"), "{id} verdict");
794
+ assert_eq!(derived.base_world.as_deref(), expected.get("baseWorld").and_then(Json::as_str), "{id} base");
795
+ assert_eq!(derived.agrees, bool_of(expected, "agrees"), "{id} agrees");
796
+ assert_eq!(derived.worlds_checked, int_of(expected, "worldsChecked"), "{id} worlds");
797
+ assert_eq!(derived.invariance_root.as_deref(), expected.get("invarianceRoot").and_then(Json::as_str), "{id} root");
798
+ assert_eq!(derived.obligation_ids, strings_of(expected, "obligationIds"), "{id} obligations");
799
+ assert_eq!(derived.met, strings_of(expected, "met"), "{id} met");
800
+ assert_eq!(derived.unmet, strings_of(expected, "unmet"), "{id} unmet");
801
+ assert_eq!(derived.source_partitions, strings_of(expected, "sourcePartitions"), "{id} sources");
802
+ if derived.verdict == "BOUND_EXCEEDED" {
803
+ let rejected = verify_kite_certificate(&world_text, "{\"format\":\"knolo-kite-certificate-1\"}");
804
+ assert!(!rejected.ok, "{id} certified an unfinished search");
805
+ continue;
806
+ }
807
+ let certificate = certificate_json(world, &derived);
808
+ let verified = verify_kite_certificate(&world_text, &certificate);
809
+ assert!(verified.ok, "{id} {}", verified.message);
810
+ let tampered = certificate.replacen(
811
+ &format!("\"verdict\":\"{}\"", derived.verdict),
812
+ "\"verdict\":\"WARRANTED_IN_SCOPE\"",
813
+ 1,
814
+ );
815
+ if derived.verdict != "WARRANTED_IN_SCOPE" {
816
+ let rejected = verify_kite_certificate(&world_text, &tampered);
817
+ assert!(!rejected.ok, "{id} accepted a tampered verdict");
818
+ }
819
+ }
820
+ }
821
+
822
+ fn certificate_json(world: &Json, derived: &KiteDerivation) -> String {
823
+ format!(
824
+ "{{\"agrees\":{},\"asOf\":{},\"baseWorld\":{},\"counterfactualChanges\":{},\"format\":\"knolo-kite-certificate-1\",\"invarianceRoot\":{},\"met\":{},\"negativeCollections\":{},\"obligationIds\":{},\"question\":{},\"semanticRoot\":{},\"sourcePartitions\":{},\"stateRoot\":{},\"unmet\":{},\"variantsChecked\":{},\"verdict\":{},\"witness\":{},\"worldsChecked\":{}}}",
825
+ derived.agrees,
826
+ json_optional(derived.as_of.as_deref()),
827
+ json_string(derived.base_world.as_deref().unwrap()),
828
+ derived.counterfactual_changes,
829
+ json_string(derived.invariance_root.as_deref().unwrap()),
830
+ json_strings(&derived.met),
831
+ json_strings(&derived.negative_collections),
832
+ json_strings(&derived.obligation_ids),
833
+ json_string(&derived.question),
834
+ json_optional(world.get("semanticRoot").and_then(Json::as_str)),
835
+ json_strings(&derived.source_partitions),
836
+ json_string(&derived.state_root),
837
+ json_strings(&derived.unmet),
838
+ derived.variants_checked,
839
+ json_string(&derived.verdict),
840
+ match &derived.witness {
841
+ Some(ids) => json_strings(ids),
842
+ None => "null".to_string(),
843
+ },
844
+ derived.worlds_checked,
845
+ )
846
+ }
847
+
848
+ fn json_string(value: &str) -> String {
849
+ format!("\"{value}\"")
850
+ }
851
+
852
+ fn json_optional(value: Option<&str>) -> String {
853
+ match value {
854
+ Some(text) => json_string(text),
855
+ None => "null".into(),
856
+ }
857
+ }
858
+
859
+ fn json_strings(values: &[String]) -> String {
860
+ format!(
861
+ "[{}]",
862
+ values.iter().map(|value| json_string(value)).collect::<Vec<_>>().join(",")
863
+ )
864
+ }
865
+
866
+ fn text_of(value: &Json, key: &str) -> String {
867
+ value.get(key).and_then(Json::as_str).unwrap().to_string()
868
+ }
869
+
870
+ fn bool_of(value: &Json, key: &str) -> bool {
871
+ match value.get(key) {
872
+ Some(Json::Bool(item)) => *item,
873
+ _ => panic!("{key}"),
874
+ }
875
+ }
876
+
877
+ fn int_of(value: &Json, key: &str) -> u64 {
878
+ u64::try_from(value.get(key).and_then(Json::as_int).unwrap()).unwrap()
879
+ }
880
+
881
+ fn strings_of(value: &Json, key: &str) -> Vec<String> {
882
+ match value.get(key) {
883
+ Some(Json::Array(items)) => items.iter().map(|item| item.as_str().unwrap().to_string()).collect(),
884
+ _ => panic!("{key}"),
885
+ }
886
+ }
887
+ }