warble-claude-code 0.1.0

Warble back-end for the Claude Code CLI target: IR → static agent files + reference renderer + capability manifest.
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
//! Faithful port of dispatcher/test/renderContract.test.ts and dispatcher/test/claudeCode.test.ts,
//! merged into one file (both suites exercise `emit_claude_code`).

use warble_claude_code::ir::{ComponentNode, WarbleIr};
use warble_claude_code::{
    emit_claude_code, emit_claude_code_with_models, emit_claude_code_with_realization,
    HybridRealization, ModelConfig, RenderFlavor,
};

const RENDER_DEMO_IR: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../examples/render-demo/ir.golden.json"
);
const DEMO_AGENT_IR: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../examples/demo-agent/ir.golden.json"
);
const GENBI_DEFAULT_IR: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../genbi-default/ir.golden.json"
);

fn load_ir(path: &str) -> WarbleIr {
    let raw = std::fs::read_to_string(path).expect("read golden IR fixture");
    serde_json::from_str(&raw).expect("golden IR deserializes")
}

/// A one-component IR carrying only the node with `verb` (mirrors genbi_dispatch_tests.rs's
/// `single` helper, kept local so this file stays self-contained).
fn single_component(ir: &WarbleIr, verb: &str) -> WarbleIr {
    let node = ir
        .components
        .iter()
        .find(|c| c.verb == verb)
        .unwrap_or_else(|| panic!("component '{verb}' in golden"))
        .clone();
    WarbleIr {
        components: vec![node],
        ..ir.clone()
    }
}

/// Split a rendered agent markdown file into (frontmatter YAML, body). Mirrors the TS tests'
/// `splitFrontmatter` regex (`^---\n([\s\S]*?)\n---\n([\s\S]*)$`).
fn split_frontmatter(markdown: &str) -> (String, String) {
    let stripped = markdown
        .strip_prefix("---\n")
        .expect("expected file to start with a YAML frontmatter block");
    let end = stripped
        .find("\n---\n")
        .expect("expected file to start with a YAML frontmatter block");
    let frontmatter = stripped[..end].to_string();
    let body = stripped[end + "\n---\n".len()..].to_string();
    (frontmatter, body)
}

fn parse_frontmatter(yaml: &str) -> serde_json::Value {
    serde_yaml::from_str(yaml).expect("frontmatter parses as YAML")
}

fn has_tool(fm: &serde_json::Value, tool: &str) -> bool {
    fm["tools"]
        .as_array()
        .expect("tools is an array")
        .iter()
        .any(|v| v.as_str() == Some(tool))
}

fn read_json(path: &std::path::Path) -> serde_json::Value {
    serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}

// --- renderContract.test.ts ------------------------------------------------------------------

#[test]
fn render_demo_headless_default_programmatic_dashboard_agent_stays_read_only_and_emits_envelope() {
    let ir = load_ir(RENDER_DEMO_IR);
    let out_dir = tempfile::tempdir().expect("tempdir");

    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let markdown =
        std::fs::read_to_string(out_dir.path().join(".claude/agents/dashboard.md")).unwrap();
    let (frontmatter, body) = split_frontmatter(&markdown);
    let parsed = parse_frontmatter(&frontmatter);
    assert!(
        !has_tool(&parsed, "Write"),
        "programmatic render flavor keeps the agent read-only (no Write)"
    );

    assert!(body.contains("## Render output"));
    assert!(body.contains("kpi_card"));
    assert!(body.contains("table"));
    assert!(body.contains("chart"));
    assert!(
        body.contains("label: string"),
        "block contract must list field types"
    );
    // programmatic: emit an envelope, do NOT write a file
    assert!(body.contains("render envelope"));
    assert!(body.contains("\"blocks\""), "must show the envelope shape");
    assert!(
        !body.contains("dashboard.html"),
        "programmatic path must not tell the agent to write a file"
    );
    assert!(body.to_lowercase().contains("do not write any files"));

    let settings = read_json(&out_dir.path().join(".claude/settings.json"));
    assert!(!has_tool(
        &serde_json::json!({ "tools": settings["permissions"]["allow"] }),
        "Write"
    ));

    // RUN.md documents the two-step programmatic run (agent -> warble-render).
    let run_md = std::fs::read_to_string(out_dir.path().join("RUN.md")).unwrap();
    assert!(run_md.contains("--output-format json"));
    assert!(run_md.contains("warble render"));
}

#[test]
fn render_demo_headless_prompt_flavor_dashboard_agent_gets_write_and_dashboard_html_instruction() {
    let ir = load_ir(RENDER_DEMO_IR);
    let out_dir = tempfile::tempdir().expect("tempdir");

    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Prompt,
    )
    .expect("emit succeeds");

    let markdown =
        std::fs::read_to_string(out_dir.path().join(".claude/agents/dashboard.md")).unwrap();
    let (frontmatter, body) = split_frontmatter(&markdown);
    let parsed = parse_frontmatter(&frontmatter);
    assert!(
        has_tool(&parsed, "Write"),
        "prompt-fallback render-gated agent must get Write"
    );

    assert!(body.contains("## Render output"));
    assert!(
        body.contains("label: string"),
        "block contract must list field types"
    );
    assert!(body.contains("dashboard.html"));

    let settings = read_json(&out_dir.path().join(".claude/settings.json"));
    assert!(has_tool(
        &serde_json::json!({ "tools": settings["permissions"]["allow"] }),
        "Write"
    ));
}

