bock-codegen 0.1.0

Multi-target code generation for Bock — JS, TS, Python, Rust, Go
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
//! Integration tests for Tier 1 AI codegen wiring (D.5).
//!
//! These exercise selective invocation, confidence gating, pinned
//! replay, deterministic fallback, and decision-manifest recording
//! per §17.2 / §17.4 / §17.8 and Q3 of the 2026-04-20 spec amendment.

use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;

use bock_ai::{
    AiCache, AiError, AiProvider, CandidateRule, GenerateRequest, GenerateResponse,
    ManifestWriter, ModuleContext, OptimizeRequest, OptimizeResponse, RepairRequest,
    RepairResponse, Rule, RuleCache, SelectRequest, SelectResponse,
};
use bock_air::{AIRNode, AirHandlerPair, EnumVariantPayload, NodeKind};
use bock_ast::{Ident, TypePath, Visibility};
use bock_codegen::{
    needs_ai_synthesis, synthesize_and_flush, verify_generated, AiSynthesisDriver,
    JsGenerator, RsGenerator, SynthesisConfig, TargetProfile,
};
use bock_codegen::CodeGenerator;
use bock_errors::{FileId, Span};
use bock_types::Strictness;

// ─── Test provider: configurable confidence + call counting ──────────────────

struct CountingProvider {
    confidence: f64,
    calls: AtomicUsize,
    fail: bool,
}

impl CountingProvider {
    fn new(confidence: f64) -> Self {
        Self {
            confidence,
            calls: AtomicUsize::new(0),
            fail: false,
        }
    }

    fn failing() -> Self {
        Self {
            confidence: 0.0,
            calls: AtomicUsize::new(0),
            fail: true,
        }
    }

    fn calls(&self) -> usize {
        self.calls.load(Ordering::SeqCst)
    }
}

#[async_trait]
impl AiProvider for CountingProvider {
    async fn generate(
        &self,
        request: &GenerateRequest,
    ) -> Result<GenerateResponse, AiError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        if self.fail {
            return Err(AiError::Unavailable("test: provider down".into()));
        }
        // Emit code that always verifies cleanly: non-empty, balanced.
        Ok(GenerateResponse {
            code: format!("// synthesized for {}\n{{ /* body */ }}\n", request.target.id),
            confidence: self.confidence,
            reasoning: Some("test".into()),
            alternatives: Vec::new(),
        })
    }

    async fn repair(&self, _request: &RepairRequest) -> Result<RepairResponse, AiError> {
        unreachable!("repair not used in D.5 tests")
    }

    async fn optimize(
        &self,
        _request: &OptimizeRequest,
    ) -> Result<OptimizeResponse, AiError> {
        unreachable!("optimize not used in D.5 tests")
    }

    async fn select(&self, _request: &SelectRequest) -> Result<SelectResponse, AiError> {
        unreachable!("select not used in D.5 tests")
    }

    fn model_id(&self) -> String {
        "counting:test".into()
    }
}

// ─── AIR fixture builders ────────────────────────────────────────────────────

fn span() -> Span {
    Span {
        file: FileId(0),
        start: 0,
        end: 0,
    }
}

fn ident(name: &str) -> Ident {
    Ident {
        name: name.into(),
        span: span(),
    }
}

fn node(id: u32, kind: NodeKind) -> AIRNode {
    AIRNode::new(id, span(), kind)
}

/// Module with a match expression (flagged by JS ai_hints).
fn module_with_match() -> AIRNode {
    let scrutinee = node(1, NodeKind::Identifier { name: ident("x") });
    let match_node = node(
        2,
        NodeKind::Match {
            scrutinee: Box::new(scrutinee),
            arms: vec![],
        },
    );
    node(
        0,
        NodeKind::Module {
            path: None,
            annotations: vec![],
            imports: vec![],
            items: vec![match_node],
        },
    )
}

