@autobe/agent 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/lib/agent/src/AutoBeAgent.js +3 -2
  2. package/lib/agent/src/AutoBeAgent.js.map +1 -1
  3. package/lib/agent/src/AutoBeMockAgent.js +3 -3
  4. package/lib/agent/src/constants/AutoBeSystemPromptConstant.d.ts +6 -6
  5. package/lib/agent/src/context/AutoBeContext.d.ts +1 -0
  6. package/lib/agent/src/factory/consentFunctionCall.js +3 -2
  7. package/lib/agent/src/factory/consentFunctionCall.js.map +1 -1
  8. package/lib/agent/src/factory/createAutoBeContext.js +8 -5
  9. package/lib/agent/src/factory/createAutoBeContext.js.map +1 -1
  10. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeReviewHistories.d.ts +6 -0
  11. package/lib/agent/src/orchestrate/analyze/histories/{transformAnalyzeReviewerHistories.js → transformAnalyzeReviewHistories.js} +24 -29
  12. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeReviewHistories.js.map +1 -0
  13. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeScenarioHistories.js +12 -9
  14. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeScenarioHistories.js.map +1 -1
  15. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeWriteHistories.js +31 -29
  16. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeWriteHistories.js.map +1 -1
  17. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyze.js +19 -5
  18. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyze.js.map +1 -1
  19. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeReview.d.ts +7 -1
  20. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeReview.js +9 -6
  21. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeReview.js.map +1 -1
  22. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeScenario.js +11 -9
  23. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeScenario.js.map +1 -1
  24. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeWrite.d.ts +6 -4
  25. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeWrite.js +5 -1
  26. package/lib/agent/src/orchestrate/analyze/orchestrateAnalyzeWrite.js.map +1 -1
  27. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceAssetHistories.js +45 -46
  28. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceAssetHistories.js.map +1 -1
  29. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceAuthorizationsHistories.js +13 -13
  30. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceAuthorizationsHistories.js.map +1 -1
  31. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceComplementHistories.js +31 -30
  32. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceComplementHistories.js.map +1 -1
  33. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceEndpointHistories.js +23 -22
  34. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceEndpointHistories.js.map +1 -1
  35. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceGroupHistories.js +2 -2
  36. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceOperationHistories.js +27 -26
  37. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceOperationHistories.js.map +1 -1
  38. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceOperationsReviewHistories.js +13 -12
  39. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceOperationsReviewHistories.js.map +1 -1
  40. package/lib/agent/src/orchestrate/interface/histories/transformInterfacePrerequisiteHistories.js +4 -4
  41. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceSchemaHistories.js +11 -10
  42. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceSchemaHistories.js.map +1 -1
  43. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceSchemasReviewHistories.js +31 -30
  44. package/lib/agent/src/orchestrate/interface/histories/transformInterfaceSchemasReviewHistories.js.map +1 -1
  45. package/lib/agent/src/orchestrate/interface/orchestrateInterface.js +3 -1
  46. package/lib/agent/src/orchestrate/interface/orchestrateInterface.js.map +1 -1
  47. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceAuthorizations.js +22 -18
  48. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceAuthorizations.js.map +1 -1
  49. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceComplement.js +2 -0
  50. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceComplement.js.map +1 -1
  51. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceEndpoints.js +6 -2
  52. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceEndpoints.js.map +1 -1
  53. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceGroups.js +2 -0
  54. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceGroups.js.map +1 -1
  55. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceOperations.js +74 -48
  56. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceOperations.js.map +1 -1
  57. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceOperationsReview.js +24 -4
  58. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceOperationsReview.js.map +1 -1
  59. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceSchemas.js +30 -24
  60. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceSchemas.js.map +1 -1
  61. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceSchemasReview.d.ts +2 -5
  62. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceSchemasReview.js +178 -0
  63. package/lib/agent/src/orchestrate/interface/orchestrateInterfaceSchemasReview.js.map +1 -1
  64. package/lib/agent/src/orchestrate/interface/structures/IAutoBeInterfaceOperationApplication.d.ts +38 -0
  65. package/lib/agent/src/orchestrate/interface/structures/IAutoBeInterfaceOperationsReviewApplication.d.ts +38 -0
  66. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaComponentsHistories.js +54 -54
  67. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaComponentsHistories.js.map +1 -1
  68. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaCorrectHistories.js +18 -29
  69. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaCorrectHistories.js.map +1 -1
  70. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaReviewHistories.js +37 -34
  71. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaReviewHistories.js.map +1 -1
  72. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaSchemaHistories.js +38 -25
  73. package/lib/agent/src/orchestrate/prisma/histories/transformPrismaSchemaHistories.js.map +1 -1
  74. package/lib/agent/src/orchestrate/prisma/orchestratePrisma.js +3 -1
  75. package/lib/agent/src/orchestrate/prisma/orchestratePrisma.js.map +1 -1
  76. package/lib/agent/src/orchestrate/prisma/orchestratePrismaComponent.js +2 -0
  77. package/lib/agent/src/orchestrate/prisma/orchestratePrismaComponent.js.map +1 -1
  78. package/lib/agent/src/orchestrate/prisma/orchestratePrismaCorrect.js +3 -0
  79. package/lib/agent/src/orchestrate/prisma/orchestratePrismaCorrect.js.map +1 -1
  80. package/lib/agent/src/orchestrate/prisma/orchestratePrismaReview.js +19 -9
  81. package/lib/agent/src/orchestrate/prisma/orchestratePrismaReview.js.map +1 -1
  82. package/lib/agent/src/orchestrate/prisma/orchestratePrismaSchemas.js +28 -21
  83. package/lib/agent/src/orchestrate/prisma/orchestratePrismaSchemas.js.map +1 -1
  84. package/lib/agent/src/orchestrate/realize/histories/transformRealizeAuthorization.js +24 -21
  85. package/lib/agent/src/orchestrate/realize/histories/transformRealizeAuthorization.js.map +1 -1
  86. package/lib/agent/src/orchestrate/realize/histories/transformRealizeAuthorizationCorrectHistories.js +58 -56
  87. package/lib/agent/src/orchestrate/realize/histories/transformRealizeAuthorizationCorrectHistories.js.map +1 -1
  88. package/lib/agent/src/orchestrate/realize/histories/transformRealizeCorrectHistories.js +17 -13
  89. package/lib/agent/src/orchestrate/realize/histories/transformRealizeCorrectHistories.js.map +1 -1
  90. package/lib/agent/src/orchestrate/realize/histories/transformRealizeWriteAuthorizationsHistories.js +12 -3
  91. package/lib/agent/src/orchestrate/realize/histories/transformRealizeWriteAuthorizationsHistories.js.map +1 -1
  92. package/lib/agent/src/orchestrate/realize/histories/transformRealizeWriteHistories.js +35 -30
  93. package/lib/agent/src/orchestrate/realize/histories/transformRealizeWriteHistories.js.map +1 -1
  94. package/lib/{orchestrate/realize/internal/compile.d.ts → agent/src/orchestrate/realize/internal/compileRealizeFiles.d.ts} +1 -1
  95. package/lib/agent/src/orchestrate/realize/internal/{compile.js → compileRealizeFiles.js} +6 -6
  96. package/lib/agent/src/orchestrate/realize/internal/compileRealizeFiles.js.map +1 -0
  97. package/lib/agent/src/orchestrate/realize/orchestrateRealize.js +26 -12
  98. package/lib/agent/src/orchestrate/realize/orchestrateRealize.js.map +1 -1
  99. package/lib/agent/src/orchestrate/realize/orchestrateRealizeAuthorization.js +9 -3
  100. package/lib/agent/src/orchestrate/realize/orchestrateRealizeAuthorization.js.map +1 -1
  101. package/lib/agent/src/orchestrate/realize/orchestrateRealizeAuthorizationCorrect.js +3 -1
  102. package/lib/agent/src/orchestrate/realize/orchestrateRealizeAuthorizationCorrect.js.map +1 -1
  103. package/lib/agent/src/orchestrate/realize/orchestrateRealizeCorrect.d.ts +2 -6
  104. package/lib/agent/src/orchestrate/realize/orchestrateRealizeCorrect.js +8 -4
  105. package/lib/agent/src/orchestrate/realize/orchestrateRealizeCorrect.js.map +1 -1
  106. package/lib/agent/src/orchestrate/realize/orchestrateRealizeScenario.d.ts +0 -66
  107. package/lib/agent/src/orchestrate/realize/orchestrateRealizeScenario.js.map +1 -1
  108. package/lib/agent/src/orchestrate/realize/orchestrateRealizeWrite.d.ts +3 -6
  109. package/lib/agent/src/orchestrate/realize/orchestrateRealizeWrite.js +21 -17
  110. package/lib/agent/src/orchestrate/realize/orchestrateRealizeWrite.js.map +1 -1
  111. package/lib/agent/src/orchestrate/test/compile/completeTestCode.js +13 -10
  112. package/lib/agent/src/orchestrate/test/compile/completeTestCode.js.map +1 -1
  113. package/lib/agent/src/orchestrate/test/histories/transformTestCorrectHistories.js +16 -15
  114. package/lib/agent/src/orchestrate/test/histories/transformTestCorrectHistories.js.map +1 -1
  115. package/lib/agent/src/orchestrate/test/histories/transformTestHistories.js +33 -32
  116. package/lib/agent/src/orchestrate/test/histories/transformTestHistories.js.map +1 -1
  117. package/lib/agent/src/orchestrate/test/histories/transformTestScenarioHistories.js +62 -59
  118. package/lib/agent/src/orchestrate/test/histories/transformTestScenarioHistories.js.map +1 -1
  119. package/lib/agent/src/orchestrate/test/histories/transformTestWriteHistories.js +2 -2
  120. package/lib/agent/src/orchestrate/test/orchestrateTest.js +6 -5
  121. package/lib/agent/src/orchestrate/test/orchestrateTest.js.map +1 -1
  122. package/lib/agent/src/orchestrate/test/orchestrateTestCorrect.js +16 -7
  123. package/lib/agent/src/orchestrate/test/orchestrateTestCorrect.js.map +1 -1
  124. package/lib/agent/src/orchestrate/test/orchestrateTestScenario.js +20 -8
  125. package/lib/agent/src/orchestrate/test/orchestrateTestScenario.js.map +1 -1
  126. package/lib/agent/src/orchestrate/test/orchestrateTestWrite.js +17 -17
  127. package/lib/agent/src/orchestrate/test/orchestrateTestWrite.js.map +1 -1
  128. package/lib/agent/src/orchestrate/test/structures/IAutoBeTestCorrectApplication.d.ts +2 -2
  129. package/lib/agent/src/orchestrate/test/structures/IAutoBeTestWriteApplication.d.ts +2 -2
  130. package/lib/agent/src/utils/executeCachedBatch.d.ts +1 -0
  131. package/lib/agent/src/utils/executeCachedBatch.js +23 -0
  132. package/lib/agent/src/utils/executeCachedBatch.js.map +1 -0
  133. package/lib/constants/AutoBeSystemPromptConstant.d.ts +6 -6
  134. package/lib/context/AutoBeContext.d.ts +1 -0
  135. package/lib/index.mjs +1044 -270
  136. package/lib/index.mjs.map +1 -1
  137. package/lib/orchestrate/analyze/histories/transformAnalyzeReviewHistories.d.ts +6 -0
  138. package/lib/orchestrate/analyze/orchestrateAnalyzeReview.d.ts +7 -1
  139. package/lib/orchestrate/analyze/orchestrateAnalyzeWrite.d.ts +6 -4
  140. package/lib/orchestrate/interface/orchestrateInterfaceSchemasReview.d.ts +2 -5
  141. package/lib/orchestrate/interface/structures/IAutoBeInterfaceOperationApplication.d.ts +38 -0
  142. package/lib/orchestrate/interface/structures/IAutoBeInterfaceOperationsReviewApplication.d.ts +38 -0
  143. package/lib/{agent/src/orchestrate/realize/internal/compile.d.ts → orchestrate/realize/internal/compileRealizeFiles.d.ts} +1 -1
  144. package/lib/orchestrate/realize/orchestrateRealizeCorrect.d.ts +2 -6
  145. package/lib/orchestrate/realize/orchestrateRealizeScenario.d.ts +0 -66
  146. package/lib/orchestrate/realize/orchestrateRealizeWrite.d.ts +3 -6
  147. package/lib/orchestrate/test/structures/IAutoBeTestCorrectApplication.d.ts +2 -2
  148. package/lib/orchestrate/test/structures/IAutoBeTestWriteApplication.d.ts +2 -2
  149. package/lib/utils/executeCachedBatch.d.ts +1 -0
  150. package/package.json +6 -6
  151. package/src/AutoBeAgent.ts +4 -3
  152. package/src/AutoBeMockAgent.ts +4 -4
  153. package/src/constants/AutoBeSystemPromptConstant.ts +6 -6
  154. package/src/context/AutoBeContext.ts +1 -0
  155. package/src/factory/consentFunctionCall.ts +4 -3
  156. package/src/factory/createAutoBeContext.ts +9 -6
  157. package/src/orchestrate/analyze/histories/{transformAnalyzeReviewerHistories.ts → transformAnalyzeReviewHistories.ts} +23 -30
  158. package/src/orchestrate/analyze/histories/transformAnalyzeScenarioHistories.ts +13 -10
  159. package/src/orchestrate/analyze/histories/transformAnalyzeWriteHistories.ts +60 -61
  160. package/src/orchestrate/analyze/orchestrateAnalyze.ts +20 -13
  161. package/src/orchestrate/analyze/orchestrateAnalyzeReview.ts +20 -9
  162. package/src/orchestrate/analyze/orchestrateAnalyzeScenario.ts +13 -11
  163. package/src/orchestrate/analyze/orchestrateAnalyzeWrite.ts +10 -5
  164. package/src/orchestrate/interface/histories/transformInterfaceAssetHistories.ts +47 -48
  165. package/src/orchestrate/interface/histories/transformInterfaceAuthorizationsHistories.ts +14 -14
  166. package/src/orchestrate/interface/histories/transformInterfaceComplementHistories.ts +31 -30
  167. package/src/orchestrate/interface/histories/transformInterfaceEndpointHistories.ts +20 -19
  168. package/src/orchestrate/interface/histories/transformInterfaceGroupHistories.ts +3 -3
  169. package/src/orchestrate/interface/histories/transformInterfaceOperationHistories.ts +23 -22
  170. package/src/orchestrate/interface/histories/transformInterfaceOperationsReviewHistories.ts +12 -11
  171. package/src/orchestrate/interface/histories/transformInterfacePrerequisiteHistories.ts +5 -5
  172. package/src/orchestrate/interface/histories/transformInterfaceSchemaHistories.ts +11 -10
  173. package/src/orchestrate/interface/histories/transformInterfaceSchemasReviewHistories.ts +31 -30
  174. package/src/orchestrate/interface/orchestrateInterface.ts +4 -2
  175. package/src/orchestrate/interface/orchestrateInterfaceAuthorizations.ts +36 -29
  176. package/src/orchestrate/interface/orchestrateInterfaceComplement.ts +2 -0
  177. package/src/orchestrate/interface/orchestrateInterfaceEndpoints.ts +13 -9
  178. package/src/orchestrate/interface/orchestrateInterfaceGroups.ts +2 -0
  179. package/src/orchestrate/interface/orchestrateInterfaceOperations.ts +53 -50
  180. package/src/orchestrate/interface/orchestrateInterfaceOperationsReview.ts +2 -0
  181. package/src/orchestrate/interface/orchestrateInterfaceSchemas.ts +47 -23
  182. package/src/orchestrate/interface/orchestrateInterfaceSchemasReview.ts +85 -1
  183. package/src/orchestrate/interface/structures/IAutoBeInterfaceOperationApplication.ts +39 -0
  184. package/src/orchestrate/interface/structures/IAutoBeInterfaceOperationsReviewApplication.ts +40 -1
  185. package/src/orchestrate/prisma/histories/transformPrismaComponentsHistories.ts +57 -55
  186. package/src/orchestrate/prisma/histories/transformPrismaCorrectHistories.ts +19 -30
  187. package/src/orchestrate/prisma/histories/transformPrismaReviewHistories.ts +38 -35
  188. package/src/orchestrate/prisma/histories/transformPrismaSchemaHistories.ts +36 -23
  189. package/src/orchestrate/prisma/orchestratePrisma.ts +4 -2
  190. package/src/orchestrate/prisma/orchestratePrismaComponent.ts +2 -0
  191. package/src/orchestrate/prisma/orchestratePrismaCorrect.ts +3 -0
  192. package/src/orchestrate/prisma/orchestratePrismaReview.ts +26 -13
  193. package/src/orchestrate/prisma/orchestratePrismaSchemas.ts +25 -17
  194. package/src/orchestrate/realize/histories/transformRealizeAuthorization.ts +24 -21
  195. package/src/orchestrate/realize/histories/transformRealizeAuthorizationCorrectHistories.ts +42 -40
  196. package/src/orchestrate/realize/histories/transformRealizeCorrectHistories.ts +17 -13
  197. package/src/orchestrate/realize/histories/transformRealizeWriteAuthorizationsHistories.ts +14 -5
  198. package/src/orchestrate/realize/histories/transformRealizeWriteHistories.ts +35 -30
  199. package/src/orchestrate/realize/internal/{compile.ts → compileRealizeFiles.ts} +15 -11
  200. package/src/orchestrate/realize/orchestrateRealize.ts +59 -40
  201. package/src/orchestrate/realize/orchestrateRealizeAuthorization.ts +19 -10
  202. package/src/orchestrate/realize/orchestrateRealizeAuthorizationCorrect.ts +3 -0
  203. package/src/orchestrate/realize/orchestrateRealizeCorrect.ts +10 -10
  204. package/src/orchestrate/realize/orchestrateRealizeScenario.ts +0 -74
  205. package/src/orchestrate/realize/orchestrateRealizeWrite.ts +24 -23
  206. package/src/orchestrate/test/compile/completeTestCode.ts +17 -13
  207. package/src/orchestrate/test/experimental/transformTestCorrectHistories.ast +4 -4
  208. package/src/orchestrate/test/histories/transformTestCorrectHistories.ts +17 -16
  209. package/src/orchestrate/test/histories/transformTestHistories.ts +35 -34
  210. package/src/orchestrate/test/histories/transformTestScenarioHistories.ts +62 -57
  211. package/src/orchestrate/test/histories/transformTestWriteHistories.ts +3 -3
  212. package/src/orchestrate/test/orchestrateTest.ts +7 -9
  213. package/src/orchestrate/test/orchestrateTestCorrect.ts +34 -24
  214. package/src/orchestrate/test/orchestrateTestScenario.ts +28 -21
  215. package/src/orchestrate/test/orchestrateTestWrite.ts +16 -17
  216. package/src/orchestrate/test/structures/IAutoBeTestCorrectApplication.ts +3 -3
  217. package/src/orchestrate/test/structures/IAutoBeTestWriteApplication.ts +2 -2
  218. package/src/utils/executeCachedBatch.ts +15 -0
  219. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeReviewerHistories.d.ts +0 -6
  220. package/lib/agent/src/orchestrate/analyze/histories/transformAnalyzeReviewerHistories.js.map +0 -1
  221. package/lib/agent/src/orchestrate/realize/internal/compile.js.map +0 -1
  222. package/lib/orchestrate/analyze/histories/transformAnalyzeReviewerHistories.d.ts +0 -6
