allen-store-sqlite 0.1.0

SQLite single-owner Tokio actor backend for allen-store (BEGIN IMMEDIATE, FULL sync, SHA-256 migrations)
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
//! Unified durable session persistence backed by [`crate::SqliteAgentStore`].
//!
//! Every session under one server authority root shares two WAL-mode SQLite databases:
//! - [`SESSIONS_DB_FILE`] (`sessions.sqlite`): canonical `AgentStore` schema holding
//!   conversation entries, tree branches, leases, effects, approvals, dialogs, and spend records.
//! - [`SESSIONS_INDEX_DB_FILE`] (`sessions_index.sqlite`): wire-envelope metadata including
//!   session catalog rows, drafts, idempotent command receipts, and chat upload receipts.

use crate::{JournalMode, SqliteAgentStore, SqliteStoreConfig};
use allen_protocol::admission::{AuthenticatedClient, CurrentAuthority, preflight};
pub use allen_protocol::authority::{
    AdmittedCommand, AuthorityFuture, SessionAuthorityPort, SessionState, default_capabilities,
    derive_capabilities, project_core_entry, project_history_entry,
};
use allen_protocol::chat_upload::{ChatUploadKey, ChatUploadOutcome, ChatUploadScope};
use allen_protocol::contracts::*;
use allen_protocol::native_console::{NativeId, NativeText};
use allen_protocol::native_history::{
    NativeHistoryDirection, NativeHistoryEntry, NativeHistoryPage, NativeHistoryQuery,
};
pub use allen_protocol::sha256_digest;
use allen_store::{LoadedBranch, SessionStore as _};
use allen_types::ids::{SessionId as CoreSessionId, TenantId as CoreTenantId};
use allen_types::lifecycle::SessionLifecycleState;
use serde::{Deserialize, Serialize};
use sqlx::{Row as _, SqlitePool};
use std::collections::BTreeMap;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

/// Filename of the unified `SqliteAgentStore` database inside a server's private root.
pub const SESSIONS_DB_FILE: &str = "sessions.sqlite";
/// Filename of the session metadata, receipt, and upload index database inside a private root.
pub const SESSIONS_INDEX_DB_FILE: &str = "sessions_index.sqlite";

const INDEX_SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS sessions_meta (
    session_id TEXT PRIMARY KEY NOT NULL,
    tenant_id TEXT NOT NULL,
    workspace_id TEXT NOT NULL,
    workspace_mode TEXT NOT NULL,
    cwd TEXT NOT NULL,
    org_id TEXT,
    user_id TEXT,
    title TEXT NOT NULL,
    unsent_draft TEXT NOT NULL DEFAULT '',
    draft_revision INTEGER NOT NULL DEFAULT 0,
    revision INTEGER NOT NULL DEFAULT 1,
    settings_revision TEXT NOT NULL,
    policy_digest TEXT NOT NULL,
    lifecycle TEXT NOT NULL DEFAULT 'draft',
    branch_epoch TEXT NOT NULL,
    activity_epoch TEXT NOT NULL,
    owner_id TEXT NOT NULL,
    lease_id TEXT NOT NULL,
    fence INTEGER NOT NULL DEFAULT 1,
    created_at_ms INTEGER NOT NULL,
    updated_at_ms INTEGER NOT NULL,
    native_session_id TEXT,
    parent_session_id TEXT
);
CREATE TABLE IF NOT EXISTS command_receipts (
    session_id TEXT NOT NULL,
    command_id TEXT NOT NULL,
    request_digest TEXT NOT NULL,
    receipt_json TEXT NOT NULL,
    PRIMARY KEY (session_id, command_id)
);
CREATE TABLE IF NOT EXISTS chat_uploads (
    session_id TEXT NOT NULL,
    upload_id TEXT NOT NULL,
    request_digest TEXT NOT NULL,
    filename TEXT NOT NULL,
    bytes INTEGER NOT NULL,
    PRIMARY KEY (session_id, upload_id)
);
";

fn opaque_id(prefix: &str) -> Result<String, String> {
    let mut bytes = [0_u8; 16];
    getrandom::fill(&mut bytes).map_err(|_| "OS randomness unavailable".to_owned())?;
    Ok(format!("{prefix}{}", allen_protocol::hex_lower(&bytes)))
}

/// Durable session identity record exported inside offline backup manifests.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SessionShardIdentity {
    /// Unique identifier of the persisted session.
    pub session_id: SessionId,
    /// Workspace identifier bound to the session.
    pub workspace_id: WorkspaceId,
    /// Execution mode (`Code` or `Chat`) of the session.
    pub workspace_mode: SessionMode,
    /// Optional parent session ID if this session was spawned as a child.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_session_id: Option<SessionId>,
}

/// Durable receipt metadata for a saved Chat-mode attachment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SavedChatAttachment {
    /// Scoped idempotency key and request digest of the upload.
    pub key: ChatUploadKey,
    /// Sanitized filename stored under the session's `uploads/` directory.
    pub name: String,
    /// Exact decoded byte length of the saved attachment.
    pub size: usize,
}

/// Shared handles to the authority's two SQLite databases (`sessions.sqlite` and
/// `sessions_index.sqlite`).
#[derive(Clone)]
pub struct AuthorityDatabases {
    /// Private state root directory containing both database files.
    pub root: PathBuf,
    /// Shared `SqliteAgentStore` pool storing session branches, entries, and leases.
    pub agent_store: Arc<SqliteAgentStore>,
    /// Filesystem path to `sessions_index.sqlite`.
    pub index_path: PathBuf,
    /// SQLx connection pool for `sessions_index.sqlite`.
    pub index_pool: SqlitePool,
}

