tempus-ddb 0.5.4

Fail-closed policy gate for AI agent actions: signed policies, single-use permits, receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
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
//! Tempus DDB: a fail-closed authorization gate for autonomous agent actions.
//!
//! An agent signs an *intent*; the gate evaluates a signed tenant policy and issues a
//! single-use, expiring *permit* (`ALLOWED` or `BLOCKED`); a credential-isolated
//! *executor* consumes the permit exactly once and signs the *outcome*; the gate links
//! everything into a dual-signed *receipt* that anyone holding the gate public key can
//! verify offline. Unknown schemas, policies, identities and execution states are
//! refused or denied, never allowed, and with no installed policy every action is denied.
//!
//! This crate is published mainly as the native extension behind the
//! [`tempus-ddb` Python package](https://pypi.org/project/tempus-ddb/) (`tempus_ddb._tempus_ddb`,
//! built with PyO3 and maturin). The Rust API that is useful on its own:
//!
//! - [`verify_receipt`], [`verify_bundle`] and [`verify_checkpoint`]: independent
//!   verification of exported evidence against a pinned gate public key, with no database.
//! - [`generate_keypair`]: Ed25519 key generation in the key-file format the CLI reads.
//! - [`StorageLayer`] and [`SqliteStorage`]: the storage boundary used
//!   by the gate and the legacy decision ledger.
//!
//! Signed JSON documents are parsed strictly: duplicate object keys are refused, and
//! numbers must be exact (no floats, no integers beyond `i64`/`u64`).
//!
//! Documentation: <https://julio-patron.github.io/tempus-ddb/docs.html>. Threat model,
//! compatibility rules and changelog live in the repository:
//! <https://github.com/Julio-Patron/tempus-ddb>.
#![allow(clippy::useless_conversion)] // PyO3 macro expansion on Rust 1.96.

#[cfg(not(target_arch = "wasm32"))]
use pyo3::exceptions::{PyPermissionError, PyRuntimeError};
#[cfg(not(target_arch = "wasm32"))]
use pyo3::prelude::*;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

#[cfg(not(target_arch = "wasm32"))]
mod b2a;

#[cfg(not(target_arch = "wasm32"))]
mod strict_json;

#[cfg(not(target_arch = "wasm32"))]
mod phase3;
#[cfg(not(target_arch = "wasm32"))]
use phase3::SignerBackend;

#[cfg(not(target_arch = "wasm32"))]
mod events;

// --- 1. PATRÓN STORAGE LAYER (TRAIT) ---
pub trait StorageLayer {
    fn insert_decision(&mut self, payload: &str, rules: &str, genesis: bool) -> Result<(), String>;
    fn insert_decision_batch(
        &mut self,
        decisions: Vec<(&str, &str)>,
        genesis: bool,
    ) -> Result<(), String>;
    fn get_latest_hash(&self) -> Result<String, String>;
    fn export_ledger(&self) -> Result<String, String>;
    fn list_decisions(&self, limit: u32, offset: u32) -> Result<String, String>;
    fn count_decisions(&self) -> Result<u64, String>;
}

// Experimental WASM support: in-memory stub storage only, not persistent ledger storage.
#[cfg(target_arch = "wasm32")]
pub struct MemoryStorage {
    records: Vec<String>,
    latest_hash: String,
}

#[cfg(target_arch = "wasm32")]
impl MemoryStorage {
    pub fn new() -> Self {
        Self {
            records: Vec::new(),
            latest_hash: "GENESIS_HASH_MEM".to_string(),
        }
    }
}

#[cfg(target_arch = "wasm32")]
impl StorageLayer for MemoryStorage {
    fn insert_decision(
        &mut self,
        payload: &str,
        _rules: &str,
        genesis: bool,
    ) -> Result<(), String> {
        self.records.push(payload.to_string());
        if genesis {
            self.latest_hash = "GENESIS_HASH_MEM".to_string();
        } else {
            self.latest_hash = "NEW_HASH_MEM".to_string(); // Simulación de nuevo hash
        }
        Ok(())
    }

    fn insert_decision_batch(
        &mut self,
        decisions: Vec<(&str, &str)>,
        genesis: bool,
    ) -> Result<(), String> {
        let mut is_first = true;
        for (payload, rules) in decisions {
            self.insert_decision(payload, rules, genesis && is_first)?;
            is_first = false;
        }
        Ok(())
    }

    fn get_latest_hash(&self) -> Result<String, String> {
        Ok(self.latest_hash.clone())
    }

    fn export_ledger(&self) -> Result<String, String> {
        // En una implementación real, serializaríamos a JSON usando serde_json
        Ok(format!("[{}]", self.records.join(",")))
    }

    fn list_decisions(&self, limit: u32, offset: u32) -> Result<String, String> {
        let start = offset as usize;
        let end = std::cmp::min(start + limit as usize, self.records.len());
        if start >= self.records.len() {
            return Ok("[]".to_string());
        }
        Ok(format!("[{}]", self.records[start..end].join(",")))
    }

    fn count_decisions(&self) -> Result<u64, String> {
        Ok(self.records.len() as u64)
    }
}

// Implementación SQLite (Para Python / Nativo)
#[cfg(not(target_arch = "wasm32"))]
use rusqlite::Connection;

#[cfg(not(target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};

#[cfg(not(target_arch = "wasm32"))]
use sha2::{Digest, Sha256};

#[cfg(not(target_arch = "wasm32"))]
use ed25519_dalek::Signer;

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Decision {
    id: String,
    parent_id: String,
    causal_depth: u64,
    actor_id: String,
    timestamp: u64,
    payload: String,
    rules_evaluated: String,
    signature: String,
}

#[cfg(not(target_arch = "wasm32"))]
pub struct SqliteStorage {
    conn: Connection,
    keyfile: String,
    cached_signing_key: std::cell::RefCell<Option<ed25519_dalek::SigningKey>>,
    cached_signer: std::cell::RefCell<Option<phase3::ConfiguredSigner>>,
}

