symforge 11.20.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! Project-scoped durable replay admission for trusted embedded hosts.
//!
//! The old `FileReplayStore` is deliberately not exposed through this API. A
//! host must call `mark_started` before performing an external effect. After a
//! crash, `Started` and `Uncertain` never become executable by age or retry.
//!
//! `reserve` is deprecated: it writes no expiry, so a crashed owner's
//! `not_started` row stays forever. Prefer `reserve_with_lease`. That path
//! stores `lease_expires_at` and can replace one expired `not_started` row.
//! Takeover is `Acquired` with `OwnerLease::took_over` set, so
//! `ReserveOutcome` keeps its existing variants. The host wall clock is read
//! once inside the immediate transaction and bound into the compare-and-swap.
//! A backward step only delays takeover.
//!
//! `mark_started` refuses when a leased reservation has already expired; the
//! row stays `not_started` for takeover. `mark_started_with_lease` arms a fresh
//! execution lease on the `started` row.
//!
//! An expired `started` row is never taken over. Reads report it as
//! `Uncertain`, with `uncertain_since` equal to the lease end, and a
//! compare-and-swap rewrites that row. `reconcile` is still the only way back
//! to a terminal outcome.
//!
//! The embedder keeps its own response bytes and checks them with
//! `ReplayOutcome::response_digest`. Raw responses are never written here.
//! Large or secret-looking responses use
//! `ReplayOutcome::from_embedder_digest`: the embedder supplies length and
//! SHA-256, and owns the response secret scan. SymForge still scans the
//! post-image bytes passed into either constructor.

use std::fs;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use rusqlite::{Connection, ErrorCode, OpenFlags, OptionalExtension, TransactionBehavior, params};
use serde_json::Value;

const KEY_FRAME: &[u8] = b"symforge-idempotency-key-v1\0";
const MAX_KEY_BYTES: usize = 512;
const MAX_SCOPE_BYTES: usize = 256;
const MAX_REQUEST_BYTES: usize = 64 * 1024;
const MAX_RESPONSE_BYTES: usize = 64 * 1024;
const MAX_EVIDENCE_BYTES: usize = 64 * 1024;
const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(5);
const SCHEMA: &str = "
    CREATE TABLE IF NOT EXISTS replay_meta (
        singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
        project_hash TEXT NOT NULL,
        scope_hash TEXT NOT NULL,
        schema_version INTEGER NOT NULL,
        legacy_cutover_digest TEXT
    );
    CREATE TABLE IF NOT EXISTS replay_entries (
        key_hash TEXT PRIMARY KEY,
        request_hash TEXT NOT NULL,
        state TEXT NOT NULL CHECK (state IN ('not_started', 'started', 'uncertain', 'completed', 'failed')),
        generation INTEGER NOT NULL CHECK (generation > 0),
        owner_token BLOB,
        outcome_kind TEXT,
        outcome_digest TEXT,
        post_image_digest TEXT,
        evidence_digest TEXT,
        lease_expires_at INTEGER,
        uncertain_since INTEGER,
        CHECK ((state IN ('not_started', 'started')) = (owner_token IS NOT NULL))
    );
    CREATE TABLE IF NOT EXISTS replay_binding (
        singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
        root_anchor_key BLOB NOT NULL,
        state_anchor_key BLOB NOT NULL
    );
";

/// A raw host key. Its debug rendering cannot disclose the supplied bytes.
#[derive(Clone, PartialEq, Eq)]
pub struct ReplayKey(String);

impl ReplayKey {
    pub fn new(raw: impl Into<String>) -> Result<Self, ReplayError> {
        let raw = raw.into();
        if raw.is_empty() || raw.len() > MAX_KEY_BYTES {
            return Err(ReplayError::InvalidKey);
        }
        Ok(Self(raw))
    }

    fn hash(&self) -> String {
        let mut frame = Vec::with_capacity(KEY_FRAME.len() + self.0.len());
        frame.extend_from_slice(KEY_FRAME);
        frame.extend_from_slice(self.0.as_bytes());
        crate::hash::digest_hex(&frame)
    }
}

impl std::fmt::Debug for ReplayKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ReplayKey(<redacted>)")
    }
}

/// The old canonical JSON framing is retained so migration cannot rebind a key.
///
/// The second field is uncertain_since in epoch millis. It rides here so
/// ReplayRecord can stay a fully public struct: a new field there would
/// reject existing struct literals. Equality is the hash alone.
/// ponytail: move onto ReplayRecord when default field values stabilize
/// (rust-lang/rust#132162) or on a major bump.
#[derive(Clone)]
pub struct RequestFingerprint(String, Option<i64>);

impl PartialEq for RequestFingerprint {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl Eq for RequestFingerprint {}

impl std::fmt::Debug for RequestFingerprint {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_tuple("RequestFingerprint")
            .field(&self.0)
            .finish()
    }
}