impl AuthorityDatabases {
    /// Opens and migrates `sessions.sqlite` and `sessions_index.sqlite` under `root`.
    ///
    /// # Errors
    ///
    /// Returns an error if either SQLite file cannot be opened or its schema migration fails.
    pub fn open(root: &Path) -> Pin<Box<dyn Future<Output = Result<Self, String>> + Send>> {
        let root_owned = root.to_path_buf();
        Box::pin(async move {
            let store_path = root_owned.join(SESSIONS_DB_FILE);
            let cfg = SqliteStoreConfig::try_new(store_path)
                .map_err(|e| format!("sqlite store config: {e}"))?
                .with_journal_mode(JournalMode::Wal);
            let agent_store = SqliteAgentStore::connect_and_migrate(cfg)
                .await
                .map_err(|e| format!("open SqliteAgentStore: {e}"))?;

            let index_path = root_owned.join(SESSIONS_INDEX_DB_FILE);
            let index_pool = open_index_pool(index_path.clone()).await?;
            for stmt in INDEX_SCHEMA
                .split(';')
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                sqlx::query(stmt)
                    .execute(&index_pool)
                    .await
                    .map_err(|e| format!("migrate sessions_index.sqlite: {e}"))?;
            }
            Ok(Self {
                root: root_owned,
                agent_store: Arc::new(agent_store),
                index_path,
                index_pool,
            })
        })
    }

    /// Returns all persisted [`SessionId`]s ordered ascending from `sessions_meta`.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite query fails or a stored ID fails validation.
    pub fn list_session_ids(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<SessionId>, String>> + Send>> {
        let pool = self.index_pool.clone();
        Box::pin(async move {
            let rows = sqlx::query("SELECT session_id FROM sessions_meta ORDER BY session_id ASC")
                .fetch_all(&pool)
                .await
                .map_err(|e| format!("list sessions: {e}"))?;
            let mut ids = Vec::with_capacity(rows.len());
            for row in rows {
                let raw: String = row.try_get(0).map_err(|e| e.to_string())?;
                ids.push(SessionId::new(raw)?);
            }
            Ok(ids)
        })
    }
}

async fn open_index_pool(path: PathBuf) -> Result<SqlitePool, String> {
    let opts = sqlx::sqlite::SqliteConnectOptions::new()
        .filename(&path)
        .create_if_missing(true)
        .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal)
        .synchronous(sqlx::sqlite::SqliteSynchronous::Normal)
        .busy_timeout(std::time::Duration::from_secs(5));
    sqlx::sqlite::SqlitePoolOptions::new()
        .max_connections(4)
        .connect_with(opts)
        .await
        .map_err(|e| format!("connect {}: {e}", path.display()))
}

async fn open_index_pool_readonly(path: PathBuf) -> Result<SqlitePool, String> {
    let opts = sqlx::sqlite::SqliteConnectOptions::new()
        .filename(&path)
        .read_only(true)
        .busy_timeout(std::time::Duration::from_secs(5));
    sqlx::sqlite::SqlitePoolOptions::new()
        .max_connections(1)
        .connect_with(opts)
        .await
        .map_err(|e| format!("connect {} readonly: {e}", path.display()))
}

async fn open_index_pool_direct(path: PathBuf) -> Result<SqlitePool, String> {
    let opts = sqlx::sqlite::SqliteConnectOptions::new()
        .filename(&path)
        .create_if_missing(false)
        .busy_timeout(std::time::Duration::from_secs(5));
    sqlx::sqlite::SqlitePoolOptions::new()
        .max_connections(1)
        .connect_with(opts)
        .await
        .map_err(|e| format!("connect {}: {e}", path.display()))
}

/// Returns the current system clock timestamp in milliseconds since the Unix epoch.
pub fn wall_millis() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Per-session durable store handle owned exclusively by one `SessionActor`.
pub struct ActorSessionStore {
    dbs: AuthorityDatabases,
    state: SessionState,
}

impl ActorSessionStore {
    /// Opens [`AuthorityDatabases`] under `root` and creates a new unscoped session row.
    ///
    /// # Errors
    ///
    /// Returns an error if database startup, `SqliteAgentStore` session creation, or
    /// `sessions_meta` insertion fails.
    #[allow(clippy::too_many_arguments)]
    pub fn create(
        root: &Path,
        id: SessionId,
        workspace_id: WorkspaceId,
        mode: SessionMode,
        cwd: PathBuf,
        epoch: &str,
        title: String,
        draft: String,
    ) -> Pin<Box<dyn Future<Output = Result<Self, String>> + Send>> {
        let root_owned = root.to_path_buf();
        let epoch_owned = epoch.to_owned();
        Box::pin(async move {
            let dbs = AuthorityDatabases::open(&root_owned).await?;
            Self::create_in_dbs(
                dbs,
                id,
                workspace_id,
                mode,
                cwd,
                &epoch_owned,
                title,
                draft,
                None,
                None,
            )
            .await
        })
    }