#[cfg(not(target_arch = "wasm32"))]
impl SqliteStorage {
    pub fn new(db_path: String, keyfile: String) -> Result<Self, String> {
        let conn = Connection::open(&db_path)
            .map_err(|e| format!("Failed to open SQLite database '{}': {}", db_path, e))?;

        conn.execute_batch(
            "PRAGMA journal_mode = WAL;
             PRAGMA synchronous = FULL;
             PRAGMA busy_timeout = 5000;",
        )
        .map_err(|e| e.to_string())?;

        conn.execute(
            "CREATE TABLE IF NOT EXISTS decisions (
                id TEXT PRIMARY KEY,
                parent_id TEXT NOT NULL,
                causal_depth INTEGER NOT NULL,
                actor_id TEXT NOT NULL,
                timestamp INTEGER NOT NULL,
                payload TEXT NOT NULL,
                rules_evaluated TEXT NOT NULL,
                signature TEXT NOT NULL
            );",
            [],
        )
        .map_err(|e| format!("Failed to create decisions table: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_parent_id ON decisions (parent_id);",
            [],
        )
        .map_err(|e| format!("Failed to create parent index: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_causal_depth ON decisions (causal_depth);",
            [],
        )
        .map_err(|e| format!("Failed to create causal depth index: {}", e))?;

        b2a::initialize_schema(&conn)?;

        Ok(Self {
            conn,
            keyfile,
            cached_signing_key: std::cell::RefCell::new(None),
            cached_signer: std::cell::RefCell::new(None),
        })
    }

    /// Load an Ed25519 signing key from a file path.
    fn load_signing_key_from_path(keyfile: &str) -> Result<ed25519_dalek::SigningKey, String> {
        #[derive(Deserialize)]
        struct KeyPairConfig {
            #[allow(dead_code)]
            public_key: String,
            private_key: String,
        }

        let content = std::fs::read_to_string(keyfile)
            .map_err(|e| format!("Failed to read key file '{}': {}", keyfile, e))?;
        let config: KeyPairConfig = serde_json::from_str(&content)
            .map_err(|e| format!("Failed to parse key file JSON: {}", e))?;

        let private_key_bytes = hex::decode(&config.private_key)
            .map_err(|e| format!("Invalid private key hex: {}", e))?;
        let private_key_array: [u8; 32] = private_key_bytes
            .try_into()
            .map_err(|_| "Private key must be exactly 32 bytes".to_string())?;

        Ok(ed25519_dalek::SigningKey::from_bytes(&private_key_array))
    }

    /// Return the signing key, loading from disk on first use and caching.
    pub(crate) fn load_signing_key(&self) -> Result<ed25519_dalek::SigningKey, String> {
        if let Some(ref key) = *self.cached_signing_key.borrow() {
            return Ok(key.clone());
        }
        let key = Self::load_signing_key_from_path(&self.keyfile)?;
        *self.cached_signing_key.borrow_mut() = Some(key.clone());
        Ok(key)
    }

    /// Load the configured signing backend. Local key files remain compatible, while
    /// production deployments may point at a non-secret Vault Transit signer config.
    pub(crate) fn load_signer(&self) -> Result<phase3::ConfiguredSigner, String> {
        if let Some(ref signer) = *self.cached_signer.borrow() {
            return Ok(signer.clone());
        }
        let signer = phase3::ConfiguredSigner::from_path(&self.keyfile)?;
        *self.cached_signer.borrow_mut() = Some(signer.clone());
        Ok(signer)
    }

    /// Compute the canonical SHA-256 hash for a decision (matches main.rs logic).
    pub fn calculate_canonical_hash(
        parent_id: &str,
        actor_id: &str,
        timestamp: u64,
        payload: &str,
        rules_evaluated: &str,
    ) -> Result<[u8; 32], String> {
        #[derive(Serialize)]
        struct CanonicalPayload<'a> {
            parent_id: &'a str,
            actor_id: &'a str,
            timestamp: u64,
            payload: serde_json::Value,
            rules_evaluated: serde_json::Value,
        }

        let payload_val: serde_json::Value =
            serde_json::from_str(payload).map_err(|e| format!("Invalid payload JSON: {}", e))?;
        let rules_val: serde_json::Value = serde_json::from_str(rules_evaluated)
            .map_err(|e| format!("Invalid rules JSON: {}", e))?;

        let canonical = CanonicalPayload {
            parent_id,
            actor_id,
            timestamp,
            payload: payload_val,
            rules_evaluated: rules_val,
        };

        let canonical_bytes = serde_json::to_vec(&canonical).unwrap();

        let mut hasher = Sha256::new();
        hasher.update(&canonical_bytes);
        Ok(hasher.finalize().into())
    }

    fn get_last_decision_conn(conn: &rusqlite::Connection) -> Result<Option<Decision>, String> {
        let mut stmt = conn.prepare(
            "SELECT id, parent_id, causal_depth, actor_id, timestamp, payload, rules_evaluated, signature
             FROM decisions
             ORDER BY causal_depth DESC, timestamp DESC
             LIMIT 1"
        ).map_err(|e| format!("Failed to prepare select statement: {}", e))?;

        let mut rows = stmt
            .query([])
            .map_err(|e| format!("Failed to query database: {}", e))?;
        if let Some(row) = rows
            .next()
            .map_err(|e| format!("Error advancing row: {}", e))?
        {
            Ok(Some(Decision {
                id: row.get(0).map_err(|e| e.to_string())?,
                parent_id: row.get(1).map_err(|e| e.to_string())?,
                causal_depth: row.get(2).map_err(|e| e.to_string())?,
                actor_id: row.get(3).map_err(|e| e.to_string())?,
                timestamp: row.get(4).map_err(|e| e.to_string())?,
                payload: row.get(5).map_err(|e| e.to_string())?,
                rules_evaluated: row.get(6).map_err(|e| e.to_string())?,
                signature: row.get(7).map_err(|e| e.to_string())?,
            }))
        } else {
            Ok(None)
        }
    }

    #[allow(dead_code)]
    fn get_last_decision(&self) -> Result<Option<Decision>, String> {
        Self::get_last_decision_conn(&self.conn)
    }

