jerrycan 0.2.0

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
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
//! Typed model of design.json (docs/contracts/design-schema.json).
//! `deny_unknown_fields` mirrors the schema's `additionalProperties: false`.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Design {
    pub name: String,
    pub contract_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<Auth>,
    /// App-scoped dependency names the generator must provide on App.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenancy: Option<Tenancy>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub jobs: Vec<JobDesign>,
    pub modules: Vec<ModuleDesign>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Auth {
    pub model: AuthModel,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthModel {
    None,
    Session,
    Jwt,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ModuleDesign {
    pub name: String,
    /// Mount prefix; defaults to "/" + name (see `effective_mount`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mount: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entities: Vec<Entity>,
    pub endpoints: Vec<Endpoint>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub subroutes: Vec<ModuleDesign>,
    /// Module-scoped dependency names the generator must stub.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Entity {
    pub name: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub belongs_to: Vec<BelongsTo>,
    pub fields: Vec<Field>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Field {
    pub name: String,
    #[serde(rename = "type")]
    pub field_type: FieldType,
    #[serde(default = "default_true")]
    pub required: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub unique: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub index: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FieldType {
    String,
    Integer,
    Float,
    Boolean,
    Datetime,
    Uuid,
    Json,
}

impl FieldType {
    /// The Rust type the generator emits. datetime/uuid ride as String until
    /// jerrycan-validate lands richer types in Phase 2 (documented in templates).
    pub fn rust_type(self) -> &'static str {
        match self {
            FieldType::String | FieldType::Datetime | FieldType::Uuid => "String",
            FieldType::Integer => "i64",
            FieldType::Float => "f64",
            FieldType::Boolean => "bool",
            FieldType::Json => "serde_json::Value",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BelongsTo {
    pub entity: String,
    #[serde(default)]
    pub on_delete: OnDelete,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnDelete {
    Cascade,
    SetNull,
    #[default]
    Restrict,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Tenancy {
    pub entity: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub member_roles: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JobDesign {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schedule: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Endpoint {
    pub operation_id: String,
    pub method: HttpMethod,
    pub path: String,
    #[serde(default)]
    pub auth_required: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_roles: Vec<String>,
    /// Genuinely public route (credential-issuing login/register, public
    /// webhooks): exempt from JL0004 (unguarded-mutation) and from generated 401
    /// tests. Validation forbids combining it with auth_required/required_roles.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub public: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_body: Option<RequestBody>,
    pub success: Success,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<ErrorCase>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HttpMethod {
    GET,
    POST,
    PUT,
    PATCH,
    DELETE,
}

impl HttpMethod {
    /// The jerrycan-core free-fn name used in generated `module()` route tables.
    pub fn builder_fn(self) -> &'static str {
        match self {
            HttpMethod::GET => "get",
            HttpMethod::POST => "post",
            HttpMethod::PUT => "put",
            HttpMethod::PATCH => "patch",
            HttpMethod::DELETE => "delete",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RequestBody {
    pub entity: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Success {
    pub status: u16,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entity: Option<String>,
    #[serde(default)]
    pub list: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ErrorCase {
    pub status: u16,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    pub when: String,
}

impl Endpoint {
    /// This endpoint needs an authenticated user (and maybe a role).
    pub fn is_guarded(&self) -> bool {
        self.auth_required || !self.required_roles.is_empty()
    }

    /// True when this endpoint carries its OWN request authentication via a
    /// cryptographic signature (the Stripe-style webhook pattern): the design
    /// declares a 4xx error case whose `when` names a signature check. Such an
    /// endpoint is intentionally NOT JWT/session-guarded — its caller is a third
    /// party that can't hold the app's session, so it proves itself by signing the
    /// payload. JL0004 (the unguarded-mutation lint) treats this as guarded so it
    /// doesn't false-positive a deliberately signature-authenticated webhook.
    pub fn declares_signature_auth(&self) -> bool {
        self.errors
            .iter()
            .any(|e| (400..500).contains(&e.status) && e.when.to_lowercase().contains("signature"))
    }
}

impl ModuleDesign {
    /// Where this module mounts (under the app, or under its parent for subroutes).
    pub fn effective_mount(&self) -> String {
        self.mount
            .clone()
            .unwrap_or_else(|| format!("/{}", self.name))
    }
}

impl Design {
    /// Reserved dependency name `db` switches generation to SQL mode.
    pub fn wants_db(&self) -> bool {
        self.dependencies.iter().any(|d| d == "db")
    }

    /// Reserved dependency name `validate` mounts the OpenAPI document.
    pub fn wants_validate(&self) -> bool {
        self.dependencies.iter().any(|d| d == "validate")
    }

    /// Auth mode: a non-`none` auth model, or the reserved `auth` dependency.
    /// Triggers session-user types in shared, guard params, and the `Auth`
    /// extension in main.rs.
    pub fn wants_auth(&self) -> bool {
        self.auth
            .as_ref()
            .map(|a| a.model != AuthModel::None)
            .unwrap_or(false)
            || self.dependencies.iter().any(|d| d == "auth")
    }

    /// Reserved dependency name `observe` wires logging + the metrics/health
    /// extension. Pure extension wiring — no per-route codegen.
    pub fn wants_observe(&self) -> bool {
        self.dependencies.iter().any(|d| d == "observe")
    }

    /// Declared background jobs switch on the generated `crates/jobs/` crate (the
    /// typed task stubs + the dispatch registry) and the `Jobs` extension wiring
    /// in main.rs. Jobs are top-level (not per-module), so this gates a single
    /// top-level crate. Jobs require a database (the engine's default store is
    /// Postgres); validation rejects jobs without a `db` dependency.
    pub fn wants_jobs(&self) -> bool {
        !self.jobs.is_empty()
    }

    /// Reserved dependency name `oauth` enables the facade `oauth` feature, so a
    /// generated handler can use `jerrycan::auth::oauth::{OAuthClient, Provider}`
    /// (the OAuth2 authorization-code client). The facade `oauth` feature implies
    /// `auth`, so the auth surface is available even without a separate `auth`
    /// dependency. The client is constructed in agent-owned handler code (no
    /// app-level extension wiring), so this only gates the Cargo feature.
    pub fn wants_oauth(&self) -> bool {
        self.dependencies.iter().any(|d| d == "oauth")
    }

    /// The facade features this design's mode requires on the `jerrycan` dep,
    /// in a stable order (scaffold and mounting must agree byte-for-byte).
    pub fn facade_features(&self) -> Vec<&'static str> {
        let mut features = Vec::new();
        if self.wants_db() {
            features.push("db");
        }
        if self.wants_validate() {
            features.push("validate");
        }
        if self.wants_auth() {
            features.push("auth");
        }
        if self.wants_observe() {
            features.push("observe");
        }
        if self.wants_jobs() {
            features.push("jobs");
        }
        // Appended last so existing designs' feature order is unchanged.
        if self.wants_oauth() {
            features.push("oauth");
        }
        features
    }

    pub fn from_path(path: &std::path::Path) -> Result<Self, String> {
        let raw = std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
        serde_json::from_str(&raw).map_err(|e| format!("invalid design.json: {e}"))
    }

    /// Entities owned by the tenant: any entity (in any module or subroute)
    /// with a belongs_to aimed at tenancy.entity. (module_name, entity_name) pairs.
    pub fn tenant_owned(&self) -> Vec<(&str, &str)> {
        let Some(tenancy) = self.tenancy.as_ref() else {
            return Vec::new();
        };
        let mut owned = Vec::new();
        for module in &self.modules {
            collect_tenant_owned(module, &tenancy.entity, &mut owned);
        }
        owned
    }

    /// The fk column a belongs_to derives: snake_case(target) + "_id".
    pub fn fk_column(target: &str) -> String {
        format!("{}_id", Self::to_snake(target))
    }

    /// snake_case a validated PascalCase entity name. Entity names are validated
    /// `^[A-Z][A-Za-z0-9]*$`, so each uppercase letter (past the first char)
    /// starts a new word: "ApiKey" -> "api_key".
    pub fn to_snake(name: &str) -> String {
        let mut snake = String::with_capacity(name.len() + 2);
        for (i, ch) in name.char_indices() {
            if i > 0 && ch.is_ascii_uppercase() {
                snake.push('_');
            }
            snake.push(ch.to_ascii_lowercase());
        }
        snake
    }

    /// The Rust key type a belongs_to target keys on: the target entity's declared
    /// `id` field type, `i64` for a synthetic or integer pk. Mirrors genroute's
    /// `key_rust_type` but resolves the entity by name across the whole design tree
    /// (a fk may point at an entity in any module or subroute). Falls back to `i64`
    /// when the target is unknown (validation guarantees it exists in practice).
    pub fn target_key_rust_type(&self, target: &str) -> &'static str {
        fn find<'a>(m: &'a ModuleDesign, target: &str) -> Option<&'a Entity> {
            m.entities
                .iter()
                .find(|e| e.name == target)
                .or_else(|| m.subroutes.iter().find_map(|s| find(s, target)))
        }
        self.modules
            .iter()
            .find_map(|m| find(m, target))
            .and_then(|e| e.fields.iter().find(|f| f.name == "id"))
            .map(|f| f.field_type.rust_type())
            .unwrap_or("i64")
    }
}

/// Walk a module and its subroutes in document order, pairing each entity
/// that belongs_to `tenant` with the owning module/subroute name.
fn collect_tenant_owned<'a>(
    module: &'a ModuleDesign,
    tenant: &str,
    out: &mut Vec<(&'a str, &'a str)>,
) {
    for entity in &module.entities {
        if entity.belongs_to.iter().any(|b| b.entity == tenant) {
            out.push((module.name.as_str(), entity.name.as_str()));
        }
    }
    for subroute in &module.subroutes {
        collect_tenant_owned(subroute, tenant, out);
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    pub(crate) const MINIMAL: &str = r#"{
        "name": "demo-api",
        "contract_version": 0,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["db"],
        "modules": [{
            "name": "todos",
            "entities": [{ "name": "Todo", "fields": [
                { "name": "title", "type": "string" },
                { "name": "done", "type": "boolean", "required": false }
            ]}],
            "endpoints": [
                { "operation_id": "list_todos", "method": "GET", "path": "/",
                  "success": { "status": 200, "entity": "Todo", "list": true } },
                { "operation_id": "create_todo", "method": "POST", "path": "/",
                  "request_body": { "entity": "Todo" },
                  "success": { "status": 201, "entity": "Todo" } },
                { "operation_id": "delete_todo", "method": "DELETE", "path": "/{id}",
                  "required_roles": ["admin"],
                  "success": { "status": 204 },
                  "errors": [{ "status": 404, "code": "JC0404", "when": "unknown id" }] }
            ],
            "subroutes": [{
                "name": "comments",
                "endpoints": [{ "operation_id": "list_comments", "method": "GET", "path": "/",
                                "success": { "status": 200 } }]
            }]
        }]
    }"#;

    pub(crate) const V1_FULL: &str = r#"{
        "name": "kolli-mini", "contract_version": 1,
        "auth": { "model": "jwt", "roles": ["owner", "member"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Workspace", "member_roles": ["owner", "member"] },
        "jobs": [{ "name": "expire_trials", "schedule": "0 * * * *" }],
        "modules": [
            { "name": "workspaces",
              "entities": [{ "name": "Workspace", "fields": [
                  { "name": "id", "type": "integer" },
                  { "name": "plan", "type": "string", "values": ["trial", "pro"] }
              ]}],
              "endpoints": [{ "operation_id": "list_workspaces", "method": "GET",
                  "path": "/", "success": { "status": 200, "entity": "Workspace", "list": true } }] },
            { "name": "leads",
              "entities": [{ "name": "Lead",
                  "belongs_to": [{ "entity": "Workspace", "on_delete": "cascade" }],
                  "fields": [
                      { "name": "id", "type": "integer" },
                      { "name": "phone", "type": "string", "unique": true, "index": true },
                      { "name": "custom", "type": "json", "required": false }
                  ]}],
              "endpoints": [{ "operation_id": "list_leads", "method": "GET",
                  "path": "/", "success": { "status": 200, "entity": "Lead", "list": true } }] }
        ]
    }"#;

    #[test]
    fn v1_design_round_trips_with_new_constructs() {
        let d: Design = serde_json::from_str(V1_FULL).unwrap();
        assert_eq!(d.contract_version, 1);
        assert_eq!(d.tenancy.as_ref().unwrap().entity, "Workspace");
        assert_eq!(d.jobs[0].name, "expire_trials");
        let lead = &d.modules[1].entities[0];
        assert_eq!(lead.belongs_to[0].entity, "Workspace");
        assert_eq!(lead.belongs_to[0].on_delete, OnDelete::Cascade);
        assert!(lead.fields[1].unique && lead.fields[1].index);
        assert_eq!(
            d.modules[0].entities[0].fields[1]
                .values
                .as_ref()
                .unwrap()
                .len(),
            2
        );
        let back = serde_json::to_string(&d).unwrap();
        let _re: Design = serde_json::from_str(&back).unwrap();
    }

    #[test]
    fn wants_jobs_gates_on_declared_jobs_and_adds_the_facade_feature() {
        // A design that declares a job switches on the jobs crate + the `jobs`
        // facade feature; the kolli eval slice (V1_FULL) carries one.
        let with_jobs: Design = serde_json::from_str(V1_FULL).unwrap();
        assert!(with_jobs.wants_jobs(), "a declared job must set wants_jobs");
        assert!(
            with_jobs.facade_features().contains(&"jobs"),
            "wants_jobs must surface the `jobs` facade feature so the app enables it: {:?}",
            with_jobs.facade_features()
        );
        // No declared jobs → no jobs crate, no `jobs` feature.
        let no_jobs: Design = serde_json::from_str(MINIMAL).unwrap();
        assert!(!no_jobs.wants_jobs());
        assert!(!no_jobs.facade_features().contains(&"jobs"));
    }

    #[test]
    fn wants_oauth_gates_on_the_dependency_and_appends_the_facade_feature() {
        // A design declaring the `oauth` dependency enables the `oauth` facade
        // feature so a generated handler can use the OAuth2 client without a
        // manual Cargo patch. `oauth` is appended LAST, after `jobs`.
        let s = r#"{ "name": "x", "contract_version": 1,
            "dependencies": ["db", "auth", "oauth"],
            "modules": [{ "name": "m", "endpoints": [
                { "operation_id": "go", "method": "GET", "path": "/go",
                  "success": { "status": 302 } }] }] }"#;
        let d: Design = serde_json::from_str(s).unwrap();
        assert!(
            d.wants_oauth(),
            "the `oauth` dependency must set wants_oauth"
        );
        let feats = d.facade_features();
        assert!(
            feats.contains(&"oauth"),
            "wants_oauth must surface the `oauth` facade feature: {feats:?}"
        );
        assert_eq!(
            feats.last(),
            Some(&"oauth"),
            "oauth is appended last: {feats:?}"
        );
        // No `oauth` dependency → no `oauth` feature.
        let no_oauth: Design = serde_json::from_str(MINIMAL).unwrap();
        assert!(!no_oauth.wants_oauth());
        assert!(!no_oauth.facade_features().contains(&"oauth"));
    }

    #[test]
    fn v0_designs_still_parse_unchanged() {
        let d: Design = serde_json::from_str(MINIMAL).unwrap();
        assert_eq!(d.contract_version, 0);
        assert!(d.tenancy.is_none() && d.jobs.is_empty());
        assert!(d.modules[0].entities[0].belongs_to.is_empty());
    }

    #[test]
    fn tenant_owned_walks_modules_and_subroutes() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        // V1_FULL has no subroutes, so graft one carrying a tenant-owned
        // entity onto modules[1] to exercise the recursion in
        // collect_tenant_owned (deleting that recursion must fail this test).
        let sub: ModuleDesign = serde_json::from_str(
            r#"{
                "name": "notes",
                "entities": [{ "name": "Note",
                    "belongs_to": [{ "entity": "Workspace" }],
                    "fields": [{ "name": "body", "type": "string" }] }],
                "endpoints": [{ "operation_id": "list_notes", "method": "GET", "path": "/",
                    "success": { "status": 200 } }]
            }"#,
        )
        .unwrap();
        d.modules[1].subroutes.push(sub);
        assert_eq!(d.tenant_owned(), vec![("leads", "Lead"), ("notes", "Note")]);
    }

    #[test]
    fn fk_column_is_snake_target_id() {
        assert_eq!(Design::fk_column("Workspace"), "workspace_id");
        assert_eq!(Design::fk_column("ApiKey"), "api_key_id");
        // fk_column derives from the shared to_snake (DRY); both must agree.
        assert_eq!(Design::to_snake("ApiKey"), "api_key");
        assert_eq!(Design::to_snake("Lead"), "lead");
    }

    #[test]
    fn target_key_rust_type_resolves_pk_across_the_tree() {
        let d: Design = serde_json::from_str(V1_FULL).unwrap();
        // Workspace declares an integer id → i64 key (the fk column type a
        // belongs_to: Workspace must use). An unknown target falls back to i64.
        assert_eq!(d.target_key_rust_type("Workspace"), "i64");
        assert_eq!(d.target_key_rust_type("Nonexistent"), "i64");
    }

    #[test]
    fn minimal_design_round_trips() {
        let d: Design = serde_json::from_str(MINIMAL).unwrap();
        assert_eq!(d.name, "demo-api");
        assert_eq!(d.modules[0].endpoints.len(), 3);
        assert_eq!(d.modules[0].subroutes[0].name, "comments");
        assert!(d.modules[0].entities[0].fields[0].required); // default true
        assert!(!d.modules[0].entities[0].fields[1].required);
        let back = serde_json::to_string(&d).unwrap();
        let _re: Design = serde_json::from_str(&back).unwrap(); // serializable both ways
    }

    #[test]
    fn unknown_fields_are_rejected_like_additional_properties_false() {
        let bad = MINIMAL.replacen(
            "\"name\": \"demo-api\",",
            "\"name\": \"demo-api\", \"surprise\": 1,",
            1,
        );
        assert!(serde_json::from_str::<Design>(&bad).is_err());
    }

    #[test]
    fn method_enum_rejects_options() {
        let bad = MINIMAL.replace("\"GET\"", "\"OPTIONS\"");
        assert!(serde_json::from_str::<Design>(&bad).is_err());
    }

    #[test]
    fn public_endpoint_flag_round_trips_defaults_false_and_skips_when_false() {
        // A credential-issuing route declares itself public; the flag must
        // survive a round trip (Task 9: JL0004 carve-out for login/register).
        let pub_ep: Endpoint = serde_json::from_str(
            r#"{ "operation_id": "register", "method": "POST", "path": "/register",
                 "public": true, "success": { "status": 201 } }"#,
        )
        .unwrap();
        assert!(pub_ep.public, "public: true must deserialize");
        let back = serde_json::to_value(&pub_ep).unwrap();
        assert_eq!(back["public"], serde_json::json!(true), "round trips");

        // Default false when absent.
        let plain: Endpoint = serde_json::from_str(
            r#"{ "operation_id": "list", "method": "GET", "path": "/",
                 "success": { "status": 200 } }"#,
        )
        .unwrap();
        assert!(!plain.public, "absent public defaults to false");
        // false is skipped on serialize (mirrors unique/index), so a non-public
        // endpoint emits no `public` key.
        let back = serde_json::to_value(&plain).unwrap();
        assert!(
            back.get("public").is_none(),
            "public: false must be skipped on serialize: {back}"
        );
    }

    #[test]
    fn published_schema_accepts_v1_constructs() {
        // Structural spot-checks keep the published contract honest (we don't
        // run a full JSON-Schema validator).
        let s = include_str!("../../../../docs/contracts/design-schema.json");
        let v: serde_json::Value = serde_json::from_str(s).unwrap();
        assert_eq!(
            v["properties"]["contract_version"]["enum"],
            serde_json::json!([0, 1])
        );
        assert!(
            s.contains("\"belongs_to\"")
                && s.contains("\"tenancy\"")
                && s.contains("\"jobs\"")
                && s.contains("\"on_delete\"")
                && s.contains("\"unique\"")
                && s.contains("\"values\"")
        );
    }
}