cufflink-types 0.10.0

Shared type definitions for the Cufflink CRUD microservice platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

pub mod openapi;
pub mod policy;
pub mod slug;

/// A service manifest describes the complete definition of a cufflink service.
/// This is generated by the SDK macros from the user's Rust struct definitions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceManifest {
    pub name: String,
    pub version: Option<String>,
    pub tables: Vec<TableDefinition>,
    #[serde(default)]
    pub cells: Vec<CellDefinition>,
    #[serde(default)]
    pub events: Vec<EventDefinition>,
    #[serde(default)]
    pub subscriptions: Vec<SubscriptionDefinition>,
    #[serde(default)]
    pub custom_routes: Vec<CustomRouteDefinition>,
    #[serde(default)]
    pub mode: ServiceMode,
    /// Authorization configuration (permission areas and default roles).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authorization: Option<AuthorizationConfig>,
    /// Optional WASM handler invoked between additive and destructive schema
    /// phases of a deploy. Used to backfill or restructure data when columns
    /// are split, renamed, or have their semantics changed. The handler must
    /// be idempotent — it may be re-invoked on retried deploys.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_migrate: Option<String>,
    /// NATS subject patterns (with `*`/`>` wildcards) this service is allowed to
    /// publish or request outside its own `dw.{tenant}.*` namespace. `None` marks
    /// a manifest built before publish authorization existed: the platform then
    /// runs in legacy mode (allow + warn). `Some` — always emitted by the current
    /// SDK — enables enforcement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publishes: Option<Vec<String>>,
    /// Platform capabilities this service requires to run safely. The platform
    /// rejects a deploy whose required features it does not advertise at
    /// `/api/version`. The SDK auto-derives this (e.g. `route_posture` when any
    /// route declares a posture) so a security-relevant manifest cannot be
    /// silently deployed to a platform too old to enforce it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_platform_features: Vec<String>,
    /// Serve the auto-generated GraphQL endpoint. Off unless the service
    /// opts in.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub graphql: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ServiceMode {
    #[default]
    Crud,
    Wasm,
    Container,
    Web,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableDefinition {
    pub name: String,
    pub columns: Vec<ColumnDefinition>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub indexes: Vec<IndexDefinition>,
    #[serde(default)]
    pub soft_delete: bool,
    /// Column name that stores the owner's user ID for row-level security.
    /// When set, CRUD operations are scoped to the authenticated user's records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner_field: Option<String>,
    /// When true, all CRUD operations on this table require authentication.
    /// Unauthenticated requests receive a 401 Unauthorized response.
    #[serde(default)]
    pub auth_required: bool,
    /// Permission area that controls access to this table's CRUD operations.
    /// When set, platform checks "{area}:view" for GET, "{area}:create" for POST,
    /// "{area}:edit" for PUT, "{area}:delete" for DELETE.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permission_area: Option<String>,
    /// Self-service ownership: when true (requires `owner_field`), owning a row
    /// authorizes access to it — the row-level scoping by `owner_field` IS the
    /// authorization, so the `permission_area` grant is NOT required for these
    /// (inherently owner-scoped) CRUD operations. Use for user-owned data a user
    /// manages themselves (their items, addresses, orders). Defaults false, so
    /// existing tables keep requiring `permission_area`; cross-owner/staff access
    /// stays gated by RBAC (typically via dedicated handlers, not owner-scoped CRUD).
    #[serde(default)]
    pub owner_self_service: bool,
    /// CRUD lifecycle hooks — WASM handler names called before/after operations.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hooks: Option<TableHooks>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnDefinition {
    pub name: String,
    pub column_type: ColumnType,
    #[serde(default)]
    pub primary_key: bool,
    #[serde(default)]
    pub nullable: bool,
    #[serde(default)]
    pub auto_generate: bool,
    pub default_value: Option<String>,
    /// Foreign key reference in "table.column" format
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub references: Option<String>,
    /// Whether to cascade deletes on the FK
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_delete: Option<ForeignKeyAction>,
    /// Whether this column has a unique constraint
    #[serde(default)]
    pub unique: bool,
    /// Validation rules for this column
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub validations: Vec<ValidationRule>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "rule", rename_all = "snake_case")]
// Note: ValidationRule contains f64 fields (Min/Max), so Eq cannot be derived
pub enum ValidationRule {
    /// Regex pattern match
    Regex { pattern: String },
    /// Minimum numeric value
    Min { value: f64 },
    /// Maximum numeric value
    Max { value: f64 },
    /// Minimum string length
    MinLength { value: usize },
    /// Maximum string length
    MaxLength { value: usize },
    /// Must be one of the listed values
    OneOf { values: Vec<String> },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct IndexDefinition {
    pub name: String,
    pub columns: Vec<String>,
    #[serde(default)]
    pub unique: bool,
}

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

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ColumnType {
    Uuid,
    Text,
    Integer,
    BigInteger,
    Float,
    Double,
    Boolean,
    Timestamp,
    Date,
    Jsonb,
}

impl ColumnType {
    pub fn to_sql(&self) -> &str {
        match self {
            ColumnType::Uuid => "UUID",
            ColumnType::Text => "TEXT",
            ColumnType::Integer => "INTEGER",
            ColumnType::BigInteger => "BIGINT",
            ColumnType::Float => "REAL",
            ColumnType::Double => "DOUBLE PRECISION",
            ColumnType::Boolean => "BOOLEAN",
            ColumnType::Timestamp => "TIMESTAMPTZ",
            ColumnType::Date => "DATE",
            ColumnType::Jsonb => "JSONB",
        }
    }

