warble-claude-code 0.5.1

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
//! Dispatch smoke for the analysis-agent flagship profile (Phase 1.2).
//!
//! Proves each of the four GenBI components legalizes onto the claude-code file target and emits a
//! runnable agent — including the two capabilities added this phase: `semantic_introspection`
//! (explore_model) and the `narrative` render block (explain_change). Each component is emitted from
//! a single-node IR sliced out of the shared golden, so per-component assertions stay isolated.

use warble_claude_code::ir::WarbleIr;
use warble_claude_code::{emit_claude_code, RenderFlavor};

const ANALYSIS_AGENT_IR: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../examples/analysis-agent/ir.golden.json"
);

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

/// A one-component IR carrying only the node with `verb`.
fn single(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()
    }
}

/// A one-component IR with that component mutated — for shapes no shipped profile declares.
fn with_component(
    ir: &WarbleIr,
    mutate: impl FnOnce(warble_claude_code::ir::ComponentNode) -> warble_claude_code::ir::ComponentNode,
) -> WarbleIr {
    WarbleIr {
        components: vec![mutate(ir.components[0].clone())],
        ..ir.clone()
    }
}

/// An IR carrying `verbs` in exactly that order — the ordering matters for any artifact the whole
/// profile shares, since a per-component write to a shared path is decided by whoever is last.
fn ordered(ir: &WarbleIr, verbs: &[&str]) -> WarbleIr {
    WarbleIr {
        components: verbs
            .iter()
            .map(|verb| {
                ir.components
                    .iter()
                    .find(|c| c.verb == *verb)
                    .unwrap_or_else(|| panic!("component '{verb}' in golden"))
                    .clone()
            })
            .collect(),
        ..ir.clone()
    }
}

fn split_frontmatter(markdown: &str) -> (String, String) {
    let stripped = markdown
        .strip_prefix("---\n")
        .expect("agent file starts with frontmatter");
    let end = stripped.find("\n---\n").expect("frontmatter terminator");
    (
        stripped[..end].to_string(),
        stripped[end + "\n---\n".len()..].to_string(),
    )
}

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

fn emit_to_tmp(ir: &WarbleIr, target: &str, flavor: RenderFlavor) -> tempfile::TempDir {
    let out = tempfile::tempdir().expect("tempdir");
    emit_claude_code(ir, out.path(), target, flavor).expect("emit succeeds");
    out
}

fn agent_files(out: &std::path::Path) -> Vec<String> {
    let mut files: Vec<String> = std::fs::read_dir(out.join(".claude/agents"))
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
        .collect();
    files.sort();
    files
}

fn read_agent(out: &std::path::Path, name: &str) -> String {
    std::fs::read_to_string(out.join(".claude/agents").join(name)).unwrap()
}

// --- explore_model: semantic_introspection grants the wren tool, no render, read-only ------------

#[test]
fn explore_model_emits_a_single_read_only_introspection_agent() {
    let ir = single(&load_ir(), "explore_model");
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);

    assert_eq!(
        agent_files(out.path()),
        vec!["explore_model.md".to_string()]
    );

    let (fm, body) = split_frontmatter(&read_agent(out.path(), "explore_model.md"));
    let fm = serde_yaml::from_str::<serde_json::Value>(&fm).unwrap();
    assert!(
        has_tool(&fm, "Bash(wren:*)"),
        "semantic_introspection must grant the wren CLI tool (`wren context show`)"
    );
    assert!(!has_tool(&fm, "Write"), "read-only: no Write");
    assert!(!has_tool(&fm, "Edit"), "read-only: no Edit");
    assert!(
        !body.contains("## Render output"),
        "explore_model renders no UI (render_blocks empty)"
    );

    // capability report records semantic_introspection with no fail.
    let report: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(out.path().join("capability-report.json")).unwrap(),
    )
    .unwrap();
    let caps = report["components"][0]["capabilities"].as_array().unwrap();
    assert!(caps
        .iter()
        .any(|c| c["capability"] == "semantic_introspection" && c["outcome"] == "realize-via"));
    assert!(caps.iter().all(|c| c["outcome"] != "fail"));
}

