ironclaw 0.22.0

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

use std::collections::HashMap;
use std::time::Duration;

use tokio::sync::RwLock;
use uuid::Uuid;

use crate::context::{JobContext, JobState, Memory};
use crate::error::JobError;

/// Manages contexts for multiple concurrent jobs.
pub struct ContextManager {
    /// Active job contexts.
    contexts: RwLock<HashMap<Uuid, JobContext>>,
    /// Memory for each job.
    memories: RwLock<HashMap<Uuid, Memory>>,
    /// Maximum concurrent jobs.
    max_jobs: usize,
}

impl ContextManager {
    /// Create a new context manager.
    pub fn new(max_jobs: usize) -> Self {
        Self {
            contexts: RwLock::new(HashMap::new()),
            memories: RwLock::new(HashMap::new()),
            max_jobs,
        }
    }

    /// Create a new job context.
    pub async fn create_job(
        &self,
        title: impl Into<String>,
        description: impl Into<String>,
    ) -> Result<Uuid, JobError> {
        self.create_job_for_user("default", title, description)
            .await
    }

    /// Create a new job context for a specific user.
    pub async fn create_job_for_user(
        &self,
        user_id: impl Into<String>,
        title: impl Into<String>,
        description: impl Into<String>,
    ) -> Result<Uuid, JobError> {
        let context = JobContext::with_user(user_id, title, description);
        let job_id = context.job_id;
        self.insert_context(context).await?;
        Ok(job_id)
    }

    /// Register a sandbox job with a pre-determined ID.
    ///
    /// Unlike `create_job_for_user` (which generates its own UUID), this method
    /// accepts an existing `job_id` — used by `execute_sandbox()` which creates
    /// the UUID before the container so it can be shared with Docker labels and
    /// DB persistence.
    ///
    /// The job starts in `InProgress` state since the container is about to be
    /// created. Counts against `max_jobs` like any other job.
    pub async fn register_sandbox_job(
        &self,
        job_id: Uuid,
        user_id: impl Into<String>,
        title: impl Into<String>,
        description: impl Into<String>,
    ) -> Result<(), JobError> {
        let mut context = JobContext::with_user(user_id, title, description);
        context.job_id = job_id;
        context.state = JobState::InProgress;
        context.started_at = Some(chrono::Utc::now());
        self.insert_context(context).await
    }

    /// Check max_jobs limit, insert context, and allocate memory.
    ///
    /// Holds the write lock for the entire check-insert to prevent TOCTOU
    /// races where two concurrent calls both pass the parallel_count check.
    async fn insert_context(&self, context: JobContext) -> Result<(), JobError> {
        let mut contexts = self.contexts.write().await;
        let parallel_count = contexts
            .values()
            .filter(|c| c.state.is_parallel_blocking())
            .count();

        if parallel_count >= self.max_jobs {
            return Err(JobError::MaxJobsExceeded { max: self.max_jobs });
        }

        let job_id = context.job_id;
        contexts.insert(job_id, context);
        drop(contexts);

        self.memories
            .write()
            .await
            .insert(job_id, Memory::new(job_id));

        Ok(())
    }

    /// Get a job context by ID.
    pub async fn get_context(&self, job_id: Uuid) -> Result<JobContext, JobError> {
        self.contexts
            .read()
            .await
            .get(&job_id)
            .cloned()
            .ok_or(JobError::NotFound { id: job_id })
    }

    /// Get a mutable reference to update a job context.
    pub async fn update_context<F, R>(&self, job_id: Uuid, f: F) -> Result<R, JobError>
    where
        F: FnOnce(&mut JobContext) -> R,
    {
        let mut contexts = self.contexts.write().await;
        let context = contexts
            .get_mut(&job_id)
            .ok_or(JobError::NotFound { id: job_id })?;
        Ok(f(context))
    }

    /// Atomically update a job context and return the updated context.
    ///
    /// This method holds the write lock for the entire update-and-read sequence,
    /// preventing concurrent workers from interleaving modifications between the
    /// update and the subsequent read (Issue #807: non-transactional context updates).
    /// Use this when you need to update context and immediately persist it to DB.
    pub async fn update_context_and_get<F>(
        &self,
        job_id: Uuid,
        f: F,
    ) -> Result<JobContext, JobError>
    where
        F: FnOnce(&mut JobContext),
    {
        let mut contexts = self.contexts.write().await;
        let context = contexts
            .get_mut(&job_id)
            .ok_or(JobError::NotFound { id: job_id })?;
        f(context);
        Ok(context.clone())
    }

    /// Get job memory.
    pub async fn get_memory(&self, job_id: Uuid) -> Result<Memory, JobError> {
        self.memories
            .read()
            .await
            .get(&job_id)
            .cloned()
            .ok_or(JobError::NotFound { id: job_id })
    }

    /// Update job memory.
    pub async fn update_memory<F, R>(&self, job_id: Uuid, f: F) -> Result<R, JobError>
    where
        F: FnOnce(&mut Memory) -> R,
    {
        let mut memories = self.memories.write().await;
        let memory = memories
            .get_mut(&job_id)
            .ok_or(JobError::NotFound { id: job_id })?;
        Ok(f(memory))
    }