#[test]
fn render_demo_interactive_dashboard_agent_gets_no_write_and_a_markdown_degrade_instruction() {
    let ir = load_ir(RENDER_DEMO_IR);
    let out_dir = tempfile::tempdir().expect("tempdir");

    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:interactive",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let markdown =
        std::fs::read_to_string(out_dir.path().join(".claude/agents/dashboard.md")).unwrap();
    let (frontmatter, body) = split_frontmatter(&markdown);
    let parsed = parse_frontmatter(&frontmatter);
    assert!(
        !has_tool(&parsed, "Write"),
        "interactive degrade path must not get Write"
    );

    assert!(body.contains("## Render output"));
    assert!(body.to_lowercase().contains("markdown"));
    assert!(
        !body.contains("dashboard.html"),
        "degrade path must not instruct writing a file"
    );

    let settings = read_json(&out_dir.path().join(".claude/settings.json"));
    assert!(!has_tool(
        &serde_json::json!({ "tools": settings["permissions"]["allow"] }),
        "Write"
    ));
}

#[test]
fn demo_agent_generate_dashboard_no_artifact_write_driver_gets_no_write_no_render_section() {
    let ir = load_ir(DEMO_AGENT_IR);
    let out_dir = tempfile::tempdir().expect("tempdir");

    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let driver_markdown =
        std::fs::read_to_string(out_dir.path().join(".claude/agents/generate_dashboard.md"))
            .unwrap();
    let (frontmatter, body) = split_frontmatter(&driver_markdown);
    let parsed = parse_frontmatter(&frontmatter);
    assert!(
        !has_tool(&parsed, "Write"),
        "component with no artifact_write must not get Write"
    );
    assert!(
        !body.contains("## Render output"),
        "no render section without artifact_write"
    );
    // JS-specific footgun ([object Object] from stringifying an unstringified object) cannot
    // occur in Rust's typed serialization; assert the description is a sensible non-empty string
    // instead, as the closest meaningful equivalent.
    let description = parsed["description"]
        .as_str()
        .expect("description is a string");
    assert!(!description.is_empty());
    assert!(!description.contains("[object Object]"));
}

/// The `[object Object]` bug lived in `buildDescription`, which only the single-agent (non-split)
/// path calls (`buildAgentMarkdown`) — demo-agent's golden IR is per-step-tier split, so its
/// driver description never touched `render_blocks` even before the fix. Exercise the
/// single-agent path directly (demo-agent's node collapsed to one tier, matching the existing
/// "single-tier" test pattern) to prove the typed-block description fix.
#[test]
fn single_agent_path_description_uses_typed_render_block_type_names_not_object_object() {
    let ir = load_ir(DEMO_AGENT_IR);
    let node = &ir.components[0];
    let mut single_tier_node = node.clone();
    for call in &mut single_tier_node.llm_calls {
        call.tier = "cheap".to_string();
    }
    let single_tier_ir = WarbleIr {
        components: vec![single_tier_node],
        ..ir.clone()
    };

    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &single_tier_ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let markdown =
        std::fs::read_to_string(out_dir.path().join(".claude/agents/generate_dashboard.md"))
            .unwrap();
    let (frontmatter, body) = split_frontmatter(&markdown);
    let parsed = parse_frontmatter(&frontmatter);

    let description = parsed["description"]
        .as_str()
        .expect("description is a string");
    assert!(!description.contains("[object Object]"));
    assert!(description.contains("chart"));
    assert!(description.contains("table"));
    assert!(description.contains("kpi_card"));
    assert!(
        !has_tool(&parsed, "Write"),
        "no artifact_write guardrail -> no Write"
    );
    assert!(
        !body.contains("## Render output"),
        "no render section without artifact_write"
    );
}

// --- claudeCode.test.ts -----------------------------------------------------------------------

/// Golden IR with both llm_calls collapsed to the same tier — no split needed.
fn make_single_tier_ir(ir: &WarbleIr) -> WarbleIr {
    let node = &ir.components[0];
    let mut new_node = node.clone();
    for call in &mut new_node.llm_calls {
        call.tier = "cheap".to_string();
    }
    WarbleIr {
        components: vec![new_node],
        ..ir.clone()
    }
}