    pub fn validate_ledger(&self) -> Result<String, String> {
        let mut stmt = self.conn.prepare(
            "SELECT id, parent_id, causal_depth, actor_id, timestamp, payload, rules_evaluated, signature
             FROM decisions
             ORDER BY causal_depth ASC, timestamp ASC"
        ).map_err(|e| format!("Failed to prepare select statement: {}", e))?;

        let rows = stmt
            .query_map([], |row| {
                Ok(Decision {
                    id: row.get(0)?,
                    parent_id: row.get(1)?,
                    causal_depth: row.get(2)?,
                    actor_id: row.get(3)?,
                    timestamp: row.get(4)?,
                    payload: row.get(5)?,
                    rules_evaluated: row.get(6)?,
                    signature: row.get(7)?,
                })
            })
            .map_err(|e| format!("Failed to execute query: {}", e))?;

        let mut decisions = Vec::new();
        for r in rows {
            match r {
                Ok(d) => decisions.push(d),
                Err(e) => return Err(format!("Error reading record: {}", e)),
            }
        }

        if decisions.is_empty() {
            return Ok(serde_json::to_string(&serde_json::json!({
                "status": "valid",
                "message": "Database is empty.",
                "total_records": 0
            }))
            .unwrap());
        }

        use std::collections::HashMap;
        let mut decision_map = HashMap::new();
        let mut genesis_count = 0;
        for d in &decisions {
            decision_map.insert(d.id.clone(), d.clone());
            if d.parent_id == "genesis" {
                genesis_count += 1;
            }
        }

        let mut errors = Vec::new();

        if !decisions.is_empty() && genesis_count == 0 {
            errors.push("No genesis decision found in the ledger.".to_string());
        } else if genesis_count > 1 {
            errors.push(format!(
                "Multiple genesis decisions found ({}). Only one is allowed.",
                genesis_count
            ));
        }

        for d in &decisions {
            let computed_hash = match Self::calculate_canonical_hash(
                &d.parent_id,
                &d.actor_id,
                d.timestamp,
                &d.payload,
                &d.rules_evaluated,
            ) {
                Ok(h) => h,
                Err(e) => {
                    errors.push(format!("Decision '{}' hash calculation error: {}", d.id, e));
                    continue;
                }
            };
            let computed_id = hex::encode(computed_hash);
            if computed_id != d.id {
                errors.push(format!(
                    "Decision '{}' has invalid hash. Computed: '{}', Recorded: '{}'",
                    d.id, computed_id, d.id
                ));
                continue;
            }

            use ed25519_dalek::{Signature, Verifier, VerifyingKey};
            let pub_bytes = match hex::decode(&d.actor_id) {
                Ok(b) => b,
                Err(e) => {
                    errors.push(format!("Invalid actor_id: {}", e));
                    continue;
                }
            };
            let pub_array: [u8; 32] = match pub_bytes.try_into() {
                Ok(a) => a,
                Err(_) => {
                    errors.push("Invalid public key size".to_string());
                    continue;
                }
            };
            let verifying_key = match VerifyingKey::from_bytes(&pub_array) {
                Ok(k) => k,
                Err(e) => {
                    errors.push(format!("Invalid public key: {}", e));
                    continue;
                }
            };

            let sig_bytes = match hex::decode(&d.signature) {
                Ok(b) => b,
                Err(e) => {
                    errors.push(format!("Invalid signature hex: {}", e));
                    continue;
                }
            };
            let sig_array: [u8; 64] = match sig_bytes.try_into() {
                Ok(a) => a,
                Err(_) => {
                    errors.push("Invalid signature size".to_string());
                    continue;
                }
            };
            let signature = Signature::from_bytes(&sig_array);

            let id_bytes = match hex::decode(&d.id) {
                Ok(b) => b,
                Err(e) => {
                    errors.push(format!("Invalid id hex: {}", e));
                    continue;
                }
            };

            if let Err(e) = verifying_key.verify(&id_bytes, &signature) {
                errors.push(format!(
                    "Decision '{}' signature verification failed: {}",
                    d.id, e
                ));
                continue;
            }

            if d.parent_id != "genesis" {
                match decision_map.get(&d.parent_id) {
                    Some(parent) => {
                        if d.causal_depth != parent.causal_depth + 1 {
                            errors.push(format!(
                                "Decision '{}' causal depth mismatch. Expected '{}', found '{}'",
                                d.id,
                                parent.causal_depth + 1,
                                d.causal_depth
                            ));
                        }
                        if d.timestamp < parent.timestamp {
                            errors.push(format!(
                                "Decision '{}' temporal anomaly. Precedes parent '{}'",
                                d.id, d.parent_id
                            ));
                        }
                    }
                    None => {
                        errors.push(format!(
                            "Decision '{}' orphan node. Parent '{}' missing",
                            d.id, d.parent_id
                        ));
                    }
                }
            } else {
                if d.causal_depth != 0 {
                    errors.push(format!(
                        "Genesis decision '{}' must have causal_depth 0",
                        d.id
                    ));
                }
            }
        }

        // Check for unregistered actors (warnings, not errors)
        let mut warnings = Vec::new();
        let mut unique_actors: std::collections::HashSet<String> = std::collections::HashSet::new();
        for d in &decisions {
            unique_actors.insert(d.actor_id.clone());
        }
        for actor in &unique_actors {
            let registered: bool = self
                .conn
                .prepare("SELECT 1 FROM agents WHERE public_key = ?1 LIMIT 1")
                .and_then(|mut s| s.exists([actor]))
                .unwrap_or(false);
            if !registered {
                warnings.push(format!(
                    "Actor '{}' is not registered in the agents table.",
                    actor
                ));
            }
        }

        if errors.is_empty() {
            let mut result = serde_json::json!({
                "status": "valid",
                "message": "All decisions verified successfully.",
                "total_records": decisions.len(),
                "unique_actors": unique_actors.len()
            });
            if !warnings.is_empty() {
                result["warnings"] = serde_json::json!(warnings);
            }
            Ok(serde_json::to_string(&result).unwrap())
        } else {
            let mut result = serde_json::json!({
                "status": "invalid",
                "errors": errors,
                "total_records": decisions.len()
            });
            if !warnings.is_empty() {
                result["warnings"] = serde_json::json!(warnings);
            }
            Err(serde_json::to_string(&result).unwrap())
        }
    }

    /// Register an agent through a signed, immutable delegation event.
    ///
    /// The first registration bootstraps the gate key itself. Every later
    /// registration must be signed by an active agent with delegation rights.
    pub fn register_agent(
        &self,
        public_key: &str,
        alias: &str,
        metadata: &str,
    ) -> Result<String, String> {
        b2a::register_agent(self, public_key, alias, metadata)
    }

    /// Verify that an agent has a valid signed registration and is active.
    pub fn verify_agent(&self, public_key: &str) -> Result<bool, String> {
        b2a::verify_agent(self, public_key)
    }

    /// List registered agents and the validity of their registration receipts.
    pub fn list_agents(&self) -> Result<String, String> {
        b2a::list_agents(self)
    }

    /// Get a single registered agent.
    pub fn get_agent(&self, public_key: &str) -> Result<String, String> {
        b2a::get_agent(self, public_key)
    }

    /// Rotate an identity to a new Ed25519 verification key while retaining its stable ID.
    pub fn rotate_agent(
        &self,
        current_public_key: &str,
        new_public_key: &str,
    ) -> Result<String, String> {
        b2a::rotate_agent(self, current_public_key, new_public_key)
    }

    /// Revoke an active identity key and invalidate its unconsumed permits.
    pub fn revoke_agent(&self, public_key: &str, reason: &str) -> Result<String, String> {
        b2a::revoke_agent(self, public_key, reason)
    }

    /// List signed rotation and revocation events.
    pub fn list_identity_events(&self) -> Result<String, String> {
        b2a::list_identity_events(self)
    }

