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
//! Tests for the MCP policy evaluator.

use super::evaluator::{McpPolicyEvaluator, PolicyDecision, PolicyDenialReason};
use super::rules::{build_effective_rules, conditions_match, make_eval_context};
use super::templates::{get_template, list_templates};
use super::types::{
    PolicyAction, PolicyRateLimit, PolicyRule, PolicyTemplateName, RateLimitDimension,
    RuleConditions, ToolCategory,
};
use crate::config::{McpPolicyConfig, OperatingMode};
use crate::storage::{self, rate_limits};

fn default_policy() -> McpPolicyConfig {
    McpPolicyConfig::default()
}

fn enforcement_disabled() -> McpPolicyConfig {
    McpPolicyConfig {
        enforce_for_mutations: false,
        ..default_policy()
    }
}

fn with_blocked(tools: Vec<&str>) -> McpPolicyConfig {
    McpPolicyConfig {
        blocked_tools: tools.into_iter().map(String::from).collect(),
        ..default_policy()
    }
}

fn dry_run_policy() -> McpPolicyConfig {
    McpPolicyConfig {
        dry_run_mutations: true,
        ..default_policy()
    }
}

fn no_approval_policy() -> McpPolicyConfig {
    McpPolicyConfig {
        require_approval_for: Vec::new(),
        ..default_policy()
    }
}

// =========================================================================
// Backward compatibility tests (v1 behavior preserved)
// =========================================================================

#[tokio::test]
async fn enforcement_disabled_allows_all() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = enforcement_disabled();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    assert_eq!(decision, PolicyDecision::Allow);
}

#[tokio::test]
async fn blocked_tool_denied() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = with_blocked(vec!["post_tweet"]);
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::ToolBlocked,
            ..
        }
    ));
}

#[tokio::test]
async fn dry_run_returns_dry_run() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = dry_run_policy();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    assert!(matches!(decision, PolicyDecision::DryRun { .. }));
}

#[tokio::test]
async fn rate_limit_exceeded_denies() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 2)
        .await
        .expect("init rate limit");

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

    let config = no_approval_policy();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::RateLimited,
            ..
        }
    ));
}

#[tokio::test]
async fn approval_required_routes() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = default_policy();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    assert!(matches!(decision, PolicyDecision::RouteToApproval { .. }));
}

#[tokio::test]
async fn non_approval_tool_allowed() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = default_policy();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "unfollow_user")
            .await
            .expect("evaluate");

    assert_eq!(decision, PolicyDecision::Allow);
}

#[tokio::test]
async fn composer_mode_forces_approval() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = no_approval_policy();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Composer, "unfollow_user")
            .await
            .expect("evaluate");

    assert!(matches!(decision, PolicyDecision::RouteToApproval { .. }));
}

#[tokio::test]
async fn audit_record_logged() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = default_policy();
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    McpPolicyEvaluator::log_decision(&pool, "post_tweet", &decision)
        .await
        .expect("log");

    let rows: Vec<(String, String)> = sqlx::query_as(
        "SELECT action_type, status FROM action_log WHERE action_type = 'mcp_policy'",
    )
    .fetch_all(&pool)
    .await
    .expect("query");

    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].0, "mcp_policy");
    assert_eq!(rows[0].1, "routed_to_approval");
}

#[tokio::test]
async fn record_mutation_increments_counter() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    McpPolicyEvaluator::record_mutation(&pool, "post_tweet", &[])
        .await
        .expect("record");

    let limits = rate_limits::get_all_rate_limits(&pool)
        .await
        .expect("get limits");
    let mcp = limits
        .iter()
        .find(|l| l.action_type == "mcp_mutation")
        .expect("mcp_mutation row");
    assert_eq!(mcp.request_count, 1);
}

#[tokio::test]
async fn blocked_takes_priority_over_dry_run() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = McpPolicyConfig {
        blocked_tools: vec!["post_tweet".to_string()],
        dry_run_mutations: true,
        ..default_policy()
    };
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::ToolBlocked,
            ..
        }
    ));
}

// =========================================================================
// Rule matching tests
// =========================================================================

#[test]
fn tool_name_match_hit() {
    let conditions = RuleConditions {
        tools: vec!["post_tweet".into()],
        ..Default::default()
    };
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(conditions_match(&conditions, &ctx));
}

