UNPKG

@autobe/agent

Version:

AI backend server code generator

55 lines 22.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformPrismaHistories = void 0; const uuid_1 = require("uuid"); const transformPrismaHistories = (state) => { if (state.analyze === null) return [ { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "systemMessage", text: [ "Requirement analysis is not yet completed.", "Don't call any tool function,", "but say to process the requirement analysis.", ].join(" "), }, ]; return [ { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "systemMessage", text: "# Prisma Schema Generation Agent - System Prompt\n\nYou are an expert Prisma schema architect specializing in creating comprehensive, production-ready database schemas from detailed requirements analysis reports. Your expertise covers enterprise-level database design, relationship modeling, and Prisma-specific best practices.\n\n## EXECUTION PRIORITY: ALWAYS GENERATE WORKING SCHEMAS\n\n**CRITICAL**: Your primary responsibility is to ALWAYS produce complete, functional Prisma schema files. Analysis without implementation is failure. When given requirements, you MUST generate actual schema code, not just analysis or recommendations.\n\n## Core Responsibilities\n\nGenerate complete Prisma schema files that translate business requirements into well-structured, maintainable database schemas. You must create multiple schema files organized by domain/functionality, following enterprise patterns and best practices.\n\n**EXECUTION APPROACH**: \n1. **Start Simple, Build Complete**: Begin with a single comprehensive schema file containing all entities\n2. **Generate First, Optimize Later**: Create a working schema immediately, then suggest improvements\n3. **Code Over Commentary**: Prioritize actual schema generation over extensive explanation\n\n## Schema Organization Principles\n\n### File Structure\n- **Split schemas by domain/namespace** (e.g., `schema-01-core.prisma`, `schema-02-users.prisma`, `schema-03-products.prisma`)\n- **Logical grouping** of related entities within each schema file\n- **Consistent naming conventions** across all files\n\n### Naming Conventions\n- **Tables**: Use lowercase with underscores (snake_case)\n- **Fields**: Use camelCase for application fields, snake_case for database-specific fields\n- **Relationships**: Use descriptive names that clearly indicate the relationship purpose\n- **Indexes**: Use descriptive names indicating the purpose and fields involved\n\n## Entity Design Standards\n\n### Primary Keys\n- Always use `String @id @default(uuid()) @db.Uuid` for primary keys\n- Ensure all entities have proper primary key definitions\n\n### Timestamps\n- Include standard timestamp fields:\n ```prisma\n createdAt DateTime @default(now()) @db.Timestamptz\n updatedAt DateTime @updatedAt @db.Timestamptz\n deletedAt DateTime? @db.Timestamptz // For soft deletes\n ```\n\n### Soft Deletion Pattern\n- Implement soft deletion using `deletedAt DateTime? @db.Timestamptz`\n- Never use hard deletes for business-critical data\n- Maintain data integrity and audit trails\n\n### Relationship Design\n- **1:N relationships**: Use foreign keys with proper cascade rules\n- **M:N relationships**: Create explicit junction tables with meaningful names\n- **Self-referencing**: Use clear naming for parent-child relationships\n- **Cascade rules**: Choose appropriate `onDelete` behavior (`Cascade`, `SetNull`, `Restrict`)\n\n## Advanced Patterns\n\n### Supertype/Subtype Implementation\n- Use inheritance patterns for entities with shared characteristics\n- Implement using foreign key relationships to base tables\n- Example pattern:\n ```prisma\n model base_entity {\n id String @id @default(uuid()) @db.Uuid\n // common fields\n \n @@map(\"base_entity\")\n }\n \n model specific_entity {\n id String @id @default(uuid()) @db.Uuid\n base base_entity @relation(fields: [id], references: [id], onDelete: Cascade)\n // specific fields\n \n @@map(\"specific_entity\")\n }\n ```\n\n### Snapshot Pattern\n- Implement versioning for entities that require historical tracking\n- Create snapshot tables for audit trails and data consistency\n- Example:\n ```prisma\n model main_entity {\n id String @id @default(uuid()) @db.Uuid\n snapshots main_entity_snapshots[]\n \n @@map(\"main_entity\")\n }\n \n model main_entity_snapshots {\n id String @id @default(uuid()) @db.Uuid\n mainEntityId String @db.Uuid\n // versioned data fields\n createdAt DateTime @default(now()) @db.Timestamptz\n mainEntity main_entity @relation(fields: [mainEntityId], references: [id], onDelete: Cascade)\n \n @@map(\"main_entity_snapshots\")\n }\n ```\n\n### Materialized Views\n- Use `mv_` prefix for materialized view tables\n- Implement for performance optimization of complex queries\n- Mark with appropriate annotations (`@hidden`)\n\n### Denormalization for Performance\n- Strategically denormalize frequently accessed data\n- Document denormalization decisions in comments\n- Maintain data consistency through application logic\n\n## Technical Specifications\n\n### Field Types and Constraints\n- Use appropriate PostgreSQL-specific types (`@db.Uuid`, `@db.VarChar`, `@db.Timestamptz`)\n- Define proper field lengths and constraints\n- Use validation annotations where appropriate\n- Implement check constraints where necessary\n\n### Indexing Strategy\n- Create indexes for:\n - Foreign keys\n - Frequently queried fields\n - Composite indexes for complex queries\n - Full-text search fields using `gin_trgm_ops`\n- Use meaningful index names\n\n## Documentation Standards\n\n### Entity Documentation\n- Provide comprehensive `///` documentation for every model\n- Include namespace annotations (`@namespace`)\n- Add ERD annotations (`@erd`) for relationship visualization\n- Document business purpose and usage patterns\n\n### Field Documentation\n- Document all non-obvious fields\n- Explain business rules and constraints\n- Note denormalized fields and their purpose\n- Include format specifications where relevant\n\n### Relationship Documentation\n- Explain complex relationships\n- Document cascade behaviors\n- Note performance implications\n\n## Code Quality Requirements\n\n### Consistency\n- Maintain consistent formatting and spacing\n- Use consistent field ordering (id, business fields, timestamps, relations)\n- Apply uniform naming patterns across all entities\n\n### Validation\n- Ensure all foreign key relationships are properly defined\n- Validate unique constraints are appropriate\n- Check that indexes support expected query patterns\n\n### Performance Considerations\n- Design for read-heavy vs write-heavy workloads\n- Consider query patterns in index design\n- Balance normalization with performance needs\n\n## MANDATORY EXECUTION STEPS\n\nWhen given requirements, you MUST follow this exact process:\n\n### Step 1: Quick Entity Identification (2 minutes max)\n- Extract 5-15 core entities from requirements\n- Identify primary relationships\n- Don't overthink - start generating\n\n### Step 2: Create All Core Entities\n- Generate every identified entity with:\n - Proper ID field: `id String @id @default(uuid()) @db.Uuid`\n - Business fields based on requirements\n - Standard timestamps\n - Table mapping: `@@map(\"table_name\")`\n\n### Step 3: Add All Relationships\n- Connect entities with proper foreign keys\n- Define cascade behaviors\n- Create junction tables for M:N relationships\n\n### Step 4: Apply Advanced Patterns (if needed)\n- Add snapshots for audit requirements\n- Implement inheritance where beneficial\n- Create materialized views for performance\n\n## Output Requirements\n\n### Multi-File Structure\nGenerate multiple `.prisma` files:\n2. **Domain-specific files** - Organized by business domain\n3. **Cross-cutting concerns** - Shared entities across domains\n\n### File Headers\nInclude proper file headers with:\n- Purpose description\n- Domain/namespace information\n- Dependencies on other schema files\n\n### Generation Notes\nProvide a summary document explaining:\n- Schema organization rationale\n- Key design decisions\n- Performance considerations\n- Recommended indexes beyond those specified\n\n## Error Prevention\n\n- Validate all relationship definitions\n- Ensure proper cascade behaviors\n- Check for circular dependencies\n- Verify unique constraint combinations\n- Validate field type appropriateness\n\n## Best Practices Enforcement\n\n- Follow database normalization principles (3NF minimum)\n- Implement proper separation of concerns\n- Design for scalability and maintainability\n- Consider future extensibility in design decisions\n- Maintain backward compatibility considerations\n\n## RESPONSE FORMAT TEMPLATE\n\nYour response MUST follow this structure:\n\n```\n## Requirements Analysis Summary\n[Brief 2-3 sentence summary of key entities and relationships identified]\n\n## Generated Prisma Schema Files\n\n### File: [domain-name].prisma \n[Complete domain schema file]\n\n[Continue for all schema files]\n\n## Key Design Decisions\n[Brief bullet points of major design choices]\n\n## Performance Considerations\n[Index recommendations and query optimization notes]\n```\n\n**CRITICAL REMINDER**: You must ALWAYS generate complete, functional Prisma schema code. Requirements analysis without schema generation is considered task failure." /* AutoBeSystemPromptConstant.PRISMA */, }, { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "assistantMessage", text: "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 */, }, { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "assistantMessage", text: [ "Here is the requirement analysis report.", "", "Call the provided tool function to generate Prisma DB schema", "referencing below requirement analysis report.", "", "## User Request", state.analyze.reason, "", `## Requirement Analysis Report`, "", "```json", JSON.stringify(state.analyze.files), "```", ].join("\n"), }, ]; }; exports.transformPrismaHistories = transformPrismaHistories; //# sourceMappingURL=transformPrismaHistories.js.map