jerrycan 0.7.13

The AI-native Rust backend platform: framework, CLI, and MCP server. https://jerrycan.cc
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
//! Drives the real binary over stdio with raw JSON-RPC lines.

use std::io::{BufRead, Write};

mod common;
use common::McpClient;

#[test]
fn initialize_list_and_unknown_method() {
    let tmp = tempfile::tempdir().unwrap();
    let mut c = McpClient::start_in(tmp.path());

    let tools = c.request("tools/list", serde_json::json!({}));
    let names: Vec<&str> = tools["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["name"].as_str().unwrap())
        .collect();
    assert_eq!(names.len(), 10, "all 10 contract tools served");
    assert!(names.contains(&"jerrycan_design") && names.contains(&"jerrycan_check"));
    // Every tool forwards its outputSchema (the contract defines one for each).
    for t in tools["tools"].as_array().unwrap() {
        assert!(
            t["outputSchema"].is_object(),
            "tool {} must forward outputSchema: {t}",
            t["name"]
        );
    }

    // Unknown method → -32601, server keeps running.
    let msg =
        serde_json::json!({"jsonrpc": "2.0", "id": 99, "method": "bogus/method", "params": {}});
    writeln!(c.stdin, "{msg}").unwrap();
    let mut line = String::new();
    c.stdout.read_line(&mut line).unwrap();
    let v: serde_json::Value = serde_json::from_str(&line).unwrap();
    assert_eq!(v["error"]["code"], -32601);

    let pong = c.request("ping", serde_json::json!({}));
    assert!(pong.as_object().unwrap().is_empty());
    c.shutdown();
}

#[test]
fn docs_tools_work_through_mcp() {
    let tmp = tempfile::tempdir().unwrap();
    let mut c = McpClient::start_in(tmp.path());

    // A successful tools/call mirrors its payload into structuredContent.
    let result = c.request(
        "tools/call",
        serde_json::json!({"name": "jerrycan_docs_search", "arguments": {"query": "override_dep"}}),
    );
    assert_eq!(result["isError"], false);
    assert_eq!(result["structuredContent"]["results"][0]["page"], "testing");

    let (err, payload) = c.call_tool(
        "jerrycan_docs_search",
        serde_json::json!({"query": "override_dep"}),
    );
    assert!(!err);
    assert_eq!(payload["results"][0]["page"], "testing");
    let (err, payload) = c.call_tool("jerrycan_docs_get", serde_json::json!({"page": "errors"}));
    assert!(!err);
    assert!(payload["markdown"].as_str().unwrap().contains("JC0404"));
    c.shutdown();
}

#[test]
fn mcp_lists_ten_tools_including_schema() {
    use jerrycan::platform::mcp::handle_message;
    let r = handle_message(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#).unwrap();
    assert!(r.contains("jerrycan_schema"), "{r}");
}

#[test]
fn oversized_line_gets_minus_32600_and_server_keeps_serving() {
    // A single 17 MiB line exceeds the 16 MiB stdio cap. The server must answer
    // with a JSON-RPC -32600 error and then keep serving the next request,
    // rather than silently truncating or exiting (the 0.1.0 audit finding).
    let tmp = tempfile::tempdir().unwrap();
    let mut c = McpClient::start_in(tmp.path());

    let oversized = "x".repeat(17 * 1024 * 1024);
    writeln!(c.stdin, "{oversized}").unwrap();

    let mut line = String::new();
    c.stdout.read_line(&mut line).unwrap();
    let v: serde_json::Value = serde_json::from_str(&line).unwrap();
    assert_eq!(v["error"]["code"], -32600, "{v}");
    assert!(v["id"].is_null(), "oversized error carries a null id: {v}");
    assert!(
        v["error"]["message"].as_str().unwrap().contains("16 MiB"),
        "{v}"
    );

    // Server survived: a normal request still works.
    let pong = c.request("ping", serde_json::json!({}));
    assert!(pong.as_object().unwrap().is_empty());
    c.shutdown();
}

const GOLDEN: &str = include_str!("../../../conformance/designs/todo-api.design.json");
const REFERENCE: &str = include_str!("../../../conformance/designs/reference-slice.design.json");

#[test]
fn design_tool_questions_then_completes() {
    let tmp = tempfile::tempdir().unwrap();
    let mut c = McpClient::start_in(tmp.path());

    // No draft → the template + a pointed ask, never code.
    let (err, payload) = c.call_tool(
        "jerrycan_design",
        serde_json::json!({"requirements": "todo backend"}),
    );
    assert!(!err);
    assert_eq!(payload["status"], "questions");
    assert!(
        payload["questions"][0]["question"]
            .as_str()
            .unwrap()
            .contains("draft")
    );

    // Broken draft → pointed questions with JSON-pointer ids.
    let mut bad: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    bad["name"] = serde_json::json!("Todo API");
    let (err, payload) = c.call_tool(
        "jerrycan_design",
        serde_json::json!({"requirements": "todo backend", "draft": bad}),
    );
    assert!(!err);
    assert_eq!(payload["status"], "questions");
    assert_eq!(payload["questions"][0]["id"], "/name");

    // Complete draft → written to disk, design_path returned.
    let good: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    let (err, payload) = c.call_tool(
        "jerrycan_design",
        serde_json::json!({"requirements": "todo backend", "draft": good}),
    );
    assert!(!err);
    assert_eq!(payload["status"], "complete");
    let design_path = payload["design_path"].as_str().unwrap();
    assert!(std::path::Path::new(design_path).exists());
    assert!(payload["next_step"].as_str().unwrap().contains("scaffold"));
    c.shutdown();
}

#[test]
fn scaffold_generate_and_list_through_mcp() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("design.json"), GOLDEN).unwrap();
    let mut c = McpClient::start_in(tmp.path());

    let app_dir = tmp.path().join("todo-api");
    let (err, payload) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({
            "design_path": tmp.path().join("design.json").to_str().unwrap(),
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err, "{payload}");
    assert!(payload["created"].as_array().unwrap().len() > 10);

    // Incremental generate with a design_slice (the MCP-only path).
    let (err, payload) = c.call_tool(
        "jerrycan_generate",
        serde_json::json!({
            "kind": "route",
            "path": "tags",
            "directory": app_dir.to_str().unwrap(),
            "design_slice": { "name": "tags", "endpoints": [
                { "operation_id": "list_tags", "method": "GET", "path": "/", "success": { "status": 200 } }
            ]},
        }),
    );
    assert!(!err, "{payload}");
    assert!(
        payload["modified"]
            .as_array()
            .unwrap()
            .iter()
            .any(|p| p == "crates/app/src/main.rs")
    );
    assert!(app_dir.join("crates/routes/tags/src/lib.rs").exists());

    let (err, payload) = c.call_tool(
        "jerrycan_list_routes",
        serde_json::json!({"directory": app_dir.to_str().unwrap()}),
    );
    assert!(!err);
    assert!(
        payload["routes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|r| r["path"] == "/tags/")
    );

    c.shutdown();
}

#[test]
fn package_refuses_when_check_is_red() {
    // The package tool gates on a green full-workspace check. A freshly scaffolded
    // app still has unimplemented handler stubs, so check fails — the tool must
    // refuse with a check-failure error rather than emitting artifacts. This
    // exercises the CLI/MCP-shared run_package wiring without a multi-minute build.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("design.json"), GOLDEN).unwrap();
    let mut c = McpClient::start_in(tmp.path());
    let app_dir = tmp.path().join("todo-api");
    let (err, _) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({
            "design_path": tmp.path().join("design.json").to_str().unwrap(),
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err);

    let (err, payload) = c.call_tool(
        "jerrycan_package",
        serde_json::json!({"target": "k8s", "directory": app_dir.to_str().unwrap()}),
    );
    assert!(err, "packaging a red-check app must error: {payload}");
    assert!(
        payload["error"].as_str().unwrap().contains("check"),
        "error names the failed check gate: {payload}"
    );
    c.shutdown();
}

#[test]
fn partial_slice_replacement_warns_about_dropped_routes() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("design.json"), GOLDEN).unwrap();
    let mut c = McpClient::start_in(tmp.path());
    let app_dir = tmp.path().join("todo-api");
    let (err, _) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({
            "design_path": tmp.path().join("design.json").to_str().unwrap(),
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err);

    // Replace todos with a ONE-endpoint slice: routes drop 8 -> 3 (comments subroute included).
    let (err, payload) = c.call_tool(
        "jerrycan_generate",
        serde_json::json!({
            "kind": "route",
            "path": "todos",
            "directory": app_dir.to_str().unwrap(),
            "design_slice": { "name": "todos", "endpoints": [
                { "operation_id": "list_todos", "method": "GET", "path": "/", "success": { "status": 200 } }
            ]},
        }),
    );
    assert!(!err, "{payload}");
    let next = payload["next_step"].as_str().unwrap();
    assert!(
        next.contains("warning") && next.contains("route count"),
        "{next}"
    );
    c.shutdown();
}

/// Issue #69: regenerating a tool-owned `lib.rs` over the MCP channel must NOT
/// silently drop an agent's hand-added `mod`/`use` wiring — the exact #69 failure,
/// live on the primary agent surface. The MCP twin of `generate route` must carry
/// the dropped line loudly (structured `warnings` + `next_step`), like the CLI does.
/// WHY (Rule 9): without this, JR4-style cross-module wiring vanishes unnoticed on
/// the surface agents actually use.
#[test]
fn generate_route_over_mcp_warns_about_dropped_agent_mod_lines() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("design.json"), GOLDEN).unwrap();
    let mut c = McpClient::start_in(tmp.path());
    let app_dir = tmp.path().join("todo-api");
    let (err, _) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({
            "design_path": tmp.path().join("design.json").to_str().unwrap(),
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err);

    // Agent hand-adds a cross-module sweep to the TOOL-OWNED lib.rs.
    let lib = app_dir.join("crates/routes/todos/src/lib.rs");
    let orig = std::fs::read_to_string(&lib).unwrap();
    std::fs::write(&lib, format!("{orig}mod cross_sweep;\n")).unwrap();

    // Regenerate the SAME module (no slice → design unchanged, so no route drops):
    // the only thing lost is the agent's `mod cross_sweep;`.
    let (err, payload) = c.call_tool(
        "jerrycan_generate",
        serde_json::json!({
            "kind": "route",
            "path": "todos",
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err, "{payload}");

    // Structured `warnings` mirrors the CLI envelope: [{file, dropped_lines}].
    let warnings = payload["warnings"]
        .as_array()
        .expect("dropped agent lines must surface in a `warnings` array");
    let hit = warnings
        .iter()
        .find(|w| {
            w["file"]
                .as_str()
                .is_some_and(|f| f.ends_with("todos/src/lib.rs"))
        })
        .expect("the dropped lib.rs must be named in warnings");
    assert!(
        hit["dropped_lines"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l == "mod cross_sweep;"),
        "the exact dropped line must be named: {hit}"
    );
    // And it must be impossible to miss for a next_step-only reader.
    assert!(
        payload["next_step"]
            .as_str()
            .unwrap()
            .contains("cross_sweep"),
        "next_step must also name the dropped wiring: {}",
        payload["next_step"]
    );
    c.shutdown();
}

#[test]
fn slice_name_path_mismatch_gets_a_pointed_hint() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("design.json"), GOLDEN).unwrap();
    let mut c = McpClient::start_in(tmp.path());
    let app_dir = tmp.path().join("todo-api");
    let (err, _) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({
            "design_path": tmp.path().join("design.json").to_str().unwrap(),
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err);

    let (err, payload) = c.call_tool(
        "jerrycan_generate",
        serde_json::json!({
            "kind": "route",
            "path": "widgets",
            "directory": app_dir.to_str().unwrap(),
            "design_slice": { "name": "gadgets", "endpoints": [
                { "operation_id": "list_gadgets", "method": "GET", "path": "/", "success": { "status": 200 } }
            ]},
        }),
    );
    assert!(err);
    let msg = payload["error"].as_str().unwrap();
    assert!(
        msg.contains("gadgets") && msg.contains("widgets"),
        "must name both sides: {msg}"
    );
    c.shutdown();
}

#[test]
fn gen_tests_writes_tool_owned_acceptance_tests() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("design.json"), GOLDEN).unwrap();
    let mut c = McpClient::start_in(tmp.path());
    let app_dir = tmp.path().join("todo-api");
    let (err, _) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({
            "design_path": tmp.path().join("design.json").to_str().unwrap(),
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err);

    let (err, payload) = c.call_tool(
        "jerrycan_gen_tests",
        serde_json::json!({
            "module": "todos",
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(!err, "{payload}");
    assert_eq!(
        payload["tests_created"][0],
        "crates/routes/todos/tests/acceptance.rs"
    );
    assert_eq!(payload["expected_failing"], 8, "6 success + 2 listed 404s");
    assert!(payload["next_step"].as_str().unwrap().contains("implement"));
    let file =
        std::fs::read_to_string(app_dir.join("crates/routes/todos/tests/acceptance.rs")).unwrap();
    assert!(file.contains("GENERATED by jerrycan gen-tests"));

    // Unknown module → structured error.
    let (err, payload) = c.call_tool(
        "jerrycan_gen_tests",
        serde_json::json!({
            "module": "ghosts",
            "directory": app_dir.to_str().unwrap(),
        }),
    );
    assert!(err);
    assert!(payload["error"].as_str().unwrap().contains("ghosts"));
    c.shutdown();
}

/// #159: the MCP `jerrycan_gen_tests` twin mirrors the 0.6.4 CLI — with NO
/// `module` it generates every endpoint-bearing module's suite plus the jobs
/// suite once, exactly like the bare CLI `gen-tests`. WHY: the CLI dropped the
/// `--module` requirement (#156), but the MCP twin still forced it, so an agent
/// on the MCP channel could not run the whole-design generation the JC0551 jobs
/// diagnostic suggests. The single-`module` call stays byte-identical.
#[test]
fn gen_tests_without_module_covers_all_modules_and_jobs_via_mcp() {
    use jerrycan::platform::design::Design;
    use jerrycan::platform::testgen::{AllAcceptance, write_all_acceptance};

    let tmp = tempfile::tempdir().unwrap();
    let app = tmp.path().join("app");
    std::fs::create_dir_all(&app).unwrap();
    std::fs::write(app.join("design.json"), REFERENCE).unwrap();

    let mut c = McpClient::start_in(tmp.path());
    let (err, payload) = c.call_tool(
        "jerrycan_gen_tests",
        serde_json::json!({ "directory": app.to_str().unwrap() }),
    );
    assert!(!err, "module-less gen_tests must succeed: {payload}");

    // Oracle: the shared all-modules writer, driven directly into a sibling root.
    let design = Design::from_path(&app.join("design.json")).unwrap();
    let oracle = tmp.path().join("oracle");
    std::fs::create_dir_all(&oracle).unwrap();
    let AllAcceptance {
        tests_created: expected_files,
        expected_failing: expected_count,
        ..
    } = write_all_acceptance(&oracle, &design).unwrap();
    // reference-slice bears multiple endpoint modules AND jobs — a real "all" case.
    assert!(
        expected_files.len() > 2 && expected_files.iter().any(|f| f.contains("jobs")),
        "fixture must exercise many modules + jobs: {expected_files:?}"
    );

    let created: Vec<String> = payload["tests_created"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect();
    assert_eq!(
        created, expected_files,
        "one suite per endpoint-bearing module, then jobs once"
    );
    for rel in &created {
        let got = std::fs::read(app.join(rel)).unwrap_or_else(|e| panic!("{rel} not written: {e}"));
        let want = std::fs::read(oracle.join(rel)).unwrap();
        assert_eq!(
            got, want,
            "{rel} must match the per-module writer byte-for-byte"
        );
    }
    assert_eq!(
        payload["expected_failing"].as_u64().unwrap() as usize,
        expected_count,
        "aggregate = sum of module counts + jobs counted exactly once"
    );

    // The single-`module` call is UNCHANGED: same one-module + jobs payload, and
    // that module's suite is byte-identical to the one the module-less run wrote.
    let (err, single) = c.call_tool(
        "jerrycan_gen_tests",
        serde_json::json!({ "module": "users", "directory": app.to_str().unwrap() }),
    );
    assert!(!err, "{single}");
    assert_eq!(
        single["tests_created"],
        serde_json::json!([
            "crates/routes/users/tests/acceptance.rs",
            "crates/jobs/tests/acceptance.rs"
        ]),
        "the single-module MCP contract is frozen"
    );
    assert_eq!(
        std::fs::read(app.join("crates/routes/users/tests/acceptance.rs")).unwrap(),
        std::fs::read(oracle.join("crates/routes/users/tests/acceptance.rs")).unwrap(),
        "both MCP paths write the identical module suite"
    );
    c.shutdown();
}