vouch-core 2.0.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
//! JSON facades for the robotics primitives.
//!
//! The robotics core ([`crate::robotics`]) works in typed Rust. These facades
//! present every capability as JSON-in / JSON-out with keys passed as bytes and
//! binary fields carried as multibase strings, so the UniFFI, WASM, and C-ABI
//! wrappers expose robotics to Swift, Kotlin/JVM, .NET, C/C++, and the browser
//! with one shared implementation instead of re-deriving the plumbing per layer.
//!
//! Convention: a verifier that returns "no subject/session" yields the JSON
//! literal `null`; callers test for it.

use serde_json::{json, Value};
use std::collections::HashSet;

use crate::error::{CoreError, Result};
use crate::robotics as r;

fn parse(s: &str) -> Result<Value> {
    serde_json::from_str(s).map_err(|e| CoreError::Json(format!("json: {e}")))
}
fn gs(v: &Value, k: &str) -> String {
    v.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string()
}
fn gos(v: &Value, k: &str) -> Option<String> {
    v.get(k).and_then(|x| x.as_str()).map(String::from)
}
fn gof(v: &Value, k: &str) -> Option<f64> {
    v.get(k).and_then(|x| x.as_f64())
}
fn gstrs(v: &Value, k: &str) -> Vec<String> {
    v.get(k)
        .and_then(|x| x.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|e| e.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default()
}
fn gostrs(v: &Value, k: &str) -> Option<Vec<String>> {
    v.get(k).and_then(|x| x.as_array()).map(|a| {
        a.iter()
            .filter_map(|e| e.as_str().map(String::from))
            .collect()
    })
}
fn gwindows(v: &Value, k: &str) -> Option<Vec<r::ShiftWindow>> {
    v.get(k).and_then(|x| x.as_array()).map(|a| {
        a.iter()
            .map(|w| r::ShiftWindow {
                start: gs(w, "start"),
                end: gs(w, "end"),
            })
            .collect()
    })
}
fn opt_obj(s: Option<&str>) -> Result<Option<Value>> {
    match s {
        Some(t) if !t.is_empty() && t != "null" => Ok(Some(parse(t)?)),
        _ => Ok(None),
    }
}
fn subj(opt: Option<Value>) -> String {
    opt.unwrap_or(Value::Null).to_string()
}

// ---- identity -------------------------------------------------------------

pub fn mint_robot_identity(robot_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::MintRobotIdentity {
        robot_did: gs(&p, "robotDid"),
        make: gs(&p, "make"),
        model: gs(&p, "model"),
        serial: gs(&p, "serial"),
        owner: gos(&p, "owner"),
        root_kind: gs(&p, "rootKind"),
        root_public_multibase: gs(&p, "rootPublicMultibase"),
        attestation: r::unmb64(&gs(&p, "attestation"))?,
        lifecycle: p.get("lifecycle").filter(|v| !v.is_null()).cloned(),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::mint_robot_identity(robot_seed, &params)?.to_string())
}

pub fn verify_robot_identity(credential_json: &str, robot_pub: &[u8]) -> Result<String> {
    Ok(subj(r::verify_robot_identity(
        &parse(credential_json)?,
        robot_pub,
    )?))
}

// ---- provenance -----------------------------------------------------------

pub fn config_hash(config_json: &str) -> Result<String> {
    Ok(r::config_hash(&parse(config_json)?))
}

pub fn build_provenance_attestation(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildProvenance {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        model_name: gs(&p, "modelName"),
        weights_hash: gs(&p, "weightsHash"),
        safety_policy: gs(&p, "safetyPolicy"),
        config: p.get("config").filter(|v| !v.is_null()).cloned(),
        version: gos(&p, "version"),
        supersedes: gos(&p, "supersedes"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_provenance_attestation(signer_seed, &params)?.to_string())
}

pub fn verify_provenance_attestation(
    attestation_json: &str,
    public_key: &[u8],
    config_json: Option<&str>,
) -> Result<String> {
    let config = opt_obj(config_json)?;
    Ok(subj(r::verify_provenance_attestation(
        &parse(attestation_json)?,
        public_key,
        config.as_ref(),
    )?))
}

// ---- capability -----------------------------------------------------------

pub fn build_physical_scope_credential(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildPhysicalScope {
        issuer_did: gs(&p, "issuerDid"),
        subject_did: gs(&p, "subjectDid"),
        max_force_n: gof(&p, "maxForceN"),
        max_speed_mps: gof(&p, "maxSpeedMps"),
        max_speed_near_humans_mps: gof(&p, "maxSpeedNearHumansMps"),
        allowed_zones: gostrs(&p, "allowedZones"),
        shift_windows: gwindows(&p, "shiftWindows"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_physical_scope_credential(signer_seed, &params)?.to_string())
}

pub fn check_physical_action(scope_json: &str, action_json: &str) -> Result<String> {
    let a = parse(action_json)?;
    let action = r::PhysicalAction {
        force_n: gof(&a, "forceN"),
        speed_mps: gof(&a, "speedMps"),
        near_humans: a
            .get("nearHumans")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        zone: gos(&a, "zone"),
        time_hm: gos(&a, "timeHm"),
    };
    let res = r::check_physical_action(&parse(scope_json)?, &action);
    Ok(json!({"ok": res.ok, "reasons": res.reasons}).to_string())
}

pub fn attenuates(parent_json: &str, child_json: &str) -> Result<bool> {
    Ok(r::attenuates(&parse(parent_json)?, &parse(child_json)?))
}

// ---- handshake ------------------------------------------------------------

fn policy(policy_json: Option<&str>) -> Result<Option<r::TrustPolicy>> {
    match opt_obj(policy_json)? {
        Some(v) => Ok(Some(r::TrustPolicy::new(
            gstrs(&v, "trustedDomains"),
            v.get("acceptUnknown")
                .and_then(|x| x.as_bool())
                .unwrap_or(false),
        ))),
        None => Ok(None),
    }
}

fn session_to_json(s: &r::BoundedSession) -> Value {
    json!({
        "sessionId": s.session_id,
        "initiator": s.initiator,
        "responder": s.responder,
        "scope": s.scope,
        "nonce": s.nonce,
        "validUntil": s.valid_until,
    })
}

fn session_from_json(v: &Value) -> r::BoundedSession {
    r::BoundedSession {
        session_id: gs(v, "sessionId"),
        initiator: gs(v, "initiator"),
        responder: gs(v, "responder"),
        scope: gstrs(v, "scope"),
        nonce: gs(v, "nonce"),
        valid_until: gos(v, "validUntil"),
    }
}

pub fn build_hello(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildHello {
        from_did: gs(&p, "fromDid"),
        proposed_scope: gstrs(&p, "proposedScope"),
        nonce: gs(&p, "nonce"),
        peer_did: gos(&p, "peerDid"),
        issued_at: gs(&p, "issuedAt"),
    };
    Ok(r::build_hello(signer_seed, &params)?.to_string())
}

pub fn build_accept(
    signer_seed: &[u8],
    hello_json: &str,
    hello_public_key: &[u8],
    policy_json: &str,
    params_json: &str,
) -> Result<String> {
    let pol = policy(Some(policy_json))?.unwrap_or_default();
    let p = parse(params_json)?;
    let params = r::BuildAccept {
        from_did: gs(&p, "fromDid"),
        offered_scope: gstrs(&p, "offeredScope"),
        session_id: gs(&p, "sessionId"),
        valid_until: gs(&p, "validUntil"),
        created: gs(&p, "created"),
    };
    Ok(r::build_accept(
        signer_seed,
        &parse(hello_json)?,
        hello_public_key,
        &pol,
        &params,
    )?
    .to_string())
}

pub fn verify_accept(
    accept_json: &str,
    accept_public_key: &[u8],
    expected_nonce: &str,
    policy_json: Option<&str>,
) -> Result<String> {
    let pol = policy(policy_json)?;
    let session = r::verify_accept(
        &parse(accept_json)?,
        accept_public_key,
        expected_nonce,
        pol.as_ref(),
    )?;
    Ok(session
        .map(|s| session_to_json(&s))
        .unwrap_or(Value::Null)
        .to_string())
}

pub fn build_confirm(
    signer_seed: &[u8],
    from_did: &str,
    session_json: &str,
    created: &str,
) -> Result<String> {
    let session = session_from_json(&parse(session_json)?);
    Ok(r::build_confirm(signer_seed, from_did, &session, created)?.to_string())
}

pub fn verify_confirm(
    confirm_json: &str,
    confirm_public_key: &[u8],
    session_id: &str,
    expected_nonce: &str,
) -> Result<bool> {
    r::verify_confirm(
        &parse(confirm_json)?,
        confirm_public_key,
        session_id,
        expected_nonce,
    )
}

// ---- black box and kill switch -------------------------------------------

pub fn genesis_prev_hash() -> String {
    r::genesis_prev_hash()
}

pub fn blackbox_append_entry(
    key: &[u8],
    seq: u64,
    event: &str,
    payload_json: &str,
    timestamp: &str,
    prev_hash: &str,
) -> Result<String> {
    Ok(
        r::blackbox_append_entry(key, seq, event, &parse(payload_json)?, timestamp, prev_hash)?
            .to_string(),
    )
}

pub fn blackbox_open_entry(entry_json: &str, key: &[u8]) -> Result<String> {
    Ok(r::open_entry(&parse(entry_json)?, key)?.to_string())
}

pub fn verify_blackbox_chain(
    entries_json: &str,
    genesis_prev_hash: Option<&str>,
) -> Result<String> {
    let entries = parse(entries_json)?;
    let arr = entries
        .as_array()
        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
    let res = r::verify_blackbox_chain(arr, genesis_prev_hash);
    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
}

pub fn build_killswitch_credential(authority_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildKillswitch {
        issuer_did: gs(&p, "issuerDid"),
        target: gs(&p, "target"),
        reason: gs(&p, "reason"),
        command: gos(&p, "command"),
        scope: gostrs(&p, "scope"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_killswitch_credential(authority_seed, &params)?.to_string())
}

pub fn verify_killswitch_credential(
    credential_json: &str,
    public_key: &[u8],
    trusted_authorities_json: Option<&str>,
) -> Result<String> {
    let trusted: Option<HashSet<String>> = opt_obj(trusted_authorities_json)?.map(|v| {
        v.as_array()
            .map(|a| {
                a.iter()
                    .filter_map(|e| e.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default()
    });
    Ok(subj(r::verify_killswitch_credential(
        &parse(credential_json)?,
        public_key,
        trusted.as_ref(),
    )?))
}

// ---- passport -------------------------------------------------------------

pub fn build_passport(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildPassport {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        make: gs(&p, "make"),
        model: gs(&p, "model"),
        owner: gs(&p, "owner"),
        authorized_actions: gstrs(&p, "authorizedActions"),
        certification: gos(&p, "certification"),
        status: gos(&p, "status"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_passport(signer_seed, &params)?.to_string())
}

pub fn encode_passport(passport_json: &str) -> Result<String> {
    Ok(r::encode_passport(&parse(passport_json)?))
}

pub fn decode_passport(uri: &str) -> Result<String> {
    Ok(r::decode_passport(uri)?.to_string())
}

pub fn verify_passport(passport_json: &str, public_key: &[u8], now_iso: &str) -> Result<String> {
    Ok(subj(r::verify_passport(
        &parse(passport_json)?,
        public_key,
        now_iso,
    )?))
}

pub fn verify_passport_uri(uri: &str, public_key: &[u8], now_iso: &str) -> Result<String> {
    Ok(subj(r::verify_passport_uri(uri, public_key, now_iso)?))
}

// ---- liveness -------------------------------------------------------------

fn gi(v: &Value, k: &str) -> i64 {
    v.get(k).and_then(|x| x.as_i64()).unwrap_or(0)
}

/// Build a motionDigest from a JSON array of samples against an optional scope.
/// `params_json` is `{"scope": {...}|null, "samples": [{forceN, speedMps,
/// nearHumans, zone, timeHm}, ...]}`.
pub fn motion_digest(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let scope = p.get("scope").filter(|v| !v.is_null()).cloned();
    let mut collector = r::MotionCollector::new(scope);
    if let Some(samples) = p.get("samples").and_then(|v| v.as_array()) {
        for s in samples {
            collector.record(&r::MotionSample {
                force_n: gof(s, "forceN"),
                speed_mps: gof(s, "speedMps"),
                near_humans: s
                    .get("nearHumans")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false),
                zone: gos(s, "zone"),
                time_hm: gos(s, "timeHm"),
            })?;
        }
    }
    Ok(collector.digest().to_string())
}

pub fn validate_motion_digest(digest_json: &str) -> Result<bool> {
    Ok(r::validate_motion_digest(&parse(digest_json)?).is_ok())
}

pub fn build_robot_heartbeat(robot_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildRobotHeartbeat {
        robot_did: gs(&p, "robotDid"),
        session_id: gs(&p, "sessionId"),
        interval_index: gi(&p, "intervalIndex"),
        interval_seconds: gi(&p, "intervalSeconds"),
        motion_digest: p.get("motionDigest").cloned().unwrap_or(Value::Null),
        valid_from: gs(&p, "validFrom"),
    };
    Ok(r::build_robot_heartbeat(robot_seed, &params)?.to_string())
}

pub fn verify_robot_heartbeat(credential_json: &str, robot_public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_robot_heartbeat(
        &parse(credential_json)?,
        robot_public_key,
    )?))
}

pub fn is_live(
    credential_json: &str,
    now_iso: &str,
    interval_seconds: Option<i64>,
    grace_intervals: i64,
) -> Result<bool> {
    r::is_live(
        &parse(credential_json)?,
        now_iso,
        interval_seconds,
        grace_intervals,
    )
}

// ---- revocation -----------------------------------------------------------

pub fn build_status_list_entry(
    status_list_credential: &str,
    status_list_index: i64,
    status_purpose: &str,
    entry_id: Option<&str>,
) -> Result<String> {
    Ok(r::build_status_list_entry(
        status_list_credential,
        status_list_index,
        status_purpose,
        entry_id,
    )?
    .to_string())
}

pub fn attach_credential_status(
    credential_json: &str,
    signer_seed: &[u8],
    params_json: &str,
) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::AttachCredentialStatus {
        status_list_credential: gs(&p, "statusListCredential"),
        status_list_index: gi(&p, "statusListIndex"),
        status_purpose: gos(&p, "statusPurpose")
            .unwrap_or_else(|| r::STATUS_PURPOSE_REVOCATION.to_string()),
        entry_id: gos(&p, "entryId"),
        created: gs(&p, "created"),
    };
    Ok(r::attach_credential_status(&parse(credential_json)?, signer_seed, &params)?.to_string())
}

pub fn check_credential_status(
    credential_json: &str,
    status_list_credential_json: &str,
    status_purpose: &str,
) -> Result<bool> {
    r::check_credential_status(
        &parse(credential_json)?,
        &parse(status_list_credential_json)?,
        status_purpose,
    )
}

// ---- safety record --------------------------------------------------------

/// Append one event to a ledger and return `{entry, head}`. The chain is
/// stateless across calls: pass the previous head as `prevHash` (or the genesis).
/// `params_json` is `{eventType, severity, details?, actor?, timestamp,
/// prevHash, seq}`.
pub fn safety_append_entry(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let prev = gs(&p, "prevHash");
    let mut log = r::SafetyEventLog::new(Some(&prev));
    let entry = log.append(
        &gs(&p, "eventType"),
        &gs(&p, "severity"),
        p.get("details").filter(|v| !v.is_null()),
        p.get("actor").and_then(|v| v.as_str()),
        &gs(&p, "timestamp"),
    )?;
    Ok(json!({"entry": entry, "head": log.head()}).to_string())
}

pub fn verify_safety_log(entries_json: &str, genesis_prev_hash: Option<&str>) -> Result<String> {
    let entries = parse(entries_json)?;
    let arr = entries
        .as_array()
        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
    let res = r::verify_safety_log(arr, genesis_prev_hash);
    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
}

pub fn summarize_entries(entries_json: &str, head: Option<&str>) -> Result<String> {
    let entries = parse(entries_json)?;
    let arr = entries
        .as_array()
        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
    Ok(r::summarize_entries(arr, head).to_string())
}

pub fn build_safety_record(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildSafetyRecord {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        summary: p.get("summary").cloned().unwrap_or(Value::Null),
        period_start: gos(&p, "periodStart"),
        period_end: gos(&p, "periodEnd"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_safety_record(signer_seed, &params)?.to_string())
}

pub fn verify_safety_record(credential_json: &str, public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_safety_record(
        &parse(credential_json)?,
        public_key,
    )?))
}

// ---- perception provenance ------------------------------------------------

/// Multibase SHA-256 of a raw sensor frame.
pub fn hash_frame(frame: &[u8]) -> String {
    r::hash_frame(frame)
}

/// Append one frame-provenance record to a log and return `{entry, head}`. The
/// chain is stateless across calls: pass the previous head as `prevHash` (or the
/// genesis). `params_json` is `{sensorId, modality, frameHash|frame_mb,
/// timestamp, prevHash}` where `frame_mb` is a multibase-encoded raw frame.
pub fn perception_record_entry(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let prev = gs(&p, "prevHash");
    let mut log = r::PerceptionLog::new(Some(&prev));
    let frame = match gos(&p, "frameMb") {
        Some(mb) => Some(r::unmb64(&mb)?),
        None => None,
    };
    let entry = log.record(
        &gs(&p, "sensorId"),
        &gs(&p, "modality"),
        frame.as_deref(),
        p.get("frameHash").and_then(|v| v.as_str()),
        &gs(&p, "timestamp"),
    )?;
    Ok(json!({"entry": entry, "head": log.head()}).to_string())
}

pub fn verify_perception_log(
    entries_json: &str,
    genesis_prev_hash: Option<&str>,
) -> Result<String> {
    let entries = parse(entries_json)?;
    let arr = entries
        .as_array()
        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
    let res = r::verify_perception_log(arr, genesis_prev_hash);
    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
}

pub fn build_perception_attestation(robot_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildPerception {
        robot_did: gs(&p, "robotDid"),
        sensor_id: gs(&p, "sensorId"),
        modality: gs(&p, "modality"),
        frame_hash: gs(&p, "frameHash"),
        captured_at: gos(&p, "capturedAt"),
        log_head: gos(&p, "logHead"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_perception_attestation(robot_seed, &params)?.to_string())
}

/// Verify a perception attestation. When `frame_mb` is a non-empty multibase
/// string, the raw frame is decoded and its hash compared to the attested value.
pub fn verify_perception_attestation(
    credential_json: &str,
    public_key: &[u8],
    frame_mb: Option<&str>,
) -> Result<String> {
    let frame = match frame_mb {
        Some(mb) if !mb.is_empty() => Some(r::unmb64(mb)?),
        _ => None,
    };
    Ok(subj(r::verify_perception_attestation(
        &parse(credential_json)?,
        public_key,
        frame.as_deref(),
    )?))
}

// ---- delegation lease -----------------------------------------------------

pub fn build_delegation_lease(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildDelegationLease {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        lease_id: gs(&p, "leaseId"),
        scope: p.get("scope").cloned().unwrap_or(Value::Null),
        parent_lease_id: gos(&p, "parentLeaseId"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gs(&p, "validUntil"),
    };
    Ok(r::build_delegation_lease(signer_seed, &params)?.to_string())
}

pub fn verify_delegation_lease(
    credential_json: &str,
    public_key: &[u8],
    now_iso: Option<&str>,
    parent_scope_json: Option<&str>,
) -> Result<String> {
    let now = match now_iso {
        Some(n) if !n.is_empty() && n != "null" => Some(n),
        _ => None,
    };
    let parent = opt_obj(parent_scope_json)?;
    Ok(subj(r::verify_delegation_lease(
        &parse(credential_json)?,
        public_key,
        now,
        parent.as_ref(),
    )?))
}

/// Decide whether a verified lease subject permits a proposed action.
/// `params_json` is `{subject, action, credential?, now?}` where `action` is the
/// same shape as [`check_physical_action`]'s action object.
pub fn lease_permits(params_json: &str) -> Result<bool> {
    let p = parse(params_json)?;
    let subject = p.get("subject").cloned().unwrap_or(Value::Null);
    let a = p.get("action").cloned().unwrap_or(Value::Null);
    let action = r::PhysicalAction {
        force_n: gof(&a, "forceN"),
        speed_mps: gof(&a, "speedMps"),
        near_humans: a
            .get("nearHumans")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        zone: gos(&a, "zone"),
        time_hm: gos(&a, "timeHm"),
    };
    let credential = p.get("credential").filter(|v| !v.is_null()).cloned();
    let now = gos(&p, "now");
    Ok(r::lease_permits(
        &subject,
        &action,
        credential.as_ref(),
        now.as_deref(),
    ))
}

// ---- physical quorum ------------------------------------------------------

pub fn build_action_approval(approver_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildActionApproval {
        approver_did: gs(&p, "approverDid"),
        action_id: gs(&p, "actionId"),
        robot_did: gs(&p, "robotDid"),
        decision: gos(&p, "decision").unwrap_or_else(|| r::APPROVE.to_string()),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_action_approval(approver_seed, &params)?.to_string())
}

/// Verify a quorum authorization. `params_json` is `{approvals: [...], actionId,
/// robotDid, approverKeys: {did: keyB64url, ...}, threshold, approverSet?: [...],
/// now?}`. Each `approverKeys` value is the approver's Ed25519 public key as a
/// base64url-no-pad string (the same encoding as a JWK `x`). Returns
/// `{authorized, approvers: [...]}`.
pub fn verify_action_authorization(params_json: &str) -> Result<String> {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;

    let p = parse(params_json)?;
    let approvals: Vec<Value> = p
        .get("approvals")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let action_id = gs(&p, "actionId");
    let robot_did = gs(&p, "robotDid");
    let threshold = p.get("threshold").and_then(|v| v.as_i64()).unwrap_or(0);

    let mut keys: Vec<r::ApproverKey> = Vec::new();
    if let Some(obj) = p.get("approverKeys").and_then(|v| v.as_object()) {
        for (did, key) in obj {
            let b64 = key
                .as_str()
                .ok_or_else(|| CoreError::Json("approverKeys values must be base64url".into()))?;
            let public_key = URL_SAFE_NO_PAD
                .decode(b64)
                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
            keys.push(r::ApproverKey {
                did: did.clone(),
                public_key,
            });
        }
    }

    let approver_set: Option<HashSet<String>> = p
        .get("approverSet")
        .filter(|v| !v.is_null())
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|e| e.as_str().map(String::from))
                .collect()
        });
    let now = gos(&p, "now");

    let (authorized, approvers) = r::verify_action_authorization(
        &approvals,
        &action_id,
        &robot_did,
        &keys,
        threshold,
        approver_set.as_ref(),
        now.as_deref(),
    )?;
    Ok(json!({"authorized": authorized, "approvers": approvers}).to_string())
}

// ---- robot lifecycle ------------------------------------------------------

fn owner_keys(v: &Value) -> Result<Vec<r::OwnerKey>> {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;
    let mut keys: Vec<r::OwnerKey> = Vec::new();
    if let Some(obj) = v.as_object() {
        for (did, key) in obj {
            let b64 = key
                .as_str()
                .ok_or_else(|| CoreError::Json("publicKeys values must be base64url".into()))?;
            let public_key = URL_SAFE_NO_PAD
                .decode(b64)
                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
            keys.push(r::OwnerKey {
                did: did.clone(),
                public_key,
            });
        }
    }
    Ok(keys)
}

fn key_entries(v: &Value) -> Result<Vec<r::KeyEntry>> {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;
    let mut keys: Vec<r::KeyEntry> = Vec::new();
    if let Some(obj) = v.as_object() {
        for (multibase, key) in obj {
            let b64 = key
                .as_str()
                .ok_or_else(|| CoreError::Json("publicKeys values must be base64url".into()))?;
            let public_key = URL_SAFE_NO_PAD
                .decode(b64)
                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
            keys.push(r::KeyEntry {
                multibase: multibase.clone(),
                public_key,
            });
        }
    }
    Ok(keys)
}

pub fn build_ownership_transfer(current_owner_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildOwnershipTransfer {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        to_owner: gs(&p, "toOwner"),
        from_owner: gos(&p, "fromOwner"),
        prev_transfer_id: gos(&p, "prevTransferId"),
        valid_from: gs(&p, "validFrom"),
    };
    Ok(r::build_ownership_transfer(current_owner_seed, &params)?.to_string())
}

pub fn verify_ownership_transfer(credential_json: &str, public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_ownership_transfer(
        &parse(credential_json)?,
        public_key,
    )?))
}

