rootcx-types 0.20.0

RootCX shared types
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
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsStatus {
    pub runtime: RuntimeStatus,
    pub postgres: PostgresStatus,
    pub forge: ForgeStatus,
}

impl OsStatus {
    pub fn offline() -> Self {
        Self {
            runtime: RuntimeStatus { version: String::new(), state: ServiceState::Offline },
            postgres: PostgresStatus { state: ServiceState::Offline, port: None, data_dir: None },
            forge: ForgeStatus { state: ServiceState::Offline, port: None },
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgeStatus {
    pub state: ServiceState,
    pub port: Option<u16>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeStatus {
    pub version: String,
    pub state: ServiceState,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostgresStatus {
    pub state: ServiceState,
    pub port: Option<u16>,
    pub data_dir: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServiceState {
    Online,
    Offline,
    Starting,
    Stopping,
    Error,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AppType {
    #[default]
    App,
    Integration,
    Agent,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionDefinition {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub input_schema: Option<JsonValue>,
    #[serde(default)]
    pub output_schema: Option<JsonValue>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppManifest {
    pub app_id: String,
    pub name: String,
    #[serde(default = "default_version")]
    pub version: String,
    #[serde(default)]
    pub description: String,
    #[serde(default, rename = "type")]
    pub app_type: AppType,
    #[serde(default)]
    pub permissions: Option<PermissionsContract>,
    #[serde(default)]
    pub data_contract: Vec<EntityContract>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actions: Vec<ActionDefinition>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_schema: Option<JsonValue>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_auth: Option<JsonValue>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub webhooks: Vec<WebhookDefinition>,
    /// Free-form usage instructions surfaced to AI via list_integrations tool
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// Trigger: auto-invoke this agent on entity events
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<TriggerConfig>,
    /// Declarative cron schedules synced on deploy
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub crons: Vec<CronDefinition>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    /// Public-access surface. Routes listed here bypass Identity. RPCs that
    /// declare `scope` additionally require a share token whose context
    /// matches the request body on the listed keys.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public: Option<PublicSurface>,
}

/// Declarative public-access surface for an app.
///
/// Anything listed here is reachable without an Authorization header.
/// Anything **not** listed retains the default JWT-required behavior.
///
/// See `core/src/extensions/sharing/` for the runtime enforcement.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicSurface {
    /// Custom RPCs exposed publicly. If `scope` is non-empty, the request
    /// must carry a share token whose `context` matches the request body on
    /// every listed key.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rpcs: Vec<PublicRpc>,
    /// CRUD collections exposed publicly with the listed actions.
    /// Allowed actions: "list", "read", "create", "update", "delete".
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub collections: Vec<PublicCollection>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicRpc {
    pub name: String,
    /// Keys to enforce-match between the share token's `context` and the
    /// request body. Empty `scope` means anonymous access (no share token
    /// required). Non-empty means a share token IS required and the listed
    /// keys MUST match exactly.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicCollection {
    pub entity: String,
    /// Subset of CRUD actions exposed: "list", "read", "create", "update", "delete".
    pub actions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CronDefinition {
    pub name: String,
    pub schedule: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload: Option<JsonValue>,
    #[serde(default = "default_overlap_policy")]
    pub overlap_policy: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WebhookDefinition {
    Simple(String),
    #[serde(rename_all = "camelCase")]
    Full { name: String, #[serde(default = "default_post")] method: String },
}

fn default_post() -> String { "POST".into() }

impl WebhookDefinition {
    pub fn name(&self) -> &str {
        match self {
            Self::Simple(s) => s.as_str(),
            Self::Full { name, .. } => name.as_str(),
        }
    }
    pub fn method(&self) -> &str {
        match self {
            Self::Simple(_) => "POST",
            Self::Full { method, .. } => method.as_str(),
        }
    }
}

fn default_overlap_policy() -> String { "skip".into() }

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TriggerConfig {
    pub app_id: String,
    pub entity: String,
    pub on: Vec<String>,
}

fn default_version() -> String {
    "0.0.1".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EntityContract {
    pub entity_name: String,
    pub fields: Vec<FieldContract>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity_key: Option<String>,
    /// Declarative secondary indexes (reconciled by name against pg_indexes at
    /// deploy). Covers the Prisma/Drizzle index surface: composite, unique,
    /// partial, functional, method, operator class, sort/nulls order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub indexes: Vec<IndexContract>,
    /// Declarative table-level CHECK constraints (reconciled by tag against
    /// pg_constraint at deploy, exactly like `indexes`). Arbitrary boolean SQL
    /// expressions: multi-column, conditional, format. Covers the Drizzle
    /// `check()` / Atlas `check {}` surface.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub checks: Vec<CheckContract>,
}

/// A declarative index. Mirrors what Prisma/Drizzle let you declare for
/// PostgreSQL. `where`/`expr`/`ops` are SQL fragments (bounded, not full
/// statements); `name` is auto-derived when omitted.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexContract {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub columns: Vec<IndexColumn>,
    #[serde(default)]
    pub unique: bool,
    /// Index method: btree (default) | hash | gist | gin | spgist | brin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub using: Option<String>,
    /// Partial-index predicate (the `WHERE ...` clause).
    #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")]
    pub where_clause: Option<String>,
    /// Storage parameters, e.g. {"fillfactor":"70"}.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub with: std::collections::BTreeMap<String, String>,
}

/// An index element: either a bare column name, or a spec carrying a column OR
/// expression plus sort/nulls/operator-class.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum IndexColumn {
    Name(String),
    Spec(IndexColumnSpec),
}

/// A declarative table-level CHECK. `expr` is an arbitrary SQL boolean fragment
/// (bounded, not a full statement); `name` is auto-derived when omitted. The
/// core reconciles it by a hash of this DECLARED spec — never by comparing to
/// Postgres's normalized stored definition — so there is no rewrite-churn.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckContract {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub expr: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexColumnSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub column: Option<String>,
    /// Functional-index expression (mutually exclusive with `column`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expr: Option<String>,
    /// asc | desc.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
    /// first | last.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nulls: Option<String>,
    /// Operator class, e.g. gin_trgm_ops.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ops: Option<String>,
}

// NOTE: no `rename_all = "camelCase"` here — at the FIELD level the manifest
// format is snake_case (`enum_values`, `on_delete`, …). camelCase silently
// dropped those keys at deser (→ null), so no enum CHECK constraints or FK
// delete rules were ever generated. Snake_case mirrors the real format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldContract {
    pub name: String,
    #[serde(rename = "type")]
    pub field_type: String,
    #[serde(default)]
    pub required: bool,
    #[serde(default)]
    pub default_value: Option<JsonValue>,
    #[serde(default)]
    pub enum_values: Option<Vec<String>>,
    #[serde(default)]
    pub references: Option<FieldReference>,
    #[serde(default)]
    pub is_primary_key: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_delete: Option<OnDeletePolicy>,
}

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldReference {
    pub entity: String,
    pub field: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledApp {
    pub id: String,
    pub name: String,
    pub version: String,
    pub status: String,
    #[serde(rename = "type", default)]
    pub app_type: AppType,
    pub entities: Vec<String>,
    #[serde(default)]
    pub has_frontend: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionsContract {
    #[serde(default)]
    pub permissions: Vec<PermissionDeclaration>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionDeclaration {
    pub key: String,
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaChange {
    pub entity: String,
    pub change_type: String,
    pub column: String,
    pub detail: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaVerification {
    pub compliant: bool,
    pub changes: Vec<SchemaChange>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderType {
    Anthropic,
    OpenAI,
    Bedrock,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentDefinition {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub system_prompt: Option<String>,
    #[serde(default)]
    pub memory: Option<AgentMemory>,
    #[serde(default)]
    pub limits: Option<AgentLimits>,
    #[serde(default)]
    pub supervision: Option<SupervisionConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentMemory {
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentLimits {
    #[serde(default)]
    pub max_turns: Option<u32>,
    #[serde(default)]
    pub max_context_tokens: Option<u64>,
    #[serde(default)]
    pub keep_recent_messages: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SupervisionConfig {
    pub mode: SupervisionMode,
    #[serde(default)]
    pub policies: Vec<SupervisionPolicy>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SupervisionMode {
    Autonomous,
    Supervised,
    Strict,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SupervisionPolicy {
    pub action: String,
    #[serde(default)]
    pub entity: Option<String>,
    #[serde(default)]
    pub requires: Option<String>,
    #[serde(default)]
    pub rate_limit: Option<RateLimit>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimit {
    pub max: u32,
    pub window: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpServerConfig {
    pub name: String,
    pub transport: McpTransport,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum McpTransport {
    Stdio { command: String, #[serde(default)] args: Vec<String> },
    Http { url: String, #[serde(default)] headers: std::collections::HashMap<String, String> },
    #[deprecated = "use Http"]
    Sse { url: String, #[serde(default)] headers: std::collections::HashMap<String, String> },
    Cli { install: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolDescriptor {
    pub name: String,
    pub description: String,
    pub input_schema: serde_json::Value,
}

// ── Workflow types ────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkflowGraph {
    pub nodes: Vec<WorkflowNode>,
    pub edges: Vec<WorkflowEdge>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkflowNode {
    pub id: String,
    pub kind: WorkflowNodeKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default)]
    pub params: JsonValue,
    #[serde(default)]
    pub position: [f32; 2],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum WorkflowNodeKind {
    Trigger { trigger: TriggerKind },
    Tool { tool_name: String },
    Control { control: ControlKind },
    Code,
    SubWorkflow { workflow_id: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TriggerKind {
    Manual,
    Schedule,
    Webhook,
    RecordChange,
    Channel,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ControlKind {
    If,
    Switch,
    Merge,
    Set,
    Loop,
    Wait,
    Stop,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkflowEdge {
    pub from: String,
    pub to: String,
    #[serde(default)]
    pub from_output: u8,
    #[serde(default)]
    pub to_input: u8,
}

/// A single data item flowing between nodes. Mirrors n8n's INodeExecutionData.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Item {
    pub json: JsonValue,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WorkflowExecutionStatus {
    Queued,
    Running,
    Succeeded,
    Failed,
    Canceled,
}

impl WorkflowExecutionStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Running => "running",
            Self::Succeeded => "succeeded",
            Self::Failed => "failed",
            Self::Canceled => "canceled",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WorkflowNodeRunStatus {
    Pending,
    Running,
    Succeeded,
    Failed,
    Skipped,
}

impl WorkflowNodeRunStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Running => "running",
            Self::Succeeded => "succeeded",
            Self::Failed => "failed",
            Self::Skipped => "skipped",
        }
    }
}

// ── LLM types ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    User,
    Assistant,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    Text { text: String },
    ToolUse { id: String, name: String, input: serde_json::Value },
    ToolResult { tool_use_id: String, content: String, #[serde(default)] is_error: bool },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    pub role: Role,
    pub content: Vec<ContentBlock>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDef {
    pub name: String,
    pub description: String,
    pub input_schema: serde_json::Value,
}


#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn index_column_deserializes_bare_string_and_spec() {
        let json = r#"{"entityName":"program","fields":[],"indexes":[{"name":"test","columns":["slug"],"unique":true}]}"#;
        let e: EntityContract = serde_json::from_str(json).expect("deser failed");
        assert_eq!(e.indexes.len(), 1, "indexes should parse");
        assert_eq!(e.indexes[0].columns.len(), 1, "columns should parse");
        match &e.indexes[0].columns[0] {
            IndexColumn::Name(n) => assert_eq!(n, "slug"),
            other => panic!("expected Name('slug'), got {:?}", other),
        }
    }

    // Regression for the snake_case field keys (see FieldContract): they must
    // survive deser AND a serialize round-trip, else the stored manifest loses
    // them again.
    #[test]
    fn field_contract_preserves_snake_case_keys() {
        let json = r#"{"name":"status","type":"text","enum_values":["draft","active"],"on_delete":"set_null"}"#;
        let f: FieldContract = serde_json::from_str(json).expect("deser failed");
        assert_eq!(f.enum_values.as_deref(), Some(&["draft".to_string(), "active".to_string()][..]));
        assert_eq!(f.on_delete, Some(OnDeletePolicy::SetNull));

        // Round-trip: re-serialize then deser — values must not be lost (proves
        // serialization is snake_case too, so the stored manifest stays faithful).
        let round: FieldContract =
            serde_json::from_value(serde_json::to_value(&f).unwrap()).expect("round-trip failed");
        assert_eq!(round.enum_values, f.enum_values, "enum_values lost on round-trip");
        assert_eq!(round.on_delete, f.on_delete, "on_delete lost on round-trip");
    }

    // The workflow editor speaks camelCase. WorkflowNodeKind is a `tag = "type"`
    // enum, and `rename_all` alone renames only the variants — fields inside
    // struct variants (tool_name, workflow_id) need `rename_all_fields`. Dropping
    // it compiles cleanly but 422s on save. Guards both directions of the exact
    // wire shapes the editor sends and reads back.
    #[test]
    fn node_kind_round_trips_camelcase_wire() {
        let cases = [
            ("tool", serde_json::json!({"type": "tool", "toolName": "query_data"})),
            ("trigger", serde_json::json!({"type": "trigger", "trigger": "recordChange"})),
            ("control", serde_json::json!({"type": "control", "control": "if"})),
            ("subWorkflow", serde_json::json!({"type": "subWorkflow", "workflowId": "wf-1"})),
        ];
        for (label, wire) in &cases {
            let kind: WorkflowNodeKind = serde_json::from_value(wire.clone())
                .unwrap_or_else(|e| panic!("[{label}] wire shape rejected: {e}"));
            assert_eq!(&serde_json::to_value(&kind).unwrap(), wire,
                "[{label}] re-serialized shape drifted from the editor's wire");
        }
    }

    #[test]
    fn entity_parses_declarative_checks() {
        let json = r#"{"entityName":"enrollment","fields":[],
            "checks":[{"name":"enrollment_dates_chk","expr":"exit_date IS NULL OR exit_date >= intake_date"},
                      {"expr":"x <> y"}]}"#;
        let e: EntityContract = serde_json::from_str(json).expect("deser failed");
        assert_eq!(e.checks.len(), 2);
        assert_eq!(e.checks[0].name.as_deref(), Some("enrollment_dates_chk"));
        assert_eq!(e.checks[1].name, None, "unnamed check keeps name None (auto-derived later)");
        assert_eq!(e.checks[1].expr, "x <> y");
    }
}