/// Module with an enum declaration (flagged by JS ai_hints).
fn module_with_enum() -> AIRNode {
    let variant = node(
        2,
        NodeKind::EnumVariant {
            name: ident("A"),
            payload: EnumVariantPayload::Unit,
        },
    );
    let enum_decl = node(
        1,
        NodeKind::EnumDecl {
            annotations: vec![],
            visibility: Visibility::Public,
            name: ident("Color"),
            generic_params: vec![],
            variants: vec![variant],
        },
    );
    node(
        0,
        NodeKind::Module {
            path: None,
            annotations: vec![],
            imports: vec![],
            items: vec![enum_decl],
        },
    )
}

/// Module containing only a literal (trivial — should never hit AI).
fn module_trivial_only() -> AIRNode {
    let lit = node(
        1,
        NodeKind::Literal {
            lit: bock_ast::Literal::Int("42".into()),
        },
    );
    node(
        0,
        NodeKind::Module {
            path: None,
            annotations: vec![],
            imports: vec![],
            items: vec![lit],
        },
    )
}

/// Module with an effect handling block (flagged on every target per ai_hints).
fn module_with_handling() -> AIRNode {
    let handler = node(3, NodeKind::Identifier { name: ident("h") });
    let body = node(
        4,
        NodeKind::Block {
            stmts: vec![],
            tail: None,
        },
    );
    let handling = node(
        1,
        NodeKind::HandlingBlock {
            handlers: vec![AirHandlerPair {
                effect: TypePath {
                    segments: vec![ident("Log")],
                    span: span(),
                },
                handler: Box::new(handler),
            }],
            body: Box::new(body),
        },
    );
    node(
        0,
        NodeKind::Module {
            path: None,
            annotations: vec![],
            imports: vec![],
            items: vec![handling],
        },
    )
}