/// Verify a chain of custody. `params_json` is `{transfers: [...], publicKeys:
/// {did: keyB64url, ...}, originOwner?}` where each `publicKeys` value is the
/// owner's Ed25519 public key as a base64url-no-pad string. Returns `{ok,
/// currentOwner}`.
pub fn verify_custody_chain(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let transfers: Vec<Value> = p
        .get("transfers")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let keys = owner_keys(p.get("publicKeys").unwrap_or(&Value::Null))?;
    let origin = gos(&p, "originOwner");
    let (ok, current) = r::verify_custody_chain(&transfers, &keys, origin.as_deref())?;
    Ok(json!({"ok": ok, "currentOwner": current}).to_string())
}

pub fn build_key_rotation(old_key_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildKeyRotation {
        robot_did: gs(&p, "robotDid"),
        new_key_multibase: gs(&p, "newKey"),
        reason: gos(&p, "reason"),
        valid_from: gs(&p, "validFrom"),
    };
    Ok(r::build_key_rotation(old_key_seed, &params)?.to_string())
}

pub fn verify_key_rotation(credential_json: &str, old_public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_key_rotation(
        &parse(credential_json)?,
        old_public_key,
    )?))
}

/// Verify a key history. `params_json` is `{rotations: [...], originKey,
/// publicKeys: {keyMultibase: keyB64url, ...}}` where each `publicKeys` value is
/// the Ed25519 public key as a base64url-no-pad string keyed by its multibase.
/// Returns `{ok, currentKey}`.
pub fn verify_key_history(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let rotations: Vec<Value> = p
        .get("rotations")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let origin_key = gs(&p, "originKey");
    let keys = key_entries(p.get("publicKeys").unwrap_or(&Value::Null))?;
    let (ok, current) = r::verify_key_history(&rotations, &origin_key, &keys)?;
    Ok(json!({"ok": ok, "currentKey": current}).to_string())
}

