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
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
//! Integration tests for workflow step composition.

use std::sync::Arc;

use crate::config::{Config, McpPolicyConfig};
use crate::error::XApiError;
use crate::llm::{GenerationParams, LlmProvider, LlmResponse};
use crate::storage;
use crate::storage::tweets::DiscoveredTweet;
use crate::x_api::types::*;
use crate::x_api::XApiClient;
use crate::LlmError;

use super::*;

// ── Mock Helpers ─────────────────────────────────────────────────────

struct MockXApiClient {
    tweets: Vec<Tweet>,
    users: Vec<User>,
}

impl MockXApiClient {
    fn with_results(tweets: Vec<Tweet>, users: Vec<User>) -> Self {
        Self { tweets, users }
    }

    fn empty() -> Self {
        Self {
            tweets: vec![],
            users: vec![],
        }
    }
}

#[async_trait::async_trait]
impl XApiClient for MockXApiClient {
    async fn search_tweets(
        &self,
        _query: &str,
        _max_results: u32,
        _since_id: Option<&str>,
        _pagination_token: Option<&str>,
    ) -> Result<SearchResponse, XApiError> {
        Ok(SearchResponse {
            data: self.tweets.clone(),
            includes: if self.users.is_empty() {
                None
            } else {
                Some(Includes {
                    users: self.users.clone(),
                })
            },
            meta: SearchMeta {
                newest_id: self.tweets.first().map(|t| t.id.clone()),
                oldest_id: self.tweets.last().map(|t| t.id.clone()),
                result_count: self.tweets.len() as u32,
                next_token: None,
            },
        })
    }

    async fn get_mentions(
        &self,
        _user_id: &str,
        _since_id: Option<&str>,
        _pagination_token: Option<&str>,
    ) -> Result<MentionResponse, XApiError> {
        Ok(SearchResponse {
            data: vec![],
            includes: None,
            meta: SearchMeta {
                newest_id: None,
                oldest_id: None,
                result_count: 0,
                next_token: None,
            },
        })
    }

    async fn post_tweet(&self, text: &str) -> Result<PostedTweet, XApiError> {
        Ok(PostedTweet {
            id: "posted_1".to_string(),
            text: text.to_string(),
        })
    }

    async fn reply_to_tweet(
        &self,
        text: &str,
        _in_reply_to_id: &str,
    ) -> Result<PostedTweet, XApiError> {
        Ok(PostedTweet {
            id: "reply_1".to_string(),
            text: text.to_string(),
        })
    }

    async fn get_tweet(&self, tweet_id: &str) -> Result<Tweet, XApiError> {
        Ok(Tweet {
            id: tweet_id.to_string(),
            text: "Test tweet".to_string(),
            author_id: "a1".to_string(),
            created_at: "2026-02-24T00:00:00Z".to_string(),
            public_metrics: PublicMetrics::default(),
            conversation_id: None,
        })
    }

    async fn get_me(&self) -> Result<User, XApiError> {
        Ok(User {
            id: "u1".to_string(),
            username: "testuser".to_string(),
            name: "Test User".to_string(),
            profile_image_url: None,
            description: None,
            location: None,
            url: None,
            public_metrics: UserMetrics::default(),
        })
    }

    async fn get_user_tweets(
        &self,
        _user_id: &str,
        _max_results: u32,
        _pagination_token: Option<&str>,
    ) -> Result<SearchResponse, XApiError> {
        Ok(SearchResponse {
            data: vec![],
            includes: None,
            meta: SearchMeta {
                newest_id: None,
                oldest_id: None,
                result_count: 0,
                next_token: None,
            },
        })
    }

    async fn get_user_by_username(&self, username: &str) -> Result<User, XApiError> {
        Ok(User {
            id: "u2".to_string(),
            username: username.to_string(),
            name: "Test".to_string(),
            profile_image_url: None,
            description: None,
            location: None,
            url: None,
            public_metrics: UserMetrics::default(),
        })
    }

