brokk-mj-controller 2.23.2

Daemon-side controller, session manager, and web server for Mjolnir
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
use super::*;
use rusqlite::OpenFlags;

const COMPATIBILITY_METADATA_VERSION: i64 = 30;

pub(super) struct SchemaState {
    pub(super) revision: i64,
    minimum_compatible: Option<i64>,
}

impl SchemaState {
    pub(super) fn ensure_supported(&self) -> Result<()> {
        self.ensure_supported_by(SCHEMA_VERSION)
    }

    fn ensure_supported_by(&self, supported: i64) -> Result<()> {
        let reason = if self.revision < supported {
            StoreSchemaMismatchReason::NeedsMigration
        } else if let Some(minimum_compatible) = self.minimum_compatible {
            if minimum_compatible <= supported {
                return Ok(());
            }
            StoreSchemaMismatchReason::Incompatible { minimum_compatible }
        } else {
            StoreSchemaMismatchReason::InvalidCompatibilityMetadata
        };
        Err(StoreSchemaMismatch {
            found: self.revision,
            supported,
            reason,
        }
        .into())
    }
}

/// The revision, ledger, and compatibility floor must describe one snapshot.
/// A missing floor is only legitimate before compatibility was introduced.
pub(super) fn read_schema_state(connection: &Connection) -> Result<SchemaState> {
    let snapshot = connection
        .unchecked_transaction()
        .context("start database compatibility snapshot")?;
    let revision: i64 = snapshot
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .context("read database migration revision")?;
    let minimum_compatible = if revision >= COMPATIBILITY_METADATA_VERSION {
        let invalid = || StoreSchemaMismatch {
            found: revision,
            supported: SCHEMA_VERSION,
            reason: StoreSchemaMismatchReason::InvalidCompatibilityMetadata,
        };
        let (count, singleton, floor, recorded): (i64, Option<i64>, Option<i64>, Option<i64>) =
            snapshot
                .query_row(
                    "SELECT count(*), min(singleton), min(minimum_compatible_version),
                    (SELECT max(version) FROM schema_migrations)
             FROM schema_compatibility",
                    [],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
                )
                .map_err(|error| {
                    // Missing tables/columns and invalid field types are
                    // structural. Busy, I/O, and interruption errors are not
                    // evidence of an incompatible migration.
                    let structural = match &error {
                        rusqlite::Error::SqliteFailure(code, _) => {
                            code.code == rusqlite::ErrorCode::Unknown
                        }
                        _ => true,
                    };
                    let error = anyhow::Error::new(error);
                    if structural {
                        error.context(invalid())
                    } else {
                        error.context("read database compatibility metadata")
                    }
                })?;
        if count != 1
            || singleton != Some(1)
            || recorded != Some(revision)
            || !floor
                .is_some_and(|floor| (COMPATIBILITY_METADATA_VERSION..=revision).contains(&floor))
        {
            return Err(invalid().into());
        }
        floor
    } else {
        None
    };
    snapshot
        .commit()
        .context("finish database compatibility snapshot")?;
    Ok(SchemaState {
        revision,
        minimum_compatible,
    })
}

pub fn database_path() -> PathBuf {
    data_dir().join("mj.sqlite3")
}

/// Verify that this client can read the daemon's store without creating or
/// migrating it. Startup must pass this gate before handing out a connection,
/// even when an older daemon happens to speak the same wire protocol.
pub fn check_read_compatibility() -> Result<()> {
    open_reader_strict(&database_path()).map(drop)
}

/// A writer-capable connection whose transactions take the WAL write lock at
/// `BEGIN`, where the busy handler applies. A DEFERRED transaction that has
/// already read cannot wait: SQLite only calls the busy handler when the
/// connection holds no transaction, so the upgrade to a write returns
/// `SQLITE_BUSY` at once (issue 1117).
pub(super) fn open_writer(path: &Path) -> Result<Connection> {
    let mut connection = open_writable(path)?;
    connection.set_transaction_behavior(rusqlite::TransactionBehavior::Immediate);
    Ok(connection)
}

fn open_writable(path: &Path) -> Result<Connection> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("create Mjolnir data directory {}", parent.display()))?;
    }
    let connection = Connection::open(path)
        .with_context(|| format!("open Mjolnir database {}", path.display()))?;
    connection.busy_timeout(Duration::from_secs(5))?;
    connection.execute_batch(
        "PRAGMA foreign_keys = ON;
         PRAGMA journal_mode = WAL;
         PRAGMA synchronous = FULL;",
    )?;
    verify_schema_once(path, &connection)?;
    committed::observe_connection(&connection, path)?;
    Ok(connection)
}

pub(super) fn open(path: &Path) -> Result<Connection> {
    open_writer(path)
}

/// Open an existing database without permitting schema or data mutation.
/// Client processes use this path so an accidental write fails locally
/// instead of competing with the daemon's writer.
#[cfg(not(test))]
pub(super) fn open_reader(path: &Path) -> Result<Connection> {
    open_reader_strict(path)
}

#[cfg(test)]
pub(super) fn open_reader(path: &Path) -> Result<Connection> {
    // Path-taking database helpers are migration fixtures in unit tests: they
    // intentionally open old or not-yet-created schemas. Production query
    // entry points compile against the strict reader above. The connection is
    // writable but keeps SQLite's DEFERRED default, so a fixture read does not
    // take the write lock.
    open_writable(path)
}

#[cfg_attr(test, allow(dead_code))]
fn open_reader_strict(path: &Path) -> Result<Connection> {
    let connection = Connection::open_with_flags(
        path,
        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .with_context(|| format!("open Mjolnir database read-only {}", path.display()))?;
    connection.busy_timeout(Duration::from_secs(5))?;
    connection.execute_batch(
        "PRAGMA foreign_keys = ON;
         PRAGMA query_only = ON;",
    )?;
    read_schema_state(&connection)?.ensure_supported()?;
    Ok(connection)
}

/// Databases this process has already migrated. A controller owns its store
/// exclusively (`ControllerStoreGuard`), so a schema verified once stays
/// verified and later connections skip the migration probes entirely.
fn verified_schemas() -> &'static Mutex<HashSet<PathBuf>> {
    static VERIFIED: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
    VERIFIED.get_or_init(|| Mutex::new(HashSet::new()))
}