    /// Ask the Tempus gate for a single-use authorization receipt.
    pub fn request_action(
        &self,
        intent: &str,
        agent_keyfile: &str,
        ttl_seconds: u64,
    ) -> Result<String, String> {
        b2a::request_action(self, intent, agent_keyfile, ttl_seconds)
    }

    /// Lower-level transport-neutral authorization API for signed requests.
    pub fn request_action_signed(
        &self,
        intent: &str,
        agent_id: &str,
        agent_signature: &str,
        ttl_seconds: u64,
    ) -> Result<String, String> {
        b2a::request_action_signed(self, intent, agent_id, agent_signature, ttl_seconds)
    }

    /// Consume an allowed permit exactly once and append the executor outcome.
    pub fn commit_outcome(
        &self,
        authorization_id: &str,
        outcome: &str,
        executor_keyfile: &str,
    ) -> Result<String, String> {
        b2a::commit_outcome(self, authorization_id, outcome, executor_keyfile)
    }

    /// Consume an allowed permit exactly once with an already signed outcome.
    pub fn commit_outcome_signed(
        &self,
        authorization_id: &str,
        outcome: &str,
    ) -> Result<String, String> {
        b2a::commit_outcome_signed(self, authorization_id, outcome)
    }

    /// Return the authorization and optional execution receipt for an action.
    pub fn get_trace(&self, action_id: &str) -> Result<String, String> {
        b2a::get_trace(self, action_id)
    }

    /// Cryptographically verify an action trace end to end.
    pub fn verify_trace(&self, action_id: &str) -> Result<String, String> {
        b2a::verify_trace(self, action_id)
    }

    /// Verify an action trace against a gate public key pinned by the verifier
    /// (and optionally pinned executor keys). Does not trust the database's
    /// own trusted root.
    pub fn verify_trace_pinned(
        &self,
        action_id: &str,
        gate_public_key: &str,
        executor_public_keys: &[String],
    ) -> Result<String, String> {
        b2a::verify_trace_pinned(self, action_id, gate_public_key, executor_public_keys)
    }

    /// Export a self-contained evidence bundle for one action (see
    /// `tempus.evidence-bundle.v1`). Contains no private key material.
    pub fn export_bundle(
        &self,
        action_id: &str,
        max_stream_events: Option<u64>,
    ) -> Result<String, String> {
        b2a::export_bundle(self, action_id, max_stream_events)
    }

    /// Install and activate a deterministic policy bundle signed by the gate.
    pub fn install_policy(&self, policy_spec: &str) -> Result<String, String> {
        let spec = strict_json::parse_labeled(policy_spec, "policy")?;
        strict_json::reject_inexact_numbers(&spec, "policy")?;
        let signer = self.load_signer()?;
        let bundle = phase3::install_policy(&self.conn, &signer, &spec, b2a::now_micros()?)?;
        b2a::canonicalize(&bundle)
    }

    /// DEVELOPMENT ONLY. Explicitly install a signed policy that allows every action,
    /// resource and executor for every tenant without its own policy. Nothing installs
    /// this implicitly: without it (or a real policy) the gate answers BLOCKED with
    /// `POLICY_NOT_INSTALLED`. Idempotent while a current dev policy is active. A stored
    /// dev policy whose `allowed_currencies` is not a list of exact codes is left in
    /// place and refused on load (`TEMPUS_POLICY_INVALID`); only this call replaces it.
    pub fn install_allow_all_dev_policy(&self) -> Result<String, String> {
        let signer = self.load_signer()?;
        let bundle = phase3::install_allow_all_dev_policy(&self.conn, &signer, b2a::now_micros()?)?;
        b2a::canonicalize(&bundle)
    }

    /// List active and retired policy bundles.
    pub fn list_policies(&self) -> Result<String, String> {
        phase3::list_policies(&self.conn)
    }

    /// Exercise the configured local or remote signer with an offline-verifiable fixture.
    pub fn signer_conformance(&self) -> Result<String, String> {
        phase3::signer_conformance(&self.load_signer()?)
    }

    pub fn create_checkpoint(&self, tenant_id: &str) -> Result<String, String> {
        let signer = self.load_signer()?;
        let created_at = b2a::now_micros()?;
        events::create_checkpoint(&self.conn, &signer, tenant_id, created_at)
    }

    pub fn export_event_stream(
        &self,
        tenant_id: &str,
        from_sequence: u64,
        limit: u32,
    ) -> Result<String, String> {
        events::export_event_stream(&self.conn, tenant_id, from_sequence, limit)
    }

    pub fn verify_checkpoint_stream(
        &self,
        checkpoint_json: &str,
        stream_json: &str,
        expected_public_key: Option<&str>,
    ) -> Result<String, String> {
        let expected = match expected_public_key {
            Some(pk) => Some(pk.to_string()),
            None => self
                .load_signer()
                .ok()
                .map(|s| s.identity().public_key.clone())
                .or_else(|| {
                    self.conn
                        .query_row(
                            "SELECT public_key FROM trusted_roots WHERE id = 1",
                            [],
                            |r| r.get(0),
                        )
                        .ok()
                }),
        };
        events::verify_checkpoint_stream(checkpoint_json, stream_json, expected.as_deref())
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl StorageLayer for SqliteStorage {
    fn insert_decision(&mut self, payload: &str, rules: &str, genesis: bool) -> Result<(), String> {
        // Validate payload and rules are valid JSON
        serde_json::from_str::<serde_json::Value>(payload)
            .map_err(|e| format!("Payload is not valid JSON: {}", e))?;
        serde_json::from_str::<serde_json::Value>(rules)
            .map_err(|e| format!("Rules is not valid JSON: {}", e))?;

        // Load signing key from keyfile
        let signing_key = self.load_signing_key()?;
        let verifying_key = signing_key.verifying_key();
        let actor_id = hex::encode(verifying_key.to_bytes());

        let tx = self
            .conn
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|e| format!("Failed to begin transaction: {}", e))?;

        // Resolve parent_id and causal_depth
        let (parent_id, causal_depth) = match Self::get_last_decision_conn(&tx)? {
            Some(last_d) => {
                if genesis {
                    // Even if there are existing decisions, --genesis forces a new root
                    ("genesis".to_string(), 0u64)
                } else {
                    (last_d.id, last_d.causal_depth + 1)
                }
            }
            None => {
                if genesis {
                    ("genesis".to_string(), 0u64)
                } else {
                    return Err(
                        "Database is empty. Use genesis=true to record the first decision."
                            .to_string(),
                    );
                }
            }
        };

        if parent_id == "genesis" {
            let mut stmt = tx
                .prepare("SELECT 1 FROM decisions WHERE parent_id = 'genesis' LIMIT 1")
                .map_err(|e| format!("Prepare error: {}", e))?;
            let exists = stmt.exists([]).map_err(|e| format!("Query error: {}", e))?;
            if exists {
                return Err("A genesis decision already exists in the database.".to_string());
            }
        }

        // Timestamp in microseconds
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .map_err(|e| format!("System time error: {}", e))?
            .as_micros() as u64;

        // Compute the deterministic SHA-256 hash
        let hash_bytes =
            Self::calculate_canonical_hash(&parent_id, &actor_id, timestamp, payload, rules)?;
        let id = hex::encode(hash_bytes);

        // Ed25519 signature of the hash
        let signature_struct = signing_key.sign(&hash_bytes);
        let signature = hex::encode(signature_struct.to_bytes());

        // Insert into SQLite
        tx.execute(
            "INSERT INTO decisions (id, parent_id, causal_depth, actor_id, timestamp, payload, rules_evaluated, signature)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            (
                &id,
                &parent_id,
                causal_depth,
                &actor_id,
                timestamp,
                payload,
                rules,
                &signature,
            ),
        ).map_err(|e| format!("Failed to insert decision into SQLite: {}", e))?;

        tx.commit()
            .map_err(|e| format!("Failed to commit transaction: {}", e))?;

        Ok(())
    }

