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
//! Tweet generation, topic selection, and text-length utilities.
//!
//! Implements the `generate_and_post` and `pick_topic_epsilon_greedy` methods
//! on [`ContentLoop`], plus the free functions used by the scheduler.

use super::{ContentLoop, ContentResult, EXPLOIT_RATIO};
use rand::seq::IndexedRandom;

impl ContentLoop {
    /// Generate a tweet and post it (or print in dry-run mode).
    pub(super) async fn generate_and_post(&self, topic: &str) -> ContentResult {
        tracing::info!(topic = %topic, "Generating tweet on topic");

        // Generate tweet
        let content = match self.generator.generate_tweet(topic).await {
            Ok(text) => text,
            Err(e) => {
                return ContentResult::Failed {
                    error: format!("Generation failed: {e}"),
                }
            }
        };

        // Validate length (280 char limit, URL-aware)
        let content = if crate::content::length::tweet_weighted_len(&content)
            > crate::content::length::MAX_TWEET_CHARS
        {
            // Retry once with explicit shorter instruction
            tracing::debug!(
                chars = content.len(),
                "Generated tweet too long, retrying with shorter instruction"
            );

            let shorter_topic = format!("{topic} (IMPORTANT: keep under 280 characters)");
            match self.generator.generate_tweet(&shorter_topic).await {
                Ok(text)
                    if crate::content::length::tweet_weighted_len(&text)
                        <= crate::content::length::MAX_TWEET_CHARS =>
                {
                    text
                }
                Ok(text) => {
                    // Truncate at word boundary
                    tracing::warn!(
                        chars = text.len(),
                        "Retry still too long, truncating at word boundary"
                    );
                    truncate_at_word_boundary(&text, 280)
                }
                Err(e) => {
                    // Use original but truncated
                    tracing::warn!(error = %e, "Retry generation failed, truncating original");
                    truncate_at_word_boundary(&content, 280)
                }
            }
        } else {
            content
        };

        if self.dry_run {
            tracing::info!(
                "DRY RUN: Would post tweet on topic '{}': \"{}\" ({} chars)",
                topic,
                content,
                content.len()
            );

            let _ = self
                .storage
                .log_action(
                    "tweet",
                    "dry_run",
                    &format!("Topic '{}': {}", topic, truncate_display(&content, 80)),
                )
                .await;
        } else {
            if let Err(e) = self.storage.post_tweet(topic, &content).await {
                tracing::error!(error = %e, "Failed to post tweet");
                let _ = self
                    .storage
                    .log_action("tweet", "failure", &format!("Post failed: {e}"))
                    .await;
                return ContentResult::Failed {
                    error: e.to_string(),
                };
            }

            let _ = self
                .storage
                .log_action(
                    "tweet",
                    "success",
                    &format!("Topic '{}': {}", topic, truncate_display(&content, 80)),
                )
                .await;
        }

        ContentResult::Posted {
            topic: topic.to_string(),
            content,
        }
    }

    /// Pick a topic using epsilon-greedy selection.
    ///
    /// If a topic scorer is available:
    /// - 80% of the time: pick from top-performing topics (exploit)
    /// - 20% of the time: pick a random topic (explore)
    ///
    /// Falls back to uniform random selection if no scorer is set or
    /// if the scorer returns no data.
    pub(super) async fn pick_topic_epsilon_greedy(
        &self,
        recent_topics: &mut Vec<String>,
        rng: &mut impl rand::Rng,
    ) -> String {
        if let Some(scorer) = &self.topic_scorer {
            let roll: f64 = rng.random();
            if roll < EXPLOIT_RATIO {
                // Exploit: try to pick from top-performing topics
                if let Ok(top_topics) = scorer.get_top_topics(10).await {
                    // Filter to topics that are in our configured list and not recent
                    let candidates: Vec<&String> = top_topics
                        .iter()
                        .filter(|t| self.topics.contains(t) && !recent_topics.contains(t))
                        .collect();

                    if !candidates.is_empty() {
                        let topic = candidates[0].clone();
                        tracing::debug!(topic = %topic, "Epsilon-greedy: exploiting top topic");
                        return topic;
                    }
                }
                // Fall through to random if no top topics match
                tracing::debug!("Epsilon-greedy: no top topics available, falling back to random");
            } else {
                tracing::debug!("Epsilon-greedy: exploring random topic");
            }
        }

        pick_topic(&self.topics, recent_topics, rng)
    }
}

// ---------------------------------------------------------------------------
// Free functions
// ---------------------------------------------------------------------------