#[test]
fn claude_code_target_splits_per_step_tiers_into_a_driver_plus_one_subagent_per_step() {
    let ir = load_ir(DEMO_AGENT_IR);
    let node = &ir.components[0];
    assert_eq!(node.verb, "generate_dashboard");
    assert!(node
        .required_capabilities
        .iter()
        .any(|c| c == "llm:per_step_tier"));
    let distinct_tiers: std::collections::HashSet<_> =
        node.llm_calls.iter().map(|c| c.tier.clone()).collect();
    assert!(distinct_tiers.len() > 1);

    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let agents_dir = out_dir.path().join(".claude/agents");
    let mut files: Vec<String> = std::fs::read_dir(&agents_dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
        .collect();
    files.sort();
    assert_eq!(
        files,
        vec![
            "generate_dashboard.md".to_string(),
            "generate_dashboard__compose_layout.md".to_string(),
            "generate_dashboard__plan_dashboard.md".to_string(),
        ]
    );

    // Driver
    let driver_md = std::fs::read_to_string(agents_dir.join("generate_dashboard.md")).unwrap();
    let (driver_fm, driver_body) = split_frontmatter(&driver_md);
    let driver = parse_frontmatter(&driver_fm);
    assert_eq!(driver["name"].as_str().unwrap(), "generate_dashboard");
    assert_eq!(driver["model"].as_str().unwrap(), "sonnet");
    assert!(has_tool(&driver, "Task"));
    assert!(has_tool(&driver, "Read"));
    assert!(
        driver_body.contains("plan_dashboard"),
        "driver body must mention the plan step"
    );
    assert!(
        driver_body.contains("compose_layout"),
        "driver body must mention the compose step"
    );
    assert!(
        driver_body.contains("query_plan"),
        "driver body must wire query_plan from plan_dashboard into compose_layout"
    );

    // plan_dashboard subagent (strong tier -> opus)
    let plan_md =
        std::fs::read_to_string(agents_dir.join("generate_dashboard__plan_dashboard.md")).unwrap();
    let (plan_fm, plan_body) = split_frontmatter(&plan_md);
    let plan = parse_frontmatter(&plan_fm);
    assert_eq!(
        plan["name"].as_str().unwrap(),
        "generate_dashboard__plan_dashboard"
    );
    assert_eq!(plan["model"].as_str().unwrap(), "opus");
    assert!(has_tool(&plan, "Bash(wren:*)"));
    assert!(!has_tool(&plan, "Write"));
    assert!(!has_tool(&plan, "Edit"));
    assert!(plan_body.contains(&node.llm_calls[0].prompt));

    // compose_layout subagent (cheap tier -> haiku)
    let compose_md =
        std::fs::read_to_string(agents_dir.join("generate_dashboard__compose_layout.md")).unwrap();
    let (compose_fm, compose_body) = split_frontmatter(&compose_md);
    let compose = parse_frontmatter(&compose_fm);
    assert_eq!(
        compose["name"].as_str().unwrap(),
        "generate_dashboard__compose_layout"
    );
    assert_eq!(compose["model"].as_str().unwrap(), "haiku");
    assert!(has_tool(&compose, "Bash(wren:*)"));
    assert!(!has_tool(&compose, "Write"));
    assert!(!has_tool(&compose, "Edit"));
    assert!(compose_body.contains(&node.llm_calls[1].prompt));

    // .claude/settings.json (not repo-root settings.json) for the split shape
    let settings = read_json(&out_dir.path().join(".claude/settings.json"));
    let allow = settings["permissions"]["allow"].as_array().unwrap();
    let allow_has = |t: &str| allow.iter().any(|v| v.as_str() == Some(t));
    assert!(allow_has("Task"));
    assert!(allow_has("Read"));
    assert!(allow_has("Bash(wren:*)"));
    let deny = settings["permissions"]["deny"].as_array();
    assert!(deny
        .map(|d| d.iter().any(|v| v.as_str() == Some("Bash(rm:*)")))
        .unwrap_or(false));

    let run_md = std::fs::read_to_string(out_dir.path().join("RUN.md")).unwrap();
    assert!(run_md.contains("--agent generate_dashboard"));
    assert!(run_md.contains("generate_dashboard__plan_dashboard"));
    assert!(run_md.contains("generate_dashboard__compose_layout"));
}

#[test]
fn a_single_tier_skill_still_produces_one_agent_v0_1_shape_unchanged() {
    let golden_ir = load_ir(DEMO_AGENT_IR);
    let ir = make_single_tier_ir(&golden_ir);
    let node = &ir.components[0];

    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let agents_dir = out_dir.path().join(".claude/agents");
    let files: Vec<String> = std::fs::read_dir(&agents_dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
        .collect();
    assert_eq!(files, vec!["generate_dashboard.md".to_string()]);

    let markdown = std::fs::read_to_string(agents_dir.join("generate_dashboard.md")).unwrap();
    let (frontmatter, body) = split_frontmatter(&markdown);
    let parsed = parse_frontmatter(&frontmatter);
    assert_eq!(parsed["name"].as_str().unwrap(), "generate_dashboard");
    assert_eq!(parsed["model"].as_str().unwrap(), "haiku");
    assert!(has_tool(&parsed, "Bash(wren:*)"));
    assert!(!has_tool(&parsed, "Write"));
    assert!(!has_tool(&parsed, "Edit"));
    assert!(body.contains(&node.prompt_fragment));

    // P1 (unified): the single-agent path now also writes `.claude/settings.json` (was out-root).
    let settings = read_json(&out_dir.path().join(".claude/settings.json"));
    let allow = settings["permissions"]["allow"].as_array().unwrap();
    assert!(allow.iter().any(|v| v.as_str() == Some("Bash(wren:*)")));
    let deny = settings["permissions"]["deny"].as_array();
    assert!(deny
        .map(|d| d.iter().any(|v| v.as_str() == Some("Bash(rm:*)")))
        .unwrap_or(false));
}

#[test]
fn claude_code_target_emits_a_valid_wren_config_json_with_strict_mode_enabled() {
    let ir = load_ir(DEMO_AGENT_IR);
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");
    let parsed = read_json(&out_dir.path().join(".wren/config.json"));
    assert!(parsed["strict_mode"].as_bool().unwrap());
    assert!(parsed["denied_functions"]
        .as_array()
        .unwrap()
        .iter()
        .any(|v| v.as_str() == Some("pg_read_file")));
}

#[test]
fn claude_code_target_emits_run_md_with_the_headless_invocation_command() {
    let ir = load_ir(DEMO_AGENT_IR);
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");
    let run_md = std::fs::read_to_string(out_dir.path().join("RUN.md")).unwrap();
    assert!(run_md.contains("--agent generate_dashboard"));
    assert!(run_md.contains(&ir.components[0].context_binding.project));
}

fn with_component(ir: &WarbleIr, mutate: impl FnOnce(ComponentNode) -> ComponentNode) -> WarbleIr {
    WarbleIr {
        components: vec![mutate(ir.components[0].clone())],
        ..ir.clone()
    }
}

type IrMutator = fn(&WarbleIr) -> WarbleIr;

/// Every not-yet-implemented IR arm must loud-fail rather than silently emit a wrong agent.
/// Handler-level arms (realization_kind / trigger.kind / outcome.kind) fail at the claude-code file
/// target's dispatch check ("wall-hit"). As of +Assertive, `tool`/`scheduled`/`assertion` are
/// realized; as of +Mutating, `gated-tool`/`mutation` are realized too (see the positive tests
/// below). What remains are the +Orchestrating arms plus the `event` *trigger* (activation by an
/// inbound event — a distinct handler from emitting one).
fn handler_wall_hit_cases() -> Vec<(&'static str, IrMutator)> {
    fn trigger_event(ir: &WarbleIr) -> WarbleIr {
        with_component(ir, |mut c| {
            c.trigger.kind = warble_claude_code::ir::TriggerKind::Event;
            c
        })
    }
    fn outcome_dispatch(ir: &WarbleIr) -> WarbleIr {
        with_component(ir, |mut c| {
            c.effect.outcome.kind = warble_claude_code::ir::OutcomeKind::Dispatch;
            c
        })
    }
    vec![
        ("trigger.kind=event", trigger_event),
        ("outcome=dispatch", outcome_dispatch),
    ]
}

#[test]
fn unimplemented_handler_arms_loud_fail_at_the_file_target_instead_of_emitting() {
    let golden = load_ir(DEMO_AGENT_IR);
    for (label, mutate) in handler_wall_hit_cases() {
        let ir = mutate(&golden);
        let out_dir = tempfile::tempdir().expect("tempdir");
        let err = emit_claude_code(
            &ir,
            out_dir.path(),
            "claude-code:headless",
            RenderFlavor::Programmatic,
        )
        .unwrap_err();
        assert!(
            err.0
                .contains("is not supported by the claude-code file target (wall-hit)"),
            "case '{label}': unexpected error message: {}",
            err.0
        );
        let files: Vec<_> = std::fs::read_dir(out_dir.path()).unwrap().collect();
        assert!(
            files.is_empty(),
            "case '{label}': must write nothing on a wall-hit"
        );
    }
}

/// Turn demo-agent's node into a minimal +Assertive shape (tool · scheduled · assertion), the way
/// `monitor_freshness` is structured, so the realized handlers can be exercised at the emit level
/// without the full authored component (that is covered end-to-end by the monitor-agent golden).
fn make_assertive_ir(golden: &WarbleIr) -> WarbleIr {
    with_component(golden, |mut c| {
        c.realization_kind = warble_claude_code::ir::RealizationKind::Tool;
        c.trigger.kind = warble_claude_code::ir::TriggerKind::Scheduled;
        c.effect.outcome.kind = warble_claude_code::ir::OutcomeKind::Assertion;
        c.effect.outcome.verdict_type = Some("freshness_verdict".to_string());
        c.effect.outcome.emits = Some(vec!["freshness_breach".to_string()]);
        // A pure assertion: no render/artifact-write path, just the status verdict facet.
        c.effect.render_blocks = vec![warble_claude_code::ir::RenderBlock {
            block_type: "status".to_string(),
            fields: std::collections::BTreeMap::new(),
        }];
        c.guardrails.retain(|g| g.name != "artifact_write");
        c.required_capabilities
            .retain(|cap| cap != "artifact_write" && cap != "render_contract");
        c.required_capabilities.push("scheduler".to_string());
        c.required_capabilities.push("notify_channel".to_string());
        c.borrowed_actions = vec!["notify_slack".to_string(), "open_ticket".to_string()];
        // Single tier so it takes the single-agent path (no per-step split), like monitor_freshness.
        for call in &mut c.llm_calls {
            call.tier = "cheap".to_string();
        }
        c.required_capabilities
            .retain(|cap| cap != "llm:per_step_tier");
        c
    })
}

#[test]
fn assertive_arms_tool_scheduled_assertion_emit_cleanly_and_stay_read_only() {
    let ir = make_assertive_ir(&load_ir(DEMO_AGENT_IR));
    let node = &ir.components[0];
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("the +Assertive arms (tool · scheduled · assertion) must dispatch, not wall-hit");

    let md = std::fs::read_to_string(
        out_dir
            .path()
            .join(format!(".claude/agents/{}.md", node.verb)),
    )
    .unwrap();
    let (frontmatter, body) = split_frontmatter(&md);
    let parsed = parse_frontmatter(&frontmatter);
    // Read-only assertion: no Write / Edit.
    assert!(
        !has_tool(&parsed, "Write"),
        "assertion is read-only: no Write"
    );
    assert!(
        !has_tool(&parsed, "Edit"),
        "assertion is read-only: no Edit"
    );
    // The assertion section carries the deterministic-assert contract + verdict_type + emit.
    assert!(body.contains("## Assertion output"));
    assert!(body.contains("freshness_verdict"), "names the verdict_type");
    assert!(
        body.contains("DETERMINISTIC"),
        "core assert is deterministic SQL, not an LLM call"
    );
    assert!(
        body.contains("freshness_breach"),
        "lists the emitted signal"
    );
    assert!(
        body.contains("notify_slack") || body.contains("open_ticket"),
        "names the borrowed on-breach actions"
    );

    // Capability report: the borrowed transports resolve realize-via, nothing fails.
    let cap: serde_json::Value = read_json(&out_dir.path().join("capability-report.json"));
    let caps = cap["components"][0]["capabilities"].as_array().unwrap();
    let outcome_of = |name: &str| {
        caps.iter()
            .find(|c| c["capability"] == name)
            .unwrap_or_else(|| panic!("capability '{name}' present in report"))["outcome"]
            .as_str()
            .unwrap()
            .to_string()
    };
    assert_eq!(outcome_of("scheduler"), "realize-via");
    assert_eq!(
        outcome_of("event_bus"),
        "realize-via",
        "emits implies event_bus (borrowed)"
    );
    assert_eq!(outcome_of("notify_channel"), "realize-via");
    assert!(caps
        .iter()
        .all(|c| c["outcome"].as_str().unwrap() != "fail"));

    // RUN.md documents the scheduled cron wiring + the verdict two-step.
    let run_md = std::fs::read_to_string(out_dir.path().join("RUN.md")).unwrap();
    assert!(
        run_md.contains("scheduler"),
        "RUN.md names the borrowed scheduler"
    );
    assert!(
        run_md.contains("verdict.json"),
        "RUN.md shows the verdict capture step"
    );
}

/// Turn demo-agent's node into a minimal +Mutating shape (gated-tool · one_shot · mutation), the
/// way a schema-migration component is structured: a proposed change to a `target`, gated on a
/// dry-run, a blast-radius check, and human approval before anything is applied. `human_approval`
/// and `blast_radius` are *declared* capabilities here (not shape-implied — see `resolve.rs`'s
/// `implied_capabilities`), and the fine-grained `context_binding.resolved` lets `blast_radius`
/// resolve natively rather than loud-failing on a coarse binding.
fn make_mutating_ir(golden: &WarbleIr) -> WarbleIr {
    with_component(golden, |mut c| {
        c.realization_kind = warble_claude_code::ir::RealizationKind::GatedTool;
        c.effect.outcome.kind = warble_claude_code::ir::OutcomeKind::Mutation;
        c.effect.outcome.target = Some("models/orders.yml".to_string());
        c.effect.outcome.change_type = Some("schema_migration".to_string());
        c.context_binding.resolved = Some(serde_json::json!({ "lineage": { "resolvable": true } }));
        // A mutating component is not read-only: drop the base guardrail so Edit/Write are granted.
        c.guardrails.retain(|g| g.name != "read_only_execution");
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "must_dry_run".to_string(),
            locked: true,
            scope: None,
            threshold: None,
        });
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "blast_radius_limit".to_string(),
            locked: true,
            scope: None,
            threshold: Some(serde_json::json!(5)),
        });
        c.required_capabilities.push("human_approval".to_string());
        c.required_capabilities.push("blast_radius".to_string());
        // Single tier so it takes the single-agent path (no per-step split), like monitor_freshness.
        for call in &mut c.llm_calls {
            call.tier = "cheap".to_string();
        }
        c.required_capabilities
            .retain(|cap| cap != "llm:per_step_tier");
        c
    })
}