    fn insert_decision_batch(
        &mut self,
        decisions: Vec<(&str, &str)>,
        genesis: bool,
    ) -> Result<(), String> {
        if decisions.is_empty() {
            return Ok(());
        }

        let signing_key = self.load_signing_key()?;
        let verifying_key = signing_key.verifying_key();
        let actor_id = hex::encode(verifying_key.to_bytes());

        let tx = self
            .conn
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|e| format!("Failed to begin transaction: {}", e))?;

        let mut current_parent_id;
        let mut current_causal_depth;

        match Self::get_last_decision_conn(&tx)? {
            Some(last_d) => {
                if genesis {
                    current_parent_id = "genesis".to_string();
                    current_causal_depth = 0u64;
                } else {
                    current_parent_id = last_d.id;
                    current_causal_depth = last_d.causal_depth + 1;
                }
            }
            None => {
                if genesis {
                    current_parent_id = "genesis".to_string();
                    current_causal_depth = 0u64;
                } else {
                    return Err(
                        "Database is empty. Use genesis=true to record the first decision."
                            .to_string(),
                    );
                }
            }
        };

        if current_parent_id == "genesis" {
            let mut stmt = tx
                .prepare("SELECT 1 FROM decisions WHERE parent_id = 'genesis' LIMIT 1")
                .map_err(|e| format!("Prepare error: {}", e))?;
            let exists = stmt.exists([]).map_err(|e| format!("Query error: {}", e))?;
            if exists {
                return Err("A genesis decision already exists in the database.".to_string());
            }
        }

        for (payload, rules) in decisions {
            serde_json::from_str::<serde_json::Value>(payload)
                .map_err(|e| format!("Payload is not valid JSON: {}", e))?;
            serde_json::from_str::<serde_json::Value>(rules)
                .map_err(|e| format!("Rules is not valid JSON: {}", e))?;

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::SystemTime::UNIX_EPOCH)
                .map_err(|e| format!("System time error: {}", e))?
                .as_micros() as u64;

            let hash_bytes = Self::calculate_canonical_hash(
                &current_parent_id,
                &actor_id,
                timestamp,
                payload,
                rules,
            )?;
            let id = hex::encode(hash_bytes);

            let signature_struct = signing_key.sign(&hash_bytes);
            let signature = hex::encode(signature_struct.to_bytes());

            tx.execute(
                "INSERT INTO decisions (id, parent_id, causal_depth, actor_id, timestamp, payload, rules_evaluated, signature)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                (
                    &id,
                    &current_parent_id,
                    current_causal_depth,
                    &actor_id,
                    timestamp,
                    payload,
                    rules,
                    &signature,
                ),
            ).map_err(|e| format!("Failed to insert decision into SQLite: {}", e))?;

            current_parent_id = id;
            current_causal_depth += 1;
        }

        tx.commit()
            .map_err(|e| format!("Failed to commit transaction: {}", e))?;

        Ok(())
    }

    fn get_latest_hash(&self) -> Result<String, String> {
        let mut stmt = self
            .conn
            .prepare("SELECT id FROM decisions ORDER BY causal_depth DESC, timestamp DESC LIMIT 1")
            .map_err(|e| format!("Failed to prepare select statement: {}", e))?;

        let mut rows = stmt
            .query([])
            .map_err(|e| format!("Failed to query database: {}", e))?;
        if let Some(row) = rows
            .next()
            .map_err(|e| format!("Error advancing row: {}", e))?
        {
            let id: String = row.get(0).unwrap();
            Ok(id)
        } else {
            Ok("GENESIS".to_string())
        }
    }

    fn export_ledger(&self) -> Result<String, String> {
        let mut stmt = self.conn.prepare(
            "SELECT id, parent_id, causal_depth, actor_id, timestamp, payload, rules_evaluated, signature
             FROM decisions
             ORDER BY causal_depth ASC, timestamp ASC"
        ).map_err(|e| format!("Failed to prepare select statement: {}", e))?;

        let rows = stmt
            .query_map([], |row| {
                Ok(Decision {
                    id: row.get(0)?,
                    parent_id: row.get(1)?,
                    causal_depth: row.get(2)?,
                    actor_id: row.get(3)?,
                    timestamp: row.get(4)?,
                    payload: row.get(5)?,
                    rules_evaluated: row.get(6)?,
                    signature: row.get(7)?,
                })
            })
            .map_err(|e| format!("Failed to execute query: {}", e))?;

        let mut decisions = Vec::new();
        for r in rows {
            match r {
                Ok(d) => decisions.push(d),
                Err(e) => return Err(format!("Error reading record: {}", e)),
            }
        }

        serde_json::to_string(&decisions)
            .map_err(|e| format!("Failed to serialize ledger to JSON: {}", e))
    }

    fn list_decisions(&self, limit: u32, offset: u32) -> Result<String, String> {
        let mut stmt = self.conn.prepare(
            "SELECT id, parent_id, causal_depth, actor_id, timestamp, payload, rules_evaluated, signature
             FROM decisions
             ORDER BY causal_depth DESC, timestamp DESC
             LIMIT ?1 OFFSET ?2"
        ).map_err(|e| format!("Failed to prepare select statement: {}", e))?;

        let rows = stmt
            .query_map([limit, offset], |row| {
                Ok(Decision {
                    id: row.get(0)?,
                    parent_id: row.get(1)?,
                    causal_depth: row.get(2)?,
                    actor_id: row.get(3)?,
                    timestamp: row.get(4)?,
                    payload: row.get(5)?,
                    rules_evaluated: row.get(6)?,
                    signature: row.get(7)?,
                })
            })
            .map_err(|e| format!("Failed to execute query: {}", e))?;

        let mut decisions = Vec::new();
        for r in rows {
            match r {
                Ok(d) => decisions.push(d),
                Err(e) => return Err(format!("Error reading record: {}", e)),
            }
        }

        serde_json::to_string(&decisions)
            .map_err(|e| format!("Failed to serialize decisions to JSON: {}", e))
    }

    fn count_decisions(&self) -> Result<u64, String> {
        let mut stmt = self
            .conn
            .prepare("SELECT COUNT(*) FROM decisions")
            .map_err(|e| format!("Failed to prepare count statement: {}", e))?;
        let count: u64 = stmt
            .query_row([], |row| row.get(0))
            .map_err(|e| format!("Failed to count decisions: {}", e))?;
        Ok(count)
    }
}
// --- 3. BINDINGS PARA PYTHON (PYO3) ---
#[cfg(not(target_arch = "wasm32"))]
#[pyclass(unsendable)]
pub struct TempusDDB {
    storage: SqliteStorage,
    #[allow(dead_code)]
    keyfile: String,
}