    /// Creates a new session in already-open [`AuthorityDatabases`] with optional `org_id`
    /// and `user_id` scope.
    ///
    /// # Errors
    ///
    /// Returns an error if tenant or session ID validation fails or SQLite insertion fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_with_scope(
        dbs: AuthorityDatabases,
        id: SessionId,
        workspace_id: WorkspaceId,
        mode: SessionMode,
        cwd: PathBuf,
        epoch: &str,
        title: String,
        draft: String,
        org_id: Option<String>,
        user_id: Option<String>,
    ) -> Result<Self, String> {
        Self::create_in_dbs(
            dbs,
            id,
            workspace_id,
            mode,
            cwd,
            epoch,
            title,
            draft,
            org_id,
            user_id,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    async fn create_in_dbs(
        dbs: AuthorityDatabases,
        id: SessionId,
        workspace_id: WorkspaceId,
        mode: SessionMode,
        cwd: PathBuf,
        epoch: &str,
        title: String,
        draft: String,
        org_id: Option<String>,
        user_id: Option<String>,
    ) -> Result<Self, String> {
        let now = wall_millis();
        let tenant_id = TenantId::new("local")?;
        let core_tenant = CoreTenantId::try_new(org_id.as_deref().unwrap_or("local"))
            .map_err(|e| format!("invalid tenant id: {e}"))?;
        let core_session =
            CoreSessionId::try_new(id.as_str()).map_err(|e| format!("invalid session id: {e}"))?;
        dbs.agent_store
            .create_session(&core_tenant, &core_session, None)
            .await
            .map_err(|e| format!("create agent session: {e}"))?;

        let branch_epoch = BranchEpoch::new("branch:1")?;
        let activity_epoch = ActivityEpoch::new("activity:1")?;
        let owner_id = OwnerId::new(format!("owner:{epoch}"))?;
        let lease_id = LeaseId::new(opaque_id("lease:")?)?;
        let settings_revision = sha256_digest(b"{}");
        let policy_digest =
            sha256_digest(format!("{}:{:?}", workspace_id.as_str(), mode).as_bytes());
        let mode_str = match mode {
            SessionMode::Code => "code",
            SessionMode::Chat => "chat",
        };

        let pool = &dbs.index_pool;
        sqlx::query(
            "INSERT INTO sessions_meta (
                session_id, tenant_id, workspace_id, workspace_mode, cwd, org_id, user_id,
                title, unsent_draft, draft_revision, revision, settings_revision, policy_digest,
                lifecycle, branch_epoch, activity_epoch, owner_id, lease_id, fence,
                created_at_ms, updated_at_ms, native_session_id, parent_session_id
            ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,0,1,?10,?11,'draft',?12,?13,?14,?15,1,?16,?16,?17,NULL)",
        )
        .bind(id.as_str())
        .bind(tenant_id.as_str())
        .bind(workspace_id.as_str())
        .bind(mode_str)
        .bind(cwd.to_string_lossy().as_ref())
        .bind(org_id.as_deref())
        .bind(user_id.as_deref())
        .bind(&title)
        .bind(&draft)
        .bind(settings_revision.as_str())
        .bind(policy_digest.as_str())
        .bind(branch_epoch.as_str())
        .bind(activity_epoch.as_str())
        .bind(owner_id.as_str())
        .bind(lease_id.as_str())
        .bind(now as i64)
        .bind(id.as_str())
        .execute(pool)
        .await
        .map_err(|e| format!("insert session metadata: {e}"))?;

        let state = build_initial_state(
            id,
            tenant_id,
            workspace_id,
            mode,
            cwd,
            org_id,
            user_id,
            title,
            draft,
            0,
            1,
            settings_revision,
            policy_digest,
            SessionLifecycle::Draft,
            branch_epoch,
            activity_epoch,
            owner_id,
            lease_id,
            1,
            now,
            now,
            epoch,
            None,
        )?;
        Ok(Self { dbs, state })
    }

    /// Loads an existing session from `dbs`, increments its owner lease fence for `epoch`,
    /// and hydrates committed transcript facts from `SqliteAgentStore`.
    ///
    /// # Errors
    ///
    /// Returns an error if the session does not exist, stored metadata is malformed, or
    /// updating the owner fence fails.
    pub fn open(
        dbs: AuthorityDatabases,
        id: SessionId,
        epoch: String,
    ) -> Pin<Box<dyn Future<Output = Result<Self, String>> + Send>> {
        Box::pin(async move { Self::open_inner(dbs, id, epoch).await })
    }

    async fn open_inner(
        dbs: AuthorityDatabases,
        id: SessionId,
        epoch: String,
    ) -> Result<Self, String> {
        let pool = &dbs.index_pool;
        let row = sqlx::query(
            "SELECT session_id, tenant_id, workspace_id, workspace_mode, cwd, org_id, user_id,
                    title, unsent_draft, draft_revision, revision, settings_revision, policy_digest,
                    lifecycle, branch_epoch, activity_epoch, owner_id, lease_id, fence,
                    created_at_ms, updated_at_ms, parent_session_id
             FROM sessions_meta WHERE session_id = ?1",
        )
        .bind(id.as_str())
        .fetch_optional(pool)
        .await
        .map_err(|e| format!("load session metadata: {e}"))?
        .ok_or_else(|| format!("session {} not found", id.as_str()))?;

        let tenant_id = TenantId::new(row.try_get::<String, _>(1).map_err(|e| e.to_string())?)?;
        let workspace_id =
            WorkspaceId::new(row.try_get::<String, _>(2).map_err(|e| e.to_string())?)?;
        let mode_str: String = row.try_get(3).map_err(|e| e.to_string())?;
        let mode = match mode_str.as_str() {
            "chat" => SessionMode::Chat,
            _ => SessionMode::Code,
        };
        let cwd = PathBuf::from(row.try_get::<String, _>(4).map_err(|e| e.to_string())?);
        let org_id: Option<String> = row.try_get(5).map_err(|e| e.to_string())?;
        let user_id: Option<String> = row.try_get(6).map_err(|e| e.to_string())?;
        let title: String = row.try_get(7).map_err(|e| e.to_string())?;
        let draft: String = row.try_get(8).map_err(|e| e.to_string())?;
        let draft_rev = row.try_get::<i64, _>(9).map_err(|e| e.to_string())? as u64;
        let rev = row.try_get::<i64, _>(10).map_err(|e| e.to_string())? as u64;
        let settings_revision =
            Digest::try_from(row.try_get::<String, _>(11).map_err(|e| e.to_string())?)?;
        let policy_digest =
            Digest::try_from(row.try_get::<String, _>(12).map_err(|e| e.to_string())?)?;
        let lifecycle_str: String = row.try_get(13).map_err(|e| e.to_string())?;
        let lifecycle = match lifecycle_str.as_str() {
            "open" => SessionLifecycle::Open,
            "closed" => SessionLifecycle::Closed,
            _ => SessionLifecycle::Draft,
        };
        let branch_epoch =
            BranchEpoch::new(row.try_get::<String, _>(14).map_err(|e| e.to_string())?)?;
        let activity_epoch =
            ActivityEpoch::new(row.try_get::<String, _>(15).map_err(|e| e.to_string())?)?;
        let owner_id = OwnerId::new(format!("owner:{epoch}"))?;
        let lease_id = LeaseId::new(opaque_id("lease:")?)?;
        let fence = (row.try_get::<i64, _>(18).map_err(|e| e.to_string())? as u64) + 1;
        let created_at_ms = row.try_get::<i64, _>(19).map_err(|e| e.to_string())? as u64;
        let updated_at_ms = row.try_get::<i64, _>(20).map_err(|e| e.to_string())? as u64;
        let parent_session_id = row
            .try_get::<Option<String>, _>(21)
            .map_err(|e| e.to_string())?
            .map(SessionId::new)
            .transpose()?;

        sqlx::query(
            "UPDATE sessions_meta SET owner_id = ?1, lease_id = ?2, fence = ?3 WHERE session_id = ?4",
        )
        .bind(owner_id.as_str())
        .bind(lease_id.as_str())
        .bind(fence as i64)
        .bind(id.as_str())
        .execute(pool)
        .await
        .map_err(|e| format!("bump session fence: {e}"))?;

        let mut state = build_initial_state(
            id.clone(),
            tenant_id,
            workspace_id,
            mode,
            cwd,
            org_id,
            user_id,
            title,
            draft,
            draft_rev,
            rev,
            settings_revision,
            policy_digest,
            lifecycle,
            branch_epoch,
            activity_epoch,
            owner_id,
            lease_id,
            fence,
            created_at_ms,
            updated_at_ms,
            &epoch,
            parent_session_id,
        )?;

        // Hydrate committed transcript facts from SqliteAgentStore on reopen.
        let core_tenant = CoreTenantId::try_new(state.org_id.as_deref().unwrap_or("local"))
            .map_err(|e| format!("invalid tenant id: {e}"))?;
        let core_session =
            CoreSessionId::try_new(id.as_str()).map_err(|e| format!("invalid session id: {e}"))?;
        if let Ok(LoadedBranch { entries, .. }) = dbs
            .agent_store
            .load_branch(&core_tenant, &core_session, None)
            .await
        {
            let leaf = entries.last().map(|e| e.entry_id.as_str().to_owned());
            state.native_state.selected_leaf = leaf.clone();
            state.authority.guard.selected_leaf = leaf.and_then(|id| EntryId::new(id).ok());
            for entry in entries {
                if let Some(rec) = project_core_entry(&entry) {
                    state.facts.insert(rec.id.clone(), rec);
                }
            }
        }

        Ok(Self { dbs, state })
    }

    /// Returns the shared [`SqliteAgentStore`] backing this session's transcript and leases.
    pub fn agent_store(&self) -> Arc<SqliteAgentStore> {
        Arc::clone(&self.dbs.agent_store)
    }

    /// Returns the validated `allen_types` tenant ID (`org_id` or `"local"`).
    pub fn core_tenant_id(&self) -> CoreTenantId {
        self.state.core_tenant_id()
    }

    /// Returns the validated `allen_types` session ID corresponding to this store.
    pub fn core_session_id(&self) -> CoreSessionId {
        self.state.core_session_id()
    }

    /// Returns a shared reference to the in-memory [`SessionState`].
    pub fn state(&self) -> &SessionState {
        &self.state
    }

    /// Returns a mutable reference to the in-memory [`SessionState`].
    pub fn state_mut(&mut self) -> &mut SessionState {
        &mut self.state
    }

    /// Clones this session's current [`SessionCatalogEntry`].
    pub fn catalog_entry(&self) -> SessionCatalogEntry {
        self.state.catalog_entry()
    }

    /// Returns the current [`ReplayCursor`] for the main session projection.
    pub fn cursor(&self) -> ReplayCursor {
        ReplayCursor {
            projection_id: ProjectionId::new("session:main").expect("valid projection id"),
            scope: self.state.authority.guard.scope.clone(),
            epoch: self.state.stream_epoch.clone(),
            after_sequence: self.state.sequence,
        }
    }

    /// Computes the current [`Capability`] list for this session's lifecycle and pending gates.
    pub fn current_capabilities(&self) -> Vec<Capability> {
        derive_capabilities(
            &self.state.catalog.lifecycle,
            self.state.native_started,
            self.state.authority.approval.is_some(),
            self.state.authority.dialog.is_some(),
        )
    }

    /// Synchronizes `state.authority.capabilities` with [`ActorSessionStore::current_capabilities`].
    pub fn sync_authority_capabilities(&mut self) {
        self.state.authority.capabilities = self
            .current_capabilities()
            .into_iter()
            .filter(|c| c.available)
            .map(|c| c.name)
            .collect();
    }

    /// Builds a complete wire [`Snapshot`] from the current guard, cursor, capabilities, and facts.
    pub fn snapshot(&self) -> Snapshot {
        Snapshot {
            version: VERSION,
            guard: self.state.authority.guard.clone(),
            cursor: self.cursor(),
            capabilities: self.current_capabilities(),
            facts: self.state.facts.values().cloned().collect(),
        }
    }

    /// Inserts or replaces a projected [`FactRecord`] by its typed ID.
    pub fn upsert_fact(&mut self, record: FactRecord) {
        self.state.facts.insert(record.id.clone(), record);
    }

    /// Removes a projected [`FactRecord`] by its typed ID, if present.
    pub fn remove_fact(&mut self, id: &str) {
        self.state.facts.remove(id);
    }

    /// Advances the publication sequence number by one and returns the updated [`ReplayCursor`].
    pub fn bump_sequence(&mut self) -> ReplayCursor {
        self.state.sequence = Counter(self.state.sequence.0 + 1);
        self.cursor()
    }

    /// Increments the durable session revision, updates `updated_at_ms` and `native:state`,
    /// and persists the new revision to `sessions_meta`.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite update fails.
    pub async fn bump_revision(&mut self) -> Result<Counter, String> {
        let next = Counter(self.state.authority.guard.revision.0 + 1);
        let now = wall_millis();
        self.state.authority.guard.revision = next;
        self.state.catalog.revision = next;
        self.state.catalog.updated_at_ms = Counter(now);
        self.state.native_state.revision = next;
        self.state.native_state.publication_sequence = Counter(self.state.sequence.0 + 1);
        self.upsert_fact(FactRecord {
            id: "native:state".to_owned(),
            fact: Fact::NativeState(self.state.native_state.clone()),
        });
        sqlx::query(
            "UPDATE sessions_meta SET revision = ?1, updated_at_ms = ?2 WHERE session_id = ?3",
        )
        .bind(next.0 as i64)
        .bind(now as i64)
        .bind(self.state.catalog.session_id.as_str())
        .execute(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("persist revision: {e}"))?;
        Ok(next)
    }

    /// Updates and persists the session's [`SessionLifecycle`] (`draft`, `open`, or `closed`).
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite update fails.
    pub async fn persist_lifecycle(&mut self, lifecycle: SessionLifecycle) -> Result<(), String> {
        let label = match lifecycle {
            SessionLifecycle::Draft => "draft",
            SessionLifecycle::Open => "open",
            SessionLifecycle::Closed => "closed",
        };
        self.state.catalog.lifecycle = lifecycle;
        sqlx::query("UPDATE sessions_meta SET lifecycle = ?1 WHERE session_id = ?2")
            .bind(label)
            .bind(self.state.catalog.session_id.as_str())
            .execute(&self.dbs.index_pool)
            .await
            .map_err(|e| format!("persist lifecycle: {e}"))?;
        Ok(())
    }

    /// Updates and persists the session's display title in `sessions_meta`.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite update fails.
    pub async fn persist_title(&mut self, title: String) -> Result<(), String> {
        self.state.catalog.title = PublicText(title.clone());
        sqlx::query("UPDATE sessions_meta SET title = ?1 WHERE session_id = ?2")
            .bind(&title)
            .bind(self.state.catalog.session_id.as_str())
            .execute(&self.dbs.index_pool)
            .await
            .map_err(|e| format!("persist title: {e}"))?;
        Ok(())
    }

    /// Saves `text` as the unsent draft, increments `draft_revision`, and persists both.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite update fails.
    pub async fn persist_draft(&mut self, text: String) -> Result<Counter, String> {
        let next_draft_rev = Counter(self.state.authority.draft_revision.0 + 1);
        self.state.authority.draft_revision = next_draft_rev;
        self.state.catalog.draft_revision = next_draft_rev;
        self.state.catalog.unsent_draft = text.clone();
        sqlx::query(
            "UPDATE sessions_meta SET unsent_draft = ?1, draft_revision = ?2 WHERE session_id = ?3",
        )
        .bind(&text)
        .bind(next_draft_rev.0 as i64)
        .bind(self.state.catalog.session_id.as_str())
        .execute(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("persist draft: {e}"))?;
        Ok(next_draft_rev)
    }

    /// Persists the latest observed profile `settings.json` SHA-256 digest for this session.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite update fails.
    pub async fn persist_settings_revision(&mut self, rev: Digest) -> Result<(), String> {
        self.state.authority.settings_revision = rev.clone();
        sqlx::query("UPDATE sessions_meta SET settings_revision = ?1 WHERE session_id = ?2")
            .bind(rev.as_str())
            .bind(self.state.catalog.session_id.as_str())
            .execute(&self.dbs.index_pool)
            .await
            .map_err(|e| format!("persist settings revision: {e}"))?;
        Ok(())
    }

    /// Fetches a durable [`WireCommandReceipt`] for `id`, returning `Ok(None)` if not recorded.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite query or JSON deserialization fails.
    pub async fn receipt(&mut self, id: &CommandId) -> Result<Option<WireCommandReceipt>, String> {
        let row = sqlx::query(
            "SELECT receipt_json FROM command_receipts WHERE session_id = ?1 AND command_id = ?2",
        )
        .bind(self.state.catalog.session_id.as_str())
        .bind(id.as_str())
        .fetch_optional(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("read receipt: {e}"))?;
        match row {
            Some(r) => {
                let raw: String = r.try_get(0).map_err(|e| e.to_string())?;
                serde_json::from_str(&raw)
                    .map(Some)
                    .map_err(|e| format!("decode receipt: {e}"))
            }
            None => Ok(None),
        }
    }

    /// Admits a client command idempotently after running [`preflight`].
    ///
    /// Returns `(receipt, already_existed, admission_class)`. When `command_id` was already
    /// recorded with the same canonical request digest, returns the stored receipt with
    /// `already_existed = true`. Rejected commands are recorded as [`ReceiptPhase::Rejected`].
    ///
    /// # Errors
    ///
    /// Returns an error if `command_id` is reused with a different payload digest or if
    /// SQLite persistence fails.
    pub async fn admit_command(
        &mut self,
        principal: &AuthenticatedClient,
        command: &CommandEnvelope,
    ) -> Result<AdmittedCommand, String> {
        let req_bytes = serde_json::to_vec(command).map_err(|e| format!("encode command: {e}"))?;
        let request_digest = sha256_digest(&req_bytes);

        if let Some(row) = sqlx::query(
            "SELECT request_digest, receipt_json FROM command_receipts
             WHERE session_id = ?1 AND command_id = ?2",
        )
        .bind(self.state.catalog.session_id.as_str())
        .bind(command.command_id.as_str())
        .fetch_optional(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("check idempotency: {e}"))?
        {
            let stored_digest: String = row.try_get(0).map_err(|e| e.to_string())?;
            if stored_digest != request_digest.as_str() {
                return Err(
                    "idempotency conflict: command_id reused with different payload".into(),
                );
            }
            let raw: String = row.try_get(1).map_err(|e| e.to_string())?;
            let receipt: WireCommandReceipt =
                serde_json::from_str(&raw).map_err(|e| format!("decode receipt: {e}"))?;
            return Ok((receipt, true, None));
        }

        self.sync_authority_capabilities();
        let class = match preflight(principal, command, &self.state.authority) {
            Ok(c) => c,
            Err(refusal) => {
                let receipt = WireCommandReceipt {
                    command_id: command.command_id.clone(),
                    request_digest: request_digest.clone(),
                    subject: principal.subject().clone(),
                    scope: self.state.authority.guard.scope.clone(),
                    admitted_revision: self.state.authority.guard.revision,
                    phase: ReceiptPhase::Rejected,
                    effects: vec![],
                    evidence_ids: vec![format!("refused:{refusal:?}")],
                };
                self.store_receipt(&receipt, &request_digest).await?;
                return Ok((receipt, false, None));
            }
        };

        let admitted_revision = self.bump_revision().await?;
        let effect_id = EffectId::new(opaque_id("effect:")?)?;
        let receipt = WireCommandReceipt {
            command_id: command.command_id.clone(),
            request_digest: request_digest.clone(),
            subject: principal.subject().clone(),
            scope: self.state.authority.guard.scope.clone(),
            admitted_revision,
            phase: ReceiptPhase::Prepared,
            effects: vec![effect_id],
            evidence_ids: vec![],
        };
        self.store_receipt(&receipt, &request_digest).await?;
        Ok((receipt, false, Some(class)))
    }

    /// Updates `receipt.phase`, appends an optional `evidence_id`, and persists the receipt.
    ///
    /// # Errors
    ///
    /// Returns an error if serializing or saving the updated receipt fails.
    pub async fn update_receipt_phase(
        &mut self,
        receipt: &mut WireCommandReceipt,
        phase: ReceiptPhase,
        evidence_id: Option<String>,
    ) -> Result<(), String> {
        receipt.phase = phase;
        if let Some(ev) = evidence_id {
            receipt.evidence_ids.push(ev);
        }
        let digest = receipt.request_digest.clone();
        self.store_receipt(receipt, &digest).await
    }

    async fn store_receipt(
        &mut self,
        receipt: &WireCommandReceipt,
        request_digest: &Digest,
    ) -> Result<(), String> {
        let json = serde_json::to_string(receipt).map_err(|e| e.to_string())?;
        sqlx::query(
            "INSERT INTO command_receipts (session_id, command_id, request_digest, receipt_json)
             VALUES (?1, ?2, ?3, ?4)
             ON CONFLICT(session_id, command_id) DO UPDATE SET receipt_json = excluded.receipt_json",
        )
        .bind(self.state.catalog.session_id.as_str())
        .bind(receipt.command_id.as_str())
        .bind(request_digest.as_str())
        .bind(&json)
        .execute(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("persist receipt: {e}"))?;
        Ok(())
    }

    /// Looks up a previously recorded chat attachment upload receipt for `key`.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite lookup fails.
    pub async fn lookup_chat_upload(
        &self,
        key: &ChatUploadKey,
    ) -> Result<Option<ChatUploadOutcome>, String> {
        if let Some(row) = sqlx::query(
            "SELECT request_digest, filename, bytes FROM chat_uploads
             WHERE session_id = ?1 AND upload_id = ?2",
        )
        .bind(self.state.catalog.session_id.as_str())
        .bind(&key.upload_id)
        .fetch_optional(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("check chat upload: {e}"))?
        {
            let digest: String = row.try_get(0).map_err(|e| e.to_string())?;
            if digest != key.request_digest.as_str() {
                return Ok(Some(ChatUploadOutcome::Refused));
            }
            let name: String = row.try_get(1).map_err(|e| e.to_string())?;
            let size = row.try_get::<i64, _>(2).map_err(|e| e.to_string())? as u32;
            return Ok(Some(ChatUploadOutcome::Saved { name, size }));
        }
        Ok(None)
    }

    /// Persists a newly saved chat attachment upload receipt in `chat_uploads`.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQLite insert fails.
    pub async fn record_chat_upload(
        &self,
        key: &ChatUploadKey,
        name: &str,
        size: u32,
    ) -> Result<(), String> {
        sqlx::query(
            "INSERT INTO chat_uploads (session_id, upload_id, request_digest, filename, bytes)
             VALUES (?1, ?2, ?3, ?4, ?5)",
        )
        .bind(self.state.catalog.session_id.as_str())
        .bind(&key.upload_id)
        .bind(key.request_digest.as_str())
        .bind(name)
        .bind(i64::from(size))
        .execute(&self.dbs.index_pool)
        .await
        .map_err(|e| format!("persist chat upload: {e}"))?;
        Ok(())
    }

    /// Loads a paginated slice of committed transcript entries from `SqliteAgentStore`.
    ///
    /// # Errors
    ///
    /// Returns an error if loading the active branch from `SqliteAgentStore` fails.
    pub async fn load_native_history(
        &self,
        query: &NativeHistoryQuery,
    ) -> Result<NativeHistoryPage, String> {
        let core_tenant = self.core_tenant_id();
        let core_session = self.core_session_id();
        let LoadedBranch { entries, .. } = self
            .dbs
            .agent_store
            .load_branch(&core_tenant, &core_session, None)
            .await
            .map_err(|e| format!("load history branch: {e}"))?;

        let limit = usize::from(u16::from(query.limit.clone()));
        let offset = query
            .cursor
            .as_ref()
            .and_then(|c| String::from(c.clone()).parse::<usize>().ok())
            .unwrap_or(0);

        let all_projected: Vec<NativeHistoryEntry> =
            entries.iter().filter_map(project_history_entry).collect();

        let (slice, next_cursor) = match query.direction {
            NativeHistoryDirection::Forward => {
                let start = offset.min(all_projected.len());
                let end = (start + limit).min(all_projected.len());
                let next = (end < all_projected.len())
                    .then(|| NativeText::try_from(end.to_string()).ok())
                    .flatten();
                (all_projected[start..end].to_vec(), next)
            }
            NativeHistoryDirection::Backward => {
                let end = all_projected.len().saturating_sub(offset);
                let start = end.saturating_sub(limit);
                let next = (start > 0)
                    .then(|| NativeText::try_from((all_projected.len() - start).to_string()).ok())
                    .flatten();
                (all_projected[start..end].to_vec(), next)
            }
        };

        let leaf_id = entries
            .last()
            .and_then(|e| NativeId::try_from(e.entry_id.as_str().to_owned()).ok());
        Ok(NativeHistoryPage {
            anchor: self.state.native_state.clone(),
            direction: query.direction.clone(),
            entries: slice,
            live_entry: None,
            next_cursor,
            leaf_id,
        })
    }
}