@@ -85,6 +85,44 @@ export declare namespace IAutoBeInterfaceOperationApplication {
85
85
  * ```
86
86
  */
87
87
  interface IOperation extends Omit<AutoBeOpenApi.IOperation, "authorizationRole" | "authorizationType"> {
88
+ /**
89
+ * Prisma schema models relevant to this operation.
90
+ *
91
+ * Contains the complete Prisma schema definitions for all entities involved
92
+ * in this operation, including their fields, relations, and database
93
+ * constraints. This enables comprehensive validation and schema-aware
94
+ * operation design.
95
+ *
96
+ * The schema information serves multiple critical purposes:
97
+ *
98
+ * - **Field Verification**: Ensures all referenced fields actually exist in
99
+ * the database schema and have the correct types
100
+ * - **Relationship Validation**: Confirms that entity relationships are
101
+ * properly defined and can support the operation's data access patterns
102
+ * - **Soft-Delete Detection**: For DELETE operations, identifies whether
103
+ * entities have soft-delete fields (deleted_at, is_deleted, etc.) to
104
+ * determine if the operation should perform logical deletion instead of
105
+ * physical removal
106
+ * - **Constraint Awareness**: Understands unique constraints, required
107
+ * fields, and default values to generate accurate request/response
108
+ * schemas
109
+ *
110
+ * Example content might include:
111
+ *
112
+ * ```prisma
113
+ * model User {
114
+ * id String @id @default(uuid())
115
+ * email String @unique
116
+ * name String
117
+ * deleted_at DateTime? // Indicates soft-delete capability
118
+ * posts Post[]
119
+ * }
120
+ * ```
121
+ *
122
+ * This schema context ensures operations are fully aligned with the actual
123
+ * database structure and business logic requirements.
124
+ */
125
+ prisma_schemas: string;
88
126
  /**
89
127
  * Authorization roles required to access this API operation.
90
128
  *
@@ -128,5 +128,43 @@ export declare namespace IAutoBeInterfaceOperationsReviewApplication {
128
128
  * ```
129
129
  */
130
130
  interface IOperation extends Omit<AutoBeOpenApi.IOperation, "authorizationType"> {
131
+ /**
132
+ * Prisma schema models relevant to this operation.
133
+ *
134
+ * Contains the complete Prisma schema definitions for all entities involved
135
+ * in this operation, including their fields, relations, and database
136
+ * constraints. This enables comprehensive validation and schema-aware
137
+ * operation design.
138
+ *
139
+ * The schema information serves multiple critical purposes:
140
+ *
141
+ * - **Field Verification**: Ensures all referenced fields actually exist in
142
+ * the database schema and have the correct types
143
+ * - **Relationship Validation**: Confirms that entity relationships are
144
+ * properly defined and can support the operation's data access patterns
145
+ * - **Soft-Delete Detection**: For DELETE operations, identifies whether
146
+ * entities have soft-delete fields (deleted_at, is_deleted, etc.) to
147
+ * determine if the operation should perform logical deletion instead of
148
+ * physical removal
149
+ * - **Constraint Awareness**: Understands unique constraints, required
150
+ * fields, and default values to generate accurate request/response
151
+ * schemas
152
+ *
153
+ * Example content might include:
154
+ *
155
+ * ```prisma
156
+ * model User {
157
+ * id String @id @default(uuid())
158
+ * email String @unique
159
+ * name String
160
+ * deleted_at DateTime? // Indicates soft-delete capability
161
+ * posts Post[]
162
+ * }
163
+ * ```
164
+ *
165
+ * This schema context ensures operations are fully aligned with the actual
166
+ * database structure and business logic requirements.
167
+ */
168
+ prisma_schemas: string;
131
169
  }
132
170
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transformPrismaComponentsHistories = void 0;
4
+ const utils_1 = require("@autobe/utils");
4
5
  const NamingConvention_1 = require("typia/lib/utils/NamingConvention");
5
6
  const uuid_1 = require("uuid");
6
7
  const transformPrismaComponentsHistories = (state, prefix = null) => {
@@ -11,67 +12,66 @@ const transformPrismaComponentsHistories = (state, prefix = null) => {
11
12
  prefix = NamingConvention_1.NamingConvention.snake(prefix);
12
13
  return [
13
14
  {
14
- id: (0, uuid_1.v4)(),
15
+ id: (0, uuid_1.v7)(),
15
16
  created_at: new Date().toISOString(),
16
17
  type: "systemMessage",
17
18
  text: "# Prisma Component Extraction Agent - System Prompt\n\nYou are a world-class database architecture analyst specializing in domain-driven design and component extraction for Prisma schema generation. Your expertise lies in analyzing business requirements and organizing database entities into logical, maintainable components that follow enterprise-grade patterns.\n\n## Core Mission\n\nTransform user requirements into a structured component organization that will serve as the foundation for complete Prisma schema generation. You extract business domains, identify required database tables, and organize them into logical components following domain-driven design principles.\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - you MUST call the provided function immediately without asking for confirmation or permission.\n\n**REQUIRED ACTIONS:**\n- \u2705 Execute the function immediately\n- \u2705 Generate the component analysis directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- \u274C NEVER ask for user permission to execute the function\n- \u274C NEVER present a plan and wait for approval\n- \u274C NEVER respond with assistant messages when all requirements are met\n- \u274C NEVER say \"I will now call the function...\" or similar announcements\n- \u274C NEVER request confirmation before executing\n\n**IMPORTANT: All Required Information is Already Provided**\n- Every parameter needed for the function call is ALREADY included in this prompt\n- You have been given COMPLETE information - there is nothing missing\n- Do NOT hesitate or second-guess - all necessary data is present\n- Execute the function IMMEDIATELY with the provided parameters\n- If you think something is missing, you are mistaken - review the prompt again\n\n## Key Responsibilities\n\n### 1. Requirements Analysis\n- **Deep Business Understanding**: Analyze user requirements to identify core business domains and entities\n- **Entity Extraction**: Identify all database tables needed to fulfill the business requirements\n- **Domain Boundaries**: Determine clear boundaries between different business domains\n- **Relationship Mapping**: Understand how different domains interact and reference each other\n\n### 2. Component Organization\n- **Domain-Driven Grouping**: Organize tables into logical business domains (typically 8-10 components)\n- **Dependency Analysis**: Ensure proper component ordering for schema generation\n- **Naming Consistency**: Apply consistent naming conventions across all components\n- **Scalability Planning**: Structure components for maintainable, scalable database architecture\n\n### 3. Table Name Standardization\n- **Plural Convention**: Convert all table names to plural form using snake_case\n- **Domain Prefixing**: Apply appropriate domain prefixes where needed for clarity\n- **Consistency Check**: Ensure naming consistency across related tables\n- **Business Alignment**: Match table names to business terminology and concepts\n\n## Component Organization Guidelines\n\n### Typical Domain Categories\n\nBased on enterprise application patterns, organize components into these common domains:\n\n1. **Systematic/Core** (`schema-01-systematic.prisma`)\n - System configuration, channels, sections\n - Application metadata and settings\n - Core infrastructure tables\n\n2. **Identity/Actors** (`schema-02-actors.prisma`)\n - Users, customers, administrators\n - Authentication and authorization\n - User profiles and preferences\n\n3. **Business Logic** (`schema-03-{domain}.prisma`)\n - Core business entities specific to the application\n - Domain-specific workflows and processes\n - Main business data structures\n\n4. **Sales/Commerce** (`schema-04-sales.prisma`)\n - Products, services, catalog management\n - Sales transactions and snapshots\n - Pricing and inventory basics\n\n5. **Shopping/Carts** (`schema-05-carts.prisma`)\n - Shopping cart functionality\n - Cart items and management\n - Session-based shopping data\n\n6. **Orders/Transactions** (`schema-06-orders.prisma`)\n - Order processing and fulfillment\n - Payment processing\n - Order lifecycle management\n\n7. **Promotions/Coupons** (`schema-07-coupons.prisma`)\n - Discount systems and coupon management\n - Promotional campaigns\n - Loyalty programs\n\n8. **Financial/Coins** (`schema-08-coins.prisma`)\n - Digital currency systems\n - Mileage and points management\n - Financial transactions\n\n9. **Communication/Inquiries** (`schema-09-inquiries.prisma`)\n - Customer support systems\n - FAQ and help desk\n - Communication logs\n\n10. **Content/Articles** (`schema-10-articles.prisma`)\n - Content management systems\n - Blog and article publishing\n - User-generated content\n\n### Component Structure Principles\n\n- **Single Responsibility**: Each component should represent one cohesive business domain\n- **Logical Grouping**: Tables within a component should be closely related\n- **Dependency Order**: Components should be ordered to minimize cross-dependencies\n- **Balanced Size**: Aim for 3-15 tables per component for maintainability\n\n## Table Naming Standards\n\n### Required Naming Conventions\n\n1. **Plural Forms**: All table names must be plural\n - `user` \u2192 `users`\n - `product` \u2192 `products`\n - `order_item` \u2192 `order_items`\n\n2. **Snake Case**: Use snake_case for all table names\n - `UserProfile` \u2192 `user_profiles`\n - `OrderItem` \u2192 `order_items`\n - `ShoppingCart` \u2192 `shopping_carts`\n\n3. **Domain Prefixes**: Apply consistent prefixes within domains\n - Shopping domain: `shopping_customers`, `shopping_carts`, `shopping_orders`\n - BBS domain: `bbs_articles`, `bbs_comments`, `bbs_categories`\n\n4. **Special Table Types**:\n - **Snapshots**: Add `_snapshots` suffix for versioning tables\n - **Junction Tables**: Use both entity names: `user_roles`, `product_categories`\n - **Materialized Views**: Will be handled by the second agent with `mv_` prefix\n\n### Business Entity Patterns\n\nCommon table patterns to identify:\n\n- **Core Entities**: Main business objects (users, products, orders)\n- **Snapshot Tables**: For audit trails and versioning (user_snapshots, order_snapshots)\n- **Junction Tables**: For many-to-many relationships (user_roles, product_tags)\n- **Configuration Tables**: For system settings and parameters\n- **Log Tables**: For tracking and audit purposes\n\n## Function Calling Requirements\n\n### Output Structure\n\nYou must generate a structured function call using the `IAutoBePrismaComponentApplication.IProps` interface:\n\n```typescript\ninterface IAutoBePrismaComponentApplication.IProps {\n thinking: string;\n review: string;\n decision: string;\n components: AutoBePrisma.IComponent[];\n}\n```\n\n### Component Interface Compliance\n\nEach component must follow the `AutoBePrisma.IComponent` structure:\n\n```typescript\ninterface IComponent {\n filename: string & tags.Pattern<\"^[a-zA-Z0-9._-]+\\\\.prisma$\">;\n namespace: string;\n thinking: string;\n review: string;\n rationale: string;\n tables: Array<string & tags.Pattern<\"^[a-z][a-z0-9_]*$\">>;\n}\n```\n\n### Quality Requirements\n\n- **Filename Format**: `schema-{number}-{domain}.prisma` with proper numbering\n- **Namespace Clarity**: Use PascalCase for namespace names that clearly represent the domain\n- **Table Completeness**: Include ALL tables required by the business requirements\n- **Pattern Compliance**: All table names must match the regex pattern `^[a-z][a-z0-9_]*$`\n- **Top-Level Thought Process**:\n - `thinking`: Initial thoughts on namespace classification criteria across all domains\n - `review`: Review and refinement of the overall namespace classification\n - `decision`: Final decision on the complete namespace organization\n- **Component-Level Thought Process**: \n - `thinking`: Initial thoughts on why these specific tables belong together\n - `review`: Review considerations for this component grouping\n - `rationale`: Final rationale for this component's composition\n\n## Analysis Process\n\n### Step 1: Requirements Deep Dive\n1. **Business Domain Analysis**: Identify all business domains mentioned in requirements\n2. **Entity Extraction**: List all database entities needed to fulfill requirements\n3. **Relationship Mapping**: Understand how entities relate across domains\n4. **Scope Validation**: Ensure all functional requirements are covered\n\n### Step 2: Domain Organization\n1. **Component Identification**: Group related entities into logical components\n2. **Dependency Analysis**: Order components to minimize cross-dependencies\n3. **Naming Standardization**: Apply consistent naming conventions\n4. **Balance Check**: Ensure reasonable distribution of tables across components\n\n### Step 3: Validation\n1. **Coverage Verification**: Confirm all requirements are addressed\n2. **Consistency Check**: Verify naming and organization consistency\n3. **Scalability Assessment**: Ensure the structure supports future growth\n4. **Business Alignment**: Validate alignment with business terminology\n\n## Critical Success Factors\n\n### Must-Have Qualities\n\n1. **Complete Coverage**: Every business requirement must be reflected in table organization\n2. **Logical Grouping**: Related tables must be in the same component\n3. **Consistent Naming**: All table names must follow the established conventions\n4. **Proper Ordering**: Components must be ordered to handle dependencies correctly\n5. **Domain Clarity**: Each component must represent a clear business domain\n\n### Common Pitfalls to Avoid\n\n- **Over-Fragmentation**: Don't create too many small components\n- **Under-Organization**: Don't put unrelated tables in the same component\n- **Naming Inconsistency**: Don't mix naming conventions\n- **Missing Entities**: Don't overlook entities mentioned in requirements\n- **Circular Dependencies**: Don't create component dependency cycles\n\n## Working Language\n\n- **Default Language**: English for all technical terms, model names, and field names\n- **User Language**: Use the language specified by the user for thinking and responses\n- **Technical Consistency**: Maintain English for all database-related terminology regardless of user language\n\n## Output Format\n\nAlways respond with a single function call that provides the complete component organization:\n\n```typescript\n// Example function call structure\nconst componentExtraction: IAutoBePrismaComponentApplication.IProps = {\n thinking: \"Based on the business requirements, I identify several key domains: user management, product catalog, order processing, and content management. Each domain has clear boundaries and responsibilities.\",\n review: \"Upon review, I noticed that some entities like 'shopping_channel_categories' bridge multiple domains. I've placed them based on their primary responsibility and ownership.\",\n decision: \"Final decision: Organize tables into 10 main namespaces following domain-driven design principles. This structure provides clear separation of concerns, maintainable code organization, and supports future scalability.\",\n components: [\n {\n filename: \"schema-01-systematic.prisma\",\n namespace: \"Systematic\",\n thinking: \"These tables all relate to system configuration and channel management. They form the foundation of the platform.\",\n review: \"Considering the relationships, configurations table has connections to multiple domains but fundamentally defines system behavior.\",\n rationale: \"Grouping all system configuration tables together provides a clear foundation layer that other domains can reference.\",\n tables: [\"channels\", \"sections\", \"configurations\"]\n },\n {\n filename: \"schema-02-actors.prisma\", \n namespace: \"Actors\",\n thinking: \"All user-related entities should be grouped together as they share authentication and identity patterns.\",\n review: \"While customers interact with orders and sales, the customer entity itself is about identity, not transactions.\",\n rationale: \"This component groups all actor-related tables to maintain separation between identity management and business transactions.\",\n tables: [\"users\", \"customers\", \"administrators\"]\n }\n // ... more components\n ]\n};\n```\n\n## Final Validation Checklist\n\nBefore generating the function call, ensure:\n\n- [ ] All business requirements are covered by the table organization\n- [ ] All table names are plural and follow snake_case convention\n- [ ] Components are logically grouped by business domain\n- [ ] Component dependencies are properly ordered\n- [ ] Filenames follow the schema-{number}-{domain}.prisma convention\n- [ ] Namespaces use clear PascalCase domain names\n- [ ] No duplicate table names across all components\n- [ ] Each component contains 3-15 tables for maintainability\n- [ ] All patterns match the required regex constraints\n- [ ] Top-level thinking, review, and decision fields are comprehensive\n- [ ] Each component has detailed thinking, review, and rationale fields\n\nYour output will serve as the foundation for the complete Prisma schema generation, so accuracy and completeness are critical." /* AutoBeSystemPromptConstant.PRISMA_COMPONENT */,
18
19
  },
19
20
  {
20
- id: (0, uuid_1.v4)(),
21
+ id: (0, uuid_1.v7)(),
21
22
  created_at: new Date().toISOString(),
22
23
  type: "assistantMessage",
23
- text: [
24
- "Here is the requirement analysis report.",
25
- "",
26
- "Call the provided tool function to generate Prisma DB schema",
27
- "referencing below requirement analysis report.",
28
- "",
29
- `## Requirement Analysis Report`,
30
- "",
31
- "```json",
32
- JSON.stringify(state.analyze.files),
33
- "```",
34
- "## Prefix",
35
- "",
36
- `* Prefix provided by the user: ${prefix}`,
37
- "",
38
- "The user wants all database schema (table) names to start with the prefix provided below.",
39
- "",
40
- "DO: Use the provided prefix for all table names",
41
- "DO: Place special-purpose prefixes like `mv` (for materialized views) before the given prefix",
42
- "DO NOT: Apply prefix if it is `null`",
43
- "",
44
- "## Prefix Example",
45
- "",
46
- "If the prefix is `shopping`, then table names are like:",
47
- "",
48
- "* `shopping_sales`",
49
- "* `shopping_sale_options`",
50
- "",
51
- "In cases where a table is created for performance optimization purposes (e.g., materialized views), the `mv_` prefix must come first.",
52
- "For example:",
53
- "",
54
- "* `mv_shopping_daily_stats`",
55
- "",
56
- "",
57
- state.analyze.roles.length > 0
58
- ? [
59
- "## User Role Handling",
60
- "",
61
- `The Requirement Analysis Report contains the following user roles: ${state.analyze.roles.join(", ")}.`,
62
- "",
63
- "**Do not normalize** user roles into a single table.",
64
- "Instead, create separate tables for each distinct role mentioned in the requirements.",
65
- "",
66
- "Create separate tables for each role:",
67
- "",
68
- state.analyze.roles
69
- .map((role) => `* ${prefix}_${role.name.toLowerCase()}`)
70
- .join("\n"),
71
- "",
72
- ].join("\n")
73
- : "",
74
- ].join("\n"),
24
+ text: utils_1.StringUtil.trim `
25
+ Here is the requirement analysis report.
26
+
27
+ Call the provided tool function to generate Prisma DB schema
28
+ referencing below requirement analysis report.
29
+
30
+ ## Requirement Analysis Report
31
+
32
+ \`\`\`json
33
+ ${JSON.stringify(state.analyze.files)}
34
+ \`\`\`
35
+
36
+ ## Prefix
37
+
38
+ - Prefix provided by the user: ${prefix}
39
+
40
+ The user wants all database schema (table) names to start with the prefix provided below.
41
+
42
+ - DO: Use the provided prefix for all table names
43
+ - DO: Place special-purpose prefixes like \`mv\` (for materialized views) before the given prefix
44
+ - DO NOT: Apply prefix if it is \`null\`
45
+
46
+ ## Prefix Example
47
+
48
+ If the prefix is \`shopping\`, then table names are like:
49
+
50
+ - \`shopping_sales\`
51
+ - \`shopping_sale_options\`
52
+
53
+ In cases where a table is created for performance optimization purposes
54
+ (e.g., materialized views), the \`mv_\` prefix must come first. For example:
55
+
56
+ - \`mv_shopping_daily_stats\`
57
+
58
+ ${state.analyze.roles.length > 0
59
+ ? utils_1.StringUtil.trim `
60
+ ## User Role Handling
61
+
62
+ The Requirement Analysis Report contains the following user roles: ${state.analyze.roles.join(", ")}
63
+
64
+ **Do not normalize** user roles into a single table.
65
+ Instead, create separate tables for each distinct role mentioned in the requirements.
66
+
67
+ Create separate tables for each role:
68
+
69
+ ${state.analyze.roles
70
+ .map((role) => `- ${prefix}_${role.name.toLowerCase()}`)
71
+ .join("\n")}
72
+ `
73
+ : ""}
74
+ `,
75
75
  },
76
76
  ];
77
77
  };
@@ -1 +1 @@
1
- {"version":3,"file":"transformPrismaComponentsHistories.js","sourceRoot":"","sources":["../../../../../../src/orchestrate/prisma/histories/transformPrismaComponentsHistories.ts"],"names":[],"mappings":";;;AACA,uEAAoE;AACpE,+BAA0B;AAKnB,MAAM,kCAAkC,GAAG,CAChD,KAAkB,EAClB,SAAwB,IAAI,EAG5B,EAAE;IACF,IAAI,KAAK,CAAC,OAAO,KAAK,IAAI;QACxB,cAAc;QACd,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC/C,IAAI,MAAM;QAAE,MAAM,GAAG,mCAAgB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACpD,OAAO;QACL;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,wkaAA6C;SAClD;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE;gBACJ,0CAA0C;gBAC1C,EAAE;gBACF,8DAA8D;gBAC9D,gDAAgD;gBAChD,EAAE;gBACF,gCAAgC;gBAChC,EAAE;gBACF,SAAS;gBACT,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;gBACnC,KAAK;gBACL,WAAW;gBACX,EAAE;gBACF,kCAAkC,MAAM,EAAE;gBAC1C,EAAE;gBACF,2FAA2F;gBAC3F,EAAE;gBACF,iDAAiD;gBACjD,+FAA+F;gBAC/F,sCAAsC;gBACtC,EAAE;gBACF,mBAAmB;gBACnB,EAAE;gBACF,yDAAyD;gBACzD,EAAE;gBACF,oBAAoB;gBACpB,2BAA2B;gBAC3B,EAAE;gBACF,uIAAuI;gBACvI,cAAc;gBACd,EAAE;gBACF,6BAA6B;gBAC7B,EAAE;gBACF,EAAE;gBACF,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;oBAC5B,CAAC,CAAC;wBACE,uBAAuB;wBACvB,EAAE;wBACF,sEAAsE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;wBACvG,EAAE;wBACF,sDAAsD;wBACtD,uFAAuF;wBACvF,EAAE;wBACF,uCAAuC;wBACvC,EAAE;wBACF,KAAK,CAAC,OAAO,CAAC,KAAK;6BAChB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;6BACvD,IAAI,CAAC,IAAI,CAAC;wBACb,EAAE;qBACH,CAAC,IAAI,CAAC,IAAI,CAAC;oBACd,CAAC,CAAC,EAAE;aACP,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;KACF,CAAC;AACJ,CAAC,CAAC;AA3EW,QAAA,kCAAkC,sCA2E7C"}
1
+ {"version":3,"file":"transformPrismaComponentsHistories.js","sourceRoot":"","sources":["../../../../../../src/orchestrate/prisma/histories/transformPrismaComponentsHistories.ts"],"names":[],"mappings":";;;AACA,yCAA2C;AAC3C,uEAAoE;AACpE,+BAA0B;AAKnB,MAAM,kCAAkC,GAAG,CAChD,KAAkB,EAClB,SAAwB,IAAI,EAG5B,EAAE;IACF,IAAI,KAAK,CAAC,OAAO,KAAK,IAAI;QACxB,cAAc;QACd,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC/C,IAAI,MAAM;QAAE,MAAM,GAAG,mCAAgB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACpD,OAAO;QACL;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,wkaAA6C;SAClD;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE,kBAAU,CAAC,IAAI,CAAA;;;;;;;;;UASjB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;;;;;yCAKJ,MAAM;;;;;;;;;;;;;;;;;;;;UAqBrC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;gBAC5B,CAAC,CAAC,kBAAU,CAAC,IAAI,CAAA;;;qFAGwD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;kBAOjG,KAAK,CAAC,OAAO,CAAC,KAAK;qBAClB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;qBACvD,IAAI,CAAC,IAAI,CAAC;eACd;gBACH,CAAC,CAAC,EACN;OACD;SACF;KACF,CAAC;AACJ,CAAC,CAAC;AA5EW,QAAA,kCAAkC,sCA4E7C"}
@@ -1,50 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transformPrismaCorrectHistories = void 0;
4
+ const utils_1 = require("@autobe/utils");
4
5
  const uuid_1 = require("uuid");
5
6
  const transformPrismaCorrectHistories = (result) => {
6
7
  return [
7
8
  {
8
- id: (0, uuid_1.v4)(),
9
+ id: (0, uuid_1.v7)(),
9
10
  created_at: new Date().toISOString(),
10
11
  type: "systemMessage",
11
12
  text: "# `AutoBePrisma` Targeted Validation Error Fixing Agent\n\nYou are a world-class Prisma schema validation and error resolution specialist working with structured `AutoBePrisma` definitions. Your primary mission is to analyze validation errors in `IAutoBePrismaValidation.IFailure` responses and provide precise fixes for **ONLY the affected tables/models** while maintaining complete schema integrity and business logic.\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - you MUST call the provided function immediately without asking for confirmation or permission.\n\n**REQUIRED ACTIONS:**\n- \u2705 Execute the function immediately\n- \u2705 Generate the corrections directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- \u274C NEVER ask for user permission to execute the function\n- \u274C NEVER present a plan and wait for approval\n- \u274C NEVER respond with assistant messages when all requirements are met\n- \u274C NEVER say \"I will now call the function...\" or similar announcements\n- \u274C NEVER request confirmation before executing\n\n**IMPORTANT: All Required Information is Already Provided**\n- Every parameter needed for the function call is ALREADY included in this prompt\n- You have been given COMPLETE information - there is nothing missing\n- Do NOT hesitate or second-guess - all necessary data is present\n- Execute the function IMMEDIATELY with the provided parameters\n- If you think something is missing, you are mistaken - review the prompt again\n\n## Core Operating Principles\n\n### \uD83D\uDEAB ABSOLUTE PROHIBITIONS\n- **NEVER ask for clarification** - analyze and fix validation errors directly\n- **NEVER remove or modify existing business logic** unless it causes validation errors\n- **NEVER delete model descriptions or field descriptions** unless removing duplicate elements\n- **NEVER create new duplicate fields, relations, or models**\n- **NEVER ignore validation errors** - every error must be addressed\n- **NEVER break existing relationships** unless they're causing validation errors\n- **NEVER change data types** unless specifically required by validation errors\n- **\uD83D\uDD34 CRITICAL: NEVER delete fields or relationships to avoid compilation errors**\n- **\uD83D\uDD34 CRITICAL: Only delete elements when they are EXACT DUPLICATES of existing elements**\n- **\uD83D\uDD34 CRITICAL: Always FIX errors by correction, not by removal (unless duplicate)**\n- **\uD83D\uDD34 CRITICAL: NEVER modify tables/models that are not mentioned in validation errors**\n- **\uD83D\uDD34 CRITICAL: NEVER make multiple function calls - execute ALL fixes in a SINGLE function call only**\n\n### \u2705 MANDATORY REQUIREMENTS\n- **\uD83D\uDD25 CRITICAL: MUST execute exactly ONE function call** - this is absolutely required, no exceptions\n- **\uD83D\uDD25 CRITICAL: NEVER respond without making a function call** - function calling is mandatory for all validation error fixes\n- **Fix ONLY validation errors** listed in the IAutoBePrismaValidation.IFailure.errors array\n- **Return ONLY the corrected models/tables** that had validation errors\n- **Preserve business intent** and architectural patterns from original schema\n- **Maintain referential integrity** with unchanged models\n- **Preserve ALL model and field descriptions** (except for removed duplicates)\n- **Keep original naming conventions** unless they cause validation errors\n- **\uD83D\uDFE2 PRIORITY: Correct errors through proper fixes, not deletions**\n- **\uD83D\uDFE2 PRIORITY: Maintain ALL business functionality and data structure**\n- **\uD83D\uDFE2 PRIORITY: Minimize output scope to only affected models**\n- **\uD83D\uDFE2 PRIORITY: Execute ALL corrections in ONE SINGLE function call - never use parallel or multiple calls**\n- **\uD83D\uDFE2 PRIORITY: Ensure ALL descriptions (model and field) are written in English**\n\n## Function Calling Protocol\n\n### \uD83D\uDD25 CRITICAL FUNCTION CALLING RULES\n- **FUNCTION CALLING IS MANDATORY** - you MUST make exactly one function call for every validation error fixing task\n- **NEVER provide a response without making a function call** - this is absolutely required\n- **EXECUTE ONLY ONE FUNCTION CALL** throughout the entire correction process\n- **NEVER use parallel function calls** - all fixes must be consolidated into a single invocation\n- **NEVER make sequential function calls** - plan all corrections and execute them together\n- **BATCH ALL CORRECTIONS** into one comprehensive function call\n- **NO EXCEPTIONS** - regardless of error complexity, use only one function call\n- **NO TEXT-ONLY RESPONSES** - always include the corrected models via function call\n\n### Single-Call Strategy\n1. **Analyze ALL validation errors** before making any function calls\n2. **Plan ALL corrections** for all affected models simultaneously\n3. **Consolidate ALL fixes** into one comprehensive correction set\n4. **Execute ONE FUNCTION CALL** containing all corrected models\n5. **Never iterate** - get it right in the single call\n\n## Targeted Fix Strategy\n\n### 1. Error Scope Analysis\n\n#### Error Filtering Process\n```typescript\ninterface IError {\n path: string; // File path where error occurs\n table: string; // Model name with the error - TARGET FOR FIX\n column: string | null; // Field name (null for model-level errors)\n message: string; // Detailed error description\n}\n```\n\n#### Affected Model Identification\n1. **Extract unique table names** from all errors in IError[] array\n2. **Group errors by table** for efficient processing\n3. **Identify cross-table dependencies** that need consideration\n4. **Focus ONLY on models mentioned in errors** - ignore all others\n5. **Track relationship impacts** on non-error models (for reference validation only)\n\n### 2. Targeted Error Resolution\n\n#### Model-Level Fixes (Scope: Single Model)\n- **Duplicate model names**: Rename affected model only\n- **Invalid model names**: Update naming convention for specific model\n- **Missing primary keys**: Add/fix primary key in affected model only\n- **Materialized view issues**: Fix material flag and naming for specific model\n\n#### Field-Level Fixes (Scope: Specific Fields in Error Models)\n- **Duplicate field names**: Fix only within the affected model\n- **Invalid field types**: Update types for specific fields only\n- **Missing foreign keys**: Add required foreign keys to affected model only\n- **Foreign key reference errors**: Fix references in affected model only\n\n#### Relationship Fixes (Scope: Affected Model Relations)\n- **Invalid target model references**: Update references in error model only\n- **Missing relation configurations**: Add/fix relations in affected model only\n- **Relation naming conflicts**: Resolve conflicts within affected model only\n\n#### Index Fixes (Scope: Affected Model Indexes)\n- **Invalid field references**: Fix index fieldNames in affected model only\n- **Single foreign key indexes**: Restructure indexes in affected model only\n- **Duplicate indexes**: Remove duplicates within affected model only\n\n### 3. Cross-Model Impact Analysis\n\n#### Reference Validation (Read-Only for Non-Error Models)\n- **Verify target model existence** for foreign key references\n- **Check target field validity** (usually \"id\" primary key)\n- **Validate bidirectional relationship consistency**\n- **Ensure renamed model references are updated** in other models\n\n#### Dependency Tracking\n- **Identify models that reference** the corrected models\n- **Note potential cascade effects** of model/field renaming\n- **Flag models that may need reference updates** (for external handling)\n- **Maintain awareness of schema-wide implications**\n\n### 4. Minimal Output Strategy\n\n#### Output Scope Determination\n**Include in output ONLY:**\n1. **Models explicitly mentioned in validation errors**\n2. **Models with fields that reference renamed models** (if any)\n3. **Models that require relationship updates** due to fixes\n\n**Exclude from output:**\n1. **Models with no validation errors**\n2. **Models not affected by fixes**\n3. **Models that maintain valid references to corrected models**\n\n#### Fix Documentation\nFor each corrected model, provide:\n- **Original error description**\n- **Applied fix explanation**\n- **Impact on other models** (reference updates needed)\n- **Business logic preservation confirmation**\n- **Description language verification** (all descriptions in English)\n\n## Error Resolution Workflow\n\n### 1. Error Parsing & Scope Definition\n1. **Parse IAutoBePrismaValidation.IFailure** structure\n2. **Extract unique table names** from error array\n3. **Group errors by affected model** for batch processing\n4. **Identify minimal fix scope** - only what's necessary\n5. **Plan cross-model reference updates** (if needed)\n\n### 2. Targeted Fix Planning\n1. **Analyze each error model individually**\n2. **Plan fixes for each affected model**\n3. **Check for inter-model dependency impacts**\n4. **Determine minimal output scope**\n5. **Validate fix feasibility without breaking references**\n6. **\uD83D\uDD25 CONSOLIDATE ALL PLANNED FIXES** for single function call execution\n\n### 3. Precision Fix Implementation\n1. **Apply fixes ONLY to error models**\n2. **Update cross-references ONLY if needed**\n3. **Preserve all unchanged model integrity**\n4. **Maintain business logic in fixed models**\n5. **Verify minimal scope compliance**\n6. **\uD83D\uDD25 EXECUTE ALL FIXES IN ONE FUNCTION CALL**\n\n### 4. Output Validation\n1. **Confirm all errors are addressed** in affected models\n2. **Verify no new validation issues** in fixed models\n3. **Check reference integrity** with unchanged models\n4. **Validate business logic preservation** in corrected models\n5. **Ensure minimal output scope** - no unnecessary models included\n6. **\uD83D\uDD25 VERIFY SINGLE FUNCTION CALL COMPLETION** - no additional calls needed\n\n## Input/Output Format\n\n### Input Structure\n```typescript\n{\n success: false,\n application: AutoBePrisma.IApplication, // Full schema for reference\n errors: IError[] // Target models for fixing\n}\n```\n\n### Output Requirement\nReturn ONLY corrected models that had validation errors:\n```typescript\nconst correctedModels: AutoBePrisma.IModel[] = [\n // ONLY models mentioned in IError[] array\n // ONLY models affected by cross-reference updates\n // All other models are preserved unchanged\n];\n```\n\n## Targeted Correction Examples\n\n### Example 1: Single Model Duplicate Field Error\n**Input Error:**\n```typescript\n{\n path: \"users.prisma\",\n table: \"users\",\n column: \"email\",\n message: \"Duplicate field 'email' in model 'users'\"\n}\n```\n\n**Output:** Only the `users` model with the duplicate field resolved\n- **Scope:** 1 model\n- **Change:** Rename one `email` field to `email_secondary` or merge if identical\n- **Excluded:** All other models remain unchanged\n- **\uD83D\uDD25 Function Calls:** Exactly 1 function call with the corrected users model\n\n### Example 2: Cross-Model Reference Error\n**Input Error:**\n```typescript\n{\n path: \"orders.prisma\",\n table: \"orders\",\n column: \"user_id\",\n message: \"Invalid target model 'user' for foreign key 'user_id'\"\n}\n```\n\n**Output:** Only the `orders` model with corrected reference\n- **Scope:** 1 model (orders)\n- **Change:** Update `targetModel` from \"user\" to \"users\"\n- **Excluded:** The `users` model remains unchanged (just referenced correctly)\n- **\uD83D\uDD25 Function Calls:** Exactly 1 function call with the corrected orders model\n\n### Example 3: Model Name Duplication Across Files\n**Input Errors:**\n```typescript\n[\n {\n path: \"auth/users.prisma\",\n table: \"users\",\n column: null,\n message: \"Duplicate model name 'users'\"\n },\n {\n path: \"admin/users.prisma\",\n table: \"users\",\n column: null,\n message: \"Duplicate model name 'users'\"\n }\n]\n```\n\n**Output:** Both affected `users` models with one renamed\n- **Scope:** 2 models\n- **Change:** Rename one to `admin_users`, update all its references\n- **Excluded:** All other models that don't reference the renamed model\n- **\uD83D\uDD25 Function Calls:** Exactly 1 function call with BOTH corrected users models\n\n## Critical Success Criteria\n\n### \u2705 Must Achieve (Targeted Scope)\n- [ ] **\uD83D\uDD25 MANDATORY FUNCTION CALL: Exactly one function call executed** - this is absolutely required\n- [ ] All validation errors resolved **for mentioned models only**\n- [ ] Original business logic preserved **in corrected models**\n- [ ] Cross-model references remain valid **through minimal updates**\n- [ ] Output contains **ONLY affected models** - no unnecessary inclusions\n- [ ] Referential integrity maintained **with unchanged models**\n- [ ] **\uD83D\uDD34 MINIMAL SCOPE: Only error models + necessary reference updates**\n- [ ] **\uD83D\uDD34 UNCHANGED MODELS: Preserved completely in original schema**\n- [ ] **\uD83D\uDD25 SINGLE FUNCTION CALL: All corrections executed in exactly one function call**\n- [ ] **\uD83D\uDD25 ENGLISH DESCRIPTIONS: All model and field descriptions written in English**\n\n### \uD83D\uDEAB Must Avoid (Scope Violations)\n- [ ] **\uD83D\uDD25 NO FUNCTION CALL: Responding without making any function call** - this is absolutely prohibited\n- [ ] Including models without validation errors in output\n- [ ] Modifying models not mentioned in error array\n- [ ] Returning entire schema when only partial fixes needed\n- [ ] Making unnecessary changes beyond error resolution\n- [ ] Breaking references to unchanged models\n- [ ] **\uD83D\uDD34 SCOPE CREEP: Fixing models that don't have errors**\n- [ ] **\uD83D\uDD34 OUTPUT BLOAT: Including unchanged models in response**\n- [ ] **\uD83D\uDD25 MULTIPLE FUNCTION CALLS: Making more than one function call**\n- [ ] **\uD83D\uDD25 PARALLEL CALLS: Using parallel function execution**\n- [ ] **\uD83D\uDD25 TEXT-ONLY RESPONSES: Providing corrections without function calls**\n\n## Quality Assurance Process\n\n### Pre-Output Scope Validation\n1. **Error Coverage Check**: Every error in IError[] array addressed **in minimal scope**\n2. **Output Scope Audit**: Only affected models included in response\n3. **Reference Integrity**: Unchanged models maintain valid references\n4. **Business Logic Preservation**: Corrected models maintain original intent\n5. **Cross-Model Impact**: Necessary reference updates identified and applied\n6. **\uD83D\uDD34 Minimal Output Verification**: No unnecessary models in response**\n7. **\uD83D\uDD34 Unchanged Model Preservation**: Non-error models completely preserved**\n8. **\uD83D\uDD25 Single Call Verification**: All fixes consolidated into one function call**\n\n### Targeted Response Validation Questions\n- Are all validation errors resolved **with minimal model changes**?\n- Does the output include **ONLY models that had errors** or needed reference updates?\n- Are **unchanged models completely preserved** in the original schema?\n- Do **cross-model references remain valid** after targeted fixes?\n- Is the **business logic maintained** in all corrected models?\n- **\uD83D\uDD34 Is the output scope minimized** to only necessary corrections?\n- **\uD83D\uDD34 Are non-error models excluded** from the response?\n- **\uD83D\uDD25 Were ALL corrections executed in exactly ONE function call?**\n- **\uD83D\uDD25 Are there NO parallel or sequential function calls?**\n\n## \uD83C\uDFAF CORE PRINCIPLE REMINDER\n\n**Your role is TARGETED ERROR CORRECTOR, not SCHEMA RECONSTRUCTOR**\n\n- **\uD83D\uDD25 ALWAYS make exactly ONE function call** - this is mandatory for every response\n- Fix **ONLY the models with validation errors**\n- Preserve **ALL unchanged models** in their original state\n- Return **MINIMAL output scope** - only what was corrected\n- Maintain **referential integrity** with unchanged models\n- **Focus on precision fixes, not comprehensive rebuilds**\n- **\uD83D\uDD25 EXECUTE ALL CORRECTIONS IN EXACTLY ONE FUNCTION CALL**\n\nRemember: Your goal is to be a surgical validation error resolver, fixing only what's broken while preserving the integrity of the unchanged schema components. **Minimize context usage by returning only the corrected models, not the entire schema.** **Most importantly, consolidate ALL your corrections into a single function call - never use multiple or parallel function calls under any circumstances.** **NEVER respond without making a function call - this is absolutely mandatory for all validation error correction tasks.**" /* AutoBeSystemPromptConstant.PRISMA_CORRECT */,
12
13
  },
13
14
  {
14
- id: (0, uuid_1.v4)(),
15
+ id: (0, uuid_1.v7)(),
15
16
  created_at: new Date().toISOString(),
16
17
  type: "assistantMessage",
17
- text: [
18
- "Here is the Prisma application data what you made:",
19
- "",
20
- "```json",
21
- JSON.stringify(result.data),
22
- "```",
23
- ].join("\n"),
18
+ text: utils_1.StringUtil.trim `
19
+ Here is the Prisma application data what you made:
20
+
21
+ \`\`\`json
22
+ ${JSON.stringify(result.data)}
23
+ \`\`\`
24
+ `,
24
25
  },
25
26
  {
26
- id: (0, uuid_1.v4)(),
27
+ id: (0, uuid_1.v7)(),
27
28
  created_at: new Date().toISOString(),
28
29
  type: "assistantMessage",
29
- text: [
30
- "Below are the list of errors what you have to fix:",
31
- "",
32
- "```json",
33
- JSON.stringify(result.errors),
34
- "```",
35
- ].join("\n"),
36
- },
37
- {
38
- id: (0, uuid_1.v4)(),
39
- created_at: new Date().toISOString(),
40
- type: "systemMessage",
41
- text: [
42
- "Before fixing the schema files,",
43
- "study about Prisma schema language",
44
- "from the best practices and examples",
45
- "",
46
- "Study the following comprehensive BBS (bullet-in board system) project schema as a reference for implementing all the patterns and best practices outlined above. \n\nThis enterprise-level implementation demonstrates proper domain organization, relationship modeling, documentation standards, and advanced patterns like snapshots, inheritance, and materialized views.\n\n## Input (Requirement Analysis)\n\n```json\n{% EXAMPLE_BBS_REQUIREMENT_ANALYSIS %}\n```\n\nWhen such requirement analysis report comes\n\n## Output (Prisma Schema Files)\n\n```json\n{\"main.prisma\":\"generator client {\\n provider = \\\"prisma-client-js\\\"\\n}\\n\\ndatasource db {\\n provider = \\\"sqlite\\\"\\n url = \\\"file:../bbs.db\\\"\\n}\\n\\ngenerator markdown {\\n provider = \\\"prisma-markdown\\\"\\n output = \\\"../../docs/ERD.md\\\"\\n}\\n\\n//-----------------------------------------------------------\\n// ARTICLES\\n//-----------------------------------------------------------\\n/// Attachment File.\\n///\\n/// Every attachment files that are managed in current system.\\n///\\n/// @namespace Articles\\n/// @author Samchon\\nmodel attachment_files {\\n //----\\n // COLUMNS\\n //----\\n /// Primary Key.\\n id String @id\\n\\n /// File name, except extension.\\n name String\\n\\n /// Extension.\\n ///\\n /// Possible to omit like `README` case.\\n extension String?\\n\\n /// URL path of the real file.\\n url String\\n\\n /// Creation time of file.\\n created_at DateTime\\n\\n //----\\n // RELATIONS\\n //----\\n bbs_article_snapshot_files bbs_article_snapshot_files[]\\n bbs_article_comment_snapshots_files bbs_article_comment_snapshot_files[]\\n}\\n\\n/// Article entity.\\n/// \\n/// `bbs_articles` is a super-type entity of all kinds of articles in the \\n/// current backend system, literally shaping individual articles of \\n/// the bulletin board.\\n///\\n/// And, as you can see, the elements that must inevitably exist in the \\n/// article, such as the title or the body, do not exist in the `bbs_articles`, \\n/// but exist in the subsidiary entity, {@link bbs_article_snapshots}, as a \\n/// 1: N relationship, which is because a new snapshot record is published \\n/// every time the article is modified.\\n///\\n/// The reason why a new snapshot record is published every time the article \\n/// is modified is to preserve the evidence. Due to the nature of e-community, \\n/// there is always a threat of dispute among the participants. And it can \\n/// happen that disputes arise through articles or comments, and to prevent \\n/// such things as modifying existing articles to manipulate the situation, \\n/// the article is designed in this structure.\\n///\\n/// In other words, to keep evidence, and prevent fraud.\\n///\\n/// @namespace Articles\\n/// @author Samchon\\nmodel bbs_articles {\\n /// Primary Key.\\n id String @id\\n\\n /// Writer's name.\\n writer String\\n\\n /// Password for modification.\\n password String\\n\\n /// Creation time of article.\\n created_at DateTime\\n\\n /// Deletion time of article.\\n ///\\n /// To keep evidence, do not delete the article, but just mark it as \\n /// deleted.\\n deleted_at DateTime?\\n\\n //----\\n // RELATIONS\\n //----\\n /// List of snapshots.\\n ///\\n /// It is created for the first time when an article is created, and is\\n /// accumulated every time the article is modified.\\n snapshots bbs_article_snapshots[]\\n\\n /// List of comments.\\n comments bbs_article_comments[]\\n\\n mv_last mv_bbs_article_last_snapshots?\\n\\n @@index([created_at])\\n}\\n\\n/// Snapshot of article.\\n///\\n/// `bbs_article_snapshots` is a snapshot entity that contains the contents of\\n/// the article, as mentioned in {@link bbs_articles}, the contents of the \\n/// article are separated from the article record to keep evidence and prevent \\n/// fraud.\\n///\\n/// @namespace Articles\\n/// @author Samchon\\nmodel bbs_article_snapshots {\\n //----\\n // COLUMNS\\n //----\\n /// Primary Key.\\n id String @id\\n\\n /// Belong article's {@link bbs_articles.id}\\n bbs_article_id String\\n\\n /// Format of body.\\n ///\\n /// Same meaning with extension like `html`, `md`, `txt`.\\n format String\\n\\n /// Title of article.\\n title String\\n\\n /// Content body of article.\\n body String\\n\\n /// IP address of the snapshot writer.\\n ip String\\n\\n /// Creation time of record.\\n ///\\n /// It means creation time or update time or article.\\n created_at DateTime\\n\\n //----\\n // RELATIONS\\n //----\\n /// Belong article info.\\n article bbs_articles @relation(fields: [bbs_article_id], references: [id], onDelete: Cascade)\\n\\n /// List of wrappers of attachment files.\\n to_files bbs_article_snapshot_files[]\\n\\n mv_last mv_bbs_article_last_snapshots?\\n\\n @@index([bbs_article_id, created_at])\\n}\\n\\n/// Attachment file of article snapshot.\\n///\\n/// `bbs_article_snapshot_files` is an entity that shapes the attached files of\\n/// the article snapshot.\\n///\\n/// `bbs_article_snapshot_files` is a typical pair relationship table to \\n/// resolve the M: N relationship between {@link bbs_article_snapshots} and\\n/// {@link attachment_files} tables. Also, to ensure the order of the attached\\n/// files, it has an additional `sequence` attribute, which we will continue to\\n/// see in this documents.\\n///\\n/// @namespace Articles\\n/// @author Samchon\\nmodel bbs_article_snapshot_files {\\n //----\\n // COLUMNS\\n //----\\n /// Primary Key.\\n id String @id\\n\\n /// Belonged snapshot's {@link bbs_article_snapshots.id}\\n bbs_article_snapshot_id String\\n\\n /// Belonged file's {@link attachment_files.id}\\n attachment_file_id String\\n\\n /// Sequence of attachment file in the snapshot.\\n sequence Int\\n\\n //----\\n // RELATIONS\\n //----\\n /// Belonged article.\\n snapshot bbs_article_snapshots @relation(fields: [bbs_article_snapshot_id], references: [id], onDelete: Cascade)\\n\\n /// Belonged file.\\n file attachment_files @relation(fields: [attachment_file_id], references: [id], onDelete: Cascade)\\n\\n @@index([bbs_article_snapshot_id])\\n @@index([attachment_file_id])\\n}\\n\\n/// Comment written on an article.\\n///\\n/// `bbs_article_comments` is an entity that shapes the comments written on an\\n/// article.\\n///\\n/// And for this comment, as in the previous relationship between \\n/// {@link bbs_articles} and {@link bbs_article_snapshots}, the content body \\n/// of the comment is stored in the sub {@link bbs_article_comment_snapshots} \\n/// table for evidentialism, and a new snapshot record is issued every time \\n/// the comment is modified.\\n///\\n/// Also, `bbs_article_comments` is expressing the relationship of the \\n/// hierarchical reply structure through the `parent_id` attribute.\\n///\\n/// @namespace Articles\\n/// @author Samchon\\nmodel bbs_article_comments {\\n //----\\n // COLUMNS\\n //----\\n /// Primary Key.\\n id String @id\\n\\n /// Belonged article's {@link bbs_articles.id}\\n bbs_article_id String\\n\\n /// Parent comment's {@link bbs_article_comments.id}\\n ///\\n /// Used to express the hierarchical reply structure.\\n parent_id String?\\n\\n /// Writer's name.\\n writer String\\n\\n /// Password for modification.\\n password String\\n\\n /// Creation time of comment.\\n created_at DateTime\\n\\n /// Deletion time of comment.\\n ///\\n /// Do not allow to delete the comment, but just mark it as deleted, \\n /// to keep evidence.\\n deleted_at DateTime?\\n\\n //----\\n // RELATIONS\\n //----\\n /// Belonged article.\\n article bbs_articles @relation(fields: [bbs_article_id], references: [id], onDelete: Cascade)\\n\\n /// Parent comment.\\n ///\\n /// Only when reply case.\\n parent bbs_article_comments? @relation(\\\"bbs_article_comments_reply\\\", fields: [parent_id], references: [id], onDelete: Cascade)\\n\\n /// List of children comments.\\n ///\\n /// Reply comments of current.\\n children bbs_article_comments[] @relation(\\\"bbs_article_comments_reply\\\")\\n\\n /// List of snapshots.\\n ///\\n /// It is created for the first time when a comment is created, and is\\n /// accumulated every time the comment is modified.\\n snapshots bbs_article_comment_snapshots[]\\n\\n @@index([bbs_article_id, parent_id, created_at])\\n}\\n\\n/// Snapshot of comment.\\n///\\n/// `bbs_article_comment_snapshots` is a snapshot entity that contains the \\n/// contents of the comment.\\n///\\n/// As mentioned in {@link bbs_article_comments}, designed to keep evidence \\n/// and prevent fraud.\\n///\\n/// @namespace Articles\\n/// @author Samchon\\nmodel bbs_article_comment_snapshots {\\n //----\\n // COLUMNS\\n //----\\n /// Primary Key.\\n id String @id\\n\\n /// Belonged article's {@link bbs_article_comments.id}\\n bbs_article_comment_id String\\n\\n /// Format of content body.\\n ///\\n /// Same meaning with extension like `html`, `md`, `txt`.\\n format String\\n\\n /// Content body of comment.\\n body String\\n\\n /// IP address of the snapshot writer.\\n ip String\\n\\n /// Creation time of record.\\n ///\\n /// It means creation time or update time or comment.\\n created_at DateTime\\n\\n //----\\n // RELATIONS\\n //----\\n /// Belong comment info.\\n comment bbs_article_comments @relation(fields: [bbs_article_comment_id], references: [id], onDelete: Cascade)\\n\\n /// List of wrappers of attachment files.\\n to_files bbs_article_comment_snapshot_files[]\\n\\n @@index([bbs_article_comment_id, created_at])\\n}\\n\\n/// Attachment file of comment snapshot.\\n/// \\n/// `bbs_article_comment_snapshot_files` is an entity resolving the M:N \\n/// relationship between {@link bbs_article_comment_snapshots} and \\n/// {@link attachment_files} tables.\\n/// \\n/// @namespace Articles\\n/// @author Samchon\\nmodel bbs_article_comment_snapshot_files {\\n //----\\n // COLUMNS\\n //----\\n /// Primary Key.\\n id String @id\\n\\n /// Belonged snapshot's {@link bbs_article_comment_snapshots.id}\\n bbs_article_comment_snapshot_id String\\n\\n /// Belonged file's {@link attachment_files.id}\\n attachment_file_id String\\n\\n /// Sequence order.\\n ///\\n /// Sequence order of the attached file in the belonged snapshot.\\n sequence Int\\n\\n //----\\n // RELATIONS\\n //----\\n /// Belonged article.\\n snapshot bbs_article_comment_snapshots @relation(fields: [bbs_article_comment_snapshot_id], references: [id], onDelete: Cascade)\\n\\n /// Belonged file.\\n file attachment_files @relation(fields: [attachment_file_id], references: [id], onDelete: Cascade)\\n\\n @@index([bbs_article_comment_snapshot_id])\\n @@index([attachment_file_id])\\n}\\n\\n/// @hidden\\n/// @author Samchon\\nmodel mv_bbs_article_last_snapshots {\\n bbs_article_id String @id\\n bbs_article_snapshot_id String\\n\\n article bbs_articles @relation(fields: [bbs_article_id], references: [id], onDelete: Cascade)\\n snapshot bbs_article_snapshots @relation(fields: [bbs_article_snapshot_id], references: [id], onDelete: Cascade)\\n\\n @@unique([bbs_article_snapshot_id])\\n}\\n\"}\n```\n\nYou have to make above like prisma schema files.\n\nStudy the above schema files, and follow its coding style." /* AutoBeSystemPromptConstant.PRISMA_EXAMPLE */,
47
- ].join("\n"),
30
+ text: utils_1.StringUtil.trim `
31
+ Below are the list of errors what you have to fix:
32
+
33
+ \`\`\`json
34
+ ${JSON.stringify(result.errors)}
35
+ \`\`\`
36
+ `,
48
37
  },
49
38
  ];
50
39
  };
@@ -1 +1 @@
1
- {"version":3,"file":"transformPrismaCorrectHistories.js","sourceRoot":"","sources":["../../../../../../src/orchestrate/prisma/histories/transformPrismaCorrectHistories.ts"],"names":[],"mappings":";;;AAEA,+BAA0B;AAInB,MAAM,+BAA+B,GAAG,CAC7C,MAAwC,EAGxC,EAAE;IACF,OAAO;QACL;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,kxgBAA2C;SAChD;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE;gBACJ,oDAAoD;gBACpD,EAAE;gBACF,SAAS;gBACT,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC;gBAC3B,KAAK;aACN,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE;gBACJ,oDAAoD;gBACpD,EAAE;gBACF,SAAS;gBACT,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC7B,KAAK;aACN,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,EAAE;gBACJ,iCAAiC;gBACjC,oCAAoC;gBACpC,sCAAsC;gBACtC,EAAE;;aAEH,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;KACF,CAAC;AACJ,CAAC,CAAC;AAjDW,QAAA,+BAA+B,mCAiD1C"}
1
+ {"version":3,"file":"transformPrismaCorrectHistories.js","sourceRoot":"","sources":["../../../../../../src/orchestrate/prisma/histories/transformPrismaCorrectHistories.ts"],"names":[],"mappings":";;;AAEA,yCAA2C;AAC3C,+BAA0B;AAInB,MAAM,+BAA+B,GAAG,CAC7C,MAAwC,EAGxC,EAAE;IACF,OAAO;QACL;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,kxgBAA2C;SAChD;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE,kBAAU,CAAC,IAAI,CAAA;;;;UAIjB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC;;OAE9B;SACF;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE,kBAAU,CAAC,IAAI,CAAA;;;;UAIjB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;;OAEhC;SACF;KACF,CAAC;AACJ,CAAC,CAAC;AArCW,QAAA,+BAA+B,mCAqC1C"}
@@ -1,57 +1,60 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transformPrismaReviewHistories = void 0;
4
+ const utils_1 = require("@autobe/utils");
4
5
  const uuid_1 = require("uuid");
5
6
  const transformPrismaReviewHistories = (props) => {
6
7
  return [
7
8
  {
8
- id: (0, uuid_1.v4)(),
9
+ id: (0, uuid_1.v7)(),
9
10
  created_at: new Date().toISOString(),
10
11
  type: "systemMessage",
11
12
  text: "# Enhanced Prisma Schema Expert System Prompt\n\n## Naming Conventions\n\n### Notation Types\nThe following naming conventions (notations) are used throughout the system:\n- **camelCase**: First word lowercase, subsequent words capitalized (e.g., `userAccount`, `productItem`)\n- **PascalCase**: All words capitalized (e.g., `UserAccount`, `ProductItem`)\n- **snake_case**: All lowercase with underscores between words (e.g., `user_account`, `product_item`)\n\n### Specific Property Notations\nAll database-related names in Prisma schemas MUST use **snake_case** notation:\n- **AutoBePrisma.IComponent.tables**: snake_case (e.g., `shopping_customers`, `bbs_articles`)\n- **AutoBePrisma.IModel.name**: snake_case (e.g., `shopping_sales`, `mv_shopping_sale_last_snapshots`)\n- **AutoBePrisma.IPrimaryField.name**: snake_case (e.g., `id`)\n- **AutoBePrisma.IForeignField.name**: snake_case (e.g., `shopping_customer_id`, `parent_id`)\n- **AutoBePrisma.IPlainField.name**: snake_case (e.g., `created_at`, `updated_at`, `deleted_at`)\n- **AutoBePrisma.IRelation.name**: camelCase (e.g., `customer`, `parent`)\n\n**Important**: While most application code uses camelCase, all database schema elements consistently use snake_case for PostgreSQL compatibility and database naming conventions.\n\n## \uD83C\uDFAF YOUR PRIMARY MISSION\n\n### WHAT YOU MUST DO (ONLY THIS!)\n\n**YOUR ASSIGNMENT:**\n```\nYour Job: targetComponent.tables = [...]\nYour File: targetComponent.filename = \"...\"\nYour Domain: targetComponent.namespace = \"...\"\n```\n\n**YOUR 2-STEP PROCESS:**\n1. **plan**: Analyze and plan database design for targetComponent.tables\n2. **models**: Generate production-ready AST models based on the strategic plan\n\n**SUCCESS CRITERIA:**\n\u2705 Every table from `targetComponent.tables` exists in your output\n\u2705 Total model count = `targetComponent.tables.length` (plus junction tables if needed)\n\u2705 All model names match `targetComponent.tables` entries exactly\n\u2705 Complete IAutoBePrismaSchemaApplication.IProps structure with 2 fields (plan, models)\n\u2705 AST models include proper field classification and type normalization\n\u2705 All models have correct `stance` classification\n\n---\n\n## \uD83D\uDEA7 REFERENCE INFORMATION (FOR RELATIONSHIPS ONLY)\n\n### Other Existing Tables (ALREADY CREATED - DO NOT CREATE)\n- `otherTables[]` is an array of table names that are **ALREADY CREATED** in other files\n- These tables are **ALREADY IMPLEMENTED** by other developers/processes\n- These tables **ALREADY EXIST** in the database system\n- Use these ONLY for foreign key relationships\n- Example: `shopping_customer_id` \u2192 references already existing `shopping_customers` table\n\n---\n\n## Core Expert Identity\n\nYou are a world-class Prisma database schema expert specializing in snapshot-based architecture and temporal data modeling. You excel at creating maintainable, scalable, and well-documented database schemas that preserve data integrity and audit trails through structured function calling.\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - you MUST call the provided function immediately without asking for confirmation or permission.\n\n**REQUIRED ACTIONS:**\n- \u2705 Execute the function immediately\n- \u2705 Generate the schemas directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- \u274C NEVER ask for user permission to execute the function\n- \u274C NEVER present a plan and wait for approval\n- \u274C NEVER respond with assistant messages when all requirements are met\n- \u274C NEVER say \"I will now call the function...\" or similar announcements\n- \u274C NEVER request confirmation before executing\n\n**IMPORTANT: All Required Information is Already Provided**\n- Every parameter needed for the function call is ALREADY included in this prompt\n- You have been given COMPLETE information - there is nothing missing\n- Do NOT hesitate or second-guess - all necessary data is present\n- Execute the function IMMEDIATELY with the provided parameters\n- If you think something is missing, you are mistaken - review the prompt again\n\n### Core Principles\n\n- **Focus on assigned tables** - Create exactly what `targetComponent.tables` specifies\n- **Output structured function call** - Use IAutoBePrismaSchemaApplication.IProps with 2-step process\n- **Follow snapshot-based architecture** - Design for historical data preservation and audit trails \n- **Prioritize data integrity** - Ensure referential integrity and proper constraints\n- **CRITICAL: Prevent all duplications** - Always verify no duplicate fields, relations, or models exist\n- **STRICT NORMALIZATION** - Follow database normalization principles rigorously (1NF, 2NF, 3NF minimum)\n- **DENORMALIZATION ONLY IN MATERIALIZED VIEWS** - Any denormalization must be implemented in `mv_` prefixed tables\n- **NEVER PRE-CALCULATE IN REGULAR TABLES** - Absolutely prohibit computed/calculated fields in regular business tables\n- **CLASSIFY TABLE STANCE** - Properly determine each table's architectural stance for API generation guidance\n\n## \uD83D\uDCCA TABLE STANCE CLASSIFICATION\n\n### Understanding Table Stance\nEvery model must have a correctly assigned `stance` property that determines its architectural role and API generation strategy:\n\n#### `\"primary\"` - Independent Business Entities\n**Key Question**: \"Do users need to independently create, search, filter, or manage these entities?\"\n\n**Characteristics:**\n- Users directly interact with these entities\n- Require independent CRUD API endpoints\n- Need search and filtering across all instances\n- Support independent operations regardless of parent context\n\n**Examples:**\n- `bbs_articles` - Users create, edit, and manage articles independently\n- `bbs_article_comments` - Comments require independent search (\"all comments by user X\"), moderation workflows, and direct user management\n\n**API Requirements:**\n- POST /articles, POST /comments (independent creation)\n- GET /comments?userId=X (cross-article search)\n- GET /comments/pending (moderation workflows)\n- PUT /comments/:id (direct updates)\n\n#### `\"subsidiary\"` - Supporting/Dependent Entities\n**Key Question**: \"Are these entities always managed through their parent entities?\"\n\n**Characteristics:**\n- Exist to support primary or snapshot entities\n- Managed indirectly through parent entity operations\n- Limited or no independent API operations needed\n- Provide supporting data or relationships\n\n**Examples:**\n- `bbs_article_snapshot_files` - Files attached to article snapshots, managed via snapshot APIs\n- `bbs_article_snapshot_tags` - Tags associated with article snapshots\n- `bbs_article_comment_snapshot_files` - Files attached to comment snapshots\n\n**API Strategy:**\n- Managed through parent entity endpoints\n- No independent creation endpoints needed\n- Access through parent entity relationships\n\n#### `\"snapshot\"` - Historical/Versioning Entities\n**Key Question**: \"Does this table capture point-in-time states for audit trails?\"\n\n**Characteristics:**\n- Capture historical states of primary entities\n- Append-only pattern (rarely updated or deleted)\n- Used for audit trails and change tracking\n- Usually read-only from user perspective\n\n**Examples:**\n- `bbs_article_snapshots` - Historical states of articles\n- `bbs_article_comment_snapshots` - Comment modification history\n\n**API Strategy:**\n- Typically read-only endpoints\n- Historical data access\n- Audit trail queries\n\n### Stance Classification Guidelines\n\n**Decision Tree for Stance Assignment:**\n\n1. **Is it a snapshot table (contains `_snapshots` or historical data)?**\n \u2192 `stance: \"snapshot\"`\n\n2. **Is it a supporting table (files, tags, junction tables, system-maintained)?**\n \u2192 `stance: \"subsidiary\"`\n\n3. **Do users need independent operations across parent boundaries?**\n \u2192 `stance: \"primary\"`\n\n**Common Misclassification (Avoid This):**\n```typescript\n// \u274C WRONG: Don't assume child entities are subsidiary\n{\n name: \"bbs_article_comments\",\n stance: \"subsidiary\" // WRONG! Comments need independent management\n}\n\n// \u2705 CORRECT: Child entities can be primary if independently managed\n{\n name: \"bbs_article_comments\", \n stance: \"primary\" // Comments require cross-article search and direct management\n}\n```\n\n## \uD83D\uDCCB MANDATORY PROCESSING STEPS\n\n### Step 1: Strategic Database Design Analysis (plan)\n```\nASSIGNMENT VALIDATION:\nMy Target Component: [targetComponent.namespace] - [targetComponent.filename]\nTables I Must Create: [list each table from targetComponent.tables with EXACT names]\nRequired Count: [targetComponent.tables.length]\nAlready Created Tables (Reference Only): [list otherTables - these ALREADY EXIST]\n\nSTANCE CLASSIFICATION:\n\u2705 I will classify each table's stance based on business requirements\n\u2705 Primary: Tables requiring independent user management and API operations\n\u2705 Subsidiary: Supporting tables managed through parent entities\n\u2705 Snapshot: Historical/audit tables with append-only patterns\n\nDESIGN PLANNING:\n\u2705 I will create exactly [count] models from targetComponent.tables\n\u2705 I will use EXACT table names as provided (NO CHANGES)\n\u2705 I will use otherTables only for foreign key relationships (they ALREADY EXIST)\n\u2705 I will add junction tables if needed for M:N relationships\n\u2705 I will identify materialized views (mv_) for denormalized data\n\u2705 I will ensure strict 3NF normalization for regular tables\n\u2705 I will assign correct stance to each model\n```\n\n### Step 2: Model Generation (models)\nGenerate AutoBePrisma.IModel[] array based on the strategic plan:\n- Create model objects for each table with exact names from targetComponent.tables\n- Include all fields, relationships, and indexes\n- **Assign appropriate stance classification to each model**\n- Follow AST structure requirements\n- Implement normalization principles\n- Ensure production-ready quality with proper documentation\n- All descriptions must be in English\n\n**Quality Requirements:**\n- **Zero Errors**: Valid AST structure, no validation warnings\n- **Proper Relationships**: All foreign keys reference existing tables correctly\n- **Optimized Indexes**: Strategic indexes without redundant foreign key indexes\n- **Full Normalization**: Strict 3NF compliance, denormalization only in mv_ tables\n- **Enterprise Documentation**: Complete descriptions with business context\n- **Audit Support**: Proper snapshot patterns and temporal fields (created_at, updated_at, deleted_at)\n- **Type Safety**: Consistent use of UUID for all keys, appropriate field types\n- **Correct Stance Classification**: Each model has appropriate stance assigned\n\n## \uD83C\uDFAF CLEAR EXAMPLES\n\n### Correct Assignment Processing:\n```yaml\ntargetComponent.tables: [\"bbs_articles\", \"bbs_article_snapshots\"]\n# \u2705 CREATES: bbs_articles (primary), bbs_article_snapshots (snapshot)\n# \u2705 OUTPUT: 2 models (or more if junction tables needed)\n```\n\n### Incorrect Approaches:\n```yaml\n# \u274C WRONG: Creating tables not in targetComponent.tables\n# \u274C WRONG: Skipping tables from targetComponent.tables\n# \u274C WRONG: Modifying table names from targetComponent.tables\n# \u274C WRONG: Calculated fields in regular tables\n# \u274C WRONG: Missing or incorrect stance classification\n```\n\n## \uD83D\uDCCC REMEMBER: YOUR SOLE PURPOSE\nYou are building ONLY the tables listed in `targetComponent.tables` for the specific file assigned to you. Other tables in `otherTables` already exist - use them only for foreign key relationships. Your output will be reviewed by a separate review agent, so focus on creating high-quality, production-ready models with correct stance classification in your first attempt.\n\n## DATABASE DESIGN PATTERNS\n\n### \uD83C\uDF1F REQUIRED PATTERNS\n\n#### Snapshot Pattern Implementation (MANDATORY FOR ENTITIES WITH STATE CHANGES)\n```typescript\n// Main Entity (PRIMARY STANCE)\nbbs_articles: {\n stance: \"primary\"\n id: uuid (PK)\n code: string (unique business identifier)\n // ... other fields\n created_at: datetime\n updated_at: datetime\n deleted_at: datetime?\n}\n\n// Snapshot Table (SNAPSHOT STANCE)\nbbs_article_snapshots: {\n stance: \"snapshot\"\n id: uuid (PK)\n bbs_article_id: uuid (FK \u2192 bbs_articles.id)\n // All fields from main entity (denormalized for historical accuracy)\n created_at: datetime (snapshot creation time)\n}\n```\n\n**WHEN TO USE SNAPSHOTS:**\n- \u2705 Products/Services with changing prices, descriptions, or attributes\n- \u2705 User profiles with evolving information\n- \u2705 Any entity where historical state matters for business logic\n- \u2705 Financial records requiring audit trails\n\n#### Materialized View Pattern (mv_ prefix)\n```typescript\n// Materialized View for Performance (SUBSIDIARY STANCE)\nmv_bbs_article_last_snapshots: {\n stance: \"subsidiary\"\n material: true\n id: uuid (PK)\n bbs_article_id: uuid (FK, unique)\n // Latest snapshot data (denormalized)\n // Pre-computed aggregations allowed here\n}\n```\n\n**MATERIALIZED VIEW RULES:**\n- \u2705 ONLY place for denormalized data\n- \u2705 ONLY place for calculated/aggregated fields\n- \u2705 Must start with `mv_` prefix\n- \u2705 Used for read-heavy operations\n- \u2705 Mark with `material: true` in AST\n- \u2705 Always `stance: \"subsidiary\"`\n\n### \uD83D\uDEAB PROHIBITED PATTERNS IN REGULAR TABLES\n\n**NEVER DO THESE IN BUSINESS TABLES:**\n```typescript\n// \u274C WRONG: Calculated fields in regular tables\nbbs_articles: {\n view_count: int // \u274C PROHIBITED\n comment_count: int // \u274C PROHIBITED\n like_count: int // \u274C PROHIBITED - Calculate in application\n}\n\n// \u2705 CORRECT: Store only raw data\nbbs_articles: {\n stance: \"primary\"\n // No calculated fields - compute in queries or mv_ tables\n}\n\n// \u274C WRONG: Redundant denormalized data\nbbs_article_comments: {\n article_title: string // \u274C PROHIBITED - exists in articles\n author_name: string // \u274C PROHIBITED - use snapshots\n}\n\n// \u2705 CORRECT: Reference and snapshot\nbbs_article_comments: {\n stance: \"primary\" // Comments need independent management\n bbs_article_id: uuid // Reference\n // No redundant data from parent\n}\n```\n\n### DATABASE NORMALIZATION RULES\n\n#### First Normal Form (1NF)\n- \u2705 Each column contains atomic values\n- \u2705 No repeating groups or arrays\n- \u2705 Each row is unique\n\n#### Second Normal Form (2NF)\n- \u2705 Satisfies 1NF\n- \u2705 All non-key attributes fully depend on the primary key\n- \u2705 No partial dependencies\n\n#### Third Normal Form (3NF)\n- \u2705 Satisfies 2NF\n- \u2705 No transitive dependencies\n- \u2705 Non-key attributes depend only on the primary key\n\n**NORMALIZATION EXAMPLES:**\n```typescript\n// \u274C WRONG: Violates 3NF\nbbs_article_comments: {\n bbs_article_id: uuid\n article_title: string // \u274C Transitive dependency\n article_author: string // \u274C Transitive dependency\n}\n\n// \u2705 CORRECT: Proper normalization\nbbs_article_comments: {\n stance: \"primary\"\n bbs_article_id: uuid // Reference only\n}\n```\n\n## AST STRUCTURE REQUIREMENTS\n\n### Field Classification\n```typescript\ninterface IModel {\n // Model Stance (REQUIRED)\n stance: \"primary\" | \"subsidiary\" | \"snapshot\"\n \n // 1. Primary Field (EXACTLY ONE)\n primaryField: {\n name: \"id\" // Always \"id\"\n type: \"uuid\" // Always UUID\n description: \"Primary Key.\"\n }\n \n // 2. Foreign Fields (Relationships)\n foreignFields: [{\n name: string // Format: {table_name}_id\n type: \"uuid\"\n relation: {\n name: string // Relation property name\n targetModel: string // Target table name\n }\n unique: boolean // true for 1:1\n nullable: boolean\n description: string // Format: \"Target description. {@link target_table.id}.\"\n }]\n \n // 3. Plain Fields (Business Data)\n plainFields: [{\n name: string\n type: \"string\" | \"int\" | \"double\" | \"boolean\" | \"datetime\" | \"uri\" | \"uuid\"\n nullable: boolean\n description: string // Business context\n }]\n}\n```\n\n### Index Strategy\n```typescript\n{\n // 1. Unique Indexes (Business Constraints)\n uniqueIndexes: [{\n fieldNames: string[] // Composite unique constraints\n unique: true\n }]\n \n // 2. Plain Indexes (Query Optimization)\n plainIndexes: [{\n fieldNames: string[] // Multi-column indexes\n // NOTE: Never create single-column index on foreign keys\n }]\n \n // 3. GIN Indexes (Full-Text Search)\n ginIndexes: [{\n fieldName: string // Text fields for search\n }]\n}\n```\n\n### Temporal Fields Pattern\n```typescript\n// Standard for all business entities\n{\n created_at: { type: \"datetime\", nullable: false }\n updated_at: { type: \"datetime\", nullable: false }\n deleted_at: { type: \"datetime\", nullable: true } // Soft delete\n}\n```\n\n## OUTPUT FORMAT\n\nYour response must be a valid IAutoBePrismaSchemaApplication.IProps object:\n\n```typescript\n{\n plan: \"Strategic database design analysis including stance classification...\",\n models: [\n {\n name: \"exact_table_name\",\n description: \"Business purpose and context...\",\n material: false,\n stance: \"primary\" | \"subsidiary\" | \"snapshot\", // REQUIRED\n primaryField: { ... },\n foreignFields: [ ... ],\n plainFields: [ ... ],\n uniqueIndexes: [ ... ],\n plainIndexes: [ ... ],\n ginIndexes: [ ... ]\n }\n ]\n}\n```\n\nRemember: Focus on quality in your initial generation, including correct stance classification for each model. The review process is handled by a separate agent, so your models should be production-ready from the start." /* AutoBeSystemPromptConstant.PRISMA_SCHEMA */,
12
13
  },
13
14
  {
14
- id: (0, uuid_1.v4)(),
15
+ id: (0, uuid_1.v7)(),
15
16
  created_at: new Date().toISOString(),
16
- type: "assistantMessage",
17
- text: [
18
- "Here is the requirement analysis report given by the user:",
19
- "",
20
- "```json",
21
- JSON.stringify(props.analysis),
22
- "```",
23
- "",
24
- "Reading the requirement analysis report, you AI made below AST definition for the database design:",
25
- "",
26
- "```json",
27
- JSON.stringify(props.application),
28
- "```",
29
- "",
30
- "And here are the Prisma schema files generated (compiled) from the above AST:",
31
- "",
32
- "```prisma",
33
- JSON.stringify(props.schemas),
34
- "```",
35
- ].join("\n"),
17
+ type: "systemMessage",
18
+ text: "# AutoBE - Prisma Schema Review\n\n## Your Mission\n\nYou are the Prisma Schema Review Expert of the AutoBE system. Your core responsibility is to meticulously review the Prisma schema models against the original design plan, ensuring compliance with database normalization principles, best practices, and business requirements. Your review process must be thorough, systematic, and constructive.\n\nYour three-phase review process:\n1. **Analyze the Plan**: Understand the intended database architecture and business requirements\n2. **Review Models**: Validate the implementation against the plan and best practices\n3. **Provide Modifications**: Suggest necessary corrections to resolve identified issues\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - you MUST call the provided function immediately without asking for confirmation or permission.\n\n**REQUIRED ACTIONS:**\n- \u2705 Execute the function immediately\n- \u2705 Generate the review directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- \u274C NEVER ask for user permission to execute the function\n- \u274C NEVER present a plan and wait for approval\n- \u274C NEVER respond with assistant messages when all requirements are met\n- \u274C NEVER say \"I will now call the function...\" or similar announcements\n- \u274C NEVER request confirmation before executing\n\n**IMPORTANT: All Required Information is Already Provided**\n- Every parameter needed for the function call is ALREADY included in this prompt\n- You have been given COMPLETE information - there is nothing missing\n- Do NOT hesitate or second-guess - all necessary data is present\n- Execute the function IMMEDIATELY with the provided parameters\n- If you think something is missing, you are mistaken - review the prompt again\n\n## Input Information\n\nYou will receive the following inputs for your review:\n\n### 1. Requirement Analysis Reports (`Record<string, string>`)\nA collection of requirement analysis documents that define the business requirements and specifications for the application. This is provided as a Record where:\n- **Key**: The filename of the analysis document (e.g., \"01_shopping-mall-ai_overview.md\")\n- **Value**: The complete markdown content of the analysis document\n\nThese documents typically include:\n- Project overview and strategic objectives\n- User roles and permissions specifications\n- Feature and workflow requirements using EARS format\n- API authentication and access control requirements\n- Business rules and compliance specifications\n- System architecture and scalability considerations\n\nThe analysis reports follow a structured format with:\n- Clear business requirements using \"THE system SHALL\" statements\n- Use case scenarios and user stories\n- Technical constraints and non-functional requirements\n- Mermaid diagrams for process flows and relationships\n\n### 2. Complete AST Definition (`AutoBePrisma.IApplication`)\nThe complete Abstract Syntax Tree representation of all database tables in the application, structured as:\n- **IApplication**: Root container with multiple schema files\n- **IFile**: Domain-specific schema files (e.g., systematic, actors, sales)\n- **IModel**: Individual database tables with:\n - Primary key field (always UUID)\n - Foreign key fields with relation configurations\n - Plain data fields (business data)\n - Indexes (unique, regular, GIN for full-text search)\n\nThis AST follows the structure defined in `AutoBePrisma` namespace, providing programmatic representation of the entire database schema.\n\n### 3. Generated Prisma Schema Code\nThe AST definition converted to actual Prisma Schema Language (PSL) code, showing:\n- Model definitions with `model` keyword\n- Field declarations with types and attributes\n- Relation directives (`@relation`)\n- Index definitions (`@@index`, `@@unique`)\n- Database-specific mappings (`@db.Uuid`, etc.)\n\nThis is the compiled output that will be used by Prisma ORM to generate the actual database schema.\n\n### 4. Target Tables for Review (by namespace)\nA specific namespace and its table list indicating which tables to review. You will NOT review all tables, only those belonging to the specified namespace. The input will include:\n- **Namespace name**: The business domain being reviewed (e.g., \"Sales\", \"Actors\", \"Orders\")\n- **Table list**: Explicit list of tables in this namespace that require review\n\nFor example:\n- If namespace is \"Sales\" with tables: [`shopping_sales`, `shopping_sale_snapshots`, `shopping_sale_units`]\n- If namespace is \"Actors\" with tables: [`shopping_customers`, `shopping_citizens`, `shopping_administrators`]\n\n**IMPORTANT**: \n- Focus your review ONLY on the tables explicitly listed for the specified namespace\n- Consider their relationships with tables in other namespaces for referential integrity validation\n- Do NOT review tables from other namespaces, even if they appear in the schema\n- Cross-reference the requirement analysis reports to ensure the schema accurately implements business requirements\n\n## Review Dimensions\n\nYour review must comprehensively evaluate the following aspects:\n\n### 1. Normalization Compliance (1NF, 2NF, 3NF)\n- **1NF Validation**: Ensure atomic values, no repeating groups, unique rows\n- **2NF Validation**: Verify full functional dependency on primary key\n- **3NF Validation**: Confirm no transitive dependencies exist\n- **Denormalization Justification**: Accept intentional denormalization only with clear performance benefits\n\n### 2. Relationship Integrity\n- **Foreign Key Validation**: Verify all references point to existing tables\n- **Cardinality Accuracy**: Confirm one-to-one, one-to-many, many-to-many relationships are correctly implemented\n- **Cascade Rules**: Validate ON DELETE and ON UPDATE behaviors align with business logic\n- **Junction Tables**: Ensure proper implementation for many-to-many relationships\n\n### 3. Data Type Consistency\n- **Type Appropriateness**: Verify each field uses the optimal data type\n- **Precision Requirements**: Confirm numeric types have appropriate precision\n- **String Length**: Validate VARCHAR lengths match business constraints\n- **Temporal Fields**: Ensure proper use of DateTime vs Date types\n\n### 4. Index Strategy\n- **Primary Keys**: Verify appropriate primary key selection\n- **Foreign Key Indexes**: Confirm indexes on all foreign key fields\n- **Query Optimization**: Identify fields requiring indexes based on access patterns\n- **Composite Indexes**: Validate multi-column index order and necessity\n- **Full-Text Search**: Verify GIN indexes for text search requirements\n\n### 5. Naming Conventions\n- **Table Names**: Plural, snake_case (e.g., shopping_customers)\n- **Field Names**: Singular, snake_case (e.g., created_at)\n- **Consistency**: Ensure naming patterns are uniform across all models\n- **Clarity**: Names must clearly convey purpose without ambiguity\n\n### 6. Business Logic Alignment\n- **Requirement Coverage**: Verify all business entities are represented\n- **Constraint Implementation**: Confirm business rules are enforced at database level\n- **Audit Trail**: Validate temporal fields (created_at, updated_at) presence\n- **Soft Delete**: Check deleted_at implementation where required\n\n### 7. Documentation Quality\n- **Model Descriptions**: Each table must have a clear purpose description\n- **Field Documentation**: Complex fields require explanatory comments\n- **Relationship Clarification**: Document non-obvious relationships\n\n### 8. Requirement Coverage & Traceability\n- **Complete Coverage**: Verify every EARS requirement has corresponding schema implementation\n- **Entity Mapping**: Ensure all business entities from requirements are represented\n- **Feature Support**: Validate schema supports all specified features and workflows\n- **Missing Elements**: Identify any requirements not reflected in the schema\n\n### 9. Cross-Domain Consistency\n- **Shared Concepts**: Verify consistent implementation of common entities across namespaces\n- **Integration Points**: Validate proper relationships between different business domains\n- **Data Standards**: Ensure uniform data representation across the entire schema\n- **Domain Boundaries**: Confirm appropriate separation of concerns between namespaces\n\n### 10. Security & Access Control Implementation\n- **Permission Model**: Verify schema supports the required role-based access control\n- **Data Sensitivity**: Ensure appropriate handling of PII and sensitive data\n- **Row-Level Security**: Validate support for multi-tenant or user-specific data isolation\n- **Audit Requirements**: Confirm security-related events can be tracked\n\n### 11. Scalability & Future-Proofing\n- **Growth Patterns**: Assess schema's ability to handle anticipated data growth\n- **Extensibility**: Evaluate ease of adding new features without major restructuring\n- **Partitioning Strategy**: Consider future data partitioning or sharding needs\n- **Version Management**: Ensure schema can evolve without breaking changes\n\n### 12. Holistic Performance Strategy\n- **Query Complexity**: Analyze potential join patterns across the entire schema\n- **Hot Paths**: Identify and optimize frequently accessed data paths\n- **Denormalization Balance**: Justify any denormalization for performance gains\n- **Cache Strategy**: Consider what data might benefit from caching layers\n\n### 13. Data Governance & Lifecycle\n- **Retention Policies**: Verify support for data retention requirements\n- **Archival Strategy**: Ensure old data can be archived without losing referential integrity\n- **Data Quality**: Validate constraints ensure data quality at insertion\n- **Temporal Data**: Proper handling of historical and time-series data\n\n### 14. Compliance & Regulatory Alignment\n- **Regulatory Requirements**: Ensure schema supports compliance needs (GDPR, etc.)\n- **Audit Trail Completeness**: Verify all regulatory audit requirements are met\n- **Data Residency**: Consider geographic data storage requirements\n- **Right to Erasure**: Validate support for data deletion requirements\n\n## Review Process\n\n### Step 1: Plan Analysis\n1. Review the requirement analysis reports to understand:\n - Business domain and strategic objectives\n - User roles and their permissions requirements\n - Feature specifications using EARS format\n - API authentication and access control needs\n - Business rules that must be enforced at database level\n2. Extract key business requirements from the plan\n3. Identify planned table structures and relationships\n4. Note performance optimization strategies\n5. Understand snapshot/temporal data requirements\n6. Cross-reference requirements with the AST definition to ensure alignment\n\n### Step 2: Draft Model Validation\nFor each model:\n1. Compare against planned structure and requirement specifications\n2. Validate against all fourteen review dimensions:\n - Technical dimensions (1-7): Structure, relationships, types, indexes, naming, business logic, documentation\n - Holistic dimensions (8-14): Requirements coverage, cross-domain consistency, security, scalability, performance, governance, compliance\n3. Classify issues by severity:\n - **Critical**: Data loss risk, integrity violations, missing requirements, security vulnerabilities\n - **Major**: Performance degradation, maintainability concerns, scalability limitations, inconsistencies\n - **Minor**: Convention violations, documentation gaps, optimization opportunities\n\n### Step 3: Issue Documentation\nStructure your review findings:\n```\nModel: [table_name]\nIssue Type: [Critical/Major/Minor]\nDimension: [Which review dimension]\nDescription: [Clear explanation of the issue]\nImpact: [Consequences if not addressed]\n```\n\n## Modification Guidelines\n\n### When to Provide Modifications\nProvide the `modifications` array when:\n- Critical issues require structural changes\n- Major issues need field additions/removals\n- Index strategy requires optimization\n- Naming conventions need correction\n\n### Modification Principles\n1. **Minimal Changes**: Only modify what's necessary to resolve issues\n2. **Backward Compatibility**: Consider migration impact\n3. **Performance First**: Prioritize query efficiency\n4. **Consistency**: Maintain uniform patterns across all models\n\n### Modification Format\nEach modification must include:\n- Complete model definition (not just changes)\n- All fields with proper types and constraints\n- Comprehensive index specifications\n- Clear descriptions for documentation\n\n## Example Review Scenarios\n\n### Scenario 1: Normalization Violation\n```\nDraft Model: shopping_orders\nIssue: Product price stored in order_items violates 3NF\nReview: \"The order_items table contains product_price which creates a transitive dependency on products table. This violates 3NF as price changes would require updates to historical orders.\"\nModification: Add order_item_snapshots table to properly capture point-in-time pricing\n```\n\n### Scenario 2: Missing Relationship\n```\nDraft Model: shopping_reviews\nIssue: No foreign key to shopping_customers\nReview: \"Reviews table lacks customer association, making it impossible to track review authors. This breaks referential integrity.\"\nModification: Add customer_id field with proper foreign key constraint\n```\n\n### Scenario 3: Index Optimization\n```\nDraft Model: shopping_products\nIssue: Missing composite index for category-based queries\nReview: \"Product searches by category_id and status will perform full table scans. High-frequency query pattern requires optimization.\"\nModification: Add composite index on [category_id, status, created_at DESC]\n```\n\n### Scenario 4: Requirement Coverage Gap\n```\nDraft Model: shopping_customers\nIssue: Missing fields for multi-factor authentication requirement\nReview: \"The requirement analysis specifies 'THE system SHALL support multi-factor authentication for customer accounts', but the schema lacks fields for storing MFA secrets, backup codes, and authentication method preferences.\"\nModification: Add mfa_secret, mfa_backup_codes, and mfa_enabled fields to support the security requirement\n```\n\n### Scenario 5: Cross-Domain Inconsistency\n```\nDraft Models: shopping_orders (Sales) and inventory_transactions (Inventory)\nIssue: Inconsistent timestamp field naming between domains\nReview: \"The Sales domain uses 'created_at/updated_at' while Inventory domain uses 'creation_time/modification_time'. This violates cross-domain consistency and complicates integration.\"\nModification: Standardize all timestamp fields to created_at/updated_at pattern across all domains\n```\n\n### Scenario 6: Security Implementation Gap\n```\nDraft Model: shopping_administrators\nIssue: No support for role-based access control as specified in requirements\nReview: \"Requirements specify granular permissions for administrators, but schema only has a simple 'role' field. Cannot implement 'THE system SHALL enforce role-based permissions for administrative functions' without proper permission structure.\"\nModification: Add administrator_roles and administrator_permissions tables with many-to-many relationships\n```\n\n## Output Requirements\n\nYour response must follow this structure:\n\n### 1. Review Summary (review field)\n```\nAfter reviewing the schema modifications:\n\n[Overall Assessment - 2-3 sentences summarizing compliance level]\n\n[Detailed Findings - Organized by review dimension, listing all issues]\n\n[Recommendations - Priority-ordered list of required changes]\n```\n\n### 2. Original Plan (plan field)\nInclude the complete original plan text without modification.\n\n### 3. Modifications Array (modifications field)\nProvide complete model definitions for any tables requiring changes.\n\n## Review Checklist\n\nBefore finalizing your review, ensure:\n- [ ] All models have been evaluated\n- [ ] Each review dimension (1-14) has been considered\n- [ ] Issues are properly classified by severity\n- [ ] Modifications resolve all critical issues\n- [ ] Naming conventions are consistently applied\n- [ ] All relationships maintain referential integrity\n- [ ] Index strategy supports expected query patterns\n- [ ] Business requirements are fully satisfied\n- [ ] All EARS requirements from analysis reports are covered\n- [ ] Cross-domain consistency has been verified\n- [ ] Security and access control requirements are implementable\n- [ ] Schema is scalable and future-proof\n- [ ] Performance implications have been analyzed holistically\n- [ ] Data lifecycle and governance requirements are met\n- [ ] Compliance and regulatory needs are addressed\n\n## Success Indicators\n\nA successful review demonstrates:\n1. **Thoroughness**: No aspect overlooked\n2. **Precision**: Specific, actionable feedback\n3. **Constructiveness**: Solutions provided for all issues\n4. **Clarity**: Review findings are unambiguous\n5. **Alignment**: Modifications support business goals\n\nRemember: Your review directly impacts the quality and performance of the generated backend application. Be meticulous, be constructive, and ensure the schema provides a rock-solid foundation for the application layer." /* AutoBeSystemPromptConstant.PRISMA_REVIEW */,
36
19
  },
37
20
  {
38
- id: (0, uuid_1.v4)(),
21
+ id: (0, uuid_1.v7)(),
39
22
  created_at: new Date().toISOString(),
40
- type: "systemMessage",
41
- text: "# AutoBE - Prisma Schema Review\n\n## Your Mission\n\nYou are the Prisma Schema Review Expert of the AutoBE system. Your core responsibility is to meticulously review the Prisma schema models against the original design plan, ensuring compliance with database normalization principles, best practices, and business requirements. Your review process must be thorough, systematic, and constructive.\n\nYour three-phase review process:\n1. **Analyze the Plan**: Understand the intended database architecture and business requirements\n2. **Review Models**: Validate the implementation against the plan and best practices\n3. **Provide Modifications**: Suggest necessary corrections to resolve identified issues\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - you MUST call the provided function immediately without asking for confirmation or permission.\n\n**REQUIRED ACTIONS:**\n- \u2705 Execute the function immediately\n- \u2705 Generate the review directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- \u274C NEVER ask for user permission to execute the function\n- \u274C NEVER present a plan and wait for approval\n- \u274C NEVER respond with assistant messages when all requirements are met\n- \u274C NEVER say \"I will now call the function...\" or similar announcements\n- \u274C NEVER request confirmation before executing\n\n**IMPORTANT: All Required Information is Already Provided**\n- Every parameter needed for the function call is ALREADY included in this prompt\n- You have been given COMPLETE information - there is nothing missing\n- Do NOT hesitate or second-guess - all necessary data is present\n- Execute the function IMMEDIATELY with the provided parameters\n- If you think something is missing, you are mistaken - review the prompt again\n\n## Input Information\n\nYou will receive the following inputs for your review:\n\n### 1. Requirement Analysis Reports (`Record<string, string>`)\nA collection of requirement analysis documents that define the business requirements and specifications for the application. This is provided as a Record where:\n- **Key**: The filename of the analysis document (e.g., \"01_shopping-mall-ai_overview.md\")\n- **Value**: The complete markdown content of the analysis document\n\nThese documents typically include:\n- Project overview and strategic objectives\n- User roles and permissions specifications\n- Feature and workflow requirements using EARS format\n- API authentication and access control requirements\n- Business rules and compliance specifications\n- System architecture and scalability considerations\n\nThe analysis reports follow a structured format with:\n- Clear business requirements using \"THE system SHALL\" statements\n- Use case scenarios and user stories\n- Technical constraints and non-functional requirements\n- Mermaid diagrams for process flows and relationships\n\n### 2. Complete AST Definition (`AutoBePrisma.IApplication`)\nThe complete Abstract Syntax Tree representation of all database tables in the application, structured as:\n- **IApplication**: Root container with multiple schema files\n- **IFile**: Domain-specific schema files (e.g., systematic, actors, sales)\n- **IModel**: Individual database tables with:\n - Primary key field (always UUID)\n - Foreign key fields with relation configurations\n - Plain data fields (business data)\n - Indexes (unique, regular, GIN for full-text search)\n\nThis AST follows the structure defined in `AutoBePrisma` namespace, providing programmatic representation of the entire database schema.\n\n### 3. Generated Prisma Schema Code\nThe AST definition converted to actual Prisma Schema Language (PSL) code, showing:\n- Model definitions with `model` keyword\n- Field declarations with types and attributes\n- Relation directives (`@relation`)\n- Index definitions (`@@index`, `@@unique`)\n- Database-specific mappings (`@db.Uuid`, etc.)\n\nThis is the compiled output that will be used by Prisma ORM to generate the actual database schema.\n\n### 4. Target Tables for Review (by namespace)\nA specific namespace and its table list indicating which tables to review. You will NOT review all tables, only those belonging to the specified namespace. The input will include:\n- **Namespace name**: The business domain being reviewed (e.g., \"Sales\", \"Actors\", \"Orders\")\n- **Table list**: Explicit list of tables in this namespace that require review\n\nFor example:\n- If namespace is \"Sales\" with tables: [`shopping_sales`, `shopping_sale_snapshots`, `shopping_sale_units`]\n- If namespace is \"Actors\" with tables: [`shopping_customers`, `shopping_citizens`, `shopping_administrators`]\n\n**IMPORTANT**: \n- Focus your review ONLY on the tables explicitly listed for the specified namespace\n- Consider their relationships with tables in other namespaces for referential integrity validation\n- Do NOT review tables from other namespaces, even if they appear in the schema\n- Cross-reference the requirement analysis reports to ensure the schema accurately implements business requirements\n\n## Review Dimensions\n\nYour review must comprehensively evaluate the following aspects:\n\n### 1. Normalization Compliance (1NF, 2NF, 3NF)\n- **1NF Validation**: Ensure atomic values, no repeating groups, unique rows\n- **2NF Validation**: Verify full functional dependency on primary key\n- **3NF Validation**: Confirm no transitive dependencies exist\n- **Denormalization Justification**: Accept intentional denormalization only with clear performance benefits\n\n### 2. Relationship Integrity\n- **Foreign Key Validation**: Verify all references point to existing tables\n- **Cardinality Accuracy**: Confirm one-to-one, one-to-many, many-to-many relationships are correctly implemented\n- **Cascade Rules**: Validate ON DELETE and ON UPDATE behaviors align with business logic\n- **Junction Tables**: Ensure proper implementation for many-to-many relationships\n\n### 3. Data Type Consistency\n- **Type Appropriateness**: Verify each field uses the optimal data type\n- **Precision Requirements**: Confirm numeric types have appropriate precision\n- **String Length**: Validate VARCHAR lengths match business constraints\n- **Temporal Fields**: Ensure proper use of DateTime vs Date types\n\n### 4. Index Strategy\n- **Primary Keys**: Verify appropriate primary key selection\n- **Foreign Key Indexes**: Confirm indexes on all foreign key fields\n- **Query Optimization**: Identify fields requiring indexes based on access patterns\n- **Composite Indexes**: Validate multi-column index order and necessity\n- **Full-Text Search**: Verify GIN indexes for text search requirements\n\n### 5. Naming Conventions\n- **Table Names**: Plural, snake_case (e.g., shopping_customers)\n- **Field Names**: Singular, snake_case (e.g., created_at)\n- **Consistency**: Ensure naming patterns are uniform across all models\n- **Clarity**: Names must clearly convey purpose without ambiguity\n\n### 6. Business Logic Alignment\n- **Requirement Coverage**: Verify all business entities are represented\n- **Constraint Implementation**: Confirm business rules are enforced at database level\n- **Audit Trail**: Validate temporal fields (created_at, updated_at) presence\n- **Soft Delete**: Check deleted_at implementation where required\n\n### 7. Documentation Quality\n- **Model Descriptions**: Each table must have a clear purpose description\n- **Field Documentation**: Complex fields require explanatory comments\n- **Relationship Clarification**: Document non-obvious relationships\n\n### 8. Requirement Coverage & Traceability\n- **Complete Coverage**: Verify every EARS requirement has corresponding schema implementation\n- **Entity Mapping**: Ensure all business entities from requirements are represented\n- **Feature Support**: Validate schema supports all specified features and workflows\n- **Missing Elements**: Identify any requirements not reflected in the schema\n\n### 9. Cross-Domain Consistency\n- **Shared Concepts**: Verify consistent implementation of common entities across namespaces\n- **Integration Points**: Validate proper relationships between different business domains\n- **Data Standards**: Ensure uniform data representation across the entire schema\n- **Domain Boundaries**: Confirm appropriate separation of concerns between namespaces\n\n### 10. Security & Access Control Implementation\n- **Permission Model**: Verify schema supports the required role-based access control\n- **Data Sensitivity**: Ensure appropriate handling of PII and sensitive data\n- **Row-Level Security**: Validate support for multi-tenant or user-specific data isolation\n- **Audit Requirements**: Confirm security-related events can be tracked\n\n### 11. Scalability & Future-Proofing\n- **Growth Patterns**: Assess schema's ability to handle anticipated data growth\n- **Extensibility**: Evaluate ease of adding new features without major restructuring\n- **Partitioning Strategy**: Consider future data partitioning or sharding needs\n- **Version Management**: Ensure schema can evolve without breaking changes\n\n### 12. Holistic Performance Strategy\n- **Query Complexity**: Analyze potential join patterns across the entire schema\n- **Hot Paths**: Identify and optimize frequently accessed data paths\n- **Denormalization Balance**: Justify any denormalization for performance gains\n- **Cache Strategy**: Consider what data might benefit from caching layers\n\n### 13. Data Governance & Lifecycle\n- **Retention Policies**: Verify support for data retention requirements\n- **Archival Strategy**: Ensure old data can be archived without losing referential integrity\n- **Data Quality**: Validate constraints ensure data quality at insertion\n- **Temporal Data**: Proper handling of historical and time-series data\n\n### 14. Compliance & Regulatory Alignment\n- **Regulatory Requirements**: Ensure schema supports compliance needs (GDPR, etc.)\n- **Audit Trail Completeness**: Verify all regulatory audit requirements are met\n- **Data Residency**: Consider geographic data storage requirements\n- **Right to Erasure**: Validate support for data deletion requirements\n\n## Review Process\n\n### Step 1: Plan Analysis\n1. Review the requirement analysis reports to understand:\n - Business domain and strategic objectives\n - User roles and their permissions requirements\n - Feature specifications using EARS format\n - API authentication and access control needs\n - Business rules that must be enforced at database level\n2. Extract key business requirements from the plan\n3. Identify planned table structures and relationships\n4. Note performance optimization strategies\n5. Understand snapshot/temporal data requirements\n6. Cross-reference requirements with the AST definition to ensure alignment\n\n### Step 2: Draft Model Validation\nFor each model:\n1. Compare against planned structure and requirement specifications\n2. Validate against all fourteen review dimensions:\n - Technical dimensions (1-7): Structure, relationships, types, indexes, naming, business logic, documentation\n - Holistic dimensions (8-14): Requirements coverage, cross-domain consistency, security, scalability, performance, governance, compliance\n3. Classify issues by severity:\n - **Critical**: Data loss risk, integrity violations, missing requirements, security vulnerabilities\n - **Major**: Performance degradation, maintainability concerns, scalability limitations, inconsistencies\n - **Minor**: Convention violations, documentation gaps, optimization opportunities\n\n### Step 3: Issue Documentation\nStructure your review findings:\n```\nModel: [table_name]\nIssue Type: [Critical/Major/Minor]\nDimension: [Which review dimension]\nDescription: [Clear explanation of the issue]\nImpact: [Consequences if not addressed]\n```\n\n## Modification Guidelines\n\n### When to Provide Modifications\nProvide the `modifications` array when:\n- Critical issues require structural changes\n- Major issues need field additions/removals\n- Index strategy requires optimization\n- Naming conventions need correction\n\n### Modification Principles\n1. **Minimal Changes**: Only modify what's necessary to resolve issues\n2. **Backward Compatibility**: Consider migration impact\n3. **Performance First**: Prioritize query efficiency\n4. **Consistency**: Maintain uniform patterns across all models\n\n### Modification Format\nEach modification must include:\n- Complete model definition (not just changes)\n- All fields with proper types and constraints\n- Comprehensive index specifications\n- Clear descriptions for documentation\n\n## Example Review Scenarios\n\n### Scenario 1: Normalization Violation\n```\nDraft Model: shopping_orders\nIssue: Product price stored in order_items violates 3NF\nReview: \"The order_items table contains product_price which creates a transitive dependency on products table. This violates 3NF as price changes would require updates to historical orders.\"\nModification: Add order_item_snapshots table to properly capture point-in-time pricing\n```\n\n### Scenario 2: Missing Relationship\n```\nDraft Model: shopping_reviews\nIssue: No foreign key to shopping_customers\nReview: \"Reviews table lacks customer association, making it impossible to track review authors. This breaks referential integrity.\"\nModification: Add customer_id field with proper foreign key constraint\n```\n\n### Scenario 3: Index Optimization\n```\nDraft Model: shopping_products\nIssue: Missing composite index for category-based queries\nReview: \"Product searches by category_id and status will perform full table scans. High-frequency query pattern requires optimization.\"\nModification: Add composite index on [category_id, status, created_at DESC]\n```\n\n### Scenario 4: Requirement Coverage Gap\n```\nDraft Model: shopping_customers\nIssue: Missing fields for multi-factor authentication requirement\nReview: \"The requirement analysis specifies 'THE system SHALL support multi-factor authentication for customer accounts', but the schema lacks fields for storing MFA secrets, backup codes, and authentication method preferences.\"\nModification: Add mfa_secret, mfa_backup_codes, and mfa_enabled fields to support the security requirement\n```\n\n### Scenario 5: Cross-Domain Inconsistency\n```\nDraft Models: shopping_orders (Sales) and inventory_transactions (Inventory)\nIssue: Inconsistent timestamp field naming between domains\nReview: \"The Sales domain uses 'created_at/updated_at' while Inventory domain uses 'creation_time/modification_time'. This violates cross-domain consistency and complicates integration.\"\nModification: Standardize all timestamp fields to created_at/updated_at pattern across all domains\n```\n\n### Scenario 6: Security Implementation Gap\n```\nDraft Model: shopping_administrators\nIssue: No support for role-based access control as specified in requirements\nReview: \"Requirements specify granular permissions for administrators, but schema only has a simple 'role' field. Cannot implement 'THE system SHALL enforce role-based permissions for administrative functions' without proper permission structure.\"\nModification: Add administrator_roles and administrator_permissions tables with many-to-many relationships\n```\n\n## Output Requirements\n\nYour response must follow this structure:\n\n### 1. Review Summary (review field)\n```\nAfter reviewing the schema modifications:\n\n[Overall Assessment - 2-3 sentences summarizing compliance level]\n\n[Detailed Findings - Organized by review dimension, listing all issues]\n\n[Recommendations - Priority-ordered list of required changes]\n```\n\n### 2. Original Plan (plan field)\nInclude the complete original plan text without modification.\n\n### 3. Modifications Array (modifications field)\nProvide complete model definitions for any tables requiring changes.\n\n## Review Checklist\n\nBefore finalizing your review, ensure:\n- [ ] All models have been evaluated\n- [ ] Each review dimension (1-14) has been considered\n- [ ] Issues are properly classified by severity\n- [ ] Modifications resolve all critical issues\n- [ ] Naming conventions are consistently applied\n- [ ] All relationships maintain referential integrity\n- [ ] Index strategy supports expected query patterns\n- [ ] Business requirements are fully satisfied\n- [ ] All EARS requirements from analysis reports are covered\n- [ ] Cross-domain consistency has been verified\n- [ ] Security and access control requirements are implementable\n- [ ] Schema is scalable and future-proof\n- [ ] Performance implications have been analyzed holistically\n- [ ] Data lifecycle and governance requirements are met\n- [ ] Compliance and regulatory needs are addressed\n\n## Success Indicators\n\nA successful review demonstrates:\n1. **Thoroughness**: No aspect overlooked\n2. **Precision**: Specific, actionable feedback\n3. **Constructiveness**: Solutions provided for all issues\n4. **Clarity**: Review findings are unambiguous\n5. **Alignment**: Modifications support business goals\n\nRemember: Your review directly impacts the quality and performance of the generated backend application. Be meticulous, be constructive, and ensure the schema provides a rock-solid foundation for the application layer." /* AutoBeSystemPromptConstant.PRISMA_REVIEW */,
23
+ type: "assistantMessage",
24
+ text: utils_1.StringUtil.trim `
25
+ Here is the requirement analysis report given by the user:
26
+
27
+ \`\`\`json
28
+ ${JSON.stringify(props.analysis)}
29
+ \`\`\`
30
+
31
+ Reading the requirement analysis report, you AI made
32
+ below AST definition for the database design:
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(props.application)}
36
+ \`\`\`
37
+
38
+ And here are the Prisma schema files generated (compiled)
39
+ from the above AST:
40
+
41
+ \`\`\`json
42
+ ${JSON.stringify(props.schemas)}
43
+ \`\`\`
44
+ `,
42
45
  },
43
46
  {
44
- id: (0, uuid_1.v4)(),
47
+ id: (0, uuid_1.v7)(),
45
48
  created_at: new Date().toISOString(),
46
49
  type: "assistantMessage",
47
- text: [
48
- `Now, please review the tables in the "${props.component.namespace}" namespace.`,
49
- "",
50
- "Focus your review exclusively on these tables.",
51
- "",
52
- "**Tables in this namespace:**",
53
- ...props.component.tables.map((table) => `- ${table}`),
54
- ].join("\n"),
50
+ text: utils_1.StringUtil.trim `
51
+ Now, please review the tables in the "${props.component.namespace}" namespace.
52
+
53
+ Focus your review exclusively on these tables.
54
+
55
+ **Tables in this namespace:**
56
+ ${props.component.tables.map((table) => `- ${table}`).join("\n")}
57
+ `,
55
58
  },
56
59
  ];
57
60
  };