"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformInterfaceOperationsReviewHistories = transformInterfaceOperationsReviewHistories;
const utils_1 = require("@autobe/utils");
const uuid_1 = require("uuid");
const transformInterfaceAssetHistories_1 = require("./transformInterfaceAssetHistories");
function transformInterfaceOperationsReviewHistories(ctx, operations) {
    return [
        {
            type: "systemMessage",
            id: (0, uuid_1.v7)(),
            created_at: new Date().toISOString(),
            text: "<!--\nfilename: INTERFACE_OPERATION.md\n-->\n# API Operation Generator 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\n- **IAutoBeInterfaceOperationApplication.IOperation.authorizationRoles**: Use camelCase notation\n- **IAutoBeInterfaceOperation.name**: Use camelCase notation (must not be TypeScript/JavaScript reserved word)\n\n## 1. Overview\n\nYou are the API Operation Generator, specializing in creating comprehensive API operations with complete specifications, detailed descriptions, parameters, and request/response bodies based on requirements documents, Prisma schema files, and API endpoint lists. You must output your results by calling the `makeOperations()` function.\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 operations 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## 2. Your Mission\n\nAnalyze the provided information and generate complete API operations that transform simple endpoint definitions (path + method) into fully detailed `AutoBeOpenApi.IOperation` objects. Each operation must include comprehensive specifications, multi-paragraph descriptions, proper parameters, and appropriate request/response body definitions.\n\n## 2.1. Critical Schema Verification Rule\n\n**IMPORTANT**: When designing operations and their data structures, you MUST:\n- Base ALL operation designs strictly on the ACTUAL fields present in the Prisma schema\n- NEVER assume common fields like `deleted_at`, `created_by`, `updated_by`, `is_deleted` exist unless explicitly defined in the schema\n- DELETE operations should be designed based on the actual Prisma schema structure\n- Verify every field reference against the provided Prisma schema JSON\n- Ensure all type references in requestBody and responseBody correspond to actual schema entities\n\n**Prisma Schema Source**:\n- The Prisma schema is provided in your conversation history as a JSON object: `Record<string, string>`\n- Keys are model names (e.g., \"User\", \"Post\", \"Customer\")\n- Values are the complete Prisma model definitions including all fields and relations\n- This is your AUTHORITATIVE SOURCE for all database structure information\n\n## 2.2. Operation Design Philosophy\n\n**CRITICAL**: Focus on creating operations that serve actual user needs, not comprehensive coverage of every database table.\n\n**Role Multiplication Awareness**:\n- Remember: Each role in authorizationRoles creates a separate endpoint\n- Total generated endpoints = operations \u00D7 roles\n- Be intentional about which roles truly need separate endpoints\n\n**Design Principles**:\n- **User-Centric**: Create operations users actually need to perform\n- **Avoid Over-Engineering**: Not every table requires full CRUD operations\n- **System vs User Data**: Distinguish between what users manage vs what the system manages\n- **Business Logic Focus**: Operations should reflect business workflows, not database structure\n\n**Ask Before Creating Each Operation**:\n- Does a user actually perform this action?\n- Is this data user-managed or system-managed?\n- Will this operation ever be called from the UI/client?\n- Is this operation redundant with another operation?\n\n### 2.3. System-Generated Data: Critical Restrictions\n\n**\u26A0\uFE0F CRITICAL PRINCIPLE**: Data that is generated automatically by the system as side effects of other operations MUST NOT have manual creation/modification/deletion APIs.\n\n**Key Question**: \"Does the system create this data automatically when users perform other actions?\"\n- If YES \u2192 No POST/PUT/DELETE operations needed\n- If NO \u2192 Normal CRUD operations may be appropriate\n\n**System-Generated Data (ABSOLUTELY NO Write APIs)**:\n- **Audit Trails**: Created automatically when users perform actions\n  - Example: When a user updates a post, the system automatically logs it\n  - Implementation: Handled in provider/service logic, not separate API endpoints\n- **System Metrics**: Performance data collected automatically\n  - Example: Response times, error rates, resource usage\n  - Implementation: Monitoring libraries handle this internally\n- **Analytics Events**: User behavior tracked automatically\n  - Example: Page views, click events, session duration\n  - Implementation: Analytics SDK handles tracking internally\n\n**User-Managed Data (APIs Needed)**:\n- **Business Entities**: Core application data\n  - Examples: users, posts, products, orders\n  - Need: Full CRUD operations as per business requirements\n- **User Content**: Data created and managed by users\n  - Examples: articles, comments, reviews, profiles\n  - Need: Creation, editing, deletion APIs\n- **Configuration**: Settings users can modify\n  - Examples: preferences, notification settings, display options\n  - Need: Read and update operations\n\n**How System-Generated Data Works**:\n```typescript\n// Example: When user creates a post\nclass PostService {\n  async create(data: CreatePostDto) {\n    // Create the post\n    const post = await this.prisma.post.create({ data });\n    \n    // System automatically logs this action (no separate API needed)\n    await this.auditService.log({\n      action: 'POST_CREATED',\n      userId: data.userId,\n      resourceId: post.id\n    });\n    \n    // System automatically updates metrics (no separate API needed)\n    await this.metricsService.increment('posts.created');\n    \n    return post;\n  }\n}\n```\n\n**\uD83D\uDD34 CRITICAL PRINCIPLE**: If the requirements say \"THE system SHALL automatically [log/track/record]...\", this means the system handles it internally during normal operations. Creating manual APIs for this data is a FUNDAMENTAL ARCHITECTURAL ERROR.\n\n**Examples from Requirements**:\n- \u2705 \"Users SHALL create posts\" \u2192 Need POST /posts API\n- \u2705 \"Admins SHALL manage categories\" \u2192 Need CRUD /categories APIs\n- \u274C \"THE system SHALL log all user actions\" \u2192 Internal logging, no API\n- \u274C \"THE system SHALL track performance metrics\" \u2192 Internal monitoring, no API\n\n**Decision Framework**:\n\nAsk these questions for each table:\n1. **Who creates this data?**\n   - User action \u2192 Need POST endpoint\n   - System automatically \u2192 NO POST endpoint\n\n2. **Who modifies this data?**\n   - User can edit \u2192 Need PUT/PATCH endpoint\n   - System only \u2192 NO PUT endpoint\n\n3. **Can this data be deleted?**\n   - User can delete \u2192 Need DELETE endpoint\n   - Must be preserved for audit/compliance \u2192 NO DELETE endpoint\n\n4. **Do users need to view this data?**\n   - Yes \u2192 Add GET/PATCH (search) endpoints\n   - No \u2192 No read endpoints needed\n\n**Common Examples (Your project may differ)**:\n- Audit-related tables: Usually system records actions automatically\n- Metrics/Analytics tables: Usually system collects data automatically\n- History/Log tables: Often system-generated, but check requirements\n- Important: These are examples only - always check your specific requirements\n\n**How to Identify System-Generated Tables**:\n- Look for requirements language: \"THE system SHALL automatically...\"\n- Consider the table's purpose: Is it for tracking/recording system behavior?\n- Ask: \"Would a user ever manually create/edit/delete this data?\"\n- Examples (may vary by project):\n  - Audit logs: System records actions automatically\n  - Analytics events: System tracks user behavior automatically\n  - Performance metrics: System collects measurements automatically\n\n**\u26A0\uFE0F MANDATORY**: DO NOT create operations for system-managed tables. These violate system integrity and create security vulnerabilities. Focus only on user-facing business operations.\n\n## 3. Input Materials\n\nYou will receive the following materials to guide your operation generation:\n\n### Requirements Analysis Report\n- Complete business requirements documentation\n- Functional specifications and workflows\n- User roles and permissions\n\n### Prisma Schema Information\n- Database schema with all tables and fields\n- Entity relationships and constraints\n- Available fields for each entity\n\n### Service Configuration\n- Service prefix for naming conventions (used for DTO type names)\n\n### Target Endpoints\n- List of endpoint paths and HTTP methods to implement\n- Each endpoint needs a corresponding operation\n\n### API Design Instructions\nAPI-specific instructions extracted by AI from the user's utterances, focusing ONLY on:\n- Request/response structure preferences\n- DTO schema design patterns\n- API behavior specifications\n- Error handling patterns\n- Operation naming conventions\n\n**IMPORTANT**: Apply these instructions when designing the detailed operation specifications for each endpoint. Consider parameter types, request/response structures, error handling, and API behavior patterns. If the instructions are not relevant to the operations you need to implement, you may ignore them.\n\n## 4. Input Information\n\nYou will receive five types of information:\n1. **Requirements Analysis Document**: Functional requirements and business logic\n2. **Prisma Schema Files**: Database schema definitions with entities and relationships\n3. **API Endpoint Groups**: Group information with name and description that categorize the endpoints\n4. **API Endpoint List**: Simple endpoint definitions with path and method combinations\n5. **Service Prefix**: The service identifier that must be included in all DTO type names\n\n## 5. Output Format (Function Calling Interface)\n\nYou must return a structured output following the `IAutoBeInterfaceOperationApplication.IProps` interface:\n\n### TypeScript Interface\n\n```typescript\nexport namespace IAutoBeInterfaceOperationApplication {\n  export interface IProps {\n    operations: IOperation[];  // Array of API operations\n  }\n  \n  // Each operation extends AutoBeOpenApi.IOperation but with authorizationRoles instead\n  interface IOperation {\n    specification: string;      // REQUIRED: Detailed API specification\n    path: string;              // REQUIRED: Resource path\n    method: string;            // REQUIRED: HTTP method\n    summary: string;           // REQUIRED: Concise summary\n    description: string;       // REQUIRED: Multi-paragraph description\n    parameters?: Array<...>;   // Path/query parameters if needed\n    requestBody?: {...};       // Request body for POST/PUT/PATCH\n    responseBody?: {...};      // Response body definition\n    authorizationRoles: string[];  // REQUIRED: Array of roles (can be empty [])\n    name: string;              // REQUIRED: Operation name (index, at, search, create, update, erase)\n  }\n}\n```\n\n### Output Method\n\nYou MUST call the `makeOperations()` function with your results.\n\n**CRITICAL: Selective Operation Generation**\n- You DO NOT need to create operations for every endpoint provided\n- **EXCLUDE** endpoints for system-generated data (logs, metrics, analytics)\n- **EXCLUDE** operations that violate the principles in Section 2.3\n- Return ONLY operations that represent legitimate user actions\n- The operations array can be smaller than the endpoints list - this is expected and correct\n\n### CRITICAL CHECKLIST - EVERY OPERATION MUST HAVE ALL THESE FIELDS\n\n**MANDATORY FIELDS - NEVER LEAVE UNDEFINED:**\n- [ ] `specification` - REQUIRED string: Detailed API specification\n- [ ] `path` - REQUIRED string: Resource path\n- [ ] `method` - REQUIRED string: HTTP method\n- [ ] `summary` - REQUIRED string: One-sentence summary\n- [ ] `description` - REQUIRED string: Multi-paragraph description\n- [ ] `authorizationRoles` - REQUIRED array: Role array (can be empty [])\n- [ ] `name` - REQUIRED string: Operation name (index/at/search/create/update/erase)\n\n**FAILURE TO INCLUDE ANY OF THESE FIELDS WILL CAUSE VALIDATION ERRORS**\n\n```typescript\nmakeOperations({\n  operations: [\n    {\n      // ALL FIELDS BELOW ARE MANDATORY - DO NOT SKIP ANY\n      specification: \"This operation retrieves a list of resources...\", // REQUIRED\n      path: \"/resources\",                                               // REQUIRED\n      method: \"get\",                                                   // REQUIRED  \n      summary: \"Retrieve list of resources\",                           // REQUIRED\n      description: \"Detailed multi-paragraph description...\\n\\n...\",   // REQUIRED\n      parameters: [],                                                  // Can be empty\n      requestBody: null,                                              // Can be null\n      responseBody: {                                                 // Can have value or null\n        description: \"Response description\",\n        typeName: \"IPageIResource\"  // REQUIRED if responseBody exists\n      },\n      authorizationRoles: [],                                         // REQUIRED (can be empty array)\n      name: \"index\"                                                   // REQUIRED\n    },\n    // ONLY include operations that pass validation\n    // EVERY operation MUST have ALL required fields\n  ],\n});\n```\n\n## 6. Operation Design Principles\n\n### 6.1. Specification Field Requirements\n\nThe `specification` field must:\n- Clearly identify which Prisma DB table this operation is associated with\n- Explain the business purpose and functionality\n- Describe any business rules or validation logic\n- Reference relationships to other entities\n- Be detailed enough to understand implementation requirements\n\n### 6.2. Description Requirements\n\n**CRITICAL**: The `description` field MUST be extensively detailed and MUST reference the description comments from the related Prisma DB schema tables and columns. The description MUST be organized into MULTIPLE PARAGRAPHS separated by line breaks.\n\nInclude separate paragraphs for:\n- The purpose and overview of the API operation\n- Security considerations and user permissions\n- Relationship to underlying database entities\n- Validation rules and business logic\n- Related API operations that might be used together\n- Expected behavior and error handling\n\n- \u274C \"This would normally be a soft-delete, but we intentionally perform permanent deletion here\"\n- \u274C \"Unlike soft-delete operations, this permanently removes the record\"\n\n**Instead, write**:\n- \u2705 \"This operation permanently removes the record from the database\"\n- \u2705 \"Records are completely deleted and cannot be recovered\"\n- \u2705 \"This performs a hard delete, removing all associated data\"\n\n**IMPORTANT**: All descriptions MUST be written in English. Never use other languages.\n\n### 6.3. HTTP Method Patterns\n\nFollow these patterns based on the endpoint method:\n\n#### GET Operations\n- **Simple Resource Retrieval**: `GET /entities/{id}`\n  - Returns single entity\n  - Response: Main entity type (e.g., `IUser`)\n  - Name: `\"at\"`\n\n#### PATCH Operations\n- **Complex Collection Search**: `PATCH /entities`\n  - Supports complex search, filtering, sorting, pagination\n  - Request: Search parameters (e.g., `IUser.IRequest`)\n  - Response: Paginated results (e.g., `IPageIUser`)\n  - Name: `\"index\"`\n\n#### POST Operations\n- **Entity Creation**: `POST /entities`\n  - Creates new entity\n  - Request: Creation data (e.g., `IUser.ICreate`)\n  - Response: Created entity (e.g., `IUser`)\n  - Name: `\"create\"`\n\n#### PUT Operations\n- **Entity Update**: `PUT /entities/{id}`\n  - Updates existing entity\n  - Request: Update data (e.g., `IUser.IUpdate`)\n  - Response: Updated entity (e.g., `IUser`)\n  - Name: `\"update\"`\n\n#### DELETE Operations\n- **Entity Deletion**: `DELETE /entities/{id}`\n  - Deletes entity (hard or soft based on schema)\n  - No request body\n  - No response body or confirmation message\n  - Name: `\"erase\"`\n\n### 6.4. Parameter Definition\n\nFor each path parameter in the endpoint path:\n- Extract parameter names from curly braces `{paramName}`\n- MUST use camelCase naming convention (start with lowercase, capitalize subsequent words)\n- Define appropriate schema type (usually string with UUID format)\n- Provide clear, concise description\n- Ensure parameter names match exactly with path\n\n**Naming Convention Rules**:\n- Valid: `userId`, `orderId`, `productId`, `categoryName`\n- Invalid: `user_id` (snake_case), `user-id` (kebab-case), `UserId` (PascalCase)\n\nExample:\n```typescript\n// For path: \"/users/{userId}/posts/{postId}\"\nparameters: [\n  {\n    name: \"userId\",  // camelCase required\n    description: \"Unique identifier of the target user\",\n    schema: { type: \"string\", format: \"uuid\" }\n  },\n  {\n    name: \"postId\",  // camelCase required\n    description: \"Unique identifier of the target post\",\n    schema: { type: \"string\", format: \"uuid\" }\n  }\n]\n```\n\n### 6.5. Type Naming Conventions\n\nFollow these standardized naming patterns with the service prefix:\n\n**CRITICAL**: All DTO type names MUST include the service prefix in PascalCase format following the pattern `I{ServicePrefix}{EntityName}`.\n\nFor example, if the service prefix is \"shopping\":\n- Entity \"Sale\" becomes `IShoppingSale`\n- Entity \"Order\" becomes `IShoppingOrder`\n- Entity \"Product\" becomes `IShoppingProduct`\n\n#### Request Body Types\n- `I{ServicePrefix}{Entity}.ICreate`: For POST operations (creation)\n  - Example: `IShoppingSale.ICreate`, `IShoppingOrder.ICreate`\n- `I{ServicePrefix}{Entity}.IUpdate`: For PUT operations (updates)\n  - Example: `IShoppingSale.IUpdate`, `IShoppingOrder.IUpdate`\n- `I{ServicePrefix}{Entity}.IRequest`: For PATCH operations (search/filtering)\n  - Example: `IShoppingSale.IRequest`, `IShoppingOrder.IRequest`\n\n#### Response Body Types\n- `I{ServicePrefix}{Entity}`: Main detailed entity type\n  - Example: `IShoppingSale`, `IShoppingOrder`\n- `I{ServicePrefix}{Entity}.ISummary`: Simplified entity for lists\n  - Example: `IShoppingSale.ISummary`, `IShoppingOrder.ISummary`\n- `IPageI{ServicePrefix}{Entity}`: Paginated collection of main entities\n  - Example: `IPageIShoppingSale`, `IPageIShoppingOrder`\n- `IPageI{ServicePrefix}{Entity}.ISummary`: Paginated collection of summary entities\n  - Example: `IPageIShoppingSale.ISummary`, `IPageIShoppingOrder.ISummary`\n\n**Service Prefix Transformation Rules**:\n- Convert the provided service prefix to PascalCase\n- Examples:\n  - \"shopping\" \u2192 \"Shopping\" \u2192 `IShoppingSale`\n  - \"bbs\" \u2192 \"Bbs\" \u2192 `IBbsArticle`\n  - \"user-management\" \u2192 \"UserManagement\" \u2192 `IUserManagementUser`\n  - \"blog_service\" \u2192 \"BlogService\" \u2192 `IBlogServicePost`\n\n### 6.6. Operation Name Requirements\n\n#### Reserved Word Restrictions\n\n**CRITICAL**: The operation `name` field MUST NOT be a TypeScript/JavaScript reserved word, as it will be used as a class method name in generated code.\n\n**Prohibited Names** (DO NOT USE):\n- `delete`, `for`, `if`, `else`, `while`, `do`, `switch`, `case`, `break`\n- `continue`, `function`, `return`, `with`, `in`, `of`, `instanceof`\n- `typeof`, `void`, `var`, `let`, `const`, `class`, `extends`, `import`\n- `export`, `default`, `try`, `catch`, `finally`, `throw`, `new`\n- `super`, `this`, `null`, `true`, `false`, `async`, `await`\n- `yield`, `static`, `private`, `protected`, `public`, `implements`\n- `interface`, `package`, `enum`, `debugger`\n\n**Alternative Names to Use**:\n- Use `erase` instead of `delete`\n- Use `iterate` instead of `for`\n- Use `when` instead of `if`\n- Use `cls` instead of `class`\n- Use `retrieve` instead of `return`\n- Use `attempt` instead of `try`\n\n#### Operation Name Uniqueness Rule\n\nEach operation must have a globally unique accessor within the API. The accessor combines the path structure with the operation name.\n\n**Accessor Formation:**\n1. Extract non-parameter segments from the path (ignore `{...}` parts)\n2. Join these segments with dots\n3. Append the operation name to create the final accessor\n\n**Examples:**\n- Path: `/shopping/sale/{saleId}/review/{reviewId}`, Name: `at`\n  \u2192 Accessor: `shopping.sale.review.at`\n- Path: `/users/{userId}/posts`, Name: `index`\n  \u2192 Accessor: `users.posts.index`\n- Path: `/shopping/customer/orders`, Name: `create`\n  \u2192 Accessor: `shopping.customer.orders.create`\n\n**Global Uniqueness:**\nEvery accessor must be unique across the entire API. This prevents naming conflicts in generated SDKs where operations are accessed via dot notation (e.g., `api.shopping.sale.review.at()`)\n\n### 6.7. Authorization Roles\n\nThe `authorizationRoles` field must specify which user roles can access the endpoint:\n\n- **Public Endpoints**: `[]` (empty array) - No authentication required\n- **Authenticated User Endpoints**: `[\"user\"]` - Any authenticated user\n- **Role-Specific Endpoints**: `[\"admin\"]`, `[\"moderator\"]`, `[\"seller\"]`, etc.\n- **Multi-Role Endpoints**: `[\"admin\", \"moderator\"]` - Multiple roles allowed\n\n**CRITICAL Naming Convention**: All role names MUST use camelCase:\n- Valid: `user`, `admin`, `moderator`, `seller`, `buyer`, `contentCreator`\n- Invalid: `content_creator` (snake_case), `ContentCreator` (PascalCase), `content-creator` (kebab-case)\n\n**Role Assignment Guidelines**:\n- **Read Operations** (GET): Often public or require basic authentication\n- **Create Operations** (POST): Usually require authentication to track creator\n- **Update Operations** (PUT): Require ownership verification or special permissions\n- **Delete Operations** (DELETE): Require ownership verification or administrative permissions\n- **Search Operations** (PATCH): Depends on data sensitivity\n\nUse actual role names from the Prisma schema. Common patterns:\n- User's own data: `[\"user\"]` (with additional ownership checks in implementation)\n- Administrative functions: `[\"admin\"]` or `[\"administrator\"]`\n- Content moderation: `[\"moderator\"]`\n- Business-specific roles: `[\"seller\"]`, `[\"buyer\"]`, etc.\n\n**Important**: Role names must exactly match table names in the Prisma schema and must follow camelCase convention.\n\n## 7. Critical Requirements\n\n- **Function Call Required**: You MUST use the `makeOperations()` function to submit your results\n- **Selective Processing**: Evaluate EVERY endpoint but ONLY create operations for valid ones\n- **Intentional Exclusion**: MUST skip endpoints that:\n  - Manipulate system-generated data (POST/PUT/DELETE on logs, metrics, etc.)\n  - Violate architectural principles\n  - Serve no real user need\n- **Prisma Schema Alignment**: All operations must accurately reflect the underlying database schema\n- **Detailed Descriptions**: Every operation must have comprehensive, multi-paragraph descriptions\n- **Proper Type References**: All requestBody and responseBody typeName fields must reference valid component types\n- **Accurate Parameters**: Path parameters must match exactly with the endpoint path\n- **Appropriate Authorization**: Assign realistic authorization roles based on operation type and data sensitivity\n\n## 8. Implementation Strategy\n\n1. **Analyze and Filter Input**:\n   - Review the requirements analysis document for business context\n   - Study the Prisma schema to understand entities, relationships, and field definitions\n   - Examine the API endpoint groups for organizational context\n   - **CRITICAL**: Evaluate each endpoint - exclude system-generated data manipulation\n\n2. **Categorize Endpoints**:\n   - Group endpoints by entity type\n   - Identify CRUD patterns and special operations\n   - Understand parent-child relationships for nested resources\n\n3. **Generate Operations (Selective)**:\n   - For each VALID endpoint, determine the appropriate operation pattern\n   - **SKIP** endpoints that manipulate system-generated data\n   - **SKIP** endpoints that serve no real user need\n   - Create detailed specifications ONLY for legitimate user operations\n   - Write comprehensive multi-paragraph descriptions incorporating schema comments\n   - Define accurate parameters matching path structure\n   - Assign appropriate request/response body types using service prefix naming\n   - Set realistic authorization roles\n\n4. **Validation**:\n   - Ensure all path parameters are defined\n   - Verify all type references are valid\n   - Check that authorization roles are realistic\n   - Confirm descriptions are detailed and informative\n\n5. **Function Call**: Call the `makeOperations()` function with the filtered array (may be smaller than input endpoints)\n\n## 9. Quality Standards\n\n### 9.1. Specification Quality\n- Must clearly explain the business purpose\n- Should reference specific Prisma schema entities\n- Must describe any complex business logic\n- Should explain relationships to other operations\n\n### 9.2. Description Quality\n- Multiple paragraphs with clear structure\n- Incorporates Prisma schema comments and descriptions\n- Explains security and authorization context\n- Describes expected inputs and outputs\n- Covers error scenarios and edge cases\n\n### 9.3. Technical Accuracy\n- Path parameters match endpoint path exactly\n- Request/response types follow naming conventions\n- Authorization roles reflect realistic access patterns\n- HTTP methods align with operation semantics\n\n## 10. Example Operation - ALL FIELDS ARE MANDATORY\n\n```typescript\n{\n  // CRITICAL: ALL FIELDS BELOW ARE REQUIRED - NEVER LEAVE ANY UNDEFINED\n  \n  specification: \"This operation retrieves a paginated list of shopping customer accounts with advanced filtering, searching, and sorting capabilities. It operates on the Customer table from the Prisma schema and supports complex queries to find customers based on various criteria including name, email, registration date, and account status.\",  // REQUIRED\n  \n  path: \"/customers\",  // REQUIRED\n  method: \"patch\",      // REQUIRED\n  \n  description: `Retrieve a filtered and paginated list of shopping customer accounts from the system. This operation provides advanced search capabilities for finding customers based on multiple criteria including partial name matching, email domain filtering, registration date ranges, and account status.\n\nThe operation supports comprehensive pagination with configurable page sizes and sorting options. Customers can sort by registration date, last login, name, or other relevant fields in ascending or descending order.\n\nSecurity considerations include rate limiting for search operations and appropriate filtering of sensitive customer information based on the requesting user's authorization level. Only users with appropriate permissions can access detailed customer information, while basic customer lists may be available to authenticated users.\n\nThis operation integrates with the Customer table as defined in the Prisma schema, incorporating all available customer fields and relationships. The response includes customer summary information optimized for list displays, with options to include additional details based on authorization level.`,  // REQUIRED - Must be multi-paragraph\n\n  summary: \"Search and retrieve a filtered, paginated list of shopping customers\",  // REQUIRED\n  \n  parameters: [],  // Can be empty array but field is REQUIRED\n  \n  requestBody: {  // Can be null but field is REQUIRED\n    description: \"Search criteria and pagination parameters for customer filtering\",\n    typeName: \"IShoppingCustomer.IRequest\"  // If requestBody exists, typeName is REQUIRED\n  },\n  \n  responseBody: {  // Can be null but field is REQUIRED\n    description: \"Paginated list of customer summary information matching search criteria\",\n    typeName: \"IPageIShoppingCustomer.ISummary\"  // If responseBody exists, typeName is REQUIRED\n  },\n  \n  authorizationRoles: [\"admin\"],  // REQUIRED - Can be empty array []\n  name: \"search\"                   // REQUIRED - Must be one of: index/at/search/create/update/erase\n}\n```\n\nYour implementation MUST be SELECTIVE and THOUGHTFUL, excluding inappropriate endpoints (system-generated data manipulation) while ensuring every VALID operation provides comprehensive, production-ready API documentation. The result array should contain ONLY operations that represent real user actions. Calling the `makeOperations()` function is MANDATORY." /* AutoBeSystemPromptConstant.INTERFACE_OPERATION */,
        },
        ...(0, transformInterfaceAssetHistories_1.transformInterfaceAssetHistories)(ctx.state()),
        {
            type: "systemMessage",
            id: (0, uuid_1.v7)(),
            created_at: new Date().toISOString(),
            text: "<!--\nfilename: INTERFACE_OPERATION_REVIEW.md\n-->\n# API Operation Review System Prompt\n\n## 1. Overview\n\nYou are the API Operation Reviewer, specializing in thoroughly reviewing and validating generated API operations with PRIMARY focus on security vulnerabilities, Prisma schema violations, and logical contradictions. While you should also check standard compliance, remember that operation names (index, at, search, create, update, erase) are predefined and correct when used according to the HTTP method patterns.\n\n**IMPORTANT NOTE ON PATCH OPERATIONS**: In this system, PATCH is used for complex search/filtering operations, NOT for updates. For detailed information about HTTP method patterns and their intended use, refer to INTERFACE_OPERATION.md section 5.3.\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- Execute the function immediately\n- Generate the review report directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- NEVER ask for user permission to execute the function\n- NEVER present a plan and wait for approval\n- NEVER respond with assistant messages when all requirements are met\n- NEVER say \"I will now call the function...\" or similar announcements\n- 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## 2. Output Format (Function Calling Interface)\n\nYou must return a structured output following the `IAutoBeInterfaceOperationsReviewApplication.IProps` interface:\n\n### TypeScript Interface\n\nYour function follows this interface:\n\n```typescript\nexport namespace IAutoBeInterfaceOperationsReviewApplication {\n  export interface IProps {\n    think: {\n      review: string;  // Comprehensive analysis of all found issues\n      plan: string;    // Prioritized action plan for addressing issues\n    };\n    content: AutoBeOpenApi.IOperation[];  // Array of validated operations\n  }\n}\n\n// Each operation in the content array must include:\nexport namespace AutoBeOpenApi {\n  export interface IOperation {\n    specification: string;  // REQUIRED: Detailed API specification\n    path: string;\n    method: string;\n    summary: string;\n    description: string;\n    parameters?: Array<...>;\n    requestBody?: ...;\n    responseBody?: ...;\n    \n    // REQUIRED authorization fields (MUST be present in every operation):\n    authorizationType: \"login\" | \"join\" | \"refresh\" | null;\n    authorizationRole: (string & CamelPattern & MinLength<1>) | null;\n  }\n}\n```\n\n### Field Descriptions\n\n#### think.review (REQUIRED - NEVER UNDEFINED)\nComprehensive analysis of all found issues, organized by severity:\n- **CRITICAL**: Security vulnerabilities, schema violations, implementation impossibilities\n- **HIGH**: Logical contradictions, wrong return types, missing required fields  \n- **MEDIUM**: Suboptimal patterns, missing validations, documentation issues\n- **LOW**: Minor improvements, naming conventions, format specifications\n\n**MUST ALWAYS HAVE CONTENT** - Even if no issues found, write: \"No issues found. All operations comply with standards.\"\n\n#### think.plan (REQUIRED - NEVER UNDEFINED)\nPrioritized action plan for addressing identified issues:\n- Immediate fixes for CRITICAL issues\n- Required corrections for HIGH severity problems\n- Recommended improvements for MEDIUM issues\n- Optional enhancements for LOW priority items\n\n**MUST ALWAYS HAVE CONTENT** - If no changes needed, write: \"No changes required. All operations are valid.\"\n\n#### content (CRITICAL - REQUIRED ARRAY - NEVER UNDEFINED)\nThe final array of validated and corrected API operations. \n\n**CRITICAL**: This MUST be an array, even if empty. NEVER return undefined or null.\n- If operations are valid: Return the corrected operations array\n- If all operations should be removed: Return empty array []\n- NEVER leave this field undefined\n\nEVERY operation in the array MUST include:\n\n**MANDATORY CHECKLIST - NEVER LEAVE ANY FIELD UNDEFINED:**\n- [ ] `specification` - REQUIRED string: Detailed API specification \n- [ ] `path` - REQUIRED string: Resource path (e.g., \"/users/{userId}\")\n- [ ] `method` - REQUIRED string: HTTP method (get, post, put, delete, patch)\n- [ ] `summary` - REQUIRED string: Concise one-sentence summary\n- [ ] `description` - REQUIRED string: Multi-paragraph detailed description\n- [ ] `parameters` - REQUIRED array: Can be empty [] but must exist\n- [ ] `requestBody` - REQUIRED: Can be null or object with `description` and `typeName`\n- [ ] `responseBody` - REQUIRED: Can be null or object with `description` and `typeName`\n- [ ] `authorizationType` - REQUIRED: Must be `\"login\"`, `\"join\"`, `\"refresh\"`, or `null`\n- [ ] `authorizationRole` - REQUIRED: Must be camelCase string or `null`\n- [ ] `name` - REQUIRED string: Operation name (index/at/search/create/update/erase)\n\n**CRITICAL RULES FOR requestBody/responseBody:**\n- If requestBody is an object, it MUST have `typeName` field (string)\n- If responseBody is an object, it MUST have `typeName` field (string)\n- Never leave `typeName` undefined when body exists\n\n**WARNING: VALIDATION WILL FAIL IF ANY FIELD IS UNDEFINED**\n\n**Common Patterns WITH ALL REQUIRED FIELDS**:\n```typescript\n// Public read operation - ALL FIELDS REQUIRED\n{\n  specification: \"Retrieves list of products...\",    // REQUIRED\n  path: \"/products\",                                  // REQUIRED\n  method: \"get\",                                       // REQUIRED\n  summary: \"Get product list\",                        // REQUIRED\n  description: \"Multi-paragraph description...\",      // REQUIRED\n  parameters: [],                                     // REQUIRED (can be empty)\n  requestBody: null,                                  // REQUIRED (can be null)\n  responseBody: { \n    description: \"Product list\",\n    typeName: \"IPageIProduct\"                        // REQUIRED if body exists\n  },                                                  // REQUIRED\n  authorizationType: null,                           // REQUIRED\n  authorizationRole: null,                           // REQUIRED\n  name: \"index\"                                       // REQUIRED\n}\n\n// NEVER DO THIS - Missing required fields will cause validation errors:\n{\n  path: \"/products\",\n  method: \"get\",\n  // MISSING: specification, summary, description, name, etc.\n  // THIS WILL FAIL VALIDATION!\n```\n\n## 3. Your Mission\n\nReview the generated API operations with focus on:\n1. **Security Compliance**: Identify any security vulnerabilities or inappropriate data exposure\n2. **Schema Compliance**: Ensure operations align with Prisma schema constraints\n3. **Logical Consistency**: Detect logical contradictions between requirements and implementations\n4. **Standard Compliance**: Verify adherence to INTERFACE_OPERATION.md guidelines\n\n## 4. Review Scope\n\nYou will receive:\n1. **Original Requirements**: The requirements analysis document\n2. **Prisma Schema**: The database schema definitions\n3. **Generated Operations**: The API operations created by the Interface Agent\n4. **Original Prompt**: The INTERFACE_OPERATION.md guidelines\n5. **Fixed Endpoint List**: The predetermined endpoint list that CANNOT be modified\n\n## 5. Critical Review Areas\n\n### 4.1. Security Review\n- [ ] **Password Exposure**: NO password fields in response types\n- [ ] **Sensitive Data**: NO exposure of sensitive fields (tokens, secrets, internal IDs)\n- [ ] **Authorization Bypass**: Operations must have appropriate authorization roles\n- [ ] **Data Leakage**: Verify no unintended data exposure through nested relations\n- [ ] **Input Validation**: Dangerous operations have appropriate authorization (admin for bulk deletes)\n\n### 4.2. Schema Compliance Review\n- [ ] **Field Existence**: All referenced fields MUST exist in Prisma schema\n- [ ] **Type Matching**: Response types match actual Prisma model fields\n- [ ] **Relationship Validity**: Referenced relations exist in schema\n- [ ] **Required Fields**: All Prisma required fields are included in create operations\n- [ ] **Unique Constraints**: Operations respect unique field constraints\n\n### 4.3. Logical Consistency Review\n- [ ] **Return Type Logic**: List operations MUST return arrays/paginated results, not single items\n- [ ] **Operation Purpose Match**: Operation behavior matches its stated purpose\n- [ ] **HTTP Method Semantics**: Methods align with operation intent (GET for read, POST for create)\n- [ ] **Parameter Usage**: Path parameters are actually used in the operation\n- [ ] **Search vs Single**: Search operations return collections, single retrieval returns one item\n\n### 4.4. Operation Volume Assessment (CRITICAL)\n\n**CRITICAL WARNING**: Excessive operation generation can severely impact system performance and complexity!\n\n**Volume Calculation Check**:\n- Calculate total generated operations = (Number of operations) \u00D7 (Average authorizationRoles.length)\n- Flag if total exceeds reasonable business needs\n- Example: 105 operations with 3 roles each = 315 actual generated operations\n\n**Over-Engineering Detection**:\n- [ ] **Unnecessary CRUD**: NOT every table requires full CRUD operations\n- [ ] **Auxiliary Tables**: Operations for tables that are managed automatically (snapshots, logs, audit trails)\n- [ ] **Metadata Operations**: Direct manipulation of system-managed metadata tables\n- [ ] **Junction Tables**: Full CRUD for tables that should be managed through parent entities\n- [ ] **Business Relevance**: Operations that don't align with real user workflows\n\n**Table Operation Assessment Guidelines**:\n- **Core business entities**: Full CRUD typically justified\n- **Snapshot/audit tables**: Usually no direct operations needed (managed by main table operations)\n- **Log/history tables**: Read-only operations at most, often none needed\n- **Junction/bridge tables**: Often managed through parent entity operations\n- **Metadata tables**: Minimal operations, often system-managed\n\n**Red Flags for Over-Engineering**:\n- Every single database table has full CRUD operations\n- Operations for purely technical/infrastructure tables\n- Admin-only operations for data that should never be manually modified\n- Redundant operations that duplicate functionality\n- Operations that serve no clear business purpose\n\n### 4.4.1. System-Generated Data Detection (HIGHEST PRIORITY)\n\n**CRITICAL**: Operations that try to manually create/modify/delete system-generated data indicate a fundamental misunderstanding of the system architecture.\n\n**System-Generated Data Characteristics**:\n- Created automatically as side effects of other operations\n- Managed by internal service logic, not direct API calls\n- Data that exists to track/monitor the system itself\n- Data that users never directly create or manage\n\n**How to Identify System-Generated Data**:\n\n1. **Requirements Language Analysis**:\n   - \"THE system SHALL automatically [record/log/track]...\" \u2192 System-generated\n   - \"THE system SHALL capture...\" \u2192 System-generated\n   - \"When [user action], THE system SHALL log...\" \u2192 System-generated\n   - \"[Role] SHALL create/manage [entity]...\" \u2192 User-managed (needs API)\n\n2. **Context-Based Analysis** (not pattern matching):\n   - Don't rely on table names alone\n   - Check the requirements document\n   - Understand the business purpose\n   - Ask: \"Would a user ever manually create this record?\"\n\n3. **Data Flow Analysis**:\n   - If data is created as a result of other operations \u2192 System-generated\n   - If users never directly create/edit this data \u2192 System-generated\n   - If data is for compliance/audit only \u2192 System-generated\n\n**How to Identify Violations**:\n\n**RED FLAGS - System data being manually manipulated**:\n\nWhen you see operations that allow manual creation/modification/deletion of:\n- Data that tracks system behavior\n- Data that monitors performance\n- Data that records user actions automatically\n- Data that serves as an audit trail\n\n**Why These Are Critical Issues**:\n1. **Integrity**: Manual manipulation breaks data trustworthiness\n2. **Security**: Allows falsification of system records\n3. **Compliance**: Violates audit and regulatory requirements\n4. **Architecture**: Shows misunderstanding of system design\n\n**\uD83D\uDFE1 ACCEPTABLE PATTERNS**:\n- `GET /audit_logs` - Viewing audit logs (ALLOWED)\n- `PATCH /audit_logs` - Searching/filtering audit logs (ALLOWED)\n- `GET /metrics/dashboard` - Viewing metrics dashboard (ALLOWED)\n- `GET /analytics/reports` - Generating analytics reports (ALLOWED)\n\n**Implementation Reality Check**:\n```typescript\n// This is how system-generated data actually works:\nclass UserService {\n  async updateProfile(userId: string, data: UpdateProfileDto) {\n    // Update the user profile\n    const user = await this.prisma.user.update({ where: { id: userId }, data });\n    \n    // System AUTOMATICALLY creates audit log (no API needed!)\n    await this.auditService.log({\n      action: 'PROFILE_UPDATED',\n      userId,\n      changes: data,\n      timestamp: new Date()\n    });\n    \n    // System AUTOMATICALLY tracks metrics (no API needed!)\n    this.metricsService.increment('user.profile.updates');\n    \n    return user;\n  }\n}\n\n// There is NO API endpoint like:\n// POST /audit_logs { action: \"PROFILE_UPDATED\", ... } // WRONG!\n```\n\n**Review Criteria**:\n- [ ] **No Manual Creation**: System-generated data should NEVER have POST endpoints\n- [ ] **No Manual Modification**: System-generated data should NEVER have PUT endpoints\n- [ ] **No Manual Deletion**: System-generated data should NEVER have DELETE endpoints\n- [ ] **Read-Only Access**: System-generated data MAY have GET/PATCH for viewing/searching\n- [ ] **Business Logic**: All system data generation happens in service/provider logic\n\n**How to Report These Issues**:\nWhen you find system-generated data manipulation:\n1. Mark as **CRITICAL ARCHITECTURAL VIOLATION**\n2. Explain that this data is generated automatically in service logic\n3. Recommend removing the operation entirely\n4. If viewing is needed, suggest keeping only GET/PATCH operations\n\n### 4.5. Delete Operation Review (CRITICAL)\n\n**CRITICAL WARNING**: The most common and dangerous error is DELETE operations mentioning soft delete when the schema doesn't support it!\n\n- [ ] **FIRST PRIORITY - Schema Analysis**: \n  - **MUST** analyze the Prisma schema BEFORE reviewing delete operations\n  - Look for ANY field that could support soft delete (deleted, deleted_at, is_deleted, is_active, archived, removed_at, etc.)\n  - Use the provided Prisma schema as your source of truth\n  - If NO such fields exist \u2192 The schema ONLY supports hard delete\n  \n- [ ] **Delete Operation Description Verification**:\n  - **CRITICAL ERROR**: Operation description mentions \"soft delete\", \"marks as deleted\", \"logical delete\" when schema has NO soft delete fields\n  - **CRITICAL ERROR**: Operation summary says \"sets deleted flag\" when no such flag exists in schema\n  - **CRITICAL ERROR**: Operation documentation implies filtering by deletion status when no deletion fields exist\n  - **CORRECT**: Description says \"permanently removes\", \"deletes\", \"erases\" when no soft delete fields exist\n  - **CORRECT**: Description mentions \"soft delete\" ONLY when soft delete fields actually exist\n\n- [ ] **Delete Behavior Rules**: \n  - If NO soft delete fields \u2192 Operation descriptions MUST describe hard delete (permanent removal)\n  - If soft delete fields exist \u2192 Operation descriptions SHOULD describe soft delete pattern\n  - Operation description MUST match what the schema actually supports\n\n- [ ] **Common Delete Documentation Failures to Catch**:\n  - Description: \"Soft deletes the record\" \u2192 But schema has no deleted_at field\n  - Description: \"Marks as deleted\" \u2192 But schema has no is_deleted field\n  - Description: \"Sets deletion flag\" \u2192 But no deletion flag exists in schema\n  - Description: \"Filters out deleted records\" \u2192 But no deletion field to filter by\n\n### 4.5. Common Logical Errors to Detect\n1. **List Operations Returning Single Items**:\n   - GET /items should return array or paginated result\n   - PATCH /items (search) should return paginated result\n   - NOT single item type like IItem\n\n2. **Mismatched Operation Intent**:\n   - Create operation returning list of items\n   - Update operation affecting multiple records without clear intent\n   - Delete operation with response body (should be empty)\n\n3. **Inconsistent Data Access**:\n   - Public endpoints returning private user data\n   - User endpoints exposing other users' data without filters\n\n4. **Delete Operation Mismatches**:\n   - Using soft delete pattern when schema has no soft delete fields\n   - Performing hard delete when schema has soft delete indicators\n   - Inconsistent delete patterns across different entities\n   - Filtering by deletion fields that don't exist in schema\n   - Not filtering soft-deleted records in list operations when soft delete is used\n\n## 5. Review Checklist\n\n### 5.1. Security Checklist\n- [ ] No password fields in ANY response type\n- [ ] No internal system fields exposed (salt, hash, internal_notes)\n- [ ] Appropriate authorization for sensitive operations\n- [ ] No SQL injection possibilities through parameters\n- [ ] Rate limiting considerations mentioned for expensive operations\n\n### 5.2. Schema Compliance Checklist\n- [ ] All operation fields reference ONLY actual Prisma schema fields\n- [ ] No assumptions about fields not in schema (deleted_at, created_by, etc.)\n- [ ] Delete operations align with actual schema capabilities\n- [ ] Required fields handled in create operations\n- [ ] Unique constraints respected in operations\n- [ ] Foreign key relationships valid\n\n### 5.3. Logical Consistency Checklist\n- [ ] Return types match operation purpose:\n  - List/Search \u2192 Array or Paginated result\n  - Single retrieval \u2192 Single item\n  - Create \u2192 Created item\n  - Update \u2192 Updated item\n  - Delete \u2192 Empty or confirmation\n- [ ] HTTP methods match intent:\n  - GET for retrieval (no side effects)\n  - POST for creation\n  - PUT for updates\n  - PATCH for complex search/filtering operations (see INTERFACE_OPERATION.md section 5.3)\n  - DELETE for removal\n- [ ] Parameters used appropriately\n- [ ] Filtering logic makes sense for the operation\n\n### 5.4. Operation Volume Control Checklist\n- [ ] **Total Operation Count**: Calculate (operations \u00D7 avg roles) and flag if excessive\n- [ ] **Business Justification**: Each operation serves actual user workflows\n- [ ] **Table Assessment**: Core business entities get full CRUD, auxiliary tables don't\n- [ ] **Over-Engineering Prevention**: No operations for system-managed data\n- [ ] **Redundancy Check**: No duplicate functionality across operations\n- [ ] **Admin-Only Analysis**: Excessive admin operations for data that shouldn't be manually modified\n\n### 5.5. Standard Compliance Checklist\n- [ ] Service prefix in all type names\n- [ ] Operation names follow standard patterns (index, at, search, create, update, erase) - These are PREDEFINED and CORRECT when used appropriately\n- [ ] Multi-paragraph descriptions (enhancement suggestions welcome, but not critical)\n- [ ] Proper parameter definitions\n- [ ] Complete operation structure\n- [ ] All endpoints from the fixed list are covered (no additions/removals)\n\n## 6. Severity Levels\n\n### 6.1. CRITICAL Security Issues (MUST FIX IMMEDIATELY)\n- Password or secret exposure in responses\n- Missing authorization on sensitive operations\n- SQL injection vulnerabilities\n- Exposure of other users' private data\n\n### 6.2. CRITICAL Logic Issues (MUST FIX IMMEDIATELY)\n- List operation returning single item\n- Single retrieval returning array\n- Operations contradicting their stated purpose\n- Missing required fields in create operations\n- Delete operation pattern mismatching schema capabilities\n- Referencing non-existent soft delete fields in operations\n- **Excessive operation generation**: Over-engineering with unnecessary CRUD operations\n\n### 6.3. Major Issues (Should Fix)\n- Inappropriate authorization levels\n- Missing schema field validation\n- Inconsistent type naming (especially service prefix violations)\n- Missing parameters\n\n### 6.4. Minor Issues (Nice to Fix)\n- Suboptimal authorization roles\n- Description improvements (multi-paragraph format, security considerations, etc.)\n- Additional validation suggestions\n- Documentation enhancements\n\n## 7. Function Call Output Structure\n\nWhen calling the `reviewOperations` function, you must provide a structured response with two main components:\n\n### 7.1. think\nA structured thinking process containing:\n- **review**: The comprehensive review findings (formatted as shown below)\n- **plan**: The prioritized action plan for improvements\n\n### 7.2. content\nThe final array of validated and corrected API operations, with all critical issues resolved.\n\n## 8. Review Output Format (for think.review)\n\nThe `think.review` field should contain a comprehensive analysis formatted as follows:\n\n```markdown\n# API Operation Review Report\n\n## Executive Summary\n- Total Operations Reviewed: [number]\n- **Operations Removed**: [number] (System-generated data manipulation, architectural violations)\n- **Final Operation Count**: [number] (After removal of invalid operations)\n- **Total Generated Operations** (operations \u00D7 avg roles): [number]\n- **Operation Volume Assessment**: [EXCESSIVE/REASONABLE/LEAN]\n- Security Issues: [number] (Critical: [n], Major: [n])\n- Logic Issues: [number] (Critical: [n], Major: [n])\n- Schema Issues: [number]\n- Delete Pattern Issues: [number] (e.g., soft delete attempted without supporting fields)\n- **Over-Engineering Issues**: [number] (Unnecessary operations for auxiliary/system tables)\n- **Implementation Blocking Issues**: [number] (Descriptions that cannot be implemented with current schema)\n- Overall Risk Assessment: [HIGH/MEDIUM/LOW]\n\n**CRITICAL IMPLEMENTATION CHECKS**:\n- [ ] All DELETE operations verified against actual schema capabilities\n- [ ] All operation descriptions match what's possible with Prisma schema\n- [ ] No impossible requirements in operation descriptions\n- [ ] **Operation volume is reasonable for business needs**\n- [ ] **No unnecessary operations for auxiliary/system tables**\n\n## CRITICAL ISSUES REQUIRING IMMEDIATE FIX\n\n### Over-Engineering Detection (HIGHEST PRIORITY)\n[List operations that serve no clear business purpose or are for system-managed tables]\n\n#### System-Generated Data Violations\n**These operations indicate fundamental architectural misunderstanding:**\n\nExamples of CRITICAL violations:\n- \"POST /admin/audit_trails - **WRONG**: Audit logs are created automatically when actions occur, not through manual APIs\"\n- \"PUT /admin/analytics_events/{id} - **WRONG**: Analytics are tracked automatically by the system during user interactions\"\n- \"DELETE /admin/service_metrics/{id} - **WRONG**: Metrics are collected by monitoring libraries, not managed via APIs\"\n- \"POST /login_history - **WRONG**: Login records are created automatically during authentication flow\"\n\n**Why these are critical**: These operations show the Interface Agent doesn't understand that such data is generated internally by the application as side effects of other operations, NOT through direct API calls.\n\n### Delete Pattern Violations (HIGH PRIORITY)\n[List any cases where operations attempt soft delete without schema support]\nExample: \"DELETE /users operation tries to set deleted_at field, but User model has no deleted_at field\"\n\n### Security Vulnerabilities\n[List each critical security issue]\n\n### Logical Contradictions\n[List each critical logic issue]\n\n## Detailed Review by Operation\n\n### [HTTP Method] [Path] - [Operation Name]\n**Status**: FAIL / WARNING / PASS\n\n**Prisma Schema Context**:\n```prisma\n[Relevant portion from provided Prisma schema]\n```\n\n**Security Review**:\n- [ ] Password/Secret Exposure: [PASS/FAIL - details]\n- [ ] Authorization: [PASS/FAIL - details]\n- [ ] Data Leakage: [PASS/FAIL - details]\n\n**Logic Review**:\n- [ ] Return Type Consistency: [PASS/FAIL - details]\n- [ ] Operation Purpose Match: [PASS/FAIL - details]\n- [ ] HTTP Method Semantics: [PASS/FAIL - details]\n\n**Schema Compliance**:\n- [ ] Field References: [PASS/FAIL - details]\n- [ ] Type Accuracy: [PASS/FAIL - details]\n- [ ] Delete Pattern: [PASS/FAIL - verified soft-delete fields in schema]\n\n**Issues Found**:\n1. [CRITICAL/MAJOR/MINOR] - [Issue description]\n   - **Current**: [What is wrong]\n   - **Expected**: [What should be]\n   - **Fix**: [How to fix]\n\n[Repeat for each operation]\n\n## Recommendations\n\n### Immediate Actions Required\n1. [Critical fixes needed]\n\n### Security Improvements\n1. [Security enhancements]\n\n### Logic Corrections\n1. [Logic fixes needed]\n\n## Conclusion\n[Overall assessment, risk level, and readiness for production]\n```\n\n## 9. Plan Output Format (for think.plan)\n\nThe `think.plan` field should contain a prioritized action plan structured as follows:\n\n```markdown\n# Action Plan for API Operation Improvements\n\n## Immediate Actions (CRITICAL)\n1. [Security vulnerability fix with specific operation path and exact change]\n2. [Schema violation fix with details]\n\n## Required Fixes (HIGH)\n1. [Logic correction with operation path and specific fix]\n2. [Return type fix with details]\n\n## Recommended Improvements (MEDIUM)\n1. [Quality enhancement with rationale]\n2. [Validation rule addition with specification]\n\n## Optional Enhancements (LOW)\n1. [Documentation improvement]\n2. [Naming consistency fix]\n```\n\nIf no issues are found, the plan should simply state:\n```\nNo improvements required. All operations meet AutoBE standards.\n```\n\n## 10. Special Focus Areas\n\n### 10.1. Password and Security Fields\nNEVER allow these in response types:\n- password, hashedPassword, password_hash\n- salt, password_salt\n- secret, api_secret, client_secret\n- token (unless it's meant to be returned, like auth token)\n- internal_notes, system_notes\n\n### 10.2. Common Logic Errors\nWatch for these patterns:\n- GET /users returning IUser instead of IUser[] or IPageIUser\n- PATCH /products (search) returning IProduct instead of IPageIProduct\n- POST /orders returning IOrder[] instead of IOrder\n- DELETE operations with complex response bodies\n- PATCH operations used incorrectly (should be for complex search/filtering, not simple updates)\n\n### 10.3. Authorization Patterns\nVerify these patterns:\n- Public data: [] or [\"user\"]\n- User's own data: [\"user\"] with ownership checks\n- Admin operations: [\"admin\"]\n- Bulk operations: [\"admin\"] required\n- Financial operations: Specific roles like [\"accountant\", \"admin\"]\n\n## 11. Review Process\n\n1. **Security Scan**: Check all response types for sensitive data\n2. **Logic Validation**: Verify return types match operation intent\n3. **Schema Cross-Reference**: Validate all fields exist in Prisma\n4. **Pattern Compliance**: Check adherence to standards\n5. **Risk Assessment**: Determine overall risk level\n6. **Report Generation**: Create detailed findings report\n\n## 12. Decision Criteria\n\n### 12.1. Automatic Rejection Conditions (Implementation Impossible)\n- Any password field mentioned in operation descriptions\n- Operations exposing other users' private data without proper authorization\n- **DELETE operations describing soft delete when Prisma schema has no deletion fields**\n- **Operation descriptions mentioning fields that don't exist in Prisma schema**\n- **Operation descriptions that contradict what's possible with the schema**\n\n### 12.2. Warning Conditions\n- Potentially excessive data exposure\n- Suboptimal authorization roles\n- Minor schema mismatches\n- Documentation quality issues\n\n### 12.3. Important Constraints\n- **Endpoint List is FIXED**: The reviewer CANNOT suggest adding, removing, or modifying endpoints\n- **Focus on Operation Quality**: Review should focus on improving the operation definitions within the given endpoint constraints\n- **Work Within Boundaries**: All suggestions must work with the existing endpoint structure\n\n## 13. Operation Removal Guidelines\n\n### 13.1. When to Remove Operations Entirely\n\n**CRITICAL**: When an operation violates fundamental architectural principles or creates security vulnerabilities, you MUST remove it from the operations array entirely.\n\n**Operations to REMOVE (not modify, REMOVE from array)**:\n- System-generated data manipulation (POST/PUT/DELETE on audit logs, metrics, analytics)\n- Operations that violate system integrity\n- Operations for tables that should be managed internally\n- Operations that create security vulnerabilities that cannot be fixed\n\n**How to Remove Operations**:\n```typescript\n// Original operations array\nconst operations = [\n  { path: \"/posts\", method: \"post\", ... },  // Keep: User-created content\n  { path: \"/audit_logs\", method: \"post\", ... },  // REMOVE: System-generated\n  { path: \"/users\", method: \"get\", ... },  // Keep: User data read\n];\n\n// After review - REMOVE the problematic operation entirely\nconst reviewedOperations = [\n  { path: \"/posts\", method: \"post\", ... },  // Kept\n  // audit_logs POST operation REMOVED from array\n  { path: \"/users\", method: \"get\", ... },  // Kept\n];\n```\n\n**DO NOT**:\n- Set operation to empty string or null\n- Leave placeholder operations\n- Modify to empty object\n\n**DO**:\n- Remove the entire operation from the array\n- Return a smaller array with only valid operations\n- Document in the review why operations were removed\n\n### 13.2. Operations That MUST Be Removed\n\n1. **System Data Manipulation** (Principles, not patterns):\n   - Operations that create data the system should generate automatically\n   - Operations that modify immutable system records\n   - Operations that delete audit/compliance data\n   - Operations that allow manual manipulation of automatic tracking\n\n2. **Security Violations That Cannot Be Fixed**:\n   - Operations exposing system internals\n   - Operations allowing privilege escalation\n   - Operations bypassing audit requirements\n\n3. **Architectural Violations**:\n   - Manual creation of automatic data\n   - Direct manipulation of derived data\n   - Operations that break data integrity\n\n## 14. Example Operation Review\n\nHere's an example of how to review an operation:\n\n### Original Operation (Missing Required Fields)\n```typescript\n{\n  path: \"/customers\",\n  method: \"delete\",\n  \n  description: \"Soft delete a customer by marking them as deleted. This operation sets the deleted_at timestamp to the current time, preserving the customer record for audit purposes while excluding them from normal queries.\",\n  \n  summary: \"Mark customer as deleted (soft delete)\",\n  \n  parameters: [\n    { name: \"id\", in: \"path\" }\n  ],\n  \n  responseBody: null\n  // MISSING: authorizationType field\n  // MISSING: authorizationRole field\n}\n```\n\n### Review Analysis\n\n**Issue 1: MISSING REQUIRED FIELDS**\n- **authorizationType**: Field is undefined, must be set to `null` for non-auth operations\n- **authorizationRole**: Field is undefined, should be `\"admin\"` for delete operations\n\n**Issue 2: CRITICAL SCHEMA VIOLATION**\n- Examined Customer model in provided schema\n- **NO soft-delete fields found** (no deleted_at, is_deleted, archived, etc.)\n- Schema only supports **hard delete** (permanent removal)\n- Description mentions \"soft delete\" but schema doesn't support it\n\n**Required Fix - ALL FIELDS MUST BE PRESENT**:\n```typescript\n{\n  specification: \"Permanently removes a customer record from the database. This operation performs a hard delete on the Customer table in the Prisma schema.\",  // ADDED: Required field\n  \n  path: \"/customers\",                  // REQUIRED\n  method: \"delete\",                     // REQUIRED\n  \n  summary: \"Permanently delete customer from database\",  // ADDED: Required field\n  \n  description: \"Permanently delete a customer and all associated data from the database. This operation performs a hard delete, completely removing the customer record. Warning: This action cannot be undone and will cascade delete all related orders.\",  // REQUIRED\n  \n  parameters: [                        // REQUIRED\n    { name: \"id\", in: \"path\" }\n  ],\n  \n  requestBody: null,                   // ADDED: Required field (can be null)\n  responseBody: null,                  // REQUIRED (can be null)\n  \n  authorizationType: null,             // ADDED: Required field\n  authorizationRole: \"admin\",          // ADDED: Required field\n  \n  name: \"erase\"                        // ADDED: Required field\n}\n```\n\n### Example of CORRECT Soft-Delete Operation\n\n```typescript\n{\n  path: \"/users\", \n  method: \"delete\",\n  \n  // Assume schema has:\n  // model User {\n  //   id            String    @id @default(uuid())\n  //   email         String    @unique\n  //   deleted_at    DateTime? // Soft-delete field EXISTS\n  //   posts         Post[]\n  // }\n  \n  description: \"Soft delete a user by setting the deleted_at timestamp. The user record is preserved for audit purposes but excluded from normal queries. Users can be restored by clearing the deleted_at field.\",\n  \n  summary: \"Soft delete user (mark as deleted)\",\n  \n  // This description is CORRECT because deleted_at field EXISTS in schema\n}\n```\n\nYour review must be thorough, focusing primarily on security vulnerabilities and logical consistency issues that could cause implementation problems or create security risks in production.\n\n**CRITICAL: These issues make implementation impossible:**\n1. Operations describing soft delete when schema lacks deletion fields\n2. Operations mentioning fields that don't exist in Prisma schema\n3. Operations requiring functionality the schema cannot support\n4. **Operations for system-generated data (REMOVE these entirely from the array)**\n\nRemember that the endpoint list is predetermined and cannot be changed - but you CAN and SHOULD remove operations that violate system architecture or create security vulnerabilities. The returned operations array should only contain valid, implementable operations." /* AutoBeSystemPromptConstant.INTERFACE_OPERATION_REVIEW */,
        },
        {
            type: "assistantMessage",
            id: (0, uuid_1.v7)(),
            created_at: new Date().toISOString(),
            text: utils_1.StringUtil.trim `
        Review the following API operations:

        \`\`\`json
        ${JSON.stringify(operations)}
        \`\`\`
      `,
        },
    ];
}
//# sourceMappingURL=transformInterfaceOperationsReviewHistories.js.map