#[allow(clippy::too_many_arguments)]
fn build_initial_state(
    session_id: SessionId,
    tenant_id: TenantId,
    workspace_id: WorkspaceId,
    workspace_mode: SessionMode,
    cwd: PathBuf,
    org_id: Option<String>,
    user_id: Option<String>,
    title: String,
    draft: String,
    draft_revision: u64,
    revision: u64,
    settings_revision: Digest,
    policy_digest: Digest,
    lifecycle: SessionLifecycle,
    branch_epoch: BranchEpoch,
    activity_epoch: ActivityEpoch,
    owner_id: OwnerId,
    lease_id: LeaseId,
    fence: u64,
    created_at_ms: u64,
    updated_at_ms: u64,
    epoch: &str,
    parent_session_id: Option<SessionId>,
) -> Result<SessionState, String> {
    let instance_id = InstanceId::new(format!("instance:{}", session_id.as_str()))?;
    let scope = Scope {
        tenant_id: tenant_id.clone(),
        instance_id: instance_id.clone(),
        session_id: session_id.clone(),
        branch_epoch: branch_epoch.clone(),
        activity_epoch: activity_epoch.clone(),
        work_id: None,
    };
    let guard = CommandGuard {
        scope,
        owner: OwnerLease {
            owner_id,
            lease_id,
            fence: Counter(fence),
        },
        revision: Counter(revision),
        selected_leaf: None,
        policy_digest,
    };
    let native_started = matches!(lifecycle, SessionLifecycle::Open);
    let runtime = RuntimeView {
        user_run_id: None,
        phase: RuntimePhase::Idle,
        lifecycle_state: Some(match lifecycle {
            SessionLifecycle::Draft => SessionLifecycleState::Draft,
            SessionLifecycle::Open => {
                SessionLifecycleState::Ready(allen_types::lifecycle::TurnState::Idle)
            }
            SessionLifecycle::Closed => SessionLifecycleState::Closed,
        }),
        native_settled: true,
        stop_requested: false,
        unresolved_effects: vec![],
        cleanup_confirmed: true,
    };
    let native_state = NativeStateView {
        runtime_id: format!("allen-runtime:{epoch}"),
        session_id: session_id.as_str().to_owned(),
        branch_epoch: branch_epoch.as_str().to_owned(),
        activity_epoch: activity_epoch.as_str().to_owned(),
        work_id: None,
        revision: Counter(revision),
        publication_sequence: Counter(0),
        selected_leaf: None,
    };
    let authority = CurrentAuthority {
        guard,
        capabilities: derive_capabilities(&lifecycle, native_started, false, false)
            .into_iter()
            .filter(|c| c.available)
            .map(|c| c.name)
            .collect(),
        approval: None,
        dialog: None,
        settings_revision,
        draft_revision: Counter(draft_revision),
        user_run_id: None,
        stop_requested: false,
        phase: RuntimePhase::Idle,
    };
    let catalog = SessionCatalogEntry {
        tenant_id,
        session_id: session_id.clone(),
        instance_id: Some(instance_id),
        workspace_id,
        workspace_mode,
        title: PublicText(title),
        created_at_ms: Counter(created_at_ms),
        updated_at_ms: Counter(updated_at_ms),
        lifecycle,
        revision: Counter(revision),
        draft_revision: Counter(draft_revision),
        unsent_draft: draft,
        native_session_id: Some(session_id.as_str().to_owned()),
        parent_session_id,
    };
    let mut facts = BTreeMap::new();
    facts.insert(
        "runtime:state".to_owned(),
        FactRecord {
            id: "runtime:state".to_owned(),
            fact: Fact::Runtime(runtime.clone()),
        },
    );
    facts.insert(
        "native:state".to_owned(),
        FactRecord {
            id: "native:state".to_owned(),
            fact: Fact::NativeState(native_state.clone()),
        },
    );
    facts.insert(
        "workflow:state".to_owned(),
        FactRecord {
            id: "workflow:state".to_owned(),
            fact: Fact::Workflow(WorkflowView {
                controller: None,
                objective: None,
                todos: vec![],
                goal: None,
                plan: None,
                wait: None,
                report_only: false,
                quarantined: false,
                strict_plan_effective: false,
                containment_pending: false,
                decision_reasons: vec![],
            }),
        },
    );
    facts.insert(
        "presence:session".to_owned(),
        FactRecord {
            id: "presence:session".to_owned(),
            fact: Fact::Presence(PresenceView::default()),
        },
    );
    let stream_epoch = StreamEpoch::new(format!("stream:{epoch}"))?;
    Ok(SessionState {
        catalog,
        cwd,
        org_id,
        user_id,
        authority,
        runtime,
        native_started,
        native_state,
        stream_epoch,
        sequence: Counter(0),
        facts,
    })
}