#[test]
fn mutating_arms_gated_tool_mutation_emit_the_lifecycle_on_interactive() {
    let ir = make_mutating_ir(&load_ir(DEMO_AGENT_IR));
    let node = &ir.components[0];
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:interactive",
        RenderFlavor::Programmatic,
    )
    .expect(
        "the +Mutating arms (gated-tool · mutation) must dispatch on interactive, not wall-hit",
    );

    let md = std::fs::read_to_string(
        out_dir
            .path()
            .join(format!(".claude/agents/{}.md", node.verb)),
    )
    .unwrap();
    let (frontmatter, body) = split_frontmatter(&md);
    let parsed = parse_frontmatter(&frontmatter);

    assert!(
        has_tool(&parsed, "Edit"),
        "mutating component must get Edit"
    );
    assert!(
        has_tool(&parsed, "Write"),
        "mutating component must get Write"
    );
    assert!(
        has_tool(&parsed, "Bash(warble:*)"),
        "mutating component must get the blast-radius gate CLI"
    );
    assert!(
        has_tool(&parsed, "Bash(wren:*)"),
        "mutating component needs wren to analyze the target before proposing a diff"
    );

    assert!(body.contains("## Mutation lifecycle"));
    let lower = body.to_lowercase();
    assert!(lower.contains("dry-run"), "names the dry-run phase");
    assert!(lower.contains("blast"), "names the blast-radius gate");
    assert!(lower.contains("approval"), "names human approval");
    assert!(
        lower.contains("rollback"),
        "names the rollback (borrowed from git)"
    );
    assert!(
        body.contains(r#""type": "diff""#),
        "shows the diff render-block envelope example"
    );

    let cap: serde_json::Value = read_json(&out_dir.path().join("capability-report.json"));
    let caps = cap["components"][0]["capabilities"].as_array().unwrap();
    let outcome_of = |name: &str| {
        caps.iter()
            .find(|c| c["capability"] == name)
            .unwrap_or_else(|| panic!("capability '{name}' present in report"))["outcome"]
            .as_str()
            .unwrap()
            .to_string()
    };
    assert_eq!(
        outcome_of("write_authz"),
        "realize-via",
        "write_authz is shape-implied by outcome=mutation"
    );
    assert_eq!(
        outcome_of("version_control"),
        "realize-via",
        "version_control (git) is shape-implied by outcome=mutation"
    );
    assert_eq!(
        outcome_of("human_approval"),
        "native",
        "human_approval resolves natively on interactive"
    );
    assert_eq!(
        outcome_of("blast_radius"),
        "native",
        "fine-grained binding lets blast_radius resolve natively"
    );
    assert!(caps
        .iter()
        .all(|c| c["outcome"].as_str().unwrap() != "fail"));

    let run_md = std::fs::read_to_string(out_dir.path().join("RUN.md")).unwrap();
    assert!(
        run_md.contains("blast-radius"),
        "RUN.md documents the blast-radius gate step"
    );
}

