newton-core 0.7.1

newton protocol core sdk
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
use uuid::Uuid;

use std::{str::FromStr, sync::Arc};

use crate::{
    error::RegoError,
    evaluate,
    mock_newton_policy_client::MockNewtonPolicyClient,
    newton_policy::{INewtonPolicy, NewtonPolicy},
    newton_prover_task_manager::{
        INewtonPolicyClient::PolicySpec,
        INewtonProverTaskManager::{self, Task},
        NewtonMessage::{self, Intent},
    },
    rego::validate_schema,
    PolicyId, TaskId,
};
use alloy::{
    dyn_abi::DynSolValue,
    primitives::{keccak256, Address, Bytes, ChainId, B256, U256},
    sol_types::SolValue,
};
use cid::Cid;

use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;

// Evaluation kernel moved to `crate::eval` so the SP1 rego challenge circuit can
// share it (the kernel compiles in zkVM builds; this module does not). Re-exported
// here so existing `crate::common::task::{...}` / `crate::common::{...}` importers
// resolve unchanged.
pub use crate::eval::{decode_calldata, parse_intent, serialize_sol_value, ParsedIntent};

/// Task request
///
/// Off-chain task creation request. Operators independently resolve the policy set
/// and fetch policy inputs. The aggregator handles numeric field variance via
/// median-based consensus.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskRequest {
    /// Task ID
    pub task_id: TaskId,
    /// Intent
    pub intent: NewtonMessage::Intent,
    /// Intent signature
    pub intent_signature: Option<Bytes>,
    /// Policy client address
    pub policy_client: Address,
    /// Policy ID
    pub policy_id: B256,
    /// The client's ordered policy set as of task creation. Frozen here so response-time
    /// validation never re-reads the client — reconfiguring it mid-flight cannot change
    /// what an in-flight task means.
    pub policies: Vec<PolicySpec>,
    /// The client's policy revision as of task creation.
    pub policy_revision: u64,
    /// WASM args (one per policy, positionally aligned with `policies`). Operators use
    /// this to generate policyTaskData; a policy's `_newton` directives, if any, ride
    /// inside its own entry rather than a task-wide blob.
    pub wasm_args: Vec<Bytes>,
    /// Quorum numbers
    pub quorum_numbers: Vec<u8>,
    /// Quorum threshold percentage
    pub quorum_threshold_percentage: u32,
    /// Task created block
    pub task_created_block: u64,
    /// timestamp marking the offchain ingestion of the task
    pub initialization_timestamp: u64,
    /// Optional IPFS CID of a TLSNotary presentation proof for zkTLS verification.
    ///
    /// This field is off-chain only — it is NOT carried into the on-chain `Task`
    /// struct (dropped by the `From<TaskRequest> for Task` conversion). The gateway
    /// persists it in the off-chain task metadata and also injects the same CID into
    /// `wasm_args` so operators can fetch and verify the proof from IPFS.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(alias = "proofCid")]
    pub proof_cid: Option<String>,
}

impl From<TaskRequest> for Task {
    fn from(task_request: TaskRequest) -> Self {
        Self {
            taskId: task_request.task_id,
            intent: task_request.intent,
            intentSignature: task_request.intent_signature.unwrap_or_default(),
            policyClient: task_request.policy_client,
            policyId: task_request.policy_id,
            policyRevision: task_request.policy_revision,
            policies: task_request.policies,
            taskCreatedBlock: task_request.task_created_block as u32,
            wasmArgs: task_request.wasm_args,
            quorumNumbers: task_request.quorum_numbers.into(),
            quorumThresholdPercentage: task_request.quorum_threshold_percentage,
            initializationTimestamp: U256::from(task_request.initialization_timestamp),
        }
    }
}

/// Write serialized data to buffer
/// # Arguments
/// * `buffer` - The buffer to encode to
/// * `data` - The data to encode
pub fn write_serialized(buffer: &mut Vec<u8>, data: &[u8]) -> Result<(), bincode::error::EncodeError> {
    let mut input: Vec<u8> = Vec::new();
    bincode::encode_into_slice(data, &mut input, bincode::config::standard())?;
    buffer.extend_from_slice(&input);
    Ok(())
}

/// Create a new task id using a uuid
pub fn task_id(seed: Option<&str>) -> TaskId {
    let uuid = if let Some(seed) = seed {
        Uuid::from_str(seed).unwrap_or_else(|_| Uuid::new_v4())
    } else {
        Uuid::new_v4()
    };
    let hash = keccak256(uuid.as_bytes());
    TaskId::from(hash)
}

/// Merges multiple JSON values into a single JSON object.
///
/// # Merge Behavior
/// - Only JSON objects are merged; non-object values are silently ignored
/// - Keys use last-write-wins semantics: later values overwrite earlier ones
///
/// # Returns
/// A single merged JSON object.
pub fn merge_jsons(jsons: Vec<serde_json::Value>) -> serde_json::Value {
    let merged = jsons.iter().fold(serde_json::Map::new(), |mut merged, data| {
        if let serde_json::Value::Object(map) = data {
            merged.extend(map.iter().map(|(k, v)| (k.clone(), v.clone())));
        }
        merged
    });
    serde_json::Value::Object(merged)
}

/// Merge multiple secrets JSON schemas into a single schema.
///
/// Merge rules:
/// - `properties`: union keys (first definition wins for duplicates)
/// - `required`: union
/// - `type`: `"object"`
/// - `additionalProperties`: dropped from the merged output (a merged schema spans several
///   policies, so no single policy's strictness carries over)
///
/// Any schema that is valid per `regorus::Schema` is considered valid here. We only special-case
/// a small subset of fields (`properties`/`required`) for merging; all other schema keywords are
/// treated as opaque and do not affect the merge result.
///
/// Invalid schema docs are ignored during merging. Concretely, a schema doc is skipped if:
/// - the schema root is not a JSON object
/// - `properties` is present and not a JSON object (and not `null`)
/// - `required` is present and not a JSON array (and not `null`)
/// - `required` is a JSON array but contains any non-string items
///
/// Rationale:
/// - Secrets schemas are external inputs (IPFS) and may drift or be malformed; skipping bad docs
///   prevents one broken PolicyData schema from blocking all clients that use the policy.
/// - The merged schema never rejects unknown keys; callers that need strict secrets validation
///   must validate against the per-PolicyData schema directly.
///
/// `schema_docs` is `(cid, schema_json)`; `cid` is included to aid debugging when extending this
/// logic or logging higher up the stack.
pub fn merge_secrets_schemas(schema_docs: Vec<(String, serde_json::Value)>) -> eyre::Result<serde_json::Value> {
    let mut merged_properties: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
    let mut merged_required: BTreeSet<String> = BTreeSet::new();

    for (cid, schema_json) in schema_docs {
        let Some(schema_obj) = schema_json.as_object() else {
            // Ignore invalid schema docs (root must be an object).
            continue;
        };

        // Merge properties
        if let Some(props_val) = schema_obj.get("properties") {
            if let Some(props_obj) = props_val.as_object() {
                for (k, v) in props_obj.iter() {
                    // First definition wins
                    if !merged_properties.contains_key(k) {
                        merged_properties.insert(k.clone(), v.clone());
                    }
                }
            } else if !props_val.is_null() {
                // Ignore invalid schema docs (`properties` must be an object if present).
                continue;
            }
        }

        // Merge required
        if let Some(req_val) = schema_obj.get("required") {
            if let Some(req_arr) = req_val.as_array() {
                let mut local_required: Vec<String> = Vec::with_capacity(req_arr.len());
                for item in req_arr {
                    let Some(key) = item.as_str() else {
                        // Ignore invalid schema docs (`required` must be an array of strings).
                        local_required.clear();
                        break;
                    };
                    local_required.push(key.to_string());
                }
                if local_required.is_empty() && !req_arr.is_empty() {
                    continue;
                }
                for k in local_required {
                    merged_required.insert(k);
                }
            } else if !req_val.is_null() {
                // Ignore invalid schema docs (`required` must be an array if present).
                continue;
            }
        }
    }

    // Build final merged schema
    let mut merged = serde_json::Map::new();
    merged.insert("type".to_string(), serde_json::Value::String("object".to_string()));
    merged.insert("properties".to_string(), serde_json::Value::Object(merged_properties));

    if !merged_required.is_empty() {
        merged.insert(
            "required".to_string(),
            serde_json::Value::Array(merged_required.into_iter().map(serde_json::Value::String).collect()),
        );
    }

    Ok(serde_json::Value::Object(merged))
}