impl SessionAuthorityPort for ActorSessionStore {
    fn state(&self) -> &SessionState {
        &self.state
    }

    fn state_mut(&mut self) -> &mut SessionState {
        &mut self.state
    }

    fn bump_revision(&mut self) -> AuthorityFuture<'_, Result<Counter, String>> {
        Box::pin(ActorSessionStore::bump_revision(self))
    }

    fn persist_lifecycle(
        &mut self,
        lifecycle: SessionLifecycle,
    ) -> AuthorityFuture<'_, Result<(), String>> {
        Box::pin(ActorSessionStore::persist_lifecycle(self, lifecycle))
    }

    fn persist_title(&mut self, title: String) -> AuthorityFuture<'_, Result<(), String>> {
        Box::pin(ActorSessionStore::persist_title(self, title))
    }

    fn persist_draft(&mut self, text: String) -> AuthorityFuture<'_, Result<Counter, String>> {
        Box::pin(ActorSessionStore::persist_draft(self, text))
    }

    fn persist_settings_revision(
        &mut self,
        rev: Digest,
    ) -> AuthorityFuture<'_, Result<(), String>> {
        Box::pin(ActorSessionStore::persist_settings_revision(self, rev))
    }

    fn receipt(
        &mut self,
        id: &CommandId,
    ) -> AuthorityFuture<'_, Result<Option<WireCommandReceipt>, String>> {
        let id = id.clone();
        Box::pin(async move { ActorSessionStore::receipt(self, &id).await })
    }

    fn admit_command<'a>(
        &'a mut self,
        principal: &'a AuthenticatedClient,
        command: &'a CommandEnvelope,
    ) -> AuthorityFuture<'a, Result<AdmittedCommand, String>> {
        Box::pin(ActorSessionStore::admit_command(self, principal, command))
    }

    fn update_receipt_phase<'a>(
        &'a mut self,
        receipt: &'a mut WireCommandReceipt,
        phase: ReceiptPhase,
        evidence_id: Option<String>,
    ) -> AuthorityFuture<'a, Result<(), String>> {
        Box::pin(ActorSessionStore::update_receipt_phase(
            self,
            receipt,
            phase,
            evidence_id,
        ))
    }

    fn lookup_chat_upload<'a>(
        &'a self,
        key: &'a ChatUploadKey,
    ) -> AuthorityFuture<'a, Result<Option<ChatUploadOutcome>, String>> {
        Box::pin(ActorSessionStore::lookup_chat_upload(self, key))
    }

    fn record_chat_upload<'a>(
        &'a self,
        key: &'a ChatUploadKey,
        name: &'a str,
        size: u32,
    ) -> AuthorityFuture<'a, Result<(), String>> {
        Box::pin(ActorSessionStore::record_chat_upload(self, key, name, size))
    }

    fn load_native_history<'a>(
        &'a self,
        query: &'a NativeHistoryQuery,
    ) -> AuthorityFuture<'a, Result<NativeHistoryPage, String>> {
        Box::pin(ActorSessionStore::load_native_history(self, query))
    }
}

