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
//! Tests for the unified mutation gateway.
//!
//! Covers: allowed, blocked (tool blocked, hard rule), rate-limited,
//! approval routing, dry-run, idempotency (duplicate), and post-execution
//! recording.

use super::*;
use crate::config::{McpPolicyConfig, OperatingMode};
use crate::mcp_policy::types::{
    PolicyAction, PolicyRateLimit, PolicyRule, RateLimitDimension, RuleConditions,
};
use crate::storage::{init_test_db, rate_limits};

fn default_policy_config() -> McpPolicyConfig {
    McpPolicyConfig {
        enforce_for_mutations: true,
        max_mutations_per_hour: 10,
        blocked_tools: vec![],
        require_approval_for: vec![],
        dry_run_mutations: false,
        template: None,
        rules: vec![],
        rate_limits: vec![],
    }
}

fn make_request<'a>(
    pool: &'a DbPool,
    config: &'a McpPolicyConfig,
    mode: &'a OperatingMode,
    tool_name: &'a str,
    params_json: &'a str,
) -> MutationRequest<'a> {
    MutationRequest {
        pool,
        policy_config: config,
        mode,
        tool_name,
        params_json,
    }
}

// ── Allowed scenario ───────────────────────────────────────────────────

#[tokio::test]
async fn gateway_allows_valid_mutation() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 10)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"hi"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::Proceed(ticket) => {
            assert!(!ticket.correlation_id.is_empty());
            assert_eq!(ticket.tool_name, "post_tweet");
        }
        other => panic!("expected Proceed, got {other:?}"),
    }
}

// ── Enforcement disabled → always allow ────────────────────────────────

#[tokio::test]
async fn gateway_allows_when_enforcement_disabled() {
    let pool = init_test_db().await.expect("init db");
    let mut config = default_policy_config();
    config.enforce_for_mutations = false;
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"hello"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    assert!(
        matches!(decision, GatewayDecision::Proceed(_)),
        "should allow when enforcement is disabled"
    );
}

// ── Blocked tool ───────────────────────────────────────────────────────

#[tokio::test]
async fn gateway_denies_blocked_tool() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 10)
        .await
        .expect("init rl");
    let mut config = default_policy_config();
    config.blocked_tools = vec!["post_tweet".to_string()];
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"hi"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::Denied(denial) => {
            assert_eq!(denial.reason, PolicyDenialReason::ToolBlocked);
        }
        other => panic!("expected Denied(ToolBlocked), got {other:?}"),
    }
}

// ── Rate limited ───────────────────────────────────────────────────────

#[tokio::test]
async fn gateway_denies_when_rate_limited() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 2)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    // Exhaust the rate limit.
    rate_limits::increment_rate_limit(&pool, "mcp_mutation")
        .await
        .expect("inc");
    rate_limits::increment_rate_limit(&pool, "mcp_mutation")
        .await
        .expect("inc");

    let req = make_request(&pool, &config, &mode, "like_tweet", r#"{"tweet_id":"1"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::Denied(denial) => {
            assert_eq!(denial.reason, PolicyDenialReason::RateLimited);
        }
        other => panic!("expected Denied(RateLimited), got {other:?}"),
    }
}

// ── Per-dimension rate limit ───────────────────────────────────────────

#[tokio::test]
async fn gateway_denies_per_dimension_rate_limit() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init global rl");

    let rl = PolicyRateLimit {
        key: "mcp:like_tweet:hourly".to_string(),
        dimension: RateLimitDimension::Tool,
        match_value: "like_tweet".to_string(),
        max_count: 1,
        period_seconds: 3600,
    };

    rate_limits::init_policy_rate_limits(&pool, &[rl.clone()])
        .await
        .expect("init policy rl");
    rate_limits::increment_rate_limit(&pool, "mcp:like_tweet:hourly")
        .await
        .expect("inc");

    let mut config = default_policy_config();
    config.rate_limits = vec![rl];
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "like_tweet", r#"{"tweet_id":"1"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::Denied(denial) => {
            assert_eq!(denial.reason, PolicyDenialReason::RateLimited);
        }
        other => panic!("expected Denied(RateLimited), got {other:?}"),
    }
}