/// RPC module for policy-set task evaluation
pub mod rpc {
    #![cfg(feature = "rpc")]
    use crate::{
        common::{
            intent::ParsedIntent,
            policy_runtime::PolicyRuntime,
            policy_set::{
                check_policy_data_bounds_with_cap, ResolvedPolicySet, MAX_POLICIES, MAX_RESPONSE_POLICY_BYTES,
            },
        },
        error::RegoError,
        evaluate,
        newton_policy::{INewtonPolicy, NewtonPolicy},
        newton_prover_task_manager::NewtonMessage,
        rego::validate_schema,
    };
    use alloy::{
        primitives::{keccak256, Address, Bytes, B256},
        providers::Provider,
    };
    use newton_rpc_provider::get_provider;
    use regorus::extensions::PolicyDomainData;
    use serde::{Deserialize, Serialize};
    use std::str::FromStr;

    /// Evaluation result for one policy
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct PolicyEvaluationResult {
        /// policy index in set
        pub policy_index: usize,
        /// policy contract address
        pub policy: Address,
        /// exact rego module bytes evaluated
        pub rego: Bytes,
        /// entrypoint
        pub entrypoint: String,
        /// policy params
        pub params: serde_json::Value,
        /// policy input (oracle data)
        pub policy_input: serde_json::Value,
        /// evaluation result
        pub result: regorus::Value,
        /// allowed flag
        pub allowed: bool,
        /// expiration window in blocks
        pub expire_after: u32,
    }

    /// Policy set evaluation result
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct PolicySetEvaluationResult {
        /// parsed intent
        pub parsed_intent: ParsedIntent,
        /// policy id
        pub policy_id: B256,
        /// per-policy results
        pub policies: Vec<PolicyEvaluationResult>,
        /// composite allowed verdict (AND over all policies)
        pub allowed: bool,
    }

    /// Parse intent and evaluate against a policy set
    ///
    /// # Arguments
    ///
    /// * `intent` - The task intent
    /// * `policy_client` - Policy client address
    /// * `oracle_outputs` - Oracle outputs (one per policy, positionally aligned)
    /// * `rpc_url` - RPC URL for chain queries
    /// * `fetcher` - Object fetcher for CID resolution
    /// * `additional_data` - Transient data merged at root (e.g. zkTLS proof)
    pub async fn parse_and_evaluate_policy_set(
        intent: &NewtonMessage::Intent,
        policy_client: Address,
        oracle_outputs: &[Bytes],
        rpc_url: &str,
        fetcher: &dyn ObjectFetcher,
        additional_data: Option<serde_json::Value>,
    ) -> Result<PolicySetEvaluationResult, RegoError> {
        tracing::info!("evaluating policy set for policy client {}", policy_client);

        let policy_set = resolve_policy_set(policy_client, rpc_url, fetcher).await?;

        evaluate_resolved_policy_set(
            serde_json::json!(intent),
            &policy_set,
            oracle_outputs,
            &[],
            additional_data,
            newton_rego_kernel::ErrorDisposition::Propagate,
        )
    }

    /// Evaluate a resolved policy set with pre-fetched oracle outputs (network-free path for enclave).
    ///
    /// # Arguments
    ///
    /// * `intent` - User intent JSON
    /// * `policy_set` - Resolved policy set with all artifacts
    /// * `oracle_outputs` - Oracle outputs (positionally aligned with policy_set.policies)
    /// * `domain_data` - Identity and confidential data, shared by every policy
    /// * `additional_data` - Transient data merged at root (e.g. zkTLS proof)
    /// * `on_error` - Error disposition (Propagate for simulation, FailClosed for challenger/circuit)
    ///
    /// # Returns
    ///
    /// Policy set evaluation result with per-policy verdicts and fail-closed AND composite verdict.
    ///
    /// # Errors
    ///
    /// Returns error if oracle_outputs length does not match policy_set.policies length.
    pub fn evaluate_resolved_policy_set(
        intent: serde_json::Value,
        policy_set: &ResolvedPolicySet,
        oracle_outputs: &[Bytes],
        domain_data: &[Box<dyn regorus::extensions::PolicyDomainData>],
        additional_data: Option<serde_json::Value>,
        on_error: newton_rego_kernel::ErrorDisposition,
    ) -> Result<PolicySetEvaluationResult, RegoError> {
        use crate::common::parse_intent;

        // A zero-policy set is unrepresentable in the protocol, and the length check
        // below is satisfied by 0 == 0 — reject it here so no empty journal can be produced.
        if policy_set.policies.is_empty() {
            return Err(RegoError::FailedToEvaluateTask(
                "policy set cannot be empty".to_string(),
            ));
        }
        if policy_set.policies.len() != oracle_outputs.len() {
            return Err(RegoError::FailedToEvaluateTask(format!(
                "oracle output count mismatch: policy set has {} policies, got {} oracle outputs",
                policy_set.policies.len(),
                oracle_outputs.len()
            )));
        }

        // Response-side oracle bytes only; the gateway bounds Task.wasmArgs at ingress. Rego and
        // oracle output are response-path fields, so they answer to the response budget — checking
        // them against the admission cap would reject sets the chain settles.
        check_policy_data_bounds_with_cap(
            policy_set
                .policies
                .iter()
                .zip(oracle_outputs)
                .enumerate()
                .flat_map(|(i, (policy, output))| {
                    [
                        (i, "params", policy.policy_config.policyParams.len()),
                        (i, "rego", policy.rego.len()),
                        (i, "output", output.len()),
                    ]
                }),
            MAX_RESPONSE_POLICY_BYTES,
        )
        .map_err(|e| RegoError::FailedToEvaluateTask(e.to_string()))?;

        let parsed_intent = parse_intent(intent).map_err(|e| RegoError::FailedToParseIntent(e.to_string()))?;
        let parsed_intent_str: String = parsed_intent.clone().into();

        let evals: Vec<newton_rego_kernel::PolicyEvaluation<'_>> = policy_set
            .policies
            .iter()
            .zip(oracle_outputs.iter())
            .map(|(p, output)| newton_rego_kernel::PolicyEvaluation {
                rego: &p.rego,
                entrypoint: &p.entrypoint,
                params: &p.policy_config.policyParams,
                oracle_output: output,
            })
            .collect();

        let verdict = newton_rego_kernel::evaluate_policy_set(
            &evals,
            &parsed_intent_str,
            domain_data,
            additional_data.as_ref(),
            on_error,
        )
        .map_err(|e| RegoError::FailedToEvaluateTask(e.to_string()))?;

        // kernel owns the AND fold and MAX_POLICIES bound, so this is the only evaluator in the tree
        let policy_results: Vec<PolicyEvaluationResult> = verdict
            .policies
            .into_iter()
            .enumerate()
            .zip(policy_set.policies.iter())
            .map(|((i, v), p)| PolicyEvaluationResult {
                policy_index: i,
                policy: p.policy_address,
                rego: p.rego.clone(),
                entrypoint: p.entrypoint.clone(),
                params: v.params,
                policy_input: v.oracle_output,
                result: v.value,
                allowed: v.allowed,
                expire_after: p.policy_config.expireAfter,
            })
            .collect();

        Ok(PolicySetEvaluationResult {
            parsed_intent,
            policy_id: policy_set.policy_id,
            policies: policy_results,
            allowed: verdict.allowed,
        })
    }