#[test]
fn mutating_component_loud_fails_on_headless_due_to_human_approval() {
    let ir = make_mutating_ir(&load_ir(DEMO_AGENT_IR));
    let out_dir = tempfile::tempdir().expect("tempdir");
    let err = emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .unwrap_err();
    assert!(
        err.0
            .contains("human_approval: fail on claude-code:headless"),
        "unexpected error message: {}",
        err.0
    );
    let files: Vec<_> = std::fs::read_dir(out_dir.path()).unwrap().collect();
    assert!(
        files.is_empty(),
        "no files should be emitted when resolution aborts"
    );
}

/// Turn demo-agent's node into a minimal +Constitutive shape (gated-tool · one_shot · mutation,
/// `target: "context"`), the way a `bootstrap_mdl` component is structured: proposing a change to
/// the semantic model/knowledge structure itself (models/metrics/knowledge), gated on a dry-run and
/// human approval, but scoped by `context_write_authz` (a path authorization) rather than
/// `blast_radius` (a downstream-lineage computation) — +Constitutive reuses the same `mutation`
/// outcome arm as +Mutating (see `make_mutating_ir`), differentiated purely by `outcome.target`.
fn make_constitutive_ir(golden: &WarbleIr) -> WarbleIr {
    with_component(golden, |mut c| {
        c.realization_kind = warble_claude_code::ir::RealizationKind::GatedTool;
        c.effect.outcome.kind = warble_claude_code::ir::OutcomeKind::Mutation;
        c.effect.outcome.target = Some("context".to_string());
        c.effect.outcome.change_type = Some("mdl_bootstrap".to_string());
        // A constitutive component is not read-only: drop the base guardrail so Edit/Write are
        // granted.
        c.guardrails.retain(|g| g.name != "read_only_execution");
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "context_write_authz".to_string(),
            locked: true,
            scope: Some("models/".to_string()),
            threshold: None,
        });
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "must_dry_run".to_string(),
            locked: true,
            scope: None,
            threshold: None,
        });
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "human_approval".to_string(),
            locked: true,
            scope: None,
            threshold: None,
        });
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "no_silent_overwrite".to_string(),
            locked: true,
            scope: None,
            threshold: None,
        });
        c.guardrails.push(warble_claude_code::ir::Guardrail {
            name: "rollback_available".to_string(),
            locked: true,
            scope: None,
            threshold: None,
        });
        c.required_capabilities
            .push("schema_introspection".to_string());
        c.required_capabilities
            .push("context_write_authz".to_string());
        c.required_capabilities.push("version_control".to_string());
        c.required_capabilities.push("human_approval".to_string());
        // No `blast_radius` / `blast_radius_limit` anywhere: this path is never gated by blast
        // radius — only the scoped context-write authorization above.
        // Single tier so it takes the single-agent path (no per-step split), like monitor_freshness.
        for call in &mut c.llm_calls {
            call.tier = "cheap".to_string();
        }
        c.required_capabilities
            .retain(|cap| cap != "llm:per_step_tier");
        c
    })
}

