backbone-mail 0.2.32

Odoo mail core port — message/notification/followers/activity/alias/sms queue (schema: messaging)
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
# OpenAPI Schema Generation

This document describes how OpenAPI specifications are generated from model and workflow schemas, and how to customize REST API definitions.

---

## Overview

The schema system generates OpenAPI 3.0 specifications alongside gRPC proto files, enabling:

- **REST API documentation** from the same schema source
- **Client SDK generation** for multiple languages
- **API testing tools** integration (Postman, Insomnia)
- **API gateway configuration** (Kong, AWS API Gateway)

```
*.model.yaml + *.workflow.yaml
              ↓
    backbone-schema schema generate <module> --target openapi
              ↓
┌─────────────────────────────────────────┐
│ Generated Outputs:                       │
│ ✓ openapi.yaml (complete spec)          │
│ ✓ Per-entity endpoint definitions        │
│ ✓ Request/response schemas               │
│ ✓ Authentication requirements            │
│ ✓ Validation constraints                 │
└─────────────────────────────────────────┘
```

---

## Generation Strategy

### Non-Destructive Updates (Git-Aware)

The OpenAPI generator uses **git-aware incremental updates** to preserve hand-written customizations:

```
┌─────────────────────────────────────────────────────────────┐
│  1. READ EXISTING                                            │
│     - Load existing openapi.yaml (if exists)                │
│     - Parse into structured sections                         │
│     - Identify generated vs hand-written sections            │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│  2. GENERATE FROM SCHEMA                                     │
│     - Generate paths from models                             │
│     - Generate schemas from entities                         │
│     - Generate security from permissions                     │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│  3. SMART MERGE                                              │
│     - Compare generated vs existing                          │
│     - Preserve hand-written extensions                       │
│     - Update only schema-driven sections                     │
│     - Mark conflicts for manual resolution                   │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│  4. OUTPUT                                                   │
│     - Write merged openapi.yaml                              │
│     - Generate diff report                                   │
│     - List preserved customizations                          │
└─────────────────────────────────────────────────────────────┘
```

### Section Markers

Generated sections are marked to distinguish from hand-written code:

```yaml
# openapi.yaml

openapi: 3.0.3
info:
  title: Sapiens API
  version: 1.0.0
  # [CUSTOM] - Hand-written, preserved during regeneration
  description: |
    User management and authentication API.

    ## Authentication
    All endpoints require Bearer token authentication.

paths:
  # [GENERATED:users] - Auto-generated from user.model.yaml
  /api/v1/users:
    get:
      summary: List users
      # ... generated content
    post:
      summary: Create user
      # ... generated content

  # [CUSTOM] - Hand-written endpoint, preserved
  /api/v1/users/me:
    get:
      summary: Get current user
      # ... custom content

components:
  schemas:
    # [GENERATED:User] - Auto-generated from user.model.yaml
    User:
      type: object
      properties:
        # ... generated properties

    # [CUSTOM] - Hand-written schema
    UserPreferences:
      type: object
      # ... custom content
```

---

## CLI Commands

### Generate OpenAPI

```bash
# Generate OpenAPI for a module
backbone-cli schema:generate sapiens --target openapi

# Generate with diff preview (don't write)
backbone-cli schema:generate sapiens --target openapi --dry-run

# Force overwrite (ignore existing customizations)
backbone-cli schema:generate sapiens --target openapi --force

# Generate to specific output location
backbone-cli schema:generate sapiens --target openapi --output ./api/openapi.yaml
```

### Diff OpenAPI

```bash
# Show what would change in existing OpenAPI
backbone-cli schema:diff sapiens --target openapi

# Output:
# Modified: /api/v1/users (added field: avatar_url)
# Modified: User schema (added property: avatar_url)
# Preserved: /api/v1/users/me (custom endpoint)
# Preserved: UserPreferences schema (custom)
```

### Validate OpenAPI

```bash
# Validate generated OpenAPI against schema
backbone-cli schema:validate sapiens --target openapi

# Check for:
# - Missing endpoints for entities
# - Schema mismatches
# - Outdated generated sections
```

---

## Generated Structure

### From Model to OpenAPI