#[cfg(not(target_arch = "wasm32"))]
#[allow(clippy::useless_conversion)]
#[pymethods]
impl TempusDDB {
    #[new]
    fn new(db_path: String, keyfile: String) -> PyResult<Self> {
        let storage =
            SqliteStorage::new(db_path, keyfile.clone()).map_err(PyPermissionError::new_err)?;

        if std::path::Path::new(&keyfile).exists() {
            storage.load_signer().map_err(PyPermissionError::new_err)?;
        }

        Ok(TempusDDB { storage, keyfile })
    }

    #[allow(unused_variables)]
    #[pyo3(signature = (payload, rules, genesis=false))]
    fn record(&mut self, payload: &str, rules: &str, genesis: bool) -> PyResult<String> {
        self.storage
            .insert_decision(payload, rules, genesis)
            .map_err(PyPermissionError::new_err)?;

        let result_json = format!(
            r#"{{"status": "success", "action": "recorded", "latest_hash": "{}"}}"#,
            self.storage.get_latest_hash().unwrap_or_default()
        );
        Ok(result_json)
    }

    #[allow(unused_variables)]
    #[pyo3(signature = (decisions, genesis=false))]
    fn record_batch(
        &mut self,
        decisions: Vec<(String, String)>,
        genesis: bool,
    ) -> PyResult<String> {
        let refs: Vec<(&str, &str)> = decisions
            .iter()
            .map(|(p, r)| (p.as_str(), r.as_str()))
            .collect();
        self.storage
            .insert_decision_batch(refs, genesis)
            .map_err(PyPermissionError::new_err)?;

        let result_json = format!(
            r#"{{"status": "success", "action": "recorded_batch", "latest_hash": "{}"}}"#,
            self.storage.get_latest_hash().unwrap_or_default()
        );
        Ok(result_json)
    }

