sysknife-daemon 0.29.0

Policy-enforced, audit-logged Linux action daemon for SysKnife
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
//! Postgres backend for the audit log.
//!
//! Wire-compatible with AWS RDS / Aurora, GCP Cloud SQL + AlloyDB, Azure
//! Database for PostgreSQL Flexible Server, Supabase (direct + pooler),
//! Neon (direct + pooler), and self-hosted Postgres.
//!
//! ## Connection lifecycle
//!
//! [`PostgresStore::connect`] takes a [`PostgresConfig`] (URL plus pool +
//! statement-cache tuning) and returns a configured `sqlx::PgPool`. The
//! same pool is used for every request — sqlx handles connection reuse,
//! retry on broken connections, and TLS via rustls.
//!
//! On connect, `PostgresStore::initialize` runs ordered, transactional schema
//! migrations under a database advisory lock. The schema mirrors SQLite
//! field-for-field; the only dialect
//! difference is `BIGINT NOT NULL UNIQUE` for `seq`. `created_at` remains
//! `TEXT` (RFC 3339 with `Z` suffix) in both backends and is cast to
//! `timestamptz` for interval arithmetic.
//!
//! ## Concurrency
//!
//! Like the SQLite path, the chain-hash + seq computation is wrapped in a
//! `BEGIN ... COMMIT` block. Postgres serialises this naturally via
//! row-level locks on the `seq` write; we use a `SELECT … FOR UPDATE` on
//! the most-recent row so concurrent writers see the same predecessor and
//! the second commit fails atomically rather than corrupting the chain.

use async_trait::async_trait;
use sqlx_core::row::Row;
use sqlx_postgres::{PgConnectOptions, PgPool, PgPoolOptions};
use std::str::FromStr;
use std::time::Duration;
use subtle::ConstantTimeEq;
use sysknife_types::{JobState, PreviewEnvelope, TransactionRecord};
use uuid::Uuid;

use crate::audit_chain::{
    AttributionCensus, AuditEventKind, AuditKey, AuditVerification, BindingOutcome, ChainContent,
    ChainIdentity, ChainRow, EventContent, EventIdentity, EventRow, StatusEvidence, StatusOutcome,
    VerifyOutcome, CURRENT_KEY_ID,
};
use crate::audit_watermark::emit_chain_tip_watermark;
use crate::auth::CallerPrincipal;
use crate::store::AuditStore;
use crate::transactions::{
    HistorySince, NewTransaction, RecordedPreviewedTransaction, TransactionStoreError,
    APPROVAL_RECEIPT_TTL_MINUTES,
};

const MIGRATION_LOCK_ID: i64 = 0x5359_534b_4e49_4645;

/// Column list every `ChainRow` read shares, declared once in `store.rs`
/// (#397) and kept next to `row_to_chain_row` here by import.
///
/// The two read paths each spelled the list out. Adding the caller-identity
/// columns updated the mapper and one of the two queries, and the miss showed
/// up only as a runtime "no column found for name: chain_version" from the
/// live-Postgres test — the unit tests, which never touch this SQL, stayed
/// green. That history now lives on the single declaration.
use crate::store::CHAIN_ROW_COLUMNS;
use crate::store::{APPROVAL_CONSUMED_SQL, NEWEST_STATUS_EVENT_SQL};

struct Migration {
    version: i64,
    name: &'static str,
    statements: &'static [&'static str],
}

const MIGRATIONS: &[Migration] = &[Migration {
    version: 1,
    name: "initial_audit_schema",
    statements: &[
        r#"
        CREATE TABLE IF NOT EXISTS transactions (
            transaction_id TEXT PRIMARY KEY,
            request_id TEXT NOT NULL,
            request_hash TEXT NOT NULL,
            action_name TEXT NOT NULL,
            risk_level TEXT NOT NULL,
            status TEXT NOT NULL,
            approval_id TEXT,
            summary TEXT NOT NULL,
            warnings_json TEXT NOT NULL,
            created_at TEXT NOT NULL,
            seq BIGINT NOT NULL UNIQUE,
            key_id TEXT NOT NULL,
            chain_hash TEXT NOT NULL,
            prev_chain_hash TEXT NOT NULL DEFAULT ''
        )
        "#,
        r#"
        CREATE TABLE IF NOT EXISTS transaction_approvals (
            transaction_id TEXT PRIMARY KEY,
            receipt_digest TEXT NOT NULL,
            approved_at TEXT NOT NULL,
            consumed_at TEXT
        )
        "#,
        r#"
        CREATE TABLE IF NOT EXISTS transaction_previews (
            transaction_id TEXT PRIMARY KEY,
            preview_json TEXT NOT NULL
        )
        "#,
        "CREATE INDEX IF NOT EXISTS transactions_seq_idx ON transactions(seq)",
    ],
},
    // Mirrors SQLITE_MIGRATIONS v2 in `transactions.rs`. The columns are
    // nullable with a legacy default because rows written by an earlier binary
    // were signed over an encoding without them — see `ChainIdentity`.
    Migration {
        version: 2,
        name: "caller_identity_and_approval_events",
        statements: &[
            "ALTER TABLE transactions ADD COLUMN IF NOT EXISTS chain_version BIGINT NOT NULL DEFAULT 1",
            "ALTER TABLE transactions ADD COLUMN IF NOT EXISTS caller_role TEXT",
            "ALTER TABLE transactions ADD COLUMN IF NOT EXISTS event_tip TEXT",
            r#"
            CREATE TABLE IF NOT EXISTS audit_events (
                seq BIGINT PRIMARY KEY,
                key_id TEXT NOT NULL,
                kind TEXT NOT NULL,
                transaction_id TEXT NOT NULL,
                receipt_digest TEXT NOT NULL,
                created_at TEXT NOT NULL,
                chain_hash TEXT NOT NULL,
                prev_chain_hash TEXT NOT NULL DEFAULT ''
            )
            "#,
            "CREATE INDEX IF NOT EXISTS audit_events_transaction_idx ON audit_events(transaction_id)",
        ],
    },
    // Mirrors SQLite migration 3. Nullable for the same reason: rows written
    // before this step were signed over an encoding with no principal, so any
    // backfill would rewrite their message and report the chain as Broken.
    Migration {
        version: 3,
        name: "caller_principal",
        statements: &["ALTER TABLE transactions ADD COLUMN IF NOT EXISTS caller_principal TEXT"],
    },
    // Mirrors SQLite migration 4 (#249). Approver identity in the signed
    // event encoding: `chain_version DEFAULT 1` keeps every historical event
    // row on the six-field LegacyV1 encoding without touching it; new
    // approval events are written at version 2 with the acting account
    // signed in. Nullable, never backfilled, for the migration-2 reason.
    Migration {
        version: 4,
        name: "event_approver_identity",
        statements: &[
            "ALTER TABLE audit_events ADD COLUMN IF NOT EXISTS chain_version BIGINT NOT NULL DEFAULT 1",
            "ALTER TABLE audit_events ADD COLUMN IF NOT EXISTS caller_principal TEXT",
        ],
    },
    // Postgres only, with no SQLite twin. Through 0.26.1 this backend chained
    // no status event, so every terminal row written before this step has
    // none, and the status cross-check's rule that an unsigned terminal status
    // is a contradiction would report every upgraded store as tampered. Rows
    // present now read `TRUE` from the column default; the second statement
    // flips the default so every row written afterwards is held to that rule.
    Migration {
        version: 5,
        name: "status_event_boundary",
        statements: &[
            "ALTER TABLE transactions ADD COLUMN IF NOT EXISTS predates_status_events BOOLEAN NOT NULL DEFAULT TRUE",
            "ALTER TABLE transactions ALTER COLUMN predates_status_events SET DEFAULT FALSE",
        ],
    },
];