pub fn build_decommission(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildDecommission {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        reason: gs(&p, "reason"),
        final_disposition: gos(&p, "finalDisposition"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_decommission(signer_seed, &params)?.to_string())
}

pub fn verify_decommission(
    credential_json: &str,
    public_key: &[u8],
    trusted_authorities_json: Option<&str>,
) -> Result<String> {
    let trusted: Option<HashSet<String>> = opt_obj(trusted_authorities_json)?.map(|v| {
        v.as_array()
            .map(|a| {
                a.iter()
                    .filter_map(|e| e.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default()
    });
    Ok(subj(r::verify_decommission(
        &parse(credential_json)?,
        public_key,
        trusted.as_ref(),
    )?))
}

// ---- regulatory conformance -----------------------------------------------

/// Check a credential set against a named profile and return the report.
/// `credentials_json` is a JSON array of credentials.
pub fn check_conformance(credentials_json: &str, profile_id: &str) -> Result<String> {
    let credentials = parse(credentials_json)?;
    let arr = credentials
        .as_array()
        .ok_or_else(|| CoreError::Json("credentials must be a JSON array".into()))?;
    Ok(r::check_conformance(arr, profile_id)?.to_string())
}

/// Multibase SHA-256 of the JCS-canonical report.
pub fn report_digest(report_json: &str) -> Result<String> {
    Ok(r::report_digest(&parse(report_json)?))
}

/// Build a signed `RobotConformanceAttestation`. `params_json` is `{issuerDid,
/// robotDid, report, validFrom, validUntil?}` where `report` comes from
/// [`check_conformance`].
pub fn build_conformance_attestation(signer_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildConformanceAttestation {
        issuer_did: gs(&p, "issuerDid"),
        robot_did: gs(&p, "robotDid"),
        report: p.get("report").cloned().unwrap_or(Value::Null),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_conformance_attestation(signer_seed, &params)?.to_string())
}

pub fn verify_conformance_attestation(credential_json: &str, public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_conformance_attestation(
        &parse(credential_json)?,
        public_key,
    )?))
}

// ---- post-quantum robot credentials --------------------------------------

pub fn sign_pq(
    credential_json: &str,
    ed25519_seed: &[u8],
    mldsa_secret: &[u8],
    mldsa_public: &[u8],
    created: &str,
) -> Result<String> {
    let ml = crate::pq::MlDsa44KeyPair::from_bytes(mldsa_secret, mldsa_public)?;
    Ok(r::sign_pq(&parse(credential_json)?, ed25519_seed, &ml, created)?.to_string())
}

pub fn is_pq(credential_json: &str) -> Result<bool> {
    Ok(r::is_pq(&parse(credential_json)?))
}

/// Verify a hybrid robot credential. `mldsa44_public` is raw 1312-byte bytes or
/// an ML-DSA-44 Multikey string carried as UTF-8 bytes.
pub fn verify_pq(
    credential_json: &str,
    ed25519_public: &[u8],
    mldsa44_public: &[u8],
) -> Result<bool> {
    let resolved = r::resolve_mldsa44_public(mldsa44_public)?;
    r::verify_pq(&parse(credential_json)?, ed25519_public, &resolved)
}

/// Dual verify auto-detected from the proof. `mldsa44_public`, when present, is
/// raw 1312-byte bytes or an ML-DSA-44 Multikey string carried as UTF-8 bytes; a
/// hybrid credential requires it, a classical credential ignores it.
pub fn verify_robot_credential(
    credential_json: &str,
    ed25519_public: &[u8],
    mldsa44_public: Option<&[u8]>,
) -> Result<bool> {
    r::verify_robot_credential(&parse(credential_json)?, ed25519_public, mldsa44_public)
}

pub fn migrate_to_pq(
    credential_json: &str,
    ed25519_seed: &[u8],
    mldsa_secret: &[u8],
    mldsa_public: &[u8],
    created: &str,
) -> Result<String> {
    let ml = crate::pq::MlDsa44KeyPair::from_bytes(mldsa_secret, mldsa_public)?;
    Ok(r::migrate_to_pq(&parse(credential_json)?, ed25519_seed, &ml, created)?.to_string())
}

// ---- cross-embodiment identity continuity ---------------------------------

pub fn build_embodiment(agent_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildEmbodiment {
        agent_did: gs(&p, "agentDid"),
        body_did: gs(&p, "body"),
        body_hardware_root: gs(&p, "bodyHardwareRoot"),
        from_body: gos(&p, "fromBody"),
        embodied_at: gs(&p, "embodiedAt"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_embodiment(agent_seed, &params)?.to_string())
}

pub fn verify_embodiment(credential_json: &str, agent_public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_embodiment(
        &parse(credential_json)?,
        agent_public_key,
    )?))
}

/// Verify a continuity chain under one agent key. `params_json` is `{embodiments:
/// [...], originBody?}`; `agent_public_key` is the agent's Ed25519 public key.
/// Returns `{ok, currentBody}`.
pub fn verify_continuity_chain(params_json: &str, agent_public_key: &[u8]) -> Result<String> {
    let p = parse(params_json)?;
    let embodiments: Vec<Value> = p
        .get("embodiments")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let origin = gos(&p, "originBody");
    let (ok, current) =
        r::verify_continuity_chain(&embodiments, agent_public_key, origin.as_deref())?;
    Ok(json!({"ok": ok, "currentBody": current}).to_string())
}

/// Check that no two embodiments place the agent in different bodies with
/// overlapping active windows. `params_json` is `{embodiments: [...]}`. Returns
/// `{ok, conflict}` where conflict, when present, is `{bodyA, bodyB}`.
pub fn check_no_fork(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let embodiments: Vec<Value> = p
        .get("embodiments")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let (ok, conflict) = r::check_no_fork(&embodiments)?;
    let conflict_json = conflict
        .map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b}))
        .unwrap_or(Value::Null);
    Ok(json!({"ok": ok, "conflict": conflict_json}).to_string())
}

