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
//! Task 3.5 — Safety guardrail integration tests.
//!
//! Tests that the PRODUCTION default limits are enforced end-to-end using
//! the real `SafetyGuard` + SQLite + `ConfigFixture::default_config()`.
//!
//! Default limits (from `LimitsConfig::default`):
//!   - Max 5 replies / day
//!   - Max 6 tweets / day
//!   - Max 1 thread / week
//!   - Max 1 reply per author / day  (anti-harassment)
//!
//! These tests are the **hard QA requirement** from SOUL.md.
//! Every guardrail must have at least one dedicated test here.

#[cfg(test)]
mod tests {
    use crate::config::{IntervalsConfig, LimitsConfig};
    use crate::safety::{DenialReason, SafetyGuard};
    use crate::storage::{init_test_db, rate_limits};

    // -------------------------------------------------------------------------
    // Helpers
    // -------------------------------------------------------------------------

    /// Init a test DB with the real production default limits.
    /// Uses `LimitsConfig::default()` which carries the production values:
    ///   max_replies_per_day=5, max_tweets_per_day=6, max_threads_per_week=1
    async fn setup_guard_with_defaults() -> (crate::storage::DbPool, SafetyGuard) {
        let pool = init_test_db().await.expect("init test db");
        rate_limits::init_rate_limits(&pool, &LimitsConfig::default(), &IntervalsConfig::default())
            .await
            .expect("init rate limits");
        let guard = SafetyGuard::new(pool.clone());
        (pool, guard)
    }

    /// Exhaust `n` reply slots by recording directly on the guard.
    async fn exhaust_replies(guard: &SafetyGuard, n: u32) {
        for _ in 0..n {
            guard.record_reply().await.expect("record reply");
        }
    }

    /// Exhaust `n` tweet slots.
    async fn exhaust_tweets(guard: &SafetyGuard, n: u32) {
        for _ in 0..n {
            guard.record_tweet().await.expect("record tweet");
        }
    }

    // =========================================================================
    // 1. Max 5 replies/day — 6th attempt is blocked
    // =========================================================================

