exochain-wasm 0.2.0-beta

ExoChain governance engine — WebAssembly bindings for Node.js
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Decision Forum bindings: DecisionObject lifecycle, constitution, TNC enforcement,
//! contestation, accountability, workflow, emergency

use serde::Deserialize;
use wasm_bindgen::prelude::*;

use crate::serde_bridge::*;

const MAX_WASM_FORUM_EMERGENCY_ACTIONS: usize = 4_096;
const MAX_WASM_FORUM_CHALLENGES: usize = 4_096;
const MAX_WASM_FORUM_CONSTITUTION_BYTES: usize = 1_048_576;

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct WasmDecisionTransitionAdjudicatedRequest {
    decision: decision_forum::decision_object::DecisionObject,
    to_state: exo_core::bcts::BctsState,
    actor_did: String,
    timestamp_ms: u64,
    timestamp_logical: u32,
    action: exo_gatekeeper::kernel::ActionRequest,
    context: exo_gatekeeper::kernel::AdjudicationContext,
}

fn parse_decision_transition_adjudicated_request(
    request_json: &str,
) -> Result<WasmDecisionTransitionAdjudicatedRequest, JsValue> {
    let request_value: serde_json::Value = from_json_str(request_json)?;
    if request_value.get("invariant_set").is_some() {
        return Err(JsValue::from_str(
            "caller-supplied invariant_set is rejected; WASM decision transitions enforce canonical constitutional invariants",
        ));
    }

    serde_json::from_value(request_value).map_err(|_| JsValue::from_str("JSON parse error"))
}

/// Create a new DecisionObject with full BCTS lifecycle
#[wasm_bindgen]
pub fn wasm_create_decision(
    decision_id: &str,
    title: &str,
    class_json: &str,
    constitution_hash_hex: &str,
    created_at_ms: u64,
    created_at_logical: u32,
) -> Result<JsValue, JsValue> {
    let id = parse_uuid(decision_id)?;
    let class: decision_forum::decision_object::DecisionClass = from_json_str(class_json)?;
    let hash = parse_hash(constitution_hash_hex, "hash")?;
    let created_at = exo_core::types::Timestamp::new(created_at_ms, created_at_logical);

    let decision = decision_forum::decision_object::DecisionObject::new(
        decision_forum::decision_object::DecisionObjectInput {
            id,
            title: title.into(),
            class,
            constitutional_hash: hash,
            created_at,
        },
    )
    .map_err(|e| JsValue::from_str(&format!("Decision error: {e}")))?;
    to_js_value(&decision)
}

/// Transition a DecisionObject to a new BCTS state
#[wasm_bindgen]
pub fn wasm_transition_decision(
    decision_json: &str,
    to_state_json: &str,
    actor_did: &str,
    timestamp_ms: u64,
    timestamp_logical: u32,
) -> Result<JsValue, JsValue> {
    let _ = (
        decision_json,
        to_state_json,
        actor_did,
        timestamp_ms,
        timestamp_logical,
    );
    Err(JsValue::from_str(
        "unadjudicated decision transitions are disabled; use wasm_transition_decision_adjudicated",
    ))
}

/// Transition a DecisionObject to a new BCTS state after kernel adjudication.
#[wasm_bindgen]
pub fn wasm_transition_decision_adjudicated(
    request_json: &str,
    constitution: &[u8],
) -> Result<JsValue, JsValue> {
    ensure_constitution_bytes(constitution.len())?;
    let WasmDecisionTransitionAdjudicatedRequest {
        mut decision,
        to_state,
        actor_did,
        timestamp_ms,
        timestamp_logical,
        action,
        context,
    } = parse_decision_transition_adjudicated_request(request_json)?;
    let actor = exo_core::Did::new(&actor_did)
        .map_err(|e| JsValue::from_str(&format!("DID error: {e}")))?;
    let ts = exo_core::types::Timestamp::new(timestamp_ms, timestamp_logical);
    let kernel = exo_gatekeeper::kernel::Kernel::new(
        constitution,
        exo_gatekeeper::invariants::InvariantSet::all(),
    );

    decision
        .transition_adjudicated_at(to_state, &actor, ts, &kernel, &action, &context)
        .map_err(|e| JsValue::from_str(&format!("Transition error: {e}")))?;
    to_js_value(&decision)
}