    /// Fetch content-addressed objects (WASM, Rego, schemas) by CID.
    ///
    /// Implementations MUST verify the CID multihash against the returned bytes.
    #[async_trait::async_trait]
    pub trait ObjectFetcher: Send + Sync {
        /// Resolve `cid` to bytes after verifying the CID multihash.
        async fn get_object(&self, cid: &str) -> eyre::Result<Vec<u8>>;
    }

    /// Resolve a policy set from chain state and IPFS artifacts
    pub async fn resolve_policy_set(
        policy_client: Address,
        rpc_url: &str,
        fetcher: &dyn ObjectFetcher,
    ) -> Result<ResolvedPolicySet, RegoError> {
        let provider = get_provider(rpc_url);

        let policy_client_contract =
            crate::newton_policy_client::NewtonPolicyClient::new(policy_client, provider.clone());

        // A single atomic call: three independent eth_calls racing against `latest` can
        // straddle a `setPolicies` landing mid-flight and return policyId, revision and
        // policies from different revisions. getPolicySetSnapshot() reads all three under
        // one EVM state view, so there is nothing left to straddle.
        let snapshot = policy_client_contract
            .getPolicySetSnapshot()
            .call()
            .await
            .map_err(|e| RegoError::FailedToGetPolicies(e.to_string()))?;
        let policy_id = snapshot._0;
        let revision = snapshot._1;
        let policy_specs = snapshot._2;

        if policy_specs.is_empty() {
            return Err(RegoError::FailedToGetPolicies("policy set cannot be empty".to_string()));
        }
        if policy_specs.len() > MAX_POLICIES {
            return Err(RegoError::FailedToGetPolicies(format!(
                "policy set exceeds MAX_POLICIES ({}): got {}",
                MAX_POLICIES,
                policy_specs.len()
            )));
        }

        let (chain_id, current_block) = tokio::try_join!(
            async {
                provider
                    .get_chain_id()
                    .await
                    .map_err(|e| format!("failed to get chain ID: {e}"))
            },
            async {
                provider
                    .get_block_number()
                    .await
                    .map_err(|e| format!("failed to read chain head: {e}"))
            },
        )
        .map_err(RegoError::FailedToGetPolicyId)?;
        let current_block = current_block as u32;

        let policies = futures_util::future::try_join_all(policy_specs.iter().map(|policy_spec| {
            resolve_policy(
                policy_client,
                policy_id,
                chain_id,
                current_block,
                policy_spec.policy,
                &policy_spec.config.policyParams,
                policy_spec.config.expireAfter,
                rpc_url,
                fetcher,
            )
        }))
        .await?;

        let policy_set = ResolvedPolicySet {
            policy_client,
            policy_id,
            revision,
            policies,
        };

        policy_set
            .verify_policy_id(chain_id)
            .map_err(|e| RegoError::FailedToGetPolicyId(format!("policy ID verification failed: {}", e)))?;

        // `rego` is a response-path field, so the response budget governs; the admission cap
        // applies to params + oracle inputs and is enforced at the gateway and on-chain.
        check_policy_data_bounds_with_cap(
            policy_set.policies.iter().enumerate().flat_map(|(i, p)| {
                [
                    (i, "params", p.policy_config.policyParams.len()),
                    (i, "rego", p.rego.len()),
                ]
            }),
            MAX_RESPONSE_POLICY_BYTES,
        )
        .map_err(|e| RegoError::FailedToGetPolicies(e.to_string()))?;

        Ok(policy_set)
    }

    /// Resolve the policy set a task froze at creation, rather than the client's live set.
    ///
    /// Task semantics are immutable across client reconfiguration, so replay MUST resolve the
    /// snapshot the task committed to. Recomputing policyId over the snapshot and comparing it
    /// to the task's own policyId proves the snapshot is exactly the set the task authorized.
    pub async fn resolve_policy_set_snapshot(
        policy_client: Address,
        policy_id: B256,
        revision: u64,
        specs: &[crate::common::types::PolicySpec],
        rpc_url: &str,
        fetcher: &dyn ObjectFetcher,
    ) -> Result<ResolvedPolicySet, RegoError> {
        if specs.is_empty() {
            return Err(RegoError::FailedToGetPolicies("policy set cannot be empty".to_string()));
        }
        if specs.len() > MAX_POLICIES {
            return Err(RegoError::FailedToGetPolicies(format!(
                "policy set exceeds MAX_POLICIES ({}): got {}",
                MAX_POLICIES,
                specs.len()
            )));
        }

        let provider = get_provider(rpc_url);
        let (chain_id, current_block) = tokio::try_join!(
            async {
                provider
                    .get_chain_id()
                    .await
                    .map_err(|e| format!("failed to get chain ID: {e}"))
            },
            async {
                provider
                    .get_block_number()
                    .await
                    .map_err(|e| format!("failed to read chain head: {e}"))
            },
        )
        .map_err(RegoError::FailedToGetPolicyId)?;
        let current_block = current_block as u32;

        let policies = futures_util::future::try_join_all(specs.iter().map(|spec| {
            resolve_policy(
                policy_client,
                policy_id,
                chain_id,
                current_block,
                spec.policy,
                &spec.config.policy_params,
                spec.config.expire_after,
                rpc_url,
                fetcher,
            )
        }))
        .await?;

        let policy_set = ResolvedPolicySet {
            policy_client,
            policy_id,
            revision,
            policies,
        };

        policy_set
            .verify_policy_id(chain_id)
            .map_err(|e| RegoError::FailedToGetPolicyId(format!("policy ID verification failed: {}", e)))?;

        // `rego` is a response-path field, so the response budget governs; the admission cap
        // applies to params + oracle inputs and is enforced at the gateway and on-chain.
        check_policy_data_bounds_with_cap(
            policy_set.policies.iter().enumerate().flat_map(|(i, p)| {
                [
                    (i, "params", p.policy_config.policyParams.len()),
                    (i, "rego", p.rego.len()),
                ]
            }),
            MAX_RESPONSE_POLICY_BYTES,
        )
        .map_err(|e| RegoError::FailedToGetPolicies(e.to_string()))?;

        Ok(policy_set)
    }