fn module_ctx(path: &str) -> ModuleContext {
    ModuleContext {
        module_path: path.into(),
        imports: Vec::new(),
        siblings: Vec::new(),
        annotations: Vec::new(),
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[test]
fn needs_ai_synthesis_trivial_bypasses_ai() {
    let js = TargetProfile::javascript();
    let lit = node(
        1,
        NodeKind::Literal {
            lit: bock_ast::Literal::Int("1".into()),
        },
    );
    assert!(!needs_ai_synthesis(&js, &lit));
}

#[test]
fn needs_ai_synthesis_flagged_for_js_match() {
    let js = TargetProfile::javascript();
    let m = node(
        1,
        NodeKind::Match {
            scrutinee: Box::new(node(2, NodeKind::Identifier { name: ident("x") })),
            arms: vec![],
        },
    );
    assert!(needs_ai_synthesis(&js, &m));
}

#[test]
fn needs_ai_synthesis_flagged_only_when_hinted() {
    // Rust does not flag Match — native support.
    let rust = TargetProfile::rust();
    let m = node(
        1,
        NodeKind::Match {
            scrutinee: Box::new(node(2, NodeKind::Identifier { name: ident("x") })),
            arms: vec![],
        },
    );
    assert!(!needs_ai_synthesis(&rust, &m));
}

#[test]
fn verify_accepts_balanced_js() {
    assert!(verify_generated("js", "function f() { return 1; }").is_ok());
}

#[test]
fn verify_rejects_unbalanced_js() {
    assert!(verify_generated("js", "function f() { return 1;").is_err());
}

#[test]
fn verify_rejects_empty() {
    assert!(verify_generated("js", "").is_err());
    assert!(verify_generated("js", "   \n  ").is_err());
}

#[test]
fn verify_python_skips_bracket_check() {
    assert!(verify_generated("python", "def f():\n    return 1\n").is_ok());
}

#[test]
fn trait_method_dispatches_through_ai_hints() {
    // CodeGenerator::needs_ai_synthesis default should match free fn.
    let gen = JsGenerator::new();
    let m = node(
        1,
        NodeKind::Match {
            scrutinee: Box::new(node(2, NodeKind::Identifier { name: ident("x") })),
            arms: vec![],
        },
    );
    assert!(gen.needs_ai_synthesis(&m));
    let lit = node(
        3,
        NodeKind::Literal {
            lit: bock_ast::Literal::Int("1".into()),
        },
    );
    assert!(!gen.needs_ai_synthesis(&lit));
}

#[test]
fn rust_trait_rejects_native_constructs() {
    let gen = RsGenerator::new();
    let m = node(
        1,
        NodeKind::Match {
            scrutinee: Box::new(node(2, NodeKind::Identifier { name: ident("x") })),
            arms: vec![],
        },
    );
    assert!(!gen.needs_ai_synthesis(&m));
}

// ── High-confidence acceptance (§17.4) ──────────────────────────────────────

#[tokio::test]
async fn high_confidence_accepted_and_recorded() {
    let provider = Arc::new(CountingProvider::new(0.9));
    let dir = tempfile::tempdir().unwrap();
    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let cache = Some(AiCache::new(dir.path()));
    let config = SynthesisConfig {
        confidence_threshold: 0.75,
        deterministic_fallback: true,
        strictness: Strictness::Development,
        auto_pin: false,
        module_path: PathBuf::from("src/m.bock"),
    };
    let driver = AiSynthesisDriver::new(provider.clone(), cache, Some(manifest.clone()), config);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .expect("synthesis ok");

    assert_eq!(stats.flagged_nodes, 1);
    assert_eq!(stats.ai_calls, 1);
    assert_eq!(stats.accepted, 1);
    assert_eq!(stats.fallback_triggered, 0);
    assert_eq!(provider.calls(), 1);

    // Manifest should have one codegen decision on disk.
    let build_dir = dir.path().join(".bock/decisions/build");
    let file = build_dir.join("src/m.bock.json");
    assert!(file.exists(), "manifest file missing: {file:?}");
    let content = std::fs::read_to_string(&file).unwrap();
    assert!(content.contains("\"codegen\""));
    assert!(content.contains("\"confidence\": 0.9"));
    assert!(!content.contains("\"pinned\": true"));
}

// ── Low-confidence fallback ─────────────────────────────────────────────────

#[tokio::test]
async fn low_confidence_triggers_fallback() {
    let provider = Arc::new(CountingProvider::new(0.5));
    let dir = tempfile::tempdir().unwrap();
    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        confidence_threshold: 0.75,
        deterministic_fallback: true,
        strictness: Strictness::Development,
        auto_pin: false,
        module_path: PathBuf::from("src/m.bock"),
    };
    let driver = AiSynthesisDriver::new(provider.clone(), None, Some(manifest.clone()), config);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .expect("synthesis ok");

    assert_eq!(stats.flagged_nodes, 1);
    assert_eq!(stats.ai_calls, 1);
    assert_eq!(stats.accepted, 0);
    assert_eq!(stats.rejected_low_confidence, 1);
    assert_eq!(stats.fallback_triggered, 1);
    // No manifest file should be written (no decision recorded).
    let build_dir = dir.path().join(".bock/decisions/build");
    assert!(!build_dir.join("src/m.bock.json").exists());
}

// ── No-provider path ────────────────────────────────────────────────────────

#[tokio::test]
async fn no_provider_falls_through() {
    let config = SynthesisConfig {
        module_path: PathBuf::from("src/m.bock"),
        ..Default::default()
    };
    let driver = AiSynthesisDriver::deterministic(config);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = driver
        .synthesize_module(&module, &target, &ctx)
        .await
        .expect("synthesis ok");

    assert_eq!(stats.flagged_nodes, 1);
    assert_eq!(stats.ai_calls, 0);
    assert_eq!(stats.accepted, 0);
    assert_eq!(stats.fallback_triggered, 1);
}

// ── Cache replay bypasses threshold ─────────────────────────────────────────

#[tokio::test]
async fn pinned_cache_replay_bypasses_threshold() {
    let dir = tempfile::tempdir().unwrap();

    // First build: high confidence → accepted + cached.
    {
        let provider = Arc::new(CountingProvider::new(0.9));
        let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
        let cache = Some(AiCache::new(dir.path()));
        let config = SynthesisConfig {
            confidence_threshold: 0.75,
            deterministic_fallback: true,
            strictness: Strictness::Development,
            auto_pin: false,
            module_path: PathBuf::from("src/m.bock"),
        };
        let driver = AiSynthesisDriver::new(provider.clone(), cache, Some(manifest), config);
        let module = module_with_match();
        let target = TargetProfile::javascript();
        let ctx = module_ctx("src/m.bock");
        let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
            .await
            .unwrap();
        assert_eq!(stats.accepted, 1);
        assert_eq!(stats.cache_hits, 0);
        assert_eq!(provider.calls(), 1);
    }

    // Second build: provider now returns LOW confidence. Cache hit wins.
    {
        let provider = Arc::new(CountingProvider::new(0.1));
        let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
        let cache = Some(AiCache::new(dir.path()));
        let config = SynthesisConfig {
            confidence_threshold: 0.75,
            deterministic_fallback: true,
            strictness: Strictness::Development,
            auto_pin: false,
            module_path: PathBuf::from("src/m.bock"),
        };
        let driver = AiSynthesisDriver::new(provider.clone(), cache, Some(manifest), config);
        let module = module_with_match();
        let target = TargetProfile::javascript();
        let ctx = module_ctx("src/m.bock");
        let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
            .await
            .unwrap();

        // Cache replay — provider never called, response treated as pinned.
        assert_eq!(provider.calls(), 0, "cache hit should skip provider");
        assert_eq!(stats.cache_hits, 1);
        assert_eq!(stats.accepted, 1);
        assert_eq!(stats.rejected_low_confidence, 0);
    }

    // Manifest should have two entries (one per build), the latter pinned.
    let manifest_file = dir.path().join(".bock/decisions/build/src/m.bock.json");
    let content = std::fs::read_to_string(&manifest_file).unwrap();
    // Count pinned=true entries.
    let pinned_count = content.matches("\"pinned\": true").count();
    assert!(pinned_count >= 1, "expected pinned replay entry in {content}");
    assert!(content.contains("\"cache-replay\""));
}

// ── Provider error + fallback ───────────────────────────────────────────────

#[tokio::test]
async fn provider_error_triggers_fallback() {
    let provider = Arc::new(CountingProvider::failing());
    let dir = tempfile::tempdir().unwrap();
    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        deterministic_fallback: true,
        module_path: PathBuf::from("src/m.bock"),
        ..Default::default()
    };
    let driver = AiSynthesisDriver::new(provider, None, Some(manifest), config);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .unwrap();

    assert_eq!(stats.provider_errors, 1);
    assert_eq!(stats.accepted, 0);
    assert_eq!(stats.fallback_triggered, 1);
}