/// Stable cache identity for a database. The file itself may not exist yet, so
/// the canonicalized parent directory carries the identity.
fn schema_cache_key(path: &Path) -> PathBuf {
    let Some(parent) = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    else {
        return path.to_owned();
    };
    match (fs::canonicalize(parent), path.file_name()) {
        (Ok(canonical), Some(name)) => canonical.join(name),
        _ => path.to_owned(),
    }
}

/// Run the migration ladder the first time this process opens a database.
/// Later opens confirm compatibility without repeating schema repairs. A
/// database behind this build is migrated again, so a recreated file under a
/// reused path still converges. Compatible future stores are never repaired.
fn verify_schema_once(path: &Path, connection: &Connection) -> Result<()> {
    let key = schema_cache_key(path);
    let mut verified = verified_schemas()
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    let state = read_schema_state(connection)?;
    if state.revision > SCHEMA_VERSION
        || (state.revision == SCHEMA_VERSION && verified.contains(&key))
    {
        // An older build must never run its repairs against a newer schema.
        return state.ensure_supported();
    }
    // Holding the lock across the ladder keeps two first opens of the same
    // database from running the additive migration steps against each other.
    migrate_schema(connection)?;
    read_schema_state(connection)?.ensure_supported()?;
    verified.insert(key);
    Ok(())
}

/// Forget that this process verified a database's schema. Only tests need it:
/// they simulate a store written by an older build by editing the schema of a
/// database this process has already opened, which no controller can do.
#[cfg(test)]
pub(super) fn forget_verified_schema(path: &Path) {
    verified_schemas()
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .remove(&schema_cache_key(path));
}

/// New stores start at the revision Mjolnir 2.7.2 shipped. Existing stores
/// retain the complete migration path, even when users skip many releases.
const BASELINE_SCHEMA_VERSION: i64 = 33;

/// The compatibility floor a baseline store records. Migration 32 (ZCode) was
/// the last breaking change before the baseline.
const BASELINE_MINIMUM_COMPATIBLE_VERSION: i64 = 32;