    /// Resolve a single policy's on-chain declaration, its Rego module, and its at-most-one
    /// oracle child (`<= 1` is enforced on-chain at `setPolicies`; composition rejects
    /// multi-oracle policies there, not here).
    #[allow(clippy::too_many_arguments)]
    async fn resolve_policy(
        policy_client: Address,
        set_policy_id: B256,
        chain_id: u64,
        current_block: u32,
        policy_address: Address,
        policy_params: &Bytes,
        expire_after: u32,
        rpc_url: &str,
        fetcher: &dyn ObjectFetcher,
    ) -> Result<PolicyRuntime, RegoError> {
        let provider = get_provider(rpc_url);
        let policy_contract = NewtonPolicy::new(policy_address, provider.clone());

        let (policy_cid, entrypoint, schema_cid, policy_code_hash, wasm_cid, secrets_schema_cid) = tokio::try_join!(
            async {
                policy_contract
                    .getPolicyCid()
                    .call()
                    .await
                    .map_err(|e| RegoError::FailedToGetArtifact(e.to_string()))
            },
            async {
                policy_contract
                    .getEntrypoint()
                    .call()
                    .await
                    .map_err(|e| RegoError::FailedToGetPolicyEntrypoint(e.to_string()))
            },
            async {
                policy_contract
                    .getSchemaCid()
                    .call()
                    .await
                    .map_err(|e| RegoError::FailedToGetPolicySchemaCid(e.to_string()))
            },
            async {
                policy_contract
                    .getPolicyCodeHash()
                    .call()
                    .await
                    .map_err(|e| RegoError::FailedToGetArtifact(e.to_string()))
            },
            async {
                policy_contract
                    .getWasmCid()
                    .call()
                    .await
                    .map_err(|e| RegoError::FailedToGetArtifact(e.to_string()))
            },
            async {
                policy_contract
                    .getSecretsSchemaCid()
                    .call()
                    .await
                    .map_err(|e| RegoError::FailedToGetArtifact(e.to_string()))
            },
        )?;

        let rego_bytes = fetcher
            .get_object(&policy_cid)
            .await
            .map_err(|e| RegoError::FailedToFetchRego(e.to_string()))?;

        // The CID binds bytes to their own multihash; policyCodeHash binds them to the policy
        // contract. ChallengeVerifier re-derives keccak256 over the response's rego bytes, so
        // evaluating unbound bytes yields a response no challenge can ever settle.
        let computed = keccak256(&rego_bytes);
        if computed != policy_code_hash {
            return Err(RegoError::RegoCodeHashMismatch {
                policy: policy_address.to_string(),
                expected: policy_code_hash.to_string(),
                computed: computed.to_string(),
            });
        }

        let schema = validate_policy_params(policy_address, policy_params, &schema_cid, fetcher).await?;

        Ok(PolicyRuntime {
            chain_id,
            policy_client,
            policy_id: set_policy_id,
            policy_address,
            policy_config: INewtonPolicy::PolicyConfig {
                policyParams: policy_params.clone(),
                expireAfter: expire_after,
            },
            entrypoint,
            schema,
            policy_cid,
            policy_code_hash,
            current_block,
            expire_block: current_block.saturating_add(expire_after),
            wasm_cid,
            secrets_schema_cid,
            rego: Bytes::from(rego_bytes),
        })
    }

    /// Check one policy's configured params against the schema its artifact declares.
    ///
    /// The params are client-supplied and the schema is the policy author's declared input
    /// contract; nothing else in the pipeline compares them, so a set that would evaluate to a
    /// decision the author never specified is rejected here — before admission, simulation and
    /// operator replay, all of which resolve through this path.
    ///
    /// Empty params are the canonical "no configuration" value and are validated as `{}`, so a
    /// schema with required properties still rejects them. Non-empty params that are not JSON
    /// are rejected rather than degraded, which is what the evaluation kernel would otherwise do.
    ///
    /// Returns the fetched schema (or `Value::Null` if the policy declares none) so the
    /// caller can carry it into `PolicyRuntime` without a second IPFS fetch.
    async fn validate_policy_params(
        policy_address: Address,
        params: &Bytes,
        schema_cid: &str,
        fetcher: &dyn ObjectFetcher,
    ) -> Result<serde_json::Value, RegoError> {
        if schema_cid.is_empty() {
            return Ok(serde_json::Value::Null);
        }

        let params_json = if params.is_empty() {
            serde_json::json!({})
        } else {
            let text = std::str::from_utf8(params).map_err(|e| {
                RegoError::FailedToValidateParamsSchema(format!(
                    "policy {policy_address} params are not valid UTF-8: {e}"
                ))
            })?;
            serde_json::from_str(text).map_err(|e| {
                RegoError::FailedToValidateParamsSchema(format!(
                    "policy {policy_address} params are not valid JSON: {e}"
                ))
            })?
        };

        let schema = load_policy_schema(schema_cid, fetcher).await?;
        validate_schema(schema.clone(), params_json)
            .map_err(|e| RegoError::FailedToValidateParamsSchema(format!("policy {policy_address}: {e}")))?;
        Ok(schema)
    }

    /// Fetch the policy schema JSON and parse it into a `serde_json::Value`.
    async fn load_policy_schema(schema_cid: &str, fetcher: &dyn ObjectFetcher) -> Result<serde_json::Value, RegoError> {
        let bytes = fetcher
            .get_object(schema_cid)
            .await
            .map_err(|e| RegoError::FailedToFetchPolicySchemaJson(e.to_string()))?;
        let schema_text =
            String::from_utf8(bytes).map_err(|e| RegoError::FailedToDecodePolicySchemaJson(e.to_string()))?;

        serde_json::from_str(&schema_text).map_err(|e| RegoError::FailedToDecodePolicySchemaJson(e.to_string()))
    }

    #[cfg(test)]
    mod params_schema_tests {
        use super::*;

        const SCHEMA_CID: &str = "schema";