    /// List all active job IDs.
    pub async fn active_jobs(&self) -> Vec<Uuid> {
        self.contexts
            .read()
            .await
            .iter()
            .filter(|(_, c)| c.state.is_active())
            .map(|(id, _)| *id)
            .collect()
    }

    /// List all job IDs.
    pub async fn all_jobs(&self) -> Vec<Uuid> {
        self.contexts.read().await.keys().cloned().collect()
    }

    /// List all active job IDs for a specific user.
    pub async fn active_jobs_for(&self, user_id: &str) -> Vec<Uuid> {
        self.contexts
            .read()
            .await
            .iter()
            .filter(|(_, c)| c.user_id == user_id && c.state.is_active())
            .map(|(id, _)| *id)
            .collect()
    }

    /// List all job IDs for a specific user.
    pub async fn all_jobs_for(&self, user_id: &str) -> Vec<Uuid> {
        self.contexts
            .read()
            .await
            .iter()
            .filter(|(_, c)| c.user_id == user_id)
            .map(|(id, _)| *id)
            .collect()
    }

    /// Get count of active jobs.
    pub async fn active_count(&self) -> usize {
        self.contexts
            .read()
            .await
            .values()
            .filter(|c| c.state.is_active())
            .count()
    }

    /// Remove a completed job (cleanup).
    pub async fn remove_job(&self, job_id: Uuid) -> Result<(JobContext, Memory), JobError> {
        let context = self
            .contexts
            .write()
            .await
            .remove(&job_id)
            .ok_or(JobError::NotFound { id: job_id })?;

        let memory = self
            .memories
            .write()
            .await
            .remove(&job_id)
            .ok_or(JobError::NotFound { id: job_id })?;

        Ok((context, memory))
    }

    /// Find stuck jobs.
    ///
    /// Returns jobs that are explicitly in `Stuck` state, plus `InProgress`
    /// jobs that have been running longer than `elapsed_threshold` (if provided).
    /// The threshold-based detection catches jobs that never transitioned to
    /// `Stuck` (e.g., due to a deadlock or unhandled timeout).
    pub async fn find_stuck_jobs(&self) -> Vec<Uuid> {
        self.find_stuck_jobs_with_threshold(None).await
    }

    /// Find stuck jobs with an optional elapsed threshold for `InProgress` detection.
    pub async fn find_stuck_jobs_with_threshold(
        &self,
        elapsed_threshold: Option<Duration>,
    ) -> Vec<Uuid> {
        let now = chrono::Utc::now();
        self.contexts
            .read()
            .await
            .iter()
            .filter(|(_, c)| {
                // Always include explicitly Stuck jobs.
                if c.state == crate::context::JobState::Stuck {
                    return true;
                }
                // Detect InProgress jobs that have been running beyond the elapsed threshold.
                // NOTE: `started_at` is set on the first transition to InProgress and is
                // NOT reset when a job recovers from Stuck back to InProgress. This means
                // a recovered job may be re-detected on the next scan. A future improvement
                // could track `in_progress_since` or use the most recent StateTransition
                // with `to == InProgress` to avoid false positives on recovered jobs.
                if c.state == crate::context::JobState::InProgress
                    && let Some(threshold) = elapsed_threshold
                    && let Some(started) = c.started_at
                {
                    let elapsed = now.signed_duration_since(started);
                    let elapsed_secs = elapsed.num_seconds().max(0) as u64;
                    return elapsed_secs > threshold.as_secs();
                }
                false
            })
            .map(|(id, _)| *id)
            .collect()
    }

    /// Get summary of all jobs.
    pub async fn summary(&self) -> ContextSummary {
        let contexts = self.contexts.read().await;

        let mut summary = ContextSummary::default();
        for ctx in contexts.values() {
            match ctx.state {
                crate::context::JobState::Pending => summary.pending += 1,
                crate::context::JobState::InProgress => summary.in_progress += 1,
                crate::context::JobState::Completed => summary.completed += 1,
                crate::context::JobState::Submitted => summary.submitted += 1,
                crate::context::JobState::Accepted => summary.accepted += 1,
                crate::context::JobState::Failed => summary.failed += 1,
                crate::context::JobState::Stuck => summary.stuck += 1,
                crate::context::JobState::Cancelled => summary.cancelled += 1,
            }
        }

        summary.total = contexts.len();
        summary
    }

    /// Get summary of all jobs for a specific user.
    pub async fn summary_for(&self, user_id: &str) -> ContextSummary {
        let contexts = self.contexts.read().await;

        let mut summary = ContextSummary::default();
        for ctx in contexts.values().filter(|c| c.user_id == user_id) {
            match ctx.state {
                crate::context::JobState::Pending => summary.pending += 1,
                crate::context::JobState::InProgress => summary.in_progress += 1,
                crate::context::JobState::Completed => summary.completed += 1,
                crate::context::JobState::Submitted => summary.submitted += 1,
                crate::context::JobState::Accepted => summary.accepted += 1,
                crate::context::JobState::Failed => summary.failed += 1,
                crate::context::JobState::Stuck => summary.stuck += 1,
                crate::context::JobState::Cancelled => summary.cancelled += 1,
            }
        }

        summary.total = summary.pending
            + summary.in_progress
            + summary.completed
            + summary.submitted
            + summary.accepted
            + summary.failed
            + summary.stuck
            + summary.cancelled;
        summary
    }
}