/// Add a vote to a DecisionObject
#[wasm_bindgen]
pub fn wasm_add_vote(decision_json: &str, vote_json: &str) -> Result<JsValue, JsValue> {
    let mut decision: decision_forum::decision_object::DecisionObject =
        from_json_str(decision_json)?;
    let vote: decision_forum::decision_object::Vote = from_json_str(vote_json)?;

    decision
        .add_vote(vote)
        .map_err(|e| JsValue::from_str(&format!("Vote error: {e}")))?;
    to_js_value(&decision)
}

/// Add evidence to a DecisionObject
#[wasm_bindgen]
pub fn wasm_add_evidence(decision_json: &str, evidence_json: &str) -> Result<JsValue, JsValue> {
    let mut decision: decision_forum::decision_object::DecisionObject =
        from_json_str(decision_json)?;
    let evidence: decision_forum::decision_object::EvidenceItem = from_json_str(evidence_json)?;

    decision
        .add_evidence(evidence)
        .map_err(|e| JsValue::from_str(&format!("Evidence error: {e}")))?;
    to_js_value(&decision)
}

/// Check if a DecisionObject is in a terminal state
#[wasm_bindgen]
pub fn wasm_decision_is_terminal(decision_json: &str) -> Result<bool, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    Ok(decision.is_terminal())
}

/// Compute the content hash of a DecisionObject (audit fingerprint)
#[wasm_bindgen]
pub fn wasm_decision_content_hash(decision_json: &str) -> Result<String, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let hash = decision
        .content_hash()
        .map_err(|e| JsValue::from_str(&format!("Hash error: {e}")))?;
    Ok(hex::encode(hash.as_bytes()))
}

/// File a challenge against a decision (contestation - GOV-008)
#[wasm_bindgen]
pub fn wasm_file_challenge(
    challenge_id: &str,
    challenger_did: &str,
    decision_id: &str,
    ground_json: &str,
    evidence_hash_hex: &str,
    created_at_ms: u64,
    created_at_logical: u32,
) -> Result<JsValue, JsValue> {
    let challenge_id = parse_uuid(challenge_id)?;
    let challenger = exo_core::Did::new(challenger_did)
        .map_err(|e| JsValue::from_str(&format!("DID error: {e}")))?;
    let decision_id = parse_uuid(decision_id)?;
    let ground: exo_governance::challenge::ChallengeGround = from_json_str(ground_json)?;
    let evidence_hash = parse_hash(evidence_hash_hex, "evidence hash")?;
    let created_at = exo_core::types::Timestamp::new(created_at_ms, created_at_logical);

    let challenge = decision_forum::contestation::file_challenge(
        decision_forum::contestation::ChallengeInput {
            id: challenge_id,
            decision_id,
            challenger,
            ground,
            evidence_hash,
            created_at,
        },
    )
    .map_err(|e| JsValue::from_str(&format!("Challenge error: {e}")))?;
    to_js_value(&challenge)
}

/// Propose an accountability action (GOV-012)
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
// WASM exports cannot accept Rust input structs directly; the explicit
// metadata fields keep provenance caller-supplied across the JS boundary.
pub fn wasm_propose_accountability(
    action_id: &str,
    target_did: &str,
    proposer_did: &str,
    action_type_json: &str,
    reason: &str,
    evidence_hash_hex: &str,
    proposed_at_ms: u64,
    proposed_at_logical: u32,
) -> Result<JsValue, JsValue> {
    let action_id = parse_uuid(action_id)?;
    let target = exo_core::Did::new(target_did)
        .map_err(|e| JsValue::from_str(&format!("DID error: {e}")))?;
    let proposer = exo_core::Did::new(proposer_did)
        .map_err(|e| JsValue::from_str(&format!("DID error: {e}")))?;
    let action_type: decision_forum::accountability::AccountabilityActionType =
        from_json_str(action_type_json)?;
    let evidence_hash = parse_hash(evidence_hash_hex, "evidence hash")?;
    let proposed_at = exo_core::types::Timestamp::new(proposed_at_ms, proposed_at_logical);

    let action = decision_forum::accountability::propose(
        decision_forum::accountability::AccountabilityInput {
            id: action_id,
            action_type,
            target,
            proposer,
            reason: reason.into(),
            evidence_hash,
            proposed_at,
        },
    )
    .map_err(|e| JsValue::from_str(&format!("Accountability error: {e}")))?;
    to_js_value(&action)
}

/// Get all BCTS state names in lifecycle order.
#[wasm_bindgen]
pub fn wasm_workflow_stages() -> Result<JsValue, JsValue> {
    let stages = vec![
        "Draft",
        "Submitted",
        "IdentityResolved",
        "ConsentValidated",
        "Deliberated",
        "Verified",
        "Governed",
        "Approved",
        "Executed",
        "Recorded",
        "Closed",
        "Denied",
        "Escalated",
        "Remediated",
    ];
    to_js_value(&stages)
}