// ── Approval routing ───────────────────────────────────────────────────

#[tokio::test]
async fn gateway_routes_to_approval() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 10)
        .await
        .expect("init rl");

    let mut config = default_policy_config();
    config.rules = vec![PolicyRule {
        id: "user:approve-all-writes".to_string(),
        priority: 200,
        label: "Approve all writes".to_string(),
        enabled: true,
        conditions: RuleConditions {
            tools: vec!["post_tweet".to_string()],
            ..Default::default()
        },
        action: PolicyAction::RequireApproval {
            reason: "Manual approval required".to_string(),
        },
    }];
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"hi"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::RoutedToApproval {
            queue_id,
            reason,
            rule_id,
        } => {
            assert!(queue_id > 0);
            assert_eq!(reason, "Manual approval required");
            assert!(rule_id.is_some());
        }
        other => panic!("expected RoutedToApproval, got {other:?}"),
    }
}

// ── Dry-run ────────────────────────────────────────────────────────────

#[tokio::test]
async fn gateway_returns_dry_run() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 10)
        .await
        .expect("init rl");

    let mut config = default_policy_config();
    config.rules = vec![PolicyRule {
        id: "user:dry-run-all".to_string(),
        priority: 200,
        label: "Dry run everything".to_string(),
        enabled: true,
        conditions: RuleConditions::default(),
        action: PolicyAction::DryRun,
    }];
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"hi"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::DryRun { rule_id } => {
            assert!(rule_id.is_some());
        }
        other => panic!("expected DryRun, got {other:?}"),
    }
}

// ── Idempotency (duplicate detection) ──────────────────────────────────

#[tokio::test]
async fn gateway_detects_duplicate() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    // First call: should proceed.
    let req1 = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"dup"}"#);
    let d1 = MutationGateway::evaluate(&req1).await.expect("eval 1");
    let ticket = match d1 {
        GatewayDecision::Proceed(t) => t,
        other => panic!("first call should proceed, got {other:?}"),
    };

    // Complete it successfully.
    MutationGateway::complete_success(&pool, &ticket, r#"{"tweet_id":"999"}"#, None, 100, &[])
        .await
        .expect("complete");

    // Second call with same params: should be duplicate.
    let req2 = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"dup"}"#);
    let d2 = MutationGateway::evaluate(&req2).await.expect("eval 2");

    match d2 {
        GatewayDecision::Duplicate(info) => {
            assert_eq!(info.original_correlation_id, ticket.correlation_id);
            assert!(info.cached_result.as_deref().unwrap_or("").contains("999"));
        }
        other => panic!("expected Duplicate, got {other:?}"),
    }
}

// ── Post-execution: success recording ──────────────────────────────────

#[tokio::test]
async fn gateway_records_success() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"ok"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("eval");
    let ticket = match decision {
        GatewayDecision::Proceed(t) => t,
        other => panic!("expected Proceed, got {other:?}"),
    };

    MutationGateway::complete_success(
        &pool,
        &ticket,
        r#"{"tweet_id":"123"}"#,
        Some(r#"{"tool":"x_delete_tweet","params":{"tweet_id":"123"}}"#),
        150,
        &config.rate_limits,
    )
    .await
    .expect("complete");

    // Verify audit trail.
    let entry = mutation_audit::get_by_correlation_id(&pool, &ticket.correlation_id)
        .await
        .expect("get")
        .expect("found");
    assert_eq!(entry.status, "success");
    assert_eq!(entry.elapsed_ms, Some(150));
    assert!(entry.rollback_action.is_some());
}

// ── Post-execution: failure recording ──────────────────────────────────