impl RequestFingerprint {
    pub fn for_json(operation: &str, arguments: &Value) -> Result<Self, ReplayError> {
        if operation.is_empty()
            || operation.len() > 128
            || serde_json::to_vec(arguments)
                .map_err(|_| ReplayError::InvalidRequest)?
                .len()
                > MAX_REQUEST_BYTES
        {
            return Err(ReplayError::InvalidRequest);
        }
        let old = crate::idempotency::RequestHash::for_tool_request(operation, arguments)
            .map_err(|_| ReplayError::InvalidRequest)?;
        Ok(Self(old.as_str().to_owned(), None))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    fn uncertain_since(&self) -> Option<SystemTime> {
        self.1.and_then(system_time_from_ms)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplayState {
    NotStarted,
    Started,
    Uncertain,
    Completed,
    Failed,
}

impl ReplayState {
    fn as_str(self) -> &'static str {
        match self {
            Self::NotStarted => "not_started",
            Self::Started => "started",
            Self::Uncertain => "uncertain",
            Self::Completed => "completed",
            Self::Failed => "failed",
        }
    }

    fn parse(value: &str) -> rusqlite::Result<Self> {
        match value {
            "not_started" => Ok(Self::NotStarted),
            "started" => Ok(Self::Started),
            "uncertain" => Ok(Self::Uncertain),
            "completed" => Ok(Self::Completed),
            "failed" => Ok(Self::Failed),
            _ => Err(rusqlite::Error::InvalidQuery),
        }
    }
}

/// Only a category and digest of the host response are durable. Raw responses,
/// error messages, and payloads are never written to the replay database.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutcomeKind {
    Applied,
    NoChange,
    Rejected,
}

impl OutcomeKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Applied => "applied",
            Self::NoChange => "no_change",
            Self::Rejected => "rejected",
        }
    }

    fn parse(value: &str) -> rusqlite::Result<Self> {
        match value {
            "applied" => Ok(Self::Applied),
            "no_change" => Ok(Self::NoChange),
            "rejected" => Ok(Self::Rejected),
            _ => Err(rusqlite::Error::InvalidQuery),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplayOutcome {
    pub kind: OutcomeKind,
    response_digest: String,
    post_image_digest: String,
}

impl ReplayOutcome {
    /// Build an outcome from response and post-image bytes. Response length is
    /// capped at 64 KiB; both buffers are secret-scanned here. Prefer
    /// [`Self::from_embedder_digest`] when the response may exceed that cap or
    /// may contain secret-looking tokens the embedder has already handled.
    pub fn from_response_and_post_image(
        kind: OutcomeKind,
        response: &[u8],
        post_image: &[u8],
    ) -> Result<Self, ReplayError> {
        if response.len() > MAX_RESPONSE_BYTES
            || !matches!(
                crate::knowledge::scan_secret_bytes("replay-response", response),
                crate::knowledge::SecretScan::Clean
            )
            || !matches!(
                crate::knowledge::scan_secret_bytes("replay-post-image", post_image),
                crate::knowledge::SecretScan::Clean
            )
        {
            return Err(ReplayError::UnsafeOutcome);
        }
        Ok(Self {
            kind,
            response_digest: crate::hash::digest_hex(response),
            post_image_digest: crate::hash::digest_hex(post_image),
        })
    }

    /// Digest-only constructor for embedder-owned response bytes.
    ///
    /// `response_len` and `response_digest_hex` (lowercase SHA-256) are recorded
    /// without reading the response body. The embedder owns secret scanning of
    /// those bytes. SymForge still secret-scans and size-caps `post_image`.
    /// There is no store-side response size cap on this path: only the digest
    /// is persisted.
    pub fn from_embedder_digest(
        kind: OutcomeKind,
        response_len: usize,
        response_digest_hex: &str,
        post_image: &[u8],
    ) -> Result<Self, ReplayError> {
        if response_len == 0
            || response_digest_hex.len() != 64
            || !response_digest_hex
                .bytes()
                .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
            || post_image.len() > MAX_RESPONSE_BYTES
            || !matches!(
                crate::knowledge::scan_secret_bytes("replay-post-image", post_image),
                crate::knowledge::SecretScan::Clean
            )
        {
            return Err(ReplayError::UnsafeOutcome);
        }
        Ok(Self {
            kind,
            response_digest: response_digest_hex.to_owned(),
            post_image_digest: crate::hash::digest_hex(post_image),
        })
    }

    pub fn matches_post_image(&self, bytes: &[u8]) -> bool {
        self.post_image_digest == crate::hash::digest_hex(bytes)
    }

    /// Digest of the response bytes. The embedder stores those bytes itself
    /// and checks them against this value.
    pub fn response_digest(&self) -> &str {
        &self.response_digest
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplayRecord {
    pub key_hash: String,
    pub request: RequestFingerprint,
    pub state: ReplayState,
    pub generation: i64,
    pub outcome: Option<ReplayOutcome>,
    pub evidence_digest: Option<String>,
}

impl ReplayRecord {
    /// When the outcome became unknown: `mark_uncertain`'s clock, or the
    /// lease end of an expired `started` row.
    pub fn uncertain_since(&self) -> Option<SystemTime> {
        self.request.uncertain_since()
    }

    pub fn matches_post_image(&self, bytes: &[u8]) -> bool {
        self.state == ReplayState::Completed
            && self
                .outcome
                .as_ref()
                .is_some_and(|outcome| outcome.matches_post_image(bytes))
    }
}

/// This unforgeable lease is returned only to the winner of the SQL insert.
/// It is intentionally not Clone or Debug, and its token is never exposed.
pub struct OwnerLease {
    key_hash: String,
    request_hash: String,
    token: Vec<u8>,
    generation: i64,
    took_over: bool,
}

impl OwnerLease {
    /// `true` when this lease replaced an expired `not_started` reservation.
    pub fn took_over(&self) -> bool {
        self.took_over
    }
}

pub enum ReserveOutcome {
    Acquired(OwnerLease),
    Existing(ReplayRecord),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReconciliationResolution {
    Completed,
    Failed,
}

/// Trusted-host postcondition evidence. The caller must verify the actual
/// operation's effect before constructing this value; only its digest is stored.
#[derive(Clone, Debug)]
pub struct ReconciliationEvidence {
    observed_generation: i64,
    observation_digest: String,
}

/// Attests that the trusted host has stopped old replay writers before
/// enabling new-key admissions in a state directory with old JSON records.
pub struct LegacyCutoverEvidence(String);

impl LegacyCutoverEvidence {
    pub fn from_checkpoint(checkpoint: &[u8]) -> Result<Self, ReplayError> {
        if checkpoint.is_empty()
            || checkpoint.len() > MAX_EVIDENCE_BYTES
            || !matches!(
                crate::knowledge::scan_secret_bytes("replay-cutover", checkpoint),
                crate::knowledge::SecretScan::Clean
            )
        {
            return Err(ReplayError::UnsafeOutcome);
        }
        Ok(Self(crate::hash::digest_hex(checkpoint)))
    }
}

impl ReconciliationEvidence {
    pub fn from_observation(
        observed_generation: i64,
        observation: &[u8],
    ) -> Result<Self, ReplayError> {
        if observed_generation < 1
            || observation.is_empty()
            || observation.len() > MAX_EVIDENCE_BYTES
            || !matches!(
                crate::knowledge::scan_secret_bytes("replay-evidence", observation),
                crate::knowledge::SecretScan::Clean
            )
        {
            return Err(ReplayError::UnsafeOutcome);
        }
        Ok(Self {
            observed_generation,
            observation_digest: crate::hash::digest_hex(observation),
        })
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ReplayError {
    #[error("invalid replay key")]
    InvalidKey,
    #[error("invalid replay request")]
    InvalidRequest,
    #[error("replay outcome or evidence is unsafe to persist")]
    UnsafeOutcome,
    #[error("replay request conflicts with the stored key binding")]
    Conflict,
    #[error("legacy replay state requires explicit reconciliation")]
    LegacyStateRequiresReconciliation,
    #[error("legacy replay store requires an exclusive migration cutover")]
    LegacyCutoverRequired,
    #[error("replay owner or state changed")]
    StaleOwner,
    #[error("replay postcondition evidence does not match the asserted outcome")]
    InvalidEvidence,
    #[error("replay state cannot make the requested transition")]
    InvalidTransition,
    #[error("project state is bound to a different root")]
    WrongProject,
    #[error("project state is bound to a different physical root")]
    WrongPhysicalRoot,
    #[error("project state is bound to a different physical state directory")]
    WrongStateDirectory,
    #[error("project state is bound to a different host scope")]
    WrongScope,
    #[error("invalid replay host scope")]
    InvalidScope,
    #[error("replay project root must be an existing directory and state path must be absolute")]
    InvalidStatePath,
    #[error("replay state path is a symlink")]
    SymlinkStatePath,
    #[error("replay database is busy; retry the admission")]
    Busy,
    #[error("replay state I/O: {0}")]
    Io(#[from] std::io::Error),
    #[error("replay database: {0}")]
    Database(rusqlite::Error),
}

impl From<rusqlite::Error> for ReplayError {
    fn from(error: rusqlite::Error) -> Self {
        match error.sqlite_error_code() {
            Some(ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked) => Self::Busy,
            _ => Self::Database(error),
        }
    }
}

/// One durable replay database within a caller-supplied project state directory.
/// The state directory may be user-local, so its canonical project binding is
/// checked in SQLite on every open.
pub struct ReplayStore {
    db_path: PathBuf,
    legacy_records: PathBuf,
    project_root: PathBuf,
    state_dir: PathBuf,
    root_anchor_key: [u8; 16],
    state_anchor_key: [u8; 16],
    busy_timeout: Duration,
}

/// Test-only guard that keeps a `BEGIN IMMEDIATE` transaction open.
#[cfg(feature = "__test-internals")]
pub struct ImmediateHold {
    conn: Option<AnchoredConnection>,
}

#[cfg(feature = "__test-internals")]
impl Drop for ImmediateHold {
    fn drop(&mut self) {
        if let Some(conn) = self.conn.take() {
            let _ = conn.execute_batch("ROLLBACK");
        }
    }
}

struct AnchoredConnection {
    conn: Connection,
    _root: crate::live_index::index_lifecycle::physical_root::PhysicalRootLease,
    _state: crate::live_index::index_lifecycle::physical_root::PhysicalRootLease,
}

impl Deref for AnchoredConnection {
    type Target = Connection;

    fn deref(&self) -> &Self::Target {
        &self.conn
    }
}

impl DerefMut for AnchoredConnection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.conn
    }
}

impl ReplayStore {
    pub fn open(
        project_root: &Path,
        project_state_dir: &Path,
        scope: &str,
    ) -> Result<Self, ReplayError> {
        Self::open_with_anchor(
            project_root,
            project_state_dir,
            scope,
            None,
            DEFAULT_BUSY_TIMEOUT,
        )
    }

    /// Hold an IMMEDIATE transaction until drop. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn begin_immediate_hold(&self) -> Result<ImmediateHold, ReplayError> {
        let conn = self.connect()?;
        conn.execute_batch("BEGIN IMMEDIATE")?;
        Ok(ImmediateHold { conn: Some(conn) })
    }

    /// Test-only open with a shorter SQLite busy wait so contention surfaces
    /// as [`ReplayError::Busy`] without a five-second sleep.
    #[cfg(feature = "__test-internals")]
    pub fn open_with_busy_timeout(
        project_root: &Path,
        project_state_dir: &Path,
        scope: &str,
        busy_timeout: Duration,
    ) -> Result<Self, ReplayError> {
        Self::open_with_anchor(project_root, project_state_dir, scope, None, busy_timeout)
    }

    pub(crate) fn open_bound(
        project_root: &Path,
        project_state_dir: &Path,
        scope: &str,
        expected_anchor: [u8; 16],
    ) -> Result<Self, ReplayError> {
        Self::open_with_anchor(
            project_root,
            project_state_dir,
            scope,
            Some(expected_anchor),
            DEFAULT_BUSY_TIMEOUT,
        )
    }

    fn open_with_anchor(
        project_root: &Path,
        project_state_dir: &Path,
        scope: &str,
        expected_anchor: Option<[u8; 16]>,
        busy_timeout: Duration,
    ) -> Result<Self, ReplayError> {
        if scope.is_empty() || scope.len() > MAX_SCOPE_BYTES {
            return Err(ReplayError::InvalidScope);
        }
        if !project_root.is_absolute() || !project_state_dir.is_absolute() || !project_root.is_dir()
        {
            return Err(ReplayError::InvalidStatePath);
        }
        let root = fs::canonicalize(project_root)?;
        let root_lease =
            crate::live_index::index_lifecycle::physical_root::PhysicalRootLease::take(&root);
        let root_anchor_key = root_lease
            .opened_stable_key()
            .ok_or(ReplayError::WrongPhysicalRoot)?;
        if expected_anchor.is_some_and(|expected| expected != root_anchor_key) {
            return Err(ReplayError::WrongPhysicalRoot);
        }
        fs::create_dir_all(project_state_dir)?;
        let state = fs::canonicalize(project_state_dir)?;
        let state_lease =
            crate::live_index::index_lifecycle::physical_root::PhysicalRootLease::take(&state);
        let state_anchor_key = state_lease
            .opened_stable_key()
            .ok_or(ReplayError::WrongStateDirectory)?;
        let replay_dir = state.join("idempotency");
        if fs::symlink_metadata(&replay_dir).is_ok_and(|meta| meta.file_type().is_symlink()) {
            return Err(ReplayError::SymlinkStatePath);
        }
        fs::create_dir_all(&replay_dir)?;
        set_private_dir(&replay_dir)?;
        let scope_hash = crate::hash::digest_hex(scope.as_bytes());
        let original_db = replay_dir.join("replay-v1.sqlite3");
        let original_meta = match fs::symlink_metadata(&original_db) {
            Ok(metadata) => Some(metadata),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => return Err(ReplayError::Io(error)),
        };
        if original_meta
            .as_ref()
            .is_some_and(|meta| meta.file_type().is_symlink())
        {
            return Err(ReplayError::SymlinkStatePath);
        }
        let original_scope = if original_meta.is_some() {
            let conn = Connection::open_with_flags(&original_db, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
            Some(conn.query_row(
                "SELECT scope_hash FROM replay_meta WHERE singleton = 1",
                [],
                |row| row.get::<_, String>(0),
            )?)
        } else {
            None
        };
        // The original single-scope database stays at its historical path.
        // New scopes receive independent files, while every scope continues to
        // inspect the shared legacy JSON directory before admitting a key.
        let db_path = if original_scope.as_deref() == Some(scope_hash.as_str()) {
            original_db
        } else {
            let scopes_dir = replay_dir.join("scopes");
            if fs::symlink_metadata(&scopes_dir).is_ok_and(|meta| meta.file_type().is_symlink()) {
                return Err(ReplayError::SymlinkStatePath);
            }
            fs::create_dir_all(&scopes_dir)?;
            set_private_dir(&scopes_dir)?;
            let scoped_dir = scopes_dir.join(&scope_hash);
            if fs::symlink_metadata(&scoped_dir).is_ok_and(|meta| meta.file_type().is_symlink()) {
                return Err(ReplayError::SymlinkStatePath);
            }
            fs::create_dir_all(&scoped_dir)?;
            set_private_dir(&scoped_dir)?;
            scoped_dir.join("replay-v1.sqlite3")
        };
        if fs::symlink_metadata(&db_path).is_ok_and(|meta| meta.file_type().is_symlink()) {
            return Err(ReplayError::SymlinkStatePath);
        }
        let store = Self {
            db_path,
            legacy_records: replay_dir.join("records"),
            project_root: root.clone(),
            state_dir: state,
            root_anchor_key,
            state_anchor_key,
            busy_timeout,
        };
        let mut conn = store.connect()?;
        conn.execute_batch(SCHEMA)?;
        ensure_lease_columns(&conn)?;
        let project_hash = crate::hash::digest_hex(root.as_os_str().as_encoded_bytes());
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        tx.execute(
            "INSERT OR IGNORE INTO replay_meta(singleton, project_hash, scope_hash, schema_version) VALUES (1, ?1, ?2, 1)",
            params![project_hash, scope_hash],
        )?;
        let bound: (String, String, i64) = tx.query_row(
            "SELECT project_hash, scope_hash, schema_version FROM replay_meta WHERE singleton = 1",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )?;
        if bound.0 != project_hash || bound.2 != 1 {
            return Err(ReplayError::WrongProject);
        }
        if bound.1 != scope_hash {
            return Err(ReplayError::WrongScope);
        }
        match tx
            .query_row(
                "SELECT root_anchor_key, state_anchor_key FROM replay_binding WHERE singleton = 1",
                [],
                |row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Vec<u8>>(1)?)),
            )
            .optional()?
        {
            Some((root_key, state_key)) => {
                if root_key != root_anchor_key {
                    return Err(ReplayError::WrongPhysicalRoot);
                }
                if state_key != state_anchor_key {
                    return Err(ReplayError::WrongStateDirectory);
                }
            }
            None => {
                let entries: i64 =
                    tx.query_row("SELECT COUNT(*) FROM replay_entries", [], |row| row.get(0))?;
                if entries != 0 {
                    return Err(ReplayError::LegacyStateRequiresReconciliation);
                }
                tx.execute(
                    "INSERT INTO replay_binding(singleton, root_anchor_key, state_anchor_key) VALUES (1, ?1, ?2)",
                    params![root_anchor_key.as_slice(), state_anchor_key.as_slice()],
                )?;
            }
        }
        tx.commit()?;
        store.ensure_current_anchors()?;
        set_private_file(&store.db_path)?;
        Ok(store)
    }

    /// The host must first stop old replay writers and verify that they cannot
    /// restart against this state directory. The checkpoint digest is kept for
    /// audit; each old per-key record still refuses automatic replay/admission.
    pub fn confirm_legacy_cutover(
        &self,
        evidence: &LegacyCutoverEvidence,
    ) -> Result<(), ReplayError> {
        let conn = self.connect()?;
        conn.execute(
            "UPDATE replay_meta SET legacy_cutover_digest = ?1 WHERE singleton = 1
                 AND (legacy_cutover_digest IS NULL OR legacy_cutover_digest = ?1)",
            params![evidence.0],
        )?;
        let stored: Option<String> = conn.query_row(
            "SELECT legacy_cutover_digest FROM replay_meta WHERE singleton = 1",
            [],
            |row| row.get(0),
        )?;
        if stored.as_deref() != Some(evidence.0.as_str()) {
            return Err(ReplayError::LegacyCutoverRequired);
        }
        Ok(())
    }

    fn ensure_current_anchors(&self) -> Result<(), ReplayError> {
        use crate::live_index::index_lifecycle::physical_root::PhysicalRootAnchor;
        if PhysicalRootAnchor::observe(&self.project_root).map(PhysicalRootAnchor::stable_key)
            != Some(self.root_anchor_key)
        {
            return Err(ReplayError::WrongPhysicalRoot);
        }
        if PhysicalRootAnchor::observe(&self.state_dir).map(PhysicalRootAnchor::stable_key)
            != Some(self.state_anchor_key)
        {
            return Err(ReplayError::WrongStateDirectory);
        }
        Ok(())
    }

    fn connect(&self) -> Result<AnchoredConnection, ReplayError> {
        use crate::live_index::index_lifecycle::physical_root::PhysicalRootLease;
        let root = PhysicalRootLease::take(&self.project_root);
        if root.opened_stable_key() != Some(self.root_anchor_key) {
            return Err(ReplayError::WrongPhysicalRoot);
        }
        let state = PhysicalRootLease::take(&self.state_dir);
        if state.opened_stable_key() != Some(self.state_anchor_key) {
            return Err(ReplayError::WrongStateDirectory);
        }
        let conn = Connection::open(&self.db_path)?;
        conn.busy_timeout(self.busy_timeout)?;
        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;")?;
        self.ensure_current_anchors()?;
        Ok(AnchoredConnection {
            conn,
            _root: root,
            _state: state,
        })
    }

    fn legacy_guard(&self, key_hash: &str) -> Result<bool, ReplayError> {
        let metadata = match fs::symlink_metadata(&self.legacy_records) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(ReplayError::Io(error)),
        };
        if !metadata.is_dir() || metadata.file_type().is_symlink() {
            return Err(ReplayError::LegacyStateRequiresReconciliation);
        }
        match fs::symlink_metadata(self.legacy_records.join(key_hash)) {
            Ok(_) => Err(ReplayError::LegacyStateRequiresReconciliation),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
            Err(error) => Err(ReplayError::Io(error)),
        }
    }

    /// Before old and new processes can coexist, the host must enforce an
    /// exclusive cutover. A legacy directory blocks all new reservations.
    /// After cutover, remove or archive that directory outside this API; old
    /// bytes are never modified here. Existing per-key old records still block
    /// if the directory is retained.
    fn ensure_legacy_admits(&self, key_hash: &str) -> Result<(), ReplayError> {
        if self.legacy_guard(key_hash)? {
            let cutover: Option<String> = self.connect()?.query_row(
                "SELECT legacy_cutover_digest FROM replay_meta WHERE singleton = 1",
                [],
                |row| row.get(0),
            )?;
            if cutover.is_none() {
                return Err(ReplayError::LegacyCutoverRequired);
            }
        }
        Ok(())
    }

    /// Unleased reservation. Prefer [`Self::reserve_with_lease`]: a row written
    /// here has no `lease_expires_at`, so a crash leaves `not_started` forever
    /// and neither takeover nor `fold_expired_started` can recover it.
    #[deprecated(note = "use reserve_with_lease; unleased not_started rows never expire")]
    pub fn reserve(
        &self,
        key: &ReplayKey,
        request: &RequestFingerprint,
    ) -> Result<ReserveOutcome, ReplayError> {
        self.reserve_inner(key, request, None, None)
    }

    /// As `reserve`, but the `not_started` row expires. An expired `not_started`
    /// row of the same request is taken over by one caller. A live row, and
    /// every `started` or `uncertain` row, returns `Existing`.
    pub fn reserve_with_lease(
        &self,
        key: &ReplayKey,
        request: &RequestFingerprint,
        lease: Duration,
    ) -> Result<ReserveOutcome, ReplayError> {
        self.reserve_inner(key, request, Some(lease), None)
    }

    /// Same admission as `reserve_with_lease`, using one caller-supplied clock
    /// reading for the compare-and-swap. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn reserve_with_lease_at(
        &self,
        key: &ReplayKey,
        request: &RequestFingerprint,
        lease: Duration,
        now: SystemTime,
    ) -> Result<ReserveOutcome, ReplayError> {
        self.reserve_inner(key, request, Some(lease), Some(time_to_ms(now)))
    }

    fn reserve_inner(
        &self,
        key: &ReplayKey,
        request: &RequestFingerprint,
        lease: Option<Duration>,
        now_ms: Option<i64>,
    ) -> Result<ReserveOutcome, ReplayError> {
        let key_hash = key.hash();
        self.ensure_legacy_admits(&key_hash)?;
        let mut conn = self.connect()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let now = now_ms.unwrap_or_else(wall_now_ms);
        fold_expired_started(&tx, &key_hash, now)?;
        let inserted = match lease {
            Some(lease) => tx.execute(
                "INSERT OR IGNORE INTO replay_entries(
                    key_hash, request_hash, state, generation, owner_token, lease_expires_at)
                 VALUES (?1, ?2, 'not_started', 1, randomblob(32), ?3)",
                params![
                    key_hash,
                    request.as_str(),
                    now.saturating_add(lease_to_ms(lease))
                ],
            )?,
            None => tx.execute(
                "INSERT OR IGNORE INTO replay_entries(
                    key_hash, request_hash, state, generation, owner_token)
                 VALUES (?1, ?2, 'not_started', 1, randomblob(32))",
                params![key_hash, request.as_str()],
            )?,
        };
        if inserted == 1 {
            let token = owner_token(&tx, &key_hash)?;
            tx.commit()?;
            return Ok(ReserveOutcome::Acquired(OwnerLease {
                key_hash,
                request_hash: request.as_str().to_owned(),
                token,
                generation: 1,
                took_over: false,
            }));
        }
        if let Some(lease) = lease {
            let head = read_head(&tx, &key_hash)?;
            if head.request_hash != request.as_str() {
                tx.commit()?;
                return Err(ReplayError::Conflict);
            }
            let expired = head.state == "not_started"
                && head.lease_expires_at.is_some_and(|expires| expires <= now);
            if expired && let Some(token) = head.token.clone() {
                let changed = tx.execute(
                    "UPDATE replay_entries
                         SET owner_token = randomblob(32),
                             generation = generation + 1,
                             lease_expires_at = ?1
                         WHERE key_hash = ?2 AND request_hash = ?3 AND state = 'not_started'
                           AND generation = ?4 AND owner_token = ?5
                           AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?6",
                    params![
                        now.saturating_add(lease_to_ms(lease)),
                        key_hash,
                        request.as_str(),
                        head.generation,
                        token,
                        now,
                    ],
                )?;
                if changed == 1 {
                    let token = owner_token(&tx, &key_hash)?;
                    tx.commit()?;
                    return Ok(ReserveOutcome::Acquired(OwnerLease {
                        key_hash,
                        request_hash: request.as_str().to_owned(),
                        token,
                        generation: head.generation + 1,
                        took_over: true,
                    }));
                }
            }
        }
        let record = read_record(&tx, &key_hash)?.ok_or(ReplayError::StaleOwner)?;
        tx.commit()?;
        if record.request != *request {
            return Err(ReplayError::Conflict);
        }
        Ok(ReserveOutcome::Existing(record))
    }

    pub fn inspect(&self, key: &ReplayKey) -> Result<Option<ReplayRecord>, ReplayError> {
        self.inspect_with_now(key, None)
    }

    /// `inspect` at one caller-supplied clock reading. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn inspect_at(
        &self,
        key: &ReplayKey,
        now: SystemTime,
    ) -> Result<Option<ReplayRecord>, ReplayError> {
        self.inspect_with_now(key, Some(time_to_ms(now)))
    }

    fn inspect_with_now(
        &self,
        key: &ReplayKey,
        now_ms: Option<i64>,
    ) -> Result<Option<ReplayRecord>, ReplayError> {
        let key_hash = key.hash();
        self.legacy_guard(&key_hash)?;
        let mut conn = self.connect()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        fold_expired_started(&tx, &key_hash, now_ms.unwrap_or_else(wall_now_ms))?;
        let record = read_record(&tx, &key_hash)?;
        tx.commit()?;
        Ok(record)
    }

    /// Remaining lifetime of a live `not_started` or `started` lease.
    /// `None` when the row has no lease, is expired, or is not in those states.
    pub fn lease_remaining(&self, key: &ReplayKey) -> Result<Option<Duration>, ReplayError> {
        self.lease_remaining_at_ms(key, None)
    }

    /// `lease_remaining` at one caller-supplied clock reading. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn lease_remaining_at(
        &self,
        key: &ReplayKey,
        now: SystemTime,
    ) -> Result<Option<Duration>, ReplayError> {
        self.lease_remaining_at_ms(key, Some(time_to_ms(now)))
    }

    fn lease_remaining_at_ms(
        &self,
        key: &ReplayKey,
        now_ms: Option<i64>,
    ) -> Result<Option<Duration>, ReplayError> {
        let key_hash = key.hash();
        self.legacy_guard(&key_hash)?;
        let now = now_ms.unwrap_or_else(wall_now_ms);
        let row = self
            .connect()?
            .query_row(
                "SELECT state, lease_expires_at FROM replay_entries WHERE key_hash = ?1",
                params![key_hash],
                |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<i64>>(1)?)),
            )
            .optional()?;
        Ok(remaining_lease(row, now))
    }

    pub fn mark_started(&self, lease: &OwnerLease) -> Result<ReplayRecord, ReplayError> {
        self.advance_to_started(lease, None, None)
    }

    /// Commit `not_started` -> `started` and arm a fresh execution lease.
    pub fn mark_started_with_lease(
        &self,
        lease: &OwnerLease,
        started_lease: Duration,
    ) -> Result<ReplayRecord, ReplayError> {
        self.advance_to_started(lease, Some(started_lease), None)
    }

    /// `mark_started_with_lease` at one caller-supplied clock reading. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn mark_started_with_lease_at(
        &self,
        lease: &OwnerLease,
        started_lease: Duration,
        now: SystemTime,
    ) -> Result<ReplayRecord, ReplayError> {
        self.advance_to_started(lease, Some(started_lease), Some(time_to_ms(now)))
    }

    /// `mark_started` at one caller-supplied clock reading. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn mark_started_at(
        &self,
        lease: &OwnerLease,
        now: SystemTime,
    ) -> Result<ReplayRecord, ReplayError> {
        self.advance_to_started(lease, None, Some(time_to_ms(now)))
    }

    /// Extend a live `not_started` or `started` lease by `extension` from now.
    ///
    /// Performs a compare-and-swap on `key_hash`, `request_hash`, `owner_token`,
    /// state (`not_started` at `lease.generation` or `started` at
    /// `lease.generation + 1`), and `lease_expires_at > now`. Never revives an
    /// expired or unleased row and does not advance `generation`, so `lease`
    /// remains valid for subsequent renewals or terminal transitions.
    pub fn renew_lease(
        &self,
        lease: &OwnerLease,
        extension: Duration,
    ) -> Result<ReplayRecord, ReplayError> {
        self.renew_lease_inner(lease, extension, None)
    }

    /// `renew_lease` at one caller-supplied clock reading. Test builds only.
    #[cfg(feature = "__test-internals")]
    pub fn renew_lease_at(
        &self,
        lease: &OwnerLease,
        extension: Duration,
        now: SystemTime,
    ) -> Result<ReplayRecord, ReplayError> {
        self.renew_lease_inner(lease, extension, Some(time_to_ms(now)))
    }

    /// Release is valid only before the host has begun the external effect.
    /// The owner token and generation are compared in the deletion itself.
    pub fn release_not_started(&self, lease: &OwnerLease) -> Result<(), ReplayError> {
        let changed = self.connect()?.execute(
            "DELETE FROM replay_entries WHERE key_hash = ?1 AND request_hash = ?2
             AND state = 'not_started' AND generation = ?3 AND owner_token = ?4",
            params![
                lease.key_hash,
                lease.request_hash,
                lease.generation,
                lease.token
            ],
        )?;
        if changed != 1 {
            return Err(ReplayError::StaleOwner);
        }
        Ok(())
    }

    pub fn complete(
        &self,
        lease: &OwnerLease,
        outcome: &ReplayOutcome,
    ) -> Result<ReplayRecord, ReplayError> {
        self.advance_owned(
            lease,
            ReplayState::Started,
            ReplayState::Completed,
            Some(outcome),
        )
    }

    /// Use only for a known terminal failure. If effect status is ambiguous,
    /// call `mark_uncertain` and require reconciliation instead.
    pub fn fail(
        &self,
        lease: &OwnerLease,
        outcome: &ReplayOutcome,
    ) -> Result<ReplayRecord, ReplayError> {
        if outcome.kind != OutcomeKind::Rejected {
            return Err(ReplayError::InvalidTransition);
        }
        self.advance_owned(
            lease,
            ReplayState::Started,
            ReplayState::Failed,
            Some(outcome),
        )
    }

    pub fn mark_uncertain(&self, lease: &OwnerLease) -> Result<ReplayRecord, ReplayError> {
        self.advance_owned(lease, ReplayState::Started, ReplayState::Uncertain, None)
    }

    fn advance_to_started(
        &self,
        lease: &OwnerLease,
        started_lease: Option<Duration>,
        now_ms: Option<i64>,
    ) -> Result<ReplayRecord, ReplayError> {
        self.legacy_guard(&lease.key_hash)?;
        let mut conn = self.connect()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let now = now_ms.unwrap_or_else(wall_now_ms);
        let next_generation = lease.generation + 1;
        let fresh_expiry = started_lease.map(|lease| now.saturating_add(lease_to_ms(lease)));
        let changed = tx.execute(
            "UPDATE replay_entries SET state = 'started', generation = ?1,
                 owner_token = owner_token,
                 lease_expires_at = COALESCE(?2, lease_expires_at)
             WHERE key_hash = ?3 AND request_hash = ?4 AND state = 'not_started'
                 AND generation = ?5 AND owner_token = ?6
                 AND (lease_expires_at IS NULL OR lease_expires_at > ?7)",
            params![
                next_generation,
                fresh_expiry,
                lease.key_hash,
                lease.request_hash,
                lease.generation,
                lease.token,
                now,
            ],
        )?;
        if changed != 1 {
            return Err(ReplayError::StaleOwner);
        }
        let record = read_record(&tx, &lease.key_hash)?.ok_or(ReplayError::StaleOwner)?;
        tx.commit()?;
        Ok(record)
    }

    fn renew_lease_inner(
        &self,
        lease: &OwnerLease,
        extension: Duration,
        now_ms: Option<i64>,
    ) -> Result<ReplayRecord, ReplayError> {
        self.legacy_guard(&lease.key_hash)?;
        let mut conn = self.connect()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let now = now_ms.unwrap_or_else(wall_now_ms);
        let fresh_expiry = now.saturating_add(lease_to_ms(extension));
        let changed = tx.execute(
            "UPDATE replay_entries
                 SET lease_expires_at = ?1
             WHERE key_hash = ?2 AND request_hash = ?3 AND owner_token = ?4
                 AND ((state = 'not_started' AND generation = ?5)
                      OR (state = 'started' AND generation = ?6))
                 AND lease_expires_at IS NOT NULL AND lease_expires_at > ?7",
            params![
                fresh_expiry,
                lease.key_hash,
                lease.request_hash,
                lease.token,
                lease.generation,
                lease.generation + 1,
                now,
            ],
        )?;
        if changed != 1 {
            return Err(ReplayError::StaleOwner);
        }
        let record = read_record(&tx, &lease.key_hash)?.ok_or(ReplayError::StaleOwner)?;
        tx.commit()?;
        Ok(record)
    }

    fn advance_owned(
        &self,
        lease: &OwnerLease,
        from: ReplayState,
        to: ReplayState,
        outcome: Option<&ReplayOutcome>,
    ) -> Result<ReplayRecord, ReplayError> {
        self.legacy_guard(&lease.key_hash)?;
        let mut conn = self.connect()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let next_generation = lease.generation
            + if from == ReplayState::NotStarted {
                1
            } else {
                2
            };
        let changed = tx.execute(
            "UPDATE replay_entries SET state = ?1, generation = ?2,
                 owner_token = CASE WHEN ?1 = 'started' THEN owner_token ELSE NULL END,
                 outcome_kind = ?3, outcome_digest = ?4, post_image_digest = ?5,
                 uncertain_since = CASE WHEN ?1 = 'uncertain' THEN ?11 ELSE uncertain_since END
             WHERE key_hash = ?6 AND request_hash = ?7 AND state = ?8
                 AND generation = ?9 AND owner_token = ?10",
            params![
                to.as_str(),
                next_generation,
                outcome.map(|value| value.kind.as_str()),
                outcome.map(|value| value.response_digest.as_str()),
                outcome.map(|value| value.post_image_digest.as_str()),
                lease.key_hash,
                lease.request_hash,
                from.as_str(),
                lease.generation
                    + if from == ReplayState::NotStarted {
                        0
                    } else {
                        1
                    },
                lease.token,
                wall_now_ms(),
            ],
        )?;
        if changed != 1 {
            return Err(ReplayError::StaleOwner);
        }
        let record = read_record(&tx, &lease.key_hash)?.ok_or(ReplayError::StaleOwner)?;
        tx.commit()?;
        Ok(record)
    }

    /// A trusted host may classify an interrupted operation only after it has
    /// verified its postcondition. CAS on the observed generation fences a
    /// concurrent owner completion. This never creates a fresh execution.
    pub fn reconcile(
        &self,
        key: &ReplayKey,
        request: &RequestFingerprint,
        evidence: &ReconciliationEvidence,
        resolution: ReconciliationResolution,
        outcome: &ReplayOutcome,
    ) -> Result<ReplayRecord, ReplayError> {
        if evidence.observation_digest != outcome.post_image_digest {
            return Err(ReplayError::InvalidEvidence);
        }
        let key_hash = key.hash();
        self.legacy_guard(&key_hash)?;
        let mut conn = self.connect()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let current = read_record(&tx, &key_hash)?.ok_or(ReplayError::InvalidTransition)?;
        if current.request != *request {
            return Err(ReplayError::Conflict);
        }
        if !matches!(current.state, ReplayState::Started | ReplayState::Uncertain) {
            return Err(ReplayError::InvalidTransition);
        }
        let target = match resolution {
            ReconciliationResolution::Completed => ReplayState::Completed,
            ReconciliationResolution::Failed if outcome.kind == OutcomeKind::Rejected => {
                ReplayState::Failed
            }
            ReconciliationResolution::Failed => return Err(ReplayError::InvalidTransition),
        };
        let changed = tx.execute(
            "UPDATE replay_entries SET state = ?1, generation = generation + 1,
                owner_token = NULL, outcome_kind = ?2, outcome_digest = ?3,
                post_image_digest = ?4, evidence_digest = ?5, uncertain_since = NULL
             WHERE key_hash = ?6 AND request_hash = ?7 AND generation = ?8
                AND state IN ('started', 'uncertain')",
            params![
                target.as_str(),
                outcome.kind.as_str(),
                outcome.response_digest,
                outcome.post_image_digest,
                evidence.observation_digest,
                key_hash,
                request.as_str(),
                evidence.observed_generation
            ],
        )?;
        if changed != 1 {
            return Err(ReplayError::StaleOwner);
        }
        let record = read_record(&tx, &key_hash)?.ok_or(ReplayError::StaleOwner)?;
        tx.commit()?;
        Ok(record)
    }
}