// ── Constitution ─────────────────────────────────────────────────

/// Ratify a constitutional corpus with a set of Ed25519 signatures.
///
/// `signatures_json` — JSON array of `[did_str, signature_hex]` pairs.
/// `quorum_json`     — JSON `{required_signatures, required_fraction_pct}`.
/// `public_keys_json` — JSON array of `[did_str, public_key_hex]` eligible signer pairs.
/// `timestamp_ms`    — caller-supplied ratification timestamp bound into signatures.
#[wasm_bindgen]
pub fn wasm_ratify_constitution(
    corpus_json: &str,
    signatures_json: &str,
    quorum_json: &str,
    public_keys_json: &str,
    timestamp_ms: u64,
) -> Result<JsValue, JsValue> {
    let _ = (
        corpus_json,
        signatures_json,
        quorum_json,
        public_keys_json,
        timestamp_ms,
    );
    Err(JsValue::from_str(
        "constitutional ratification requires a trusted core runtime adapter; public WASM callers cannot supply signer keys or eligible signer sets",
    ))
}

/// Amend a constitutional corpus by adding or updating an article.
///
/// `amendment_json`  — JSON `Article` object.
/// `signatures_json` — JSON array of `[did_str, signature_hex]` pairs.
/// `quorum_json`     — JSON `{required_signatures, required_fraction_pct}`.
/// `public_keys_json` — JSON array of `[did_str, public_key_hex]` eligible signer pairs.
/// `timestamp_ms`    — caller-supplied amendment timestamp bound into signatures.
#[wasm_bindgen]
pub fn wasm_amend_constitution(
    corpus_json: &str,
    amendment_json: &str,
    signatures_json: &str,
    quorum_json: &str,
    public_keys_json: &str,
    timestamp_ms: u64,
) -> Result<JsValue, JsValue> {
    let _ = (
        corpus_json,
        amendment_json,
        signatures_json,
        quorum_json,
        public_keys_json,
        timestamp_ms,
    );
    Err(JsValue::from_str(
        "constitutional amendment requires a trusted core runtime adapter; public WASM callers cannot supply signer keys or eligible signer sets",
    ))
}

/// Dry-run a constitutional amendment — returns conflict descriptions.
#[wasm_bindgen]
pub fn wasm_dry_run_amendment(corpus_json: &str, proposed_json: &str) -> Result<JsValue, JsValue> {
    let corpus: decision_forum::constitution::ConstitutionCorpus = from_json_str(corpus_json)?;
    let proposed: decision_forum::constitution::Article = from_json_str(proposed_json)?;
    let conflicts = decision_forum::constitution::dry_run_amendment(&corpus, &proposed)
        .map_err(|e| JsValue::from_str(&format!("Dry-run error: {e}")))?;
    to_js_value(&conflicts)
}

// ── TNC Enforcement ──────────────────────────────────────────────
//
// TncContext<'a> holds a borrowed &DecisionObject and cannot be deserialized
// directly.  Each binding takes:
//   - decision_json: &str — the DecisionObject (owned, deserialized locally)
//   - flags_json: &str    — untrusted JSON object carrying caller-asserted
//                           boolean precondition claims. The bridge parses this
//                           object for shape compatibility only; caller claims
//                           never satisfy TNC proof obligations.
//
// The TncContext is then constructed on the stack inside each function so the
// borrow checker is satisfied without requiring an unsafe transmute.

#[derive(serde::Deserialize)]
struct TncFlags {
    #[serde(default)]
    constitutional_hash_valid: bool,
    #[serde(default)]
    consent_verified: bool,
    #[serde(default)]
    identity_verified: bool,
    #[serde(default)]
    evidence_complete: bool,
    #[serde(default)]
    quorum_met: bool,
    #[serde(default)]
    human_gate_satisfied: bool,
    #[serde(default)]
    authority_chain_verified: bool,
    #[serde(default)]
    ai_ceilings_externally_verified: bool,
}

impl TncFlags {
    fn has_any_asserted_claim(&self) -> bool {
        self.constitutional_hash_valid
            || self.consent_verified
            || self.identity_verified
            || self.evidence_complete
            || self.quorum_met
            || self.human_gate_satisfied
            || self.authority_chain_verified
            || self.ai_ceilings_externally_verified
    }
}