#[test]
fn constitutive_arms_gated_tool_context_mutation_emit_cleanly_on_interactive() {
    let ir = make_constitutive_ir(&load_ir(DEMO_AGENT_IR));
    let node = &ir.components[0];
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:interactive",
        RenderFlavor::Programmatic,
    )
    .expect(
        "the +Constitutive arm (gated-tool · mutation · target=context) must dispatch on \
interactive, not wall-hit",
    );

    let md = std::fs::read_to_string(
        out_dir
            .path()
            .join(format!(".claude/agents/{}.md", node.verb)),
    )
    .unwrap();
    let (frontmatter, body) = split_frontmatter(&md);
    let parsed = parse_frontmatter(&frontmatter);

    assert!(
        has_tool(&parsed, "Edit"),
        "constitutive component must get Edit"
    );
    assert!(
        has_tool(&parsed, "Write"),
        "constitutive component must get Write"
    );
    assert!(
        has_tool(&parsed, "Bash(wren:*)"),
        "constitutive component needs wren for schema_introspection"
    );
    assert!(
        !has_tool(&parsed, "Bash(warble:*)"),
        "constitutive component is not gated by blast-radius: no warble CLI grant"
    );

    assert!(body.contains("## Mutation lifecycle"));
    let lower = body.to_lowercase();
    assert!(lower.contains("dry-run"), "names the dry-run phase");
    assert!(lower.contains("approval"), "names human approval");
    assert!(
        lower.contains("rollback"),
        "names the rollback (borrowed from git)"
    );
    assert!(lower.contains("diff"), "names the diff envelope");
    assert!(lower.contains("context"), "names the context target");
    assert!(
        body.contains("models/"),
        "names the context_write_authz scope"
    );
    assert!(
        !lower.contains("blast"),
        "constitutive mutation section must never mention blast-radius"
    );
    assert!(
        body.contains(r#""type": "diff""#),
        "shows the diff render-block envelope example"
    );

    let settings = read_json(&out_dir.path().join(".claude/settings.json"));
    let allow = settings["permissions"]["allow"].as_array().unwrap();
    let allow_has = |t: &str| allow.iter().any(|v| v.as_str() == Some(t));
    assert!(allow_has("Edit"));
    assert!(allow_has("Write"));
    assert!(allow_has("Bash(wren:*)"));
    assert!(
        !allow_has("Bash(warble:*)"),
        "settings must not grant the blast-radius CLI to a constitutive component"
    );

    let cap: serde_json::Value = read_json(&out_dir.path().join("capability-report.json"));
    let caps = cap["components"][0]["capabilities"].as_array().unwrap();
    let outcome_of = |name: &str| {
        caps.iter()
            .find(|c| c["capability"] == name)
            .unwrap_or_else(|| panic!("capability '{name}' present in report"))["outcome"]
            .as_str()
            .unwrap()
            .to_string()
    };
    assert_eq!(
        outcome_of("context_write_authz"),
        "realize-via",
        "context_write_authz is shape-implied by outcome=mutation, target=context"
    );
    assert_eq!(
        outcome_of("version_control"),
        "realize-via",
        "version_control (git) is shape-implied by outcome=mutation"
    );
    assert_eq!(
        outcome_of("schema_introspection"),
        "realize-via",
        "schema_introspection resolves via the wren CLI"
    );
    assert_eq!(
        outcome_of("human_approval"),
        "native",
        "human_approval resolves natively on interactive"
    );
    assert!(
        caps.iter().all(|c| c["capability"] != "write_authz"),
        "target=context must use context_write_authz, never write_authz (scopes must not cross)"
    );
    assert!(caps
        .iter()
        .all(|c| c["outcome"].as_str().unwrap() != "fail"));
}