        struct StaticFetcher(&'static str);

        #[async_trait::async_trait]
        impl ObjectFetcher for StaticFetcher {
            async fn get_object(&self, _cid: &str) -> eyre::Result<Vec<u8>> {
                Ok(self.0.as_bytes().to_vec())
            }
        }

        const SCHEMA: &str = r#"{"type":"object","properties":{"limit":{"type":"number"}},"required":["limit"]}"#;

        async fn check(params: &[u8], schema_cid: &str) -> Result<serde_json::Value, RegoError> {
            validate_policy_params(
                Address::ZERO,
                &Bytes::from(params.to_vec()),
                schema_cid,
                &StaticFetcher(SCHEMA),
            )
            .await
        }

        #[tokio::test]
        async fn accepts_params_matching_the_declared_schema() {
            check(br#"{"limit":5}"#, SCHEMA_CID).await.unwrap();
        }

        #[tokio::test]
        async fn rejects_params_the_schema_does_not_admit() {
            let err = check(br#"{"limit":"five"}"#, SCHEMA_CID).await.unwrap_err();
            assert!(matches!(err, RegoError::FailedToValidateParamsSchema(_)));
        }

        /// Empty params are the canonical "no configuration" value, not an escape hatch: they
        /// validate as `{}` so a schema with required properties still rejects them.
        #[tokio::test]
        async fn rejects_empty_params_against_a_schema_with_required_properties() {
            let err = check(b"", SCHEMA_CID).await.unwrap_err();
            assert!(matches!(err, RegoError::FailedToValidateParamsSchema(_)));
        }

        /// The evaluation kernel degrades unparseable params to `{}`; admission must not, or a
        /// malformed configuration silently evaluates as an empty one.
        #[tokio::test]
        async fn rejects_params_that_are_not_json() {
            let err = check(b"not json", SCHEMA_CID).await.unwrap_err();
            assert!(matches!(err, RegoError::FailedToValidateParamsSchema(_)));
        }

        /// A policy that declares no schema has no contract to enforce.
        #[tokio::test]
        async fn skips_validation_when_the_policy_declares_no_schema() {
            check(b"anything at all", "").await.unwrap();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::newton_prover_task_manager::{INewtonPolicy, INewtonPolicyClient, NewtonMessage};
    use alloy::{json_abi::StateMutability, sol, sol_types::SolCall};
    use serde_json::json;

    // Sample test data based on the provided log
    sol! {
        // MockToken token buy contract
        contract MockToken {
            function mint(address account, uint256 amount) public {}
            function buy(address token, uint256 amount) public {}
        }
    }

    fn create_sample_intent() -> NewtonMessage::Intent {
        let buy_call = MockToken::buyCall {
            token: "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf".parse().unwrap(),
            amount: U256::from(200000000000u64),
        };
        let calldata = buy_call.abi_encode();

        NewtonMessage::Intent {
            from: "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266".parse().unwrap(),
            to: "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf".parse().unwrap(),
            value: U256::from(10000000000000000u64),
            data: calldata.into(),
            chainId: U256::from(31337),
            functionSignature: "function buy(address token, uint256 amount)".as_bytes().to_vec().into(),
        }
    }

    fn create_sample_policy_config() -> INewtonPolicy::PolicyConfig {
        INewtonPolicy::PolicyConfig {
            policyParams: Bytes::from(
                r#"{
                "allowed_actions": {
                    "31337": {
                        "function_signature": "function buy(address,uint256)",
                        "address": "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf",
                        "max_limit": 1000000000000000000
                    },
                    "11155111": {
                        "function_signature": "function buy(address,uint256)",
                        "address": "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf",
                        "max_limit": 1000000000000000000
                    }
                },
                "token_whitelist": {
                    "31337": {
                        "symbol": "NEWT",
                        "address": "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf",
                        "max_limit": 1000000000000000000
                    },
                    "11155111": {
                        "symbol": "WBTC",
                        "address": "0x29f2D40B0605204364af54EC677bD022dA425d03",
                        "max_limit": 1000000000000000000
                    }
                }
            }"#
                .as_bytes(),
            ),
            expireAfter: 1000,
        }
    }

    fn create_sample_policy_spec() -> INewtonPolicyClient::PolicySpec {
        INewtonPolicyClient::PolicySpec {
            policy: "0xed33e3a3f077bcd7c01fe5e2c1c38d5e016c012f".parse().unwrap(),
            config: create_sample_policy_config(),
        }
    }

    fn create_sample_task() -> INewtonProverTaskManager::Task {
        INewtonProverTaskManager::Task {
            taskId: "0x4261fbbb3dfc2863eb06e5c271096d9d839bc9c41e9a8d181e1403baca5d9902"
                .parse()
                .unwrap(),
            policyClient: "0xed33e3a3f077bcd7c01fe5e2c1c38d5e016c012f".parse().unwrap(),
            policyId: "0x4261fbbb3dfc2863eb06e5c271096d9d839bc9c41e9a8d181e1403baca5d9902"
                .parse()
                .unwrap(),
            policyRevision: 1,
            intent: create_sample_intent(),
            intentSignature: Bytes::default(),
            policies: vec![create_sample_policy_spec()],
            wasmArgs: vec![newton_testing_utils::policy::TEST_POLICY_WASM_ARGS.as_bytes().into()],
            taskCreatedBlock: 0,
            quorumNumbers: Bytes::from([0]),
            quorumThresholdPercentage: 0,
            initializationTimestamp: U256::ZERO,
        }
    }

    #[test]
    fn test_decode_calldata_selector_mismatch() {
        let calldata: Bytes = "0x12345678".parse().unwrap(); // Wrong selector
        let function_signature: Bytes = "function _doSomething()".as_bytes().to_vec().into();

        let result = decode_calldata(&calldata, &function_signature);

        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(error.to_string().contains("Function selector mismatch"));
    }

    #[test]
    fn test_decode_calldata_comprehensive_types() {
        use alloy::{
            primitives::{FixedBytes, I256},
            sol,
        };

        // Test contract with various Solidity types
        sol! {
            contract TestContract {
                function testFunction(
                    bool b,
                    uint256 u,
                    int256 i,
                    address a,
                    bytes32 fb,
                    bytes dynBytes,
                    string s,
                    uint256[] dynamicArray,
                    uint256[3] fixedArray,
                    (address, uint256) tuple
                ) public {}
            }
        }

        // Create test call with various types
        let test_call = TestContract::testFunctionCall {
            b: true,
            u: U256::from(123456789),
            i: I256::try_from(-987654321i64).unwrap(),
            a: "0x742d35Cc6634C0532925A3B8D4C9dB96C4B4d8B6".parse().unwrap(),
            fb: FixedBytes::from([0x12u8; 32]),
            dynBytes: Bytes::from(vec![0xab, 0xcd, 0xef]),
            s: "Hello World".to_string(),
            dynamicArray: vec![U256::from(1), U256::from(2), U256::from(3)],
            fixedArray: [U256::from(10), U256::from(20), U256::from(30)],
            tuple: (
                "0x1234567890123456789012345678901234567890".parse().unwrap(),
                U256::from(999),
            ),
        };

        let calldata = test_call.abi_encode();
        let function_signature: Bytes = Bytes::from("function testFunction(bool,uint256,int256,address,bytes32,bytes,string,uint256[],uint256[3],(address,uint256))".as_bytes().to_vec());

        let result = decode_calldata(&Bytes::from(calldata), &function_signature);
        assert!(result.is_ok());

        let (_func, inputs) = result.unwrap();
        assert_eq!(inputs.len(), 10);

        // Verify each decoded parameter
        match &inputs[0] {
            DynSolValue::Bool(b) => assert!(*b),
            _ => panic!("Expected bool"),
        }

        match &inputs[1] {
            DynSolValue::Uint(u, _) => assert_eq!(*u, U256::from(123456789)),
            _ => panic!("Expected uint256"),
        }

        match &inputs[2] {
            DynSolValue::Int(i, _) => assert_eq!(*i, I256::try_from(-987654321i64).unwrap()),
            _ => panic!("Expected int256"),
        }

        match &inputs[3] {
            DynSolValue::Address(a) => assert_eq!(
                *a,
                "0x742d35Cc6634C0532925A3B8D4C9dB96C4B4d8B6".parse::<Address>().unwrap()
            ),
            _ => panic!("Expected address"),
        }

        match &inputs[4] {
            DynSolValue::FixedBytes(fb, _) => assert_eq!(fb.as_slice(), &[0x12u8; 32]),
            _ => panic!("Expected bytes32"),
        }

        match &inputs[5] {
            DynSolValue::Bytes(b) => assert_eq!(b.as_slice(), &vec![0xab, 0xcd, 0xef]),
            _ => panic!("Expected bytes"),
        }

        match &inputs[6] {
            DynSolValue::String(s) => assert_eq!(s, "Hello World"),
            _ => panic!("Expected string"),
        }

        match &inputs[7] {
            DynSolValue::Array(arr) => {
                assert_eq!(arr.len(), 3);
                match &arr[0] {
                    DynSolValue::Uint(u, _) => assert_eq!(*u, U256::from(1)),
                    _ => panic!("Expected uint in array"),
                }
            }
            _ => panic!("Expected array"),
        }

        match &inputs[8] {
            DynSolValue::FixedArray(arr) => {
                assert_eq!(arr.len(), 3);
                match &arr[0] {
                    DynSolValue::Uint(u, _) => assert_eq!(*u, U256::from(10)),
                    _ => panic!("Expected uint in fixed array"),
                }
            }
            _ => panic!("Expected fixed array"),
        }

        match &inputs[9] {
            DynSolValue::Tuple(tuple) => {
                assert_eq!(tuple.len(), 2);
                match &tuple[0] {
                    DynSolValue::Address(a) => assert_eq!(
                        *a,
                        "0x1234567890123456789012345678901234567890".parse::<Address>().unwrap()
                    ),
                    _ => panic!("Expected address in tuple"),
                }
                match &tuple[1] {
                    DynSolValue::Uint(u, _) => assert_eq!(*u, U256::from(999)),
                    _ => panic!("Expected uint in tuple"),
                }
            }
            _ => panic!("Expected tuple"),
        }
    }

    #[test]
    fn test_decode_calldata_primitive_types() {
        use alloy::{primitives::I256, sol};

        sol! {
            contract PrimitiveTest {
                function primitiveTest(
                    uint8 u8,
                    uint16 u16,
                    uint32 u32,
                    uint64 u64,
                    uint128 u128,
                    uint256 u256,
                    int8 i8,
                    int16 i16,
                    int32 i32,
                    int64 i64,
                    int128 i128,
                    int256 i256
                ) public {}
            }
        }

        let test_call = PrimitiveTest::primitiveTestCall {
            u8: 255,
            u16: 65535,
            u32: 4294967295,
            u64: 18446744073709551615,
            u128: 340282366920938463463374607431768211455u128,
            u256: U256::from_str_radix(
                "115792089237316195423570985008687907853269984665640564039457584007913129639935",
                10,
            )
            .unwrap(),
            i8: -128,
            i16: -32768,
            i32: -2147483648,
            i64: -9223372036854775808,
            i128: -170141183460469231731687303715884105727i128,
            i256: I256::try_from(-170141183460469231731687303715884105727i128).unwrap(),
        };

        let calldata = test_call.abi_encode();
        let function_signature: Bytes = Bytes::from(
            "function primitiveTest(uint8,uint16,uint32,uint64,uint128,uint256,int8,int16,int32,int64,int128,int256)"
                .as_bytes()
                .to_vec(),
        );

        let result = decode_calldata(&Bytes::from(calldata), &function_signature);
        assert!(result.is_ok());

        let (_, inputs) = result.unwrap();
        assert_eq!(inputs.len(), 12);

        // Test that all primitive types are correctly decoded
        for (i, input) in inputs.iter().enumerate() {
            match input {
                DynSolValue::Uint(_, bits) | DynSolValue::Int(_, bits) => {
                    // Verify the bit width is preserved
                    assert!(*bits > 0 && *bits <= 256);
                }
                _ => panic!("Expected numeric type at index {}", i),
            }
        }
    }

    #[test]
    fn test_parse_intent() {
        let intent = json!(create_sample_intent());
        let parsed_intent = parse_intent(intent).unwrap();

        // Verify all fields are correctly parsed
        assert_eq!(
            parsed_intent.from,
            "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266".parse::<Address>().unwrap()
        );
        assert_eq!(
            parsed_intent.to,
            "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf".parse::<Address>().unwrap()
        );
        assert_eq!(parsed_intent.value, U256::from(10000000000000000u64)); // 0.01 ether
        assert_eq!(parsed_intent.chain_id, Some(ChainId::from(0x7a69u64)));
        assert_eq!(
            parsed_intent.decoded_function_signature,
            Some("function buy(address token, uint256 amount)".to_string())
        );
        assert_eq!(parsed_intent.decoded_function_arguments.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_parse_intent_missing_fields() {
        let incomplete_json = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2"
            // Missing other required fields
        });

        let result = parse_intent(incomplete_json);

        assert!(result.is_err());
    }

    #[test]
    fn test_parse_intent_optional_chain_id() {
        // Test with missing chainId - should set to None
        let json_without_chain_id = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
        });

        let result = parse_intent(json_without_chain_id);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.chain_id, None);

        // Test with invalid hex chainId - should set to None
        let json_invalid_hex_chain_id = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "0xGGGG"
        });