#[test]
fn tool_name_match_miss() {
    let conditions = RuleConditions {
        tools: vec!["like_tweet".into()],
        ..Default::default()
    };
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(!conditions_match(&conditions, &ctx));
}

#[test]
fn category_match_hit() {
    let conditions = RuleConditions {
        categories: vec![ToolCategory::Write],
        ..Default::default()
    };
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(conditions_match(&conditions, &ctx));
}

#[test]
fn category_match_miss() {
    let conditions = RuleConditions {
        categories: vec![ToolCategory::Engage],
        ..Default::default()
    };
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(!conditions_match(&conditions, &ctx));
}

#[test]
fn mode_match_hit() {
    let conditions = RuleConditions {
        modes: vec![OperatingMode::Autopilot],
        ..Default::default()
    };
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(conditions_match(&conditions, &ctx));
}

#[test]
fn mode_match_miss() {
    let conditions = RuleConditions {
        modes: vec![OperatingMode::Composer],
        ..Default::default()
    };
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(!conditions_match(&conditions, &ctx));
}

#[test]
fn empty_conditions_match_all() {
    let conditions = RuleConditions::default();
    let ctx = make_eval_context("any_tool", &OperatingMode::Autopilot);
    assert!(conditions_match(&conditions, &ctx));
}

#[test]
fn multi_condition_and_logic() {
    // Requires both category=Write AND mode=Autopilot
    let conditions = RuleConditions {
        categories: vec![ToolCategory::Write],
        modes: vec![OperatingMode::Autopilot],
        ..Default::default()
    };

    // Match: Write + Autopilot
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    assert!(conditions_match(&conditions, &ctx));

    // No match: Write + Composer
    let ctx = make_eval_context("post_tweet", &OperatingMode::Composer);
    assert!(!conditions_match(&conditions, &ctx));

    // No match: Engage + Autopilot
    let ctx = make_eval_context("like_tweet", &OperatingMode::Autopilot);
    assert!(!conditions_match(&conditions, &ctx));
}

// =========================================================================
// Template tests
// =========================================================================

#[test]
fn list_templates_returns_three() {
    let templates = list_templates();
    assert_eq!(templates.len(), 3);
}

#[test]
fn safe_default_template_has_expected_rules() {
    let template = get_template(&PolicyTemplateName::SafeDefault);
    assert!(template.rules.len() >= 3);
    // Should have a delete approval rule
    assert!(template
        .rules
        .iter()
        .any(|r| r.id.contains("delete_approval")));
}

#[tokio::test]
async fn template_applied_produces_expected_decisions() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 50)
        .await
        .expect("init rate limit");

    let config = McpPolicyConfig {
        template: Some(PolicyTemplateName::GrowthAggressive),
        require_approval_for: Vec::new(),
        ..default_policy()
    };

    // Growth aggressive allows most mutations
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");
    assert_eq!(decision, PolicyDecision::Allow);

    // But delete still requires approval (hard rule)
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "delete_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(decision, PolicyDecision::RouteToApproval { .. }));
}

#[tokio::test]
async fn template_plus_user_rules_coexist() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 50)
        .await
        .expect("init rate limit");

    // User rule at priority 99 fires before template's allow_all at 150
    let config = McpPolicyConfig {
        template: Some(PolicyTemplateName::GrowthAggressive),
        rules: vec![PolicyRule {
            id: "user:block_likes".into(),
            priority: 99, // Before template rules
            label: "Block likes".into(),
            enabled: true,
            conditions: RuleConditions {
                tools: vec!["like_tweet".into()],
                ..Default::default()
            },
            action: PolicyAction::Deny {
                reason: "user blocked likes".into(),
            },
        }],
        require_approval_for: Vec::new(),
        ..default_policy()
    };

    // like_tweet denied at priority 99 (before template allow at 150)
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "like_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::UserRule,
            ..
        }
    ));

    // post_tweet still allowed by template
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");
    assert_eq!(decision, PolicyDecision::Allow);
}

// =========================================================================
// Hard rule tests
// =========================================================================

#[tokio::test]
async fn delete_tweet_always_routes_to_approval() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 200)
        .await
        .expect("init rate limit");

    // Even with agency_mode template (maximum autonomy)
    let config = McpPolicyConfig {
        template: Some(PolicyTemplateName::AgencyMode),
        require_approval_for: Vec::new(),
        ..default_policy()
    };

    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "delete_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(decision, PolicyDecision::RouteToApproval { .. }));
}