**Input: user.model.yaml**
```yaml
models:
  - name: User
    collection: users

    fields:
      id:
        type: uuid
        attributes: ["@id", "@default(uuid)"]

      email:
        type: email
        attributes: ["@unique", "@required"]

      username:
        type: string
        attributes: ["@min(3)", "@max(50)", "@required"]

      status:
        type: UserStatus
        attributes: ["@default(active)"]

      created_at:
        type: datetime
        attributes: ["@default(now)"]

      deleted_at:
        type: datetime?

enums:
  - name: UserStatus
    values:
      - active
      - inactive
      - suspended
```

**Output: openapi.yaml (paths section)**
```yaml
paths:
  # [GENERATED:users]
  /api/v1/users:
    get:
      operationId: listUsers
      summary: List users
      description: Retrieve a paginated list of users
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
        - $ref: '#/components/parameters/SortParam'
        - $ref: '#/components/parameters/FilterParam'
        - name: status
          in: query
          description: Filter by status
          schema:
            $ref: '#/components/schemas/UserStatus'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
      security:
        - bearerAuth: []

    post:
      operationId: createUser
      summary: Create user
      description: Create a new user
      tags:
        - Users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          $ref: '#/components/responses/Conflict'
      security:
        - bearerAuth: []

  /api/v1/users/{id}:
    get:
      operationId: getUser
      summary: Get user by ID
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/IdParam'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          $ref: '#/components/responses/NotFound'
      security:
        - bearerAuth: []

    put:
      operationId: updateUser
      summary: Update user
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/IdParam'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateUserRequest'
      responses:
        '200':
          description: User updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/ValidationError'
        '404':
          $ref: '#/components/responses/NotFound'
      security:
        - bearerAuth: []

    patch:
      operationId: partialUpdateUser
      summary: Partial update user
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/IdParam'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PatchUserRequest'
      responses:
        '200':
          description: User updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/ValidationError'
        '404':
          $ref: '#/components/responses/NotFound'
      security:
        - bearerAuth: []

    delete:
      operationId: deleteUser
      summary: Delete user (soft delete)
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/IdParam'
      responses:
        '204':
          description: User deleted
        '404':
          $ref: '#/components/responses/NotFound'
      security:
        - bearerAuth: []

  /api/v1/users/bulk:
    post:
      operationId: bulkCreateUsers
      summary: Bulk create users
      tags:
        - Users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BulkCreateUsersRequest'
      responses:
        '201':
          description: Users created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BulkCreateUsersResponse'
      security:
        - bearerAuth: []

  /api/v1/users/upsert:
    post:
      operationId: upsertUser
      summary: Upsert user
      tags:
        - Users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpsertUserRequest'
      responses:
        '200':
          description: User upserted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
      security:
        - bearerAuth: []

  /api/v1/users/trash:
    get:
      operationId: listDeletedUsers
      summary: List deleted users
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserListResponse'
      security:
        - bearerAuth: []

  /api/v1/users/{id}/restore:
    post:
      operationId: restoreUser
      summary: Restore deleted user
      tags:
        - Users
      parameters:
        - $ref: '#/components/parameters/IdParam'
      responses:
        '200':
          description: User restored
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          $ref: '#/components/responses/NotFound'
      security:
        - bearerAuth: []

  /api/v1/users/empty:
    delete:
      operationId: emptyUsersTrash
      summary: Empty trash (permanent delete)
      tags:
        - Users
      responses:
        '204':
          description: Trash emptied
      security:
        - bearerAuth: []
```

**Output: openapi.yaml (schemas section)**
```yaml
components:
  schemas:
    # [GENERATED:User]
    User:
      type: object
      required:
        - id
        - email
        - username
        - status
        - created_at
      properties:
        id:
          type: string
          format: uuid
          readOnly: true
          description: Unique identifier
        email:
          type: string
          format: email
          description: User email address
        username:
          type: string
          minLength: 3
          maxLength: 50
          description: Username
        status:
          $ref: '#/components/schemas/UserStatus'
        created_at:
          type: string
          format: date-time
          readOnly: true
        deleted_at:
          type: string
          format: date-time
          nullable: true
          readOnly: true

    # [GENERATED:UserStatus]
    UserStatus:
      type: string
      enum:
        - active
        - inactive
        - suspended
      default: active

    # [GENERATED:CreateUserRequest]
    CreateUserRequest:
      type: object
      required:
        - email
        - username
      properties:
        email:
          type: string
          format: email
        username:
          type: string
          minLength: 3
          maxLength: 50
        status:
          $ref: '#/components/schemas/UserStatus'

    # [GENERATED:UpdateUserRequest]
    UpdateUserRequest:
      type: object
      required:
        - email
        - username
        - status
      properties:
        email:
          type: string
          format: email
        username:
          type: string
          minLength: 3
          maxLength: 50
        status:
          $ref: '#/components/schemas/UserStatus'

    # [GENERATED:PatchUserRequest]
    PatchUserRequest:
      type: object
      properties:
        email:
          type: string
          format: email
        username:
          type: string
          minLength: 3
          maxLength: 50
        status:
          $ref: '#/components/schemas/UserStatus'

    # [GENERATED:UserListResponse]
    UserListResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/User'
        meta:
          $ref: '#/components/schemas/PaginationMeta'
```

