tuitbot-core 0.1.47

Core library for Tuitbot autonomous X growth assistant
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
//! Task 3.5 — content_loop comprehensive tests: safety guardrails + publisher.
//!
//! Covers:
//!  - Safety guardrail enforcement (daily tweet cap, thread cap)
//!  - publisher: try_post_scheduled happy path and dry-run
//!  - Dry-run vs live posting semantics
//!  - Single topic, no topics
//!  - Posted result captures correct topic and content

#[cfg(test)]
mod tests {
    use super::super::test_mocks::{make_topics, MockGenerator, MockSafety, MockStorage};
    use super::super::{ContentLoop, ContentResult};
    use crate::automation::loop_helpers::{ContentLoopError, ContentStorage};
    use std::sync::Arc;
    use std::sync::Mutex;

    // -------------------------------------------------------------------------
    // Safety guardrail: daily tweet limit (6/day)
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn safety_blocks_tweet_when_can_tweet_false() {
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet content".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: false,
                can_thread: true,
            }),
            Arc::new(MockStorage::new(None)),
            make_topics(),
            0,
            false,
        );
        let result = content.run_once(Some("Rust")).await;
        assert!(
            matches!(result, ContentResult::RateLimited),
            "expected RateLimited when can_tweet=false, got {result:?}"
        );
    }

    #[tokio::test]
    async fn safety_allows_tweet_when_thread_blocked() {
        // Thread blocked but tweet allowed — tweet path should succeed.
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet about Rust".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: false,
            }),
            Arc::new(MockStorage::new(None)),
            make_topics(),
            0,
            false,
        );
        let result = content.run_once(Some("Rust")).await;
        assert!(
            matches!(result, ContentResult::Posted { .. }),
            "tweet should post even when thread is rate-limited"
        );
    }

    #[tokio::test]
    async fn safety_blocks_when_both_limits_hit() {
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: false,
                can_thread: false,
            }),
            Arc::new(MockStorage::new(None)),
            make_topics(),
            0,
            false,
        );
        let result = content.run_once(None).await;
        assert!(matches!(result, ContentResult::RateLimited));
    }

    // -------------------------------------------------------------------------
    // Safety guardrail: no topics configured
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn no_topics_returns_no_topics_regardless_of_safety() {
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            Arc::new(MockStorage::new(None)),
            Vec::new(),
            0,
            false,
        );
        let result = content.run_once(None).await;
        assert!(matches!(result, ContentResult::NoTopics));
    }

    #[tokio::test]
    async fn single_topic_gets_used() {
        let storage = Arc::new(MockStorage::new(None));
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet about single topic".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            vec!["only_topic".to_string()],
            0,
            false,
        );
        let result = content.run_once(Some("only_topic")).await;
        assert!(matches!(result, ContentResult::Posted { .. }));
        assert_eq!(storage.posted_count(), 1);
    }

    // -------------------------------------------------------------------------
    // Dry-run semantics
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn dry_run_logs_action_but_does_not_write_tweet() {
        let storage = Arc::new(MockStorage::new(None));
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "dry run tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            0,
            true,
        );
        let result = content.run_once(Some("Rust")).await;
        assert!(matches!(result, ContentResult::Posted { .. }));
        assert_eq!(storage.posted_count(), 0, "dry-run must not persist tweets");
        assert_eq!(storage.action_count(), 1, "dry-run must log action");
    }

    #[tokio::test]
    async fn live_run_writes_tweet_and_logs_action() {
        let storage = Arc::new(MockStorage::new(None));
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "live tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            0,
            false,
        );
        let result = content.run_once(Some("Rust")).await;
        assert!(matches!(result, ContentResult::Posted { .. }));
        assert_eq!(storage.posted_count(), 1, "live run must persist tweet");
        assert_eq!(storage.action_count(), 1, "live run must log action");
    }

    // -------------------------------------------------------------------------
    // Publisher: try_post_scheduled
    // -------------------------------------------------------------------------

    struct ScheduledMockStorage {
        pub scheduled: Mutex<Option<(i64, String, String)>>,
        pub posted_scheduled: Mutex<Vec<(String, String)>>,
        pub marked_posted: Mutex<Vec<i64>>,
        pub actions: Mutex<Vec<(String, String, String)>>,
    }

    impl ScheduledMockStorage {
        fn with_item(id: i64, content_type: &str, content: &str) -> Arc<Self> {
            Arc::new(Self {
                scheduled: Mutex::new(Some((id, content_type.to_string(), content.to_string()))),
                posted_scheduled: Mutex::new(Vec::new()),
                marked_posted: Mutex::new(Vec::new()),
                actions: Mutex::new(Vec::new()),
            })
        }

        fn empty() -> Arc<Self> {
            Arc::new(Self {
                scheduled: Mutex::new(None),
                posted_scheduled: Mutex::new(Vec::new()),
                marked_posted: Mutex::new(Vec::new()),
                actions: Mutex::new(Vec::new()),
            })
        }
    }

    #[async_trait::async_trait]
    impl ContentStorage for ScheduledMockStorage {
        async fn last_tweet_time(
            &self,
        ) -> Result<Option<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(None)
        }
        async fn last_thread_time(
            &self,
        ) -> Result<Option<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(None)
        }
        async fn todays_tweet_times(
            &self,
        ) -> Result<Vec<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(Vec::new())
        }
        async fn post_tweet(&self, topic: &str, content: &str) -> Result<(), ContentLoopError> {
            self.posted_scheduled
                .lock()
                .expect("lock")
                .push((topic.to_string(), content.to_string()));
            Ok(())
        }
        async fn create_thread(&self, _t: &str, _c: usize) -> Result<String, ContentLoopError> {
            Ok("t1".to_string())
        }
        async fn update_thread_status(
            &self,
            _id: &str,
            _s: &str,
            _c: usize,
            _r: Option<&str>,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn store_thread_tweet(
            &self,
            _id: &str,
            _pos: usize,
            _tid: &str,
            _c: &str,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn log_action(&self, a: &str, s: &str, m: &str) -> Result<(), ContentLoopError> {
            self.actions
                .lock()
                .expect("lock")
                .push((a.to_string(), s.to_string(), m.to_string()));
            Ok(())
        }
        async fn next_scheduled_item(
            &self,
        ) -> Result<Option<(i64, String, String)>, ContentLoopError> {
            Ok(self.scheduled.lock().expect("lock").clone())
        }
        async fn mark_scheduled_posted(
            &self,
            id: i64,
            _tid: Option<&str>,
        ) -> Result<(), ContentLoopError> {
            self.marked_posted.lock().expect("lock").push(id);
            Ok(())
        }
    }

    #[tokio::test]
    async fn try_post_scheduled_returns_none_when_queue_empty() {
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            ScheduledMockStorage::empty(),
            make_topics(),
            0,
            false,
        );
        let result = content.try_post_scheduled().await;
        assert!(result.is_none(), "empty queue → None");
    }

    #[tokio::test]
    async fn try_post_scheduled_posts_tweet_type() {
        let storage = ScheduledMockStorage::with_item(42, "tweet", "Scheduled tweet content");
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            0,
            false,
        );
        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        assert!(matches!(result.unwrap(), ContentResult::Posted { .. }));
        let posts = storage.posted_scheduled.lock().expect("lock");
        assert_eq!(posts.len(), 1);
        assert_eq!(posts[0].1, "Scheduled tweet content");
    }

    #[tokio::test]
    async fn try_post_scheduled_dry_run_does_not_post() {
        let storage = ScheduledMockStorage::with_item(7, "tweet", "Dry scheduled tweet");
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            0,
            true,
        );
        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        let posts = storage.posted_scheduled.lock().expect("lock");
        assert_eq!(posts.len(), 0, "dry-run must not post scheduled tweet");
    }

    // -------------------------------------------------------------------------
    // Publisher: scheduled thread posting
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn try_post_scheduled_thread_posts_via_thread_poster() {
        use crate::automation::thread_loop::test_mocks::MockPoster;
        let tweets = serde_json::to_string(&vec!["Tweet 1", "Tweet 2", "Tweet 3"]).unwrap();
        let storage = ScheduledMockStorage::with_item(99, "thread", &tweets);
        let poster = Arc::new(MockPoster::new());

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            0,
            false,
        )
        .with_thread_poster(poster.clone());

        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        assert!(matches!(result.unwrap(), ContentResult::Posted { .. }));
        assert_eq!(poster.posted_count(), 3, "all 3 tweets should be posted");
        let marked = storage.marked_posted.lock().expect("lock");
        assert_eq!(marked.len(), 1);
        assert_eq!(marked[0], 99);
    }

    #[tokio::test]
    async fn try_post_scheduled_thread_fails_without_poster() {
        let tweets = serde_json::to_string(&vec!["Tweet 1", "Tweet 2"]).unwrap();
        let storage = ScheduledMockStorage::with_item(10, "thread", &tweets);

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            0,
            false,
        );
        // No .with_thread_poster() → should fail

        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        match result.unwrap() {
            ContentResult::Failed { error } => {
                assert!(
                    error.contains("No thread poster"),
                    "expected 'No thread poster' error, got: {error}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn try_post_scheduled_thread_fails_on_unparseable_content() {
        use crate::automation::thread_loop::test_mocks::MockPoster;
        let storage = ScheduledMockStorage::with_item(11, "thread", "not json at all");
        let poster = Arc::new(MockPoster::new());

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            0,
            false,
        )
        .with_thread_poster(poster);

        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        match result.unwrap() {
            ContentResult::Failed { error } => {
                assert!(
                    error.contains("Cannot parse"),
                    "expected parse error, got: {error}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn try_post_scheduled_thread_fails_on_empty_tweets() {
        use crate::automation::thread_loop::test_mocks::MockPoster;
        let tweets: Vec<String> = vec![];
        let json = serde_json::to_string(&tweets).unwrap();
        let storage = ScheduledMockStorage::with_item(12, "thread", &json);
        let poster = Arc::new(MockPoster::new());

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            0,
            false,
        )
        .with_thread_poster(poster);

        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        match result.unwrap() {
            ContentResult::Failed { error } => {
                assert!(
                    error.contains("no tweets"),
                    "expected 'no tweets' error, got: {error}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn try_post_scheduled_thread_permanent_failure() {
        use crate::automation::thread_loop::test_mocks::MockPoster;
        let tweets = serde_json::to_string(&vec!["Tweet 1", "Tweet 2", "Tweet 3"]).unwrap();
        let storage = ScheduledMockStorage::with_item(13, "thread", &tweets);
        let poster = Arc::new(MockPoster::failing_at(1)); // fail on second tweet

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            0,
            false,
        )
        .with_thread_poster(poster);

        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        match result.unwrap() {
            ContentResult::Failed { error } => {
                // "API error" is not a transient error, so it's marked as permanent failure
                assert!(
                    error.contains("failed permanently") && error.contains("tweet 2/3"),
                    "got: {error}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    // ScheduledMockStorage variant that returns an error from next_scheduled_item
    struct FailingScheduledStorage;

    #[async_trait::async_trait]
    impl ContentStorage for FailingScheduledStorage {
        async fn last_tweet_time(
            &self,
        ) -> Result<Option<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(None)
        }
        async fn last_thread_time(
            &self,
        ) -> Result<Option<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(None)
        }
        async fn todays_tweet_times(
            &self,
        ) -> Result<Vec<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(Vec::new())
        }
        async fn post_tweet(&self, _: &str, _: &str) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn create_thread(&self, _: &str, _: usize) -> Result<String, ContentLoopError> {
            Ok("t1".to_string())
        }
        async fn update_thread_status(
            &self,
            _: &str,
            _: &str,
            _: usize,
            _: Option<&str>,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn store_thread_tweet(
            &self,
            _: &str,
            _: usize,
            _: &str,
            _: &str,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn log_action(&self, _: &str, _: &str, _: &str) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn next_scheduled_item(
            &self,
        ) -> Result<Option<(i64, String, String)>, ContentLoopError> {
            Err(ContentLoopError::StorageError("db unavailable".to_string()))
        }
        async fn mark_scheduled_posted(
            &self,
            _: i64,
            _: Option<&str>,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn try_post_scheduled_returns_none_on_storage_error() {
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            Arc::new(FailingScheduledStorage),
            make_topics(),
            0,
            false,
        );
        let result = content.try_post_scheduled().await;
        assert!(result.is_none(), "storage error → None (graceful fallback)");
    }

    // ScheduledMockStorage variant where post_tweet fails
    struct FailingPostScheduledStorage {
        scheduled: Mutex<Option<(i64, String, String)>>,
    }

    impl FailingPostScheduledStorage {
        fn with_item(id: i64, content: &str) -> Arc<Self> {
            Arc::new(Self {
                scheduled: Mutex::new(Some((id, "tweet".to_string(), content.to_string()))),
            })
        }
    }

    #[async_trait::async_trait]
    impl ContentStorage for FailingPostScheduledStorage {
        async fn last_tweet_time(
            &self,
        ) -> Result<Option<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(None)
        }
        async fn last_thread_time(
            &self,
        ) -> Result<Option<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(None)
        }
        async fn todays_tweet_times(
            &self,
        ) -> Result<Vec<chrono::DateTime<chrono::Utc>>, ContentLoopError> {
            Ok(Vec::new())
        }
        async fn post_tweet(&self, _: &str, _: &str) -> Result<(), ContentLoopError> {
            Err(ContentLoopError::PostFailed(
                "X API unavailable".to_string(),
            ))
        }
        async fn create_thread(&self, _: &str, _: usize) -> Result<String, ContentLoopError> {
            Ok("t1".to_string())
        }
        async fn update_thread_status(
            &self,
            _: &str,
            _: &str,
            _: usize,
            _: Option<&str>,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn store_thread_tweet(
            &self,
            _: &str,
            _: usize,
            _: &str,
            _: &str,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn log_action(&self, _: &str, _: &str, _: &str) -> Result<(), ContentLoopError> {
            Ok(())
        }
        async fn next_scheduled_item(
            &self,
        ) -> Result<Option<(i64, String, String)>, ContentLoopError> {
            Ok(self.scheduled.lock().expect("lock").clone())
        }
        async fn mark_scheduled_posted(
            &self,
            _: i64,
            _: Option<&str>,
        ) -> Result<(), ContentLoopError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn try_post_scheduled_tweet_failure_returns_failed() {
        let storage = FailingPostScheduledStorage::with_item(20, "My scheduled tweet");
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "unused".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            0,
            false,
        );
        let result = content.try_post_scheduled().await;
        assert!(result.is_some());
        match result.unwrap() {
            ContentResult::Failed { error } => {
                assert!(
                    error.contains("Scheduled post failed"),
                    "expected 'Scheduled post failed', got: {error}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    // -------------------------------------------------------------------------
    // Scheduler: run_slot_iteration
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn run_slot_iteration_posts_when_no_scheduled_and_safety_allows() {
        let storage = Arc::new(MockStorage::new(None));
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "Slot tweet!".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            14400,
            false,
        );

        let mut recent = Vec::new();
        let mut rng = rand::rng();
        let result = content.run_slot_iteration(&mut recent, 3, &mut rng).await;
        assert!(matches!(result, ContentResult::Posted { .. }));
        assert_eq!(storage.posted_count(), 1);
        assert_eq!(recent.len(), 1);
    }

    #[tokio::test]
    async fn run_slot_iteration_rate_limited_when_safety_blocks() {
        let storage = Arc::new(MockStorage::new(None));
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: false,
                can_thread: true,
            }),
            storage,
            make_topics(),
            14400,
            false,
        );

        let mut recent = Vec::new();
        let mut rng = rand::rng();
        let result = content.run_slot_iteration(&mut recent, 3, &mut rng).await;
        assert!(matches!(result, ContentResult::RateLimited));
    }

    #[tokio::test]
    async fn run_slot_iteration_prioritizes_scheduled_content() {
        let storage = ScheduledMockStorage::with_item(50, "tweet", "Scheduled first!");
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "should not be used".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            14400,
            false,
        );

        let mut recent = Vec::new();
        let mut rng = rand::rng();
        let result = content.run_slot_iteration(&mut recent, 3, &mut rng).await;
        match result {
            ContentResult::Posted { topic, content } => {
                assert!(topic.contains("scheduled:50"));
                assert_eq!(content, "Scheduled first!");
            }
            other => panic!("expected Posted with scheduled content, got {other:?}"),
        }
    }

    // -------------------------------------------------------------------------
    // Scheduler: run_iteration with scheduled content priority
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn run_iteration_checks_scheduled_before_elapsed() {
        let storage = ScheduledMockStorage::with_item(60, "tweet", "Iteration scheduled!");
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "should not be used".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage.clone(),
            make_topics(),
            14400,
            false,
        );

        let mut recent = Vec::new();
        let mut rng = rand::rng();
        let result = content.run_iteration(&mut recent, 3, &mut rng).await;
        match result {
            ContentResult::Posted { topic, .. } => {
                assert!(
                    topic.contains("scheduled:60"),
                    "scheduled content should take priority"
                );
            }
            other => panic!("expected Posted with scheduled content, got {other:?}"),
        }
    }

    // -------------------------------------------------------------------------
    // Posted result captures correct topic + content
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn posted_result_contains_topic_and_content() {
        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "Great content about testing".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            Arc::new(MockStorage::new(None)),
            vec!["testing".to_string()],
            0,
            false,
        );
        let result = content.run_once(Some("testing")).await;
        match result {
            ContentResult::Posted { topic, content } => {
                assert_eq!(topic, "testing");
                assert_eq!(content, "Great content about testing");
            }
            other => panic!("expected Posted, got {other:?}"),
        }
    }
}