/// Configuration for the Postgres backend. Built by `main.rs` from
/// `[storage]` in `config.toml`.
#[derive(Clone, Debug)]
pub struct PostgresConfig {
    /// `postgres://...` URL. SSL mode and other knobs are encoded here.
    pub url: String,
    /// Maximum pool size. 8 is comfortable for a single SysKnife daemon;
    /// raise if multiple shells run concurrently.
    pub max_connections: u32,
    /// `acquire_timeout` for getting a connection from the pool. Raise above
    /// the default 5s if you hit Neon cold starts (~600 ms first call).
    pub acquire_timeout: Duration,
    /// Set to 0 for transaction-mode PgBouncer (including some hosted
    /// poolers), which cannot use sqlx's per-connection prepared-statement
    /// cache. Default 100 covers direct Postgres connections.
    pub statement_cache_capacity: usize,
}

impl Default for PostgresConfig {
    fn default() -> Self {
        Self {
            url: String::new(),
            max_connections: 8,
            acquire_timeout: Duration::from_secs(10),
            statement_cache_capacity: 100,
        }
    }
}

/// Postgres-backed [`AuditStore`].
#[derive(Debug, Clone)]
pub struct PostgresStore {
    pool: PgPool,
    audit_key: std::sync::Arc<AuditKey>,
}

struct InsertedTransaction {
    record: TransactionRecord,
    seq: u64,
    chain_hash: String,
}

