clt-rs 0.6.19

File-backed task manager with a TUI Kanban board and multi-project Codex agent registry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
use anyhow::{Context, Result};
use clt_database::turso::{Connection, Database, params, transaction::TransactionBehavior};

use super::RepositoryDatabase;
use crate::{
    agent::{
        AGENT_EXTERNAL_COMPLETION_REASON, AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX, AgentGitMode,
        AgentRunOutcome, GitFinalizationRecord, GitFinalizationState, NewGitFinalization,
        TursoAgentStore, git_finalization_record_from_row, query_count, row_integer,
        row_optional_integer, row_optional_text, row_text, update_project_after_run,
    },
    managed_git::AgentGitStartState,
    runner::agent_timestamp,
};

#[cfg(test)]
#[path = "tests/git_journals.rs"]
mod tests;

/// Persistence for launch boundaries and managed Git finalization journals.
pub(in crate::agent) struct GitJournalsRepository(RepositoryDatabase);

impl GitJournalsRepository {
    pub(in crate::agent) fn new(db: &Database) -> Self {
        Self(RepositoryDatabase::new(db))
    }

    pub(in crate::agent) async fn connect(&self) -> Result<Connection> {
        self.0.connect().await
    }
}

impl TursoAgentStore {
    /// Cancel an unbound journal only after the caller has locked the board and
    /// proved that no task or nested board still references its exact session.
    pub(crate) fn cancel_orphaned_working_git_finalization_blocking(
        &self,
        expected: &GitFinalizationRecord,
        finalizer_holder: &str,
        reason: &str,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
            let mut conn = self.repositories.git_journals.connect().await?;
            let transaction = conn
                .transaction_with_behavior(TransactionBehavior::Immediate)
                .await
                .context("Failed to begin cancelling an abandoned unbound Git journal")?;
            let current = {
                let mut rows = transaction
                    .query(
                        "SELECT project_id, codex_session_id, state, git_mode, starting_head,
                                branch_ref, upstream_ref, worktree_baseline, task_identity,
                                owner_run_token, commit_oid, generation, last_error, created_at,
                                updated_at, completed_at, acknowledged_at, acknowledged_run_id
                           FROM git_finalizations
                          WHERE project_id = ?1 AND codex_session_id = ?2",
                        params![expected.project_id, expected.codex_session_id.as_str()],
                    )
                    .await
                    .context("Failed to recheck the exact abandoned Git journal")?;
                rows.next()
                    .await
                    .context("Failed to read the abandoned Git journal snapshot")?
                    .map(|row| git_finalization_record_from_row(&row))
                    .transpose()?
            };
            let Some(current) = current else {
                transaction
                    .rollback()
                    .await
                    .context("Failed to finish inspecting an absent orphaned Git journal")?;
                return Ok(false);
            };
            if current != *expected
                || current.state != GitFinalizationState::Working
                || current.task_identity.is_some()
                || current.commit_oid.is_some()
                || current.owner_run_token.is_some()
                || current.completed_at.is_some()
                || current.acknowledged_at.is_some()
                || current.acknowledged_run_id.is_some()
            {
                transaction
                    .rollback()
                    .await
                    .context("Failed to finish rejecting a changed or bound Git journal")?;
                return Ok(false);
            }
            let recovery_token = format!(
                "{AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX}{}",
                expected.generation
            );
            let now = agent_timestamp();
            let owns_idle_project = query_count(
                &transaction,
                "SELECT COUNT(*) FROM leases l
                  WHERE l.project_id = ?1 AND l.holder = ?2
                    AND CAST(l.expires_at AS INTEGER) > CAST(?3 AS INTEGER)
                    AND NOT EXISTS (
                        SELECT 1 FROM agent_workers w
                         WHERE w.project_id = ?1
                           AND w.state IN ('dispatching', 'running', 'finalizing')
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM session_controls sc
                         WHERE sc.project_id = ?1
                           AND NOT (
                               sc.child_pid IS NULL
                               AND sc.interactive_holder IS NULL
                               AND sc.interactive_launch_token IS NULL
                               AND (sc.state = 'stopped'
                                    OR (sc.state = 'resume_requested'
                                        AND EXISTS (
                                            SELECT 1 FROM git_finalizations g
                                             WHERE g.project_id = sc.project_id
                                               AND g.codex_session_id = sc.codex_session_id
                                               AND g.state IN ('working', 'tracking', 'commit_pending', 'push_pending')
                                               AND sc.run_token = ?4 || CAST(g.generation AS TEXT)
                                        )))
                           )
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM session_controls sc
                         WHERE sc.project_id = ?1 AND sc.codex_session_id = ?5
                           AND NOT COALESCE((
                               (sc.state = 'resume_requested' AND sc.run_token = ?6)
                               OR (sc.state = 'stopped' AND (sc.run_token IS NULL OR sc.run_token = ?6))
                           ), 0)
                    )",
                params![
                    expected.project_id,
                    finalizer_holder,
                    now.as_str(),
                    AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX,
                    expected.codex_session_id.as_str(),
                    recovery_token.as_str(),
                ],
            )
            .await?
                == 1;
            if !owns_idle_project {
                transaction
                    .rollback()
                    .await
                    .context("Failed to finish rejecting an orphaned Git journal without its idle fence")?;
                return Ok(false);
            }
            expected
                .generation
                .checked_add(1)
                .context("Abandoned Git journal generation overflowed")?;
            let changed = transaction
                .execute(
                    "UPDATE git_finalizations
                        SET state = 'cancelled', owner_run_token = NULL,
                            generation = generation + 1, last_error = ?1,
                            updated_at = ?2, completed_at = ?2
                      WHERE project_id = ?3 AND codex_session_id = ?4
                        AND state = 'working' AND generation = ?5
                        AND task_identity IS NULL AND commit_oid IS NULL
                        AND owner_run_token IS NULL",
                    params![
                        reason,
                        updated_at,
                        expected.project_id,
                        expected.codex_session_id.as_str(),
                        expected.generation,
                    ],
                )
                .await
                .context("Failed to cancel the exact abandoned Git journal")?;
            if changed != 1 {
                transaction
                    .rollback()
                    .await
                    .context("Failed to roll back a rejected orphaned Git journal cancellation")?;
                return Ok(false);
            }
            transaction
                .execute(
                    "DELETE FROM session_controls
                      WHERE project_id = ?1 AND codex_session_id = ?2
                        AND child_pid IS NULL
                        AND interactive_holder IS NULL
                        AND interactive_launch_token IS NULL
                        AND ((state = 'resume_requested' AND run_token = ?3)
                             OR (state = 'stopped' AND (run_token IS NULL OR run_token = ?3)))",
                    params![
                        expected.project_id,
                        expected.codex_session_id.as_str(),
                        recovery_token.as_str(),
                    ],
                )
                .await
                .context("Failed to clear the abandoned journal's exact idle session control")?;
            transaction
                .commit()
                .await
                .context("Failed to durably cancel the abandoned unbound Git journal")?;
            Ok(true)
        })
    }

    /// Retire an unbound journal whose owning run can no longer be running.
    ///
    /// A run that ends after registering its Codex session but before claiming a
    /// task leaves a WORKING journal with no task identity and no commit proof.
    /// Its recorded owner token belongs to a run that already finished, so the
    /// normal owner-fenced retirement can never match again and the project
    /// stays wedged. This retires that exact journal only while the project is
    /// idle, so a live run is never disturbed.
    pub(crate) fn retire_abandoned_unbound_git_finalization_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        reason: &str,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
            let mut conn = self.repositories.git_journals.connect().await?;
            let transaction = conn
                .transaction_with_behavior(TransactionBehavior::Immediate)
                .await
                .context("Failed to begin retiring an abandoned unbound Git journal")?;
            let idle_project = query_count(
                &transaction,
                "SELECT COUNT(*) FROM git_finalizations g
                  WHERE g.project_id = ?1 AND g.codex_session_id = ?2
                    AND g.state = 'working' AND g.generation = ?3
                    AND g.task_identity IS NULL AND g.commit_oid IS NULL
                    AND g.completed_at IS NULL AND g.acknowledged_at IS NULL
                    AND g.owner_run_token IS NOT NULL
                    AND NOT EXISTS (
                        SELECT 1 FROM agent_workers w
                         WHERE w.project_id = ?1
                           AND w.state IN ('dispatching', 'running', 'finalizing')
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM agent_workers owner
                         WHERE owner.project_id = ?1
                           AND owner.worker_token = g.owner_run_token
                           AND owner.state IN ('dispatching', 'running', 'finalizing')
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM leases l
                         WHERE l.project_id = ?1
                           AND CAST(l.expires_at AS INTEGER) > CAST(?4 AS INTEGER)
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM session_controls sc
                         WHERE sc.project_id = ?1 AND sc.codex_session_id = ?2
                           AND (sc.child_pid IS NOT NULL
                                OR sc.interactive_holder IS NOT NULL
                                OR sc.interactive_launch_token IS NOT NULL
                                OR sc.state NOT IN ('stopped', 'resume_requested')
                                OR EXISTS (
                                    SELECT 1 FROM agent_workers live
                                     WHERE live.worker_token = sc.run_token
                                       AND live.state IN ('dispatching', 'running', 'finalizing')
                                ))
                    )",
                params![
                    project_id,
                    codex_session_id,
                    expected_generation,
                    updated_at,
                ],
            )
            .await?
                == 1;
            if !idle_project {
                transaction
                    .rollback()
                    .await
                    .context("Failed to finish rejecting a non-idle abandoned Git journal")?;
                return Ok(false);
            }
            transaction
                .execute(
                    "UPDATE git_finalizations
                        SET state = 'cancelled', owner_run_token = NULL,
                            generation = generation + 1, last_error = ?1,
                            updated_at = ?2, completed_at = ?2
                      WHERE project_id = ?3 AND codex_session_id = ?4
                        AND state = 'working' AND generation = ?5",
                    params![
                        reason,
                        updated_at,
                        project_id,
                        codex_session_id,
                        expected_generation,
                    ],
                )
                .await
                .context("Failed to cancel the abandoned unbound Git journal")?;
            transaction
                .execute(
                    "DELETE FROM session_controls
                      WHERE project_id = ?1 AND codex_session_id = ?2
                        AND state IN ('stopped', 'resume_requested')
                        AND child_pid IS NULL
                        AND interactive_holder IS NULL
                        AND interactive_launch_token IS NULL",
                    params![project_id, codex_session_id],
                )
                .await
                .context("Failed to clear the abandoned journal's idle session control")?;
            transaction
                .commit()
                .await
                .context("Failed to durably retire the abandoned unbound Git journal")?;
            Ok(true)
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn accept_external_git_completion_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        task_identity: &str,
        lease_holder: &str,
        acquired_at: &str,
        expires_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.accept_external_git_completion(
                project_id,
                codex_session_id,
                expected_generation,
                task_identity,
                lease_holder,
                acquired_at,
                expires_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    async fn accept_external_git_completion(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        task_identity: &str,
        lease_holder: &str,
        acquired_at: &str,
        expires_at: &str,
    ) -> Result<bool> {
        let mut conn = self.repositories.git_journals.connect().await?;
        let transaction = conn
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .await
            .with_context(|| {
                format!(
                    "Failed to begin accepting external completion for Codex session {codex_session_id}"
                )
            })?;

        if query_count(
            &transaction,
            "SELECT COUNT(*) FROM agent_workers
              WHERE project_id = ?1
                AND state IN ('dispatching', 'running', 'finalizing')",
            [project_id],
        )
        .await?
            > 0
        {
            anyhow::bail!(
                "Task {codex_session_id} still has an active agent worker; stop it before moving the task to Done as an external completion"
            );
        }

        if query_count(
            &transaction,
            "SELECT COUNT(*) FROM session_controls
              WHERE project_id = ?1 AND codex_session_id = ?2
                AND NOT (
                    state IN ('stopped', 'resume_requested')
                    AND child_pid IS NULL
                    AND interactive_holder IS NULL
                    AND interactive_launch_token IS NULL
                )",
            params![project_id, codex_session_id],
        )
        .await?
            > 0
        {
            anyhow::bail!(
                "Codex session {codex_session_id} is still active; stop it before moving the task to Done as an external completion"
            );
        }

        transaction
            .execute(
                "DELETE FROM leases
                  WHERE project_id = ?1
                    AND CAST(expires_at AS INTEGER) <= CAST(?2 AS INTEGER)",
                params![project_id, acquired_at],
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to clear an expired project lease before accepting external completion for {codex_session_id}"
                )
            })?;
        if query_count(
            &transaction,
            "SELECT COUNT(*) FROM leases WHERE project_id = ?1",
            [project_id],
        )
        .await?
            > 0
        {
            anyhow::bail!(
                "Task {codex_session_id} still has an active project lease; stop its agent session before moving the task to Done as an external completion"
            );
        }
        let lease_inserted = transaction
            .execute(
                "INSERT OR IGNORE INTO leases (project_id, holder, acquired_at, expires_at)
                 SELECT ?1, ?2, ?3, ?4
                  WHERE EXISTS (
                      SELECT 1 FROM git_finalizations
                       WHERE project_id = ?1 AND codex_session_id = ?5
                         AND state = 'working' AND generation = ?6
                         AND task_identity = ?7
                  )",
                params![
                    project_id,
                    lease_holder,
                    acquired_at,
                    expires_at,
                    codex_session_id,
                    expected_generation,
                    task_identity,
                ],
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to fence the project while accepting external completion for {codex_session_id}"
                )
            })?;
        if lease_inserted != 1 {
            transaction.commit().await.with_context(|| {
                format!("Failed to finish a rejected external completion for {codex_session_id}")
            })?;
            return Ok(false);
        }

        let changed = transaction
            .execute(
                "UPDATE git_finalizations
                    SET state = 'cancelled', owner_run_token = NULL,
                        generation = generation + 1, last_error = ?1,
                        updated_at = ?2, completed_at = ?2
                  WHERE project_id = ?3 AND codex_session_id = ?4
                    AND state = 'working' AND generation = ?5
                    AND task_identity = ?6",
                params![
                    AGENT_EXTERNAL_COMPLETION_REASON,
                    acquired_at,
                    project_id,
                    codex_session_id,
                    expected_generation,
                    task_identity,
                ],
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to cancel the managed Git journal for externally completed task {codex_session_id}"
                )
            })?;
        if changed != 1 {
            return Ok(false);
        }

        transaction
            .execute(
                "DELETE FROM session_controls
                  WHERE project_id = ?1 AND codex_session_id = ?2
                    AND state IN ('stopped', 'resume_requested')
                    AND child_pid IS NULL
                    AND interactive_holder IS NULL
                    AND interactive_launch_token IS NULL",
                params![project_id, codex_session_id],
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to clear the idle resume state for externally completed task {codex_session_id}"
                )
            })?;

        transaction.commit().await.with_context(|| {
            format!("Failed to commit external completion for Codex session {codex_session_id}")
        })?;
        Ok(true)
    }

    pub(crate) fn record_git_launch_state_blocking(
        &self,
        project_id: i64,
        run_token: &str,
        git_mode: AgentGitMode,
        start: &AgentGitStartState,
        created_at: &str,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
                if git_mode == AgentGitMode::Off {
                    anyhow::bail!("A Git launch state cannot use Git mode off");
                }
                let mut conn = self.repositories.git_journals.connect().await?;
                let transaction = conn
                    .transaction_with_behavior(TransactionBehavior::Immediate)
                    .await
                    .context("Failed to begin recording the prelaunch Git state")?;
                if query_count(
                    &transaction,
                    "SELECT COUNT(*) FROM agent_git_launch_states
                      WHERE project_id = ?1 AND run_token <> ?2",
                    params![project_id, run_token],
                )
                .await?
                    != 0
                {
                    anyhow::bail!(
                        "A prior automated run has an unconsumed Git launch boundary for project {project_id}; refusing to replace it"
                    );
                }
                let inserted = transaction
                    .execute(
                        "INSERT OR IGNORE INTO agent_git_launch_states (
                            project_id, run_token, git_mode, starting_head, branch_ref,
                            upstream_ref, worktree_baseline, created_at
                         ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                        params![
                            project_id,
                            run_token,
                            git_mode.database_value(),
                            start.starting_head.as_str(),
                            start.branch_ref.as_deref(),
                            start.upstream_ref.as_deref(),
                            start.worktree_baseline.as_str(),
                            created_at,
                        ],
                    )
                    .await
                    .context("Failed to persist the prelaunch Git state")?;
                if inserted == 0
                    && query_count(
                        &transaction,
                        "SELECT COUNT(*) FROM agent_git_launch_states
                          WHERE project_id = ?1 AND run_token = ?2
                            AND git_mode = ?3 AND starting_head = ?4
                            AND branch_ref IS ?5 AND upstream_ref IS ?6
                            AND worktree_baseline = ?7",
                        params![
                            project_id,
                            run_token,
                            git_mode.database_value(),
                            start.starting_head.as_str(),
                            start.branch_ref.as_deref(),
                            start.upstream_ref.as_deref(),
                            start.worktree_baseline.as_str(),
                        ],
                    )
                    .await?
                        != 1
                {
                    anyhow::bail!(
                        "Automated run {run_token} already has a different immutable Git launch boundary"
                    );
                }
                transaction
                    .commit()
                    .await
                    .context("Failed to commit the prelaunch Git state")?;
                Ok(inserted == 1)
            })
    }

    pub(crate) fn has_other_git_launch_state_blocking(
        &self,
        project_id: i64,
        run_token: &str,
    ) -> Result<bool> {
        self.blocking.block_on(async {
            let conn = self.repositories.git_journals.connect().await?;
            Ok(query_count(
                &conn,
                "SELECT COUNT(*) FROM agent_git_launch_states
                      WHERE project_id = ?1 AND run_token <> ?2",
                params![project_id, run_token],
            )
            .await?
                != 0)
        })
    }

    pub(crate) fn git_launch_state_for_project_blocking(
        &self,
        project_id: i64,
    ) -> Result<Option<(String, AgentGitMode, AgentGitStartState)>> {
        self.blocking.block_on(async {
            let conn = self.repositories.git_journals.connect().await?;
            let mut rows = conn
                .query(
                    "SELECT run_token, git_mode, starting_head, branch_ref,
                                upstream_ref, worktree_baseline
                           FROM agent_git_launch_states
                          WHERE project_id = ?1
                          ORDER BY created_at, run_token",
                    [project_id],
                )
                .await
                .context("Failed to read project Git launch states")?;
            let Some(row) = rows
                .next()
                .await
                .context("Failed to read project Git launch-state row")?
            else {
                return Ok(None);
            };
            let launch = (
                row_text(&row, 0, "run_token")?,
                AgentGitMode::from_database(&row_text(&row, 1, "git_mode")?)?,
                AgentGitStartState {
                    starting_head: row_text(&row, 2, "starting_head")?,
                    branch_ref: row_optional_text(&row, 3, "branch_ref")?,
                    upstream_ref: row_optional_text(&row, 4, "upstream_ref")?,
                    worktree_baseline: row_text(&row, 5, "worktree_baseline")?,
                },
            );
            if rows
                .next()
                .await
                .context("Failed to check for duplicate project Git launch states")?
                .is_some()
            {
                anyhow::bail!(
                    "Project {project_id} has more than one unconsumed Git launch boundary"
                );
            }
            Ok(Some(launch))
        })
    }

    pub(crate) fn reclaim_unchanged_git_launch_state_blocking(
        &self,
        project_id: i64,
        run_token: &str,
        git_mode: AgentGitMode,
        start: &AgentGitStartState,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
            let mut conn = self.repositories.git_journals.connect().await?;
            let transaction = conn
                .transaction_with_behavior(TransactionBehavior::Immediate)
                .await
                .context("Failed to begin reclaiming an unchanged Git launch state")?;
            let terminal_worker = query_count(
                &transaction,
                "SELECT COUNT(*) FROM agent_workers
                      WHERE worker_token = ?1 AND project_id = ?2
                        AND state IN ('completed', 'abandoned', 'superseded')",
                params![run_token, project_id],
            )
            .await?
                == 1;
            let any_session = query_count(
                &transaction,
                "SELECT COUNT(*) FROM session_controls
                      WHERE project_id = ?1 AND run_token = ?2",
                params![project_id, run_token],
            )
            .await?
                != 0;
            if !terminal_worker || any_session {
                transaction
                    .commit()
                    .await
                    .context("Failed to finish checking an unreclaimable Git launch state")?;
                return Ok(false);
            }
            let deleted = transaction
                .execute(
                    "DELETE FROM agent_git_launch_states
                          WHERE project_id = ?1 AND run_token = ?2
                            AND git_mode = ?3 AND starting_head = ?4
                            AND branch_ref IS ?5 AND upstream_ref IS ?6
                            AND worktree_baseline = ?7",
                    params![
                        project_id,
                        run_token,
                        git_mode.database_value(),
                        start.starting_head.as_str(),
                        start.branch_ref.as_deref(),
                        start.upstream_ref.as_deref(),
                        start.worktree_baseline.as_str(),
                    ],
                )
                .await
                .context("Failed to delete the proven-unchanged Git launch state")?;
            transaction
                .commit()
                .await
                .context("Failed to commit Git launch-state reclamation")?;
            Ok(deleted == 1)
        })
    }

    pub(crate) fn git_launch_state_blocking(
        &self,
        project_id: i64,
        run_token: &str,
    ) -> Result<Option<(AgentGitMode, AgentGitStartState)>> {
        self.blocking.block_on(async {
            let conn = self.repositories.git_journals.connect().await?;
            let mut rows = conn
                .query(
                    "SELECT git_mode, starting_head, branch_ref, upstream_ref,
                                worktree_baseline
                           FROM agent_git_launch_states
                          WHERE project_id = ?1 AND run_token = ?2",
                    params![project_id, run_token],
                )
                .await
                .context("Failed to read the prelaunch Git state")?;
            let Some(row) = rows
                .next()
                .await
                .context("Failed to read the prelaunch Git state row")?
            else {
                return Ok(None);
            };
            Ok(Some((
                AgentGitMode::from_database(&row_text(&row, 0, "git_mode")?)?,
                AgentGitStartState {
                    starting_head: row_text(&row, 1, "starting_head")?,
                    branch_ref: row_optional_text(&row, 2, "branch_ref")?,
                    upstream_ref: row_optional_text(&row, 3, "upstream_ref")?,
                    worktree_baseline: row_text(&row, 4, "worktree_baseline")?,
                },
            )))
        })
    }

    #[cfg_attr(unix, allow(dead_code))]
    pub(crate) fn delete_git_launch_state_blocking(
        &self,
        project_id: i64,
        run_token: &str,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
            let conn = self.repositories.git_journals.connect().await?;
            Ok(conn
                .execute(
                    "DELETE FROM agent_git_launch_states
                          WHERE project_id = ?1 AND run_token = ?2",
                    params![project_id, run_token],
                )
                .await
                .context("Failed to delete the prelaunch Git state")?
                == 1)
        })
    }

    pub(crate) fn create_git_finalization_blocking(
        &self,
        finalization: NewGitFinalization<'_>,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.create_git_finalization(finalization))
    }

    async fn create_git_finalization(&self, finalization: NewGitFinalization<'_>) -> Result<bool> {
        if finalization.codex_session_id.is_empty() {
            anyhow::bail!("Git finalization requires a Codex session ID");
        }
        if finalization.git_mode == AgentGitMode::Off {
            anyhow::bail!("Git finalization cannot be created when Git automation is off");
        }
        let mut conn = self.repositories.git_journals.connect().await?;
        let transaction = conn
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .await
            .with_context(|| {
                format!(
                    "Failed to begin creating Git finalization for project {} and Codex session {}",
                    finalization.project_id, finalization.codex_session_id
                )
            })?;
        let inserted = if let Some(owner_run_token) = finalization.owner_run_token {
            transaction
                .execute(
                    "INSERT OR IGNORE INTO git_finalizations (
                        project_id, codex_session_id, state, git_mode, starting_head,
                        branch_ref, upstream_ref, worktree_baseline, task_identity,
                        owner_run_token, commit_oid, generation,
                        last_error, created_at, updated_at, completed_at
                     ) SELECT ?1, ?2, 'working', ?3, ?4, ?5, ?6, ?7, ?8, ?9, NULL, 0,
                              NULL, ?10, ?10, NULL
                       WHERE EXISTS (
                           SELECT 1 FROM session_controls
                            WHERE project_id = ?1 AND codex_session_id = ?2
                              AND state = 'running' AND run_token = ?9
                       )",
                    params![
                        finalization.project_id,
                        finalization.codex_session_id,
                        finalization.git_mode.database_value(),
                        finalization.starting_head,
                        finalization.branch_ref,
                        finalization.upstream_ref,
                        finalization.worktree_baseline,
                        finalization.task_identity,
                        owner_run_token,
                        finalization.created_at,
                    ],
                )
                .await
        } else {
            transaction
                .execute(
                    "INSERT OR IGNORE INTO git_finalizations (
                        project_id, codex_session_id, state, git_mode, starting_head,
                        branch_ref, upstream_ref, worktree_baseline, task_identity,
                        owner_run_token, commit_oid, generation,
                        last_error, created_at, updated_at, completed_at
                     ) VALUES (?1, ?2, 'working', ?3, ?4, ?5, ?6, ?7, ?8, NULL, NULL, 0,
                               NULL, ?9, ?9, NULL)",
                    params![
                        finalization.project_id,
                        finalization.codex_session_id,
                        finalization.git_mode.database_value(),
                        finalization.starting_head,
                        finalization.branch_ref,
                        finalization.upstream_ref,
                        finalization.worktree_baseline,
                        finalization.task_identity,
                        finalization.created_at,
                    ],
                )
                .await
        }
        .with_context(|| {
            format!(
                "Failed to create Git finalization for project {} and Codex session {}",
                finalization.project_id, finalization.codex_session_id
            )
        })?;
        transaction.commit().await.with_context(|| {
            format!(
                "Failed to commit Git finalization creation for project {} and Codex session {}",
                finalization.project_id, finalization.codex_session_id
            )
        })?;
        Ok(inserted == 1)
    }

    pub(crate) fn git_finalization_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
    ) -> Result<Option<GitFinalizationRecord>> {
        self.blocking
            .block_on(self.git_finalization(project_id, codex_session_id))
    }

    async fn git_finalization(
        &self,
        project_id: i64,
        codex_session_id: &str,
    ) -> Result<Option<GitFinalizationRecord>> {
        let conn = self.repositories.git_journals.connect().await?;
        let mut rows = conn
            .query(
                "SELECT project_id, codex_session_id, state, git_mode, starting_head,
                        branch_ref, upstream_ref, worktree_baseline, task_identity,
                        owner_run_token, commit_oid, generation, last_error, created_at,
                        updated_at, completed_at, acknowledged_at, acknowledged_run_id
                   FROM git_finalizations
                  WHERE project_id = ?1 AND codex_session_id = ?2",
                params![project_id, codex_session_id],
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to read Git finalization for project {project_id} and Codex session {codex_session_id}"
                )
            })?;
        rows.next()
            .await
            .context("Failed to read Git finalization row")?
            .map(|row| git_finalization_record_from_row(&row))
            .transpose()
    }

    pub(crate) fn list_pending_git_finalizations_blocking(
        &self,
        project_id: Option<i64>,
    ) -> Result<Vec<GitFinalizationRecord>> {
        self.blocking
            .block_on(self.list_pending_git_finalizations(project_id))
    }

    async fn list_pending_git_finalizations(
        &self,
        project_id: Option<i64>,
    ) -> Result<Vec<GitFinalizationRecord>> {
        let conn = self.repositories.git_journals.connect().await?;
        let mut rows = conn
            .query(
                "SELECT project_id, codex_session_id, state, git_mode, starting_head,
                        branch_ref, upstream_ref, worktree_baseline, task_identity,
                        owner_run_token, commit_oid, generation, last_error, created_at,
                        updated_at, completed_at, acknowledged_at, acknowledged_run_id
                   FROM git_finalizations
                  WHERE state IN ('working', 'tracking', 'commit_pending', 'push_pending')
                    AND (?1 IS NULL OR project_id = ?1)
                  ORDER BY CAST(updated_at AS INTEGER), project_id, codex_session_id",
                params![project_id],
            )
            .await
            .context("Failed to list pending Git finalizations")?;
        let mut finalizations = Vec::new();
        while let Some(row) = rows
            .next()
            .await
            .context("Failed to read pending Git finalization row")?
        {
            finalizations.push(git_finalization_record_from_row(&row)?);
        }
        Ok(finalizations)
    }

    pub(crate) fn list_unacknowledged_completed_git_finalizations_blocking(
        &self,
        project_id: Option<i64>,
    ) -> Result<Vec<GitFinalizationRecord>> {
        self.blocking
            .block_on(self.list_unacknowledged_completed_git_finalizations(project_id))
    }

    async fn list_unacknowledged_completed_git_finalizations(
        &self,
        project_id: Option<i64>,
    ) -> Result<Vec<GitFinalizationRecord>> {
        let conn = self.repositories.git_journals.connect().await?;
        let mut rows = conn
            .query(
                "SELECT project_id, codex_session_id, state, git_mode, starting_head,
                        branch_ref, upstream_ref, worktree_baseline, task_identity,
                        owner_run_token, commit_oid, generation, last_error, created_at,
                        updated_at, completed_at, acknowledged_at, acknowledged_run_id
                   FROM git_finalizations
                  WHERE state = 'completed' AND acknowledged_at IS NULL
                    AND (?1 IS NULL OR project_id = ?1)
                  ORDER BY CAST(completed_at AS INTEGER), project_id, codex_session_id",
                params![project_id],
            )
            .await
            .context("Failed to list unacknowledged completed Git finalizations")?;
        let mut finalizations = Vec::new();
        while let Some(row) = rows
            .next()
            .await
            .context("Failed to read an unacknowledged Git finalization row")?
        {
            finalizations.push(git_finalization_record_from_row(&row)?);
        }
        Ok(finalizations)
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn compare_and_set_git_finalization_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        next_state: GitFinalizationState,
        owner_run_token: Option<&str>,
        commit_oid: Option<&str>,
        last_error: Option<&str>,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.compare_and_set_git_finalization(
                project_id,
                codex_session_id,
                expected_generation,
                next_state,
                None,
                None,
                false,
                owner_run_token,
                commit_oid,
                last_error,
                updated_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn compare_and_set_owned_git_finalization_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        next_state: GitFinalizationState,
        owner_run_token: &str,
        commit_oid: Option<&str>,
        last_error: Option<&str>,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.compare_and_set_git_finalization(
                project_id,
                codex_session_id,
                expected_generation,
                next_state,
                None,
                None,
                true,
                Some(owner_run_token),
                commit_oid,
                last_error,
                updated_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn compare_and_set_git_finalization_with_identity_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        next_state: GitFinalizationState,
        task_identity: &str,
        owner_run_token: Option<&str>,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.compare_and_set_git_finalization(
                project_id,
                codex_session_id,
                expected_generation,
                next_state,
                Some(task_identity),
                None,
                true,
                owner_run_token,
                None,
                None,
                updated_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn track_git_finalization_with_manifest_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        task_identity: &str,
        worktree_baseline: &str,
        owner_run_token: &str,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.compare_and_set_git_finalization(
                project_id,
                codex_session_id,
                expected_generation,
                GitFinalizationState::Tracking,
                Some(task_identity),
                Some(worktree_baseline),
                true,
                Some(owner_run_token),
                None,
                None,
                updated_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn reseal_git_finalization_manifest_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        task_identity: &str,
        worktree_baseline: &str,
        owner_run_token: &str,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.compare_and_set_git_finalization(
                project_id,
                codex_session_id,
                expected_generation,
                GitFinalizationState::CommitPending,
                Some(task_identity),
                Some(worktree_baseline),
                true,
                Some(owner_run_token),
                None,
                None,
                updated_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn recover_git_finalization_intent_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        task_identity: &str,
        owner_run_token: Option<&str>,
        updated_at: &str,
    ) -> Result<bool> {
        self.blocking
            .block_on_persist(self.compare_and_set_git_finalization(
                project_id,
                codex_session_id,
                expected_generation,
                GitFinalizationState::Tracking,
                Some(task_identity),
                None,
                false,
                owner_run_token,
                None,
                None,
                updated_at,
            ))
    }

    #[allow(clippy::too_many_arguments)]
    async fn compare_and_set_git_finalization(
        &self,
        project_id: i64,
        codex_session_id: &str,
        expected_generation: i64,
        next_state: GitFinalizationState,
        task_identity: Option<&str>,
        worktree_baseline: Option<&str>,
        require_running_owner: bool,
        owner_run_token: Option<&str>,
        commit_oid: Option<&str>,
        last_error: Option<&str>,
        updated_at: &str,
    ) -> Result<bool> {
        let mut conn = self.repositories.git_journals.connect().await?;
        let transaction = conn
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .await
            .with_context(|| {
                format!(
                    "Failed to begin updating Git finalization for project {project_id} and Codex session {codex_session_id}"
                )
            })?;
        let current = {
            let mut rows = transaction
                .query(
                    "SELECT project_id, codex_session_id, state, git_mode, starting_head,
                            branch_ref, upstream_ref, worktree_baseline, task_identity,
                            owner_run_token, commit_oid, generation, last_error, created_at,
                            updated_at, completed_at, acknowledged_at, acknowledged_run_id
                       FROM git_finalizations
                      WHERE project_id = ?1 AND codex_session_id = ?2",
                    params![project_id, codex_session_id],
                )
                .await
                .with_context(|| {
                    format!(
                        "Failed to inspect Git finalization for project {project_id} and Codex session {codex_session_id}"
                    )
                })?;
            rows.next()
                .await
                .context("Failed to read Git finalization compare-and-set row")?
                .map(|row| git_finalization_record_from_row(&row))
                .transpose()?
        };
        let Some(current) = current else {
            transaction
                .commit()
                .await
                .context("Failed to finish compare-and-set for a missing Git finalization")?;
            return Ok(false);
        };
        if current.generation != expected_generation {
            transaction
                .commit()
                .await
                .context("Failed to finish compare-and-set for a changed Git finalization")?;
            return Ok(false);
        }
        if require_running_owner {
            let Some(owner_run_token) = owner_run_token else {
                anyhow::bail!("Git completion intent requires a running owner token");
            };
            if query_count(
                &transaction,
                "SELECT COUNT(*) FROM session_controls
                  WHERE project_id = ?1 AND codex_session_id = ?2
                    AND state = 'running' AND run_token = ?3",
                params![project_id, codex_session_id, owner_run_token],
            )
            .await?
                != 1
            {
                transaction.commit().await.with_context(|| {
                    format!(
                        "Failed to finish fenced Git completion intent for project {project_id} and Codex session {codex_session_id}"
                    )
                })?;
                return Ok(false);
            }
        }
        if !current.state.can_transition_to(next_state) {
            anyhow::bail!(
                "Invalid Git finalization transition from {} to {}",
                current.state.database_value(),
                next_state.database_value()
            );
        }
        if next_state == GitFinalizationState::PushPending
            && current.git_mode != AgentGitMode::CommitAndPush
        {
            anyhow::bail!("Only commit-and-push finalizations may enter push_pending");
        }
        if let (Some(current_identity), Some(next_identity)) =
            (current.task_identity.as_deref(), task_identity)
            && current_identity != next_identity
        {
            anyhow::bail!(
                "Git finalization task identity cannot change after completion intent is recorded"
            );
        }
        let effective_task_identity = task_identity.or(current.task_identity.as_deref());
        if next_state.is_finalizing() && effective_task_identity.is_none() {
            anyhow::bail!(
                "Git finalization cannot enter {} without a task identity",
                next_state.database_value()
            );
        }
        let effective_commit_oid = commit_oid.or(current.commit_oid.as_deref());
        if let (Some(current_oid), Some(next_oid)) = (current.commit_oid.as_deref(), commit_oid)
            && current_oid != next_oid
        {
            anyhow::bail!("Git finalization commit OID cannot change once recorded");
        }
        if matches!(
            next_state,
            GitFinalizationState::PushPending | GitFinalizationState::Completed
        ) && effective_commit_oid.is_none()
        {
            anyhow::bail!(
                "Git finalization cannot enter {} without a commit OID",
                next_state.database_value()
            );
        }
        if next_state == GitFinalizationState::Completed
            && ((current.git_mode == AgentGitMode::Commit
                && current.state != GitFinalizationState::CommitPending)
                || (current.git_mode == AgentGitMode::CommitAndPush
                    && current.state != GitFinalizationState::PushPending))
        {
            anyhow::bail!(
                "Git finalization cannot complete before its configured commit or push step"
            );
        }

        let completed_at = next_state.is_terminal().then_some(updated_at);
        let changed = transaction
            .execute(
                "UPDATE git_finalizations
                    SET state = ?1,
                        task_identity = COALESCE(task_identity, ?2),
                        worktree_baseline = COALESCE(?3, worktree_baseline),
                        owner_run_token = ?4,
                        commit_oid = CASE WHEN ?5 IS NULL THEN commit_oid ELSE ?5 END,
                        generation = generation + 1,
                        last_error = ?6,
                        updated_at = ?7,
                        completed_at = ?8
                  WHERE project_id = ?9 AND codex_session_id = ?10 AND generation = ?11",
                params![
                    next_state.database_value(),
                    task_identity,
                    worktree_baseline,
                    owner_run_token,
                    commit_oid,
                    last_error,
                    updated_at,
                    completed_at,
                    project_id,
                    codex_session_id,
                    expected_generation,
                ],
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to update Git finalization for project {project_id} and Codex session {codex_session_id}"
                )
            })?;
        if changed == 1 {
            let next_generation = expected_generation
                .checked_add(1)
                .context("Git finalization generation overflowed")?;
            if next_state.is_terminal() {
                transaction
                    .execute(
                        "DELETE FROM session_controls
                          WHERE project_id = ?1 AND codex_session_id = ?2
                            AND state = 'resume_requested' AND child_pid IS NULL
                            AND interactive_holder IS NULL AND interactive_launch_token IS NULL
                            AND run_token = ?3 || CAST(?4 AS TEXT)",
                        params![
                            project_id,
                            codex_session_id,
                            AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX,
                            expected_generation
                        ],
                    )
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to clear the terminal Git finalization recovery fence for session {codex_session_id}"
                        )
                    })?;
            } else {
                transaction
                    .execute(
                    "UPDATE session_controls
                        SET run_token = ?1 || CAST(?2 AS TEXT), updated_at = ?3
                      WHERE project_id = ?4 AND codex_session_id = ?5
                        AND state = 'resume_requested' AND child_pid IS NULL
                        AND interactive_holder IS NULL AND interactive_launch_token IS NULL
                        AND run_token = ?1 || CAST(?6 AS TEXT)",
                    params![
                        AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX,
                        next_generation,
                        updated_at,
                        project_id,
                        codex_session_id,
                        expected_generation
                    ],
                )
                .await
                .with_context(|| {
                    format!(
                        "Failed to advance the Git finalization recovery fence for session {codex_session_id}"
                    )
                })?;
            }
        }
        transaction.commit().await.with_context(|| {
            format!(
                "Failed to commit Git finalization update for project {project_id} and Codex session {codex_session_id}"
            )
        })?;
        Ok(changed == 1)
    }

    #[cfg(test)]
    pub(crate) fn delete_terminal_git_finalization_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
                let conn = self.repositories.git_journals.connect().await?;
                let removed = conn
                    .execute(
                        "DELETE FROM git_finalizations
                          WHERE project_id = ?1 AND codex_session_id = ?2
                            AND state IN ('completed', 'cancelled')",
                        params![project_id, codex_session_id],
                    )
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to delete terminal Git finalization for project {project_id} and Codex session {codex_session_id}"
                        )
                    })?;
                Ok(removed == 1)
            })
    }

    pub(crate) fn acknowledge_completed_git_finalization_session_blocking(
        &self,
        project_id: i64,
        codex_session_id: &str,
    ) -> Result<bool> {
        self.blocking.block_on_persist(async {
                let mut conn = self.repositories.git_journals.connect().await?;
                let acknowledged_at = agent_timestamp();
                let transaction = conn
                    .transaction_with_behavior(TransactionBehavior::Immediate)
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to begin acknowledging completed Git finalization for project {project_id} and Codex session {codex_session_id}"
                        )
                    })?;
                let completed = {
                    let mut rows = transaction
                        .query(
                            "SELECT completed_at, commit_oid, acknowledged_at,
                                    acknowledged_run_id
                               FROM git_finalizations
                              WHERE project_id = ?1 AND codex_session_id = ?2
                                AND state = 'completed'",
                            params![project_id, codex_session_id],
                        )
                        .await
                        .with_context(|| {
                            format!(
                                "Failed to inspect completed Git finalization for project {project_id} and Codex session {codex_session_id}"
                            )
                        })?;
                    rows
                        .next()
                        .await
                        .context("Failed to read completed Git finalization acknowledgement")?
                        .map(|row| {
                            Ok::<_, anyhow::Error>((
                                row_text(&row, 0, "completed_at")?,
                                row_optional_text(&row, 1, "commit_oid")?,
                                row_optional_text(&row, 2, "acknowledged_at")?,
                                row_optional_integer(&row, 3, "acknowledged_run_id")?,
                            ))
                        })
                        .transpose()?
                };
                let Some((completed_at, commit_oid, prior_acknowledgement, _)) = completed
                else {
                    transaction.commit().await.with_context(|| {
                        format!(
                            "Failed to finish acknowledging absent Git finalization for project {project_id} and Codex session {codex_session_id}"
                        )
                    })?;
                    return Ok(false);
                };

                if prior_acknowledgement.is_some() {
                    transaction
                        .execute(
                            "DELETE FROM session_controls
                              WHERE project_id = ?1 AND codex_session_id = ?2
                                AND state = 'resume_requested' AND child_pid IS NULL
                                AND interactive_holder IS NULL
                                AND run_token LIKE ?3",
                            params![
                                project_id,
                                codex_session_id,
                                format!("{AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX}%")
                            ],
                        )
                        .await
                        .with_context(|| {
                            format!(
                                "Failed to clear a late resume request for completed Git finalization {codex_session_id}"
                            )
                        })?;
                    transaction.commit().await.with_context(|| {
                        format!(
                            "Failed to commit idempotent Git finalization acknowledgement for {codex_session_id}"
                        )
                    })?;
                    return Ok(true);
                }

                let latest_session_run = {
                    let mut rows = transaction
                        .query(
                            "SELECT id, status, finished_at
                               FROM runs
                              WHERE project_id = ?1 AND codex_session_id = ?2
                              ORDER BY id DESC
                              LIMIT 1",
                            params![project_id, codex_session_id],
                        )
                        .await
                        .with_context(|| {
                            format!(
                                "Failed to find an existing successful run for Git finalization {codex_session_id}"
                            )
                        })?;
                    rows
                        .next()
                        .await
                        .context("Failed to read an existing Git finalization run")?
                        .map(|row| {
                            Ok::<_, anyhow::Error>((
                                row_integer(&row, 0, "id")?,
                                row_text(&row, 1, "status")?,
                                row_optional_text(&row, 2, "finished_at")?,
                            ))
                        })
                        .transpose()?
                };
                let short_commit = commit_oid
                    .as_deref()
                    .map(|oid| &oid[..oid.len().min(12)])
                    .unwrap_or("unknown");
                let summary = format!(
                    "CLT recovered the proven Git finalization at commit {short_commit} after an interrupted run acknowledgement."
                );
                let acknowledged_run_id = match latest_session_run {
                    Some((run_id, status, finished_at))
                        if matches!(status.as_str(), "success" | "idle")
                            && finished_at
                                .as_deref()
                                .and_then(|value| value.parse::<u64>().ok())
                                >= completed_at.parse::<u64>().ok() =>
                    {
                        run_id
                    }
                    _ => {
                    transaction
                        .execute(
                            "INSERT INTO runs (
                                project_id, status, started_at, finished_at, summary,
                                codex_session_id
                             ) VALUES (?1, 'success', ?2, ?2, ?3, ?4)",
                            params![
                                project_id,
                                completed_at.as_str(),
                                summary.as_str(),
                                codex_session_id,
                            ],
                        )
                        .await
                        .with_context(|| {
                            format!(
                                "Failed to record recovered success for Git finalization {codex_session_id}"
                            )
                        })?;
                    query_count(&transaction, "SELECT last_insert_rowid()", ()).await?
                    }
                };

                let latest_project_run_id =
                    query_count(&transaction, "SELECT COALESCE(MAX(id), 0) FROM runs WHERE project_id = ?1", [project_id]).await?;
                if latest_project_run_id == acknowledged_run_id {
                    update_project_after_run(
                        &transaction,
                        &AgentRunOutcome {
                            project_id,
                            status: "success",
                            started_at: &completed_at,
                            finished_at: Some(&completed_at),
                            exit_code: None,
                            log_dir: None,
                            stdout_path: None,
                            stderr_path: None,
                            summary: Some(&summary),
                            codex_session_id: Some(codex_session_id),
                        },
                    )
                    .await?;
                }

                let marked = transaction
                    .execute(
                        "UPDATE git_finalizations
                            SET acknowledged_at = ?1, acknowledged_run_id = ?2
                          WHERE project_id = ?3 AND codex_session_id = ?4
                            AND state = 'completed' AND acknowledged_at IS NULL",
                        params![
                            acknowledged_at.as_str(),
                            acknowledged_run_id,
                            project_id,
                            codex_session_id,
                        ],
                    )
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to mark Git finalization {codex_session_id} acknowledged"
                        )
                    })?;
                if marked != 1 {
                    anyhow::bail!(
                        "Git finalization acknowledgement for {codex_session_id} changed inside its exclusive transaction"
                    );
                }
                transaction
                    .execute(
                        "DELETE FROM session_controls
                          WHERE project_id = ?1 AND codex_session_id = ?2
                            AND state = 'resume_requested' AND child_pid IS NULL
                            AND interactive_holder IS NULL
                            AND run_token LIKE ?3
                            AND EXISTS (
                                SELECT 1 FROM git_finalizations
                                 WHERE project_id = ?1 AND codex_session_id = ?2
                                   AND state = 'completed'
                            )",
                        params![
                            project_id,
                            codex_session_id,
                            format!("{AGENT_GIT_FINALIZATION_RESUME_TOKEN_PREFIX}%")
                        ],
                    )
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to acknowledge completed Git finalization for project {project_id} and Codex session {codex_session_id}"
                        )
                    })?;
                transaction.commit().await.with_context(|| {
                    format!(
                        "Failed to commit completed Git finalization acknowledgement for project {project_id} and Codex session {codex_session_id}"
                    )
                })?;
                Ok(true)
            })
    }
}