#[tokio::test]
async fn gateway_records_failure() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "like_tweet", r#"{"id":"1"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("eval");
    let ticket = match decision {
        GatewayDecision::Proceed(t) => t,
        other => panic!("expected Proceed, got {other:?}"),
    };

    MutationGateway::complete_failure(&pool, &ticket, "X API rate limit", 50)
        .await
        .expect("fail");

    let entry = mutation_audit::get_by_correlation_id(&pool, &ticket.correlation_id)
        .await
        .expect("get")
        .expect("found");
    assert_eq!(entry.status, "failure");
    assert_eq!(entry.error_message.as_deref(), Some("X API rate limit"));
}

// ── Retry after failure is allowed ─────────────────────────────────────

#[tokio::test]
async fn gateway_allows_retry_after_failure() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    // First attempt: proceed then fail.
    let req1 = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"retry"}"#);
    let d1 = MutationGateway::evaluate(&req1).await.expect("eval");
    let ticket = match d1 {
        GatewayDecision::Proceed(t) => t,
        other => panic!("first call should proceed, got {other:?}"),
    };
    MutationGateway::complete_failure(&pool, &ticket, "error", 10)
        .await
        .expect("fail");

    // Retry: should proceed (not duplicate, since first attempt failed).
    let req2 = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"retry"}"#);
    let d2 = MutationGateway::evaluate(&req2).await.expect("eval 2");
    assert!(
        matches!(d2, GatewayDecision::Proceed(_)),
        "retry after failure should proceed"
    );
}

// ── Hard rule denial ───────────────────────────────────────────────────

#[tokio::test]
async fn gateway_denies_hard_rule() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init rl");

    let mut config = default_policy_config();
    // Use post_tweet (no built-in hard rule) with a hard:-prefixed deny rule
    // to test the HardRule denial path. delete_tweet has a built-in
    // hard:delete_approval at priority 0 that would match first.
    config.rules = vec![PolicyRule {
        id: "hard:no-posting".to_string(),
        priority: 10,
        label: "No posting".to_string(),
        enabled: true,
        conditions: RuleConditions {
            tools: vec!["post_tweet".to_string()],
            ..Default::default()
        },
        action: PolicyAction::Deny {
            reason: "Posting is prohibited".to_string(),
        },
    }];
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "post_tweet", r#"{"text":"blocked"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::Denied(denial) => {
            assert_eq!(denial.reason, PolicyDenialReason::HardRule);
        }
        other => panic!("expected Denied(HardRule), got {other:?}"),
    }
}

// ── Delete always routes to approval (built-in hard rule) ──────────────

#[tokio::test]
async fn gateway_routes_delete_to_approval() {
    let pool = init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 100)
        .await
        .expect("init rl");
    let config = default_policy_config();
    let mode = OperatingMode::Autopilot;

    let req = make_request(&pool, &config, &mode, "delete_tweet", r#"{"tweet_id":"1"}"#);
    let decision = MutationGateway::evaluate(&req).await.expect("evaluate");

    match decision {
        GatewayDecision::RoutedToApproval { rule_id, .. } => {
            assert_eq!(rule_id, Some("hard:delete_approval".to_string()));
        }
        other => panic!("expected RoutedToApproval for delete, got {other:?}"),
    }
}

// ── Correlation ID format ──────────────────────────────────────────────

#[test]
fn correlation_id_is_uuid_v4_format() {
    let id = generate_correlation_id();
    assert_eq!(id.len(), 36);
    assert_eq!(&id[8..9], "-");
    assert_eq!(&id[13..14], "-");
    assert_eq!(&id[14..15], "4"); // version nibble
    assert_eq!(&id[18..19], "-");
    assert_eq!(&id[23..24], "-");
}

#[test]
fn correlation_ids_are_unique() {
    let ids: Vec<String> = (0..100).map(|_| generate_correlation_id()).collect();
    let unique: std::collections::HashSet<&str> = ids.iter().map(|s| s.as_str()).collect();
    assert_eq!(ids.len(), unique.len());
}