#[tokio::test]
async fn composer_mode_always_routes_to_approval() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 200)
        .await
        .expect("init rate limit");

    let config = McpPolicyConfig {
        template: Some(PolicyTemplateName::AgencyMode),
        require_approval_for: Vec::new(),
        ..default_policy()
    };

    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Composer, "like_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(decision, PolicyDecision::RouteToApproval { .. }));
}

// =========================================================================
// Rate limit per-dimension tests
// =========================================================================

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

    let per_tool_limits = vec![PolicyRateLimit {
        key: "mcp:tool:like_tweet:hourly".into(),
        dimension: RateLimitDimension::Tool,
        match_value: "like_tweet".into(),
        max_count: 2,
        period_seconds: 3600,
    }];

    rate_limits::init_policy_rate_limits(&pool, &per_tool_limits)
        .await
        .expect("init policy rate limits");

    // Exhaust per-tool limit
    rate_limits::increment_rate_limit(&pool, "mcp:tool:like_tweet:hourly")
        .await
        .expect("inc");
    rate_limits::increment_rate_limit(&pool, "mcp:tool:like_tweet:hourly")
        .await
        .expect("inc");

    let config = McpPolicyConfig {
        require_approval_for: Vec::new(),
        rate_limits: per_tool_limits,
        ..default_policy()
    };

    // like_tweet should be rate limited
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "like_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::RateLimited,
            ..
        }
    ));

    // post_tweet should still be allowed (different tool)
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");
    assert_eq!(decision, PolicyDecision::Allow);
}

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

    let per_cat_limits = vec![PolicyRateLimit {
        key: "mcp:category:engage:daily".into(),
        dimension: RateLimitDimension::Category,
        match_value: "engage".into(),
        max_count: 1,
        period_seconds: 86400,
    }];

    rate_limits::init_policy_rate_limits(&pool, &per_cat_limits)
        .await
        .expect("init");

    // Exhaust category limit
    rate_limits::increment_rate_limit(&pool, "mcp:category:engage:daily")
        .await
        .expect("inc");

    let config = McpPolicyConfig {
        require_approval_for: Vec::new(),
        rate_limits: per_cat_limits,
        ..default_policy()
    };

    // like_tweet (engage category) should be rate limited
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "like_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::RateLimited,
            ..
        }
    ));
}

#[tokio::test]
async fn global_limit_still_works_alongside_per_dimension() {
    let pool = storage::init_test_db().await.expect("init db");
    // Set global limit to 1
    rate_limits::init_mcp_rate_limit(&pool, 1)
        .await
        .expect("init rate limit");

    let per_tool_limits = vec![PolicyRateLimit {
        key: "mcp:tool:post_tweet:hourly".into(),
        dimension: RateLimitDimension::Tool,
        match_value: "post_tweet".into(),
        max_count: 100, // Very high per-tool limit
        period_seconds: 3600,
    }];

    rate_limits::init_policy_rate_limits(&pool, &per_tool_limits)
        .await
        .expect("init");

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

    let config = McpPolicyConfig {
        require_approval_for: Vec::new(),
        rate_limits: per_tool_limits,
        ..default_policy()
    };

    // Should be denied by global limit even though per-tool limit is fine
    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");
    assert!(matches!(
        decision,
        PolicyDecision::Deny {
            reason: PolicyDenialReason::RateLimited,
            ..
        }
    ));
}

// =========================================================================
// Effective rules construction tests
// =========================================================================

#[test]
fn effective_rules_sorted_by_priority() {
    let config = McpPolicyConfig {
        rules: vec![
            PolicyRule {
                id: "user:z".into(),
                priority: 250,
                label: "Z".into(),
                enabled: true,
                conditions: RuleConditions::default(),
                action: PolicyAction::Allow,
            },
            PolicyRule {
                id: "user:a".into(),
                priority: 200,
                label: "A".into(),
                enabled: true,
                conditions: RuleConditions::default(),
                action: PolicyAction::Allow,
            },
        ],
        ..default_policy()
    };

    let rules = build_effective_rules(&config, &OperatingMode::Autopilot);
    // Hard rules first (priority 0), then user rules in priority order
    assert!(rules[0].priority <= rules[1].priority);
    for i in 1..rules.len() {
        assert!(rules[i - 1].priority <= rules[i].priority);
    }
}