    #[pyo3(signature = ())]
    fn validate(&self) -> PyResult<String> {
        self.storage
            .validate_ledger()
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = ())]
    fn export(&self) -> PyResult<String> {
        self.storage
            .export_ledger()
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (limit=10, offset=0))]
    fn list(&self, limit: u32, offset: u32) -> PyResult<String> {
        self.storage
            .list_decisions(limit, offset)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = ())]
    fn count(&self) -> PyResult<u64> {
        self.storage
            .count_decisions()
            .map_err(PyRuntimeError::new_err)
    }

    // --- Multi-Signer: Agent management ---

    #[pyo3(signature = (public_key, alias, metadata="{}".to_string()))]
    fn register_agent(&self, public_key: &str, alias: &str, metadata: String) -> PyResult<String> {
        self.storage
            .register_agent(public_key, alias, &metadata)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = ())]
    fn list_agents(&self) -> PyResult<String> {
        self.storage.list_agents().map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (public_key,))]
    fn get_agent(&self, public_key: &str) -> PyResult<String> {
        self.storage
            .get_agent(public_key)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (current_public_key, new_public_key))]
    fn rotate_agent(&self, current_public_key: &str, new_public_key: &str) -> PyResult<String> {
        self.storage
            .rotate_agent(current_public_key, new_public_key)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (public_key, reason))]
    fn revoke_agent(&self, public_key: &str, reason: &str) -> PyResult<String> {
        self.storage
            .revoke_agent(public_key, reason)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = ())]
    fn list_identity_events(&self) -> PyResult<String> {
        self.storage
            .list_identity_events()
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (public_key,))]
    fn verify_agent(&self, public_key: &str) -> PyResult<bool> {
        self.storage
            .verify_agent(public_key)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (intent, agent_keyfile, ttl_seconds=60))]
    fn request_action(
        &self,
        intent: &str,
        agent_keyfile: &str,
        ttl_seconds: u64,
    ) -> PyResult<String> {
        self.storage
            .request_action(intent, agent_keyfile, ttl_seconds)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (intent, agent_id, agent_signature, ttl_seconds=60))]
    fn request_action_signed(
        &self,
        intent: &str,
        agent_id: &str,
        agent_signature: &str,
        ttl_seconds: u64,
    ) -> PyResult<String> {
        self.storage
            .request_action_signed(intent, agent_id, agent_signature, ttl_seconds)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (authorization_id, outcome, executor_keyfile))]
    fn commit_outcome(
        &self,
        authorization_id: &str,
        outcome: &str,
        executor_keyfile: &str,
    ) -> PyResult<String> {
        self.storage
            .commit_outcome(authorization_id, outcome, executor_keyfile)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (authorization_id, outcome))]
    fn commit_outcome_signed(&self, authorization_id: &str, outcome: &str) -> PyResult<String> {
        self.storage
            .commit_outcome_signed(authorization_id, outcome)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (action_id,))]
    fn get_trace(&self, action_id: &str) -> PyResult<String> {
        self.storage
            .get_trace(action_id)
            .map_err(PyRuntimeError::new_err)
    }

    /// Verify an action trace. With `gate_public_key` the gate key is pinned by
    /// the caller and the database's own trusted root is not used; without it the
    /// result is marked `"independent": false`.
    #[pyo3(signature = (action_id, gate_public_key=None, executor_public_keys=None))]
    fn verify_trace(
        &self,
        action_id: &str,
        gate_public_key: Option<&str>,
        executor_public_keys: Option<Vec<String>>,
    ) -> PyResult<String> {
        match gate_public_key {
            Some(gate) => self.storage.verify_trace_pinned(
                action_id,
                gate,
                &executor_public_keys.unwrap_or_default(),
            ),
            None if executor_public_keys.is_some() => {
                Err("executor_public_keys requires gate_public_key".to_string())
            }
            None => self.storage.verify_trace(action_id),
        }
        .map_err(PyRuntimeError::new_err)
    }

    /// Export one action as a self-contained evidence bundle (JSON string).
    #[pyo3(signature = (action_id, max_stream_events=None))]
    fn export_bundle(&self, action_id: &str, max_stream_events: Option<u64>) -> PyResult<String> {
        self.storage
            .export_bundle(action_id, max_stream_events)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (policy_spec,))]
    fn install_policy(&self, policy_spec: &str) -> PyResult<String> {
        self.storage
            .install_policy(policy_spec)
            .map_err(PyRuntimeError::new_err)
    }

    /// DEVELOPMENT ONLY: explicitly install an allow-all policy (emits a UserWarning).
    #[pyo3(signature = ())]
    fn install_allow_all_dev_policy(&self, py: Python<'_>) -> PyResult<String> {
        let bundle = self
            .storage
            .install_allow_all_dev_policy()
            .map_err(PyRuntimeError::new_err)?;
        PyErr::warn(
            py,
            &py.get_type::<pyo3::exceptions::PyUserWarning>(),
            c"tempus: allow-all development policy installed; every action is ALLOWED. \
              Do not use in production: install a real policy with install_policy().",
            1,
        )?;
        Ok(bundle)
    }

    #[pyo3(signature = ())]
    fn list_policies(&self) -> PyResult<String> {
        self.storage
            .list_policies()
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = ())]
    fn signer_conformance(&self) -> PyResult<String> {
        self.storage
            .signer_conformance()
            .map_err(PyRuntimeError::new_err)
    }

    /// Return the public key of the current keyfile ("who am I?").
    #[pyo3(signature = ())]
    fn whoami(&self) -> PyResult<String> {
        let signer = self
            .storage
            .load_signer()
            .map_err(PyRuntimeError::new_err)?;
        use crate::phase3::SignerBackend;
        let identity = signer.identity();
        let public_key = identity.public_key.clone();

        // Try to find the agent alias
        let alias = match self.storage.get_agent(&public_key) {
            Ok(json_str) => serde_json::from_str::<serde_json::Value>(&json_str)
                .ok()
                .and_then(|v| v["alias"].as_str().map(|s| s.to_string()))
                .unwrap_or_default(),
            Err(_) => String::new(),
        };

        Ok(serde_json::to_string(&serde_json::json!({
            "public_key": public_key,
            "alias": alias,
            "keyfile": self.keyfile,
            "signer_uri": identity.signer_uri,
            "key_version": identity.key_version,
            "algorithm": identity.algorithm,
        }))
        .unwrap())
    }

    #[pyo3(signature = (tenant_id="*".to_string()))]
    fn create_checkpoint(&self, tenant_id: String) -> PyResult<String> {
        self.storage
            .create_checkpoint(&tenant_id)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (tenant_id="*".to_string(), from_sequence=1, limit=1000))]
    fn export_event_stream(
        &self,
        tenant_id: String,
        from_sequence: u64,
        limit: u32,
    ) -> PyResult<String> {
        self.storage
            .export_event_stream(&tenant_id, from_sequence, limit)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (checkpoint_json, stream_json, expected_public_key=None))]
    fn verify_checkpoint_stream(
        &self,
        checkpoint_json: &str,
        stream_json: &str,
        expected_public_key: Option<&str>,
    ) -> PyResult<String> {
        self.storage
            .verify_checkpoint_stream(checkpoint_json, stream_json, expected_public_key)
            .map_err(PyRuntimeError::new_err)
    }
}

/// Verify a standalone receipt (trace, permit or outcome JSON) with no database,
/// against a gate public key pinned by the verifier.
#[cfg(not(target_arch = "wasm32"))]
pub fn verify_receipt(
    receipt_json: &str,
    gate_public_key: &str,
    executor_public_keys: &[String],
) -> Result<String, String> {
    b2a::verify_receipt_pinned(receipt_json, gate_public_key, executor_public_keys)
}

/// Verify an evidence bundle with no database, against a pinned gate public key.
#[cfg(not(target_arch = "wasm32"))]
pub fn verify_bundle(
    bundle_json: &str,
    gate_public_key: &str,
    executor_public_keys: &[String],
) -> Result<String, String> {
    b2a::verify_bundle_pinned(bundle_json, gate_public_key, executor_public_keys)
}

/// Verify a checkpoint and its event stream with no database. The signer must
/// equal `expected_public_key`, which the verifier supplies out of band.
#[cfg(not(target_arch = "wasm32"))]
pub fn verify_checkpoint(
    checkpoint_json: &str,
    stream_json: &str,
    expected_public_key: &str,
) -> Result<String, String> {
    let expected = expected_public_key.trim().to_ascii_lowercase();
    b2a::decode_public_key(&expected).map_err(|e| format!("gate public key: {e}"))?;
    events::verify_checkpoint_stream(checkpoint_json, stream_json, Some(&expected))
}

#[cfg(not(target_arch = "wasm32"))]
pub fn generate_keypair(output: &str) -> Result<String, String> {
    use ed25519_dalek::SigningKey;
    use rand::rngs::OsRng;
    use std::fs::File;
    use std::io::Write;

    #[derive(Serialize)]
    struct KeyPairConfig {
        public_key: String,
        private_key: String,
    }

    let mut csprng = OsRng;
    let signing_key = SigningKey::generate(&mut csprng);
    let verifying_key = signing_key.verifying_key();

    let config = KeyPairConfig {
        public_key: hex::encode(verifying_key.to_bytes()),
        private_key: hex::encode(signing_key.to_bytes()),
    };

    let json_str =
        serde_json::to_string_pretty(&config).map_err(|e| format!("Serialization error: {}", e))?;

    let mut file =
        File::create(output).map_err(|e| format!("Error creating key file {}: {}", output, e))?;

    file.write_all(json_str.as_bytes())
        .map_err(|e| format!("Error writing key file {}: {}", output, e))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let perms = std::fs::Permissions::from_mode(0o600);
        if let Err(e) = std::fs::set_permissions(output, perms) {
            eprintln!("Warning: Could not set key file permissions: {}", e);
        }
    }

    Ok(json_str)
}