fn parse_untrusted_tnc_flags(flags_json: &str) -> Result<TncFlags, JsValue> {
    let flags: TncFlags = from_json_str(flags_json)?;
    let _caller_asserted_proofs = flags.has_any_asserted_claim();
    Ok(flags)
}

fn build_tnc_ctx<'a>(
    decision: &'a decision_forum::decision_object::DecisionObject,
    _flags: &TncFlags,
) -> decision_forum::tnc_enforcer::TncContext<'a> {
    decision_forum::tnc_enforcer::TncContext {
        decision,
        constitutional_hash_valid: false,
        consent_verified: false,
        identity_verified: false,
        evidence_complete: false,
        quorum_met: false,
        human_gate_satisfied: false,
        authority_chain_verified: false,
        ai_ceilings_externally_verified: false,
    }
}

fn tnc_result(r: decision_forum::error::Result<()>) -> Result<JsValue, JsValue> {
    match r {
        Ok(()) => to_js_value(&serde_json::json!({"ok": true})),
        Err(e) => to_js_value(&serde_json::json!({"ok": false, "error": e.to_string()})),
    }
}

/// Enforce TNC-01: authority chain cryptographically verified.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_01(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_01(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-02: human gate satisfied.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_02(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_02(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-03: consent verified.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_03(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_03(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-04: identity verified.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_04(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_04(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-05: delegation expiry enforced.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_05(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_05(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-06: constitutional binding valid.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_06(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_06(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-07: quorum verified.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_07(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_07(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-08: terminal decisions immutable.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_08(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_08(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-09: AI delegation ceiling enforced.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_09(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_09(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce TNC-10: evidence bundle complete.
#[wasm_bindgen]
pub fn wasm_enforce_tnc_10(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    tnc_result(decision_forum::tnc_enforcer::enforce_tnc_10(
        &build_tnc_ctx(&decision, &flags),
    ))
}

/// Enforce all 10 TNCs — returns Ok or the first violation.
#[wasm_bindgen]
pub fn wasm_enforce_all_tnc(decision_json: &str, flags_json: &str) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    match decision_forum::tnc_enforcer::enforce_all(&build_tnc_ctx(&decision, &flags)) {
        Ok(()) => to_js_value(&serde_json::json!({"ok": true, "violations": []})),
        Err(e) => to_js_value(&serde_json::json!({"ok": false, "error": e.to_string()})),
    }
}

/// Collect all TNC violations without short-circuiting.
///
/// Returns `{violations: [...]}` — empty array means all TNCs pass.
#[wasm_bindgen]
pub fn wasm_collect_tnc_violations(
    decision_json: &str,
    flags_json: &str,
) -> Result<JsValue, JsValue> {
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let flags = parse_untrusted_tnc_flags(flags_json)?;
    let violations =
        decision_forum::tnc_enforcer::collect_violations(&build_tnc_ctx(&decision, &flags));
    let descriptions: Vec<String> = violations.iter().map(|e| e.to_string()).collect();
    to_js_value(&serde_json::json!({"violations": descriptions}))
}

// ── Human Gate ───────────────────────────────────────────────────

/// Enforce the human gate for a decision — Err if human approval is required
/// but not present in the vote set.
#[wasm_bindgen]
pub fn wasm_enforce_human_gate(policy_json: &str, decision_json: &str) -> Result<JsValue, JsValue> {
    let policy: decision_forum::human_gate::HumanGatePolicy = from_json_str(policy_json)?;
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    match decision_forum::human_gate::enforce_human_gate(&policy, &decision) {
        Ok(()) => to_js_value(&serde_json::json!({"ok": true})),
        Err(e) => to_js_value(&serde_json::json!({"ok": false, "error": e.to_string()})),
    }
}

/// Return true if the given decision class requires human approval under the policy.
#[wasm_bindgen]
pub fn wasm_requires_human_approval(policy_json: &str, class_json: &str) -> Result<bool, JsValue> {
    let policy: decision_forum::human_gate::HumanGatePolicy = from_json_str(policy_json)?;
    let class: decision_forum::decision_object::DecisionClass = from_json_str(class_json)?;
    Ok(decision_forum::human_gate::requires_human_approval(
        &policy, class,
    ))
}

/// Return true if the given decision class is within the AI delegation ceiling.
#[wasm_bindgen]
pub fn wasm_ai_within_ceiling(policy_json: &str, class_json: &str) -> Result<bool, JsValue> {
    let policy: decision_forum::human_gate::HumanGatePolicy = from_json_str(policy_json)?;
    let class: decision_forum::decision_object::DecisionClass = from_json_str(class_json)?;
    Ok(decision_forum::human_gate::ai_within_ceiling(
        &policy, class,
    ))
}