    /// Map to the filter column type for query param parsing
    pub fn filter_type(&self) -> &str {
        match self {
            ColumnType::Uuid => "uuid",
            ColumnType::Text => "text",
            ColumnType::Integer | ColumnType::BigInteger => "integer",
            ColumnType::Float | ColumnType::Double => "double",
            ColumnType::Boolean => "boolean",
            ColumnType::Timestamp => "timestamp",
            ColumnType::Date => "date",
            ColumnType::Jsonb => "jsonb",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CellDefinition {
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventDefinition {
    pub name: String,
    pub table: String,
    pub action: EventAction,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EventAction {
    Create,
    Update,
    Delete,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionDefinition {
    pub subject: String,
    pub handler: String,
    pub handler_type: HandlerType,
    #[serde(default)]
    pub config: HashMap<String, String>,
    /// Explicit JetStream stream to host this subscription's consumer. When
    /// `None`, the platform uses the tenant stream (`DW_{tenant}`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HandlerType {
    DeleteCascade,
    UpdateField,
    Webhook,
    Wasm,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomRouteDefinition {
    pub method: String,
    pub path: String,
    pub handler: String,
    /// When present, the HTTP route accepts the request, persists a
    /// `wasm_jobs` row, publishes to JetStream, and returns `202 Accepted`
    /// with `{job_id}`. The handler executes asynchronously on a worker
    /// with no inline 30s wall.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job: Option<JobConfig>,
    /// Who may call this route. `None` marks a manifest built before route
    /// postures existed: the platform runs it in legacy mode (best-effort auth,
    /// no enforcement) and warns. `Some` — always emitted by the current SDK —
    /// makes the platform enforce the declared posture.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub posture: Option<RoutePosture>,
    /// Pass the caller's `authorization`, `cookie` and `proxy-authorization`
    /// headers into the guest. Without it they are stripped once the tenant's
    /// `tenant_binding` policy is enforced.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub forward_auth: bool,
}

/// The authorization posture of a custom route, enforced by the platform so a
/// guest handler cannot forget it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RoutePosture {
    /// Deliberately anonymous. `reason` is mandatory so every public route is
    /// greppable and reviewable (third-party webhooks, signup, public profiles).
    Public { reason: String },
    /// Any authenticated tenant principal.
    Authenticated,
    /// Authenticated and holding the `{area}:{operation}` permission.
    Permission { area: String, operation: String },
    /// Authenticated; the guest scopes the operation to rows whose `field`
    /// equals the caller's subject. The platform enforces authentication.
    Owner { field: String },
}

impl RoutePosture {
    /// Whether a caller with no credentials can reach this route.
    pub fn is_anonymous(&self) -> bool {
        matches!(self, RoutePosture::Public { .. })
    }

    /// Short human label for audit output.
    pub fn label(&self) -> &'static str {
        match self {
            RoutePosture::Public { .. } => "public",
            RoutePosture::Authenticated => "authenticated",
            RoutePosture::Permission { .. } => "permission",
            RoutePosture::Owner { .. } => "owner",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct JobConfig {
    /// Per-handler wall-clock ceiling enforced by the worker.
    pub timeout_secs: u32,
    /// Maximum delivery attempts before the job is permanently failed.
    /// `1` disables retry-on-crash.
    pub max_attempts: u32,
}

impl JobConfig {
    pub const DEFAULT_TIMEOUT_SECS: u32 = 600;
    pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
}

impl Default for JobConfig {
    fn default() -> Self {
        Self {
            timeout_secs: Self::DEFAULT_TIMEOUT_SECS,
            max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
        }
    }
}

/// CRUD lifecycle hooks for a table. Each field names a WASM handler function.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TableHooks {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub before_create: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after_create: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub before_update: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after_update: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub before_delete: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after_delete: Option<String>,
}

/// Authorization configuration declared in the service manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationConfig {
    /// Permission areas declared by this service.
    #[serde(default)]
    pub areas: Vec<PermissionAreaDef>,
    /// Default roles to seed on first deployment.
    #[serde(default)]
    pub default_roles: Vec<DefaultRoleDef>,
}

/// A permission area with its supported operations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionAreaDef {
    pub name: String,
    #[serde(default)]
    pub operations: Vec<String>,
}

/// A default role seeded on deployment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DefaultRoleDef {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub permissions: Vec<String>,
}

/// Description of the changes a deploy is about to apply, passed as the
/// payload to the `on_migrate` hook so user code can decide which backfill
/// blocks should fire.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SchemaDiff {
    #[serde(default)]
    pub added_tables: Vec<String>,
    #[serde(default)]
    pub dropped_tables: Vec<String>,
    /// (table, column) pairs for newly added columns. In phase 2 these
    /// already exist in the database (added in phase 1) but may be NULL on
    /// existing rows; the hook is the place to backfill them.
    #[serde(default)]
    pub added_columns: Vec<(String, String)>,
    /// (table, column) pairs for columns that will be dropped in phase 3.
    /// During phase 2 these are still present in the database, so the hook
    /// can read them to populate new columns before they disappear.
    #[serde(default)]
    pub dropped_columns: Vec<(String, String)>,
    /// (table, column, old_type, new_type)
    #[serde(default)]
    pub type_changes: Vec<(String, String, String, String)>,
    /// (table, column, new_nullable)
    #[serde(default)]
    pub nullability_changes: Vec<(String, String, bool)>,
}

impl SchemaDiff {
    pub fn added_column(&self, table: &str, col: &str) -> bool {
        self.added_columns
            .iter()
            .any(|(t, c)| t == table && c == col)
    }

    pub fn dropped_column(&self, table: &str, col: &str) -> bool {
        self.dropped_columns
            .iter()
            .any(|(t, c)| t == table && c == col)
    }

    pub fn added_table(&self, table: &str) -> bool {
        self.added_tables.iter().any(|t| t == table)
    }

    pub fn dropped_table(&self, table: &str) -> bool {
        self.dropped_tables.iter().any(|t| t == table)
    }

    pub fn is_empty(&self) -> bool {
        self.added_tables.is_empty()
            && self.dropped_tables.is_empty()
            && self.added_columns.is_empty()
            && self.dropped_columns.is_empty()
            && self.type_changes.is_empty()
            && self.nullability_changes.is_empty()
    }
}

impl ServiceManifest {
    /// Get table definition by name
    pub fn get_table(&self, name: &str) -> Option<&TableDefinition> {
        self.tables.iter().find(|t| t.name == name)
    }

    /// Whether this manifest needs a WASM artifact bundled at deploy time.
    ///
    /// A WASM module is required when the service runs user code: explicit
    /// `mode: wasm`, an `on_migrate` schema hook, table CRUD lifecycle hooks,
    /// or any `Wasm` subscription/custom-route handler. The CLI uses this to
    /// decide whether to compile a WASM artifact; the platform uses it to
    /// reject deploys that arrive without one.
    pub fn requires_wasm(&self) -> bool {
        if self.mode == ServiceMode::Wasm {
            return true;
        }
        if self.on_migrate.is_some() {
            return true;
        }
        if self.tables.iter().any(|t| t.hooks.is_some()) {
            return true;
        }
        if !self.custom_routes.is_empty() {
            return true;
        }
        if self
            .subscriptions
            .iter()
            .any(|s| matches!(s.handler_type, HandlerType::Wasm))
        {
            return true;
        }
        false
    }

    /// All handler names this manifest expects the WASM module to export.
    /// Used at deploy time to reject manifests whose declared handlers are
    /// missing from the bundled binary.
    pub fn declared_wasm_handlers(&self) -> Vec<&str> {
        let mut handlers: Vec<&str> = Vec::new();
        if let Some(ref h) = self.on_migrate {
            handlers.push(h.as_str());
        }
        for route in &self.custom_routes {
            handlers.push(route.handler.as_str());
        }
        for sub in &self.subscriptions {
            if matches!(sub.handler_type, HandlerType::Wasm) {
                handlers.push(sub.handler.as_str());
            }
        }
        for table in &self.tables {
            if let Some(ref hooks) = table.hooks {
                for h in [
                    hooks.before_create.as_deref(),
                    hooks.after_create.as_deref(),
                    hooks.before_update.as_deref(),
                    hooks.after_update.as_deref(),
                    hooks.before_delete.as_deref(),
                    hooks.after_delete.as_deref(),
                ]
                .iter()
                .flatten()
                {
                    handlers.push(h);
                }
            }
        }
        handlers.sort();
        handlers.dedup();
        handlers
    }

    /// The `custom_routes` entry exposing `handler` over the HTTP `_fn/`
    /// surface, if any. Only custom routes are HTTP-invocable; subscription,
    /// `on_migrate`, and table-hook handlers run solely via their internal
    /// triggers, so a handler absent here must not be dispatched from an
    /// inbound request. Matched by name alone — the `_fn/` route accepts every
    /// method, so a verb-aware match would demote a job handler to inline
    /// execution on the wrong verb.
    pub fn http_route(&self, handler: &str) -> Option<&CustomRouteDefinition> {
        self.custom_routes.iter().find(|r| r.handler == handler)
    }

    /// Whether this manifest was built by a posture-aware SDK. True when any
    /// custom route carries a posture — the current SDK emits a posture on
    /// every route, so a posture-aware manifest is all-or-nothing and a lone
    /// undeclared route among declared ones signals tampering or a bug.
    pub fn is_posture_aware(&self) -> bool {
        self.custom_routes.iter().any(|r| r.posture.is_some())
    }

    /// SHA-256 of the whole manifest: the deploy skip check compares this, so
    /// a change to any field (`publishes`, `events`, `mode`, …) deploys.
    pub fn deploy_hash(&self) -> String {
        use sha2::{Digest, Sha256};
        hex::encode(Sha256::digest(serde_json::to_vec(self).unwrap_or_default()))
    }

    /// SHA-256 of the schema-bearing fields, stored on schema snapshots.
    pub fn schema_hash(&self) -> String {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(
            serde_json::to_string(&self.tables)
                .unwrap_or_default()
                .as_bytes(),
        );
        hasher.update(
            serde_json::to_string(&self.custom_routes)
                .unwrap_or_default()
                .as_bytes(),
        );
        hasher.update(
            serde_json::to_string(&self.subscriptions)
                .unwrap_or_default()
                .as_bytes(),
        );
        hasher.update(
            serde_json::to_string(&self.authorization)
                .unwrap_or_default()
                .as_bytes(),
        );
        hasher.update(
            serde_json::to_string(&self.on_migrate)
                .unwrap_or_default()
                .as_bytes(),
        );
        hex::encode(hasher.finalize())
    }
}

impl TableDefinition {
    /// Get the primary key column
    pub fn primary_key(&self) -> Option<&ColumnDefinition> {
        self.columns.iter().find(|c| c.primary_key)
    }

    /// Get all non-primary-key, non-auto columns (for INSERT/UPDATE)
    pub fn writable_columns(&self) -> Vec<&ColumnDefinition> {
        self.columns
            .iter()
            .filter(|c| !c.auto_generate || !c.primary_key)
            .collect()
    }
}

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

    fn sample_manifest() -> ServiceManifest {
        ServiceManifest {
            name: "test-service".into(),
            version: Some("1.0.0".into()),
            tables: vec![TableDefinition {
                name: "todos".into(),
                columns: vec![
                    ColumnDefinition {
                        name: "id".into(),
                        column_type: ColumnType::Uuid,
                        primary_key: true,
                        nullable: false,
                        auto_generate: true,
                        default_value: None,
                        references: None,
                        on_delete: None,
                        unique: false,
                        validations: vec![],
                    },
                    ColumnDefinition {
                        name: "title".into(),
                        column_type: ColumnType::Text,
                        primary_key: false,
                        nullable: false,
                        auto_generate: false,
                        default_value: None,
                        references: None,
                        on_delete: None,
                        unique: false,
                        validations: vec![],
                    },
                    ColumnDefinition {
                        name: "user_id".into(),
                        column_type: ColumnType::Uuid,
                        primary_key: false,
                        nullable: false,
                        auto_generate: false,
                        default_value: None,
                        references: Some("users.id".into()),
                        on_delete: Some(ForeignKeyAction::Cascade),
                        unique: false,
                        validations: vec![],
                    },
                ],
                indexes: vec![],
                soft_delete: false,
                owner_field: None,
                auth_required: false,
                permission_area: None,
                owner_self_service: false,
                hooks: None,
            }],
            cells: vec![],
            events: vec![],
            subscriptions: vec![],
            custom_routes: vec![],
            mode: ServiceMode::Crud,
            authorization: None,
            on_migrate: None,
            publishes: None,
            required_platform_features: vec![],
            graphql: false,
        }
    }

    #[test]
    fn test_manifest_serialization_roundtrip() {
        let manifest = sample_manifest();
        let json = serde_json::to_string(&manifest).unwrap();
        let parsed: ServiceManifest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "test-service");
        assert_eq!(parsed.tables.len(), 1);
        assert_eq!(parsed.tables[0].columns.len(), 3);
    }

    #[test]
    fn test_get_table() {
        let manifest = sample_manifest();
        assert!(manifest.get_table("todos").is_some());
        assert!(manifest.get_table("nonexistent").is_none());
    }

    #[test]
    fn test_primary_key() {
        let manifest = sample_manifest();
        let table = manifest.get_table("todos").unwrap();
        let pk = table.primary_key().unwrap();
        assert_eq!(pk.name, "id");
        assert!(pk.auto_generate);
    }

    #[test]
    fn test_schema_hash_deterministic() {
        let m1 = sample_manifest();
        let m2 = sample_manifest();
        assert_eq!(m1.schema_hash(), m2.schema_hash());
    }

    #[test]
    fn test_schema_hash_changes() {
        let mut m1 = sample_manifest();
        let m2 = sample_manifest();
        m1.tables[0].columns.push(ColumnDefinition {
            name: "extra".into(),
            column_type: ColumnType::Text,
            primary_key: false,
            nullable: true,
            auto_generate: false,
            default_value: None,
            references: None,
            on_delete: None,
            unique: false,
            validations: vec![],
        });
        assert_ne!(m1.schema_hash(), m2.schema_hash());
    }

    #[test]
    fn test_column_type_to_sql() {
        assert_eq!(ColumnType::Uuid.to_sql(), "UUID");
        assert_eq!(ColumnType::Text.to_sql(), "TEXT");
        assert_eq!(ColumnType::Integer.to_sql(), "INTEGER");
        assert_eq!(ColumnType::BigInteger.to_sql(), "BIGINT");
        assert_eq!(ColumnType::Boolean.to_sql(), "BOOLEAN");
        assert_eq!(ColumnType::Timestamp.to_sql(), "TIMESTAMPTZ");
        assert_eq!(ColumnType::Date.to_sql(), "DATE");
        assert_eq!(ColumnType::Jsonb.to_sql(), "JSONB");
    }

    #[test]
    fn test_fk_serialization() {
        let manifest = sample_manifest();
        let json = serde_json::to_string(&manifest).unwrap();
        assert!(json.contains("\"references\":\"users.id\""));
        assert!(json.contains("\"on_delete\":\"cascade\""));

        let parsed: ServiceManifest = serde_json::from_str(&json).unwrap();
        let user_id_col = &parsed.tables[0].columns[2];
        assert_eq!(user_id_col.references.as_deref(), Some("users.id"));
        assert_eq!(user_id_col.on_delete, Some(ForeignKeyAction::Cascade));
    }

    #[test]
    fn test_fk_not_serialized_when_none() {
        let col = ColumnDefinition {
            name: "title".into(),
            column_type: ColumnType::Text,
            primary_key: false,
            nullable: false,
            auto_generate: false,
            default_value: None,
            references: None,
            on_delete: None,
            unique: false,
            validations: vec![],
        };
        let json = serde_json::to_string(&col).unwrap();
        assert!(!json.contains("references"));
        assert!(!json.contains("on_delete"));
    }

    #[test]
    fn test_unique_column_serialization() {
        let col = ColumnDefinition {
            name: "email".into(),
            column_type: ColumnType::Text,
            primary_key: false,
            nullable: false,
            auto_generate: false,
            default_value: None,
            references: None,
            on_delete: None,
            unique: true,
            validations: vec![],
        };
        let json = serde_json::to_string(&col).unwrap();
        assert!(json.contains("\"unique\":true"));
        let parsed: ColumnDefinition = serde_json::from_str(&json).unwrap();
        assert!(parsed.unique);
    }

    #[test]
    fn test_index_serialization() {
        let table = TableDefinition {
            name: "users".into(),
            columns: vec![],
            indexes: vec![IndexDefinition {
                name: "idx_users_email".into(),
                columns: vec!["email".into()],
                unique: true,
            }],
            soft_delete: false,
            owner_field: None,
            auth_required: false,
            permission_area: None,
            owner_self_service: false,
            hooks: None,
        };
        let json = serde_json::to_string(&table).unwrap();
        assert!(json.contains("idx_users_email"));
        let parsed: TableDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.indexes.len(), 1);
        assert!(parsed.indexes[0].unique);
    }