#[test]
fn v1_compat_rules_generated_when_no_v2_config() {
    let config = McpPolicyConfig {
        blocked_tools: vec!["bad_tool".into()],
        require_approval_for: vec!["post_tweet".into()],
        ..default_policy()
    };

    let rules = build_effective_rules(&config, &OperatingMode::Autopilot);
    // Should have hard rules + v1 compat rules
    assert!(rules.iter().any(|r| r.id.starts_with("v1:blocked:")));
    assert!(rules.iter().any(|r| r.id.starts_with("v1:approval:")));
}

#[test]
fn v1_compat_rules_not_generated_with_template() {
    let config = McpPolicyConfig {
        template: Some(PolicyTemplateName::SafeDefault),
        blocked_tools: vec!["bad_tool".into()],
        ..default_policy()
    };

    let rules = build_effective_rules(&config, &OperatingMode::Autopilot);
    // Should NOT have v1 compat rules when template is set
    assert!(!rules.iter().any(|r| r.id.starts_with("v1:")));
}

#[test]
fn disabled_rules_excluded_from_matching() {
    let config = McpPolicyConfig {
        rules: vec![PolicyRule {
            id: "user:disabled".into(),
            priority: 200,
            label: "Disabled".into(),
            enabled: false,
            conditions: RuleConditions::default(),
            action: PolicyAction::Deny {
                reason: "should not fire".into(),
            },
        }],
        ..default_policy()
    };

    let rules = build_effective_rules(&config, &OperatingMode::Autopilot);
    // The disabled rule should still be in the list (for display)
    // but find_matching_rule should skip it
    let ctx = make_eval_context("post_tweet", &OperatingMode::Autopilot);
    let matching = super::rules::find_matching_rule(&rules, &ctx);
    // Should match a hard rule or v1 rule, not the disabled one
    if let Some(rule) = matching {
        assert_ne!(rule.id, "user:disabled");
    }
}

// =========================================================================
// Audit record tests
// =========================================================================

#[tokio::test]
async fn audit_record_includes_rule_metadata() {
    let pool = storage::init_test_db().await.expect("init db");
    rate_limits::init_mcp_rate_limit(&pool, 20)
        .await
        .expect("init rate limit");

    let config = McpPolicyConfig {
        template: Some(PolicyTemplateName::SafeDefault),
        require_approval_for: Vec::new(),
        ..default_policy()
    };

    let decision =
        McpPolicyEvaluator::evaluate(&pool, &config, &OperatingMode::Autopilot, "post_tweet")
            .await
            .expect("evaluate");

    McpPolicyEvaluator::log_decision(&pool, "post_tweet", &decision)
        .await
        .expect("log");

    let rows: Vec<(String, Option<String>)> = sqlx::query_as(
        "SELECT action_type, metadata FROM action_log WHERE action_type = 'mcp_policy'",
    )
    .fetch_all(&pool)
    .await
    .expect("query");

    assert_eq!(rows.len(), 1);
    // Metadata should include v2 audit fields
    let metadata = rows[0].1.as_ref().expect("metadata should exist");
    assert!(metadata.contains("category"));
    assert!(metadata.contains("matched_rule_id"));
}

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

    let per_tool_limits = vec![PolicyRateLimit {
        key: "mcp:tool:like_tweet:hourly".into(),
        dimension: RateLimitDimension::Tool,
        match_value: "like_tweet".into(),
        max_count: 10,
        period_seconds: 3600,
    }];

    rate_limits::init_policy_rate_limits(&pool, &per_tool_limits)
        .await
        .expect("init");

    McpPolicyEvaluator::record_mutation(&pool, "like_tweet", &per_tool_limits)
        .await
        .expect("record");

    let limits = rate_limits::get_all_rate_limits(&pool)
        .await
        .expect("get limits");

    // Global counter incremented
    let mcp = limits
        .iter()
        .find(|l| l.action_type == "mcp_mutation")
        .expect("mcp_mutation row");
    assert_eq!(mcp.request_count, 1);

    // Per-tool counter incremented
    let per_tool = limits
        .iter()
        .find(|l| l.action_type == "mcp:tool:like_tweet:hourly")
        .expect("per-tool row");
    assert_eq!(per_tool.request_count, 1);
}