fn wall_now_ms() -> i64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(duration) => i64::try_from(duration.as_millis()).unwrap_or(i64::MAX),
        // Before the epoch the lease only lasts longer. That delays takeover.
        Err(_) => 0,
    }
}

#[cfg(feature = "__test-internals")]
fn time_to_ms(now: SystemTime) -> i64 {
    match now.duration_since(UNIX_EPOCH) {
        Ok(duration) => i64::try_from(duration.as_millis()).unwrap_or(i64::MAX),
        Err(_) => 0,
    }
}

fn system_time_from_ms(ms: i64) -> Option<SystemTime> {
    if ms < 0 {
        return None;
    }
    UNIX_EPOCH.checked_add(Duration::from_millis(u64::try_from(ms).ok()?))
}

fn lease_to_ms(lease: Duration) -> i64 {
    i64::try_from(lease.as_millis()).unwrap_or(i64::MAX)
}

fn ensure_lease_columns(conn: &Connection) -> Result<(), ReplayError> {
    for name in ["lease_expires_at", "uncertain_since"] {
        let mut info = conn.prepare("PRAGMA table_info(replay_entries)")?;
        let present = info
            .query_map([], |row| row.get::<_, String>(1))?
            .collect::<Result<Vec<_>, _>>()?
            .iter()
            .any(|column| column == name);
        drop(info);
        if present {
            continue;
        }
        let sql = format!("ALTER TABLE replay_entries ADD COLUMN {name} INTEGER");
        match conn.execute(&sql, []) {
            Ok(_) => {}
            Err(error) if error.to_string().contains("duplicate column") => {}
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}

struct EntryHead {
    request_hash: String,
    state: String,
    generation: i64,
    token: Option<Vec<u8>>,
    lease_expires_at: Option<i64>,
}

fn read_head(conn: &Connection, key_hash: &str) -> Result<EntryHead, ReplayError> {
    conn.query_row(
        "SELECT request_hash, state, generation, owner_token, lease_expires_at
         FROM replay_entries WHERE key_hash = ?1",
        params![key_hash],
        |row| {
            Ok(EntryHead {
                request_hash: row.get(0)?,
                state: row.get(1)?,
                generation: row.get(2)?,
                token: row.get(3)?,
                lease_expires_at: row.get(4)?,
            })
        },
    )
    .optional()?
    .ok_or(ReplayError::StaleOwner)
}

fn owner_token(conn: &Connection, key_hash: &str) -> Result<Vec<u8>, ReplayError> {
    conn.query_row(
        "SELECT owner_token FROM replay_entries WHERE key_hash = ?1",
        params![key_hash],
        |row| row.get(0),
    )
    .map_err(ReplayError::from)
}

fn fold_expired_started(conn: &Connection, key_hash: &str, now: i64) -> Result<(), ReplayError> {
    conn.execute(
        "UPDATE replay_entries
         SET state = 'uncertain',
             generation = generation + 1,
             owner_token = NULL,
             uncertain_since = lease_expires_at
         WHERE key_hash = ?1 AND state = 'started'
           AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?2",
        params![key_hash, now],
    )?;
    Ok(())
}

fn remaining_lease(row: Option<(String, Option<i64>)>, now: i64) -> Option<Duration> {
    let (state, expires) = row?;
    if state != "not_started" && state != "started" {
        return None;
    }
    let expires = expires?;
    if expires <= now {
        return None;
    }
    Some(Duration::from_millis(
        u64::try_from(expires - now).unwrap_or(u64::MAX),
    ))
}

fn read_record(conn: &Connection, key_hash: &str) -> Result<Option<ReplayRecord>, ReplayError> {
    conn.query_row(
        "SELECT key_hash, request_hash, state, generation, outcome_kind, outcome_digest, post_image_digest, evidence_digest, uncertain_since
         FROM replay_entries WHERE key_hash = ?1",
        params![key_hash],
        |row| {
            let state: String = row.get(2)?;
            let kind: Option<String> = row.get(4)?;
            let digest: Option<String> = row.get(5)?;
            let post_image: Option<String> = row.get(6)?;
            Ok(ReplayRecord {
                key_hash: row.get(0)?,
                request: RequestFingerprint(row.get(1)?, row.get(8)?),
                state: ReplayState::parse(&state)?,
                generation: row.get(3)?,
                outcome: match (kind, digest, post_image) {
                    (Some(kind), Some(digest), Some(post_image_digest)) => Some(ReplayOutcome {
                        kind: OutcomeKind::parse(&kind)?,
                        response_digest: digest,
                        post_image_digest,
                    }),
                    (None, None, None) => None,
                    _ => return Err(rusqlite::Error::InvalidQuery),
                },
                evidence_digest: row.get(7)?,
            })
        },
    )
    .optional()
    .map_err(ReplayError::from)
}

#[cfg(unix)]
fn set_private_dir(path: &Path) -> Result<(), std::io::Error> {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(path, fs::Permissions::from_mode(0o700))
}

#[cfg(not(unix))]
fn set_private_dir(_path: &Path) -> Result<(), std::io::Error> {
    Ok(())
}

#[cfg(unix)]
fn set_private_file(path: &Path) -> Result<(), std::io::Error> {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
}

#[cfg(not(unix))]
fn set_private_file(_path: &Path) -> Result<(), std::io::Error> {
    Ok(())
}