    #[test]
    fn test_indexes_not_serialized_when_empty() {
        let table = TableDefinition {
            name: "users".into(),
            columns: vec![],
            indexes: vec![],
            soft_delete: false,
            owner_field: None,
            auth_required: false,
            permission_area: None,
            owner_self_service: false,
            hooks: None,
        };
        let json = serde_json::to_string(&table).unwrap();
        assert!(!json.contains("indexes"));
    }

    #[test]
    fn test_service_mode_default() {
        let json = r#"{"name":"svc","tables":[]}"#;
        let m: ServiceManifest = serde_json::from_str(json).unwrap();
        assert_eq!(m.mode, ServiceMode::Crud);
    }

    #[test]
    fn test_owner_field_serialization() {
        let table = TableDefinition {
            name: "notes".into(),
            columns: vec![],
            indexes: vec![],
            soft_delete: false,
            owner_field: Some("user_id".into()),
            auth_required: false,
            permission_area: None,
            owner_self_service: false,
            hooks: None,
        };
        let json = serde_json::to_string(&table).unwrap();
        assert!(json.contains("\"owner_field\":\"user_id\""));
        let parsed: TableDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.owner_field.as_deref(), Some("user_id"));
    }

    #[test]
    fn test_owner_field_not_serialized_when_none() {
        let table = TableDefinition {
            name: "notes".into(),
            columns: vec![],
            indexes: vec![],
            soft_delete: false,
            owner_field: None,
            auth_required: false,
            permission_area: None,
            owner_self_service: false,
            hooks: None,
        };
        let json = serde_json::to_string(&table).unwrap();
        assert!(!json.contains("owner_field"));
    }