// ---- physical custody handoff ---------------------------------------------

fn actor_keys(v: &Value) -> Result<Vec<r::ActorKey>> {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;
    let mut keys: Vec<r::ActorKey> = Vec::new();
    if let Some(obj) = v.as_object() {
        for (did, key) in obj {
            let b64 = key
                .as_str()
                .ok_or_else(|| CoreError::Json("publicKeys values must be base64url".into()))?;
            let public_key = URL_SAFE_NO_PAD
                .decode(b64)
                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
            keys.push(r::ActorKey {
                did: did.clone(),
                public_key,
            });
        }
    }
    Ok(keys)
}

pub fn build_handoff(receiver_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildHandoff {
        task_id: gs(&p, "taskId"),
        from_actor: gs(&p, "fromActor"),
        to_actor: gs(&p, "toActor"),
        condition: gos(&p, "condition"),
        handoff_at: gs(&p, "handoffAt"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_handoff(receiver_seed, &params)?.to_string())
}

pub fn verify_handoff(credential_json: &str, receiver_public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_handoff(
        &parse(credential_json)?,
        receiver_public_key,
    )?))
}

/// Verify a custody chain. `params_json` is `{handoffs: [...], publicKeys: {did:
/// keyB64url, ...}, originActor?}` where each `publicKeys` value is the receiver's
/// Ed25519 public key as a base64url-no-pad string. Returns `{ok, currentHolder}`.
pub fn verify_handoff_chain(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let handoffs: Vec<Value> = p
        .get("handoffs")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let keys = actor_keys(p.get("publicKeys").unwrap_or(&Value::Null))?;
    let origin = gos(&p, "originActor");
    let (ok, current) = r::verify_handoff_chain(&handoffs, &keys, origin.as_deref())?;
    Ok(json!({"ok": ok, "currentHolder": current}).to_string())
}