/// Inspects a copied `sessions_index.sqlite` file for backup/restore verification.
pub async fn inspect_copied_index(
    index_db_path: &Path,
) -> Result<Vec<(SessionShardIdentity, TenantId, PathBuf)>, String> {
    let pool = open_index_pool_readonly(index_db_path.to_path_buf()).await?;
    let rows = sqlx::query(
        "SELECT session_id, tenant_id, workspace_id, workspace_mode, cwd, parent_session_id
         FROM sessions_meta ORDER BY session_id ASC",
    )
    .fetch_all(&pool)
    .await
    .map_err(|e| format!("inspect sessions_index.sqlite: {e}"))?;
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        let session_id = SessionId::new(row.try_get::<String, _>(0).map_err(|e| e.to_string())?)?;
        let tenant_id = TenantId::new(row.try_get::<String, _>(1).map_err(|e| e.to_string())?)?;
        let workspace_id =
            WorkspaceId::new(row.try_get::<String, _>(2).map_err(|e| e.to_string())?)?;
        let mode_str: String = row.try_get(3).map_err(|e| e.to_string())?;
        let workspace_mode = match mode_str.as_str() {
            "chat" => SessionMode::Chat,
            _ => SessionMode::Code,
        };
        let cwd = PathBuf::from(row.try_get::<String, _>(4).map_err(|e| e.to_string())?);
        let parent_session_id = row
            .try_get::<Option<String>, _>(5)
            .map_err(|e| e.to_string())?
            .map(SessionId::new)
            .transpose()?;
        out.push((
            SessionShardIdentity {
                session_id,
                workspace_id,
                workspace_mode,
                parent_session_id,
            },
            tenant_id,
            cwd,
        ));
    }
    Ok(out)
}