// --- answer_query: 3-step split, repair_sql subagent present -------------------------------------

#[test]
fn answer_query_splits_into_driver_plus_three_step_subagents() {
    let ir = single(&load_ir(), "answer_query");
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);

    assert_eq!(
        agent_files(out.path()),
        vec![
            "answer_query.md".to_string(),
            "answer_query__generate_sql.md".to_string(),
            "answer_query__repair_sql.md".to_string(),
            "answer_query__resolve_intent.md".to_string(),
        ],
        "per-step-tier split emits a driver + one subagent per step"
    );

    // repair_sql subagent runs at the strong tier and stays read-only.
    let (fm, _) = split_frontmatter(&read_agent(out.path(), "answer_query__repair_sql.md"));
    let fm = serde_yaml::from_str::<serde_json::Value>(&fm).unwrap();
    assert_eq!(fm["model"].as_str().unwrap(), "opus"); // strong → opus (default binding)
    assert!(!has_tool(&fm, "Write"));

    // no artifact_write guardrail ⇒ no render section (the table is emitted as {columns,rows}).
    let driver = read_agent(out.path(), "answer_query.md");
    assert!(!driver.contains("## Render output"));
}

// --- generate_dashboard: render contract folded into the split driver ----------------------------

#[test]
fn generate_dashboard_emits_the_locked_render_contract_in_the_driver() {
    let ir = single(&load_ir(), "generate_dashboard");
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);

    let driver = read_agent(out.path(), "generate_dashboard.md");
    let (fm, body) = split_frontmatter(&driver);
    let fm = serde_yaml::from_str::<serde_json::Value>(&fm).unwrap();

    assert!(body.contains("## Render output"), "render section present");
    for block in ["kpi_card", "table", "chart"] {
        assert!(body.contains(block), "block contract must list {block}");
    }
    assert!(
        body.contains("label: string"),
        "typed field schema must be shown"
    );
    // programmatic flavor: agent stays read-only, emits an envelope.
    assert!(!has_tool(&fm, "Write"), "programmatic → no Write");
    assert!(body.contains("render envelope"));

    // prompt flavor: the driver gets Write + a dashboard.html instruction.
    let out_prompt = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Prompt);
    let (fm_p, body_p) = split_frontmatter(&read_agent(out_prompt.path(), "generate_dashboard.md"));
    let fm_p = serde_yaml::from_str::<serde_json::Value>(&fm_p).unwrap();
    assert!(has_tool(&fm_p, "Write"), "prompt flavor → Write granted");
    assert!(body_p.contains("dashboard.html"));
}

// --- explain_change: the narrative render block ---------------------------------------------------

#[test]
fn explain_change_emits_a_single_agent_with_the_narrative_render_block() {
    let ir = single(&load_ir(), "explain_change");
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);

    assert_eq!(
        agent_files(out.path()),
        vec!["explain_change.md".to_string()],
        "both steps are strong tier → single agent, no split"
    );
    let (fm, body) = split_frontmatter(&read_agent(out.path(), "explain_change.md"));
    let fm = serde_yaml::from_str::<serde_json::Value>(&fm).unwrap();

    assert!(body.contains("## Render output"));
    assert!(
        body.contains("narrative"),
        "the narrative block must appear in the render contract"
    );
    assert!(!has_tool(&fm, "Write"), "programmatic → no Write");
}

// --- interactive degrade + whole-profile smoke ---------------------------------------------------

#[test]
fn render_components_degrade_to_markdown_on_interactive() {
    let ir = single(&load_ir(), "explain_change");
    let out = emit_to_tmp(&ir, "claude-code:interactive", RenderFlavor::Programmatic);
    let (_, body) = split_frontmatter(&read_agent(out.path(), "explain_change.md"));
    assert!(
        body.to_lowercase().contains("markdown"),
        "interactive degrades render to markdown"
    );
}