    #[test]
    fn test_owner_field_defaults_to_none() {
        let json = r#"{"name":"notes","columns":[]}"#;
        let table: TableDefinition = serde_json::from_str(json).unwrap();
        assert!(table.owner_field.is_none());
    }

    #[test]
    fn test_auth_required_serialization() {
        let table = TableDefinition {
            name: "orders".into(),
            columns: vec![],
            indexes: vec![],
            soft_delete: false,
            owner_field: None,
            auth_required: true,
            permission_area: None,
            owner_self_service: false,
            hooks: None,
        };
        let json = serde_json::to_string(&table).unwrap();
        assert!(json.contains("\"auth_required\":true"));
        let parsed: TableDefinition = serde_json::from_str(&json).unwrap();
        assert!(parsed.auth_required);
    }

    #[test]
    fn test_auth_required_defaults_to_false() {
        let json = r#"{"name":"orders","columns":[]}"#;
        let table: TableDefinition = serde_json::from_str(json).unwrap();
        assert!(!table.auth_required);
    }

    #[test]
    fn test_on_migrate_defaults_to_none() {
        let json = r#"{"name":"svc","tables":[]}"#;
        let m: ServiceManifest = serde_json::from_str(json).unwrap();
        assert!(m.on_migrate.is_none());
    }