---

## Workflow Integration

### State Transitions as Endpoints

**Input: user.workflow.yaml**
```yaml
states:
  field: status

  transitions:
    verify:
      from: pending_verification
      to: active
      roles: [system]

    suspend:
      from: [active, inactive]
      to: suspended
      roles: [admin]

    reactivate:
      from: suspended
      to: active
      roles: [admin]
```

**Output: Transition endpoints**
```yaml
paths:
  # [GENERATED:users:transitions]
  /api/v1/users/{id}/verify:
    post:
      operationId: verifyUser
      summary: Verify user
      description: |
        Transition user status from `pending_verification` to `active`.

        **Allowed roles:** system
      tags:
        - Users
        - State Transitions
      parameters:
        - $ref: '#/components/parameters/IdParam'
      responses:
        '200':
          description: User verified
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: Invalid transition
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransitionError'
        '404':
          $ref: '#/components/responses/NotFound'
      security:
        - bearerAuth: []

  /api/v1/users/{id}/suspend:
    post:
      operationId: suspendUser
      summary: Suspend user
      description: |
        Transition user status from `active` or `inactive` to `suspended`.

        **Allowed roles:** admin
      tags:
        - Users
        - State Transitions
      parameters:
        - $ref: '#/components/parameters/IdParam'
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                reason:
                  type: string
                  description: Reason for suspension
      responses:
        '200':
          description: User suspended
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/InvalidTransition'
      security:
        - bearerAuth: []

  /api/v1/users/{id}/reactivate:
    post:
      operationId: reactivateUser
      summary: Reactivate user
      description: |
        Transition user status from `suspended` to `active`.

        **Allowed roles:** admin
      tags:
        - Users
        - State Transitions
      parameters:
        - $ref: '#/components/parameters/IdParam'
      responses:
        '200':
          description: User reactivated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/InvalidTransition'
      security:
        - bearerAuth: []
```

### Permissions as Security Requirements

**Input: user.workflow.yaml**
```yaml
permissions:
  admin:
    allow:
      - all

  user:
    allow:
      - action: read
        if: "id == $actor.id"
      - action: update
        if: "id == $actor.id"
        only: [email, username]
    deny:
      - delete
```

**Output: Security schemes and role documentation**
```yaml
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        JWT token authentication.

        Include the token in the Authorization header:
        ```
        Authorization: Bearer <token>
        ```

  # Role-based access documentation
  x-roles:
    admin:
      description: Full access to all operations
      permissions:
        - all

    user:
      description: Limited access to own resources
      permissions:
        - read (own)
        - update (own, fields: email, username)
      restrictions:
        - Cannot delete

# Endpoint-specific security notes
paths:
  /api/v1/users/{id}:
    get:
      x-permissions:
        admin: "Full access"
        user: "Only if id == actor.id"
```

---

## Validation Rules in OpenAPI

**Input: user.workflow.yaml**
```yaml
rules:
  username_format:
    condition: "username matches '^[a-z0-9_]{3,50}$'"
    message: "Username must be 3-50 lowercase alphanumeric"
    code: INVALID_USERNAME

  password_strength:
    condition: |
      password.length >= 8 &&
      password matches '[A-Z]' &&
      password matches '[a-z]' &&
      password matches '[0-9]'
    message: "Password must be 8+ characters with uppercase, lowercase, and number"
    code: WEAK_PASSWORD
```

**Output: Schema with validation**
```yaml
components:
  schemas:
    CreateUserRequest:
      type: object
      properties:
        username:
          type: string
          pattern: '^[a-z0-9_]{3,50}$'
          description: |
            Username must be 3-50 lowercase alphanumeric.

            **Validation code:** INVALID_USERNAME

        password:
          type: string
          minLength: 8
          description: |
            Password must be 8+ characters with uppercase, lowercase, and number.

            **Validation code:** WEAK_PASSWORD
          x-validation:
            - pattern: '[A-Z]'
              message: Must contain uppercase letter
            - pattern: '[a-z]'
              message: Must contain lowercase letter
            - pattern: '[0-9]'
              message: Must contain number
```