/// Return true if the given vote was cast by a human actor.
#[wasm_bindgen]
pub fn wasm_is_human_vote(vote_json: &str) -> Result<bool, JsValue> {
    let vote: decision_forum::decision_object::Vote = from_json_str(vote_json)?;
    Ok(decision_forum::human_gate::is_human_vote(&vote))
}

/// Return true if the given vote was cast by an AI agent.
#[wasm_bindgen]
pub fn wasm_is_ai_vote(vote_json: &str) -> Result<bool, JsValue> {
    let vote: decision_forum::decision_object::Vote = from_json_str(vote_json)?;
    Ok(decision_forum::human_gate::is_ai_vote(&vote))
}

// ── Quorum ───────────────────────────────────────────────────────

/// Check whether the quorum requirement for a decision is satisfied.
///
/// Returns `{status, total_votes, approve_count, approve_pct}` on Met,
/// or `{status, reason}` on NotMet / Degraded.
#[wasm_bindgen]
pub fn wasm_check_quorum(registry_json: &str, decision_json: &str) -> Result<JsValue, JsValue> {
    use decision_forum::quorum::QuorumCheckResult;

    let registry: decision_forum::quorum::QuorumRegistry = from_json_str(registry_json)?;
    let decision: decision_forum::decision_object::DecisionObject = from_json_str(decision_json)?;
    let result = decision_forum::quorum::check_quorum(&registry, &decision)
        .map_err(|e| JsValue::from_str(&format!("Quorum error: {e}")))?;

    // QuorumCheckResult doesn't implement Serialize — flatten manually.
    let json = match result {
        QuorumCheckResult::Met {
            total_votes,
            approve_count,
            approve_pct,
        } => serde_json::json!({
            "status": "Met",
            "total_votes": total_votes,
            "approve_count": approve_count,
            "approve_pct": approve_pct,
        }),
        QuorumCheckResult::NotMet { reason } => serde_json::json!({
            "status": "NotMet",
            "reason": reason,
        }),
        QuorumCheckResult::Degraded {
            reason,
            available,
            required,
        } => serde_json::json!({
            "status": "Degraded",
            "reason": reason,
            "available": available,
            "required": required,
        }),
    };
    to_js_value(&json)
}

/// Verify that enough eligible voters exist to reach quorum before voting opens.
#[wasm_bindgen]
pub fn wasm_verify_quorum_precondition(
    registry_json: &str,
    class_json: &str,
    eligible_voters: usize,
    eligible_human_voters: usize,
) -> Result<bool, JsValue> {
    let registry: decision_forum::quorum::QuorumRegistry = from_json_str(registry_json)?;
    let class: decision_forum::decision_object::DecisionClass = from_json_str(class_json)?;
    decision_forum::quorum::verify_quorum_precondition(
        &registry,
        class,
        eligible_voters,
        eligible_human_voters,
    )
    .map_err(|e| JsValue::from_str(&format!("Precondition error: {e}")))
}

// ── Emergency Protocol ───────────────────────────────────────────

/// Create an emergency action under the given policy.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
// Mirrors the emergency action provenance contract across the JS/Rust
// boundary without rebuilding IDs, HLC timestamps, or quarterly action history
// inside the bridge.
pub fn wasm_create_emergency_action(
    action_id: &str,
    action_type_json: &str,
    actor_did: &str,
    justification: &str,
    monetary_cap_cents: u64,
    evidence_hash_hex: &str,
    policy_json: &str,
    timestamp_ms: u64,
    timestamp_logical: u32,
    prior_actions_json: &str,
) -> Result<JsValue, JsValue> {
    let action_id = parse_uuid(action_id)?;
    let action_type: decision_forum::emergency::EmergencyActionType =
        from_json_str(action_type_json)?;
    let actor =
        exo_core::Did::new(actor_did).map_err(|e| JsValue::from_str(&format!("DID error: {e}")))?;
    let evidence_hash = parse_hash(evidence_hash_hex, "evidence hash")?;
    let policy: decision_forum::emergency::EmergencyPolicy = from_json_str(policy_json)?;
    let ts = exo_core::types::Timestamp::new(timestamp_ms, timestamp_logical);
    let prior_actions: Vec<decision_forum::emergency::EmergencyAction> = from_json_bounded_vec(
        prior_actions_json,
        "forum emergency actions",
        MAX_WASM_FORUM_EMERGENCY_ACTIONS,
    )?;

    let action = decision_forum::emergency::create_emergency_action(
        decision_forum::emergency::EmergencyActionInput {
            id: action_id,
            action_type,
            actor,
            justification: justification.into(),
            monetary_cap_cents,
            evidence_hash,
            created_at: ts,
        },
        &policy,
        &prior_actions,
    )
    .map_err(|e| JsValue::from_str(&format!("Emergency error: {e}")))?;
    to_js_value(&action)
}