    async fn quote_tweet(
        &self,
        text: &str,
        _quoted_tweet_id: &str,
    ) -> Result<PostedTweet, XApiError> {
        Ok(PostedTweet {
            id: "qt_1".to_string(),
            text: text.to_string(),
        })
    }

    async fn like_tweet(&self, _user_id: &str, _tweet_id: &str) -> Result<bool, XApiError> {
        Ok(true)
    }

    async fn follow_user(&self, _user_id: &str, _target_user_id: &str) -> Result<bool, XApiError> {
        Ok(true)
    }

    async fn unfollow_user(
        &self,
        _user_id: &str,
        _target_user_id: &str,
    ) -> Result<bool, XApiError> {
        Ok(false)
    }
}

struct MockLlmProvider {
    reply_text: String,
}

impl MockLlmProvider {
    fn new(text: &str) -> Self {
        Self {
            reply_text: text.to_string(),
        }
    }
}

#[async_trait::async_trait]
impl LlmProvider for MockLlmProvider {
    fn name(&self) -> &str {
        "mock"
    }

    async fn complete(
        &self,
        _system: &str,
        _user_message: &str,
        _params: &GenerationParams,
    ) -> Result<LlmResponse, LlmError> {
        Ok(LlmResponse {
            text: self.reply_text.clone(),
            usage: crate::llm::TokenUsage {
                input_tokens: 10,
                output_tokens: 5,
            },
            model: "mock-model".to_string(),
        })
    }

    async fn health_check(&self) -> Result<(), LlmError> {
        Ok(())
    }
}

fn test_config() -> Config {
    let mut config = Config::default();
    config.mcp_policy = McpPolicyConfig {
        enforce_for_mutations: false,
        blocked_tools: Vec::new(),
        require_approval_for: Vec::new(),
        dry_run_mutations: false,
        max_mutations_per_hour: 20,
        ..McpPolicyConfig::default()
    };
    config.business.product_keywords = vec!["rust".to_string(), "async".to_string()];
    config.business.industry_topics = vec!["software engineering".to_string()];
    config.scoring.threshold = 0; // low threshold for test tweets to pass
    config
}

fn sample_tweet(id: &str, text: &str, author_id: &str) -> Tweet {
    Tweet {
        id: id.to_string(),
        text: text.to_string(),
        author_id: author_id.to_string(),
        created_at: "2026-02-24T12:00:00Z".to_string(),
        public_metrics: PublicMetrics {
            like_count: 10,
            retweet_count: 2,
            reply_count: 1,
            quote_count: 0,
            impression_count: 500,
            bookmark_count: 0,
        },
        conversation_id: None,
    }
}

fn sample_user(id: &str, username: &str, followers: u64) -> User {
    User {
        id: id.to_string(),
        username: username.to_string(),
        name: username.to_string(),
        profile_image_url: None,
        description: None,
        location: None,
        url: None,
        public_metrics: UserMetrics {
            followers_count: followers,
            following_count: 100,
            tweet_count: 500,
        },
    }
}

async fn seed_discovered_tweet(db: &storage::DbPool, id: &str, text: &str, author: &str) {
    let tweet = DiscoveredTweet {
        id: id.to_string(),
        author_id: "a1".to_string(),
        author_username: author.to_string(),
        content: text.to_string(),
        like_count: 10,
        retweet_count: 2,
        reply_count: 1,
        impression_count: Some(500),
        relevance_score: Some(75.0),
        matched_keyword: Some("rust".to_string()),
        discovered_at: "2026-02-24T12:00:00Z".to_string(),
        replied_to: 0,
    };
    storage::tweets::insert_discovered_tweet(db, &tweet)
        .await
        .expect("seed tweet");
}

// ── Discover step tests ──────────────────────────────────────────────

mod discover_tests {
    use super::*;