    #[test]
    fn test_on_migrate_serialization_roundtrip() {
        let mut m = sample_manifest();
        m.on_migrate = Some("handle_on_migrate".into());
        let json = serde_json::to_string(&m).unwrap();
        assert!(json.contains("\"on_migrate\":\"handle_on_migrate\""));
        let parsed: ServiceManifest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.on_migrate.as_deref(), Some("handle_on_migrate"));
    }

    #[test]
    fn test_on_migrate_skipped_when_none() {
        let m = sample_manifest();
        let json = serde_json::to_string(&m).unwrap();
        assert!(!json.contains("on_migrate"));
    }

    #[test]
    fn deploy_hash_covers_fields_schema_hash_ignores() {
        let m1 = sample_manifest();
        let mut m2 = sample_manifest();
        assert_eq!(m1.deploy_hash(), m2.deploy_hash());
        m2.publishes = Some(vec!["acme.orders.>".into()]);
        assert_ne!(m1.deploy_hash(), m2.deploy_hash());
        assert_eq!(m1.schema_hash(), m2.schema_hash());
    }

    #[test]
    fn test_on_migrate_changes_schema_hash() {
        let m1 = sample_manifest();
        let mut m2 = sample_manifest();
        m2.on_migrate = Some("handle_on_migrate".into());
        assert_ne!(m1.schema_hash(), m2.schema_hash());
    }

    #[test]
    fn test_subscription_stream_defaults_to_none_in_legacy_json() {
        let json = r#"{"subject":"x","handler":"h","handler_type":"wasm"}"#;
        let sub: SubscriptionDefinition = serde_json::from_str(json).unwrap();
        assert!(sub.stream.is_none());
    }

    #[test]
    fn test_subscription_stream_roundtrip_when_set() {
        let sub = SubscriptionDefinition {
            subject: "cufflink.tick.5min".into(),
            handler: "handle_tick_resync".into(),
            handler_type: HandlerType::Wasm,
            config: HashMap::new(),
            stream: Some("CUFFLINK_TICKS".into()),
        };
        let json = serde_json::to_string(&sub).unwrap();
        assert!(json.contains("\"stream\":\"CUFFLINK_TICKS\""));
        let parsed: SubscriptionDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.stream.as_deref(), Some("CUFFLINK_TICKS"));
    }

    #[test]
    fn test_subscription_stream_skipped_when_none() {
        let sub = SubscriptionDefinition {
            subject: "x".into(),
            handler: "h".into(),
            handler_type: HandlerType::Wasm,
            config: HashMap::new(),
            stream: None,
        };
        let json = serde_json::to_string(&sub).unwrap();
        assert!(!json.contains("stream"));
    }

    #[test]
    fn test_schema_diff_helpers() {
        let diff = SchemaDiff {
            added_tables: vec!["batches".into()],
            dropped_tables: vec!["legacy_batches".into()],
            added_columns: vec![("pickups".into(), "min".into())],
            dropped_columns: vec![("pickups".into(), "midpoint".into())],
            type_changes: vec![],
            nullability_changes: vec![],
        };
        assert!(!diff.is_empty());
        assert!(diff.added_table("batches"));
        assert!(!diff.added_table("nope"));
        assert!(diff.dropped_table("legacy_batches"));
        assert!(diff.added_column("pickups", "min"));
        assert!(!diff.added_column("pickups", "max"));
        assert!(diff.dropped_column("pickups", "midpoint"));
    }

    #[test]
    fn test_schema_diff_is_empty_default() {
        assert!(SchemaDiff::default().is_empty());
    }

    #[test]
    fn test_schema_diff_serialization_roundtrip() {
        let diff = SchemaDiff {
            added_tables: vec![],
            dropped_tables: vec![],
            added_columns: vec![("t".into(), "c".into())],
            dropped_columns: vec![],
            type_changes: vec![("t".into(), "c".into(), "TEXT".into(), "INTEGER".into())],
            nullability_changes: vec![("t".into(), "c".into(), false)],
        };
        let json = serde_json::to_string(&diff).unwrap();
        let parsed: SchemaDiff = serde_json::from_str(&json).unwrap();
        assert!(parsed.added_column("t", "c"));
        assert_eq!(parsed.type_changes.len(), 1);
        assert_eq!(parsed.nullability_changes.len(), 1);
    }

    #[test]
    fn test_requires_wasm_false_for_plain_crud() {
        let m = sample_manifest();
        assert!(!m.requires_wasm());
    }

    #[test]
    fn test_requires_wasm_true_for_wasm_mode() {
        let mut m = sample_manifest();
        m.mode = ServiceMode::Wasm;
        assert!(m.requires_wasm());
    }

    #[test]
    fn test_requires_wasm_true_for_on_migrate() {
        let mut m = sample_manifest();
        m.on_migrate = Some("handle_on_migrate".into());
        assert!(m.requires_wasm());
    }

    #[test]
    fn test_requires_wasm_true_for_table_hooks() {
        let mut m = sample_manifest();
        m.tables[0].hooks = Some(TableHooks {
            before_create: Some("validate".into()),
            ..Default::default()
        });
        assert!(m.requires_wasm());
    }

    #[test]
    fn test_requires_wasm_true_for_custom_routes() {
        let mut m = sample_manifest();
        m.custom_routes.push(CustomRouteDefinition {
            method: "GET".into(),
            path: "/hello".into(),
            handler: "hello".into(),
            job: None,
            posture: None,
            forward_auth: false,
        });
        assert!(m.requires_wasm());
    }

    #[test]
    fn test_requires_wasm_true_for_wasm_subscription() {
        let mut m = sample_manifest();
        m.subscriptions.push(SubscriptionDefinition {
            subject: "events.foo".into(),
            handler: "on_foo".into(),
            handler_type: HandlerType::Wasm,
            config: HashMap::new(),
            stream: None,
        });
        assert!(m.requires_wasm());
    }

    #[test]
    fn test_requires_wasm_false_for_non_wasm_subscription() {
        let mut m = sample_manifest();
        m.subscriptions.push(SubscriptionDefinition {
            subject: "events.foo".into(),
            handler: "on_foo".into(),
            handler_type: HandlerType::Webhook,
            config: HashMap::new(),
            stream: None,
        });
        assert!(!m.requires_wasm());
    }

    #[test]
    fn test_declared_wasm_handlers_collects_all_sources() {
        let mut m = sample_manifest();
        m.on_migrate = Some("on_mig".into());
        m.custom_routes.push(CustomRouteDefinition {
            method: "GET".into(),
            path: "/h".into(),
            handler: "route_h".into(),
            job: None,
            posture: None,
            forward_auth: false,
        });
        m.subscriptions.push(SubscriptionDefinition {
            subject: "x".into(),
            handler: "sub_h".into(),
            handler_type: HandlerType::Wasm,
            config: HashMap::new(),
            stream: None,
        });
        m.subscriptions.push(SubscriptionDefinition {
            subject: "y".into(),
            handler: "wh_ignored".into(),
            handler_type: HandlerType::Webhook,
            config: HashMap::new(),
            stream: None,
        });
        m.tables[0].hooks = Some(TableHooks {
            before_create: Some("bc".into()),
            after_create: Some("ac".into()),
            before_delete: Some("bc".into()), // duplicate handler name
            ..Default::default()
        });
        let handlers = m.declared_wasm_handlers();
        assert!(handlers.contains(&"on_mig"));
        assert!(handlers.contains(&"route_h"));
        assert!(handlers.contains(&"sub_h"));
        assert!(handlers.contains(&"bc"));
        assert!(handlers.contains(&"ac"));
        assert!(!handlers.contains(&"wh_ignored"));
        // Deduplicated
        assert_eq!(handlers.iter().filter(|h| **h == "bc").count(), 1);
    }

    #[test]
    fn http_route_exposes_only_custom_routes() {
        let mut m = sample_manifest();
        m.on_migrate = Some("on_mig".into());
        m.custom_routes.push(CustomRouteDefinition {
            method: "GET".into(),
            path: "/h".into(),
            handler: "route_h".into(),
            job: None,
            posture: None,
            forward_auth: false,
        });
        m.subscriptions.push(SubscriptionDefinition {
            subject: "evt.sub".into(),
            handler: "sub_h".into(),
            handler_type: HandlerType::Wasm,
            config: HashMap::new(),
            stream: None,
        });
        m.tables[0].hooks = Some(TableHooks {
            after_create: Some("hook_h".into()),
            ..Default::default()
        });

        assert_eq!(
            m.http_route("route_h").map(|r| r.handler.as_str()),
            Some("route_h")
        );
        assert!(m.http_route("sub_h").is_none());
        assert!(m.http_route("on_mig").is_none());
        assert!(m.http_route("hook_h").is_none());
        assert!(m.http_route("unknown").is_none());
    }

    #[test]
    fn http_route_allows_handler_declared_as_both_route_and_subscription() {
        let mut m = sample_manifest();
        m.custom_routes.push(CustomRouteDefinition {
            method: "POST".into(),
            path: "/dual".into(),
            handler: "dual".into(),
            job: Some(JobConfig::default()),
            posture: None,
            forward_auth: false,
        });
        m.subscriptions.push(SubscriptionDefinition {
            subject: "evt.dual".into(),
            handler: "dual".into(),
            handler_type: HandlerType::Wasm,
            config: HashMap::new(),
            stream: None,
        });

        let route = m
            .http_route("dual")
            .expect("dual-purpose handler stays HTTP-invocable");
        assert!(route.job.is_some());
    }

    #[test]
    fn job_config_defaults() {
        let cfg = JobConfig::default();
        assert_eq!(cfg.timeout_secs, JobConfig::DEFAULT_TIMEOUT_SECS);
        assert_eq!(cfg.max_attempts, JobConfig::DEFAULT_MAX_ATTEMPTS);
    }

    #[test]
    fn custom_route_serde_round_trip_with_job() {
        let route = CustomRouteDefinition {
            method: "POST".into(),
            path: "/run".into(),
            handler: "do_thing".into(),
            job: Some(JobConfig {
                timeout_secs: 900,
                max_attempts: 2,
            }),
            posture: None,
            forward_auth: false,
        };
        let json = serde_json::to_string(&route).unwrap();
        let round: CustomRouteDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(round.method, "POST");
        let job = round.job.unwrap();
        assert_eq!(job.timeout_secs, 900);
        assert_eq!(job.max_attempts, 2);
    }

    #[test]
    fn forward_auth_defaults_off_and_is_only_serialized_when_set() {
        let stored: CustomRouteDefinition =
            serde_json::from_str(r#"{"method":"GET","path":"/x","handler":"x"}"#).unwrap();
        assert!(!stored.forward_auth);
        let json = serde_json::to_string(&stored).unwrap();
        assert!(!json.contains("forward_auth"), "{json}");
        let forwarding = CustomRouteDefinition {
            forward_auth: true,
            ..stored
        };
        let json = serde_json::to_value(&forwarding).unwrap();
        assert_eq!(json["forward_auth"], true);
    }

    #[test]
    fn custom_route_without_job_serializes_without_field() {
        let route = CustomRouteDefinition {
            method: "GET".into(),
            path: "/x".into(),
            handler: "x".into(),
            job: None,
            posture: None,
            forward_auth: false,
        };
        let json = serde_json::to_value(&route).unwrap();
        assert!(json.get("job").is_none(), "absent job should be omitted");
        assert!(
            json.get("posture").is_none(),
            "absent posture should be omitted"
        );
    }

    #[test]
    fn custom_route_legacy_json_without_job_deserializes() {
        let json = r#"{"method":"GET","path":"/x","handler":"x"}"#;
        let route: CustomRouteDefinition = serde_json::from_str(json).unwrap();
        assert!(route.job.is_none());
        assert!(route.posture.is_none());
    }

    #[test]
    fn route_posture_serde_tagged_round_trip() {
        let cases = [
            RoutePosture::Public {
                reason: "stripe webhook".into(),
            },
            RoutePosture::Authenticated,
            RoutePosture::Permission {
                area: "items".into(),
                operation: "edit".into(),
            },
            RoutePosture::Owner {
                field: "customer_id".into(),
            },
        ];
        for p in cases {
            let json = serde_json::to_string(&p).unwrap();
            let round: RoutePosture = serde_json::from_str(&json).unwrap();
            assert_eq!(round, p);
        }
        let public = serde_json::to_value(RoutePosture::Authenticated).unwrap();
        assert_eq!(public["kind"], "authenticated");
    }

    #[test]
    fn posture_aware_detects_any_declared_route() {
        let mut m = sample_manifest();
        assert!(!m.is_posture_aware());
        m.custom_routes.push(CustomRouteDefinition {
            method: "GET".into(),
            path: "/a".into(),
            handler: "a".into(),
            job: None,
            posture: None,
            forward_auth: false,
        });
        assert!(!m.is_posture_aware());
        m.custom_routes.push(CustomRouteDefinition {
            method: "GET".into(),
            path: "/b".into(),
            handler: "b".into(),
            job: None,
            posture: Some(RoutePosture::Authenticated),
            forward_auth: false,
        });
        assert!(m.is_posture_aware());
    }

    #[test]
    fn manifest_publishes_and_features_default_absent() {
        let json = serde_json::to_value(sample_manifest()).unwrap();
        assert!(json.get("publishes").is_none());
        assert!(json.get("required_platform_features").is_none());
        let legacy = r#"{"name":"s","tables":[],"mode":"crud"}"#;
        let parsed: ServiceManifest = serde_json::from_str(legacy).unwrap();
        assert!(parsed.publishes.is_none());
        assert!(parsed.required_platform_features.is_empty());
    }
}