#[cfg(not(target_arch = "wasm32"))]
#[pyfunction]
#[allow(clippy::useless_conversion)]
pub fn gen_keys(output: String) -> PyResult<String> {
    generate_keypair(&output).map_err(PyRuntimeError::new_err)
}

/// Verify a standalone receipt (trace, permit or outcome JSON) without a database.
#[cfg(not(target_arch = "wasm32"))]
#[pyfunction]
#[pyo3(name = "verify_receipt", signature = (receipt_json, gate_public_key, executor_public_keys=None))]
#[allow(clippy::useless_conversion)]
pub fn py_verify_receipt(
    receipt_json: &str,
    gate_public_key: &str,
    executor_public_keys: Option<Vec<String>>,
) -> PyResult<String> {
    verify_receipt(
        receipt_json,
        gate_public_key,
        &executor_public_keys.unwrap_or_default(),
    )
    .map_err(PyRuntimeError::new_err)
}

/// Verify an evidence bundle without a database, against a pinned gate key.
#[cfg(not(target_arch = "wasm32"))]
#[pyfunction]
#[pyo3(name = "verify_bundle", signature = (bundle_json, gate_public_key, executor_public_keys=None))]
#[allow(clippy::useless_conversion)]
pub fn py_verify_bundle(
    bundle_json: &str,
    gate_public_key: &str,
    executor_public_keys: Option<Vec<String>>,
) -> PyResult<String> {
    verify_bundle(
        bundle_json,
        gate_public_key,
        &executor_public_keys.unwrap_or_default(),
    )
    .map_err(PyRuntimeError::new_err)
}

/// Verify a checkpoint and event stream without a database, against a pinned key.
#[cfg(not(target_arch = "wasm32"))]
#[pyfunction]
#[pyo3(name = "verify_checkpoint", signature = (checkpoint_json, stream_json, expected_public_key))]
#[allow(clippy::useless_conversion)]
pub fn py_verify_checkpoint(
    checkpoint_json: &str,
    stream_json: &str,
    expected_public_key: &str,
) -> PyResult<String> {
    verify_checkpoint(checkpoint_json, stream_json, expected_public_key)
        .map_err(PyRuntimeError::new_err)
}

#[cfg(not(target_arch = "wasm32"))]
#[pymodule]
fn _tempus_ddb(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(py_verify_receipt, m)?)?;
    m.add_function(wrap_pyfunction!(py_verify_bundle, m)?)?;
    m.add_function(wrap_pyfunction!(py_verify_checkpoint, m)?)?;
    m.add_class::<TempusDDB>()?;
    m.add_class::<TempusExecutor>()?;
    m.add_function(wrap_pyfunction!(gen_keys, m)?)?;
    Ok(())
}

// --- 4. BINDINGS PARA JAVASCRIPT (WASM-BINDGEN) ---
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub struct TempusDDBWasm {
    storage: MemoryStorage,
    keyfile: String,
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
impl TempusDDBWasm {
    #[wasm_bindgen(constructor)]
    pub fn new(keyfile: String) -> Result<TempusDDBWasm, JsValue> {
        let storage = MemoryStorage::new();
        Ok(TempusDDBWasm { storage, keyfile })
    }

    #[wasm_bindgen]
    pub fn record(&mut self, payload: &str, rules: &str, genesis: bool) -> Result<String, JsValue> {
        self.storage
            .insert_decision(payload, rules, genesis)
            .map_err(|e| JsValue::from_str(&e))?;

        let result_json = format!(
            r#"{{"status": "success", "action": "recorded", "latest_hash": "{}"}}"#,
            self.storage.get_latest_hash().unwrap_or_default()
        );
        Ok(result_json)
    }

    #[wasm_bindgen]
    pub fn get_ledger(&self) -> Result<String, JsValue> {
        self.storage
            .export_ledger()
            .map_err(|e| JsValue::from_str(&e))
    }
}

#[cfg(not(target_arch = "wasm32"))]
mod executor;

#[cfg(not(target_arch = "wasm32"))]
use executor::{MediatedExecutor, SqliteExecutorStorage};

#[cfg(not(target_arch = "wasm32"))]
#[pyclass(unsendable)]
pub struct TempusExecutor {
    inner: MediatedExecutor,
}

#[cfg(not(target_arch = "wasm32"))]
#[pymethods]
impl TempusExecutor {
    #[new]
    #[pyo3(signature = (db_path, keyfile, trusted_gate_id, trusted_tenant_id, pool_size=8, gate_db=None))]
    pub fn new(
        db_path: String,
        keyfile: String,
        trusted_gate_id: String,
        trusted_tenant_id: String,
        pool_size: u32,
        gate_db: Option<String>,
    ) -> PyResult<Self> {
        let storage = SqliteExecutorStorage::with_pool_size(&db_path, pool_size)
            .map_err(PyRuntimeError::new_err)?;
        let gate_db_final = gate_db.or_else(|| std::env::var("TEMPUS_GATE_DB").ok());
        let mut inner = MediatedExecutor::new(
            Box::new(storage),
            &keyfile,
            &trusted_gate_id,
            &trusted_tenant_id,
        )
        .map_err(PyRuntimeError::new_err)?;
        inner = inner.with_gate_db(gate_db_final);
        Ok(Self { inner })
    }

    pub fn verify_and_consume_permit(&self, permit_json: String) -> PyResult<String> {
        let auth = self
            .inner
            .verify_and_consume_permit(&permit_json)
            .map_err(PyPermissionError::new_err)?;
        Ok(serde_json::to_string(&auth).unwrap())
    }

    pub fn complete_execution(
        &self,
        authorization_id: String,
        action_id: String,
        status: String,
        output_json: String,
    ) -> PyResult<String> {
        let output: serde_json::Value = serde_json::from_str(&output_json)
            .map_err(|e| PyRuntimeError::new_err(format!("Invalid output JSON: {}", e)))?;

        let outcome = self
            .inner
            .complete_execution(&authorization_id, &action_id, &status, output)
            .map_err(PyRuntimeError::new_err)?;

        Ok(outcome)
    }

    pub fn mark_unknown(&self, authorization_id: String, reason: String) -> PyResult<String> {
        self.inner
            .mark_unknown(&authorization_id, &reason)
            .map_err(PyRuntimeError::new_err)
    }

    #[pyo3(signature = (older_than_seconds=0))]
    pub fn recover_incomplete(&self, older_than_seconds: u64) -> PyResult<String> {
        self.inner
            .recover_incomplete(older_than_seconds)
            .map_err(PyRuntimeError::new_err)
    }

    pub fn get_execution_state(&self, authorization_id: String) -> PyResult<String> {
        self.inner
            .get_execution_state(&authorization_id)
            .map_err(PyRuntimeError::new_err)
    }
}