#[test]
fn the_whole_flagship_profile_dispatches_all_four_components() {
    let ir = load_ir();
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);
    let files = agent_files(out.path());
    for verb in [
        "explore_model.md",
        "answer_query.md",
        "generate_dashboard.md",
        "explain_change.md",
    ] {
        assert!(
            files.contains(&verb.to_string()),
            "flagship dispatch must emit the '{verb}' agent; got {files:?}"
        );
    }
}

/// The session envelope is the union of the profile's components, not whichever component the IR
/// ends with. `answer_query` is a per-step-tier split whose driver delegates with `Task`;
/// `explore_model` is a plain agent that never needs it. Ordered so the plain one is last, a
/// per-component write leaves the session without `Task` pre-approved at all.
#[test]
fn settings_json_is_the_union_of_the_profile_not_its_last_component() {
    let ir = ordered(&load_ir(), &["answer_query", "explore_model"]);
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);
    let settings: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(out.path().join(".claude/settings.json")).unwrap(),
    )
    .unwrap();
    let allow = settings["permissions"]["allow"]
        .as_array()
        .expect("allow array")
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect::<Vec<_>>();
    for tool in ["Task", "Read", "Bash(wren:*)"] {
        assert!(
            allow.contains(&tool.to_string()),
            "session envelope must carry '{tool}' from some component; got {allow:?}"
        );
    }
    assert_eq!(
        allow.len(),
        allow.iter().collect::<std::collections::HashSet<_>>().len(),
        "union must not duplicate a grant two components share: {allow:?}"
    );
    let deny = settings["permissions"]["deny"]
        .as_array()
        .expect("a component demanded the destructive-bash denials, so the scope keeps them");
    assert!(deny.iter().any(|v| v.as_str() == Some("Bash(rm:*)")));
    let comment = settings["$comment"].as_str().expect("comment");
    for verb in ["answer_query", "explore_model"] {
        assert!(
            comment.contains(&format!("{verb}: ")),
            "each component's own note keeps its subject once they share one file"
        );
    }
}

/// An authored purpose reaches the two places a selector reads — the entry agent's frontmatter
/// `description` and the scope inventory — and stops at the component boundary: a per-step subagent
/// keeps its own step-scoped line, because a step is not a destination anything may choose.
#[test]
fn an_authored_purpose_replaces_the_synthesized_shape_line_for_entry_agents_only() {
    let ir = load_ir();
    let authored = ir
        .components
        .iter()
        .find(|c| c.verb == "answer_query")
        .and_then(|c| c.description.clone())
        .expect("answer_query carries an authored description");
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);

    let (driver_fm, _) = split_frontmatter(&read_agent(out.path(), "answer_query.md"));
    let driver_fm = serde_yaml::from_str::<serde_json::Value>(&driver_fm).unwrap();
    let driver_description = driver_fm["description"].as_str().expect("description");
    assert!(
        driver_description.starts_with(authored.trim()),
        "the entry agent's description is the authored purpose, not a synthesized shape line: {driver_description}"
    );
    assert!(
        !driver_description.contains("orchestrator that delegates"),
        "how the component subdivides its work is not what it is for: {driver_description}"
    );
    for example in &ir
        .components
        .iter()
        .find(|c| c.verb == "answer_query")
        .expect("answer_query")
        .examples
    {
        assert!(
            driver_description.contains(example.trim()),
            "authored examples ride along in the field the selector reads"
        );
    }

    // The step subagent keeps its own subject.
    let (step_fm, _) = split_frontmatter(&read_agent(out.path(), "answer_query__generate_sql.md"));
    let step_fm = serde_yaml::from_str::<serde_json::Value>(&step_fm).unwrap();
    let step_description = step_fm["description"].as_str().expect("description");
    assert!(step_description.contains("step of"));
    assert!(
        !step_description.contains(authored.trim()),
        "a step must not advertise itself with the component's purpose: {step_description}"
    );

    // And the scope inventory uses the purpose instead of the shape word.
    let prompt = std::fs::read_to_string(out.path().join(".claude/CLAUDE.md")).unwrap();
    assert!(prompt.contains(authored.trim()));
    assert!(
        !prompt.contains("- `answer_query` — analytical"),
        "the inventory line must not fall back to the shape word once a purpose is authored"
    );
}