---

## Customization Options

### OpenAPI Overrides File

Create `*.openapi.yaml` files to customize generated OpenAPI:

```yaml
# libs/modules/sapiens/schema/openapi/user.openapi.yaml

# Override or extend generated OpenAPI for User
overrides:
  # Custom info section
  info:
    description: |
      Extended description for User API.

      ## Rate Limits
      - 100 requests per minute for read operations
      - 10 requests per minute for write operations

  # Override specific paths
  paths:
    /api/v1/users:
      get:
        # Add custom parameter
        parameters:
          - name: include_deleted
            in: query
            schema:
              type: boolean
            description: Include soft-deleted users

        # Override responses
        responses:
          '200':
            description: Custom description
            headers:
              X-Rate-Limit-Remaining:
                schema:
                  type: integer

  # Add custom endpoints (preserved during regeneration)
  custom_paths:
    /api/v1/users/me:
      get:
        operationId: getCurrentUser
        summary: Get current authenticated user
        tags:
          - Users
        responses:
          '200':
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/User'

    /api/v1/users/search:
      post:
        operationId: searchUsers
        summary: Advanced user search
        requestBody:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserSearchRequest'

  # Add custom schemas
  custom_schemas:
    UserSearchRequest:
      type: object
      properties:
        query:
          type: string
        filters:
          type: object
          additionalProperties: true
```

### Module-Level OpenAPI Config

In `index.model.yaml`:

```yaml
module: sapiens
version: 1

openapi:
  title: Sapiens User Management API
  version: 1.0.0
  description: User management, authentication, and authorization

  servers:
    - url: https://api.example.com
      description: Production
    - url: https://staging-api.example.com
      description: Staging
    - url: http://localhost:3001
      description: Local development

  tags:
    - name: Users
      description: User management operations
    - name: Authentication
      description: Login, logout, and token management
    - name: Roles
      description: Role and permission management

  security:
    default: bearerAuth

  responses:
    include_rate_limit_headers: true
    include_request_id: true
```

---

## Merge Strategies

### What Gets Preserved

| Section | Behavior |
|---------|----------|
| `info.description` | Preserved if marked `[CUSTOM]` |
| `info.contact`, `info.license` | Always preserved |
| `servers` | Merged (custom servers added) |
| `paths` (generated entities) | Updated from schema |
| `paths` (custom endpoints) | Preserved |
| `components/schemas` (generated) | Updated from schema |
| `components/schemas` (custom) | Preserved |
| `components/securitySchemes` | Merged |
| `x-*` extensions | Preserved |

### What Gets Updated

- Entity CRUD paths (`/api/v1/{collection}/*`)
- Entity schemas (`User`, `CreateUserRequest`, etc.)
- Enum schemas
- Transition endpoints (from workflow)
- Validation patterns and constraints

### Conflict Resolution

When a conflict is detected:

```bash
$ backbone-cli schema:generate sapiens --target openapi

⚠ Conflict detected in /api/v1/users:
  - Schema says: email is required
  - Existing says: email is optional

Options:
  1. Use schema definition (recommended)
  2. Keep existing (manual override)
  3. Skip this endpoint

Enter choice [1/2/3]:
```

Or use flags:

```bash
# Always use schema definition
backbone-cli schema:generate sapiens --target openapi --strategy schema-wins

# Always preserve existing
backbone-cli schema:generate sapiens --target openapi --strategy existing-wins

# Generate conflict markers
backbone-cli schema:generate sapiens --target openapi --strategy mark-conflicts
```

---

## Type Mapping

### Schema Type to OpenAPI Type

| Schema Type | OpenAPI Type | Format | Additional |
|-------------|--------------|--------|------------|
| `uuid` | `string` | `uuid` | |
| `string` | `string` | | |
| `int` | `integer` | `int32` | |
| `int64` | `integer` | `int64` | |
| `float` | `number` | `float` | |
| `float64` | `number` | `double` | |
| `bool` | `boolean` | | |
| `datetime` | `string` | `date-time` | |
| `date` | `string` | `date` | |
| `time` | `string` | `time` | |
| `email` | `string` | `email` | |
| `url` | `string` | `uri` | |
| `phone` | `string` | | `pattern: ^\+?[1-9]\d{1,14}$` |
| `ip` | `string` | | `oneOf: [ipv4, ipv6]` |
| `json` | `object` | | `additionalProperties: true` |
| `decimal` | `string` | | `pattern: ^\d+\.\d+$` |
| `money` | `object` | | `{amount, currency}` |
| `bytes` | `string` | `byte` | |
| `Type?` | | | `nullable: true` |
| `Type[]` | `array` | | `items: {$ref}` |