impl PostgresStore {
    async fn connect_pool(config: &PostgresConfig) -> Result<PgPool, TransactionStoreError> {
        let mut connect_opts = PgConnectOptions::from_str(&config.url).map_err(|e| {
            TransactionStoreError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("invalid postgres URL: {e}"),
            ))
        })?;
        // Refuse a remote connection that could leak the credential (#149). This
        // is a hard configuration refusal, not a transient I/O error: it fails
        // daemon startup and is never retried. It is mapped onto Io(PermissionDenied)
        // only because that is the closest existing variant; nothing branches on
        // the ErrorKind for this path.
        crate::pg_tls::require_tls_for_remote(&connect_opts).map_err(|msg| {
            TransactionStoreError::Io(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                msg,
            ))
        })?;
        connect_opts = connect_opts.statement_cache_capacity(config.statement_cache_capacity);
        PgPoolOptions::new()
            .max_connections(config.max_connections)
            .acquire_timeout(config.acquire_timeout)
            .connect_with(connect_opts)
            .await
            .map_err(map_sqlx_err)
    }

    /// Connect to the configured Postgres database, run the migration,
    /// and bind an audit key for chain computation.
    pub async fn connect(
        config: &PostgresConfig,
        audit_key: std::sync::Arc<AuditKey>,
    ) -> Result<Self, TransactionStoreError> {
        let pool = Self::connect_pool(config).await?;

        let store = Self { pool, audit_key };
        store.initialize().await?;
        Ok(store)
    }

    /// Verify an existing Postgres chain — transaction chain, approval-event
    /// chain, and the binding between them — with only the exported public
    /// key. This path performs no migrations and never loads the signing key.
    pub async fn verify_all_with_pubkey(
        config: &PostgresConfig,
        verifying_key_hex: &str,
    ) -> Result<AuditVerification, TransactionStoreError> {
        let pool = Self::connect_pool(config).await?;
        let tx_rows = fetch_chain_rows_from_pool(&pool).await?;
        let event_rows = match fetch_event_rows_from_pool(&pool).await {
            Ok(rows) => rows,
            Err(err) => {
                // A chain written before the migration has no `audit_events`
                // table. That is an absent feature, not a missing verification:
                // report zero events rather than failing the whole verify.
                //
                // That is the ONLY reason to carry on. This used to be
                // `unwrap_or_default()`, which also swallowed a revoked SELECT,
                // a dropped table, a lost connection and a malformed row — each
                // becoming "zero approval events", which is either a clean bill
                // for a trail nobody read or, when a transaction row commits a
                // non-empty event tip, a `MissingEvent` binding published in the
                // words operators are taught to read as deleted approvals.
                //
                // So ask specifically whether the table is absent, and fail
                // closed on everything else, including a probe that cannot
                // answer: an audit tool that cannot read its evidence must say
                // so rather than grade it.
                match audit_events_table_absent(&pool).await {
                    Ok(true) => Vec::new(),
                    Ok(false) => {
                        return Ok(Self::unreadable_events(
                            verifying_key_hex,
                            &tx_rows,
                            format!("could not read the approval-event table: {err}"),
                        ))
                    }
                    Err(probe_err) => {
                        return Ok(Self::unreadable_events(
                            verifying_key_hex,
                            &tx_rows,
                            format!(
                                "could not read the approval-event table ({err}), and could not \
                                 determine whether it exists ({probe_err})"
                            ),
                        ))
                    }
                }
            }
        };
        let mut verification =
            crate::audit_chain::verify_all_with_pubkey(verifying_key_hex, &tx_rows, &event_rows);
        verification.status = Some(status_verdict(&pool).await);
        Ok(verification)
    }

    /// The transaction chain still verifies on its own — report it — but the
    /// event chain was not read, so its verdict is inconclusive and the binding
    /// check between the two did not run. `NotChecked` is what keeps that
    /// distinct from a binding that ran over zero events and agreed.
    fn unreadable_events(
        verifying_key_hex: &str,
        tx_rows: &[ChainRow],
        reason: String,
    ) -> AuditVerification {
        AuditVerification {
            chain: crate::audit_chain::verify_chain_with_pubkey(verifying_key_hex, tx_rows),
            // The status events live in the table that could not be read, so
            // the cross-check has nothing to compare the column with.
            status: Some(StatusOutcome::CannotVerify {
                detail: format!("status cross-check not run: {reason}"),
            }),
            events: VerifyOutcome::CannotVerify { reason },
            binding: BindingOutcome::NotChecked,
            attribution: Some(AttributionCensus::of(tx_rows)),
        }
    }

    /// Read the transaction chain without a signing key or schema mutation.
    /// Used by `sysknife audit export`, which must never acquire signing
    /// capability merely to serialize rows that already exist.
    pub async fn read_chain_rows(
        config: &PostgresConfig,
    ) -> Result<Vec<ChainRow>, TransactionStoreError> {
        let pool = Self::connect_pool(config).await?;
        fetch_chain_rows_from_pool(&pool).await
    }

    /// All three checks with the daemon's key.
    pub async fn verify_all(
        &self,
        key: &AuditKey,
    ) -> Result<AuditVerification, TransactionStoreError> {
        let tx_rows = fetch_chain_rows_from_pool(&self.pool).await?;
        let event_rows = fetch_event_rows_from_pool(&self.pool).await?;
        let mut verification = crate::audit_chain::verify_all(key, &tx_rows, &event_rows);
        verification.status = Some(status_verdict(&self.pool).await);
        Ok(verification)
    }

    /// Apply pending schema migrations atomically. The advisory transaction
    /// lock serializes concurrent daemon starts against the same database.
    async fn initialize(&self) -> Result<(), TransactionStoreError> {
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        sqlx_core::query::query("SELECT pg_advisory_xact_lock($1)")
            .bind(MIGRATION_LOCK_ID)
            .execute(&mut *tx)
            .await
            .map_err(map_sqlx_err)?;

        sqlx_core::query::query(
            r#"
            CREATE TABLE IF NOT EXISTS schema_migrations (
                version BIGINT PRIMARY KEY,
                name TEXT NOT NULL,
                applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
            )
            "#,
        )
        .execute(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;

        let current: i64 = sqlx_core::query_scalar::query_scalar(
            "SELECT COALESCE(MAX(version), 0) FROM schema_migrations",
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;
        let latest = MIGRATIONS.last().map_or(0, |migration| migration.version);
        if current > latest {
            return Err(TransactionStoreError::DatabaseInvariant(format!(
                "postgres schema version {current} is newer than this binary supports ({latest})"
            )));
        }

        for migration in MIGRATIONS
            .iter()
            .filter(|migration| migration.version > current)
        {
            // Run statements separately for transaction-mode poolers that
            // reject multi-statement query strings.
            for statement in migration.statements {
                sqlx_core::query::query(*statement)
                    .execute(&mut *tx)
                    .await
                    .map_err(map_sqlx_err)?;
            }
            sqlx_core::query::query(
                "INSERT INTO schema_migrations (version, name) VALUES ($1, $2)",
            )
            .bind(migration.version)
            .bind(migration.name)
            .execute(&mut *tx)
            .await
            .map_err(map_sqlx_err)?;
        }

        tx.commit().await.map_err(map_sqlx_err)
    }

    async fn revoke_unconsumed_approval_in_tx(
        tx: &mut sqlx_core::transaction::Transaction<'_, sqlx_postgres::Postgres>,
        key: &AuditKey,
        transaction_id: &str,
        revoker_signed: &str,
    ) -> Result<bool, TransactionStoreError> {
        // Read the digest before the DELETE: the event names which receipt was
        // retracted, and after the delete there is nothing left to name.
        let digest: Option<String> = sqlx_core::query_scalar::query_scalar(
            "SELECT receipt_digest FROM transaction_approvals \
             WHERE transaction_id = $1 AND consumed_at IS NULL",
        )
        .bind(transaction_id)
        .fetch_optional(&mut **tx)
        .await
        .map_err(map_sqlx_err)?;
        let result = sqlx_core::query::query(
            "DELETE FROM transaction_approvals \
             WHERE transaction_id = $1 AND consumed_at IS NULL",
        )
        .bind(transaction_id)
        .execute(&mut **tx)
        .await
        .map_err(map_sqlx_err)?;
        if result.rows_affected() > 0 {
            let digest = digest.ok_or_else(|| {
                TransactionStoreError::DatabaseInvariant(format!(
                    "revoked an approval for {transaction_id} that had no receipt digest"
                ))
            })?;
            append_event(
                tx,
                key,
                AuditEventKind::ApprovalRevoked,
                transaction_id,
                &digest,
                EventIdentity::V2 {
                    caller_principal: revoker_signed,
                },
            )
            .await?;
        }
        Ok(result.rows_affected() > 0)
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn map_sqlx_err(e: sqlx_core::Error) -> TransactionStoreError {
    let message = format!("postgres: {e}");
    let invariant = match &e {
        sqlx_core::Error::Database(db) => db
            .code()
            .is_some_and(|code| code.starts_with("22") || code.starts_with("23")),
        sqlx_core::Error::TypeNotFound { .. }
        | sqlx_core::Error::ColumnIndexOutOfBounds { .. }
        | sqlx_core::Error::ColumnNotFound(_)
        | sqlx_core::Error::ColumnDecode { .. }
        | sqlx_core::Error::Decode(_) => true,
        _ => false,
    };
    if invariant {
        TransactionStoreError::DatabaseInvariant(message)
    } else {
        TransactionStoreError::Io(std::io::Error::other(message))
    }
}

fn serialize<T: serde::Serialize>(v: &T) -> Result<String, TransactionStoreError> {
    serde_json::to_string(v).map_err(TransactionStoreError::Json)
}

fn deserialize<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, TransactionStoreError> {
    serde_json::from_str(s).map_err(TransactionStoreError::Json)
}

/// UTC timestamp in the same RFC 3339 millisecond shape the SQLite backend
/// produces via `strftime('%Y-%m-%dT%H:%M:%fZ','now')`.
///
/// `%S` is load-bearing: chrono's `%.3f` renders only the fractional part, so
/// omitting `%S` yields `2026-07-27T12:34:.567Z`. That value is signed into
/// `ChainContent.created_at` on every audit row and cast to `timestamptz` by
/// approve, claim-for-execution, the stale sweep, and the history filter.
fn now_iso() -> String {
    chrono::Utc::now()
        .format("%Y-%m-%dT%H:%M:%S%.3fZ")
        .to_string()
}

// ---------------------------------------------------------------------------
// AuditStore impl
// ---------------------------------------------------------------------------

#[async_trait]
impl AuditStore for PostgresStore {
    async fn record(
        &self,
        transaction: NewTransaction,
    ) -> Result<TransactionRecord, TransactionStoreError> {
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let transaction_id = Uuid::new_v4().to_string();
        let inserted =
            insert_transaction(&mut tx, &self.audit_key, &transaction_id, transaction).await?;
        tx.commit().await.map_err(map_sqlx_err)?;
        emit_chain_tip_watermark(inserted.seq, &inserted.chain_hash);
        Ok(inserted.record)
    }

    async fn record_previewed(
        &self,
        transaction: NewTransaction,
        preview: PreviewEnvelope,
    ) -> Result<RecordedPreviewedTransaction, TransactionStoreError> {
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let transaction_id = Uuid::new_v4().to_string();
        let inserted =
            insert_transaction(&mut tx, &self.audit_key, &transaction_id, transaction).await?;

        sqlx_core::query::query(
            "INSERT INTO transaction_previews (transaction_id, preview_json) VALUES ($1, $2)",
        )
        .bind(&inserted.record.transaction_id)
        .bind(serialize(&preview)?)
        .execute(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;

        tx.commit().await.map_err(map_sqlx_err)?;
        emit_chain_tip_watermark(inserted.seq, &inserted.chain_hash);
        Ok(RecordedPreviewedTransaction {
            transaction: inserted.record,
            preview,
        })
    }

    async fn get(
        &self,
        transaction_id: &str,
    ) -> Result<Option<TransactionRecord>, TransactionStoreError> {
        let row = sqlx_core::query::query(
            "SELECT transaction_id, request_id, request_hash, action_name, risk_level, \
                    status, approval_id, summary, warnings_json \
             FROM transactions WHERE transaction_id = $1",
        )
        .bind(transaction_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_sqlx_err)?;
        row.map(row_to_record).transpose()
    }

    async fn get_preview(
        &self,
        transaction_id: &str,
    ) -> Result<Option<PreviewEnvelope>, TransactionStoreError> {
        let row = sqlx_core::query::query(
            "SELECT preview_json FROM transaction_previews WHERE transaction_id = $1",
        )
        .bind(transaction_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_sqlx_err)?;
        match row {
            Some(r) => {
                let s: String = r.try_get("preview_json").map_err(map_sqlx_err)?;
                Ok(Some(deserialize(&s)?))
            }
            None => Ok(None),
        }
    }

    async fn update_status(
        &self,
        transaction_id: &str,
        new_status: JobState,
    ) -> Result<(), TransactionStoreError> {
        // Read-validate-write with a state-machine guard, same shape as the
        // SQLite path but strictly stronger: `SELECT ... FOR UPDATE` takes a
        // row lock for the lifetime of this transaction, so no concurrent
        // writer can change `status` between our read and our `UPDATE` — the
        // read-modify-write here is atomic by construction. SQLite has no
        // equivalent row-level lock, so its `update_status` instead uses an
        // explicit compare-and-swap (`UPDATE ... WHERE status = <observed>`,
        // checking `rows_affected`) to get the same guarantee.
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let current_str: Option<String> = sqlx_core::query_scalar::query_scalar(
            "SELECT status FROM transactions WHERE transaction_id = $1 FOR UPDATE",
        )
        .bind(transaction_id)
        .fetch_optional(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;
        let current_str = current_str
            .ok_or_else(|| TransactionStoreError::NotFound(transaction_id.to_string()))?;
        let current: JobState = deserialize(&current_str)?;
        if !crate::jobs::allowed_transition(&current, &new_status) {
            return Err(TransactionStoreError::InvalidTransition {
                from: current,
                to: new_status,
            });
        }
        sqlx_core::query::query("UPDATE transactions SET status = $1 WHERE transaction_id = $2")
            .bind(serialize(&new_status)?)
            .bind(transaction_id)
            .execute(&mut *tx)
            .await
            .map_err(map_sqlx_err)?;
        // The outcome is chained in the same transaction as the column write,
        // as on SQLite: written separately, a crash between them would leave a
        // status nobody can corroborate, which the cross-check reads as
        // tampering. Status events name no account (#249) and stay legacy.
        append_event(
            &mut tx,
            &self.audit_key,
            AuditEventKind::from(new_status),
            transaction_id,
            "",
            EventIdentity::LegacyV1,
        )
        .await?;
        tx.commit().await.map_err(map_sqlx_err)?;
        Ok(())
    }

    async fn approve_transaction(
        &self,
        transaction_id: &str,
        approver: CallerPrincipal,
    ) -> Result<Option<String>, TransactionStoreError> {
        // Rendered once so the signed string and the stored column provably
        // come from the same value.
        let approver_signed = approver.as_signed_str();
        let row = sqlx_core::query::query(
            "SELECT request_hash, approval_id FROM transactions WHERE transaction_id = $1",
        )
        .bind(transaction_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_sqlx_err)?;
        let Some(row) = row else {
            return Ok(None);
        };
        let request_hash: String = row.try_get("request_hash").map_err(map_sqlx_err)?;
        let committed_digest: Option<String> = row.try_get("approval_id").map_err(map_sqlx_err)?;
        let receipt = self
            .audit_key
            .approval_receipt(transaction_id, &request_hash);
        let receipt_digest = crate::audit_chain::approval_receipt_digest(&receipt);
        let commitment_matches = committed_digest.as_deref().is_some_and(|committed| {
            bool::from(receipt_digest.as_bytes().ct_eq(committed.as_bytes()))
        });
        if !commitment_matches {
            return Err(TransactionStoreError::DatabaseInvariant(format!(
                "transaction {transaction_id} approval commitment does not match its signed preview"
            )));
        }
        let queued = serialize(&JobState::Queued)?;
        // Approval row and chained event commit together — an approval absent
        // from the event chain is exactly what that chain exists to prevent.
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let result = sqlx_core::query::query(
            sqlx_core::sql_str::AssertSqlSafe(format!(
                "INSERT INTO transaction_approvals \
                     (transaction_id, receipt_digest, approved_at) \
                 SELECT transaction_id, $1, $2 FROM transactions \
                 WHERE transaction_id = $3 \
                   AND status = $4 \
                   AND created_at::timestamptz > now() - INTERVAL '{APPROVAL_RECEIPT_TTL_MINUTES} minutes' \
                 ON CONFLICT (transaction_id) DO NOTHING"
            )),
        )
        .bind(&receipt_digest)
        .bind(now_iso())
        .bind(transaction_id)
        .bind(&queued)
        .execute(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;
        if result.rows_affected() > 0 {
            append_event(
                &mut tx,
                &self.audit_key,
                AuditEventKind::ApprovalGranted,
                transaction_id,
                &receipt_digest,
                EventIdentity::V2 {
                    caller_principal: &approver_signed,
                },
            )
            .await?;
        }
        tx.commit().await.map_err(map_sqlx_err)?;
        Ok((result.rows_affected() > 0).then_some(receipt))
    }

    async fn revoke_unconsumed_approval(
        &self,
        transaction_id: &str,
        revoker: CallerPrincipal,
    ) -> Result<bool, TransactionStoreError> {
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let revoked = Self::revoke_unconsumed_approval_in_tx(
            &mut tx,
            &self.audit_key,
            transaction_id,
            &revoker.as_signed_str(),
        )
        .await?;
        tx.commit().await.map_err(map_sqlx_err)?;
        Ok(revoked)
    }

    async fn claim_approved_for_execution(
        &self,
        transaction_id: &str,
        receipt_digest: &str,
        executor: CallerPrincipal,
    ) -> Result<bool, TransactionStoreError> {
        let queued = serialize(&JobState::Queued)?;
        let running = serialize(&JobState::Running)?;
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let result = sqlx_core::query::query(
            sqlx_core::sql_str::AssertSqlSafe(format!(
                "UPDATE transactions SET status = $1 \
                 WHERE transaction_id = $2 \
                   AND status = $3 \
                   AND created_at::timestamptz > now() - INTERVAL '{APPROVAL_RECEIPT_TTL_MINUTES} minutes' \
                   AND EXISTS ( \
                       SELECT 1 FROM transaction_approvals \
                       WHERE transaction_id = $2 \
                         AND receipt_digest = $4 \
                         AND consumed_at IS NULL \
                   )"
            )),
        )
        .bind(&running)
        .bind(transaction_id)
        .bind(&queued)
        .bind(receipt_digest)
        .execute(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;
        if result.rows_affected() > 0 {
            sqlx_core::query::query(
                "UPDATE transaction_approvals SET consumed_at = $1 \
                 WHERE transaction_id = $2 AND consumed_at IS NULL",
            )
            .bind(now_iso())
            .bind(transaction_id)
            .execute(&mut *tx)
            .await
            .map_err(map_sqlx_err)?;
            append_event(
                &mut tx,
                &self.audit_key,
                AuditEventKind::ApprovalConsumed,
                transaction_id,
                receipt_digest,
                EventIdentity::V2 {
                    caller_principal: &executor.as_signed_str(),
                },
            )
            .await?;
            append_event(
                &mut tx,
                &self.audit_key,
                AuditEventKind::StatusRunning,
                transaction_id,
                "",
                EventIdentity::LegacyV1,
            )
            .await?;
        }
        tx.commit().await.map_err(map_sqlx_err)?;
        Ok(result.rows_affected() > 0)
    }

    async fn cleanup_stale_queued(&self) -> Result<u64, TransactionStoreError> {
        let queued = serialize(&JobState::Queued)?;
        let canceled = serialize(&JobState::Canceled)?;
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let stale_ids: Vec<String> = sqlx_core::query_scalar::query_scalar(
            sqlx_core::sql_str::AssertSqlSafe(format!(
                "SELECT transaction_id FROM transactions \
                 WHERE status = $1 \
                   AND created_at::timestamptz <= now() - INTERVAL '{APPROVAL_RECEIPT_TTL_MINUTES} minutes'"
            )),
        )
        .bind(&queued)
        .fetch_all(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;
        let mut canceled_count = 0;
        for transaction_id in stale_ids {
            let result = sqlx_core::query::query(
                "UPDATE transactions SET status = $1 \
                 WHERE transaction_id = $2 AND status = $3",
            )
            .bind(&canceled)
            .bind(&transaction_id)
            .bind(&queued)
            .execute(&mut *tx)
            .await
            .map_err(map_sqlx_err)?;
            if result.rows_affected() > 0 {
                // Daemon-initiated revocation: the stale sweep has no caller
                // connection to attribute, and `Unattributed` records exactly
                // that rather than inventing an account (#249).
                Self::revoke_unconsumed_approval_in_tx(
                    &mut tx,
                    &self.audit_key,
                    &transaction_id,
                    &CallerPrincipal::Unattributed.as_signed_str(),
                )
                .await?;
                append_event(
                    &mut tx,
                    &self.audit_key,
                    AuditEventKind::StatusCanceled,
                    &transaction_id,
                    "",
                    EventIdentity::LegacyV1,
                )
                .await?;
                canceled_count += result.rows_affected();
            }
        }
        tx.commit().await.map_err(map_sqlx_err)?;
        Ok(canceled_count)
    }

    async fn cancel_queued(
        &self,
        transaction_id: &str,
        canceller: CallerPrincipal,
    ) -> Result<bool, TransactionStoreError> {
        // Option A: the `status = $3` (Queued) guard means a Running (in-flight)
        // transaction is never cancelled.
        let queued = serialize(&JobState::Queued)?;
        let canceled = serialize(&JobState::Canceled)?;
        let mut tx = self.pool.begin().await.map_err(map_sqlx_err)?;
        let result = sqlx_core::query::query(
            "UPDATE transactions SET status = $1 \
             WHERE transaction_id = $2 AND status = $3",
        )
        .bind(&canceled)
        .bind(transaction_id)
        .bind(&queued)
        .execute(&mut *tx)
        .await
        .map_err(map_sqlx_err)?;
        if result.rows_affected() > 0 {
            // Caller-attributed cancel (see the SQLite impl): the revocation
            // event names the account that cancelled, not `Unattributed`.
            Self::revoke_unconsumed_approval_in_tx(
                &mut tx,
                &self.audit_key,
                transaction_id,
                &canceller.as_signed_str(),
            )
            .await?;
            append_event(
                &mut tx,
                &self.audit_key,
                AuditEventKind::StatusCanceled,
                transaction_id,
                "",
                EventIdentity::LegacyV1,
            )
            .await?;
        }
        tx.commit().await.map_err(map_sqlx_err)?;
        Ok(result.rows_affected() > 0)
    }

    async fn list_transactions(
        &self,
        limit: u32,
        status_filter: Option<&str>,
        action_filter: Option<&str>,
        since: Option<HistorySince>,
    ) -> Result<Vec<TransactionRecord>, TransactionStoreError> {
        let limit = limit.min(100) as i64;

        // Validate the status filter against the JobState enum so a typo
        // produces an error instead of silent empty results.
        let validated_status: Option<String> = status_filter
            .map(|s| -> Result<String, TransactionStoreError> {
                let parsed: JobState = deserialize(&format!("\"{s}\""))?;
                serialize(&parsed)
            })
            .transpose()?;

        let mut sql = String::from(
            "SELECT transaction_id, request_id, request_hash, action_name, risk_level, \
                    status, approval_id, summary, warnings_json \
             FROM transactions WHERE TRUE",
        );
        let mut idx = 1;
        if validated_status.is_some() {
            sql.push_str(&format!(" AND status = ${idx}"));
            idx += 1;
        }
        if action_filter.is_some() {
            sql.push_str(&format!(" AND action_name = ${idx}"));
            idx += 1;
        }
        match since {
            Some(HistorySince::Hours(_)) => {
                sql.push_str(&format!(
                    " AND created_at::timestamptz > now() - (${idx} || ' hours')::INTERVAL"
                ));
                idx += 1;
            }
            Some(HistorySince::Cutoff(_)) => {
                sql.push_str(&format!(
                    " AND created_at::timestamptz >= ${idx}::timestamptz"
                ));
                idx += 1;
            }
            None => {}
        }
        sql.push_str(&format!(" ORDER BY seq DESC LIMIT ${idx}"));

        let mut q = sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(sql.as_str()));
        if let Some(s) = &validated_status {
            q = q.bind(s);
        }
        if let Some(a) = action_filter {
            q = q.bind(a);
        }
        match since {
            Some(HistorySince::Hours(h)) => q = q.bind(h.to_string()),
            Some(HistorySince::Cutoff(at)) => q = q.bind(HistorySince::cutoff_rfc3339(&at)),
            None => {}
        }
        q = q.bind(limit);

        let rows = q.fetch_all(&self.pool).await.map_err(map_sqlx_err)?;
        rows.into_iter().map(row_to_record).collect()
    }

    async fn list_history(
        &self,
        limit: u32,
        status_filter: Option<&str>,
        action_filter: Option<&str>,
        since: Option<HistorySince>,
    ) -> Result<Vec<crate::transactions::JobHistoryEntry>, TransactionStoreError> {
        // Parallels list_transactions but selects created_at and returns the
        // structured JobHistoryEntry DTO. Same filter/validation semantics.
        let limit = limit.min(100) as i64;
        let validated_status: Option<String> = status_filter
            .map(|s| -> Result<String, TransactionStoreError> {
                let parsed: JobState = deserialize(&format!("\"{s}\""))?;
                serialize(&parsed)
            })
            .transpose()?;

        let mut sql = String::from(
            "SELECT transaction_id, action_name, risk_level, status, summary, created_at \
             FROM transactions WHERE TRUE",
        );
        let mut idx = 1;
        if validated_status.is_some() {
            sql.push_str(&format!(" AND status = ${idx}"));
            idx += 1;
        }
        if action_filter.is_some() {
            sql.push_str(&format!(" AND action_name = ${idx}"));
            idx += 1;
        }
        match since {
            Some(HistorySince::Hours(_)) => {
                sql.push_str(&format!(
                    " AND created_at::timestamptz > now() - (${idx} || ' hours')::INTERVAL"
                ));
                idx += 1;
            }
            Some(HistorySince::Cutoff(_)) => {
                sql.push_str(&format!(
                    " AND created_at::timestamptz >= ${idx}::timestamptz"
                ));
                idx += 1;
            }
            None => {}
        }
        sql.push_str(&format!(" ORDER BY seq DESC LIMIT ${idx}"));

        let mut q = sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(sql.as_str()));
        if let Some(s) = &validated_status {
            q = q.bind(s);
        }
        if let Some(a) = action_filter {
            q = q.bind(a);
        }
        match since {
            Some(HistorySince::Hours(h)) => q = q.bind(h.to_string()),
            Some(HistorySince::Cutoff(at)) => q = q.bind(HistorySince::cutoff_rfc3339(&at)),
            None => {}
        }
        q = q.bind(limit);

        let rows = q.fetch_all(&self.pool).await.map_err(map_sqlx_err)?;
        rows.into_iter().map(row_to_history_entry).collect()
    }

    async fn fetch_chain_row(
        &self,
        transaction_id: &str,
    ) -> Result<Option<ChainRow>, TransactionStoreError> {
        let row = sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(format!(
            "SELECT {CHAIN_ROW_COLUMNS} FROM transactions WHERE transaction_id = $1"
        )))
        .bind(transaction_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_sqlx_err)?;
        row.map(row_to_chain_row).transpose()
    }

    async fn fetch_event_rows(&self) -> Result<Vec<EventRow>, TransactionStoreError> {
        fetch_event_rows_from_pool(&self.pool).await
    }

    async fn fetch_chain_rows(&self) -> Result<Vec<ChainRow>, TransactionStoreError> {
        fetch_chain_rows_from_pool(&self.pool).await
    }

    async fn verify_audit_chain(
        &self,
        key: &AuditKey,
    ) -> Result<VerifyOutcome, TransactionStoreError> {
        let rows = self.fetch_chain_rows().await?;
        Ok(crate::audit_chain::verify_chain(key, &rows))
    }
}

async fn fetch_chain_rows_from_pool(pool: &PgPool) -> Result<Vec<ChainRow>, TransactionStoreError> {
    let rows = sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(format!(
        "SELECT {CHAIN_ROW_COLUMNS} FROM transactions ORDER BY seq ASC"
    )))
    .fetch_all(pool)
    .await
    .map_err(map_sqlx_err)?;
    rows.into_iter().map(row_to_chain_row).collect()
}

/// Is `audit_events` genuinely not there, as opposed to unreadable?
///
/// `to_regclass` resolves the name through the same `search_path` the queries
/// use and returns NULL when nothing matches. It answers existence, not access:
/// a table the caller may not SELECT still resolves, which is exactly the
/// distinction the caller needs.
async fn audit_events_table_absent(pool: &PgPool) -> Result<bool, TransactionStoreError> {
    let present: Option<String> =
        sqlx_core::query_scalar::query_scalar("SELECT to_regclass('audit_events')::text")
            .fetch_one(pool)
            .await
            .map_err(map_sqlx_err)?;
    Ok(present.is_none())
}

/// The status cross-check, with a failure to run it reported as an
/// inconclusive verdict. Dropping a failed check would let the other checks
/// report an intact log; the SQLite CLI path maps errors the same way.
async fn status_verdict(pool: &PgPool) -> StatusOutcome {
    status_matches_chain_from_pool(pool)
        .await
        .unwrap_or_else(|error| StatusOutcome::CannotVerify {
            detail: format!("status cross-check failed: {error}"),
        })
}

/// Postgres twin of `TransactionStore::status_matches_chain`: the same SQL
/// fragments and the same rules ([`crate::audit_chain::status_outcome`]).
///
/// The auditor path runs no migrations, so it may read a store whose daemon
/// predates `audit_events` or migration 5. It asks which of the two exists
/// rather than failing: with no event table there is no status event to find,
/// and with no boundary column every row predates status events, because the
/// daemon that wrote them chained none.
async fn status_matches_chain_from_pool(
    pool: &PgPool,
) -> Result<StatusOutcome, TransactionStoreError> {
    let events_present = !audit_events_table_absent(pool).await?;
    let boundary_present: bool = sqlx_core::query_scalar::query_scalar(
        "SELECT EXISTS (SELECT 1 FROM pg_attribute \
         WHERE attrelid = to_regclass('transactions') \
           AND attname = 'predates_status_events' AND NOT attisdropped)",
    )
    .fetch_one(pool)
    .await
    .map_err(map_sqlx_err)?;
    let (newest, consumed) = if events_present {
        (NEWEST_STATUS_EVENT_SQL, APPROVAL_CONSUMED_SQL)
    } else {
        ("NULL::text", "FALSE")
    };
    let predates = if boundary_present {
        "t.predates_status_events"
    } else {
        "TRUE"
    };
    let rows = sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(format!(
        "SELECT t.transaction_id, t.status, {newest} AS newest, {consumed} AS consumed, \
                {predates} AS predates FROM transactions t"
    )))
    .fetch_all(pool)
    .await
    .map_err(map_sqlx_err)?;
    let evidence = rows
        .into_iter()
        .map(|row| {
            Ok(StatusEvidence {
                transaction_id: row.try_get("transaction_id").map_err(map_sqlx_err)?,
                status: deserialize(&row.try_get::<String, _>("status").map_err(map_sqlx_err)?)?,
                newest_status_event: row.try_get("newest").map_err(map_sqlx_err)?,
                approval_consumed: row.try_get("consumed").map_err(map_sqlx_err)?,
                predates_status_events: row.try_get("predates").map_err(map_sqlx_err)?,
            })
        })
        .collect::<Result<Vec<_>, TransactionStoreError>>()?;
    Ok(crate::audit_chain::status_outcome(evidence))
}

/// Fetch every approval event in seq order.
async fn fetch_event_rows_from_pool(pool: &PgPool) -> Result<Vec<EventRow>, TransactionStoreError> {
    let rows = sqlx_core::query::query(
        "SELECT seq, key_id, kind, transaction_id, receipt_digest, \
                created_at, prev_chain_hash, chain_hash, chain_version, caller_principal \
         FROM audit_events ORDER BY seq ASC",
    )
    .fetch_all(pool)
    .await
    .map_err(map_sqlx_err)?;
    rows.into_iter().map(row_to_event_row).collect()
}

/// Append one signed approval event inside the caller's transaction.
///
/// `FOR UPDATE` on the current tip serialises concurrent appends the same way
/// `insert_transaction` serialises on the transaction chain tip; without it two
/// approvals could compute the same `seq` and collide on the primary key.
async fn append_event(
    tx: &mut sqlx_core::transaction::Transaction<'_, sqlx_postgres::Postgres>,
    key: &AuditKey,
    kind: AuditEventKind,
    transaction_id: &str,
    receipt_digest: &str,
    identity: EventIdentity<'_>,
) -> Result<(), TransactionStoreError> {
    let prev: Option<(i64, String)> = sqlx_core::query_as::query_as(
        "SELECT seq, chain_hash FROM audit_events ORDER BY seq DESC LIMIT 1 FOR UPDATE",
    )
    .fetch_optional(&mut **tx)
    .await
    .map_err(map_sqlx_err)?;
    let (seq, prev_chain_hash) = match prev {
        Some((s, h)) => ((s as u64) + 1, h),
        None => (1, String::new()),
    };
    let created_at = now_iso();
    let key_id = CURRENT_KEY_ID.to_string();
    // Build the content once and derive the stored version from its identity,
    // so the chain_version column is provably the version whose message was
    // signed — the same discipline the SQLite backend follows.
    let content = EventContent {
        seq,
        key_id: &key_id,
        kind,
        transaction_id,
        receipt_digest,
        created_at: &created_at,
        identity,
    };
    let chain_hash = key.event_hash(&content, &prev_chain_hash);
    let stored_principal = match identity {
        EventIdentity::V2 { caller_principal } => Some(caller_principal),
        EventIdentity::LegacyV1 => None,
    };
    sqlx_core::query::query(
        "INSERT INTO audit_events ( \
            seq, key_id, kind, transaction_id, receipt_digest, \
            created_at, chain_hash, prev_chain_hash, chain_version, caller_principal \
         ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
    )
    .bind(seq as i64)
    .bind(&key_id)
    .bind(kind.as_str())
    .bind(transaction_id)
    .bind(receipt_digest)
    .bind(&created_at)
    .bind(&chain_hash)
    .bind(&prev_chain_hash)
    .bind(identity.version() as i64)
    .bind(stored_principal)
    .execute(&mut **tx)
    .await
    .map_err(map_sqlx_err)?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Insert path — chain-aware
// ---------------------------------------------------------------------------

async fn insert_transaction(
    tx: &mut sqlx_core::transaction::Transaction<'_, sqlx_postgres::Postgres>,
    key: &AuditKey,
    transaction_id: &str,
    transaction: NewTransaction,
) -> Result<InsertedTransaction, TransactionStoreError> {
    let warnings_json = serialize(&transaction.warnings)?;
    let status = JobState::Queued;
    let created_at = now_iso();
    let key_id = CURRENT_KEY_ID.to_string();
    // Always the store's own commitment — see the matching note in
    // `transactions.rs`; a caller may not supply this value.
    let approval_id = Some(key.approval_commitment(transaction_id, &transaction.request_hash));

    // SELECT … FOR UPDATE on the most-recent row (if any) so concurrent
    // writers serialise on the chain tip. Without this, two parallel
    // record() calls could both compute seq=N+1 and then race on the
    // UNIQUE(seq) constraint — the loser would get a unique-violation
    // error.
    let prev: Option<(i64, String)> = sqlx_core::query_as::query_as(
        "SELECT seq, chain_hash FROM transactions ORDER BY seq DESC LIMIT 1 FOR UPDATE",
    )
    .fetch_optional(&mut **tx)
    .await
    .map_err(map_sqlx_err)?;
    let (seq, prev_chain_hash) = match prev {
        Some((s, h)) => ((s as u64) + 1, h),
        None => (1, String::new()),
    };

    // Bind the row to the approval-event chain tip as of this insert. Read
    // inside the same DB transaction as the seq allocation above.
    let event_tip: String = sqlx_core::query_scalar::query_scalar(
        "SELECT COALESCE((SELECT chain_hash FROM audit_events ORDER BY seq DESC LIMIT 1), '')",
    )
    .fetch_one(&mut **tx)
    .await
    .map_err(map_sqlx_err)?;
    let caller_role = transaction.caller_role.as_str();
    let caller_principal = transaction.caller_principal.as_signed_str();

    // As in the SQLite path: derive the stored version from the identity that was
    // signed, so the column cannot disagree with the message.
    let identity = ChainIdentity::V4 {
        caller_role,
        event_tip: &event_tip,
        caller_principal: &caller_principal,
    };
    let chain_hash = key.chain_hash(
        &ChainContent {
            seq,
            key_id: &key_id,
            transaction_id,
            request_id: &transaction.request_id,
            request_hash: &transaction.request_hash,
            action_name: &transaction.action_name,
            risk_level: transaction.risk_level,
            summary: &transaction.summary,
            approval_id: approval_id.as_deref(),
            warnings_json: &warnings_json,
            created_at: &created_at,
            identity,
        },
        &prev_chain_hash,
    );

    sqlx_core::query::query(
        "INSERT INTO transactions ( \
            transaction_id, request_id, request_hash, action_name, risk_level, \
            status, approval_id, summary, warnings_json, created_at, \
            seq, key_id, chain_hash, prev_chain_hash, \
            chain_version, caller_role, event_tip, caller_principal \
         ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)",
    )
    .bind(transaction_id)
    .bind(&transaction.request_id)
    .bind(&transaction.request_hash)
    .bind(&transaction.action_name)
    .bind(serialize(&transaction.risk_level)?)
    .bind(serialize(&status)?)
    .bind(&approval_id)
    .bind(&transaction.summary)
    .bind(&warnings_json)
    .bind(&created_at)
    .bind(seq as i64)
    .bind(&key_id)
    .bind(&chain_hash)
    .bind(&prev_chain_hash)
    .bind(i64::from(identity.version()))
    .bind(caller_role)
    .bind(&event_tip)
    .bind(&caller_principal)
    .execute(&mut **tx)
    .await
    .map_err(map_sqlx_err)?;

    Ok(InsertedTransaction {
        record: TransactionRecord {
            transaction_id: transaction_id.to_string(),
            request_id: transaction.request_id,
            request_hash: transaction.request_hash,
            action_name: transaction.action_name,
            risk_level: transaction.risk_level,
            status,
            approval_id,
            summary: transaction.summary,
            warnings: transaction.warnings,
        },
        seq,
        chain_hash,
    })
}

// ---------------------------------------------------------------------------
// Row mappers
// ---------------------------------------------------------------------------

fn row_to_history_entry(
    row: sqlx_postgres::PgRow,
) -> Result<crate::transactions::JobHistoryEntry, TransactionStoreError> {
    Ok(crate::transactions::JobHistoryEntry {
        transaction_id: row.try_get("transaction_id").map_err(map_sqlx_err)?,
        action_name: row.try_get("action_name").map_err(map_sqlx_err)?,
        risk_level: deserialize(
            &row.try_get::<String, _>("risk_level")
                .map_err(map_sqlx_err)?,
        )?,
        status: deserialize(&row.try_get::<String, _>("status").map_err(map_sqlx_err)?)?,
        summary: row.try_get("summary").map_err(map_sqlx_err)?,
        created_at: row.try_get("created_at").map_err(map_sqlx_err)?,
    })
}

fn row_to_record(row: sqlx_postgres::PgRow) -> Result<TransactionRecord, TransactionStoreError> {
    Ok(TransactionRecord {
        transaction_id: row.try_get("transaction_id").map_err(map_sqlx_err)?,
        request_id: row.try_get("request_id").map_err(map_sqlx_err)?,
        request_hash: row.try_get("request_hash").map_err(map_sqlx_err)?,
        action_name: row.try_get("action_name").map_err(map_sqlx_err)?,
        risk_level: deserialize(
            &row.try_get::<String, _>("risk_level")
                .map_err(map_sqlx_err)?,
        )?,
        status: deserialize(&row.try_get::<String, _>("status").map_err(map_sqlx_err)?)?,
        approval_id: row.try_get("approval_id").map_err(map_sqlx_err)?,
        summary: row.try_get("summary").map_err(map_sqlx_err)?,
        warnings: deserialize(
            &row.try_get::<String, _>("warnings_json")
                .map_err(map_sqlx_err)?,
        )?,
    })
}

fn row_to_chain_row(row: sqlx_postgres::PgRow) -> Result<ChainRow, TransactionStoreError> {
    Ok(ChainRow {
        seq: row.try_get::<i64, _>("seq").map_err(map_sqlx_err)? as u64,
        key_id: row.try_get("key_id").map_err(map_sqlx_err)?,
        transaction_id: row.try_get("transaction_id").map_err(map_sqlx_err)?,
        request_id: row.try_get("request_id").map_err(map_sqlx_err)?,
        request_hash: row.try_get("request_hash").map_err(map_sqlx_err)?,
        action_name: row.try_get("action_name").map_err(map_sqlx_err)?,
        risk_level: deserialize(
            &row.try_get::<String, _>("risk_level")
                .map_err(map_sqlx_err)?,
        )?,
        summary: row.try_get("summary").map_err(map_sqlx_err)?,
        approval_id: row.try_get("approval_id").map_err(map_sqlx_err)?,
        warnings_json: row.try_get("warnings_json").map_err(map_sqlx_err)?,
        created_at: row.try_get("created_at").map_err(map_sqlx_err)?,
        prev_chain_hash: row.try_get("prev_chain_hash").map_err(map_sqlx_err)?,
        chain_hash: row.try_get("chain_hash").map_err(map_sqlx_err)?,
        chain_version: row
            .try_get::<i64, _>("chain_version")
            .map_err(map_sqlx_err)? as u32,
        caller_role: row.try_get("caller_role").map_err(map_sqlx_err)?,
        event_tip: row.try_get("event_tip").map_err(map_sqlx_err)?,
        caller_principal: row.try_get("caller_principal").map_err(map_sqlx_err)?,
    })
}

fn row_to_event_row(row: sqlx_postgres::PgRow) -> Result<EventRow, TransactionStoreError> {
    Ok(EventRow {
        seq: row.try_get::<i64, _>("seq").map_err(map_sqlx_err)? as u64,
        key_id: row.try_get("key_id").map_err(map_sqlx_err)?,
        kind: row.try_get("kind").map_err(map_sqlx_err)?,
        transaction_id: row.try_get("transaction_id").map_err(map_sqlx_err)?,
        receipt_digest: row.try_get("receipt_digest").map_err(map_sqlx_err)?,
        created_at: row.try_get("created_at").map_err(map_sqlx_err)?,
        prev_chain_hash: row.try_get("prev_chain_hash").map_err(map_sqlx_err)?,
        chain_hash: row.try_get("chain_hash").map_err(map_sqlx_err)?,
        chain_version: row
            .try_get::<i64, _>("chain_version")
            .map_err(map_sqlx_err)? as u32,
        caller_principal: row.try_get("caller_principal").map_err(map_sqlx_err)?,
    })
}

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

    /// Verifies that PostgresConfig defaults are sensible and don't accidentally
    /// disable the statement cache.
    #[test]
    fn default_config_keeps_statement_cache_enabled() {
        let c = PostgresConfig::default();
        assert!(c.statement_cache_capacity > 0);
        assert!(c.max_connections >= 4);
        assert!(c.acquire_timeout >= Duration::from_secs(5));
    }

    #[test]
    fn url_parsing_accepts_standard_postgres_url() {
        let opts = PgConnectOptions::from_str(
            "postgres://user:pass@host.example.com:5432/audit?sslmode=require",
        )
        .expect("standard URL parses");
        // Ensure binding via PgPoolOptions wouldn't reject it (just smoke-check).
        let _ = opts.statement_cache_capacity(0);
    }

    #[test]
    fn now_iso_produces_a_parseable_rfc3339_timestamp() {
        // `now_iso()` is signed into `ChainContent.created_at` on every
        // audit row and is cast to `timestamptz` by approve, claim-for-
        // execution, the stale sweep, and the history filter. The format
        // string previously omitted `%S`, yielding `2026-07-27T12:34:.567Z`:
        // seconds silently vanished, the chain attested to a broken value
        // forever, and same-minute ordering became unrecoverable.
        let ts = now_iso();
        let parsed = chrono::DateTime::parse_from_rfc3339(&ts);
        assert!(
            parsed.is_ok(),
            "now_iso() must emit a parseable RFC 3339 timestamp, got {ts:?} ({parsed:?})"
        );
        assert_eq!(
            ts.len(),
            "2026-07-27T12:34:56.789Z".len(),
            "timestamp shape changed unexpectedly: {ts}"
        );
    }

    #[test]
    fn now_iso_matches_the_sqlite_backends_timestamp_shape() {
        // Both backends feed the same signed chain, so a row written by
        // Postgres must be byte-comparable with one written by SQLite
        // (`strftime('%Y-%m-%dT%H:%M:%fZ','now')`, which yields
        // milliseconds). Divergent shapes make cross-backend verification
        // and time-ordered queries subtly wrong.
        let ts = now_iso();
        let (date, rest) = ts.split_once('T').expect("timestamp has a T separator");
        assert_eq!(date.len(), "2026-07-27".len(), "date part: {ts}");
        assert!(rest.ends_with('Z'), "must be UTC with a Z suffix: {ts}");
        let time = rest.trim_end_matches('Z');
        let fields: Vec<&str> = time.split(':').collect();
        assert_eq!(fields.len(), 3, "expected HH:MM:SS.mmm, got {time:?}");
        assert!(
            fields[2].contains('.'),
            "seconds field must carry fractional milliseconds: {time:?}"
        );
        let (secs, millis) = fields[2].split_once('.').expect("checked above");
        assert_eq!(secs.len(), 2, "seconds must be two digits: {time:?}");
        assert_eq!(millis.len(), 3, "expected millisecond precision: {time:?}");
    }

    #[test]
    fn schema_decode_errors_are_classified_as_invariant_failures() {
        let error = map_sqlx_err(sqlx_core::Error::ColumnNotFound("chain_hash".to_string()));
        assert!(matches!(error, TransactionStoreError::DatabaseInvariant(_)));
    }
}