/// Rebinds a session's stored `cwd` inside a restored `sessions_index.sqlite`.
pub async fn rebind_copied_cwd(
    index_db_path: &Path,
    session_id: &SessionId,
    previous: &Path,
    next: &Path,
) -> Result<(), String> {
    let pool = open_index_pool_direct(index_db_path.to_path_buf()).await?;
    let affected =
        sqlx::query("UPDATE sessions_meta SET cwd = ?1 WHERE session_id = ?2 AND cwd = ?3")
            .bind(next.to_string_lossy().as_ref())
            .bind(session_id.as_str())
            .bind(previous.to_string_lossy().as_ref())
            .execute(&pool)
            .await
            .map_err(|e| format!("rebind restored cwd: {e}"))?
            .rows_affected();
    if affected != 1 {
        return Err("rebind restored cwd did not match expected session row".into());
    }
    Ok(())
}

/// Reads the saved chat upload receipt for offline chat restore verification.
pub async fn read_chat_restore(
    index_db_path: &Path,
    id: &SessionId,
) -> Result<(PathBuf, SavedChatAttachment), String> {
    let pool = open_index_pool_readonly(index_db_path.to_path_buf()).await?;
    let meta =
        sqlx::query("SELECT tenant_id, workspace_id, cwd FROM sessions_meta WHERE session_id = ?1")
            .bind(id.as_str())
            .fetch_optional(&pool)
            .await
            .map_err(|e| format!("read chat session meta: {e}"))?
            .ok_or("chat session not found in backup index")?;
    let tenant_id = TenantId::new(meta.try_get::<String, _>(0).map_err(|e| e.to_string())?)?;
    let workspace_id = WorkspaceId::new(meta.try_get::<String, _>(1).map_err(|e| e.to_string())?)?;
    let cwd = PathBuf::from(meta.try_get::<String, _>(2).map_err(|e| e.to_string())?);

    let upload = sqlx::query(
        "SELECT upload_id, request_digest, filename, bytes FROM chat_uploads WHERE session_id = ?1 LIMIT 1",
    )
    .bind(id.as_str())
    .fetch_optional(&pool)
    .await
    .map_err(|e| format!("read chat upload row: {e}"))?
    .ok_or("no saved chat attachment in backup index")?;
    let upload_id: String = upload.try_get(0).map_err(|e| e.to_string())?;
    let request_digest =
        Digest::try_from(upload.try_get::<String, _>(1).map_err(|e| e.to_string())?)?;
    let name: String = upload.try_get(2).map_err(|e| e.to_string())?;
    let size = upload.try_get::<i64, _>(3).map_err(|e| e.to_string())? as usize;

    Ok((
        cwd,
        SavedChatAttachment {
            key: ChatUploadKey {
                scope: ChatUploadScope {
                    tenant_id,
                    workspace_id,
                    session_id: id.clone(),
                },
                upload_id,
                request_digest,
            },
            name,
            size,
        },
    ))
}