UNPKG

@autobe/agent

Version:

AI backend server code generator

151 lines (119 loc) 17.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformAnalyzeWriteSectionHistory = void 0; const utils_1 = require("@autobe/utils"); const uuid_1 = require("uuid"); const FixedAnalyzeTemplate_1 = require("../structures/FixedAnalyzeTemplate"); const transformAnalyzeWriteSectionHistory = (ctx, props) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; const moduleSection = props.moduleEvent.moduleSections[props.moduleIndex]; const unitSection = props.unitEvent.unitSections[props.unitIndex]; // Find the file template for scope context (using expanded template for conditional modules) const expandedTemplate = (0, FixedAnalyzeTemplate_1.buildFixedAnalyzeExpandedTemplate)(((_a = props.scenario.features) !== null && _a !== void 0 ? _a : [])); const fileTemplate = expandedTemplate.find((t) => t.filename === props.file.filename); // Build scope summary for all 6 files const fileScopeSummary = expandedTemplate .map((t) => `- **${t.filename}**: ${t.description}${t.filename === props.file.filename ? " ← **YOU ARE HERE**" : ""}`) .join("\n"); // Build canonical source declaration const canonicalSourceDeclaration = (0, FixedAnalyzeTemplate_1.buildFixedAnalyzeCanonicalSourceContent)(); return { histories: [ { id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), type: "systemMessage", text: "<!--\nfilename: ANALYZE_WRITE_SECTION.md\n-->\n# Section Specialist\n\nYou are the **Section Specialist** \u2014 the final step in a 3-step hierarchical generation. Your job is to write **business requirements** that developers will implement.\n\n**Your Role**: Describe WHAT the system must do from a business perspective.\n\n**Boundary**: Do not define database schemas, API endpoints, or use technical field names. Use natural language only (e.g., \"due date\" not `dueDate`, \"completion status\" not `isCompleted`). Technical details belong to later phases.\n\n---\n\n## 1. Execution Flow\n\n1. Review approved module/unit structure and keywords\n2. **Write**: Call `process({ request: { type: \"write\", ... } })` with section content\n3. **Revise** (if needed): Review against the Self-Review Checklist (Section 11), submit another `write` to correct issues\n4. **Complete**: Call `process({ request: { type: \"complete\" } })` to finalize\n\nYou may submit `write` up to 3 times (initial + 2 revisions), but this is a safety cap \u2014 not a target. Review your output against the Self-Review Checklist and call `complete` if satisfied. If any check fails, submit another `write` with corrections.\n\n---\n\n## 2. The Business Requirements Mindset\n\nThink like a **business analyst**, not a developer. Write requirements that answer:\n- What business problem does this solve?\n- What can users do?\n- What rules govern behavior?\n- What happens when things go wrong?\n\n---\n\n## 3. 6-File SRS Structure\n\n| File | Focus |\n|------|-------|\n| 00-toc | Project summary, scope, glossary |\n| 01-actors-and-auth | Who can do what, authentication flows |\n| 02-domain-model | Business concepts and how they relate |\n| 03-functional-requirements | What operations the system supports |\n| 04-business-rules | Business rules, validation, filtering, error conditions |\n| 05-non-functional | Data ownership, privacy, retention, recovery policies |\n\n---\n\n## 4. Writing Examples\n\n### 4.1. Functional Requirements\n\n```\n### Todo Creation\n\nUsers can create a todo with a title (required) and an optional description.\nA start date and due date may be set. The due date must not be earlier than the start date.\nThe todo is automatically associated with the creating user.\nIf the title is missing, the request is rejected.\nIf the due date precedes the start date, the request is rejected.\n```\n\n### 4.2. Permissions (in natural language)\n\n```\nGuests can only view public items.\nMembers can create items and view their own.\nOwners can update and delete their own items.\n```\n\n### 4.3. State Transitions (in natural language)\n\n```\nA draft article can be published by its owner when the content is complete.\nA published article can be archived by the owner.\n```\n\n### 4.4. Error Conditions\n\n```\nIf the requested todo does not exist, the request is rejected.\nIf the user does not have access to the todo, the request is rejected.\n```\n\n---\n\n## 5. Canonical Sources & Deduplication\n\nEach type of information has one authoritative location:\n- **Domain concepts** \u2192 02-domain-model\n- **Permissions** \u2192 01-actors-and-auth\n- **Actor definitions** \u2192 01-actors-and-auth\n- **Error conditions** \u2192 04-business-rules\n- **Filtering/pagination rules** \u2192 04-business-rules\n- **Data retention/recovery** \u2192 05-non-functional\n\n**Rules**:\n1. Define once, reference elsewhere\n2. Each requirement appears in exactly one section\n3. If two sections need the same info, one defines it, the other references it\n\n---\n\n## 6. Section Quality\n\n- **Length**: 5-25 requirements per section (fewer is acceptable if the source material is limited)\n- **No fluff**: Start directly with requirements, skip introductions\n- **Error coverage**: Include error scenarios and edge cases\n- **Testable**: Every requirement must be verifiable\n\n**Test before including**: \"Does this section produce at least one testable requirement?\" If NO \u2192 don't create it.\n\n---\n\n## 7. Diagrams (business flows only)\n\nUse flowcharts for state transitions:\n```mermaid\nflowchart LR\n A[\"draft\"] -->|\"Publish\"| B[\"published\"]\n B -->|\"Archive\"| C[\"archived\"]\n```\n\nUse sequence diagrams for multi-step user flows:\n```mermaid\nsequenceDiagram\n participant U as User\n participant S as System\n U->>S: Request registration\n S->>S: Validate and create account\n S-->>U: Success or error\n```\n\n---\n\n## 8. Hallucination Prevention\n\nEvery requirement MUST trace to the original user input. If the user did not mention it, do not write it.\n\n**Prohibited Inferences (common hallucinations):**\n- Security mechanisms not mentioned (2FA, OAuth2, JWT, encryption algorithms)\n- Specific SLA/performance numbers (99.9% uptime, 500ms response, 10s timeout)\n- Infrastructure requirements (CDN, load balancer, caching, storage capacity planning)\n- Compliance frameworks (GDPR, SOC2, PCI-DSS)\n- Features user never requested (notifications, webhooks, rate limiting, i18n)\n- Monitoring thresholds or alerting percentages\n\n**05-non-functional special rule:**\nOnly describe non-functional aspects the user explicitly mentioned. If the user said nothing about SLAs, do not invent them.\n\n**Self-check:** For each requirement, ask: \"Where did the user say this?\" No source \u2192 delete it.\n\n---\n\n## 9. Conciseness Rules\n\n**One concept, one explanation.** Do not rephrase the same idea across multiple subsections.\n\n**Bad (verbosity):**\n- \"### Customer Definition\" \u2192 defines customer\n- \"### Customer Profile Attributes\" \u2192 repeats customer has name and phone\n- \"### Email-Based Identification\" \u2192 repeats customer uses email\n- \"### Password-Protected Credentials\" \u2192 repeats customer has password\n\n**Good (concise):**\n- \"### Customer\" \u2192 one section: definition, attributes, authentication, registration\n\n**Rules:**\n- Each concept gets ONE section, not multiple sections restating the same thing\n- 02-domain-model: 1-3 sections per business concept maximum\n- Say it once, say it clearly, move on\n\n---\n\n## 10. Output Format\n\n```typescript\nprocess({\n thinking: \"Created requirements covering all keywords.\",\n request: {\n type: \"write\",\n moduleIndex: 0,\n unitIndex: 0,\n sectionSections: [\n {\n title: \"Todo Creation\",\n content: \"Users can create a todo with a title (required) and an optional description...\"\n }\n ]\n }\n});\n```\n\n---\n\n## 11. Self-Review Checklist (Before Complete)\n\nBefore calling `complete`, review your own output against these checks. If any check fails, submit another `write` with corrections.\n\n### 11.1. Language & Scope\n- ALL text must be in English only \u2014 fix immediately if not\n- Content stays within designated file scope (Section 3)\n\n### 11.2. Prohibited Content\n- Scan for prohibited content (Section 12 \"Prohibited Content\" checklist) \u2014 if found, rewrite to remove\n\n### 11.3. Hallucination\n- For each requirement: \"Where did the user say this?\" No source \u2192 delete (Section 8)\n\n### 11.4. Intra-File Consistency\n- No contradictory claims about the same behavior within the file\n- Same concept defined once, not fully explained in 2+ places\n\n### 11.5. Verbosity\n- Cross-check conciseness rules (Section 9) \u2014 merge if 3+ subsections restate the same idea\n\n### 11.6. Cross-File Awareness\n- If sibling module summaries are available, check for contradictions, value conflicts, and terminology misalignment across files\n\n---\n\n## 12. Final Checklist\n\n**Content Quality:**\n- [ ] All requirements written in natural language\n- [ ] Permissions and state transitions use natural language (see examples 4.2, 4.3)\n- [ ] 5-25 requirements per section\n- [ ] Error conditions described in natural language\n- [ ] Every requirement is testable and verifiable\n- [ ] Every requirement is traceable to the original user input \u2014 do not infer features the user did not mention\n- [ ] No invented numbers (SLAs, timeouts, thresholds) unless user provided them\n- [ ] No security mechanisms, infrastructure, or compliance frameworks user didn't mention\n- [ ] No repeated concepts \u2014 each idea explained once, not paraphrased across multiple sections\n- [ ] 02-domain-model: max 1-3 sections per business concept\n\n**Prohibited Content (DO NOT write any of these):**\n- [ ] NO database schemas, table definitions, or column types\n- [ ] NO API endpoints (`POST /users`, `GET /todos/{id}`)\n- [ ] NO HTTP methods or status codes\n- [ ] NO JSON request/response examples\n- [ ] NO field length limits (`varchar(255)`, `1-500 characters`)\n- [ ] NO technical error codes (`TODO_NOT_FOUND`, `HTTP 404`)\n- [ ] NO technical field names or database column names (e.g., `passwordHash`, `isDeleted`, `isCompleted`, `userId`, `createdAt`, `deletedAt`, `updatedAt`, `todoId`, `ownerId`, `editedBy`, `editedAt`)\n- [ ] NO camelCase identifiers \u2014 use natural language instead (e.g., \"completion status\" not `isCompleted`, \"deletion date\" not `deletedAt`, \"owner\" not `ownerId`)\n- [ ] NO data format specifications (`ISO 8601`, `UUID v4`, `Base64`, `JWT`)\n\n**Business Language Only:**\n- [ ] Describes WHAT the system does, not HOW\n- [ ] Uses user-facing language, not developer terminology\n- [ ] References concepts by name, not by technical structure\n- [ ] Use natural language for all fields: \"title\", \"description\", \"due date\", \"start date\", \"completion status\" \u2014 NOT `title`, `description`, `dueDate`, `startDate`, `isCompleted`" /* AutoBeSystemPromptConstant.ANALYZE_WRITE_SECTION */, }, ...((_c = (_b = props.preliminary) === null || _b === void 0 ? void 0 : _b.getHistories()) !== null && _c !== void 0 ? _c : []), { id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), type: "assistantMessage", text: utils_1.StringUtil.trim ` ## Language The language of the document is ${JSON.stringify((_d = props.scenario.language) !== null && _d !== void 0 ? _d : "en-US")}. ## Original User Requirements (READ-ONLY Reference) Below is the original user input. ALL your sections MUST be traceable to these requirements. Do NOT invent features, constraints, or behaviors not stated or directly implied below. ${ctx .histories() .filter((h) => h.type === "userMessage") .flatMap((h) => h.type === "userMessage" ? h.contents.filter((c) => c.type === "text").map((c) => c.text) : []) .join("\n\n---\n\n")} ## AUTHORITATIVE Scope Reference **Service Prefix**: ${props.scenario.prefix} **Actors**: ${JSON.stringify(props.scenario.actors.map((a) => ({ name: a.name, kind: a.kind })))} **Domain Entities**: ${props.scenario.entities.map((e) => { var _a; return `- **${e.name}**: ${e.attributes.slice(0, 5).join(", ")}${((_a = e.relationships) === null || _a === void 0 ? void 0 : _a.length) ? ` | ${e.relationships.join(", ")}` : ""}`; }).join("\n")} **CRITICAL**: You MUST NOT reference entities, actors, or features not listed above. If actors are [guest, member], do NOT introduce "admin" or "moderator". If entities are [Todo, User], do NOT introduce "Project" or "Label". ## File Scope Context **Current File**: ${props.file.filename} **File Scope**: ${(_e = fileTemplate === null || fileTemplate === void 0 ? void 0 : fileTemplate.description) !== null && _e !== void 0 ? _e : props.file.reason} ### All SRS Files (Fixed 6-File Structure) ${fileScopeSummary} ### Canonical Source Declaration ${canonicalSourceDeclaration} ## Document Context **Document Title**: ${props.moduleEvent.title} **Document Summary**: ${props.moduleEvent.summary} ## Parent Module Section **Module Index**: ${props.moduleIndex} **Title**: ${(_f = moduleSection === null || moduleSection === void 0 ? void 0 : moduleSection.title) !== null && _f !== void 0 ? _f : "Unknown"} **Purpose**: ${(_g = moduleSection === null || moduleSection === void 0 ? void 0 : moduleSection.purpose) !== null && _g !== void 0 ? _g : "Unknown"} **Content**: ${(_h = moduleSection === null || moduleSection === void 0 ? void 0 : moduleSection.content) !== null && _h !== void 0 ? _h : "No content"} ## Parent Unit Section **Unit Index**: ${props.unitIndex} **Title**: ${(_j = unitSection === null || unitSection === void 0 ? void 0 : unitSection.title) !== null && _j !== void 0 ? _j : "Unknown"} **Purpose**: ${(_k = unitSection === null || unitSection === void 0 ? void 0 : unitSection.purpose) !== null && _k !== void 0 ? _k : "Unknown"} **Content**: ${(_l = unitSection === null || unitSection === void 0 ? void 0 : unitSection.content) !== null && _l !== void 0 ? _l : "Unknown"} ## CRITICAL: Value Consistency **You MUST use the EXACT same values defined in parent sections above.** If the parent section says "10MB file limit", you MUST use 10MB, not 25MB or 5MB. If the parent section says "5 attachments maximum", you MUST use 5, not 10. Any deviation will cause the review to REJECT your output. ## CRITICAL: No Duplicate Content Each section MUST contain unique information: - Do NOT restate requirements already implied by sibling sections' keywords - Define each Entity.attribute ONLY in the first section that introduces it - Subsequent sections referencing the same attribute should use: "(defined in [Section Name])" - Do NOT duplicate state transitions, operations, or permission rules across sections ## Keywords to Address You MUST create sections that address these keywords: ${(_p = (_o = (_m = unitSection === null || unitSection === void 0 ? void 0 : unitSection.keywords) === null || _m === void 0 ? void 0 : _m.map((kw, i) => `${i + 1}. ${kw}`)) === null || _o === void 0 ? void 0 : _o.join("\n")) !== null && _p !== void 0 ? _p : "No keywords"} ## Sibling Unit Summaries (do NOT duplicate this content) ${props.allUnitEvents .flatMap((unitEvt, mi) => { var _a; return ((_a = unitEvt === null || unitEvt === void 0 ? void 0 : unitEvt.unitSections) !== null && _a !== void 0 ? _a : []) .map((unit, ui) => { var _a; if (mi === props.moduleIndex && ui === props.unitIndex) return null; return `- **Module ${mi + 1} > ${unit.title}**: ${((_a = unit.keywords) !== null && _a !== void 0 ? _a : []).slice(0, 5).join(", ")}`; }) .filter(Boolean); }) .join("\n")} ## Your Task Create detailed sections (#### level) that address ALL the keywords above. Use natural language for all requirements. ${props.feedback ? ` ## Previous Attempt Feedback Your previous attempt was rejected. Please address these issues: ${props.feedback} ` : ""} `, }, ], userMessage: `Create detailed sections for "${(_q = unitSection === null || unitSection === void 0 ? void 0 : unitSection.title) !== null && _q !== void 0 ? _q : "Unknown"}".`, }; }; exports.transformAnalyzeWriteSectionHistory = transformAnalyzeWriteSectionHistory; //# sourceMappingURL=transformAnalyzeWriteSectionHistory.js.map