/// Ratify an emergency action with a governance decision.
#[wasm_bindgen]
pub fn wasm_ratify_emergency(
    action_json: &str,
    decision_id: &str,
    timestamp_ms: u64,
) -> Result<JsValue, JsValue> {
    let mut action: decision_forum::emergency::EmergencyAction = from_json_str(action_json)?;
    let id: uuid::Uuid = decision_id
        .parse()
        .map_err(|e| JsValue::from_str(&format!("UUID error: {e}")))?;
    let ts = exo_core::types::Timestamp::new(timestamp_ms, 0);
    decision_forum::emergency::ratify_emergency(&mut action, id, ts)
        .map_err(|e| JsValue::from_str(&format!("Ratify error: {e}")))?;
    to_js_value(&action)
}

/// Check whether an emergency action's ratification window has expired.
/// Mutates `ratification_status` to `Expired` if so. Returns `true` if expired.
#[wasm_bindgen]
pub fn wasm_check_expiry(action_json: &str, now_ms: u64) -> Result<JsValue, JsValue> {
    let mut action: decision_forum::emergency::EmergencyAction = from_json_str(action_json)?;
    let now = exo_core::types::Timestamp::new(now_ms, 0);
    let expired = decision_forum::emergency::check_expiry(&mut action, &now);
    to_js_value(&serde_json::json!({"expired": expired, "action": action}))
}

/// Return true if the emergency action history requires a governance review
/// (e.g. frequency threshold exceeded under the policy).
#[wasm_bindgen]
pub fn wasm_needs_governance_review(
    actions_json: &str,
    policy_json: &str,
) -> Result<bool, JsValue> {
    let actions: Vec<decision_forum::emergency::EmergencyAction> = from_json_bounded_vec(
        actions_json,
        "forum emergency actions",
        MAX_WASM_FORUM_EMERGENCY_ACTIONS,
    )?;
    let policy: decision_forum::emergency::EmergencyPolicy = from_json_str(policy_json)?;
    Ok(decision_forum::emergency::needs_governance_review(
        &actions, &policy,
    ))
}

// ── Contestation ─────────────────────────────────────────────────

/// Move a challenge from Filed → UnderReview.
#[wasm_bindgen]
pub fn wasm_begin_review(challenge_json: &str) -> Result<JsValue, JsValue> {
    let mut challenge: decision_forum::contestation::ChallengeObject =
        from_json_str(challenge_json)?;
    decision_forum::contestation::begin_review(&mut challenge)
        .map_err(|e| JsValue::from_str(&format!("Review error: {e}")))?;
    to_js_value(&challenge)
}

/// Withdraw a challenge (Filed or UnderReview → Withdrawn).
#[wasm_bindgen]
pub fn wasm_withdraw_challenge(challenge_json: &str) -> Result<JsValue, JsValue> {
    let mut challenge: decision_forum::contestation::ChallengeObject =
        from_json_str(challenge_json)?;
    decision_forum::contestation::withdraw(&mut challenge)
        .map_err(|e| JsValue::from_str(&format!("Withdraw error: {e}")))?;
    to_js_value(&challenge)
}

/// Return true if the given decision is currently contested (has an active challenge).
#[wasm_bindgen]
pub fn wasm_is_contested(challenges_json: &str, decision_id: &str) -> Result<bool, JsValue> {
    let challenges: Vec<decision_forum::contestation::ChallengeObject> = from_json_bounded_vec(
        challenges_json,
        "forum challenges",
        MAX_WASM_FORUM_CHALLENGES,
    )?;
    let id: uuid::Uuid = decision_id
        .parse()
        .map_err(|e| JsValue::from_str(&format!("UUID error: {e}")))?;
    Ok(decision_forum::contestation::is_contested(&challenges, id))
}

// ── Accountability ───────────────────────────────────────────────