        let result = parse_intent(json_invalid_hex_chain_id);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.chain_id, None);

        // Test with invalid decimal chainId - should set to None
        let json_invalid_decimal_chain_id = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "not_a_number"
        });

        let result = parse_intent(json_invalid_decimal_chain_id);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.chain_id, None);

        // Test with valid hex chainId
        let json_valid_hex_chain_id = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "0x7a69"
        });

        let result = parse_intent(json_valid_hex_chain_id);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.chain_id, Some(31337u64));

        // Test with valid decimal chainId
        let json_valid_decimal_chain_id = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "1"
        });

        let result = parse_intent(json_valid_decimal_chain_id);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.chain_id, Some(1u64));
    }

    #[test]
    fn test_parse_intent_optional_function_signature() {
        // Test without functionSignature - should be None
        let json_without_sig = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "1"
        });

        let result = parse_intent(json_without_sig);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.function_signature, None);
        assert_eq!(parsed.decoded_function_signature, None);
        assert_eq!(parsed.decoded_function_arguments, None);
        assert_eq!(parsed.function, None);

        // Test with functionSignature but no data - decoding should fail gracefully
        let json_with_sig_no_data = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "chainId": "1",
            "functionSignature": "function doSomething()"
        });

        let result = parse_intent(json_with_sig_no_data);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert!(parsed.function_signature.is_some());
        assert_eq!(parsed.data, None);
        assert_eq!(parsed.decoded_function_signature, None);
    }

    #[test]
    fn test_parse_intent_optional_data() {
        // Test without data - should be None
        let json_without_data = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "chainId": "1"
        });

        let result = parse_intent(json_without_data);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.data, None);

        // Test with data
        let json_with_data = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "1"
        });

        let result = parse_intent(json_with_data);
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert!(parsed.data.is_some());
        assert_eq!(parsed.data.unwrap(), Bytes::from(vec![0x6b, 0x23, 0x05, 0xce]));
    }

    #[test]
    fn test_parse_intent_minimal_valid() {
        // Test with only required fields (from, to, value)
        let minimal_json = json!({
            "from": "0xb9e89063d40f95bf2aac0c06777764d7378ead10",
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "1000000000000000000"
        });

        let result = parse_intent(minimal_json);
        assert!(result.is_ok());
        let parsed = result.unwrap();

        assert_eq!(
            parsed.from,
            "0xb9e89063d40f95bf2aac0c06777764d7378ead10".parse::<Address>().unwrap()
        );
        assert_eq!(
            parsed.to,
            "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2".parse::<Address>().unwrap()
        );
        assert_eq!(parsed.value, U256::from(1000000000000000000u64));
        assert_eq!(parsed.chain_id, None);
        assert_eq!(parsed.data, None);
        assert_eq!(parsed.function_signature, None);
        assert_eq!(parsed.decoded_function_signature, None);
        assert_eq!(parsed.decoded_function_arguments, None);
        assert_eq!(parsed.function, None);
    }

    #[test]
    fn test_parse_intent_full_valid() {
        // Test with all fields present and valid
        let buy_call = MockToken::buyCall {
            token: "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf".parse().unwrap(),
            amount: U256::from(200000000000u64),
        };
        let calldata = buy_call.abi_encode();

        let full_json = json!({
            "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
            "to": "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf",
            "value": "10000000000000000",
            "data": format!("0x{}", crate::hex!(&calldata)),
            "chainId": "0x7a69",
            "functionSignature": "function buy(address token, uint256 amount)"
        });

        let result = parse_intent(full_json);
        assert!(result.is_ok());
        let parsed = result.unwrap();

        assert!(parsed.chain_id.is_some());
        assert_eq!(parsed.chain_id.unwrap(), 31337u64);
        assert!(parsed.data.is_some());
        assert!(parsed.function_signature.is_some());
        assert!(parsed.decoded_function_signature.is_some());
        assert_eq!(
            parsed.decoded_function_signature.unwrap(),
            "function buy(address token, uint256 amount)"
        );
        assert!(parsed.decoded_function_arguments.is_some());
        assert_eq!(parsed.decoded_function_arguments.as_ref().unwrap().len(), 2);
        assert!(parsed.function.is_some());
    }

    #[test]
    fn test_parse_intent_invalid_address() {
        let invalid_json = json!({
            "from": "0x123456789012345678901234567890123456789012", // Invalid address length (too long)
            "to": "0x2e2ed0cfd3ad2f1d34481277b3204d807ca2f8c2",
            "value": "0x0",
            "data": "0x6b2305ce",
            "chainId": "0x7a69",
            "functionSignature": "0x66756e6374696f6e205f646f536f6d657468696e672829"
        });

        let result = parse_intent(invalid_json);

        assert!(result.is_err());
    }

    #[test]
    fn test_serialize_sol_value() {
        // Test different Solidity value types
        let bool_val = DynSolValue::Bool(true);
        let serialized_bool = serialize_sol_value(&bool_val);
        assert_eq!(serialized_bool, serde_json::Value::Bool(true));

        let uint_val = DynSolValue::Uint(U256::from(123), 256);
        let serialized_uint = serialize_sol_value(&uint_val);
        assert_eq!(serialized_uint, serde_json::Value::String("123".to_string()));

        let address_val = DynSolValue::Address("0x742d35Cc6634C0532925A3B8D4C9dB96C4B4d8B6".parse().unwrap());
        let serialized_address = serialize_sol_value(&address_val);
        assert_eq!(
            serialized_address,
            serde_json::Value::String("0x742d35cc6634c0532925a3b8d4c9db96c4b4d8b6".to_string())
        );

        let bytes_val = DynSolValue::Bytes(vec![0x12, 0x34, 0x56]);
        let serialized_bytes = serialize_sol_value(&bytes_val);
        assert_eq!(serialized_bytes, serde_json::Value::String("0x123456".to_string()));

        let string_val = DynSolValue::String("Hello World".to_string());
        let serialized_string = serialize_sol_value(&string_val);
        assert_eq!(serialized_string, serde_json::Value::String("Hello World".to_string()));

        // Test fixed bytes preserving exact length
        use alloy::primitives::FixedBytes;
        let mut fixed_bytes_array = [0u8; 32];
        fixed_bytes_array[0] = 0x12;
        fixed_bytes_array[1] = 0x34;
        let fixed_bytes_val = DynSolValue::FixedBytes(FixedBytes::from(fixed_bytes_array), 32);
        let serialized_fixed_bytes = serialize_sol_value(&fixed_bytes_val);
        assert_eq!(
            serialized_fixed_bytes,
            serde_json::Value::String("0x1234000000000000000000000000000000000000000000000000000000000000".to_string())
        );

        // Octane Warning #3: zero-tail bytes32 must serialize to full-width hex
        let mut zero_tail_array = [0u8; 32];
        zero_tail_array[0] = 0xaa;
        zero_tail_array[1] = 0xbb;
        let zero_tail_val = DynSolValue::FixedBytes(FixedBytes::from(zero_tail_array), 32);
        let serialized_zero_tail = serialize_sol_value(&zero_tail_val);
        assert_eq!(
            serialized_zero_tail,
            serde_json::Value::String("0xaabb000000000000000000000000000000000000000000000000000000000000".to_string()),
            "bytes32 with trailing zeros must serialize to full 64-nibble hex"
        );

        // All-zero bytes32 must also be full-width
        let all_zero_array = [0u8; 32];
        let all_zero_val = DynSolValue::FixedBytes(FixedBytes::from(all_zero_array), 32);
        let serialized_all_zero = serialize_sol_value(&all_zero_val);
        assert_eq!(
            serialized_all_zero,
            serde_json::Value::String("0x0000000000000000000000000000000000000000000000000000000000000000".to_string()),
            "all-zero bytes32 must serialize to full 64-nibble hex, not '0x'"
        );

        // Test array
        let array_val = DynSolValue::Array(vec![
            DynSolValue::Uint(U256::from(1), 256),
            DynSolValue::Uint(U256::from(2), 256),
            DynSolValue::Uint(U256::from(3), 256),
        ]);
        let serialized_array = serialize_sol_value(&array_val);
        let expected_array = serde_json::json!(["1", "2", "3"]);
        assert_eq!(serialized_array, expected_array);

        // Test tuple
        let tuple_val = DynSolValue::Tuple(vec![
            DynSolValue::Address("0x742d35Cc6634C0532925A3B8D4C9dB96C4B4d8B6".parse().unwrap()),
            DynSolValue::Uint(U256::from(1000), 256),
        ]);
        let serialized_tuple = serialize_sol_value(&tuple_val);
        let expected_tuple = serde_json::json!(["0x742d35cc6634c0532925a3b8d4c9db96c4b4d8b6", "1000"]);
        assert_eq!(serialized_tuple, expected_tuple);
    }

    // Test cases for parse_and_evaluate_policy_set
    // Note: These are unit tests that focus on the core logic without blockchain interactions

    #[tokio::test]
    #[cfg(feature = "rpc")]
    async fn test_parse_and_evaluate_policy_set_success() {
        // Create a task with valid policy data
        let task = create_sample_task();

        // Note: This test would require mocking the blockchain interactions
        // For now, we'll test the individual pieces that make up this function

        // Test that we can parse the intent from the task
        let intent_json = json!(task.intent);
        let parsed_intent = parse_intent(intent_json).unwrap();

        // Verify the parsed intent has the expected structure
        assert_eq!(
            parsed_intent.from,
            "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266".parse::<Address>().unwrap()
        );
        assert_eq!(
            parsed_intent.to,
            "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf".parse::<Address>().unwrap()
        );
        assert_eq!(parsed_intent.value, U256::from(10000000000000000u64));
        assert_eq!(
            parsed_intent.decoded_function_signature,
            Some("function buy(address token, uint256 amount)".to_string())
        );
        let args = parsed_intent.decoded_function_arguments.as_ref().unwrap();
        assert_eq!(args.len(), 2);
        assert_eq!(args[0], "0x8f86403a4de0bb5791fa46b8e795c547942fe4cf");
        assert_eq!(args[1], "200000000000");

        let func = parsed_intent.function.as_ref().unwrap();
        assert_eq!(func.name, "buy");
        assert_eq!(func.inputs.len(), 2);
        assert_eq!(func.inputs[0].ty, "address");
        assert_eq!(func.inputs[1].ty, "uint256");
        assert_eq!(func.outputs.len(), 0);
        assert_eq!(func.state_mutability, StateMutability::NonPayable);
    }

    #[test]
    fn test_intent_round_trip_alloy_serde_to_parsed_intent() {
        use crate::common::intent::RawParsedIntent;

        // Pin the invariant the circuit relies on: NewtonMessage::Intent (Solidity struct)
        // -> serde_json::json! -> parse_intent -> RawParsedIntent -> String
        // must produce strings for Bytes/U256 fields, never null, even when empty/zero.

        // Case 1: Empty calldata (plain ETH transfer)
        let intent = Intent {
            from: "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266".parse().unwrap(),
            to: "0x70997970c51812dc3a010c7d01b50e0d17dc79c8".parse().unwrap(),
            value: U256::from(1000000000000000000u64), // 1 ETH
            data: Bytes::new(),                        // empty
            chainId: U256::ZERO,                       // no chain ID
            functionSignature: Bytes::new(),           // no function signature
        };

        let intent_json = serde_json::json!(intent);
        let parsed_intent = parse_intent(intent_json).expect("should parse empty-calldata intent");
        let final_json_str: String = parsed_intent.clone().into(); // From<ParsedIntent> for String
        let final_json: serde_json::Value =
            serde_json::from_str(&final_json_str).expect("ParsedIntent JSON should be valid");

        // Bytes.to_string() emits "0x" for empty; ChainId (u64).to_string() emits decimal
        assert_eq!(final_json["data"], "0x", "empty Bytes must serialize as '0x', not null");
        assert_eq!(
            final_json["chain_id"], "0",
            "zero ChainId must serialize as '0', not null"
        );
        assert_eq!(
            final_json["function_signature"], "0x",
            "empty Bytes must serialize as '0x', not null"
        );

        // Case 2: Non-empty calldata
        let intent_with_data = Intent {
            from: "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266".parse().unwrap(),
            to: "0x70997970c51812dc3a010c7d01b50e0d17dc79c8".parse().unwrap(),
            value: U256::from(1000000000000000000u64),
            data: Bytes::from(vec![0x6b, 0x23, 0x05, 0xce]),
            chainId: U256::from(1u64),
            functionSignature: Bytes::from("function transfer(address,uint256)".as_bytes()),
        };

        let intent_json = serde_json::json!(intent_with_data);
        let parsed_intent = parse_intent(intent_json).expect("should parse intent with data");
        let final_json_str: String = parsed_intent.clone().into();
        let final_json: serde_json::Value =
            serde_json::from_str(&final_json_str).expect("ParsedIntent JSON should be valid");

        assert_eq!(final_json["data"], "0x6b2305ce");
        assert_eq!(final_json["chain_id"], "1"); // ChainId is decimal
        assert!(final_json["function_signature"].as_str().unwrap().starts_with("0x"));
    }

    #[tokio::test]
    #[cfg(feature = "rpc")]
    async fn test_parse_and_evaluate_policy_set_invalid_intent() {
        use alloy::primitives::Bytes;

        // Create a task with invalid intent data
        let mut task = create_sample_task();

        // Corrupt the intent data to make it invalid (not valid ABI-encoded calldata)
        task.intent.data = Bytes::from("invalid_data".as_bytes());

        // Test that parsing the intent succeeds but decoding fails gracefully
        let intent_json = json!(task.intent);
        let result = parse_intent(intent_json);

        // Parsing should succeed (data is valid hex after serialization)
        assert!(result.is_ok());
        let parsed = result.unwrap();

        // But the data is present
        assert!(parsed.data.is_some());

        // And decoding should have failed, so decoded fields should be None
        assert!(parsed.decoded_function_signature.is_none());
        assert!(parsed.decoded_function_arguments.is_none());
        assert!(parsed.function.is_none());
    }

    #[tokio::test]
    async fn test_evaluate_basic_policy() {
        use crate::evaluate;

        let policy = newton_testing_utils::policy::TEST_POLICY_REGO;

        let policy_params_and_data = newton_testing_utils::policy::TEST_POLICY_DATA;

        let parsed_intent = newton_testing_utils::policy::TEST_POLICY_PARSED_INTENT;

        let policy_rule = "data.basic.allow";

        // Test the evaluation
        let result = evaluate(
            policy.to_string(),
            policy_params_and_data,
            parsed_intent,
            &[],
            policy_rule,
            None,
        );

        // The evaluation should succeed
        assert!(result.is_ok());

        let evaluation_result = result.unwrap();

        // The result should be a boolean indicating whether the action is allowed
        match evaluation_result {
            regorus::Value::Bool(result) => {
                // The policy evaluation is working correctly
                assert!(result, "Policy evaluation failed");
            }
            _ => panic!("Expected boolean result, got: {}", evaluation_result),
        }
    }

    #[test]
    fn merge_secrets_schemas_unions() {
        let schema_a = json!({
            "type": "object",
            "properties": {
                "COIN_GECKO_API": { "type": "string", "minLength": 1 }
            },
            "required": ["COIN_GECKO_API"],
            "additionalProperties": false
        });

        // Duplicate key with different constraint should be ignored (first wins)
        let schema_b = json!({
            "type": "object",
            "properties": {
                "COIN_GECKO_API": { "type": "string", "minLength": 999 },
                "WEATHER_API": { "type": "string", "minLength": 1 }
            },
            "required": ["WEATHER_API"]
        });

        let merged = merge_secrets_schemas(vec![("cid_a".to_string(), schema_a), ("cid_b".to_string(), schema_b)])
            .expect("merge");

        let props = merged
            .get("properties")
            .and_then(|v| v.as_object())
            .expect("properties object");

        assert!(props.contains_key("COIN_GECKO_API"));
        assert!(props.contains_key("WEATHER_API"));

        // First schema wins for duplicate property definitions
        assert_eq!(
            props.get("COIN_GECKO_API").unwrap().get("minLength").unwrap(),
            &json!(1)
        );

        let required = merged
            .get("required")
            .and_then(|v| v.as_array())
            .expect("required array");
        assert!(required.contains(&json!("COIN_GECKO_API")));
        assert!(required.contains(&json!("WEATHER_API")));

        assert!(merged.get("additionalProperties").is_none());
    }

    #[test]
    fn merge_secrets_schemas_ignores_additional_properties_false() {
        let schema_a = json!({
            "type": "object",
            "properties": { "A": { "type": "string" } },
            "additionalProperties": true
        });
        let schema_b = json!({
            "type": "object",
            "properties": { "B": { "type": "string" } },
            "additionalProperties": false
        });

        let merged = merge_secrets_schemas(vec![("cid_a".to_string(), schema_a), ("cid_b".to_string(), schema_b)])
            .expect("merge");

        assert!(merged.get("additionalProperties").is_none());
    }

    #[test]
    fn merge_secrets_schemas_ignores_non_object_schema() {
        let merged = merge_secrets_schemas(vec![("cid_bad".to_string(), json!(["nope"]))]).expect("merge");
        assert!(merged.get("additionalProperties").is_none());
        let props = merged
            .get("properties")
            .and_then(|v| v.as_object())
            .expect("properties object");
        assert!(props.is_empty());
    }

    #[test]
    fn merge_secrets_schemas_ignores_invalid_properties_shape() {
        let schema = json!({
            "type": "object",
            "properties": ["not", "an", "object"]
        });

        let merged = merge_secrets_schemas(vec![("cid_bad".to_string(), schema)]).expect("merge");
        assert!(merged.get("additionalProperties").is_none());
        let props = merged
            .get("properties")
            .and_then(|v| v.as_object())
            .expect("properties object");
        assert!(props.is_empty());
    }

    #[test]
    fn merge_secrets_schemas_ignores_invalid_required() {
        let schema_not_array = json!({
            "type": "object",
            "properties": {},
            "required": "NOPE"
        });
        let merged = merge_secrets_schemas(vec![("cid_bad".to_string(), schema_not_array)]).expect("merge");
        assert!(merged.get("additionalProperties").is_none());
        assert!(merged.get("required").is_none());

        let schema_non_string = json!({
            "type": "object",
            "properties": {},
            "required": ["OK", 123]
        });
        let merged = merge_secrets_schemas(vec![("cid_bad2".to_string(), schema_non_string)]).expect("merge");
        assert!(merged.get("additionalProperties").is_none());
        assert!(merged.get("required").is_none());
    }

    #[test]
    fn task_request_proof_cid_serialization() {
        use serde_json;

        let request = TaskRequest {
            task_id: B256::ZERO,
            intent: NewtonMessage::Intent {
                from: Address::ZERO,
                to: Address::ZERO,
                value: U256::ZERO,
                data: Bytes::default(),
                chainId: U256::from(1),
                functionSignature: Bytes::default(),
            },
            intent_signature: None,
            policy_client: Address::ZERO,
            policy_id: B256::ZERO,
            policies: vec![create_sample_policy_spec()],
            policy_revision: 1,
            wasm_args: vec![],
            quorum_numbers: vec![0],
            quorum_threshold_percentage: 40,
            task_created_block: 100,
            proof_cid: Some("bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi".to_string()),
            initialization_timestamp: 0,
        };

        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(
            json["proof_cid"],
            "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"
        );

        let request_no_proof = TaskRequest {
            proof_cid: None,
            ..request
        };
        let json2 = serde_json::to_value(&request_no_proof).unwrap();
        assert!(json2.get("proof_cid").is_none());

        // Deserialize without proof_cid field should default to None
        let mut json3 = json.clone();
        json3.as_object_mut().unwrap().remove("proof_cid");
        let deserialized: TaskRequest = serde_json::from_value(json3).unwrap();
        assert!(deserialized.proof_cid.is_none());

        let mut json4 = json.clone();
        json4
            .as_object_mut()
            .unwrap()
            .insert("proofCid".to_string(), serde_json::json!("bafycamelcase"));
        json4.as_object_mut().unwrap().remove("proof_cid");
        let deserialized_camel: TaskRequest = serde_json::from_value(json4).unwrap();
        assert_eq!(deserialized_camel.proof_cid.as_deref(), Some("bafycamelcase"));
    }

    #[test]
    fn tls_proof_data_injected_into_rego_root_namespace() {
        // additional_data (tls_proof) is merged at the root level in Rego,
        // giving clean namespaces: data.tls_proof.*, data.wasm.*, data.privacy.*
        let tls_proof = serde_json::json!({
            "server_name": "api.twitter.com",
            "verified": true,
            "response_body": "{\"id\":\"123\",\"name\":\"test\"}",
            "request_target": "/2/users/me"
        });

        let policy_data = serde_json::json!({
            "params": {},
            "wasm": { "some_key": "some_value" },
            "tls_proof": tls_proof,
        });

        // Verify tls_proof is accessible at data.tls_proof (root level)
        assert_eq!(policy_data["tls_proof"]["server_name"], "api.twitter.com");
        assert_eq!(policy_data["tls_proof"]["verified"], true);
        assert_eq!(policy_data["wasm"]["some_key"], "some_value");
    }
}