fn migrate_schema(connection: &Connection) -> Result<()> {
    let state = read_schema_state(connection)?;
    let version = state.revision;
    if version > SCHEMA_VERSION {
        return state.ensure_supported();
    }
    if version == 0 {
        create_baseline_schema(connection)?;
    } else if version < BASELINE_SCHEMA_VERSION {
        super::legacy_schema::migrate_to_baseline(connection)
            .context("upgrade historical database schema")?;
    }
    // Compatible: adds one table. Older readers ignore it and treat read-write
    // mounts as copy-on-write, a behaviour difference rather than lost data.
    // Older writers rewrite `session_mounts` but never touch this table, so its
    // rows survive their updates; a row only applies while a mount with the same
    // source and destination is still not read-only, so an older build that
    // makes the mount read-only or removes it keeps that choice. The
    // compatibility floor stays where it is.
    if version < 34 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             CREATE TABLE IF NOT EXISTS session_mount_access (
                 session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
                 source BLOB NOT NULL,
                 destination BLOB NOT NULL,
                 access TEXT NOT NULL CHECK(access IN ('rw')),
                 PRIMARY KEY(session_id, destination)
             ) STRICT;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (34, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 34;
             COMMIT;",
        )?;
    }
    // Compatible: adds one nullable column. Older readers ignore it, and the
    // older writer's session upsert lists columns explicitly, so it preserves
    // the value. An older executable launching such a session uses the shared
    // `/workspace` instead of the recorded per-session path, which is a
    // behaviour difference, not data loss. The compatibility floor stays where
    // it is.
    if version < 35 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             ALTER TABLE sessions ADD COLUMN container_workspace TEXT;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (35, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 35;
             COMMIT;",
        )?;
    }
    // Compatible: adds one nullable column. Older readers ignore it, and the
    // older writer's session upsert lists columns explicitly, so it preserves
    // the value. An older executable launching such a session runs it without
    // the mbx build cache, which is a behaviour difference, not data loss. The
    // compatibility floor stays where it is.
    if version < 36 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             ALTER TABLE sessions ADD COLUMN build_cache_json TEXT;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (36, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 36;
             COMMIT;",
        )?;
    }
    // Compatible: adds one nullable column to `session_targets`. Only a
    // container sub-agent child row ever carries a value, and older builds
    // could never start such a child, so an older update that rewrites the row
    // without the column loses nothing usable. Older readers ignore it. The
    // compatibility floor stays where it is.
    if version < 37 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             ALTER TABLE session_targets ADD COLUMN borrowed_from TEXT;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (37, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 37;
             COMMIT;",
        )?;
    }
    // Compatible: adds one table holding the dashboard's conversation pane
    // arrangement per workspace. Older readers never select from it and older
    // writers never touch it, so their updates leave its rows intact; a
    // workspace deleted by an older build still removes them through the
    // foreign key. Losing the table only means the conversation area opens as
    // a single pane. The compatibility floor stays where it is.
    if version < 38 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             CREATE TABLE IF NOT EXISTS workspace_layouts (
                 workspace_id TEXT PRIMARY KEY REFERENCES workspaces(workspace_id) ON DELETE CASCADE,
                 layout TEXT NOT NULL
             ) STRICT;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (38, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 38;
             COMMIT;",
        )?;
    }
    // Breaking: persisted input_required API events can now omit the structured
    // request. Older readers require it and fail to deserialize the event log;
    // the shared read/write compatibility floor must advance with the revision.
    if version < 39 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             UPDATE schema_compatibility SET minimum_compatible_version = 39 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (39, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 39;
             COMMIT;",
        )?;
    }
    // Breaking: native child projections and relay observations must be preserved
    // by every reader/writer; older builds cannot interpret their lifecycle.
    if version < 40 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             CREATE TABLE native_agents (
                 owner TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
                 child TEXT NOT NULL,
                 staging INTEGER NOT NULL CHECK(staging IN (0,1)),
                 body TEXT NOT NULL CHECK(json_valid(body)),
                 PRIMARY KEY(owner, child, staging)
             ) STRICT;
             CREATE TABLE native_agent_transcript (
                 owner TEXT NOT NULL,
                 child TEXT NOT NULL,
                 staging INTEGER NOT NULL,
                 stable_id TEXT NOT NULL,
                 position INTEGER NOT NULL,
                 body TEXT NOT NULL CHECK(json_valid(body)),
                 PRIMARY KEY(owner, child, staging, stable_id),
                 FOREIGN KEY(owner, child, staging) REFERENCES native_agents(owner, child, staging)
                     ON DELETE CASCADE ON UPDATE CASCADE
             ) STRICT;
             CREATE INDEX native_agent_transcript_position ON native_agent_transcript(owner, child, staging, position);
             CREATE TABLE native_agent_replay (
                 owner TEXT PRIMARY KEY REFERENCES sessions(session_id) ON DELETE CASCADE
             ) STRICT;
             UPDATE schema_compatibility SET minimum_compatible_version = 40 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (40, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 40;
             COMMIT;",
        )?;
    }
    // Breaking: clear-context relay commands/outcomes are persisted in event
    // JSON. Older readers cannot decode them or honor the context boundary.
    if version < 41 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             UPDATE schema_compatibility SET minimum_compatible_version = 41 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (41, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 41;
             COMMIT;",
        )?;
    }

    // Breaking: older layout writers discard Browse identity and pin badges.
    if version < 42 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             UPDATE schema_compatibility SET minimum_compatible_version = 42 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (42, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 42;
             COMMIT;",
        )?;
    }

    // Breaking: durable steering commands/observations and native availability
    // cannot be interpreted or preserved by older readers and writers.
    if version < 43 {
        connection.execute_batch("BEGIN IMMEDIATE;
            UPDATE schema_compatibility SET minimum_compatible_version = 43 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (43, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 43;
            COMMIT;")?;
    }

    // Breaking: new quota recovery commands in stored relay JSON cannot be
    // read or preserved by older binaries, even though the cache is additive.
    if version < 44 {
        connection.execute_batch("BEGIN IMMEDIATE;
            CREATE TABLE quota_reset_cache (identity TEXT PRIMARY KEY, body TEXT NOT NULL);
            UPDATE schema_compatibility SET minimum_compatible_version = 44 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (44, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 44;
            COMMIT;")?;
    }

    // Compatible: adds one nullable column. Older readers ignore it, and the
    // older writer's session upsert lists columns explicitly, so it preserves
    // the value. An older executable relaunching such a session starts it at
    // HEAD or the remote default branch instead of the recorded revision,
    // which is a behaviour difference, not data loss. The compatibility floor
    // stays where it is.
    if version < 45 {
        // The column is added only when it is absent, the way migration 34
        // creates its table only when absent: a store rolled back to an older
        // revision still carries the column, and a second ALTER would refuse.
        let add_column =
            match super::legacy_schema::table_has_column(connection, "sessions", "launch_base")? {
                true => "",
                false => "ALTER TABLE sessions ADD COLUMN launch_base TEXT;",
            };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (45, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 45;
             COMMIT;"
        ))?;
    }

    // Breaking: older writers can replace a target without updating its saved
    // connection, leaving access metadata attached to the wrong resource.
    // Refuse both older readers and writers before they operate that target.
    if version < 46 {
        let add_column = if super::legacy_schema::table_has_column(
            connection,
            "sessions",
            "target_runtime_json",
        )? {
            ""
        } else {
            "ALTER TABLE sessions ADD COLUMN target_runtime_json TEXT;"
        };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             UPDATE schema_compatibility SET minimum_compatible_version = 46 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (46, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 46;
             COMMIT;"
        ))?;
    }

    // Breaking: the managed checkout JSON can now describe an independent
    // clone. Older readers reject its `kind`, and older writers cannot safely
    // retain that clone's unpublished commits during lifecycle cleanup.
    if version < 47 {
        let add_branch =
            if super::legacy_schema::table_has_column(connection, "sessions", "launch_branch")? {
                ""
            } else {
                "ALTER TABLE sessions ADD COLUMN launch_branch TEXT;"
            };
        let add_publication = if super::legacy_schema::table_has_column(
            connection,
            "sessions",
            "publication_json",
        )? {
            ""
        } else {
            "ALTER TABLE sessions ADD COLUMN publication_json TEXT;"
        };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_branch}
             {add_publication}
             UPDATE schema_compatibility SET minimum_compatible_version = 47 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (47, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 47;
             COMMIT;",
        ))?;
    }

    // Breaking: stored relay JSON can now hold the steering-returned outcome,
    // and stored active-turn JSON the prompt a steer continued, which older
    // readers reject and older writers would drop.
    if version < 48 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             UPDATE schema_compatibility SET minimum_compatible_version = 48 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (48, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 48;
             COMMIT;",
        )?;
    }

    // Breaking: a sub-agent record can now say its child has the `handback`
    // tool, and older readers refuse the unknown field. The reports themselves
    // live in their own table, because a full state save rewrites every
    // sub-agent record from whatever copy the saving controller holds.
    if version < 49 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             CREATE TABLE IF NOT EXISTS subagent_handbacks (
                 child_session_id TEXT PRIMARY KEY,
                 handback_command_id TEXT,
                 handback_message TEXT,
                 handback_recorded_at_ms INTEGER,
                 reminder_command_id TEXT,
                 reminder_for_command_id TEXT,
                 reminder_sent_at_ms INTEGER,
                 reminder_failed_for_command_id TEXT
             );
             UPDATE schema_compatibility SET minimum_compatible_version = 49 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (49, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 49;
             COMMIT;",
        )?;
    }

    // Compatible: a new nullable column that only this build reads. Older
    // readers ignore it, and older writers name their columns, so an update
    // from one keeps it.
    if version < 50 {
        let add_column = if super::legacy_schema::table_has_column(
            connection,
            "subagent_handbacks",
            "awaited_ordinal",
        )? {
            ""
        } else {
            "ALTER TABLE subagent_handbacks ADD COLUMN awaited_ordinal INTEGER;"
        };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (50, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 50;
             COMMIT;"
        ))?;
    }

    // Compatible: the directory on the parent's target where a child writes
    // the details its report points to. A nullable column only this build
    // reads, like `awaited_ordinal`.
    if version < 51 {
        let add_column = if super::legacy_schema::table_has_column(
            connection,
            "subagent_handbacks",
            "report_dir",
        )? {
            ""
        } else {
            "ALTER TABLE subagent_handbacks ADD COLUMN report_dir TEXT;"
        };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (51, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 51;
             COMMIT;"
        ))?;
    }

    // Compatible: adds one table that only this build reads. It lists the
    // sub-agents a parent's suspend stopped until the parent's model has been
    // told. It is not a column of `sessions` because a full state save
    // rewrites every session row from whatever copy the saving controller
    // holds, which could drop the list or bring back one already delivered.
    // Rows go with their parent's session row.
    if version < 52 {
        connection.execute_batch(
            "BEGIN IMMEDIATE;
             CREATE TABLE IF NOT EXISTS stopped_subagents (
                 parent_session_id TEXT NOT NULL
                     REFERENCES sessions(session_id) ON DELETE CASCADE,
                 child_session_id TEXT NOT NULL,
                 record_json TEXT NOT NULL CHECK(json_valid(record_json)),
                 PRIMARY KEY(parent_session_id, child_session_id)
             ) STRICT;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (52, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 52;
             COMMIT;",
        )?;
    }

    // Breaking: a sub-agent whose turn ended can be stored as `parked`. The
    // `sessions.state` constraint has to be rebuilt to admit it, and an older
    // reader panics on a state it does not know, so the floor rises with the
    // revision.
    if version < 53 {
        migrate_parked_session_state(connection)?;
    }

    // Breaking: older daemons cannot enforce exact checkout preparation on
    // admitted sessions, so they must not recover or provision these records.
    if version < 54 {
        let add_column =
            if super::legacy_schema::table_has_column(connection, "sessions", "checkout_json")? {
                ""
            } else {
                "ALTER TABLE sessions ADD COLUMN checkout_json TEXT;"
            };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             UPDATE schema_compatibility SET minimum_compatible_version = 54 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (54, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 54;
             COMMIT;"
        ))?;
    }

    // Breaking: older daemons cannot enforce the runtime constraint or read
    // the new runtime receipt stored in relay/API events.
    if version < 55 {
        let add_column = if super::legacy_schema::table_has_column(
            connection,
            "sessions",
            "expected_runtime_identity",
        )? {
            ""
        } else {
            "ALTER TABLE sessions ADD COLUMN expected_runtime_identity TEXT;"
        };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             UPDATE schema_compatibility SET minimum_compatible_version = 55 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (55, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 55;
             COMMIT;"
        ))?;
    }

    // Breaking: older readers/writers cannot honor None or fixed model/effort.
    if version < 56 {
        let add_column = if super::legacy_schema::table_has_column(
            connection,
            "sessions",
            "subagents",
        )? {
            ""
        } else {
            "ALTER TABLE sessions ADD COLUMN subagents TEXT CHECK(subagents IS NULL OR json_valid(subagents));"
        };
        connection.execute_batch(&format!(
            "BEGIN IMMEDIATE;
             {add_column}
             UPDATE sessions SET subagents = CASE WHEN mjolnir_subagents = 1
                 THEN '{{\"mode\":\"all_models\"}}' ELSE '{{\"mode\":\"native\"}}' END WHERE subagents IS NULL AND mjolnir_subagents IS NOT NULL;
             CREATE TABLE IF NOT EXISTS subagent_preference (singleton INTEGER PRIMARY KEY CHECK(singleton = 1), policy TEXT NOT NULL CHECK(json_valid(policy)));
             UPDATE schema_compatibility SET minimum_compatible_version = 56 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at) VALUES (56, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
             PRAGMA user_version = 56;
             COMMIT;"
        ))?;
    }

    // Breaking: typed event bodies cannot be decoded by older readers, and
    // pending checkpoint identities must survive every writer's transitions.
    if version < 57 {
        let tx = connection.unchecked_transaction()?;
        tx.execute_batch("DROP TRIGGER IF EXISTS api_session_error_updated;
            DROP TRIGGER IF EXISTS api_session_error_inserted;
            CREATE TABLE IF NOT EXISTS checkpoint_operations (
                session_id TEXT PRIMARY KEY REFERENCES sessions(session_id) ON DELETE CASCADE,
                command_id TEXT NOT NULL UNIQUE,
                related_command_ids TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(related_command_ids))
            ) STRICT;")?;
        super::events::migrate_event_outcomes(&tx)?;
        tx.execute_batch("UPDATE schema_compatibility SET minimum_compatible_version = 57 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (57, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 57;")?;
        tx.commit()?;
    }

    // Breaking: relay assessment observations and seeded-context commands are
    // persisted as JSON that older readers cannot decode or preserve.
    if version < 58 {
        connection.execute_batch("BEGIN IMMEDIATE;
            UPDATE schema_compatibility SET minimum_compatible_version = 58 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (58, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 58;
            COMMIT;")?;
    }

    // Breaking: an older daemon cannot resume acknowledged startup delivery
    // and may instead restore or resend its prompt with a different identity.
    if version < 59 {
        connection.execute_batch("BEGIN IMMEDIATE;
            CREATE TABLE IF NOT EXISTS startup_steps (
                sequence INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                group_id TEXT,
                command_id TEXT NOT NULL UNIQUE,
                step_json TEXT NOT NULL,
                phase TEXT NOT NULL DEFAULT 'pending'
                    CHECK (phase IN ('pending', 'delivering', 'accepted', 'cancelling', 'rejecting', 'done', 'failed', 'dismissed')),
                error TEXT,
                accepted_ordinal INTEGER
            ) STRICT;
            CREATE INDEX IF NOT EXISTS startup_steps_session_sequence
                ON startup_steps(session_id, sequence);
            CREATE INDEX IF NOT EXISTS startup_steps_group_sequence
                ON startup_steps(group_id, sequence) WHERE group_id IS NOT NULL;
            CREATE INDEX IF NOT EXISTS startup_steps_pending
                ON startup_steps(session_id, sequence)
                WHERE phase IN ('pending', 'delivering', 'accepted', 'cancelling', 'rejecting');
            UPDATE schema_compatibility SET minimum_compatible_version = 59 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (59, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 59;
            COMMIT;")?;
    }
    // Breaking: older dispatchers would resolve a prepared request's target
    // again instead of honoring its persisted effect identity and outcome.
    if version < 60 {
        connection.execute_batch("BEGIN IMMEDIATE;
            CREATE TABLE IF NOT EXISTS delegation_effects (
                parent_session_id TEXT NOT NULL,
                request_id TEXT NOT NULL,
                phase TEXT NOT NULL,
                prepared_json TEXT,
                result_json TEXT,
                receipt_pending INTEGER NOT NULL DEFAULT 0,
                PRIMARY KEY(parent_session_id, request_id)
            ) STRICT;
            CREATE INDEX IF NOT EXISTS delegation_effects_receipt_cleanup
                ON delegation_effects(parent_session_id, request_id) WHERE receipt_pending = 1;
            UPDATE schema_compatibility SET minimum_compatible_version = 60 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (60, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 60;
            COMMIT;")?;
    }
    // Breaking: older review hosts clear active reviews on startup and cannot
    // reconstruct or preserve the durable orchestration and effect outbox.
    if version < 61 {
        let add_column = if super::legacy_schema::table_has_column(
            connection,
            "turn_review_state",
            "orchestration",
        )? {
            ""
        } else {
            "ALTER TABLE turn_review_state ADD COLUMN orchestration TEXT;"
        };
        connection.execute_batch(&format!("BEGIN IMMEDIATE;
            {add_column}
            UPDATE schema_compatibility SET minimum_compatible_version = 61 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (61, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 61;
            COMMIT;"))?;
    }
    // Breaking: older recovery cannot distinguish an accepted worker swap
    // awaiting readiness from a worker that should be recreated or abandoned.
    if version < 62 {
        connection.execute_batch("BEGIN IMMEDIATE;
            CREATE TABLE IF NOT EXISTS worker_restart_intents (
                session_id TEXT PRIMARY KEY REFERENCES sessions(session_id) ON DELETE CASCADE,
                operation_id TEXT NOT NULL,
                target_json TEXT NOT NULL,
                desired_build TEXT NOT NULL,
                phase TEXT NOT NULL CHECK(phase IN ('prepared', 'swapping', 'awaiting_readiness'))
            ) STRICT;
            UPDATE schema_compatibility SET minimum_compatible_version = 62 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (62, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 62;
            COMMIT;")?;
    }

    // Breaking: older delegation executors do not fence delayed lifecycle
    // effects against the durable incarnation they originally selected.
    if version < 63 {
        connection.execute_batch("BEGIN IMMEDIATE;
            CREATE TABLE IF NOT EXISTS session_incarnations (
                session_id TEXT PRIMARY KEY REFERENCES sessions(session_id) ON DELETE CASCADE,
                identity TEXT NOT NULL
            ) STRICT;
            INSERT OR IGNORE INTO session_incarnations(session_id, identity)
                SELECT session_id, lower(hex(randomblob(16))) FROM sessions;
            CREATE TRIGGER IF NOT EXISTS session_incarnation_insert
                AFTER INSERT ON sessions BEGIN
                    INSERT INTO session_incarnations(session_id, identity)
                    VALUES(NEW.session_id, lower(hex(randomblob(16))));
                END;
            CREATE TRIGGER IF NOT EXISTS session_incarnation_resume
                AFTER UPDATE OF state ON sessions
                WHEN (NEW.state = 'provisioning' AND OLD.state <> 'provisioning')
                  OR (NEW.state = 'running' AND OLD.state IN
                      ('stopped', 'parked', 'error', 'lost', 'destroyed-with-data-loss'))
                BEGIN
                    UPDATE session_incarnations SET identity = lower(hex(randomblob(16)))
                    WHERE session_id = NEW.session_id;
                END;
            UPDATE schema_compatibility SET minimum_compatible_version = 63 WHERE singleton = 1;
            INSERT INTO schema_migrations(version, applied_at) VALUES (63, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
            PRAGMA user_version = 63;
            COMMIT;")?;
    }

    let recorded: Option<i64> =
        connection.query_row("SELECT max(version) FROM schema_migrations", [], |row| {
            row.get(0)
        })?;
    if recorded != Some(SCHEMA_VERSION) {
        bail!(
            "Mjolnir database migration ledger {:?} does not match schema {}",
            recorded,
            SCHEMA_VERSION
        );
    }
    Ok(())
}

/// Migration 53: rebuild `sessions` so its `state` constraint admits
/// `'parked'`. SQLite cannot alter a CHECK constraint, so the table is copied
/// into one declared with the new constraint, the way migration 32
/// (`migrate_zcode_harness_kind`) did. The table's own stored definition is
/// edited, so every column later migrations added is kept as it is. A store
/// whose constraint already admits the value is only stamped.
fn migrate_parked_session_state(connection: &Connection) -> Result<()> {
    const BEFORE: &str = "'stopped','lost',";
    const AFTER: &str = "'stopped','parked','lost',";
    connection.execute_batch("PRAGMA foreign_keys = OFF;")?;
    let migration = (|| -> Result<()> {
        let transaction = connection.unchecked_transaction()?;
        let sql: String = transaction.query_row(
            "SELECT sql FROM sqlite_schema WHERE type='table' AND name='sessions'",
            [],
            |row| row.get(0),
        )?;
        let (_, definition) = sql
            .split_once('(')
            .context("missing sessions table definition")?;
        if !definition.contains(AFTER) {
            ensure!(
                definition.matches(BEFORE).count() == 1,
                "unexpected sessions state constraint"
            );
            let definition = definition.replace(BEFORE, AFTER);
            let objects: Vec<String> = transaction
                .prepare(
                    "SELECT sql FROM sqlite_schema WHERE tbl_name='sessions'
                     AND type IN ('index','trigger') AND sql IS NOT NULL",
                )?
                .query_map([], |row| row.get(0))?
                .collect::<rusqlite::Result<_>>()?;
            transaction.execute_batch(&format!(
                "CREATE TABLE sessions_parked_v53 ({definition};
                 INSERT INTO sessions_parked_v53 SELECT * FROM sessions;
                 DROP TABLE sessions;
                 ALTER TABLE sessions_parked_v53 RENAME TO sessions;"
            ))?;
            for object in objects {
                transaction.execute_batch(&object)?;
            }
            ensure!(
                !transaction
                    .prepare("PRAGMA foreign_key_check")?
                    .exists([])?,
                "foreign key violation in the parked-state migration"
            );
        }
        transaction.execute_batch(
            "UPDATE schema_compatibility SET minimum_compatible_version = 53
                 WHERE singleton = 1;
             INSERT INTO schema_migrations(version, applied_at)
                 VALUES (53, strftime('%Y-%m-%dT%H:%M:%fZ','now'));
             PRAGMA user_version = 53;",
        )?;
        transaction.commit()?;
        Ok(())
    })();
    let restored = connection.execute_batch("PRAGMA foreign_keys = ON;");
    migration.context("migrate the sessions state constraint for parked sub-agents")?;
    restored.context("restore foreign key enforcement after the parked-state migration")?;
    Ok(())
}

/// Create an empty store at the baseline revision in one immediate transaction.
/// The revision is read again under the write lock, so a second process that
/// raced to create the same store finds it already created.
fn create_baseline_schema(connection: &Connection) -> Result<()> {
    connection.execute_batch("BEGIN IMMEDIATE;")?;
    let created = (|| -> Result<()> {
        let version: i64 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
        if version != 0 {
            return Ok(());
        }
        connection.execute_batch(include_str!("baseline.sql"))?;
        connection.execute(
            "INSERT INTO schema_compatibility(singleton, minimum_compatible_version) VALUES (1, ?1)",
            [BASELINE_MINIMUM_COMPATIBLE_VERSION],
        )?;
        connection.execute(
            "INSERT INTO schema_migrations(version, applied_at)
             VALUES (?1, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
            [BASELINE_SCHEMA_VERSION],
        )?;
        connection.pragma_update(None, "user_version", BASELINE_SCHEMA_VERSION)?;
        Ok(())
    })();
    match created {
        Ok(()) => connection
            .execute_batch("COMMIT;")
            .context("commit baseline database schema"),
        Err(error) => {
            if let Err(rollback) = connection.execute_batch("ROLLBACK;") {
                tracing::warn!(%rollback, "could not roll back a failed baseline schema");
            }
            Err(error.context("create baseline database schema"))
        }
    }
}

#[cfg(test)]
pub(super) fn advance_test_schema(path: &Path, revision: i64, minimum_compatible: i64) {
    let connection = Connection::open(path).unwrap();
    let transaction = connection.unchecked_transaction().unwrap();
    transaction
        .execute(
            "UPDATE schema_compatibility SET minimum_compatible_version = ?1",
            [minimum_compatible],
        )
        .unwrap();
    transaction
        .execute(
            "INSERT INTO schema_migrations(version, applied_at) VALUES (?1, 'test')",
            [revision],
        )
        .unwrap();
    transaction
        .pragma_update(None, "user_version", revision)
        .unwrap();
    transaction.commit().unwrap();
    forget_verified_schema(path);
}

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

    #[test]
    fn every_historical_revision_upgrades_directly_and_preserves_user_data() {
        for revision in 1..SCHEMA_VERSION {
            let directory = tempfile::tempdir().unwrap();
            let path = directory.path().join("mj.sqlite3");
            let connection = Connection::open(&path).unwrap();
            connection
                .execute_batch(include_str!("legacy_v1.sql"))
                .unwrap();
            connection.execute_batch(
                "INSERT INTO session_contexts VALUES ('old-session', 'project', '2026-01-01T00:00:00Z');
                 INSERT INTO sessions(session_id, title, harness_kind, last_profile,
                     target_template_id, state, updated_at, native_session_id)
                     VALUES ('old-session', 'Keep my work', 'codex', 'codex', 'local', 'error',
                         '2026-01-01T00:00:00Z', 'native-original');
                 INSERT INTO prompt_history(session_id, event_sequence, submitted_at, text)
                     VALUES ('old-session', 1, '2026-01-01T00:00:00Z', 'Keep my prompt');"
            ).unwrap();
            // Interrupt at each historical transaction boundary. Closing the
            // connection rolls back the interrupted step, exactly as a killed
            // updater would. Reopening must resume without manual cleanup.
            connection
                .execute_batch(&format!(
                    "CREATE TRIGGER stop_at_revision BEFORE INSERT ON schema_migrations
                 WHEN NEW.version > {revision}
                 BEGIN SELECT RAISE(ABORT, 'fixture migration boundary'); END;"
                ))
                .unwrap();
            if revision < BASELINE_SCHEMA_VERSION {
                assert!(super::super::legacy_schema::migrate_to_baseline(&connection).is_err());
            } else {
                super::super::legacy_schema::migrate_to_baseline(&connection).unwrap();
                assert!(migrate_schema(&connection).is_err());
            }
            drop(connection);
            let connection = Connection::open(&path).unwrap();
            let found: i64 = connection
                .query_row("PRAGMA user_version", [], |row| row.get(0))
                .unwrap();
            assert_eq!(found, revision);
            connection
                .execute_batch("DROP TRIGGER stop_at_revision")
                .unwrap();
            drop(connection);

            let writer =
                open_writer(&path).unwrap_or_else(|error| panic!("revision {revision}: {error:#}"));
            assert_eq!(read_schema_state(&writer).unwrap().revision, SCHEMA_VERSION);
            assert_eq!(
                writer
                    .query_row("PRAGMA integrity_check", [], |row| row.get::<_, String>(0))
                    .unwrap(),
                "ok"
            );
            assert!(
                !writer
                    .prepare("PRAGMA foreign_key_check")
                    .unwrap()
                    .exists([])
                    .unwrap()
            );
            drop(writer);
            let reader = open_reader_strict(&path).unwrap();
            let prompt: String = reader
                .query_row("SELECT text FROM prompt_history", [], |row| row.get(0))
                .unwrap();
            assert_eq!(prompt, "Keep my prompt");
            let state = load_state_from(&path).unwrap();
            assert_eq!(state.sessions["old-session"].title, "Keep my work");
            assert_eq!(
                state.sessions["old-session"].native_session_id.as_deref(),
                Some("native-original")
            );
            drop(reader);
            // A fresh writer process must not apply any migration twice.
            forget_verified_schema(&path);
            drop(open_writer(&path).unwrap());
        }
    }

    /// The oldest executable revision that can still read and write a store at
    /// `SCHEMA_VERSION`. Migration 62 requires durable worker-swap recovery.
    const MINIMUM_COMPATIBLE_VERSION: i64 = 63;

    /// Rewrites a store's recorded schema version the way another build's
    /// migration ladder would, and forgets that this process verified it.
    fn stamp_schema_version(path: &Path, version: i64) {
        if version > SCHEMA_VERSION {
            advance_test_schema(path, version, version);
            return;
        }
        let connection = Connection::open(path).unwrap();
        connection
            .execute_batch(&format!("PRAGMA user_version = {version};"))
            .unwrap();
        connection
            .execute(
                "DELETE FROM schema_migrations WHERE version > ?1",
                [version],
            )
            .unwrap();
        if version == 30 {
            connection
                .execute(
                    "UPDATE schema_compatibility SET minimum_compatible_version = 30 WHERE singleton = 1",
                    [],
                )
                .unwrap();
        }
        drop(connection);
        forget_verified_schema(path);
    }

    #[test]
    fn subagent_policy_migration_preserves_legacy_choices_and_refuses_old_writers() {
        use mj_core::subagent::SubagentPolicy;
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("subagent-policy.sqlite3");
        for id in ["all", "native", "unset"] {
            save_session_to(&path, &super::super::tests::session(id, "project")).unwrap();
        }
        let connection = Connection::open(&path).unwrap();
        connection
            .execute_batch(
                "UPDATE sessions SET mjolnir_subagents = 1 WHERE session_id = 'all';
             UPDATE sessions SET mjolnir_subagents = 0 WHERE session_id = 'native';
             ALTER TABLE sessions DROP COLUMN subagents;
             DROP TABLE subagent_preference;
             DELETE FROM schema_migrations WHERE version >= 56;
             UPDATE schema_compatibility SET minimum_compatible_version = 55;
             PRAGMA user_version = 55;",
            )
            .unwrap();
        drop(connection);
        forget_verified_schema(&path);
        let upgraded = open_writer(&path).unwrap();
        assert!(
            read_schema_state(&upgraded)
                .unwrap()
                .ensure_supported_by(55)
                .is_err()
        );
        drop(upgraded);
        let state = load_state_from(&path).unwrap();
        assert_eq!(
            state.sessions["all"].subagents,
            Some(SubagentPolicy::AllModels)
        );
        assert_eq!(
            state.sessions["native"].subagents,
            Some(SubagentPolicy::Native)
        );
        assert_eq!(state.sessions["unset"].subagents, None);
        assert_eq!(state.last_subagent_policy, SubagentPolicy::Native);
    }

    #[test]
    fn steering_migration_refuses_builds_that_cannot_read_returned_steers() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("steering-migration.sqlite3");
        let record = super::super::tests::session("steered-session", "project");
        save_session_to(&path, &record).unwrap();
        let connection = Connection::open(&path).unwrap();
        connection
            .execute_batch(
                "DELETE FROM schema_migrations WHERE version >= 48;
             UPDATE schema_compatibility SET minimum_compatible_version = 47;
             PRAGMA user_version = 47;",
            )
            .unwrap();
        drop(connection);
        forget_verified_schema(&path);
        let upgraded = open_writer(&path).unwrap();
        let schema = read_schema_state(&upgraded).unwrap();
        assert_eq!(schema.revision, SCHEMA_VERSION);
        assert_eq!(schema.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
        let error = schema.ensure_supported_by(47).unwrap_err();
        assert!(matches!(
            error.downcast_ref::<StoreSchemaMismatch>().unwrap().reason,
            StoreSchemaMismatchReason::Incompatible {
                minimum_compatible: MINIMUM_COMPATIBLE_VERSION
            }
        ));
        drop(upgraded);
        assert_eq!(load_state_from(&path).unwrap().sessions[&record.id], record);
    }

    #[test]
    fn durable_target_migration_preserves_sessions_and_refuses_previous_builds() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("target-migration.sqlite3");
        let record = super::super::tests::session("preserved-session", "project");
        save_session_to(&path, &record).unwrap();
        let connection = Connection::open(&path).unwrap();
        connection
            .execute_batch(
                "ALTER TABLE sessions DROP COLUMN target_runtime_json;
             DELETE FROM schema_migrations WHERE version >= 46;
             UPDATE schema_compatibility SET minimum_compatible_version = 44;
             PRAGMA user_version = 45;",
            )
            .unwrap();
        forget_verified_schema(&path);
        let upgraded = open_writer(&path).unwrap();
        let schema = read_schema_state(&upgraded).unwrap();
        assert_eq!(schema.revision, SCHEMA_VERSION);
        assert_eq!(schema.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
        let error = schema.ensure_supported_by(45).unwrap_err();
        assert!(matches!(
            error.downcast_ref::<StoreSchemaMismatch>().unwrap().reason,
            StoreSchemaMismatchReason::Incompatible {
                minimum_compatible: MINIMUM_COMPATIBLE_VERSION
            }
        ));
        drop(upgraded);
        let restored = load_state_from(&path).unwrap();
        assert_eq!(restored.sessions[&record.id], record);
    }

    #[test]
    fn native_agents_and_unstructured_input_raise_the_store_compatibility_floor() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("mj.sqlite3");
        let connection = open_writer(&path).unwrap();
        connection
            .execute_batch(
                "BEGIN IMMEDIATE;
             DROP TABLE quota_reset_cache;
             DROP TABLE native_agent_transcript;
             DROP TABLE native_agents;
             DROP TABLE native_agent_replay;
             DELETE FROM schema_migrations WHERE version >= 39;
             UPDATE schema_compatibility SET minimum_compatible_version = 32;
             PRAGMA user_version = 38;
             COMMIT;",
            )
            .unwrap();
        migrate_schema(&connection).unwrap();
        let state = read_schema_state(&connection).unwrap();
        assert_eq!(state.revision, SCHEMA_VERSION);
        assert_eq!(state.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
        let event = ApiEventData::InputRequired {
            request: None,
            turn_id: Some(1),
        };
        #[derive(serde::Deserialize)]
        struct LegacyInputEvent {
            #[serde(rename = "request")]
            _request: mj_core::elicitation::ElicitationRequest,
        }
        let encoded = serde_json::to_value(&event).unwrap();
        assert!(serde_json::from_value::<LegacyInputEvent>(encoded["data"].clone()).is_err());
    }

    #[test]
    fn older_readers_and_reopened_writers_preserve_a_compatible_future_schema() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("mj.sqlite3");
        let connection = open_writer(&path).unwrap();
        connection
            .execute_batch(
                "CREATE TABLE future_feature(value TEXT NOT NULL);
                 INSERT INTO future_feature VALUES ('preserve me');",
            )
            .unwrap();
        drop(connection);
        advance_test_schema(&path, SCHEMA_VERSION + 1, SCHEMA_VERSION);

        let reader = open_reader_strict(&path).unwrap();
        assert_eq!(
            reader
                .query_row("SELECT value FROM future_feature", [], |row| row
                    .get::<_, String>(0))
                .unwrap(),
            "preserve me"
        );
        assert!(reader.execute("DELETE FROM future_feature", []).is_err());
        drop(reader);

        // A repair would recreate this deliberately removed trigger. A future
        // schema is authoritative even when it differs from our own repairs.
        let raw = Connection::open(&path).unwrap();
        raw.execute_batch("DROP TRIGGER session_contexts_workspace_update;")
            .unwrap();
        drop(raw);
        let writer = open_writer(&path).unwrap();
        assert!(!writer.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name = 'session_contexts_workspace_update')", [], |row| row.get::<_, bool>(0)).unwrap());
        assert_eq!(
            writer
                .query_row("SELECT value FROM future_feature", [], |row| row
                    .get::<_, String>(0))
                .unwrap(),
            "preserve me"
        );
        let state = read_schema_state(&writer).unwrap();
        assert_eq!(state.revision, SCHEMA_VERSION + 1);
        assert_eq!(state.minimum_compatible, Some(SCHEMA_VERSION));
    }

    #[test]
    fn invalid_compatibility_metadata_refuses_readers_and_writers() {
        for alteration in [
            "DROP TABLE schema_compatibility",
            "DELETE FROM schema_compatibility",
            "PRAGMA ignore_check_constraints = ON; UPDATE schema_compatibility SET minimum_compatible_version = 0",
            "UPDATE schema_compatibility SET minimum_compatible_version = 99999",
            "PRAGMA ignore_check_constraints = ON; UPDATE schema_compatibility SET singleton = 2",
            "PRAGMA ignore_check_constraints = ON; INSERT INTO schema_compatibility VALUES (2, 30)",
            "DROP TABLE schema_compatibility; CREATE TABLE schema_compatibility(singleton, minimum_compatible_version); INSERT INTO schema_compatibility VALUES (1, 'invalid')",
            "DELETE FROM schema_migrations WHERE version = (SELECT max(version) FROM schema_migrations)",
        ] {
            for future in [false, true] {
                let directory = tempfile::tempdir().unwrap();
                let path = directory.path().join("mj.sqlite3");
                drop(open_writer(&path).unwrap());
                if future {
                    advance_test_schema(&path, SCHEMA_VERSION + 1, SCHEMA_VERSION);
                }
                let raw = Connection::open(&path).unwrap();
                raw.execute_batch(alteration).unwrap();
                let before: i64 = raw
                    .query_row("PRAGMA schema_version", [], |row| row.get(0))
                    .unwrap();
                // Exercise the cached path as well as a fresh writer open.
                for error in [
                    open_reader_strict(&path).unwrap_err(),
                    open_writer(&path).unwrap_err(),
                ] {
                    let mismatch = error.downcast_ref::<StoreSchemaMismatch>().unwrap();
                    assert_eq!(
                        mismatch.reason,
                        StoreSchemaMismatchReason::InvalidCompatibilityMetadata,
                        "{alteration}"
                    );
                }
                forget_verified_schema(&path);
                assert!(open_writer(&path).is_err(), "{alteration}");
                let after: i64 = raw
                    .query_row("PRAGMA schema_version", [], |row| row.get(0))
                    .unwrap();
                assert_eq!(
                    before, after,
                    "a rejected open repaired schema: {alteration}"
                );
            }
        }
    }

    #[test]
    fn a_failed_baseline_leaves_an_empty_store_that_a_retry_creates() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("mj.sqlite3");
        let connection = Connection::open(&path).unwrap();
        // A table the baseline also creates makes its batch fail part way.
        connection
            .execute_batch("CREATE TABLE workspaces(conflict TEXT)")
            .unwrap();

        let error = migrate_schema(&connection).unwrap_err();

        assert!(format!("{error:#}").contains("create baseline database schema"));
        assert!(
            connection.is_autocommit(),
            "the failed baseline left a transaction open"
        );
        assert_eq!(read_schema_state(&connection).unwrap().revision, 0);
        let tables: i64 = connection
            .query_row(
                "SELECT count(*) FROM sqlite_schema WHERE type = 'table'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(tables, 1, "only the conflicting table remains");

        connection.execute_batch("DROP TABLE workspaces").unwrap();
        drop(connection);
        let writer = open_writer(&path).unwrap();
        let state = read_schema_state(&writer).unwrap();
        assert_eq!(state.revision, SCHEMA_VERSION);
        assert_eq!(state.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
    }

    /// A store ahead of this build cannot be fixed by starting a daemon of
    /// this build, so the reader must not say so. This is the message the
    /// incident in #24 printed twice a second for an hour.
    #[test]
    fn strict_reader_reports_a_newer_store_without_blaming_the_daemon() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("mj.sqlite3");
        drop(open_writer(&path).unwrap());
        stamp_schema_version(&path, SCHEMA_VERSION + 1);

        let error = open_reader_strict(&path).unwrap_err();

        let mismatch = error
            .chain()
            .find_map(|cause| cause.downcast_ref::<StoreSchemaMismatch>())
            .expect("the reader reports the mismatch as a typed cause");
        assert_eq!(mismatch.found, SCHEMA_VERSION + 1);
        assert_eq!(mismatch.supported, SCHEMA_VERSION);
        let message = mismatch.to_string();
        assert!(message.contains("upgrade Mjolnir"), "got {message}");
        assert!(
            !message.contains("start the Mjolnir daemon"),
            "got {message}"
        );
    }

    /// A store behind this build keeps the advice that works, verbatim, so
    /// existing log greps and runbooks keep matching.
    #[test]
    fn strict_reader_keeps_the_migrate_advice_when_the_store_is_behind() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("mj.sqlite3");
        drop(open_writer(&path).unwrap());
        let raw = Connection::open(&path).unwrap();
        raw.execute_batch(&format!(
            "UPDATE schema_compatibility SET minimum_compatible_version = {0};
             DELETE FROM schema_migrations WHERE version > {0};
             INSERT OR IGNORE INTO schema_migrations(version, applied_at) VALUES ({0}, 'test');
             PRAGMA user_version = {0};",
            SCHEMA_VERSION - 1
        ))
        .unwrap();
        drop(raw);

        let error = open_reader_strict(&path).unwrap_err();

        let mismatch = error
            .chain()
            .find_map(|cause| cause.downcast_ref::<StoreSchemaMismatch>())
            .expect("the reader reports the mismatch as a typed cause");
        assert_eq!(
            mismatch.to_string(),
            format!(
                "Mjolnir database schema {} is not the supported schema {SCHEMA_VERSION}; \
                 start the Mjolnir daemon to migrate it",
                SCHEMA_VERSION - 1
            )
        );
    }

    #[test]
    fn strict_reader_rejects_mutation() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("mj.sqlite3");
        drop(open_writer(&path).unwrap());

        let reader = open_reader_strict(&path).unwrap();
        let error = reader
            .execute("CREATE TABLE forbidden(value TEXT)", [])
            .unwrap_err();
        assert!(
            matches!(
                error.sqlite_error_code(),
                Some(rusqlite::ErrorCode::ReadOnly)
            ),
            "unexpected mutation error: {error}"
        );
    }
}