// ── Trivial code never hits AI ──────────────────────────────────────────────

#[tokio::test]
async fn trivial_code_never_hits_ai() {
    let provider = Arc::new(CountingProvider::new(1.0));
    let dir = tempfile::tempdir().unwrap();
    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        module_path: PathBuf::from("src/m.bock"),
        ..Default::default()
    };
    let driver = AiSynthesisDriver::new(provider.clone(), None, Some(manifest), config);

    let module = module_trivial_only();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = driver
        .synthesize_module(&module, &target, &ctx)
        .await
        .unwrap();

    assert_eq!(stats.flagged_nodes, 0);
    assert_eq!(stats.ai_calls, 0);
    assert_eq!(stats.fallback_triggered, 0);
    assert_eq!(provider.calls(), 0, "provider must not be called for literals");
}

// ── Production strictness without pinned decisions ──────────────────────────

#[tokio::test]
async fn production_without_pin_is_unpinned_fallback() {
    let provider = Arc::new(CountingProvider::new(0.99));
    let dir = tempfile::tempdir().unwrap();
    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        confidence_threshold: 0.75,
        deterministic_fallback: true,
        strictness: Strictness::Production,
        auto_pin: false,
        module_path: PathBuf::from("src/m.bock"),
    };
    // No cache — guarantees no pinned decision available.
    let driver = AiSynthesisDriver::new(provider.clone(), None, Some(manifest), config);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .unwrap();

    assert_eq!(stats.production_unpinned, 1);
    assert_eq!(stats.accepted, 0);
    assert_eq!(stats.fallback_triggered, 1);
}