#[test]
fn constitutive_component_loud_fails_on_headless_due_to_human_approval() {
    let ir = make_constitutive_ir(&load_ir(DEMO_AGENT_IR));
    let out_dir = tempfile::tempdir().expect("tempdir");
    let err = emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .unwrap_err();
    assert!(
        err.0
            .contains("human_approval: fail on claude-code:headless"),
        "unexpected error message: {}",
        err.0
    );
    let files: Vec<_> = std::fs::read_dir(out_dir.path()).unwrap().collect();
    assert!(
        files.is_empty(),
        "no files should be emitted when resolution aborts"
    );
}

// --- Phase 1.3: hero render contract (verified facet + definition block + explicit verify gate) ---

/// `generate_dashboard`'s locked render contract (genbi-default) must list the `definition` block
/// and its driver body must carry the shared verify+definition contract text verbatim, including the
/// `"verified": true` envelope example — the same wording asserted in render_tests.rs for the HTML
/// side of this contract.
#[test]
fn genbi_default_generate_dashboard_driver_lists_definition_block_and_verify_contract() {
    let ir = single_component(&load_ir(GENBI_DEFAULT_IR), "generate_dashboard");
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let driver_md =
        std::fs::read_to_string(out_dir.path().join(".claude/agents/generate_dashboard.md"))
            .unwrap();
    let (_, body) = split_frontmatter(&driver_md);

    assert!(
        body.contains("`definition`"),
        "render section must list a `definition` block line"
    );
    assert!(
        body.contains("per-answer verify"),
        "body must carry the per-answer verify wording"
    );
    assert!(
        body.contains("REFUSE"),
        "body must carry the refuse path wording"
    );
    assert!(
        body.contains("\"verified\": true"),
        "envelope example must show the verified facet"
    );
}

/// `answer_query`'s 3-step split makes the deterministic verify gate explicit in the subagent
/// bodies (the split path folds each step's prompt verbatim into its own subagent file): the
/// `generate_sql` step names the gate and asks the agent to verify the result set, and the
/// `repair_sql` step carries the REFUSE path when the result still cannot be validated.
#[test]
fn genbi_default_answer_query_subagents_make_the_deterministic_gate_explicit() {
    let ir = single_component(&load_ir(GENBI_DEFAULT_IR), "answer_query");
    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    let generate_sql_md = std::fs::read_to_string(
        out_dir
            .path()
            .join(".claude/agents/answer_query__generate_sql.md"),
    )
    .unwrap();
    assert!(
        generate_sql_md.contains("deterministic gate"),
        "generate_sql step must name the deterministic gate"
    );
    assert!(
        generate_sql_md.contains("Verify the result set"),
        "generate_sql step must ask the agent to verify the result set"
    );

    let repair_sql_md = std::fs::read_to_string(
        out_dir
            .path()
            .join(".claude/agents/answer_query__repair_sql.md"),
    )
    .unwrap();
    assert!(
        repair_sql_md.contains("REFUSE"),
        "repair_sql step must carry the refuse path when validation still fails"
    );
}

/// P1: the single-agent (non-split) emit path writes its settings to
/// `.claude/settings.json` — the same location the split path already used — and must NOT write a
/// root-level `settings.json` (that was the pre-fix location).
#[test]
fn single_agent_path_writes_dotclaude_settings_and_not_a_root_settings_file() {
    let golden_ir = load_ir(DEMO_AGENT_IR);
    let ir = make_single_tier_ir(&golden_ir);

    let out_dir = tempfile::tempdir().expect("tempdir");
    emit_claude_code(
        &ir,
        out_dir.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
    )
    .expect("emit succeeds");

    assert!(
        out_dir.path().join(".claude/settings.json").exists(),
        "single-agent path must write .claude/settings.json"
    );
    assert!(
        !out_dir.path().join("settings.json").exists(),
        "single-agent path must NOT write a root-level settings.json"
    );
}