    #[tokio::test]
    async fn reply_limit_5_per_day_allows_5_attempts() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        for i in 1..=5 {
            let result = guard
                .can_reply_to(&format!("tweet_{i}"), None)
                .await
                .expect("check");
            assert!(
                result.is_ok(),
                "reply {i}/5 should be allowed, got: {result:?}"
            );
            guard.record_reply().await.expect("record");
        }
    }

    #[tokio::test]
    async fn reply_limit_5_per_day_blocks_6th_attempt() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        exhaust_replies(&guard, 5).await;

        let result = guard.can_reply_to("tweet_6th", None).await.expect("check");
        match result {
            Err(DenialReason::RateLimited {
                action_type,
                current,
                max,
            }) => {
                assert_eq!(action_type, "reply");
                assert_eq!(current, 5, "counter should show 5 used");
                assert_eq!(max, 5, "max should be the default 5");
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn reply_limit_5_per_day_blocks_all_subsequent_attempts() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        exhaust_replies(&guard, 5).await;

        // 7th, 8th, 9th all blocked
        for i in 6..=9 {
            let result = guard
                .can_reply_to(&format!("tweet_{i}"), None)
                .await
                .expect("check");
            assert!(
                result.is_err(),
                "attempt {i} should be blocked after 5 replies"
            );
        }
    }

    // =========================================================================
    // 2. Max 6 tweets/day — 7th attempt is blocked
    // =========================================================================

    #[tokio::test]
    async fn tweet_limit_6_per_day_allows_6_attempts() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        for i in 1..=6 {
            let result = guard.can_post_tweet().await.expect("check");
            assert!(
                result.is_ok(),
                "tweet {i}/6 should be allowed, got: {result:?}"
            );
            guard.record_tweet().await.expect("record");
        }
    }

    #[tokio::test]
    async fn tweet_limit_6_per_day_blocks_7th_attempt() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        exhaust_tweets(&guard, 6).await;

        let result = guard.can_post_tweet().await.expect("check");
        match result {
            Err(DenialReason::RateLimited {
                action_type,
                current,
                max,
            }) => {
                assert_eq!(action_type, "tweet");
                assert_eq!(current, 6, "counter should show 6 used");
                assert_eq!(max, 6, "max should be the default 6");
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn tweet_limit_counter_reaches_max_exactly() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        // Post 6 times — all should succeed
        for _ in 0..6 {
            let result = guard.can_post_tweet().await.expect("check");
            assert!(result.is_ok(), "should allow before max");
            guard.record_tweet().await.expect("record");
        }

        // 7th — must be blocked
        let result = guard.can_post_tweet().await.expect("check");
        assert!(result.is_err(), "7th tweet must be blocked");
    }

    // =========================================================================
    // 3. Max 1 thread/week — 2nd attempt is blocked
    // =========================================================================

    #[tokio::test]
    async fn thread_limit_1_per_week_allows_first_attempt() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        let result = guard.can_post_thread().await.expect("check");
        assert!(result.is_ok(), "first thread of the week should be allowed");
    }

    #[tokio::test]
    async fn thread_limit_1_per_week_blocks_second_attempt() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        guard.record_thread().await.expect("record");

        let result = guard.can_post_thread().await.expect("check");
        match result {
            Err(DenialReason::RateLimited {
                action_type,
                current,
                max,
            }) => {
                assert_eq!(action_type, "thread");
                assert_eq!(current, 1, "one thread posted this week");
                assert_eq!(max, 1, "max should be the default 1/week");
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn thread_limit_blocks_all_subsequent_attempts() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        guard.record_thread().await.expect("record");

        for _ in 0..3 {
            let result = guard.can_post_thread().await.expect("check");
            assert!(result.is_err(), "all attempts after 1st must be blocked");
        }
    }

    // =========================================================================
    // 4. Max 1 reply per author / day (anti-harassment)
    // =========================================================================

    #[tokio::test]
    async fn anti_harassment_allows_first_reply_to_author() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        let result = guard
            .check_author_limit("author_1", 1)
            .await
            .expect("check");
        assert!(result.is_ok(), "first reply to author_1 should be allowed");
    }

    #[tokio::test]
    async fn anti_harassment_blocks_second_reply_to_same_author() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        // Record one interaction with author_1
        guard
            .record_author_interaction("author_1", "alice")
            .await
            .expect("record");

        let result = guard
            .check_author_limit("author_1", 1)
            .await
            .expect("check");
        assert_eq!(
            result,
            Err(DenialReason::AuthorLimitReached),
            "second reply to author_1 must be blocked (anti-harassment)"
        );
    }

    #[tokio::test]
    async fn anti_harassment_allows_different_authors() {
        let (_pool, guard) = setup_guard_with_defaults().await;

        // Reply to author_1 — record it
        guard
            .record_author_interaction("author_1", "alice")
            .await
            .expect("record");

        // Reply to author_2 — should be allowed (different author)
        let result = guard
            .check_author_limit("author_2", 1)
            .await
            .expect("check");
        assert!(
            result.is_ok(),
            "author_2 reply should be allowed even though author_1 is at limit"
        );
    }

    #[tokio::test]
    async fn anti_harassment_author_2_gets_second_reply_blocked() {
        // Explicitly test the scenario from the acceptance criteria:
        // "author_2 gets second reply blocked"
        let (_pool, guard) = setup_guard_with_defaults().await;

        // First reply to author_2 allowed
        let first = guard
            .check_author_limit("author_2", 1)
            .await
            .expect("check");
        assert!(first.is_ok(), "first reply to author_2 allowed");
        guard
            .record_author_interaction("author_2", "bob")
            .await
            .expect("record");

        // Second reply to author_2 — must be blocked
        let second = guard
            .check_author_limit("author_2", 1)
            .await
            .expect("check");
        assert_eq!(
            second,
            Err(DenialReason::AuthorLimitReached),
            "second reply to author_2 must be blocked (anti-harassment)"
        );
    }

    // =========================================================================
    // 5. Jaccard similarity dedup — duplicate content rejected
    // =========================================================================

    #[tokio::test]
    async fn jaccard_dedup_blocks_near_duplicate_reply() {
        let (pool, guard) = setup_guard_with_defaults().await;

        // Jaccard threshold = 0.8. These two texts differ only in the last word,
        // giving Jaccard ≈ 0.85 — just above the threshold.
        let original =
            "Rust ownership model makes memory safety a first-class citizen in systems programming";
        let near_dup =
            "Rust ownership model makes memory safety a first-class citizen in systems engineering";

        // Record original reply
        let reply = crate::storage::replies::ReplySent {
            id: 0,
            target_tweet_id: "tweet_orig".to_string(),
            reply_tweet_id: Some("r1".to_string()),
            reply_content: original.to_string(),
            llm_provider: None,
            llm_model: None,
            created_at: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            status: "sent".to_string(),
            error_message: None,
        };
        crate::storage::replies::insert_reply(&pool, &reply)
            .await
            .expect("insert");

        // Near-duplicate reply should be blocked
        let result = guard
            .can_reply_to("tweet_new", Some(near_dup))
            .await
            .expect("check");
        assert_eq!(
            result,
            Err(DenialReason::SimilarPhrasing),
            "near-duplicate reply must be blocked by Jaccard similarity check"
        );
    }

    #[tokio::test]
    async fn jaccard_dedup_allows_clearly_different_content() {
        let (pool, guard) = setup_guard_with_defaults().await;

        let original = "Rust ownership model prevents memory errors at compile time";
        let different =
            "Python list comprehensions are elegant and readable for data transformation";

        let reply = crate::storage::replies::ReplySent {
            id: 0,
            target_tweet_id: "tweet_orig".to_string(),
            reply_tweet_id: Some("r1".to_string()),
            reply_content: original.to_string(),
            llm_provider: None,
            llm_model: None,
            created_at: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            status: "sent".to_string(),
            error_message: None,
        };
        crate::storage::replies::insert_reply(&pool, &reply)
            .await
            .expect("insert");

        let result = guard
            .can_reply_to("tweet_new", Some(different))
            .await
            .expect("check");
        assert!(
            result.is_ok(),
            "clearly different content must pass dedup check"
        );
    }

    // =========================================================================
    // 6. No auto-follow / auto-like in automation paths
    // =========================================================================

    #[tokio::test]
    async fn no_auto_follow_endpoint_in_safety_guard() {
        // SafetyGuard must not expose any auto-follow or auto-like method.
        // This is a compile-time documentation test — if someone adds
        // `follow_user()` or `like_tweet()` to SafetyGuard, this comment
        // serves as an audit trail requiring explicit review.
        //
        // The guard only exposes: can_reply_to, can_post_tweet, can_post_thread,
        // check_author_limit, check_banned_phrases, record_*, rate_limiter(),
        // dedup_checker(). No follow/like methods exist — verified by API audit.
        let (_pool, guard) = setup_guard_with_defaults().await;

        // Verify the guard can still do its intended job
        let tweet_ok = guard.can_post_tweet().await.expect("tweet check");
        assert!(tweet_ok.is_ok());
        let thread_ok = guard.can_post_thread().await.expect("thread check");
        assert!(thread_ok.is_ok());
        let reply_ok = guard.can_reply_to("t1", None).await.expect("reply check");
        assert!(reply_ok.is_ok());
    }

    // =========================================================================
    // 7. LimitsConfig::default() carries the correct production values
    // =========================================================================

    #[test]
    fn limits_config_default_has_production_values() {
        let limits = LimitsConfig::default();
        assert_eq!(limits.max_replies_per_day, 5, "default: 5 replies/day");
        assert_eq!(limits.max_tweets_per_day, 6, "default: 6 tweets/day");
        assert_eq!(limits.max_threads_per_week, 1, "default: 1 thread/week");
        assert_eq!(
            limits.max_replies_per_author_per_day, 1,
            "default: 1 reply/author/day"
        );
        assert!(
            limits.banned_phrases.contains(&"check out".to_string()),
            "default banned phrases include 'check out'"
        );
    }
}