    #[tokio::test]
    async fn happy_path_search_score_rank() {
        let db = storage::init_test_db().await.unwrap();
        let tweets = vec![
            sample_tweet("t1", "Learning rust async programming today", "a1"),
            sample_tweet("t2", "Just had coffee", "a2"),
        ];
        let users = vec![
            sample_user("a1", "rustdev", 5000),
            sample_user("a2", "coffeelover", 200),
        ];
        let client = MockXApiClient::with_results(tweets, users);
        let config = test_config();

        let output = discover::execute(
            &db,
            &client,
            &config,
            DiscoverInput {
                query: Some("rust".to_string()),
                min_score: None,
                limit: Some(10),
                since_id: None,
            },
        )
        .await
        .unwrap();

        assert!(!output.candidates.is_empty());
        assert_eq!(output.query_used, "rust");
    }

    #[tokio::test]
    async fn empty_results() {
        let db = storage::init_test_db().await.unwrap();
        let client = MockXApiClient::empty();
        let config = test_config();

        let output = discover::execute(
            &db,
            &client,
            &config,
            DiscoverInput {
                query: Some("rust".to_string()),
                min_score: None,
                limit: None,
                since_id: None,
            },
        )
        .await
        .unwrap();

        assert!(output.candidates.is_empty());
    }

    #[tokio::test]
    async fn default_query_from_keywords() {
        let db = storage::init_test_db().await.unwrap();
        let tweets = vec![sample_tweet(
            "t1",
            "rust async is amazing for async tasks",
            "a1",
        )];
        let users = vec![sample_user("a1", "dev", 1000)];
        let client = MockXApiClient::with_results(tweets, users);
        let config = test_config();

        let output = discover::execute(
            &db,
            &client,
            &config,
            DiscoverInput {
                query: None, // should use product_keywords
                min_score: None,
                limit: None,
                since_id: None,
            },
        )
        .await
        .unwrap();

        assert_eq!(output.query_used, "rust OR async");
    }

    #[tokio::test]
    async fn no_query_no_keywords_errors() {
        let db = storage::init_test_db().await.unwrap();
        let client = MockXApiClient::empty();
        let mut config = test_config();
        config.business.product_keywords = vec![];

        let err = discover::execute(
            &db,
            &client,
            &config,
            DiscoverInput {
                query: None,
                min_score: None,
                limit: None,
                since_id: None,
            },
        )
        .await
        .unwrap_err();

        assert!(matches!(err, WorkflowError::InvalidInput(_)));
    }
}

// ── Draft step tests ─────────────────────────────────────────────────

mod draft_tests {
    use super::*;