/// Move an accountability action from Proposed → DueProcess.
#[wasm_bindgen]
pub fn wasm_begin_due_process(action_json: &str) -> Result<JsValue, JsValue> {
    let mut action: decision_forum::accountability::AccountabilityAction =
        from_json_str(action_json)?;
    decision_forum::accountability::begin_due_process(&mut action)
        .map_err(|e| JsValue::from_str(&format!("Due-process error: {e}")))?;
    to_js_value(&action)
}

/// Enact an accountability action after due process completes.
#[wasm_bindgen]
pub fn wasm_enact_accountability(
    action_json: &str,
    decision_id: &str,
    timestamp_ms: u64,
) -> Result<JsValue, JsValue> {
    let mut action: decision_forum::accountability::AccountabilityAction =
        from_json_str(action_json)?;
    let id: uuid::Uuid = decision_id
        .parse()
        .map_err(|e| JsValue::from_str(&format!("UUID error: {e}")))?;
    let ts = exo_core::types::Timestamp::new(timestamp_ms, 0);
    decision_forum::accountability::enact(&mut action, id, ts)
        .map_err(|e| JsValue::from_str(&format!("Enact error: {e}")))?;
    to_js_value(&action)
}

/// Reverse an enacted accountability action.
#[wasm_bindgen]
pub fn wasm_reverse_accountability(action_json: &str) -> Result<JsValue, JsValue> {
    let mut action: decision_forum::accountability::AccountabilityAction =
        from_json_str(action_json)?;
    decision_forum::accountability::reverse(&mut action)
        .map_err(|e| JsValue::from_str(&format!("Reverse error: {e}")))?;
    to_js_value(&action)
}

/// Return true if the due-process deadline has passed for an action.
#[wasm_bindgen]
pub fn wasm_is_due_process_expired(action_json: &str, now_ms: u64) -> Result<bool, JsValue> {
    let action: decision_forum::accountability::AccountabilityAction = from_json_str(action_json)?;
    let now = exo_core::types::Timestamp::new(now_ms, 0);
    Ok(decision_forum::accountability::is_due_process_expired(
        &action, &now,
    ))
}

// ── Forum Authority ──────────────────────────────────────────────

/// Legacy ForumAuthority verifier.
///
/// This export fails closed because authenticity requires a trusted root
/// public key supplied from the caller's trust boundary. Use
/// `wasm_verify_forum_authority_with_key` for cryptographic verification.
#[wasm_bindgen]
pub fn wasm_verify_forum_authority(authority_json: &str) -> Result<JsValue, JsValue> {
    let authority: decision_forum::authority::ForumAuthority = from_json_str(authority_json)?;
    match decision_forum::authority::verify_forum_authority(&authority) {
        Ok(()) => to_js_value(&serde_json::json!({"ok": true})),
        Err(e) => to_js_value(&serde_json::json!({"ok": false, "error": e.to_string()})),
    }
}

/// Verify the integrity and authenticity of a ForumAuthority object.
#[wasm_bindgen]
pub fn wasm_verify_forum_authority_with_key(
    authority_json: &str,
    root_public_key_hex: &str,
) -> Result<JsValue, JsValue> {
    let authority: decision_forum::authority::ForumAuthority = from_json_str(authority_json)?;
    let root_public_key = parse_public_key_hex(root_public_key_hex)?;
    match decision_forum::authority::verify_forum_authority_with_key(&authority, &root_public_key) {
        Ok(()) => to_js_value(&serde_json::json!({"ok": true})),
        Err(e) => to_js_value(&serde_json::json!({"ok": false, "error": e.to_string()})),
    }
}

fn parse_uuid(value: &str) -> Result<uuid::Uuid, JsValue> {
    value
        .parse()
        .map_err(|e| JsValue::from_str(&format!("UUID error: {e}")))
}

fn parse_hash(value: &str, label: &str) -> Result<exo_core::Hash256, JsValue> {
    let bytes = hex::decode(value).map_err(|e| JsValue::from_str(&format!("hex: {e}")))?;
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| JsValue::from_str(&format!("{label} must be 32 bytes")))?;
    Ok(exo_core::Hash256::from_bytes(arr))
}

fn parse_public_key_hex(public_key_hex: &str) -> Result<exo_core::PublicKey, JsValue> {
    let bytes = hex::decode(public_key_hex).map_err(|e| JsValue::from_str(&format!("hex: {e}")))?;
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| JsValue::from_str("public key must be 32 bytes"))?;
    Ok(exo_core::PublicKey::from_bytes(arr))
}