// ── Production strictness WITH pinned decisions ─────────────────────────────

#[tokio::test]
async fn production_with_pinned_decision_replays() {
    let dir = tempfile::tempdir().unwrap();

    // Warm-up: development build populates the cache.
    {
        let provider = Arc::new(CountingProvider::new(0.9));
        let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
        let cache = Some(AiCache::new(dir.path()));
        let config = SynthesisConfig {
            strictness: Strictness::Development,
            module_path: PathBuf::from("src/m.bock"),
            ..Default::default()
        };
        let driver = AiSynthesisDriver::new(provider, cache, Some(manifest), config);
        let module = module_with_match();
        let target = TargetProfile::javascript();
        let ctx = module_ctx("src/m.bock");
        synthesize_and_flush(&driver, &module, &target, &ctx)
            .await
            .unwrap();
    }

    // Production build: cache replay delivers a pinned decision.
    {
        let provider = Arc::new(CountingProvider::new(0.01));
        let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
        let cache = Some(AiCache::new(dir.path()));
        let config = SynthesisConfig {
            strictness: Strictness::Production,
            deterministic_fallback: true,
            module_path: PathBuf::from("src/m.bock"),
            ..Default::default()
        };
        let driver = AiSynthesisDriver::new(provider.clone(), cache, Some(manifest), config);
        let module = module_with_match();
        let target = TargetProfile::javascript();
        let ctx = module_ctx("src/m.bock");

        let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
            .await
            .unwrap();

        assert_eq!(stats.production_unpinned, 0);
        assert_eq!(stats.accepted, 1);
        assert_eq!(stats.cache_hits, 1);
        assert_eq!(provider.calls(), 0, "cache-served pin skips provider");
    }
}

// ── Enum declaration hit ────────────────────────────────────────────────────

#[tokio::test]
async fn enum_flagged_on_js_but_not_rust() {
    let js_provider = Arc::new(CountingProvider::new(0.9));
    let config = SynthesisConfig {
        module_path: PathBuf::from("src/m.bock"),
        ..Default::default()
    };
    let driver = AiSynthesisDriver::new(js_provider.clone(), None, None, config.clone());

    let module = module_with_enum();

    let stats = driver
        .synthesize_module(&module, &TargetProfile::javascript(), &module_ctx("m.bock"))
        .await
        .unwrap();
    assert!(stats.flagged_nodes >= 1, "js flags enum + variant");
    assert!(stats.ai_calls >= 1);

    // Rust — no enum flag.
    let rust_provider = Arc::new(CountingProvider::new(0.9));
    let driver2 = AiSynthesisDriver::new(rust_provider.clone(), None, None, config);
    let stats2 = driver2
        .synthesize_module(&module, &TargetProfile::rust(), &module_ctx("m.bock"))
        .await
        .unwrap();
    // Rust's ai_hints don't include EnumDecl, EnumVariant, or anything else
    // this module uses → no AI calls.
    assert_eq!(stats2.flagged_nodes, 0);
    assert_eq!(stats2.ai_calls, 0);
    assert_eq!(rust_provider.calls(), 0);
}

// ── D.6: rule cache is consulted before AI generation ──────────────────────

#[tokio::test]
async fn rule_cache_hit_skips_ai_and_records_rule_applied() {
    let provider = Arc::new(CountingProvider::new(0.9));
    let dir = tempfile::tempdir().unwrap();

    // Seed the rule cache so Match on JS is served deterministically.
    let rules = RuleCache::new(dir.path());
    let candidate = CandidateRule {
        target_id: "js".into(),
        pattern: "Match → switch".into(),
        template: "switch(x) { /* arms */ }".into(),
        priority: 10,
    };
    let rule = Rule::from_candidate(&candidate, "Match", 0.95);
    rules.insert(&rule).unwrap();

    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        confidence_threshold: 0.75,
        deterministic_fallback: true,
        strictness: Strictness::Development,
        auto_pin: false,
        module_path: PathBuf::from("src/m.bock"),
    };
    let driver = AiSynthesisDriver::new(provider.clone(), None, Some(manifest), config)
        .with_rule_cache(rules);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .unwrap();

    assert_eq!(stats.flagged_nodes, 1);
    assert_eq!(stats.rule_applied, 1, "rule should serve this node");
    assert_eq!(stats.ai_calls, 0, "AI must not be called on rule hit");
    assert_eq!(provider.calls(), 0, "provider untouched");

    // Manifest should have a rule_applied decision, not codegen.
    let file = dir
        .path()
        .join(".bock/decisions/build/src/m.bock.json");
    let content = std::fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("\"rule_applied\""),
        "missing rule_applied entry: {content}"
    );
    assert!(!content.contains("\"codegen\""));
}