// --- hybrid: llm:per_step_provider on the file target (bash-script realization) -------------------

const HYBRID_CFG: &str = "tiers:\n  strong: opus\n  cheap:\n    provider: openai_compat\n    endpoint: http://localhost:11434/v1\n    model: qwen2.5\n  orchestrator: sonnet\n";

#[test]
fn non_anthropic_provider_binding_emits_bash_script_hybrid_on_file_target() {
    // The file target now realizes llm:per_step_provider via bash-script: the LOCAL step becomes an
    // emitted local-inference script the driver runs through Bash; the cloud steps stay the driver's
    // own work. It must NOT loud-fail, and must NOT put the local model in an agent's frontmatter.
    let ir = single_component(&load_ir(GENBI_DEFAULT_IR), "answer_query");
    let models = ModelConfig::from_yaml(HYBRID_CFG).expect("parse hybrid config");
    let out = tempfile::tempdir().expect("tempdir");
    emit_claude_code_with_models(
        &ir,
        out.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
        &models,
    )
    .expect("hybrid bash-script emit succeeds on the file target");

    // Local-inference script + its system prompt + a wrapper for the local step are emitted.
    assert!(out.path().join("scripts/local_infer.py").is_file());
    assert!(out
        .path()
        .join("scripts/answer_query__resolve_intent.sh")
        .is_file());
    assert!(out
        .path()
        .join("scripts/answer_query__resolve_intent.system.txt")
        .is_file());

    let driver =
        std::fs::read_to_string(out.path().join(".claude/agents/answer_query.md")).unwrap();
    let (frontmatter, body) = split_frontmatter(&driver);
    // Driver runs on the cloud (strong) model; the local model must NOT leak into frontmatter.
    assert!(
        frontmatter.contains("model: opus"),
        "driver hosts on the cloud tier"
    );
    assert!(
        !driver.contains("model: qwen2.5"),
        "local model must not be a frontmatter model"
    );
    // Local step routed to the script; cloud steps done by the driver itself.
    assert!(body.contains("resolve_intent` — runs on a LOCAL model"));
    assert!(body.contains("answer_query__resolve_intent.sh"));
    assert!(body.contains("generate_sql` — you do this yourself"));

    // Settings allow bash (to run the wrapper) + wren, and keep the destructive-bash denials.
    let settings = read_json(&out.path().join(".claude/settings.json"));
    let allow = &settings["permissions"]["allow"];
    assert!(allow
        .as_array()
        .unwrap()
        .iter()
        .any(|v| v.as_str() == Some("Bash(bash:*)")));
    assert!(allow
        .as_array()
        .unwrap()
        .iter()
        .any(|v| v.as_str() == Some("Bash(wren:*)")));
}

#[test]
fn all_anthropic_string_binding_passes_the_provider_gate() {
    // The M3 proxy path: `cheap` bound to a bare model name (provider defaults to anthropic) must NOT
    // trip the gate — Warble sees all-anthropic; a proxy does name-based routing invisibly.
    let ir = single_component(&load_ir(GENBI_DEFAULT_IR), "answer_query");
    let models = ModelConfig::from_yaml(
        "tiers:\n  strong: opus\n  cheap: qwen2.5\n  orchestrator: sonnet\n",
    )
    .expect("parse");
    let out = std::env::temp_dir().join("warble-emit-gate-ok");
    let res = emit_claude_code_with_models(
        &ir,
        &out,
        "claude-code:headless",
        RenderFlavor::Programmatic,
        &models,
    );
    assert!(
        res.is_ok(),
        "all-anthropic (string) binding passes the gate: {:?}",
        res.err()
    );
}

#[test]
fn mcp_server_realization_emits_mcp_config_and_no_bash_widening() {
    let ir = single_component(&load_ir(GENBI_DEFAULT_IR), "answer_query");
    let models = ModelConfig::from_yaml(HYBRID_CFG).expect("parse hybrid config");
    let out = tempfile::tempdir().expect("tempdir");
    emit_claude_code_with_realization(
        &ir,
        out.path(),
        "claude-code:headless",
        RenderFlavor::Programmatic,
        &models,
        HybridRealization::McpServer,
    )
    .expect("mcp-server hybrid emit succeeds");

    // .mcp.json registers `warble mcp-serve`; mcp-steps.json carries the local binding.
    let mcp = read_json(&out.path().join(".mcp.json"));
    let args = mcp["mcpServers"]["warble"]["args"].as_array().unwrap();
    assert!(args.iter().any(|v| v.as_str() == Some("mcp-serve")));
    let steps = read_json(&out.path().join("mcp-steps.json"));
    assert_eq!(steps["steps"]["resolve_intent"]["model"], "qwen2.5");
    assert_eq!(
        steps["steps"]["resolve_intent"]["endpoint"],
        "http://localhost:11434/v1"
    );

    // Driver calls the MCP tool for the local step; settings allow it and do NOT widen bash.
    let driver =
        std::fs::read_to_string(out.path().join(".claude/agents/answer_query.md")).unwrap();
    assert!(driver.contains("local_infer` MCP tool"));
    assert!(!driver.contains("model: qwen2.5"));
    let allow = read_json(&out.path().join(".claude/settings.json"))["permissions"]["allow"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.as_str().map(str::to_string))
        .collect::<Vec<_>>();
    assert!(allow.contains(&"mcp__warble__local_infer".to_string()));
    assert!(
        !allow.contains(&"Bash(bash:*)".to_string()),
        "mcp-server realization must NOT widen the bash allowlist"
    );
}