fn ensure_constitution_bytes(len: usize) -> Result<(), JsValue> {
    if len > MAX_WASM_FORUM_CONSTITUTION_BYTES {
        return Err(JsValue::from_str(
            "constitution exceeds maximum WASM decision-forum size",
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use decision_forum::decision_object::{
        ActorKind, AuthorityLink, DecisionClass, DecisionObject, DecisionObjectInput,
    };
    use exo_core::{Hash256, Timestamp, types::Did};

    #[test]
    fn decision_forum_bridge_does_not_synthesize_clock_metadata() {
        let source = include_str!("decision_forum_bindings.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(
            !production.contains("HybridClock::new()"),
            "decision-forum WASM exports must require caller-supplied HLC metadata"
        );
        assert!(
            !production.contains("Uuid::new_v4"),
            "decision-forum WASM exports must require caller-supplied UUID metadata"
        );
    }

    #[test]
    fn wasm_tnc_adapter_does_not_trust_caller_supplied_flags() {
        let mut decision = DecisionObject::new(DecisionObjectInput {
            id: uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000901").expect("valid UUID"),
            title: "Caller-supplied TNC flags".into(),
            class: DecisionClass::Routine,
            constitutional_hash: Hash256::from_bytes([1_u8; 32]),
            created_at: Timestamp::new(1_700_000_000_000, 0),
        })
        .expect("valid decision");
        decision
            .add_authority_link(AuthorityLink {
                actor_did: Did::new("did:exo:authority-root").expect("valid DID"),
                actor_kind: ActorKind::Human,
                delegation_hash: Hash256::from_bytes([2_u8; 32]),
                timestamp: Timestamp::new(1_700_000_000_001, 0),
            })
            .expect("valid authority link");

        let caller_flags = super::TncFlags {
            constitutional_hash_valid: true,
            consent_verified: true,
            identity_verified: true,
            evidence_complete: true,
            quorum_met: true,
            human_gate_satisfied: true,
            authority_chain_verified: true,
            ai_ceilings_externally_verified: true,
        };

        let ctx = super::build_tnc_ctx(&decision, &caller_flags);
        let err = decision_forum::tnc_enforcer::enforce_all(&ctx)
            .expect_err("caller-provided WASM flags cannot satisfy TNC proof obligations");
        assert!(
            err.to_string().contains("authority chain not verified"),
            "unexpected TNC rejection: {err}"
        );
    }

    #[test]
    fn forum_authority_wasm_verifier_requires_trusted_public_key() {
        let source = include_str!("decision_forum_bindings.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(
            production.contains("wasm_verify_forum_authority_with_key"),
            "WASM authority verification must expose a trusted-public-key verification path"
        );
        assert!(
            production.contains("verify_forum_authority_with_key"),
            "WASM authority verification must call the cryptographic core verifier"
        );
    }

    #[test]
    fn wasm_constitution_exports_reject_caller_supplied_signer_keys() {
        let source = include_str!("decision_forum_bindings.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        for export_name in ["wasm_ratify_constitution", "wasm_amend_constitution"] {
            let body = production
                .split(&format!("pub fn {export_name}"))
                .nth(1)
                .unwrap_or_else(|| panic!("{export_name} export must exist"))
                .split("///")
                .next()
                .expect("export body must be bounded by next doc comment");
            assert!(
                body.contains("trusted core runtime adapter"),
                "{export_name} must fail closed at the public WASM boundary"
            );
            assert!(
                !body.contains("parse_public_key_pairs(public_keys_json)"),
                "{export_name} must not parse caller-supplied signer keys"
            );
            assert!(
                !body.contains("public_keys.keys().cloned().collect()"),
                "{export_name} must not derive eligible signers from caller-supplied keys"
            );
        }
    }

    #[test]
    fn wasm_emergency_create_requires_bounded_prior_action_history() {
        let source = include_str!("decision_forum_bindings.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");
        let body = production
            .split("pub fn wasm_create_emergency_action")
            .nth(1)
            .expect("emergency create export exists")
            .split("/// Ratify an emergency action")
            .next()
            .expect("emergency create export body is bounded by ratify docs");

        assert!(
            body.contains("prior_actions_json: &str"),
            "WASM emergency creation must require caller-supplied prior action history"
        );
        assert!(
            body.contains("from_json_bounded_vec(")
                && body.contains("prior_actions_json")
                && body.contains("MAX_WASM_FORUM_EMERGENCY_ACTIONS"),
            "WASM emergency creation must parse bounded prior action history"
        );
        assert!(
            body.contains("&prior_actions"),
            "WASM emergency creation must pass prior action history into the core constructor"
        );
    }
}