### Attribute to OpenAPI Constraint

| Attribute | OpenAPI Property |
|-----------|------------------|
| `@required` | `required: [field]` |
| `@min(n)` | `minLength: n` (string) or `minimum: n` (number) |
| `@max(n)` | `maxLength: n` (string) or `maximum: n` (number) |
| `@unique` | (documented in description) |
| `@default(v)` | `default: v` |
| `@pattern(regex)` | `pattern: regex` |
| `@email` | `format: email` |
| `@url` | `format: uri` |
| `@sensitive` | (excluded from response, `writeOnly: true`) |

---

## Output Files

```
libs/modules/{module}/
├── schema/
│   ├── models/
│   ├── workflows/
│   └── openapi/                    # OpenAPI customizations
│       ├── index.openapi.yaml      # Module-level config
│       └── {entity}.openapi.yaml   # Per-entity overrides
│
└── openapi/                        # Generated OpenAPI
    ├── openapi.yaml                # Complete spec (single file)
    ├── paths/                      # Split paths (optional)
    │   ├── users.yaml
    │   └── roles.yaml
    └── schemas/                    # Split schemas (optional)
        ├── user.yaml
        └── role.yaml
```

---

## Integration Examples

### Swagger UI

```yaml
# docker-compose.yml
services:
  swagger-ui:
    image: swaggerapi/swagger-ui
    ports:
      - "8080:8080"
    environment:
      SWAGGER_JSON: /openapi/openapi.yaml
    volumes:
      - ./libs/modules/sapiens/openapi:/openapi
```

### API Gateway (Kong)

```bash
# Import OpenAPI to Kong
deck sync --kong-addr http://localhost:8001 \
  --openapi-spec libs/modules/sapiens/openapi/openapi.yaml
```

### Client SDK Generation

```bash
# Generate TypeScript client
openapi-generator generate \
  -i libs/modules/sapiens/openapi/openapi.yaml \
  -g typescript-axios \
  -o clients/typescript

# Generate Rust client
openapi-generator generate \
  -i libs/modules/sapiens/openapi/openapi.yaml \
  -g rust \
  -o clients/rust
```

---

## Best Practices

### 1. Keep Custom Endpoints Separate

```yaml
# Good: Use openapi/ override files
schema/openapi/user.openapi.yaml:
  custom_paths:
    /api/v1/users/me: ...

# Avoid: Mixing custom with generated
# (will be overwritten on regeneration)
```

### 2. Use Descriptive Operation IDs

Operation IDs are auto-generated but can be overridden:

```yaml
# Generated: listUsers, createUser, getUser
# Override in openapi file if needed:
overrides:
  paths:
    /api/v1/users:
      get:
        operationId: getAllUsers  # Custom ID
```

### 3. Document Business Rules

Add `x-business-rules` extension for complex validations:

```yaml
components:
  schemas:
    CreateOrderRequest:
      x-business-rules:
        - name: minimum_order
          description: Order total must be at least $10
          code: MINIMUM_ORDER_AMOUNT
        - name: items_in_stock
          description: All items must be in stock
          code: ITEMS_OUT_OF_STOCK
```

### 4. Version Your API

```yaml
# index.model.yaml
openapi:
  version: 2.0.0  # Bump when breaking changes

# paths use version prefix
paths:
  /api/v2/users: ...  # New version
  /api/v1/users: ...  # Deprecated
```

---

## Next Steps

- [RULE_FORMAT_MODELS.md]./RULE_FORMAT_MODELS.md — entity definition syntax
- [RULE_FORMAT_HOOKS.md]./RULE_FORMAT_HOOKS.md — state machines, validation, permissions
- [RULE_FORMAT_WORKFLOWS.md]./RULE_FORMAT_WORKFLOWS.md — multi-step business processes
- [GENERATION.md]./GENERATION.md — generator targets and CLI
- [GENERATION.md]./GENERATION.md - All code generation targets