/// Context isolation walls a component's interior off behind a parent that holds none of its tools.
/// The child is where the tools actually are, so it must not be advertised with the component's
/// purpose: that would put a deliberately internal agent on the same footing as its parent for
/// anything selecting by description.
#[test]
fn the_context_isolation_child_does_not_advertise_the_components_purpose() {
    let base = load_ir();
    let ir = with_component(&single(&base, "answer_query"), |mut node| {
        node.required_capabilities
            .push("context_isolation".to_string());
        node
    });
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);
    let authored = ir.components[0]
        .description
        .as_deref()
        .expect("answer_query carries an authored description")
        .trim();

    let (parent_fm, _) = split_frontmatter(&read_agent(out.path(), "answer_query.md"));
    let parent_fm = serde_yaml::from_str::<serde_json::Value>(&parent_fm).unwrap();
    assert!(
        parent_fm["description"]
            .as_str()
            .expect("description")
            .starts_with(authored),
        "the parent is the entry agent and keeps the authored purpose"
    );

    let (child_fm, _) = split_frontmatter(&read_agent(out.path(), "answer_query__isolated.md"));
    let child_fm = serde_yaml::from_str::<serde_json::Value>(&child_fm).unwrap();
    let child_description = child_fm["description"].as_str().expect("description");
    assert!(
        !child_description.contains(authored),
        "the isolated child must not carry the component's purpose: {child_description}"
    );
    assert_ne!(
        child_description,
        parent_fm["description"].as_str().unwrap(),
        "parent and child must be distinguishable by description"
    );
}

/// The scope prompt describes the whole profile and only states what the emitted output backs.
#[test]
fn scope_prompt_inventories_every_agent_and_discloses_the_render_degrade() {
    let ir = load_ir();
    let out = emit_to_tmp(&ir, "claude-code:interactive", RenderFlavor::Programmatic);
    let prompt = std::fs::read_to_string(out.path().join(".claude/CLAUDE.md")).unwrap();
    assert!(prompt.contains(&format!("# Warble scope: `{}`", ir.profile)));
    assert!(prompt.contains(&ir.components[0].context_binding.project));
    for verb in [
        "explore_model",
        "answer_query",
        "generate_dashboard",
        "explain_change",
    ] {
        assert!(
            prompt.contains(&format!("- `{verb}`")),
            "scope prompt must inventory '{verb}'"
        );
    }
    // Interactive degrades the render contract, so the prompt must say so rather than let a session
    // promise a file it cannot write.
    assert!(
        prompt.contains("degrades to a markdown table")
            && prompt.contains("Do not offer a dashboard file"),
        "scope prompt must disclose the render degrade: {prompt}"
    );
    // Describes, never routes: no per-profile policy about which agent answers what.
    assert!(
        !prompt.to_lowercase().contains("when the user asks"),
        "scope prompt must not carry routing policy"
    );
}

/// RUN.md is one document for the whole profile. There is a single emitted directory and a single
/// RUN.md path, so a per-component document would be written once per component and the last one
/// would silently win — leaving three quarters of the flagship profile undocumented.
#[test]
fn run_md_documents_every_component_of_the_profile_not_just_the_last_one() {
    let ir = load_ir();
    let out = emit_to_tmp(&ir, "claude-code:headless", RenderFlavor::Programmatic);
    let run = std::fs::read_to_string(out.path().join("RUN.md")).unwrap();
    assert!(
        run.starts_with(&format!("# Running `{}`", ir.profile)),
        "RUN.md is titled after the profile, not one of its components: {run}"
    );
    for verb in [
        "explore_model",
        "answer_query",
        "generate_dashboard",
        "explain_change",
    ] {
        assert!(
            run.contains(&format!("## `{verb}`")),
            "RUN.md must carry a section for '{verb}'"
        );
        assert!(
            run.contains(&format!("--agent {verb}")),
            "RUN.md must show how to invoke '{verb}'"
        );
    }
}