/// Return the actor holding the task at ISO time `at`. `params_json` is
/// `{handoffs: [...], at}`. Returns `{holder}` where holder is the actor DID or
/// null.
pub fn holder_at(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let handoffs: Vec<Value> = p
        .get("handoffs")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let at = gs(&p, "at");
    let holder = r::holder_at(&handoffs, &at);
    Ok(json!({"holder": holder}).to_string())
}

/// Localize the first attested condition change. `params_json` is `{handoffs:
/// [...]}`. Returns `{change}` where change, when present, is `{responsibleHolder,
/// fromCondition, toCondition}`, else null.
pub fn locate_condition_change(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let handoffs: Vec<Value> = p
        .get("handoffs")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let change = r::locate_condition_change(&handoffs)
        .map(|c| {
            json!({
                "responsibleHolder": c.responsible_holder,
                "fromCondition": c.from_condition,
                "toCondition": c.to_condition,
            })
        })
        .unwrap_or(Value::Null);
    Ok(json!({"change": change}).to_string())
}

// ---- robot-to-infrastructure bounded access -------------------------------

pub fn build_access_grant(operator_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildAccessGrant {
        operator_did: gs(&p, "operatorDid"),
        robot_did: gs(&p, "robotDid"),
        resource: gs(&p, "resource"),
        operations: gstrs(&p, "operations"),
        zone: gos(&p, "zone"),
        granted_at: gs(&p, "grantedAt"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_access_grant(operator_seed, &params)?.to_string())
}

/// Verify an access grant. `params_json` is `{grant: {...}, now?}`. Returns the
/// credentialSubject on success, the JSON literal `null` if invalid.
pub fn verify_access_grant(credential_json: &str, operator_public_key: &[u8]) -> Result<String> {
    let p = parse(credential_json)?;
    let grant = p.get("grant").cloned().unwrap_or(p.clone());
    let now = gos(&p, "now");
    Ok(subj(r::verify_access_grant(
        &grant,
        operator_public_key,
        now.as_deref(),
    )?))
}

pub fn build_access_request(robot_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildAccessRequest {
        robot_did: gs(&p, "robotDid"),
        resource: gs(&p, "resource"),
        operation: gs(&p, "operation"),
        requested_at: gs(&p, "requestedAt"),
    };
    Ok(r::build_access_request(robot_seed, &params)?.to_string())
}

/// Decide, offline, whether to allow the requested access. `params_json` is
/// `{grant: {...}, request: {...}, now?}`. Returns `{ok, reasons}`.
pub fn authorize_access(
    params_json: &str,
    operator_public_key: &[u8],
    robot_public_key: &[u8],
) -> Result<String> {
    let p = parse(params_json)?;
    let grant = p.get("grant").cloned().unwrap_or(Value::Null);
    let request = p.get("request").cloned().unwrap_or(Value::Null);
    let now = gos(&p, "now");
    let res = r::authorize_access(
        &grant,
        &request,
        operator_public_key,
        robot_public_key,
        now.as_deref(),
    )?;
    Ok(json!({"ok": res.ok, "reasons": res.reasons}).to_string())
}

/// Return true if `child` is a valid attenuation of `parent`. `params_json` is
/// `{parent: {...}, child: {...}}`. Returns `{ok}`.
pub fn attenuates_grant(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let parent = p.get("parent").cloned().unwrap_or(Value::Null);
    let child = p.get("child").cloned().unwrap_or(Value::Null);
    let ok = r::attenuates_grant(&parent, &child);
    Ok(json!({"ok": ok}).to_string())
}

// ---- fused-sensor provenance ----------------------------------------------

/// Deterministic multibase digest over an ordered list of input frame hashes.
/// `params_json` is `{inputFrameHashes: [...]}`.
pub fn fusion_inputs_digest(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    Ok(r::fusion_inputs_digest(&gstrs(&p, "inputFrameHashes"))?)
}

/// Multibase SHA-256 of a raw fused output.
pub fn hash_fused_output(output: &[u8]) -> String {
    r::hash_fused_output(output)
}

/// Build a signed fused-perception attestation. `params_json` is `{robotDid,
/// fusionMethod, inputFrameHashes, fusedOutputMb?|fusedOutputHash?, capturedAt?,
/// validFrom, validUntil?}` where `fusedOutputMb` is a multibase-encoded raw
/// output.
pub fn build_fused_attestation(robot_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let fused_output = match gos(&p, "fusedOutputMb") {
        Some(mb) if !mb.is_empty() => Some(r::unmb64(&mb)?),
        _ => None,
    };
    let params = r::BuildFusedAttestation {
        robot_did: gs(&p, "robotDid"),
        fusion_method: gs(&p, "fusionMethod"),
        input_frame_hashes: gstrs(&p, "inputFrameHashes"),
        fused_output,
        fused_output_hash: gos(&p, "fusedOutputHash"),
        captured_at: gos(&p, "capturedAt"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_fused_attestation(robot_seed, &params)?.to_string())
}

/// Verify a fused-perception attestation. When `fused_output_mb` is a non-empty
/// multibase string, the raw fused output is decoded and its hash compared to the
/// attested value. Returns the credentialSubject on success, `null` if invalid.
pub fn verify_fused_attestation(
    credential_json: &str,
    public_key: &[u8],
    fused_output_mb: Option<&str>,
) -> Result<String> {
    let fused_output = match fused_output_mb {
        Some(mb) if !mb.is_empty() => Some(r::unmb64(mb)?),
        _ => None,
    };
    Ok(subj(r::verify_fused_attestation(
        &parse(credential_json)?,
        public_key,
        fused_output.as_deref(),
    )?))
}

/// Confirm every input frame the attestation names was recorded in the robot's
/// perception log. `params_json` is `{credential: {...}, logEntries: [...]}`.
/// Returns `{ok, missing}`.
pub fn verify_fusion_inputs(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let credential = p.get("credential").cloned().unwrap_or(Value::Null);
    let entries = p
        .get("logEntries")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let res = r::verify_fusion_inputs(&credential, &entries);
    Ok(json!({"ok": res.ok, "missing": res.missing}).to_string())
}

// ---- wear and degradation attestation -------------------------------------

/// Build a signed wear attestation. `params_json` is `{robotDid, wearLevel,
/// metrics?, prevProof?, attestedAt?, validFrom, validUntil?}` where `metrics`, if
/// present, is an object carried through into the subject unchanged.
pub fn build_wear_attestation(robot_seed: &[u8], params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let params = r::BuildWearAttestation {
        robot_did: gs(&p, "robotDid"),
        wear_level: gof(&p, "wearLevel").unwrap_or(0.0),
        metrics: p.get("metrics").filter(|v| !v.is_null()).cloned(),
        prev_proof: gos(&p, "prevProof"),
        attested_at: gos(&p, "attestedAt"),
        valid_from: gs(&p, "validFrom"),
        valid_until: gos(&p, "validUntil"),
    };
    Ok(r::build_wear_attestation(robot_seed, &params)?.to_string())
}

/// Verify a wear attestation. Returns the credentialSubject on success, `null` if
/// invalid.
pub fn verify_wear_attestation(credential_json: &str, public_key: &[u8]) -> Result<String> {
    Ok(subj(r::verify_wear_attestation(
        &parse(credential_json)?,
        public_key,
    )?))
}

/// Verify an ordered wear history. `params_json` is `{attestations: [...]}`.
/// Returns `{ok, latest}` where `latest`, when `ok`, is the latest
/// credentialSubject.
pub fn verify_wear_chain(params_json: &str, public_key: &[u8]) -> Result<String> {
    let p = parse(params_json)?;
    let attestations: Vec<Value> = p
        .get("attestations")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let latest = r::verify_wear_chain(&attestations, public_key)?;
    Ok(json!({"ok": latest.is_some(), "latest": latest}).to_string())
}

/// Derive a physical scope narrowed for a wear level. `params_json` is `{scope:
/// {...}, wearLevel}`. Returns the narrowed scope JSON.
pub fn attenuate_for_wear(params_json: &str) -> Result<String> {
    let p = parse(params_json)?;
    let scope = p.get("scope").cloned().unwrap_or(Value::Null);
    let wear_level = gof(&p, "wearLevel").unwrap_or(0.0);
    Ok(r::attenuate_for_wear(&scope, wear_level)?.to_string())
}