    #[tokio::test]
    async fn happy_path_generate_drafts() {
        let db = storage::init_test_db().await.unwrap();
        seed_discovered_tweet(
            &db,
            "t1",
            "Rust is great for systems programming",
            "rustdev",
        )
        .await;

        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Great point about Rust!"));
        let config = test_config();

        let results = draft::execute(
            &db,
            &llm,
            &config,
            DraftInput {
                candidate_ids: vec!["t1".to_string()],
                archetype: None,
                mention_product: false,
                account_id: None,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        match &results[0] {
            DraftResult::Success { draft_text, .. } => {
                assert_eq!(draft_text, "Great point about Rust!");
            }
            DraftResult::Error { error_message, .. } => {
                panic!("Expected success, got error: {error_message}");
            }
        }
    }

    #[tokio::test]
    async fn candidate_not_found() {
        let db = storage::init_test_db().await.unwrap();
        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Reply"));
        let config = test_config();

        let results = draft::execute(
            &db,
            &llm,
            &config,
            DraftInput {
                candidate_ids: vec!["nonexistent".to_string()],
                archetype: None,
                mention_product: false,
                account_id: None,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        assert!(
            matches!(&results[0], DraftResult::Error { error_code, .. } if error_code == "not_found")
        );
    }

    #[tokio::test]
    async fn empty_input_errors() {
        let db = storage::init_test_db().await.unwrap();
        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Reply"));
        let config = test_config();

        let err = draft::execute(
            &db,
            &llm,
            &config,
            DraftInput {
                candidate_ids: vec![],
                archetype: None,
                mention_product: false,
                account_id: None,
            },
        )
        .await
        .unwrap_err();

        assert!(matches!(err, WorkflowError::InvalidInput(_)));
    }
}

// ── Queue step tests ─────────────────────────────────────────────────

mod queue_tests {
    use super::*;

    #[tokio::test]
    async fn queues_in_approval_mode() {
        let db = storage::init_test_db().await.unwrap();
        seed_discovered_tweet(&db, "t1", "Rust topic", "dev").await;

        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Great insight!"));
        let client = MockXApiClient::empty();
        let mut config = test_config();
        config.approval_mode = true;

        let results = queue::execute(
            &db,
            Some(&client as &dyn XApiClient),
            Some(&llm),
            &config,
            QueueInput {
                items: vec![QueueItem {
                    candidate_id: "t1".to_string(),
                    pre_drafted_text: Some("This is my reply!".to_string()),
                }],
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        assert!(matches!(&results[0], ProposeResult::Queued { .. }));
    }

    #[tokio::test]
    async fn executes_in_autopilot_mode() {
        let db = storage::init_test_db().await.unwrap();
        seed_discovered_tweet(&db, "t1", "Rust topic", "dev").await;

        let client = MockXApiClient::empty(); // reply_to_tweet returns "reply_1"
        let mut config = test_config();
        config.approval_mode = false;

        let results = queue::execute(
            &db,
            Some(&client as &dyn XApiClient),
            None,
            &config,
            QueueInput {
                items: vec![QueueItem {
                    candidate_id: "t1".to_string(),
                    pre_drafted_text: Some("Direct reply!".to_string()),
                }],
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        match &results[0] {
            ProposeResult::Executed { reply_tweet_id, .. } => {
                assert_eq!(reply_tweet_id, "reply_1");
            }
            other => panic!("Expected Executed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn tweet_not_found_blocked() {
        let db = storage::init_test_db().await.unwrap();
        let config = test_config();

        let results = queue::execute(
            &db,
            None,
            None,
            &config,
            QueueInput {
                items: vec![QueueItem {
                    candidate_id: "nonexistent".to_string(),
                    pre_drafted_text: Some("reply".to_string()),
                }],
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        assert!(matches!(&results[0], ProposeResult::Blocked { .. }));
    }

    #[tokio::test]
    async fn empty_items_errors() {
        let db = storage::init_test_db().await.unwrap();
        let config = test_config();

        let err = queue::execute(
            &db,
            None,
            None,
            &config,
            QueueInput {
                items: vec![],
                mention_product: false,
            },
        )
        .await
        .unwrap_err();

        assert!(matches!(err, WorkflowError::InvalidInput(_)));
    }
}

// ── Thread plan step tests ───────────────────────────────────────────

mod thread_plan_tests {
    use super::*;

    fn valid_thread_text() -> &'static str {
        "Most people think async is hard\n---\n\
         But the reality is simpler than you think\n---\n\
         Step one: understand the event loop\n---\n\
         Step two: learn about futures and polling\n---\n\
         Step three: build something real and iterate"
    }

    #[tokio::test]
    async fn happy_path_generates_thread() {
        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new(valid_thread_text()));
        let config = test_config();

        let output = thread_plan::execute(
            &llm,
            &config,
            ThreadPlanInput {
                topic: "software engineering".to_string(),
                objective: Some("establish expertise".to_string()),
                target_audience: Some("developers".to_string()),
                structure: None,
            },
        )
        .await
        .unwrap();

        assert_eq!(output.tweet_count, 5);
        assert_eq!(output.estimated_performance, "high");
        assert_eq!(output.hook_type, "contrarian"); // "Most people..."
    }

    #[tokio::test]
    async fn novel_topic_medium_performance() {
        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new(valid_thread_text()));
        let config = test_config();

        let output = thread_plan::execute(
            &llm,
            &config,
            ThreadPlanInput {
                topic: "cooking recipes".to_string(),
                objective: None,
                target_audience: None,
                structure: None,
            },
        )
        .await
        .unwrap();

        assert_eq!(output.estimated_performance, "medium");
        assert_eq!(output.topic_relevance, "novel_topic");
    }
}

// ── Orchestrator tests ───────────────────────────────────────────────

mod orchestrate_tests {
    use super::*;

    #[tokio::test]
    async fn full_cycle_discover_draft_queue() {
        let db = storage::init_test_db().await.unwrap();
        let tweets = vec![sample_tweet(
            "t1",
            "Learning rust async programming today",
            "a1",
        )];
        let users = vec![sample_user("a1", "rustdev", 5000)];
        let client = MockXApiClient::with_results(tweets, users);
        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Great point about Rust!"));
        let mut config = test_config();
        config.approval_mode = true;

        let report = orchestrate::run_discovery_cycle(
            &db,
            &client,
            &llm,
            &config,
            CycleInput {
                query: Some("rust".to_string()),
                min_score: None,
                limit: Some(10),
                since_id: None,
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert!(report.summary.candidates_found > 0);
        // Drafts should have been generated for actionable candidates
        assert!(report.summary.drafts_generated > 0 || report.summary.drafts_failed > 0);
    }

    #[tokio::test]
    async fn empty_search_returns_empty_report() {
        let db = storage::init_test_db().await.unwrap();
        let client = MockXApiClient::empty();
        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Reply"));
        let config = test_config();

        let report = orchestrate::run_discovery_cycle(
            &db,
            &client,
            &llm,
            &config,
            CycleInput {
                query: Some("rust".to_string()),
                min_score: None,
                limit: None,
                since_id: None,
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert_eq!(report.summary.candidates_found, 0);
        assert!(report.drafts.is_empty());
        assert!(report.queued.is_empty());
    }
}

// ── Publish step tests ───────────────────────────────────────────────

mod publish_tests {
    use super::*;

    #[tokio::test]
    async fn publish_reply_through_toolkit() {
        let client = MockXApiClient::empty();

        let output = publish::reply(&client, "Great point!", "t1").await.unwrap();

        assert_eq!(output.tweet_id, "reply_1");
        assert_eq!(output.text, "Great point!");
    }

    #[tokio::test]
    async fn publish_tweet_through_toolkit() {
        let client = MockXApiClient::empty();

        let output = publish::tweet(&client, "Hello world!").await.unwrap();

        assert_eq!(output.tweet_id, "posted_1");
        assert_eq!(output.text, "Hello world!");
    }
}

// ── Approval + scheduling mode combination tests ────────────────────

mod approval_scheduling_tests {
    use super::*;

    #[tokio::test]
    async fn autopilot_approval_on_queues_with_pending_status() {
        let db = storage::init_test_db().await.unwrap();
        seed_discovered_tweet(&db, "t1", "Rust topic", "dev").await;

        let llm: Arc<dyn LlmProvider> = Arc::new(MockLlmProvider::new("Insightful!"));
        let client = MockXApiClient::empty();
        let mut config = test_config();
        config.approval_mode = true;

        let results = queue::execute(
            &db,
            Some(&client as &dyn XApiClient),
            Some(&llm),
            &config,
            QueueInput {
                items: vec![QueueItem {
                    candidate_id: "t1".to_string(),
                    pre_drafted_text: Some("Scheduled reply".to_string()),
                }],
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        assert!(matches!(&results[0], ProposeResult::Queued { .. }));

        // Verify the item is in the approval queue with pending status.
        let pending = storage::approval_queue::get_pending(&db).await.unwrap();
        assert!(!pending.is_empty());
        assert_eq!(pending[0].status, "pending");
    }

    #[tokio::test]
    async fn autopilot_approval_off_executes_immediately() {
        let db = storage::init_test_db().await.unwrap();
        seed_discovered_tweet(&db, "t1", "Rust topic", "dev").await;

        let client = MockXApiClient::empty();
        let mut config = test_config();
        config.approval_mode = false;

        let results = queue::execute(
            &db,
            Some(&client as &dyn XApiClient),
            None,
            &config,
            QueueInput {
                items: vec![QueueItem {
                    candidate_id: "t1".to_string(),
                    pre_drafted_text: Some("Direct post".to_string()),
                }],
                mention_product: false,
            },
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        match &results[0] {
            ProposeResult::Executed { reply_tweet_id, .. } => {
                assert_eq!(reply_tweet_id, "reply_1");
            }
            other => panic!("Expected Executed, got {other:?}"),
        }

        // Approval queue should be empty.
        let pending = storage::approval_queue::get_pending(&db).await.unwrap();
        assert!(pending.is_empty());
    }

    #[tokio::test]
    async fn scheduled_for_preserved_through_enqueue() {
        let db = storage::init_test_db().await.unwrap();

        // Enqueue with scheduling intent.
        let id = storage::approval_queue::enqueue_with_context_for(
            &db,
            storage::accounts::DEFAULT_ACCOUNT_ID,
            "tweet",
            "",
            "",
            "Scheduled tweet content",
            "Topic",
            "",
            0.0,
            "[]",
            None,
            None,
            Some("2026-03-15T14:00:00Z"),
        )
        .await
        .unwrap();

        // Verify scheduled_for is stored.
        let item = storage::approval_queue::get_by_id(&db, id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(item.scheduled_for.as_deref(), Some("2026-03-15T14:00:00Z"));
        assert_eq!(item.status, "pending");
    }

    #[tokio::test]
    async fn approval_mode_preserves_schedule_across_status_changes() {
        let db = storage::init_test_db().await.unwrap();

        let id = storage::approval_queue::enqueue_with_context_for(
            &db,
            storage::accounts::DEFAULT_ACCOUNT_ID,
            "tweet",
            "",
            "",
            "Content with schedule",
            "",
            "",
            0.0,
            "[]",
            None,
            None,
            Some("2026-04-01T10:00:00Z"),
        )
        .await
        .unwrap();

        // Approve the item.
        let review = storage::approval_queue::ReviewAction {
            actor: Some("tester".to_string()),
            notes: None,
        };
        storage::approval_queue::update_status_with_review(&db, id, "approved", &review)
            .await
            .unwrap();

        // scheduled_for should still be present after status change.
        let item = storage::approval_queue::get_by_id(&db, id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(item.status, "approved");
        assert_eq!(item.scheduled_for.as_deref(), Some("2026-04-01T10:00:00Z"));
    }
}

// ── Error propagation tests ──────────────────────────────────────────

mod error_tests {
    use super::*;

    #[test]
    fn workflow_error_from_toolkit() {
        let toolkit_err = crate::toolkit::ToolkitError::InvalidInput {
            message: "bad input".to_string(),
        };
        let workflow_err: WorkflowError = toolkit_err.into();
        assert!(matches!(workflow_err, WorkflowError::Toolkit(_)));
    }

    #[test]
    fn workflow_error_from_llm() {
        let llm_err = LlmError::NotConfigured;
        let workflow_err: WorkflowError = llm_err.into();
        assert!(matches!(workflow_err, WorkflowError::Llm(_)));
    }

    #[test]
    fn workflow_error_display() {
        let err = WorkflowError::InvalidInput("test error".to_string());
        assert_eq!(err.to_string(), "invalid input: test error");
    }
}