#[tokio::test]
async fn rule_cache_miss_still_calls_ai() {
    let provider = Arc::new(CountingProvider::new(0.9));
    let dir = tempfile::tempdir().unwrap();

    // Rule exists but for a different node kind — should miss.
    let rules = RuleCache::new(dir.path());
    let candidate = CandidateRule {
        target_id: "js".into(),
        pattern: "Call".into(),
        template: "call()".into(),
        priority: 1,
    };
    rules
        .insert(&Rule::from_candidate(&candidate, "Call", 0.8))
        .unwrap();

    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        confidence_threshold: 0.75,
        deterministic_fallback: true,
        strictness: Strictness::Development,
        auto_pin: false,
        module_path: PathBuf::from("src/m.bock"),
    };
    let driver = AiSynthesisDriver::new(provider.clone(), None, Some(manifest), config)
        .with_rule_cache(rules);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .unwrap();

    assert_eq!(stats.rule_applied, 0);
    assert_eq!(stats.ai_calls, 1);
    assert_eq!(stats.accepted, 1);
    assert_eq!(provider.calls(), 1);
}

#[tokio::test]
async fn rule_cache_production_requires_pinned_rule() {
    let provider = Arc::new(CountingProvider::new(0.99));
    let dir = tempfile::tempdir().unwrap();

    // Unpinned rule — production should ignore it.
    let rules = RuleCache::new(dir.path());
    let candidate = CandidateRule {
        target_id: "js".into(),
        pattern: "Match".into(),
        template: "switch(x) {}".into(),
        priority: 1,
    };
    rules
        .insert(&Rule::from_candidate(&candidate, "Match", 0.9))
        .unwrap();

    let manifest = Arc::new(Mutex::new(ManifestWriter::new(dir.path())));
    let config = SynthesisConfig {
        confidence_threshold: 0.75,
        deterministic_fallback: true,
        strictness: Strictness::Production,
        auto_pin: false,
        module_path: PathBuf::from("src/m.bock"),
    };
    let driver = AiSynthesisDriver::new(provider.clone(), None, Some(manifest), config)
        .with_rule_cache(rules);

    let module = module_with_match();
    let target = TargetProfile::javascript();
    let ctx = module_ctx("src/m.bock");

    let stats = synthesize_and_flush(&driver, &module, &target, &ctx)
        .await
        .unwrap();

    // Unpinned rule skipped → production without a pinned codegen
    // decision either → unpinned fallback.
    assert_eq!(stats.rule_applied, 0);
    assert_eq!(stats.production_unpinned, 1);
}

// ── Handling block flagged across every target ──────────────────────────────

#[tokio::test]
async fn handling_block_flagged_on_every_target() {
    let module = module_with_handling();
    let ctx = module_ctx("src/m.bock");
    for target in TargetProfile::all_builtins() {
        let provider = Arc::new(CountingProvider::new(0.9));
        let config = SynthesisConfig {
            module_path: PathBuf::from("src/m.bock"),
            ..Default::default()
        };
        let driver = AiSynthesisDriver::new(provider.clone(), None, None, config);
        let stats = driver
            .synthesize_module(&module, &target, &ctx)
            .await
            .unwrap();
        assert!(
            stats.flagged_nodes >= 1,
            "target {} should flag handling block",
            target.id
        );
    }
}