/// Pick a topic that is not in the recent list.
/// If all topics are recent, clear the list and pick any.
pub(super) fn pick_topic(
    topics: &[String],
    recent: &mut Vec<String>,
    rng: &mut impl rand::Rng,
) -> String {
    let available: Vec<&String> = topics.iter().filter(|t| !recent.contains(t)).collect();

    if available.is_empty() {
        // All topics recently used -- clear and pick any
        recent.clear();
        topics.choose(rng).expect("topics is non-empty").clone()
    } else {
        available
            .choose(rng)
            .expect("available is non-empty")
            .to_string()
    }
}

/// Truncate content at a word boundary, fitting within max_len characters.
pub(super) fn truncate_at_word_boundary(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        return s.to_string();
    }

    // Find last space before max_len - 3 (for "...")
    let cutoff = max_len.saturating_sub(3);
    match s[..cutoff].rfind(' ') {
        Some(pos) => format!("{}...", &s[..pos]),
        None => format!("{}...", &s[..cutoff]),
    }
}

/// Truncate a string for display purposes.
pub(super) fn truncate_display(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len])
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::super::test_mocks::{
        make_topics, FailingGenerator, FailingTopicScorer, FirstCallRng, MockGenerator, MockSafety,
        MockStorage, MockTopicScorer, OverlongGenerator,
    };
    use super::super::{ContentLoop, ContentResult};
    use std::sync::{Arc, Mutex};

    #[tokio::test]
    async fn overlong_tweet_gets_truncated() {
        let long_text = "a ".repeat(200); // 400 chars
        let content = ContentLoop::new(
            Arc::new(OverlongGenerator {
                first_response: long_text.clone(),
                retry_response: long_text,
                call_count: Mutex::new(0),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            Arc::new(MockStorage::new(None)),
            make_topics(),
            14400,
            true,
        );

        let result = content.run_once(Some("Rust")).await;
        if let ContentResult::Posted { content, .. } = result {
            assert!(content.len() <= 280);
        } else {
            panic!("Expected Posted result");
        }
    }

    #[test]
    fn truncate_at_word_boundary_short() {
        let result = super::truncate_at_word_boundary("Hello world", 280);
        assert_eq!(result, "Hello world");
    }

    #[test]
    fn truncate_at_word_boundary_long() {
        let text = "The quick brown fox jumps over the lazy dog and more words here";
        let result = super::truncate_at_word_boundary(text, 30);
        assert!(result.len() <= 30);
        assert!(result.ends_with("..."));
    }

    #[test]
    fn truncate_display_short() {
        assert_eq!(super::truncate_display("hello", 10), "hello");
    }

    #[test]
    fn truncate_display_long() {
        let result = super::truncate_display("hello world this is long", 10);
        assert_eq!(result, "hello worl...");
    }

    #[test]
    fn pick_topic_avoids_recent() {
        let topics = make_topics();
        let mut recent = vec!["Rust".to_string(), "CLI tools".to_string()];
        let mut rng = rand::rng();

        for _ in 0..20 {
            let topic = super::pick_topic(&topics, &mut recent, &mut rng);
            assert_ne!(topic, "Rust");
            assert_ne!(topic, "CLI tools");
        }
    }

    #[test]
    fn pick_topic_clears_when_all_recent() {
        let topics = make_topics();
        let mut recent = topics.clone();
        let mut rng = rand::rng();

        let topic = super::pick_topic(&topics, &mut recent, &mut rng);
        assert!(topics.contains(&topic));
        assert!(recent.is_empty());
    }

    #[tokio::test]
    async fn epsilon_greedy_exploits_top_topic() {
        let storage = Arc::new(MockStorage::new(None));
        let scorer = Arc::new(MockTopicScorer {
            top_topics: vec!["Rust".to_string()],
        });

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            14400,
            false,
        )
        .with_topic_scorer(scorer);

        let mut recent = Vec::new();
        let mut rng = FirstCallRng::low_roll();

        let topic = content
            .pick_topic_epsilon_greedy(&mut recent, &mut rng)
            .await;
        assert_eq!(topic, "Rust");
    }

    #[tokio::test]
    async fn epsilon_greedy_explores_when_roll_high() {
        let storage = Arc::new(MockStorage::new(None));
        let scorer = Arc::new(MockTopicScorer {
            top_topics: vec!["Rust".to_string()],
        });

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            14400,
            false,
        )
        .with_topic_scorer(scorer);

        let mut recent = Vec::new();
        let mut rng = FirstCallRng::high_roll();

        let topic = content
            .pick_topic_epsilon_greedy(&mut recent, &mut rng)
            .await;
        assert!(make_topics().contains(&topic));
    }

    #[tokio::test]
    async fn epsilon_greedy_falls_back_on_scorer_error() {
        let storage = Arc::new(MockStorage::new(None));
        let scorer = Arc::new(FailingTopicScorer);

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            14400,
            false,
        )
        .with_topic_scorer(scorer);

        let mut recent = Vec::new();
        let mut rng = FirstCallRng::low_roll();

        let topic = content
            .pick_topic_epsilon_greedy(&mut recent, &mut rng)
            .await;
        assert!(make_topics().contains(&topic));
    }

    #[tokio::test]
    async fn epsilon_greedy_without_scorer_picks_random() {
        let storage = Arc::new(MockStorage::new(None));

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

        let mut recent = Vec::new();
        let mut rng = rand::rng();

        let topic = content
            .pick_topic_epsilon_greedy(&mut recent, &mut rng)
            .await;
        assert!(make_topics().contains(&topic));
    }

    #[tokio::test]
    async fn generation_failure_returns_failed() {
        let content = ContentLoop::new(
            Arc::new(FailingGenerator),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            Arc::new(MockStorage::new(None)),
            make_topics(),
            14400,
            false,
        );

        let result = content.run_once(Some("Rust")).await;
        assert!(matches!(result, ContentResult::Failed { .. }));
    }

    // -----------------------------------------------------------------------
    // Additional generator coverage tests
    // -----------------------------------------------------------------------

    #[test]
    fn truncate_at_word_boundary_no_space() {
        let result = super::truncate_at_word_boundary("abcdefghijklmnop", 10);
        // No space found before cutoff (10-3=7), truncates at pos 7
        assert_eq!(result, "abcdefg...");
    }

    #[test]
    fn truncate_at_word_boundary_exact_cutoff() {
        let result = super::truncate_at_word_boundary("Hello World", 11);
        assert_eq!(result, "Hello World"); // fits exactly
    }

    #[test]
    fn truncate_display_exact_length() {
        assert_eq!(super::truncate_display("12345", 5), "12345");
    }

    #[test]
    fn truncate_display_one_over() {
        let result = super::truncate_display("123456", 5);
        assert_eq!(result, "12345...");
    }

    #[tokio::test]
    async fn overlong_with_retry_fitting() {
        let content = ContentLoop::new(
            Arc::new(OverlongGenerator {
                first_response: "a ".repeat(200), // 400 chars (too long)
                retry_response: "Short retry tweet".to_string(), // fits
                call_count: Mutex::new(0),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            Arc::new(MockStorage::new(None)),
            make_topics(),
            14400,
            false,
        );

        let result = content.run_once(Some("Rust")).await;
        if let ContentResult::Posted { content, .. } = result {
            assert_eq!(content, "Short retry tweet");
        } else {
            panic!("Expected Posted");
        }
    }

    #[tokio::test]
    async fn epsilon_greedy_skips_recent_topics() {
        let storage = Arc::new(MockStorage::new(None));
        let scorer = Arc::new(MockTopicScorer {
            top_topics: vec!["Rust".to_string(), "CLI tools".to_string()],
        });

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            14400,
            false,
        )
        .with_topic_scorer(scorer);

        // "Rust" is in recent, so exploit should pick "CLI tools"
        let mut recent = vec!["Rust".to_string()];
        let mut rng = FirstCallRng::low_roll();

        let topic = content
            .pick_topic_epsilon_greedy(&mut recent, &mut rng)
            .await;
        assert_eq!(topic, "CLI tools");
    }

    #[tokio::test]
    async fn epsilon_greedy_falls_through_when_all_top_are_recent() {
        let storage = Arc::new(MockStorage::new(None));
        let scorer = Arc::new(MockTopicScorer {
            top_topics: vec!["Rust".to_string()],
        });

        let content = ContentLoop::new(
            Arc::new(MockGenerator {
                response: "tweet".to_string(),
            }),
            Arc::new(MockSafety {
                can_tweet: true,
                can_thread: true,
            }),
            storage,
            make_topics(),
            14400,
            false,
        )
        .with_topic_scorer(scorer);

        // All top topics are recent -> falls through to random
        let mut recent = vec!["Rust".to_string()];
        let mut rng = FirstCallRng::low_roll();

        let topic = content
            .pick_topic_epsilon_greedy(&mut recent, &mut rng)
            .await;
        // Should pick a non-Rust topic from the full list
        assert!(make_topics().contains(&topic));
    }

    #[test]
    fn pick_topic_single_topic() {
        let topics = vec!["Only".to_string()];
        let mut recent = Vec::new();
        let mut rng = rand::rng();

        let topic = super::pick_topic(&topics, &mut recent, &mut rng);
        assert_eq!(topic, "Only");
    }

    #[test]
    fn pick_topic_rotates_through_all() {
        let topics = vec!["A".to_string(), "B".to_string()];
        let mut recent = Vec::new();
        let mut rng = rand::rng();

        // First pick: one of A or B
        let first = super::pick_topic(&topics, &mut recent, &mut rng);
        recent.push(first.clone());

        // Second pick: must be the other
        let second = super::pick_topic(&topics, &mut recent, &mut rng);
        assert_ne!(first, second);
    }
}