impl Default for ContextManager {
    fn default() -> Self {
        Self::new(10)
    }
}

/// Summary of all job contexts.
#[derive(Debug, Default)]
pub struct ContextSummary {
    pub total: usize,
    pub pending: usize,
    pub in_progress: usize,
    pub completed: usize,
    pub submitted: usize,
    pub accepted: usize,
    pub failed: usize,
    pub stuck: usize,
    pub cancelled: usize,
}

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

    #[tokio::test]
    async fn test_create_job() {
        let manager = ContextManager::new(5);
        let job_id = manager.create_job("Test", "Description").await.unwrap();

        let context = manager.get_context(job_id).await.unwrap();
        assert_eq!(context.title, "Test");
    }

    #[tokio::test]
    async fn test_create_job_for_user_sets_user_id() {
        let manager = ContextManager::new(5);
        let job_id = manager
            .create_job_for_user("user-123", "Test", "Description")
            .await
            .unwrap();

        let context = manager.get_context(job_id).await.unwrap();
        assert_eq!(context.user_id, "user-123");
    }

    #[tokio::test]
    async fn test_max_jobs_limit() {
        let manager = ContextManager::new(2);

        manager.create_job("Job 1", "Desc").await.unwrap();
        manager.create_job("Job 2", "Desc").await.unwrap();

        // Start the jobs to make them active
        for job_id in manager.all_jobs().await {
            manager
                .update_context(job_id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }

        // Third job should fail
        let result = manager.create_job("Job 3", "Desc").await;
        assert!(matches!(result, Err(JobError::MaxJobsExceeded { max: 2 })));
    }

    #[tokio::test]
    async fn test_update_context() {
        let manager = ContextManager::new(5);
        let job_id = manager.create_job("Test", "Desc").await.unwrap();

        manager
            .update_context(job_id, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();

        let context = manager.get_context(job_id).await.unwrap();
        assert_eq!(context.state, crate::context::JobState::InProgress);
    }

    // === QA Plan P3 - 4.2: Concurrent job stress tests ===

    #[tokio::test]
    async fn concurrent_creates_produce_unique_ids() {
        let manager = std::sync::Arc::new(ContextManager::new(100));

        let handles: Vec<_> = (0..50)
            .map(|i| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move {
                    mgr.create_job(format!("Job {i}"), format!("Desc {i}"))
                        .await
                })
            })
            .collect();

        let mut ids = std::collections::HashSet::new();
        for handle in handles {
            let result = handle.await.expect("task should not panic");
            let job_id = result.expect("create_job should succeed");
            assert!(ids.insert(job_id), "Duplicate job ID: {job_id}");
        }

        assert_eq!(ids.len(), 50);
        assert_eq!(manager.all_jobs().await.len(), 50);
    }

    #[tokio::test]
    async fn concurrent_creates_respect_max_jobs_limit() {
        // max_jobs = 5, but create_job only counts *active* jobs (InProgress).
        // Pending jobs don't count against the limit, so we need to transition them.
        let manager = std::sync::Arc::new(ContextManager::new(5));

        // First, create 5 jobs and make them active.
        for i in 0..5 {
            let id = manager
                .create_job(format!("Job {i}"), "desc")
                .await
                .unwrap();
            manager
                .update_context(id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }

        // Now try to create 10 more concurrently -- all should fail.
        let handles: Vec<_> = (0..10)
            .map(|i| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move { mgr.create_job(format!("Overflow {i}"), "desc").await })
            })
            .collect();

        for handle in handles {
            let result = handle.await.expect("task should not panic");
            assert!(
                matches!(result, Err(JobError::MaxJobsExceeded { .. })),
                "Expected MaxJobsExceeded, got: {:?}",
                result
            );
        }

        // Still exactly 5 jobs.
        assert_eq!(manager.all_jobs().await.len(), 5);
    }

    #[tokio::test]
    async fn concurrent_creates_and_reads_no_corruption() {
        let manager = std::sync::Arc::new(ContextManager::new(100));

        // Spawn writers that create jobs.
        let writer_handles: Vec<_> = (0..20)
            .map(|i| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move {
                    mgr.create_job_for_user(
                        format!("user-{}", i % 5),
                        format!("Job {i}"),
                        format!("Description for job {i}"),
                    )
                    .await
                })
            })
            .collect();

        // Concurrently, spawn readers that list jobs.
        let reader_handles: Vec<_> = (0..20)
            .map(|_| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move {
                    let _all = mgr.all_jobs().await;
                    let _active = mgr.active_jobs().await;
                    let _summary = mgr.summary().await;
                })
            })
            .collect();

        // Wait for all writers.
        let mut ids = Vec::new();
        for handle in writer_handles {
            let result = handle.await.expect("writer should not panic");
            ids.push(result.expect("create should succeed"));
        }

        // Wait for all readers.
        for handle in reader_handles {
            handle.await.expect("reader should not panic");
        }

        // All 20 jobs created with unique IDs.
        let unique: std::collections::HashSet<_> = ids.iter().collect();
        assert_eq!(unique.len(), 20);

        // Each user has 4 jobs (20 jobs / 5 users).
        for u in 0..5 {
            let user_jobs = manager.all_jobs_for(&format!("user-{u}")).await;
            assert_eq!(user_jobs.len(), 4, "user-{u} should have 4 jobs");
        }
    }

    #[tokio::test]
    async fn concurrent_updates_do_not_lose_state() {
        let manager = std::sync::Arc::new(ContextManager::new(100));

        // Create 10 jobs.
        let mut job_ids = Vec::new();
        for i in 0..10 {
            let id = manager
                .create_job(format!("Job {i}"), "desc")
                .await
                .unwrap();
            job_ids.push(id);
        }

        // Concurrently transition all to InProgress.
        let handles: Vec<_> = job_ids
            .iter()
            .map(|&id| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move {
                    mgr.update_context(id, |ctx| {
                        ctx.transition_to(crate::context::JobState::InProgress, None)
                    })
                    .await
                })
            })
            .collect();

        for handle in handles {
            let result = handle.await.expect("task should not panic");
            result
                .expect("update should succeed")
                .expect("transition should succeed");
        }

        // All 10 should now be InProgress.
        let active = manager.active_jobs().await;
        assert_eq!(active.len(), 10);
        for id in &job_ids {
            let ctx = manager.get_context(*id).await.unwrap();
            assert_eq!(ctx.state, crate::context::JobState::InProgress);
        }
    }

    #[tokio::test]
    async fn get_context_not_found() {
        let manager = ContextManager::new(5);
        let bogus_id = Uuid::new_v4();
        let result = manager.get_context(bogus_id).await;
        assert!(matches!(result, Err(JobError::NotFound { id }) if id == bogus_id));
    }

    #[tokio::test]
    async fn update_context_not_found() {
        let manager = ContextManager::new(5);
        let bogus_id = Uuid::new_v4();
        let result = manager.update_context(bogus_id, |_ctx| {}).await;
        assert!(matches!(result, Err(JobError::NotFound { id }) if id == bogus_id));
    }

    #[tokio::test]
    async fn remove_job_returns_context_and_memory() {
        let manager = ContextManager::new(5);
        let job_id = manager.create_job("Removable", "bye bye").await.unwrap();

        let (ctx, mem) = manager.remove_job(job_id).await.unwrap();
        assert_eq!(ctx.title, "Removable");
        assert_eq!(mem.job_id, job_id);

        // After removal, get should fail
        assert!(matches!(
            manager.get_context(job_id).await,
            Err(JobError::NotFound { .. })
        ));
        assert!(matches!(
            manager.get_memory(job_id).await,
            Err(JobError::NotFound { .. })
        ));
    }

    #[tokio::test]
    async fn remove_job_not_found() {
        let manager = ContextManager::new(5);
        let result = manager.remove_job(Uuid::new_v4()).await;
        assert!(matches!(result, Err(JobError::NotFound { .. })));
    }

    #[tokio::test]
    async fn get_memory_and_update_memory() {
        let manager = ContextManager::new(5);
        let job_id = manager.create_job("Mem test", "desc").await.unwrap();

        // Fresh memory should be empty
        let mem = manager.get_memory(job_id).await.unwrap();
        assert_eq!(mem.job_id, job_id);
        assert!(mem.actions.is_empty());
        assert!(mem.conversation.is_empty());

        // Update memory by adding a message
        manager
            .update_memory(job_id, |m| {
                m.add_message(crate::llm::ChatMessage::user("hello from test"));
            })
            .await
            .unwrap();

        let mem = manager.get_memory(job_id).await.unwrap();
        assert_eq!(mem.conversation.len(), 1);
        assert_eq!(mem.conversation.messages()[0].content, "hello from test");
    }

    #[tokio::test]
    async fn update_memory_not_found() {
        let manager = ContextManager::new(5);
        let result = manager.update_memory(Uuid::new_v4(), |_| {}).await;
        assert!(matches!(result, Err(JobError::NotFound { .. })));
    }

    #[tokio::test]
    async fn get_memory_not_found() {
        let manager = ContextManager::new(5);
        let result = manager.get_memory(Uuid::new_v4()).await;
        assert!(matches!(result, Err(JobError::NotFound { .. })));
    }

    #[tokio::test]
    async fn find_stuck_jobs_returns_only_stuck() {
        let manager = ContextManager::new(10);

        let id1 = manager.create_job("Job 1", "desc").await.unwrap();
        let id2 = manager.create_job("Job 2", "desc").await.unwrap();
        let id3 = manager.create_job("Job 3", "desc").await.unwrap();

        // Transition id1 and id2 to InProgress, then mark id2 as stuck
        for id in [id1, id2, id3] {
            manager
                .update_context(id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }
        manager
            .update_context(id2, |ctx| ctx.mark_stuck("timed out"))
            .await
            .unwrap()
            .unwrap();

        let stuck = manager.find_stuck_jobs().await;
        assert_eq!(stuck.len(), 1);
        assert_eq!(stuck[0], id2);
    }

    /// Regression test for #1223: InProgress jobs exceeding the threshold
    /// should be detected as stuck even if they never transitioned to Stuck.
    #[tokio::test]
    async fn find_stuck_jobs_with_threshold_detects_idle_in_progress() {
        let manager = ContextManager::new(10);

        let id1 = manager.create_job("Active job", "desc").await.unwrap();
        let id2 = manager.create_job("Idle job", "desc").await.unwrap();

        // Both transition to InProgress
        for id in [id1, id2] {
            manager
                .update_context(id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }

        // Backdate id2's started_at to simulate a long-running job
        manager
            .update_context(id2, |ctx| -> Result<(), crate::error::JobError> {
                ctx.started_at = Some(chrono::Utc::now() - chrono::Duration::seconds(600));
                Ok(())
            })
            .await
            .unwrap()
            .unwrap();

        // With a 5-minute threshold, only id2 (10 min) should be detected
        let stuck = manager
            .find_stuck_jobs_with_threshold(Some(Duration::from_secs(300)))
            .await;
        assert_eq!(stuck.len(), 1);
        assert_eq!(stuck[0], id2);

        // Without threshold, neither InProgress job is detected (no explicit Stuck state)
        let stuck_no_threshold = manager.find_stuck_jobs().await;
        assert!(stuck_no_threshold.is_empty());
    }

    #[tokio::test]
    async fn active_count_tracks_non_terminal_jobs() {
        let manager = ContextManager::new(10);

        let id1 = manager.create_job("J1", "d").await.unwrap();
        let id2 = manager.create_job("J2", "d").await.unwrap();

        // Both pending (active)
        assert_eq!(manager.active_count().await, 2);

        // Transition id1 through to Failed (terminal)
        manager
            .update_context(id1, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();
        manager
            .update_context(id1, |ctx| {
                ctx.transition_to(crate::context::JobState::Failed, None)
            })
            .await
            .unwrap()
            .unwrap();

        // id1 is terminal, id2 still pending
        assert_eq!(manager.active_count().await, 1);

        // Transition id2 to cancelled
        manager
            .update_context(id2, |ctx| {
                ctx.transition_to(crate::context::JobState::Cancelled, None)
            })
            .await
            .unwrap()
            .unwrap();

        assert_eq!(manager.active_count().await, 0);
    }

    #[tokio::test]
    async fn active_jobs_for_filters_by_user() {
        let manager = ContextManager::new(10);

        manager
            .create_job_for_user("alice", "A1", "d")
            .await
            .unwrap();
        manager
            .create_job_for_user("alice", "A2", "d")
            .await
            .unwrap();
        let bob_id = manager.create_job_for_user("bob", "B1", "d").await.unwrap();

        assert_eq!(manager.active_jobs_for("alice").await.len(), 2);
        assert_eq!(manager.active_jobs_for("bob").await.len(), 1);
        assert_eq!(manager.active_jobs_for("nobody").await.len(), 0);

        // Make bob's job terminal
        manager
            .update_context(bob_id, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();
        manager
            .update_context(bob_id, |ctx| {
                ctx.transition_to(crate::context::JobState::Failed, None)
            })
            .await
            .unwrap()
            .unwrap();

        assert_eq!(manager.active_jobs_for("bob").await.len(), 0);
        // But all_jobs_for still shows it
        assert_eq!(manager.all_jobs_for("bob").await.len(), 1);
    }

    #[tokio::test]
    async fn summary_counts_states_correctly() {
        let manager = ContextManager::new(10);

        let id1 = manager.create_job("J1", "d").await.unwrap();
        let id2 = manager.create_job("J2", "d").await.unwrap();
        let id3 = manager.create_job("J3", "d").await.unwrap();

        // id1: Pending -> InProgress -> Completed
        manager
            .update_context(id1, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();
        manager
            .update_context(id1, |ctx| {
                ctx.transition_to(crate::context::JobState::Completed, None)
            })
            .await
            .unwrap()
            .unwrap();

        // id2: Pending -> InProgress -> Failed
        manager
            .update_context(id2, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();
        manager
            .update_context(id2, |ctx| {
                ctx.transition_to(crate::context::JobState::Failed, None)
            })
            .await
            .unwrap()
            .unwrap();

        // id3: stays Pending

        let s = manager.summary().await;
        assert_eq!(s.total, 3);
        assert_eq!(s.pending, 1);
        assert_eq!(s.completed, 1);
        assert_eq!(s.failed, 1);
        assert_eq!(s.in_progress, 0);
        assert_eq!(s.stuck, 0);
        assert_eq!(s.cancelled, 0);
        assert_eq!(s.submitted, 0);
        assert_eq!(s.accepted, 0);

        // Suppress unused field warning
        let _ = id3;
    }

    #[tokio::test]
    async fn summary_for_scopes_to_user() {
        let manager = ContextManager::new(10);

        manager
            .create_job_for_user("alice", "A1", "d")
            .await
            .unwrap();
        let bob_id = manager.create_job_for_user("bob", "B1", "d").await.unwrap();

        // Transition bob's job to InProgress
        manager
            .update_context(bob_id, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();

        let alice_summary = manager.summary_for("alice").await;
        assert_eq!(alice_summary.total, 1);
        assert_eq!(alice_summary.pending, 1);
        assert_eq!(alice_summary.in_progress, 0);

        let bob_summary = manager.summary_for("bob").await;
        assert_eq!(bob_summary.total, 1);
        assert_eq!(bob_summary.pending, 0);
        assert_eq!(bob_summary.in_progress, 1);

        let nobody_summary = manager.summary_for("nobody").await;
        assert_eq!(nobody_summary.total, 0);
    }

    #[tokio::test]
    async fn default_context_manager_has_max_10() {
        let manager = ContextManager::default();
        // Create 10 jobs and make them active
        for i in 0..10 {
            let id = manager
                .create_job(format!("Job {i}"), "desc")
                .await
                .unwrap();
            manager
                .update_context(id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }
        // 11th should fail
        let result = manager.create_job("overflow", "d").await;
        assert!(matches!(result, Err(JobError::MaxJobsExceeded { max: 10 })));
    }

    #[tokio::test]
    async fn all_jobs_returns_all_regardless_of_state() {
        let manager = ContextManager::new(10);

        let id1 = manager.create_job("J1", "d").await.unwrap();
        manager.create_job("J2", "d").await.unwrap();

        // Make id1 terminal
        manager
            .update_context(id1, |ctx| {
                ctx.transition_to(crate::context::JobState::InProgress, None)
            })
            .await
            .unwrap()
            .unwrap();
        manager
            .update_context(id1, |ctx| {
                ctx.transition_to(crate::context::JobState::Failed, None)
            })
            .await
            .unwrap()
            .unwrap();

        // all_jobs includes terminal, active_jobs does not
        assert_eq!(manager.all_jobs().await.len(), 2);
        assert_eq!(manager.active_jobs().await.len(), 1);
    }

    #[tokio::test]
    async fn create_job_uses_default_user() {
        let manager = ContextManager::new(5);
        let job_id = manager.create_job("Test", "desc").await.unwrap();
        let ctx = manager.get_context(job_id).await.unwrap();
        assert_eq!(ctx.user_id, "default");
    }

    #[tokio::test]
    async fn concurrent_remove_and_read() {
        let manager = std::sync::Arc::new(ContextManager::new(100));

        // Create 20 jobs
        let mut job_ids = Vec::new();
        for i in 0..20 {
            let id = manager
                .create_job(format!("Job {i}"), "desc")
                .await
                .unwrap();
            job_ids.push(id);
        }

        // Concurrently remove the first 10 while reading the last 10
        let remove_handles: Vec<_> = job_ids[..10]
            .iter()
            .map(|&id| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move { mgr.remove_job(id).await })
            })
            .collect();

        let read_handles: Vec<_> = job_ids[10..]
            .iter()
            .map(|&id| {
                let mgr = std::sync::Arc::clone(&manager);
                tokio::spawn(async move { mgr.get_context(id).await })
            })
            .collect();

        for handle in remove_handles {
            handle
                .await
                .expect("remove task should not panic")
                .expect("remove should succeed");
        }

        for handle in read_handles {
            let ctx = handle
                .await
                .expect("read task should not panic")
                .expect("read should succeed");
            assert!(job_ids[10..].contains(&ctx.job_id));
        }

        assert_eq!(manager.all_jobs().await.len(), 10);
    }

    #[tokio::test]
    async fn update_context_and_get_atomicity_regression_issue_807() {
        // Regression test for Issue #807: non-transactional context updates.
        // Verify that update_context_and_get returns the exact state that was set,
        // without allowing concurrent workers to interleave modifications.
        let manager = std::sync::Arc::new(ContextManager::new(100));
        let job_id = manager
            .create_job("Atomicity Test", "verify no race condition")
            .await
            .unwrap(); // safety: test code

        // Update and get atomically, setting metadata
        let metadata = serde_json::json!({ "priority": "high", "user_id": 42 });
        let returned_ctx = manager
            .update_context_and_get(job_id, |ctx| {
                ctx.metadata = metadata.clone();
                ctx.max_tokens = 5000;
            })
            .await
            .unwrap(); // safety: test code

        // Verify the returned context has the exact updates we set
        assert_eq!(returned_ctx.metadata, metadata); // safety: test code
        assert_eq!(returned_ctx.max_tokens, 5000); // safety: test code

        // Verify a fresh get returns the same state
        let fresh_ctx = manager.get_context(job_id).await.unwrap(); // safety: test code
        assert_eq!(fresh_ctx.metadata, metadata); // safety: test code
        assert_eq!(fresh_ctx.max_tokens, 5000); // safety: test code
    }

    #[tokio::test]
    async fn update_context_and_get_no_concurrent_interleave() {
        // Verify that concurrent updates cannot interleave during update_context_and_get.
        // If the lock were released too early, a concurrent state transition could
        // get mixed into the returned context.
        let manager = std::sync::Arc::new(ContextManager::new(100));
        let job_id = manager
            .create_job("Concurrent Race Test", "ensure atomicity")
            .await
            .unwrap(); // safety: test code

        let metadata = serde_json::json!({ "test": "race_condition" });
        let metadata_clone = metadata.clone();

        // Spawn a task that will update_context_and_get
        let mgr1 = std::sync::Arc::clone(&manager);
        let returned_ctx_handle = tokio::spawn(async move {
            mgr1.update_context_and_get(job_id, |ctx| {
                ctx.metadata = metadata_clone;
                ctx.max_tokens = 3000;
            })
            .await
        });

        // The returned context should have *only* the metadata update, not any
        // concurrent state transitions that might happen during the operation.
        let returned_ctx = returned_ctx_handle.await.unwrap().unwrap(); // safety: test code

        // Verify atomicity: returned context has the metadata we set
        assert_eq!(returned_ctx.metadata, metadata); // safety: test code
        assert_eq!(returned_ctx.max_tokens, 3000); // safety: test code
        // And it's in the initial state (Pending), not modified by concurrent workers
        assert_eq!(returned_ctx.state, crate::context::JobState::Pending); // safety: test code
    }

    #[tokio::test]
    async fn sequential_routines_unlimited_completed_not_counted() {
        // TEST: Sequential (non-parallel) routines should NOT be limited by max_jobs.
        //
        // Completed/Submitted jobs should NOT count toward the parallel job limit,
        // since they're no longer actively consuming execution resources.
        //
        // Scenario: Create 10 sequential routines, each completing before the next starts.
        // Currently FAILS because Completed jobs still count as "active".
        // After fix, should PASS because only Pending/InProgress/Stuck count.

        let manager = ContextManager::new(5); // max 5 truly parallel jobs

        // Try to create and complete 10 sequential routines
        for i in 0..10 {
            let result = manager
                .create_job(format!("Sequential Routine {}", i), "one at a time")
                .await;

            match result {
                Ok(job_id) => {
                    // Simulate execution: Pending -> InProgress -> Completed
                    manager
                        .update_context(job_id, |ctx| {
                            ctx.transition_to(crate::context::JobState::InProgress, None)
                        })
                        .await
                        .unwrap()
                        .unwrap();

                    manager
                        .update_context(job_id, |ctx| {
                            ctx.transition_to(crate::context::JobState::Completed, None)
                        })
                        .await
                        .unwrap()
                        .unwrap();

                    println!("✓ Routine {} created and completed", i);
                }
                Err(JobError::MaxJobsExceeded { max }) => {
                    panic!(
                        "✗ Routine {} FAILED to create: MaxJobsExceeded (max={}).\n\
                         This shows the bug: Completed jobs from routines 0-4 are still counting \
                         toward the limit even though they're not running.\n\
                         After the fix, this test should pass because Completed jobs won't count.",
                        i, max
                    );
                }
                Err(e) => {
                    panic!("Unexpected error for routine {}: {:?}", i, e);
                }
            }
        }

        // If we reach here, all 10 routines succeeded (bug is fixed)
        assert_eq!(manager.all_jobs().await.len(), 10);
        println!("✓ SUCCESS: All 10 sequential routines created despite max_jobs=5 limit");
        println!("  This is correct: Completed jobs don't count toward parallel limit");
    }

    #[tokio::test]
    async fn parallel_jobs_limit_enforced_for_active_jobs() {
        // TEST: Parallel (simultaneous) jobs ARE limited by max_jobs.
        //
        // Jobs in Pending/InProgress/Stuck states consume execution slots.
        // The 6th truly-active job should fail because the limit is 5.
        //
        // This test verifies the limit DOES work correctly for parallel execution.

        let manager = ContextManager::new(5); // max 5 parallel jobs

        // Create 5 jobs and make them InProgress (simulating parallel execution)
        let mut job_ids = Vec::new();
        for i in 0..5 {
            let job_id = manager
                .create_job(format!("Parallel Job {}", i), "running in parallel")
                .await
                .expect("First 5 jobs should create successfully");
            job_ids.push(job_id);

            // Transition to InProgress (simulating active execution)
            manager
                .update_context(job_id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }

        // Verify all 5 jobs are InProgress
        for job_id in &job_ids {
            let ctx = manager.get_context(*job_id).await.unwrap();
            assert_eq!(
                ctx.state,
                crate::context::JobState::InProgress,
                "All jobs should be InProgress"
            );
        }

        // Check active count - should be 5 (all InProgress)
        let active_count = manager.active_count().await;
        assert_eq!(
            active_count, 5,
            "Active count should be 5 (all InProgress jobs count)"
        );

        // Try to create a 6th job - should FAIL because limit is reached
        let result = manager.create_job("Parallel Job 6", "sixth job").await;

        match result {
            Err(JobError::MaxJobsExceeded { max: 5 }) => {
                println!("✓ SUCCESS: Parallel job limit correctly enforced at 5 active jobs");
                println!("✓ 6th InProgress job correctly blocked when 5 are already running");
            }
            Ok(_) => {
                panic!(
                    "FAILED: 6th parallel job should have been blocked \
                     but was created. Limit enforcement is broken."
                );
            }
            Err(e) => {
                panic!(
                    "UNEXPECTED ERROR: Expected MaxJobsExceeded but got: {:?}",
                    e
                );
            }
        }
    }

    #[tokio::test]
    async fn completed_jobs_should_free_slots_after_fix() {
        // TEST: After the fix, Completed jobs should NOT count toward the limit.
        //
        // This test demonstrates that when a job transitions from InProgress -> Completed,
        // it should free up a slot in the parallel execution limit.
        //
        // Currently FAILS (bug not fixed), proving Completed jobs incorrectly stay in the limit.
        // After fix, this will PASS (Completed jobs freed their slot).

        let manager = ContextManager::new(5); // max 5 parallel jobs

        // Create 5 InProgress jobs (fill the limit)
        let mut job_ids = Vec::new();
        for i in 0..5 {
            let job_id = manager
                .create_job(format!("Job {}", i), "parallel")
                .await
                .unwrap();
            job_ids.push(job_id);

            manager
                .update_context(job_id, |ctx| {
                    ctx.transition_to(crate::context::JobState::InProgress, None)
                })
                .await
                .unwrap()
                .unwrap();
        }

        // Verify limit is hit
        let result = manager.create_job("Job 5", "should fail").await;
        assert!(
            matches!(result, Err(JobError::MaxJobsExceeded { max: 5 })),
            "Limit should be hit with 5 InProgress jobs"
        );
        println!("✓ Limit enforced: 5 InProgress jobs block 6th creation");

        // Now transition job 0 from InProgress -> Completed
        manager
            .update_context(job_ids[0], |ctx| {
                ctx.transition_to(crate::context::JobState::Completed, None)
            })
            .await
            .unwrap()
            .unwrap();

        println!("✓ Job 0 transitioned: InProgress -> Completed");

        // Try to create a 6th job - this will FAIL until the bug is fixed
        let result = manager
            .create_job("Job 5 (retry)", "after 1 Completed")
            .await;

        match result {
            Ok(job_6) => {
                println!("✓ SUCCESS: 6th job created after job 0 completed");
                println!("✓ This proves Completed jobs don't count toward the limit (BUG FIXED)");

                // Verify we can transition it to InProgress
                manager
                    .update_context(job_6, |ctx| {
                        ctx.transition_to(crate::context::JobState::InProgress, None)
                    })
                    .await
                    .unwrap()
                    .unwrap();
                println!("✓ 6th job now InProgress: 4 remaining + 1 new = 5 limit reached");
            }
            Err(JobError::MaxJobsExceeded { max: 5 }) => {
                panic!(
                    "✗ BUG NOT FIXED: 6th job creation still blocked after freeing slot.\n\
                     State: 1 Completed (job 0) + 4 InProgress (jobs 1-4) = 5 active\n\
                     BUG: Completed job 0 still counts toward limit\n\
                     EXPECTED: Only 4 InProgress count, 1 slot free"
                );
            }
            Err(e) => {
                panic!("Unexpected error: {:?}", e);
            }
        }
    }

    // === Regression: sandbox jobs must be visible to query tools ===
    // Before the fix, execute_sandbox() only persisted to DB but never
    // registered in ContextManager, making sandbox jobs invisible to
    // list_jobs, job_status, job_events, and resolve_job_id.

    #[tokio::test]
    async fn register_sandbox_job_visible_to_queries() {
        let manager = ContextManager::new(5);
        let job_id = Uuid::new_v4();

        manager
            .register_sandbox_job(
                job_id,
                "user-42",
                "Run tests",
                "Execute test suite in sandbox",
            )
            .await
            .unwrap();

        // Job should be retrievable by ID (used by job_status, job_events)
        let ctx = manager.get_context(job_id).await.unwrap();
        assert_eq!(ctx.job_id, job_id);
        assert_eq!(ctx.user_id, "user-42");
        assert_eq!(ctx.title, "Run tests");
        assert_eq!(ctx.state, JobState::InProgress);
        assert!(ctx.started_at.is_some());

        // Job should appear in all_jobs (used by resolve_job_id prefix matching)
        let all = manager.all_jobs().await;
        assert!(all.contains(&job_id));

        // Job should appear in user-scoped listing (used by list_jobs)
        let user_jobs = manager.all_jobs_for("user-42").await;
        assert!(user_jobs.contains(&job_id));

        // Job should appear in active jobs listing
        let active = manager.active_jobs_for("user-42").await;
        assert!(active.contains(&job_id));
    }

    #[tokio::test]
    async fn register_sandbox_job_respects_max_jobs() {
        let manager = ContextManager::new(2);

        // Fill up the slots with sandbox jobs
        manager
            .register_sandbox_job(Uuid::new_v4(), "user-1", "Job 1", "desc")
            .await
            .unwrap();
        manager
            .register_sandbox_job(Uuid::new_v4(), "user-1", "Job 2", "desc")
            .await
            .unwrap();

        // Third should fail
        let result = manager
            .register_sandbox_job(Uuid::new_v4(), "user-1", "Job 3", "desc")
            .await;
        assert!(matches!(result, Err(JobError::MaxJobsExceeded { max: 2 })));
    }

    #[tokio::test]
    async fn register_sandbox_job_transitions_correctly() {
        let manager = ContextManager::new(5);
        let job_id = Uuid::new_v4();

        manager
            .register_sandbox_job(job_id, "user-1", "Task", "desc")
            .await
            .unwrap();

        // Should be able to transition InProgress -> Completed
        manager
            .update_context(job_id, |ctx| ctx.transition_to(JobState::Completed, None))
            .await
            .unwrap()
            .unwrap();

        let ctx = manager.get_context(job_id).await.unwrap();
        assert_eq!(ctx.state, JobState::Completed);
    }
}