sweagent 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +829 -1072
- package/dist/index.cjs +341 -449
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +504 -966
- package/dist/index.d.ts +504 -966
- package/dist/index.js +341 -449
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/utils/errors.ts","../src/lib/utils/json-parse.ts","../src/lib/utils/logger.ts","../src/lib/utils/utils.ts","../src/lib/tools/tools.ts","../src/lib/agents/agent-observers.ts","../src/lib/agents/agent.ts","../src/lib/models/providers/base.ts","../src/lib/models/providers/openai.ts","../src/lib/models/providers/anthropic.ts","../src/lib/models/providers/google.ts","../src/lib/models/create-model.ts","../src/lib/subagents/subagent.ts","../src/lib/template-engine/compiler.ts","../src/lib/mcp/transports.ts","../src/lib/mcp/client.ts","../src/modules/hello-world/tool.ts","../src/modules/hello-world/agent.ts","../src/modules/db-designer/schemas/field.schema.ts","../src/modules/db-designer/schemas/module.schema.ts","../src/modules/db-designer/schemas/project.schema.ts","../src/modules/db-designer/prompts/system.prompt.ts","../src/modules/db-designer/prompts/design.prompt.ts","../src/modules/db-designer/prompts/redesign.prompt.ts","../src/modules/db-designer/tools/validate-schema.tool.ts","../src/modules/db-designer/tools/design-database.tool.ts","../src/modules/db-designer/tools/design-database-pro.tool.ts","../src/modules/db-designer/tools/redesign-database.tool.ts","../src/modules/db-designer/tools/index.ts","../src/modules/db-designer/subagents/entity-analyzer.subagent.ts","../src/modules/db-designer/subagents/schema-refiner.subagent.ts","../src/modules/db-designer/agent.ts","../src/modules/react-builder/schemas/branding.schema.ts","../src/modules/react-builder/schemas/app-config.schema.ts","../src/modules/react-builder/schemas/field.schema.ts","../src/modules/react-builder/schemas/page.schema.ts","../src/modules/react-builder/schemas/application.schema.ts","../src/modules/react-builder/schemas/user.schema.ts","../src/modules/react-builder/prompts/system.prompt.ts","../src/modules/react-builder/prompts/instruction.prompt.ts","../src/modules/react-builder/prompts/examples.prompt.ts","../src/modules/react-builder/prompts/feedback.prompt.ts","../src/modules/react-builder/tools/validate-frontend-config.tool.ts","../src/modules/react-builder/tools/generate-frontend.tool.ts","../src/modules/react-builder/tools/generate-feature-breakdown.tool.ts","../src/modules/react-builder/tools/scaffold-vite.ts","../src/modules/react-builder/tools/index.ts","../src/modules/react-builder/subagents/graphql-analyzer.subagent.ts","../src/modules/react-builder/subagents/config-validator.subagent.ts","../src/modules/react-builder/agent.ts","../src/modules/requirement-gatherer/schemas/actor.schema.ts","../src/modules/requirement-gatherer/schemas/flow.schema.ts","../src/modules/requirement-gatherer/schemas/story.schema.ts","../src/modules/requirement-gatherer/schemas/module.schema.ts","../src/modules/requirement-gatherer/schemas/database.schema.ts","../src/modules/requirement-gatherer/schemas/api-design.schema.ts","../src/modules/requirement-gatherer/schemas/context.schema.ts","../src/modules/requirement-gatherer/schemas/requirement.schema.ts","../src/modules/requirement-gatherer/prompts/system.prompt.ts","../src/modules/requirement-gatherer/prompts/discovery.prompt.ts","../src/modules/requirement-gatherer/prompts/requirements.prompt.ts","../src/modules/requirement-gatherer/prompts/design.prompt.ts","../src/modules/requirement-gatherer/prompts/synthesis.prompt.ts","../src/modules/requirement-gatherer/context.ts","../src/modules/requirement-gatherer/stages/base.ts","../src/modules/requirement-gatherer/stages/discovery.stage.ts","../src/modules/requirement-gatherer/stages/requirements-invoke.ts","../src/modules/requirement-gatherer/stages/requirements.stage.ts","../src/modules/requirement-gatherer/stages/design.stage.ts","../src/modules/requirement-gatherer/stages/synthesis.stage.ts","../src/modules/requirement-gatherer/stages/discovery.state.ts","../src/modules/requirement-gatherer/stages/requirements.state.ts","../src/modules/requirement-gatherer/stages/design.state.ts","../src/modules/requirement-gatherer/stages/synthesis.state.ts","../src/modules/requirement-gatherer/stages/state-registry.ts","../src/modules/requirement-gatherer/router.ts","../src/modules/requirement-gatherer/chat.ts","../src/modules/requirement-gatherer/agent.ts","../src/modules/requirement-gatherer/context-builder.ts","../src/modules/planning/context.ts","../src/modules/planning/stages/base.ts","../src/modules/planning/prompts/system.prompt.ts","../src/modules/planning/prompts/discovery.prompt.ts","../src/modules/planning/prompts/requirements.prompt.ts","../src/modules/planning/prompts/design.prompt.ts","../src/modules/planning/prompts/synthesis.prompt.ts","../src/modules/planning/prompts/edit.prompt.ts","../src/modules/planning/stages/discovery.stage.ts","../src/modules/planning/stages/discovery.state.ts","../src/modules/data-modeler/subagents/entity-analyzer.ts","../src/modules/data-modeler/subagents/relationship-mapper.ts","../src/modules/data-modeler/subagents/schema-refiner.ts","../src/modules/frontend-architect/subagents/page-planner.ts","../src/modules/frontend-architect/subagents/component-analyzer.ts","../src/modules/frontend-architect/subagents/framework-selector.ts","../src/modules/auth-designer/subagents/security-analyzer.ts","../src/modules/auth-designer/subagents/flow-designer.ts","../src/modules/planning/stages/requirements.stage.ts","../src/modules/planning/stages/requirements.state.ts","../src/modules/api-designer/subagents/endpoint-analyzer.ts","../src/modules/api-designer/subagents/contract-designer.ts","../src/modules/planning/stages/design.stage.ts","../src/modules/planning/stages/design.state.ts","../src/modules/planning/writer.ts","../src/modules/execution-planner/subagents/edge-case-analyzer.ts","../src/modules/execution-planner/subagents/testing-strategist.ts","../src/modules/planning/stages/synthesis.stage.ts","../src/modules/planning/stages/synthesis.state.ts","../src/modules/planning/stages/state-registry.ts","../src/modules/planning/router.ts","../src/modules/planning/chat.ts","../src/modules/planning/agent.ts","../src/modules/planning/edit-agent.ts","../src/modules/planning/context-builder.ts","../src/modules/data-modeler/schemas/data-model.schema.ts","../src/modules/data-modeler/prompts/system.prompt.ts","../src/modules/data-modeler/prompts/design.prompt.ts","../src/modules/data-modeler/prompts/pro-design.prompt.ts","../src/modules/data-modeler/tools/validate-schema.ts","../src/modules/data-modeler/tools/design-schema.ts","../src/modules/data-modeler/tools/design-schema-pro.ts","../src/modules/data-modeler/tools/refine-schema.ts","../src/modules/data-modeler/tools/index.ts","../src/modules/data-modeler/agent.ts","../src/modules/api-designer/schemas/api-design.schema.ts","../src/modules/api-designer/prompts/system.prompt.ts","../src/modules/api-designer/prompts/design.prompt.ts","../src/modules/api-designer/tools/validate-api.ts","../src/modules/api-designer/tools/design-api.ts","../src/modules/api-designer/tools/design-api-pro.ts","../src/modules/api-designer/tools/index.ts","../src/modules/api-designer/agent.ts","../src/modules/auth-designer/schemas/auth-design.schema.ts","../src/modules/auth-designer/prompts/system.prompt.ts","../src/modules/auth-designer/prompts/design.prompt.ts","../src/modules/auth-designer/tools/validate-auth.ts","../src/modules/auth-designer/tools/design-auth.ts","../src/modules/auth-designer/tools/index.ts","../src/modules/auth-designer/agent.ts","../src/modules/frontend-architect/schemas/frontend-design.schema.ts","../src/modules/frontend-architect/prompts/system.prompt.ts","../src/modules/frontend-architect/prompts/design.prompt.ts","../src/modules/frontend-architect/tools/validate-frontend.ts","../src/modules/frontend-architect/tools/design-frontend.ts","../src/modules/frontend-architect/tools/index.ts","../src/modules/frontend-architect/agent.ts","../src/modules/execution-planner/schemas/execution-plan.schema.ts","../src/modules/execution-planner/prompts/system.prompt.ts","../src/modules/execution-planner/prompts/design.prompt.ts","../src/modules/execution-planner/tools/validate-plan.ts","../src/modules/execution-planner/tools/create-plan.ts","../src/modules/execution-planner/tools/index.ts","../src/modules/execution-planner/agent.ts","../src/modules/backend-architect/schemas/backend-design.schema.ts","../src/modules/backend-architect/prompts/system.prompt.ts","../src/modules/backend-architect/prompts/design.prompt.ts","../src/modules/backend-architect/tools/validate-backend.ts","../src/modules/backend-architect/tools/design-backend.ts","../src/modules/backend-architect/tools/index.ts","../src/modules/backend-architect/subagents/service-planner.ts","../src/modules/backend-architect/subagents/framework-selector.ts","../src/modules/backend-architect/agent.ts","../src/modules/apollo-builder/schemas/subgraph-config.schema.ts","../src/modules/apollo-builder/prompts/system.prompt.ts","../src/modules/apollo-builder/prompts/design.prompt.ts","../src/modules/apollo-builder/tools/validate-subgraph.ts","../src/modules/apollo-builder/tools/generate-subgraph.ts","../src/modules/apollo-builder/tools/scaffold-subgraph.ts","../src/modules/apollo-builder/tools/index.ts","../src/modules/apollo-builder/subagents/schema-generator.ts","../src/modules/apollo-builder/subagents/resolver-planner.ts","../src/modules/apollo-builder/agent.ts","../src/modules/express-builder/schemas/express-config.schema.ts","../src/modules/express-builder/prompts/system.prompt.ts","../src/modules/express-builder/prompts/design.prompt.ts","../src/modules/express-builder/tools/validate-express.ts","../src/modules/express-builder/tools/generate-express.ts","../src/modules/express-builder/tools/scaffold-express.ts","../src/modules/express-builder/tools/index.ts","../src/modules/express-builder/subagents/route-generator.ts","../src/modules/express-builder/subagents/middleware-configurator.ts","../src/modules/express-builder/agent.ts","../src/modules/nextjs-builder/schemas/nextjs-config.schema.ts","../src/modules/nextjs-builder/prompts/system.prompt.ts","../src/modules/nextjs-builder/prompts/design.prompt.ts","../src/modules/nextjs-builder/tools/validate-nextjs.ts","../src/modules/nextjs-builder/tools/generate-nextjs.ts","../src/modules/nextjs-builder/tools/index.ts","../src/modules/nextjs-builder/subagents/route-planner.ts","../src/modules/nextjs-builder/subagents/api-route-generator.ts","../src/modules/nextjs-builder/agent.ts"],"names":["LibraryError","message","cause","ModelError","provider","ToolError","toolName","ValidationError","errors","AgentError","iteration","SubagentError","subagentName","extractJson","text","trimmed","codeBlock","parseModelJsonResponse","schema","jsonStr","parsed","err","preview","result","issues","i","safeJsonParse","label","NOOP_LOGGER","createLogger","config","name","level","pretty","file","stream","destination","streamFd","pinoLogger","pino","targets","transport","wrapPino","loggerConfigFromEnv","overrides","raw","enabledRaw","enabled","levelRaw","streamRaw","prettyRaw","p","msg","data","bindings","emptyDetails","emptyOutputDetails","sumTokenUsage","usages","inputTokens","outputTokens","totalTokens","usage","defineTool","description","inputSchema","handler","tool","args","e","createToolSet","tools","getTools","toolSet","getTool","executeTool","toolImpl","input","options","logger","out","executeToolByName","notifyObserversStep","observers","step","o","notifyObserversTool","notifyObserversError","error","runAgent","model","systemPrompt","maxIterations","onStep","messages","steps","response","s","tc","assistantContent","toolResults","toolCall","execResult","agentResult","outputVal","createAIModel","params","modelName","getModel","schemaOnlyTools","t","_execute","rest","generateText","toolCalls","prompt","images","content","img","schemaWrapped","zodSchema","generateObject","createOpenAIModel","apiKey","baseUrl","createOpenAI","createAnthropicModel","createAnthropic","createGoogleModel","createGoogleGenerativeAI","createModel","NAME_REGEX","defineSubagent","resolveTools","definition","parentTools","base","disallowed","filtered","key","runSubagent","parentModel","createSubagentTool","z","createSubagentToolSet","definitions","def","compileTemplate","template","context","Handlebars","findHbsFiles","dir","results","W","entries","entry","fullPath","ie","toOutputPath","hbsRelPath","shouldSkip","relativePath","skipPatterns","pattern","scaffoldProject","templateDir","outputDir","hbsFiles","files","hbsFile","outputRelPath","inputPath","outputPath","templateSource","compiled","registerHelpers","a","b","obj","str","_","c","getSdkRoot","createRequire","path","sdkRoot","parseToolResult","first","createHttpTransport","url","headers","modPath","mod","pathToFileURL","requestInit","createStdioTransport","command","BaseMcpClient","info","resolveOpts","envPrefix","serverLabel","apiKeyHeader","argsEnv","client","Client","helloWorldTool","DEFAULT_SYSTEM_PROMPT","runHelloWorldAgent","modelConfig","fieldSchema","n","moduleSchema","v","ctx","issue","projectSchema","DB_DESIGN_SYSTEM_PROMPT","createDbDesignPrompt","requirement","formatUserTypes","actors","actor","index","goals","g","formatUserFlows","flows","flow","actorName","formatUserStories","stories","storiesByFlow","story","flowStories","sections","preconditions","postconditions","dataInvolved","d","storyText","orphanStories","f","formatTechnicalRequirements","tech","lines","extractDataEntities","entities","extractRoles","buildPromptVariables","createProDbDesignPrompt","vars","createRedesignPrompt","existingSchema","userFeedback","validateSchemaTool","createDesignDatabaseTool","userPrompt","structuredInputSchema","createDesignDatabaseProTool","dbDesign","metadata","createRedesignDatabaseTool","feedback","createDbDesignerTools","ENTITY_ANALYZER_SYSTEM_PROMPT","entityAnalyzerSubagent","SCHEMA_REFINER_SYSTEM_PROMPT","createSchemaRefinerSubagent","ORCHESTRATOR_SYSTEM_PROMPT","runDbDesignerAgent","dbTools","schemaRefiner","subagentTools","BrandingSchema","AppConfigSchema","ValidationSchema","FieldOptionsSchema","FormFieldSchema","ColumnSchema","ApiResponseTypeSchema","ListingPageApiSchema","AuthPageApiSchema","DrawerSchema","AuthPageSchema","ListingPageSchema","PageSchema","ModuleSchema","ApplicationSchema","LoginInputSchema","SpecializationSchema","UserSchema","CreateUserInputSchema","UpdateUserInputSchema","ForgotPasswordSchema","ResetPasswordSchema","REACT_BUILDER_SYSTEM_PROMPT","REACT_BUILDER_INSTRUCTION","buildInstructionPrompt","EXAMPLE_GRAPHQL_SCHEMA","EXAMPLE_JSON_OUTPUT","buildExampleShotPrompt","buildFeedbackPrompt","schemaFile","validateFrontendConfigTool","buildGeneratePrompt","graphqlSchema","appInfo","instruction","example","appInfoBlock","createGenerateFrontendTool","createGenerateFeatureBreakdownTool","toTemplateContext","m","scaffoldViteTool","us","createReactBuilderTools","GRAPHQL_ANALYZER_SYSTEM_PROMPT","graphqlAnalyzerSubagent","CONFIG_VALIDATOR_SYSTEM_PROMPT","createConfigValidatorSubagent","runReactBuilderAgent","reactTools","configValidator","actorSchema","actorsResultSchema","flowSchema","flowsResultSchema","storySchema","storiesResultSchema","crudApiSchema","extractedModuleSchema","modulesResultSchema","entityFieldSchema","entityIndexSchema","entityRelationSchema","databaseEntitySchema","databaseDesignSchema","httpMethodSchema","optionalStringRecordSchema","k","restEndpointSchema","restApiDesignSchema","graphqlTypeFieldSchema","graphqlKindSchema","graphqlTypeDefinitionSchema","graphqlOperationArgSchema","graphqlOperationSchema","graphqlApiDesignSchema","apiStyleSchema","apiDesignSchema","projectBriefSchema","questionSchema","chatEntrySchema","requirementContextSchema","requirementSummarySchema","finalRequirementSchema","REQUIREMENT_GATHERER_SYSTEM_PROMPT","DISCOVERY_SYSTEM_FRAGMENT","DISCOVERY_USER_PROMPT","buildDiscoveryPrompt","userMessage","history","PROJECT_BLOCK","EXTRACT_ACTORS_PROMPT","GENERATE_FLOWS_PROMPT","GENERATE_STORIES_PROMPT","EXTRACT_MODULES_PROMPT","buildExtractActorsPrompt","projectName","projectGoal","projectFeatures","buildGenerateFlowsPrompt","actorsJson","buildGenerateStoriesPrompt","flowsJson","buildExtractModulesPrompt","storiesJson","DESIGN_DB_PROMPT","DESIGN_APIS_PROMPT","DESIGN_DATABASE_SYSTEM_PROMPT","DESIGN_APIS_SYSTEM_PROMPT","buildDesignDatabasePrompt","projectBrief","modules","buildDesignApisPrompt","database","SYNTHESIS_SYSTEM_FRAGMENT","SYNTHESIS_USER_PROMPT","buildSynthesisPrompt","apiDesign","createInitialContext","mergeStageResult","addChatEntry","role","advanceStage","order","idx","next","summarizeModules","summarizeStories","safeParseJson","runDiscoveryStage","needsClarification","questions","q","validated","pb","getActors","_logger","getFlows","_actors","getStories","_flows","getModules","_stories","runRequirementsStage","_userMessage","brief","runDesignStage","projectBriefStr","modulesSummary","storiesSummary","actorsSummary","dbPrompt","dbMessages","dbResponse","dbJsonStr","dbParsed","databaseResult","apiPrompt","apiMessages","apiResponse","apiJsonStr","apiParsed","apiDesignResult","runSynthesisStage","finalRequirement","DiscoveryState","RequirementsState","DesignState","SynthesisState","states","getStateForStage","stage","runStage","merged","finalReq","STAGE_ORDER","processRequirementChat","runOne","runResult","nextStage","MAX_TURNS","runRequirementGathererAgent","lastResult","turns","output","DEFAULT_STAGE","RequirementContextBuilder","pendingQuestions","createRequirementContextBuilder","EMPTY_SECTIONS","newSections","projectDescription","isConfirmation","normalized","PLANNING_SYSTEM_PROMPT","CONTEXT_BLOCK","REQUIREMENTS_OVERVIEW_PROMPT","REQUIREMENTS_FEATURE_DATA_PROMPT","buildRequirementsOverviewPrompt","buildRequirementsFeatureDataPrompt","overviewAndTechStack","DESIGN_CONTEXT","DESIGN_IMPLEMENTATION_PROMPT","buildDesignImplementationPrompt","priorSections","apiRoutes","SYNTHESIS_CONTEXT","EDIT_PLAN_SYSTEM_PROMPT","buildEditPlanPrompt","existingPlan","hasProjectOverview","lower","hasOverview","userConfirmed","forceAdvance","advance","storeDescription","RELATIONSHIP_MAPPER_SYSTEM_PROMPT","relationshipMapperSubagent","PAGE_PLANNER_SYSTEM_PROMPT","pagePlannerSubagent","COMPONENT_ANALYZER_SYSTEM_PROMPT","componentAnalyzerSubagent","FRAMEWORK_SELECTOR_SYSTEM_PROMPT","frameworkSelectorSubagent","SECURITY_ANALYZER_SYSTEM_PROMPT","securityAnalyzerSubagent","FLOW_DESIGNER_SYSTEM_PROMPT","flowDesignerSubagent","invokeMarkdown","r","splitOverviewAndTechStack","splitFeatureDecisionsAndDataModels","part1","overview","techStack","part2","featureDecisions","dataModels","priorContext","pagesAndRoutes","fullContext","authFlow","ENDPOINT_ANALYZER_SYSTEM_PROMPT","endpointAnalyzerSubagent","CONTRACT_DESIGNER_SYSTEM_PROMPT","contractDesignerSubagent","gatherPriorSections","parts","contractResult","implementation","assemblePlan","writePlanToFile","markdown","writeFile","EDGE_CASE_ANALYZER_SYSTEM_PROMPT","edgeCaseAnalyzerSubagent","TESTING_STRATEGIST_SYSTEM_PROMPT","testingStrategistSubagent","gatherAllSections","extractProjectName","firstLine","match","executionPlan","edgeCases","testingChecklist","fullSections","fullMarkdown","processPlanningChat","planMarkdown","runPlanningAgent","continueMsg","editPlan","revised","PlanningContextBuilder","createPlanningContextBuilder","relationTypeSchema","dataEntitySchema","dbTypeSchema","dataModelDesignSchema","DATA_MODELER_SYSTEM_PROMPT","DESIGN_SCHEMA_PROMPT","REFINE_SCHEMA_PROMPT","buildDesignSchemaPrompt","buildRefineSchemaPrompt","PRO_DESIGN_PROMPT","buildProDesignPrompt","databaseType","createDesignSchemaTool","createDesignSchemaProTool","createRefineSchemaTools","createDataModelerTools","runDataModelerAgent","allTools","stringRecordSchema","stringOrObjectArraySchema","arr","API_DESIGNER_SYSTEM_PROMPT","DESIGN_API_PROMPT","PRO_DESIGN_API_PROMPT","buildDesignApiPrompt","buildProDesignApiPrompt","apiStyle","dataModel","validateApiTool","design","createDesignApiTool","createDesignApiProTool","createApiDesignerTools","runApiDesignerAgent","authFlowStepSchema","authFlowSchema","authMiddlewareSchema","roleDefinitionSchema","securityPolicySchema","authDesignSchema","AUTH_DESIGNER_SYSTEM_PROMPT","DESIGN_AUTH_PROMPT","buildDesignAuthPrompt","validateAuthTool","createDesignAuthTool","createAuthDesignerTools","runAuthDesignerAgent","formFieldSchema","pageDesignSchema","componentDesignSchema","frontendDesignSchema","FRONTEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_FRONTEND_PROMPT","buildDesignFrontendPrompt","validateFrontendTool","createDesignFrontendTool","createFrontendArchitectTools","reactBuilderSubagent","nextjsBuilderSubagent","runFrontendArchitectAgent","phaseStepSchema","implementationPhaseSchema","edgeCaseSchema","testChecklistItemSchema","executionPlanSchema","EXECUTION_PLANNER_SYSTEM_PROMPT","CREATE_EXECUTION_PLAN_PROMPT","buildCreateExecutionPlanPrompt","validateExecutionPlanTool","plan","createExecutionPlanTool","createExecutionPlannerTools","runExecutionPlannerAgent","ciEnum","values","middlewareSchema","serviceSchema","routeGroupSchema","backendDesignSchema","BACKEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_BACKEND_PROMPT","buildDesignBackendPrompt","validateBackendTool","createDesignBackendTool","createBackendArchitectTools","SERVICE_PLANNER_SYSTEM_PROMPT","servicePlannerSubagent","runBackendArchitectAgent","graphqlFieldSchema","graphqlTypeSchema","resolverOperationSchema","subgraphModuleSchema","subgraphConfigSchema","APOLLO_BUILDER_SYSTEM_PROMPT","DESIGN_SUBGRAPH_PROMPT","buildDesignSubgraphPrompt","validateSubgraphTool","createGenerateSubgraphTool","scaffoldSubgraphTool","ja","createApolloBuilderTools","SCHEMA_GENERATOR_SYSTEM_PROMPT","schemaGeneratorSubagent","RESOLVER_PLANNER_SYSTEM_PROMPT","resolverPlannerSubagent","runApolloBuilderAgent","routerMethodSchema","routerSchema","modelFieldSchema","modelSchema","middlewareConfigSchema","expressConfigSchema","EXPRESS_BUILDER_SYSTEM_PROMPT","DESIGN_EXPRESS_PROMPT","buildDesignExpressPrompt","validateExpressTool","createGenerateExpressTool","scaffoldExpressTool","za","createExpressBuilderTools","ROUTE_GENERATOR_SYSTEM_PROMPT","routeGeneratorSubagent","MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT","middlewareConfiguratorSubagent","runExpressBuilderAgent","nextjsPageSchema","nextjsLayoutSchema","nextjsApiRouteSchema","serverActionSchema","nextjsConfigSchema","NEXTJS_BUILDER_SYSTEM_PROMPT","DESIGN_NEXTJS_PROMPT","buildDesignNextjsPrompt","validateNextjsTool","createGenerateNextjsTool","createNextjsBuilderTools","ROUTE_PLANNER_SYSTEM_PROMPT","routePlannerSubagent","API_ROUTE_GENERATOR_SYSTEM_PROMPT","apiRouteGeneratorSubagent","runNextjsBuilderAgent"],"mappings":"igCAOO,IAAMA,EAAAA,CAAN,cAA2B,KAAM,CACtC,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAe,CAC1C,KAAA,CAAMD,CAAAA,CAASC,CAAAA,GAAU,MAAA,CAAY,MAAA,CAAY,CAAE,KAAA,CAAAA,CAAM,CAAC,CAAA,CAC1D,IAAA,CAAK,IAAA,CAAO,cAAA,CACRA,CAAAA,EAAO,KAAA,GACT,IAAA,CAAK,KAAA,CAAQ,CAAA,EAAG,IAAA,CAAK,KAAK;AAAA,WAAA,EAAgBA,CAAAA,CAAM,KAAK,CAAA,CAAA,EAEzD,CACF,EAKaC,EAAAA,CAAN,cAAyBH,EAAa,CAC3C,WAAA,CACEC,CAAAA,CACgBG,EAChBF,CAAAA,CACA,CACA,MAAMD,CAAAA,CAASC,CAAK,EAHJ,IAAA,CAAA,QAAA,CAAAE,CAAAA,CAIhB,IAAA,CAAK,IAAA,CAAO,aACd,CACF,EAKaC,CAAAA,CAAN,cAAwBL,EAAa,CAC1C,WAAA,CACEC,EACgBK,CAAAA,CAChBJ,CAAAA,CACA,C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Custom error classes for the library\n */\n\n/**\n * Base error class for all library errors\n */\nexport class LibraryError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'LibraryError';\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n}\n\n/**\n * Error thrown when model operations fail\n */\nexport class ModelError extends LibraryError {\n constructor(\n message: string,\n public readonly provider?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ModelError';\n }\n}\n\n/**\n * Error thrown when tool execution fails\n */\nexport class ToolError extends LibraryError {\n constructor(\n message: string,\n public readonly toolName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ToolError';\n }\n}\n\n/**\n * Error thrown when tool input validation fails\n */\nexport class ValidationError extends LibraryError {\n constructor(\n message: string,\n public readonly errors?: unknown[]\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Error thrown when agent execution fails\n */\nexport class AgentError extends LibraryError {\n constructor(\n message: string,\n public readonly iteration?: number,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'AgentError';\n }\n}\n\n/**\n * Error thrown when subagent execution fails\n */\nexport class SubagentError extends LibraryError {\n constructor(\n message: string,\n public readonly subagentName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'SubagentError';\n }\n}\n","/**\n * Shared utilities for extracting and parsing JSON from model responses.\n *\n * Models frequently wrap JSON in markdown code blocks or include extra text.\n * These helpers handle extraction, parsing, and Zod validation with clear errors\n * so the agent can retry on failure.\n */\n\nimport type { z } from 'zod';\n\n/**\n * Extract a JSON string from model output.\n * Handles markdown code blocks (```json ... ``` or ``` ... ```) and bare JSON.\n */\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\n/**\n * Parse a model text response as JSON then validate with a Zod schema.\n * Throws a descriptive error on failure (JSON syntax or validation) so the\n * wrapping ToolError gives the agent enough context to retry.\n */\nexport function parseModelJsonResponse<T>(text: string, schema: z.ZodType<T>): T {\n const jsonStr = extractJson(text);\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonStr);\n } catch (err) {\n const preview = jsonStr.length > 300 ? jsonStr.slice(0, 300) + '...' : jsonStr;\n throw new Error(\n `Failed to parse model response as JSON: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n const result = schema.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues\n .slice(0, 5)\n .map(i => ` ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n throw new Error(`Model JSON does not match expected schema:\\n${issues}`);\n }\n return result.data;\n}\n\n/**\n * Parse a raw JSON string (e.g. tool input) with a descriptive error on failure.\n */\nexport function safeJsonParse(jsonStr: string, label?: string): unknown {\n try {\n return JSON.parse(jsonStr) as unknown;\n } catch (err) {\n const preview = jsonStr.length > 200 ? jsonStr.slice(0, 200) + '...' : jsonStr;\n throw new Error(\n `Invalid JSON${label ? ` for ${label}` : ''}: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n}\n","/**\n * Structured logger using Pino (JSON by default, optional pretty/file).\n * Use loggerConfigFromEnv() for .env-driven config (SWE_LOG_* vars).\n */\n\nimport pino from 'pino';\nimport type { Logger } from '../types/common';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LoggerConfig {\n /** Logger name (appears in logs) */\n name?: string;\n /** Minimum log level */\n level?: LogLevel;\n /** Use pino-pretty for readable output */\n pretty?: boolean;\n /** File path for JSON logs */\n file?: string;\n /** Console stream: stderr avoids mixing with stdout prompts (e.g. inquirer). Default: stderr when pretty, else stdout. */\n stream?: 'stdout' | 'stderr';\n /** When false, returns a no-op logger (no output). Set via SWE_LOG_ENABLED=0. */\n enabled?: boolean;\n /** Optional stream for testing (bypasses transport) */\n destination?: pino.DestinationStream;\n}\n\nconst NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n\nexport function createLogger(config: LoggerConfig = {}): Logger {\n if (config.enabled === false) {\n return NOOP_LOGGER;\n }\n\n const { name, level = 'info', pretty = false, file, stream, destination } = config;\n\n const streamFd = stream === 'stderr' ? 2 : stream === 'stdout' ? 1 : pretty ? 2 : 1;\n\n let pinoLogger: pino.Logger;\n\n if (destination) {\n pinoLogger = pino({ name, level }, destination);\n } else {\n const targets: pino.TransportTargetOptions[] = [];\n\n if (pretty) {\n targets.push({\n target: 'pino-pretty',\n options: {\n colorize: true,\n destination: streamFd,\n singleLine: true,\n ignore: 'time,pid,hostname',\n translateTime: false,\n },\n level,\n });\n } else {\n targets.push({\n target: 'pino/file',\n options: { destination: streamFd },\n level,\n });\n }\n\n if (file) {\n targets.push({\n target: 'pino/file',\n options: { destination: file, mkdir: true },\n level,\n });\n }\n\n const transport = pino.transport({ targets }) as pino.DestinationStream;\n pinoLogger = pino({ name, level }, transport);\n }\n\n return wrapPino(pinoLogger);\n}\n\n/**\n * Build logger config from process.env (SWE_* vars). Caller loads .env if desired (e.g. dotenv or `node --env-file=.env`).\n *\n * Env vars (all optional):\n * - SWE_LOG_ENABLED: 1|true|yes (default) = on; 0|false|no|disabled = off (no-op logger).\n * - SWE_LOG_LEVEL: debug|info|warn|error (default: info).\n * - SWE_LOG_STREAM: stdout|stderr; default stderr when SWE_LOG_PRETTY is true, else stdout.\n * - SWE_LOG_PRETTY: 1|true|yes = human-readable (pino-pretty); 0|false (default) = JSON.\n * - SWE_LOG_FILE: path to also write JSON logs to a file.\n * - SWE_LOG_NAME: logger name in output.\n *\n * For interactive CLIs (e.g. inquirer), use pretty and stderr so logs do not mix with stdout prompts.\n */\nexport function loggerConfigFromEnv(overrides: Partial<LoggerConfig> = {}): LoggerConfig {\n const raw = process.env;\n const enabledRaw = (raw.SWE_LOG_ENABLED ?? 'true').trim().toLowerCase();\n const enabled =\n enabledRaw !== '0' &&\n enabledRaw !== 'false' &&\n enabledRaw !== 'no' &&\n enabledRaw !== 'disabled';\n\n const levelRaw = (raw.SWE_LOG_LEVEL ?? 'info').trim().toLowerCase();\n const level: LogLevel =\n levelRaw === 'debug' || levelRaw === 'info' || levelRaw === 'warn' || levelRaw === 'error'\n ? levelRaw\n : 'info';\n\n const streamRaw = (raw.SWE_LOG_STREAM ?? '').trim().toLowerCase();\n const prettyRaw = (raw.SWE_LOG_PRETTY ?? '0').trim().toLowerCase();\n const pretty = prettyRaw === '1' || prettyRaw === 'true' || prettyRaw === 'yes';\n const stream: 'stdout' | 'stderr' =\n streamRaw === 'stdout'\n ? 'stdout'\n : streamRaw === 'stderr'\n ? 'stderr'\n : pretty\n ? 'stderr'\n : 'stdout';\n\n const file = raw.SWE_LOG_FILE?.trim() || undefined;\n const name = raw.SWE_LOG_NAME?.trim() || undefined;\n\n return {\n enabled,\n level,\n stream,\n pretty,\n ...(file && { file }),\n ...(name && { name }),\n ...overrides,\n };\n}\n\nfunction wrapPino(p: pino.Logger): Logger {\n return {\n debug: (msg, data) => {\n p.debug(data ?? {}, msg);\n },\n info: (msg, data) => {\n p.info(data ?? {}, msg);\n },\n warn: (msg, data) => {\n p.warn(data ?? {}, msg);\n },\n error: (msg, err) => {\n if (err instanceof Error) {\n p.error({ err }, msg);\n } else {\n p.error(err ?? {}, msg);\n }\n },\n child: (bindings: Record<string, unknown>) => wrapPino(p.child(bindings as pino.Bindings)),\n };\n}\n","/**\n * Utility functions\n */\n\nimport type { LanguageModelUsage } from 'ai';\n\nconst emptyDetails = {\n noCacheTokens: undefined as number | undefined,\n cacheReadTokens: undefined as number | undefined,\n cacheWriteTokens: undefined as number | undefined,\n};\nconst emptyOutputDetails = {\n textTokens: undefined as number | undefined,\n reasoningTokens: undefined as number | undefined,\n};\n\n/**\n * Sum token usage from multiple steps (AI SDK LanguageModelUsage)\n */\nexport function sumTokenUsage(usages: (LanguageModelUsage | undefined)[]): LanguageModelUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n let totalTokens = 0;\n\n for (const usage of usages) {\n if (usage) {\n inputTokens += usage.inputTokens ?? 0;\n outputTokens += usage.outputTokens ?? 0;\n totalTokens += usage.totalTokens ?? 0;\n }\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens,\n inputTokenDetails: emptyDetails,\n outputTokenDetails: emptyOutputDetails,\n };\n}\n","/**\n * Tools: defineTool, createToolSet, execute, zodToJsonSchema\n */\n\nimport { z } from 'zod';\nimport { tool } from 'ai';\nimport type { Tool, ToolExecutionOptions } from 'ai';\nimport type { Logger } from '../types/common';\nimport type { ToolConfig, ToolContext, ToolExecutionResult } from '../types/tool';\nimport { ToolError } from '../utils/errors';\n\n/** Tool has description (and optional title) in config; name is the key in createToolSet. */\nexport function defineTool<TInput extends z.ZodType, TOutput>(\n config: ToolConfig<TInput, TOutput>\n): Tool {\n const { name, description, input: inputSchema, handler } = config;\n return tool({\n description,\n inputSchema,\n execute: async (args: unknown): Promise<TOutput> => {\n const parsed = inputSchema.safeParse(args);\n if (!parsed.success)\n throw new ToolError(`Invalid input: ${parsed.error.message}`, name, parsed.error);\n try {\n return await handler(parsed.data as z.infer<TInput>, undefined as ToolContext | undefined);\n } catch (e) {\n if (e instanceof ToolError) throw e;\n throw new ToolError(\n `Tool \"${name}\" failed: ${e instanceof Error ? e.message : String(e)}`,\n name,\n e instanceof Error ? e : undefined\n );\n }\n },\n } as unknown as Parameters<typeof tool>[0]);\n}\n\nexport type ToolSet = Record<string, Tool>;\n\n/** Pass a record: key = tool name (same as in defineTool config). */\nexport function createToolSet(tools: ToolSet): ToolSet {\n return tools;\n}\n\nexport function getTools(toolSet: ToolSet): Tool[] {\n return Object.values(toolSet);\n}\n\nexport function getTool(toolSet: ToolSet, name: string): Tool | undefined {\n return toolSet[name];\n}\n\nexport interface ExecuteToolOptions {\n toolCallId?: string;\n abortSignal?: AbortSignal;\n logger?: Logger;\n}\n\nexport async function executeTool<TInput, TOutput>(\n toolImpl: Tool<TInput, TOutput>,\n input: TInput,\n options?: ExecuteToolOptions & { toolName?: string }\n): Promise<ToolExecutionResult<TOutput>> {\n const { logger } = options ?? {};\n const toolName =\n options?.toolName ??\n ('name' in toolImpl && typeof toolImpl.name === 'string' ? toolImpl.name : 'unknown');\n\n if (!toolImpl.execute) {\n logger?.error('Tool has no execute function', { toolName });\n return { success: false, error: 'Tool has no execute function' };\n }\n logger?.debug('Executing tool', { toolName, toolCallId: options?.toolCallId });\n try {\n const out = await toolImpl.execute(input, {\n toolCallId: options?.toolCallId ?? '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as ToolExecutionOptions);\n logger?.info('Tool completed', { toolName, toolCallId: options?.toolCallId });\n return { success: true, output: out as TOutput };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n logger?.error('Tool failed', {\n toolName,\n toolCallId: options?.toolCallId,\n error: msg,\n });\n return { success: false, error: msg };\n }\n}\n\nexport async function executeToolByName(\n tools: ToolSet,\n name: string,\n input: unknown,\n options?: ExecuteToolOptions\n): Promise<ToolExecutionResult> {\n const toolImpl = tools[name];\n if (!toolImpl) {\n options?.logger?.error('Tool not found', {\n name,\n availableTools: Object.keys(tools),\n });\n throw new ToolError(`Tool not found: ${name}`);\n }\n return executeTool(toolImpl, input, { ...options, toolName: name });\n}\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport function zodToJsonSchema(schema: z.ZodType): JsonSchemaObject {\n const result = z.toJSONSchema(schema) as JsonSchemaObject & {\n $schema?: string;\n definitions?: unknown;\n };\n const { $schema: _s, definitions: _d, ...rest } = result;\n return rest as JsonSchemaObject;\n}\n","/**\n * Notify agent observers (step, tool, error). Keeps agent.ts under 150 lines.\n */\n\nimport type { AgentObserver, AgentStep } from '../types/agent';\n\nexport function notifyObserversStep(observers: AgentObserver[] | undefined, step: AgentStep): void {\n observers?.forEach(o => o.onStep?.(step));\n}\n\nexport function notifyObserversTool(\n observers: AgentObserver[] | undefined,\n toolName: string,\n result: unknown\n): void {\n observers?.forEach(o => o.onToolExecution?.(toolName, result));\n}\n\nexport function notifyObserversError(observers: AgentObserver[] | undefined, error: Error): void {\n observers?.forEach(o => o.onError?.(error));\n}\n","/**\n * Agent loop: model + tools, AI SDK message shapes\n */\n\nimport type { AgentConfig, AgentResult, AgentStep, AgentToolResult } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport type { ModelToolCall } from '../types/model';\nimport { AgentError } from '../utils/errors';\nimport { sumTokenUsage } from '../utils/utils';\nimport { executeToolByName } from '../tools';\nimport { notifyObserversStep, notifyObserversTool, notifyObserversError } from './agent-observers';\n\n/**\n * Run an agent with the given configuration.\n *\n * 1. Calls the model with ModelMessage[] and tools\n * 2. If no tool calls, returns the response\n * 3. If tool calls, executes them and appends assistant + tool messages (AI SDK shape)\n * 4. Repeats until done or max iterations reached\n *\n * @example\n * ```typescript\n * const result = await runAgent({\n * model: createModel({ provider: 'openai', model: 'gpt-4o' }),\n * tools: createToolSet({ search: searchTool, calculator: calculatorTool }),\n * systemPrompt: 'You are a helpful assistant.',\n * input: 'What is 2 + 2?',\n * maxIterations: 10\n * });\n * console.log(result.output);\n * ```\n */\nexport async function runAgent(config: AgentConfig): Promise<AgentResult> {\n const {\n model,\n tools,\n systemPrompt,\n input,\n maxIterations = 10,\n onStep,\n observers,\n logger,\n } = config;\n\n logger?.info('Starting agent', { maxIterations });\n\n const messages: ModelMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: input },\n ];\n\n const steps: AgentStep[] = [];\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n if (iteration > 0 && iteration >= maxIterations - 2) {\n logger?.warn('Approaching max iterations', { iteration, maxIterations });\n }\n logger?.debug('Agent iteration', { iteration });\n\n const response = await model.invoke(messages, { tools });\n\n const step: AgentStep = {\n iteration,\n content: response.text,\n toolCalls: response.toolCalls,\n usage: response.usage,\n };\n\n if (response.text) {\n logger?.debug('Model response', { iteration, textLength: response.text.length });\n }\n\n if (!response.toolCalls?.length) {\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n logger?.info('Agent completed', {\n steps: steps.length,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n });\n return {\n output: response.text,\n steps,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n messages,\n };\n }\n\n logger?.debug('Tool calls', {\n iteration,\n toolCalls: response.toolCalls.map((tc: ModelToolCall) => ({\n name: tc.toolName,\n toolCallId: tc.toolCallId,\n })),\n });\n\n const assistantContent = [\n ...(response.text ? [{ type: 'text' as const, text: response.text }] : []),\n ...response.toolCalls.map((tc: ModelToolCall) => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n })),\n ];\n messages.push({ role: 'assistant', content: assistantContent });\n\n const toolResults: AgentToolResult[] = [];\n\n for (const toolCall of response.toolCalls) {\n const execResult = await executeToolByName(tools, toolCall.toolName, toolCall.input, {\n toolCallId: toolCall.toolCallId,\n logger,\n });\n\n const agentResult: AgentToolResult = {\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: execResult.success ? execResult.output : execResult.error,\n isError: !execResult.success,\n };\n toolResults.push(agentResult);\n notifyObserversTool(observers, toolCall.toolName, agentResult.output);\n\n const outputVal = agentResult.isError\n ? { type: 'error-text' as const, value: String(agentResult.output) }\n : {\n type: 'text' as const,\n value:\n typeof agentResult.output === 'string'\n ? agentResult.output\n : JSON.stringify(agentResult.output),\n };\n\n messages.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: outputVal,\n },\n ],\n });\n }\n\n step.toolResults = toolResults;\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n }\n\n const err = new AgentError(\n `Agent reached maximum iterations (${maxIterations}) without completing`,\n maxIterations - 1\n );\n notifyObserversError(observers, err);\n logger?.error('Agent failed: max iterations reached', { maxIterations, error: err });\n throw err;\n}\n","/**\n * Shared AI SDK adapter - pass-through to generateText (no conversions)\n */\n\nimport { generateText, generateObject, zodSchema } from 'ai';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\n InvokeObjectOptions,\n InvokeObjectResult,\n VisionOptions,\n ModelProvider,\n ModelTool,\n ModelToolCall,\n} from '../../types/model';\nimport type { ModelMessage, ImageInput } from '../../types/common';\nimport { ModelError } from '../../utils/errors';\n\nexport interface CreateAIModelParams {\n provider: ModelProvider;\n modelName: string;\n getModel: () => LanguageModelV3 | Promise<LanguageModelV3>;\n}\n\n/**\n * Create a sweagent Model that uses an AI SDK LanguageModel.\n * Messages and tools are passed through to generateText; result returned as ModelResponse.\n */\nexport function createAIModel(params: CreateAIModelParams): Model {\n const { provider, modelName, getModel } = params;\n\n return {\n provider,\n modelName,\n\n async invoke(messages: ModelMessage[], options?: InvokeOptions): Promise<ModelResponse> {\n try {\n const model = await getModel();\n const schemaOnlyTools: Record<string, ModelTool> | undefined = options?.tools\n ? (Object.fromEntries(\n Object.entries(options.tools).map(([name, t]) => {\n const { execute: _execute, ...rest } = t as Record<string, unknown>;\n return [name, rest];\n })\n ) as Record<string, ModelTool>)\n : undefined;\n const result = await generateText({\n model,\n messages,\n tools: schemaOnlyTools,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n stopSequences: options?.stop,\n });\n\n const toolCalls: ModelToolCall[] = result.toolCalls.map(tc => ({\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input as unknown,\n }));\n\n return {\n text: result.text,\n toolCalls,\n usage: result.usage,\n finishReason: result.finishReason,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to invoke ${provider} model`, provider, err);\n }\n },\n\n async generateVision(\n prompt: string,\n images: ImageInput[],\n options?: VisionOptions\n ): Promise<ModelResponse> {\n try {\n const model = await getModel();\n\n const content: (\n | { type: 'text'; text: string }\n | { type: 'image'; image: string; mimeType?: string }\n )[] = [];\n for (const img of images) {\n content.push({\n type: 'image',\n image: `data:${img.mimeType};base64,${img.base64}`,\n mimeType: img.mimeType,\n });\n }\n content.push({ type: 'text', text: prompt });\n\n const messages: ModelMessage[] = [];\n if (options?.systemPrompt) {\n messages.push({ role: 'system', content: options.systemPrompt });\n }\n messages.push({ role: 'user', content });\n\n const result = await generateText({\n model,\n messages,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n });\n\n return {\n text: result.text,\n toolCalls: [],\n usage: result.usage,\n finishReason: result.finishReason,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to generate vision response`, provider, err);\n }\n },\n\n async invokeObject<T>(\n messages: ModelMessage[],\n schema: unknown,\n options?: InvokeObjectOptions\n ): Promise<InvokeObjectResult<T>> {\n try {\n const model = await getModel();\n const schemaWrapped = zodSchema(schema as Parameters<typeof zodSchema>[0]);\n // Structured output; prefer generateObject until migrate to generateText+output\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const result = await generateObject({\n model,\n messages,\n schema: schemaWrapped,\n temperature: options?.temperature,\n maxOutputTokens: options?.maxOutputTokens,\n });\n return {\n data: result.object as T,\n usage: result.usage,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to invokeObject ${provider} model`, provider, err);\n }\n },\n };\n}\n","/**\n * OpenAI model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createOpenAI } from '@ai-sdk/openai';\n\n/**\n * Create an OpenAI model instance\n */\nexport function createOpenAIModel(config: ModelConfig): Model {\n const { model: modelName, apiKey, baseUrl } = config;\n\n const provider = createOpenAI({\n apiKey: apiKey ?? process.env.OPENAI_API_KEY,\n baseURL: baseUrl,\n });\n\n return createAIModel({\n provider: 'openai',\n modelName,\n getModel: () => provider.chat(modelName),\n });\n}\n","/**\n * Anthropic model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createAnthropic } from '@ai-sdk/anthropic';\n\n/**\n * Create an Anthropic model instance\n */\nexport function createAnthropicModel(config: ModelConfig): Model {\n const { model: modelName, apiKey } = config;\n\n const provider = createAnthropic({\n apiKey: apiKey ?? process.env.ANTHROPIC_API_KEY,\n });\n\n return createAIModel({\n provider: 'anthropic',\n modelName,\n getModel: () => provider(modelName),\n });\n}\n","/**\n * Google (Gemini) model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createGoogleGenerativeAI } from '@ai-sdk/google';\n\n/**\n * Create a Google (Gemini) model instance\n */\nexport function createGoogleModel(config: ModelConfig): Model {\n const { model: modelName, apiKey } = config;\n\n const provider = createGoogleGenerativeAI({\n apiKey: apiKey ?? process.env.GOOGLE_GENERATIVE_AI_API_KEY,\n });\n\n return createAIModel({\n provider: 'google',\n modelName,\n getModel: () => provider(modelName),\n });\n}\n","/**\n * Create a model instance based on provider\n */\n\nimport type { Model, ModelConfig } from '../types/model';\nimport { ModelError } from '../utils/errors';\nimport { createOpenAIModel } from './providers/openai';\nimport { createAnthropicModel } from './providers/anthropic';\nimport { createGoogleModel } from './providers/google';\n\n/**\n * Create a model instance for the given provider\n *\n * @example\n * ```typescript\n * const model = createModel({\n * provider: 'openai',\n * model: 'gpt-4o',\n * temperature: 0.7\n * });\n *\n * const response = await model.invoke([\n * { role: 'user', content: 'Hello!' }\n * ]);\n * ```\n */\nexport function createModel(config: ModelConfig): Model {\n const { provider } = config;\n\n switch (provider) {\n case 'openai':\n return createOpenAIModel(config);\n case 'anthropic':\n return createAnthropicModel(config);\n case 'google':\n return createGoogleModel(config);\n default:\n throw new ModelError(\n `Unsupported provider: ${provider}. Supported providers: openai, anthropic, google`\n );\n }\n}\n","/**\n * Subagents: define, run, and expose as tools to a parent agent\n */\n\nimport { z } from 'zod';\nimport type { SubagentConfig, SubagentDefinition, SubagentResult } from '../types/subagent';\nimport type { AgentTool } from '../types/agent';\nimport type { Model } from '../types/model';\nimport { runAgent } from '../agents';\nimport { createModel } from '../models/create-model';\nimport { defineTool } from '../tools';\nimport type { ToolSet } from '../tools';\nimport { SubagentError } from '../utils/errors';\n\nconst NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n/**\n * Validates and creates a subagent definition (analogous to defineTool).\n * Name must be kebab-case.\n */\nexport function defineSubagent(config: SubagentConfig): SubagentDefinition {\n if (!config.name.trim()) {\n throw new SubagentError('Subagent name is required', undefined);\n }\n if (!NAME_REGEX.test(config.name)) {\n throw new SubagentError(\n `Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${config.name}`,\n config.name\n );\n }\n return { ...config };\n}\n\nexport interface RunSubagentOptions {\n /** Parent's tools; used when definition does not specify tools (filtered by disallowedTools) */\n parentTools?: Record<string, AgentTool>;\n /** Parent's model; used when definition does not specify model */\n parentModel?: Model;\n}\n\n/**\n * Resolves the tool set for a subagent: definition.tools if set,\n * otherwise parentTools with disallowedTools removed.\n * Subagent tools (keys starting with \"subagent_\") are never inherited (no nesting).\n */\nfunction resolveTools(\n definition: SubagentDefinition,\n parentTools?: Record<string, AgentTool>\n): Record<string, AgentTool> {\n if (definition.tools != null && Object.keys(definition.tools).length > 0) {\n return definition.tools;\n }\n const base = parentTools ?? {};\n const disallowed = new Set(definition.disallowedTools ?? []);\n const filtered: Record<string, AgentTool> = {};\n for (const [key, t] of Object.entries(base)) {\n if (key.startsWith('subagent_')) continue; // no nesting\n if (!disallowed.has(key)) {\n filtered[key] = t;\n }\n }\n return filtered;\n}\n\n/**\n * Executes the subagent in isolation: resolves tools and model, runs runAgent, returns SubagentResult.\n */\nexport async function runSubagent(\n definition: SubagentDefinition,\n input: string,\n options?: RunSubagentOptions\n): Promise<SubagentResult> {\n const { parentTools, parentModel } = options ?? {};\n const tools = resolveTools(definition, parentTools);\n\n const model = definition.model == null ? parentModel : createModel(definition.model);\n if (!model) {\n throw new SubagentError(\n 'Subagent has no model: set definition.model or pass parentModel in options',\n definition.name\n );\n }\n const result = await runAgent({\n model,\n tools,\n systemPrompt: definition.systemPrompt,\n input,\n maxIterations: definition.maxIterations ?? 10,\n onStep: definition.onStep,\n });\n return { ...result, subagentName: definition.name };\n}\n\nexport interface CreateSubagentToolOptions {\n parentTools?: Record<string, AgentTool>;\n parentModel?: Model;\n}\n\n/**\n * Wraps a subagent as an AI SDK Tool so a parent agent can delegate via a tool call.\n * Input: { prompt: string }. Returns the subagent's final output string.\n */\nexport function createSubagentTool(\n definition: SubagentDefinition,\n options?: CreateSubagentToolOptions\n): AgentTool {\n const toolName = `subagent_${definition.name}`;\n return defineTool({\n name: toolName,\n description: definition.description,\n input: z.object({\n prompt: z.string().describe('The task or question to delegate to this subagent'),\n }),\n handler: async ({ prompt }) => {\n const result = await runSubagent(definition, prompt, {\n parentTools: options?.parentTools,\n parentModel: options?.parentModel,\n });\n return result.output;\n },\n });\n}\n\n/**\n * Creates a Record<string, Tool> from multiple subagent definitions, keyed by subagent_<name>.\n */\nexport function createSubagentToolSet(\n definitions: SubagentDefinition[],\n options?: CreateSubagentToolOptions\n): ToolSet {\n const out: ToolSet = {};\n for (const def of definitions) {\n const tool = createSubagentTool(def, options);\n out[`subagent_${def.name}`] = tool;\n }\n return out;\n}\n","/**\n * Handlebars template compiler - reads .hbs files, compiles with context, writes output\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport Handlebars from 'handlebars';\nimport type { TemplateContext, ScaffoldConfig, ScaffoldResult, ScaffoldError } from './types';\n\n/** Compile a single Handlebars template string with context */\nexport function compileTemplate(template: string, context: TemplateContext): string {\n const compiled = Handlebars.compile(template, { noEscape: true });\n return compiled(context);\n}\n\n/** Recursively find all .hbs files in a directory */\nfunction findHbsFiles(dir: string, base: string = dir): string[] {\n const results: string[] = [];\n if (!fs.existsSync(dir)) return results;\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...findHbsFiles(fullPath, base));\n } else if (entry.name.endsWith('.hbs')) {\n results.push(path.relative(base, fullPath));\n }\n }\n return results;\n}\n\n/** Convert a .hbs relative path to the output file path (strip .hbs extension) */\nfunction toOutputPath(hbsRelPath: string): string {\n return hbsRelPath.replace(/\\.hbs$/, '');\n}\n\n/** Check if a path matches any skip pattern (simple glob: * matches any segment) */\nfunction shouldSkip(relativePath: string, skipPatterns: string[]): boolean {\n for (const pattern of skipPatterns) {\n const regex = new RegExp(\n '^' +\n pattern\n .replace(/\\./g, '\\\\.')\n .replace(/\\*\\*/g, '<<GLOBSTAR>>')\n .replace(/\\*/g, '[^/]*')\n .replace(/<<GLOBSTAR>>/g, '.*') +\n '$'\n );\n if (regex.test(relativePath)) return true;\n }\n return false;\n}\n\n/**\n * Scaffold a project: compile all .hbs templates in templateDir with context,\n * write results to outputDir, return summary.\n */\nexport async function scaffoldProject(config: ScaffoldConfig): Promise<ScaffoldResult> {\n const { templateDir, outputDir, context, skipPatterns = [] } = config;\n const hbsFiles = findHbsFiles(templateDir);\n const files: string[] = [];\n const errors: ScaffoldError[] = [];\n\n for (const hbsFile of hbsFiles) {\n if (shouldSkip(hbsFile, skipPatterns)) continue;\n\n const outputRelPath = toOutputPath(hbsFile);\n const inputPath = path.join(templateDir, hbsFile);\n const outputPath = path.join(outputDir, outputRelPath);\n\n try {\n const templateSource = fs.readFileSync(inputPath, 'utf-8');\n const compiled = compileTemplate(templateSource, context);\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, compiled, 'utf-8');\n files.push(outputRelPath);\n } catch (err) {\n errors.push({\n file: hbsFile,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { fileCount: files.length, files, errors };\n}\n\n/** Register common Handlebars helpers */\nexport function registerHelpers(): void {\n Handlebars.registerHelper('eq', (a, b) => a === b);\n Handlebars.registerHelper('neq', (a, b) => a !== b);\n Handlebars.registerHelper('json', obj => JSON.stringify(obj, null, 2));\n Handlebars.registerHelper('uppercase', (str: string) =>\n typeof str === 'string' ? str.toUpperCase() : ''\n );\n Handlebars.registerHelper('lowercase', (str: string) =>\n typeof str === 'string' ? str.toLowerCase() : ''\n );\n Handlebars.registerHelper('capitalize', (str: string) =>\n typeof str === 'string' ? str.charAt(0).toUpperCase() + str.slice(1) : ''\n );\n Handlebars.registerHelper('camelCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toLowerCase());\n });\n Handlebars.registerHelper('pascalCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toUpperCase());\n });\n}\n\n// Register helpers on module load\nregisterHelpers();\n","/**\n * MCP SDK transport creation and result parsing. Isolates SDK path and dynamic imports.\n */\n\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { McpTransport, McpToolContent } from './types';\n\nfunction getSdkRoot(): string {\n const require = createRequire(import.meta.url);\n const entry = require.resolve('@modelcontextprotocol/sdk/client');\n return path.dirname(path.dirname(path.dirname(path.dirname(entry))));\n}\n\nconst sdkRoot = getSdkRoot();\n\n/** Parse first text content block of an MCP tool result to JSON or { text } / { raw }. */\nexport function parseToolResult(result: { content?: McpToolContent[] }): unknown {\n const content = result.content;\n if (!content?.length) return {};\n const first = content[0];\n if (first?.type === 'text' && typeof first.text === 'string') {\n const text = first.text.trim();\n if (text.startsWith('{') || text.startsWith('[')) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return { raw: text };\n }\n }\n return { text };\n }\n return result;\n}\n\n/** Build StreamableHTTPClientTransport from the MCP SDK. */\nexport async function createHttpTransport(\n url: string,\n headers?: Record<string, string>\n): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'streamableHttp.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StreamableHTTPClientTransport: new (\n url: URL,\n opts?: { requestInit?: RequestInit }\n ) => McpTransport;\n };\n const requestInit: RequestInit | undefined = headers\n ? { headers: new Headers(headers) }\n : undefined;\n return new mod.StreamableHTTPClientTransport(\n new URL(url),\n requestInit ? { requestInit } : undefined\n );\n}\n\n/** Build StdioClientTransport from the MCP SDK. */\nexport async function createStdioTransport(command: string, args: string[]): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'stdio.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StdioClientTransport: new (params: { command: string; args: string[] }) => McpTransport;\n };\n return new mod.StdioClientTransport({ command, args });\n}\n","/**\n * BaseMcpClient - reusable MCP client with lazy connection and typed tool invocation.\n * Extend and add domain methods that call this.callTool(name, args).\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client';\nimport { ToolError } from '../utils/errors';\nimport { createHttpTransport, createStdioTransport, parseToolResult } from './transports';\nimport type {\n McpClientConfig,\n McpClientInfo,\n McpToolContent,\n McpTransport,\n McpResolveOptions,\n} from './types';\n\nexport class BaseMcpClient {\n private readonly info: McpClientInfo;\n private readonly config: McpClientConfig;\n private client: Client | null = null;\n private transport: McpTransport | null = null;\n private connectPromise: Promise<void> | null = null;\n\n constructor(info: McpClientInfo, config: McpClientConfig) {\n this.info = info;\n this.config = config;\n }\n\n /** Build config from options + env (<PREFIX>_URL, _API_KEY, _COMMAND, _ARGS). */\n static resolveConfig(\n options?: McpClientConfig,\n resolveOpts: McpResolveOptions = { envPrefix: 'MCP' }\n ): McpClientConfig {\n const { envPrefix, serverLabel, apiKeyHeader } = resolveOpts;\n const url = options?.url ?? process.env[`${envPrefix}_URL`];\n const apiKey = process.env[`${envPrefix}_API_KEY`];\n const command = options?.command ?? process.env[`${envPrefix}_COMMAND`];\n const argsEnv = process.env[`${envPrefix}_ARGS`];\n const args = options?.args ?? (argsEnv ? argsEnv.split(',').map(a => a.trim()) : undefined);\n\n let headers = options?.headers ? { ...options.headers } : undefined;\n if (apiKey) {\n const name = apiKeyHeader ?? 'Authorization';\n\n headers = headers ?? {};\n\n headers[name] = name === 'Authorization' ? `Bearer ${apiKey}` : apiKey;\n }\n\n if (url) return { url, headers };\n if (command) return { command, args: args?.length ? args : [] };\n throw new ToolError(\n `${serverLabel ?? envPrefix} uses MCP only. Set ${envPrefix}_URL or ${envPrefix}_COMMAND (and optionally ${envPrefix}_ARGS).`,\n 'mcp_client'\n );\n }\n\n private async ensureConnected(): Promise<Client> {\n if (this.client) return this.client;\n if (this.connectPromise) {\n await this.connectPromise;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n this.connectPromise = this.doConnect();\n await this.connectPromise;\n this.connectPromise = null;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n\n private async doConnect(): Promise<void> {\n const client = new Client(\n { name: this.info.name, version: this.info.version },\n { capabilities: {} }\n );\n if (this.config.url) {\n this.transport = await createHttpTransport(this.config.url, this.config.headers);\n } else if (this.config.command) {\n this.transport = await createStdioTransport(this.config.command, this.config.args ?? []);\n } else {\n throw new ToolError('MCP config missing: provide url or command.', 'mcp_client');\n }\n await client.connect(this.transport as Parameters<Client['connect']>[0]);\n this.client = client;\n }\n\n /** Call MCP tool and parse result. Subclasses use this for typed domain methods. */\n protected async callTool<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {\n const client = await this.ensureConnected();\n const result = await client.callTool({ name, arguments: args });\n if (result && typeof result === 'object' && 'content' in result) {\n return parseToolResult(result as { content?: McpToolContent[] }) as T;\n }\n return result as T;\n }\n\n async close(): Promise<void> {\n if (this.transport) {\n await this.transport.close();\n this.transport = null;\n }\n this.client = null;\n this.connectPromise = null;\n }\n}\n","/**\n * Hello World tool\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../lib/tools';\n\nexport const helloWorldTool = defineTool({\n name: 'hello_world',\n description: 'Returns a greeting message for the given name',\n input: z.object({\n name: z.string().describe('Name to greet'),\n }),\n handler: async ({ name }) => {\n return { greeting: `Hello, ${name}! Welcome to sweagent.` };\n },\n});\n","/**\n * Hello World agent - runs an agent with the hello world tool\n */\n\nimport type { AgentResult, AgentStep } from '../../lib/types/agent';\nimport type { Logger } from '../../lib/types/common';\nimport type { ModelConfig } from '../../lib/types/model';\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { helloWorldTool } from './tool';\n\nexport interface HelloWorldAgentConfig {\n /** User input (e.g. \"Say hello to Alice\") */\n input: string;\n /** Model config; defaults to OpenAI gpt-4o-mini */\n model?: ModelConfig;\n /** System prompt override */\n systemPrompt?: string;\n /** Max iterations; default 3 */\n maxIterations?: number;\n /** Callback for each step */\n onStep?: (step: AgentStep) => void;\n /** Optional logger for execution logs */\n logger?: Logger;\n}\n\nconst DEFAULT_SYSTEM_PROMPT =\n 'You are a friendly greeter. Use the hello_world tool to greet users.';\n\nexport async function runHelloWorldAgent(config: HelloWorldAgentConfig): Promise<AgentResult> {\n const {\n input,\n model: modelConfig,\n systemPrompt = DEFAULT_SYSTEM_PROMPT,\n maxIterations = 3,\n onStep,\n logger,\n } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n\n return runAgent({\n model,\n tools: createToolSet({ hello_world: helloWorldTool }),\n systemPrompt,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Field-level schema for MongoDB collection fields\n */\n\nimport { z } from 'zod';\n\nexport const fieldSchema = z.object({\n fieldName: z.string().describe('fieldName must be in camelCase'),\n fieldType: z\n .string()\n .default('string')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['string', 'text', 'varchar'].includes(n)) return 'string' as const;\n if (['number', 'int', 'integer', 'float', 'double', 'decimal'].includes(n))\n return 'number' as const;\n if (['boolean', 'bool'].includes(n)) return 'boolean' as const;\n if (['types.objectid', 'objectid', 'ref', 'reference'].includes(n))\n return 'Types.ObjectId' as const;\n if (['date', 'datetime', 'timestamp'].includes(n)) return 'Date' as const;\n if (['object', 'json', 'mixed'].includes(n)) return 'object' as const;\n if (['email'].includes(n)) return 'email' as const;\n if (['password', 'hash'].includes(n)) return 'password' as const;\n if (['enum', 'select'].includes(n)) return 'enum' as const;\n if (['array'].includes(n)) return 'string' as const;\n return 'string' as const;\n })\n .pipe(\n z.enum([\n 'string',\n 'number',\n 'boolean',\n 'Types.ObjectId',\n 'Date',\n 'object',\n 'email',\n 'password',\n 'enum',\n ])\n ),\n isArray: z.coerce.boolean().default(false),\n isRequired: z.coerce.boolean().default(true),\n isUnique: z.coerce.boolean().default(false),\n values: z\n .array(z.string())\n .default([])\n .describe('Enum values if fieldType is enum, else empty array'),\n defaultVal: z.union([z.string(), z.boolean(), z.number(), z.null()]).optional(),\n relationTo: z.string().optional().describe('Module name for relations'),\n relationType: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_]+/g, '-');\n if (['one-to-one', '1:1', '1-to-1'].includes(n)) return 'one-to-one' as const;\n if (['many-to-one', 'n:1', 'n-to-1', 'many-to-1', '*:1'].includes(n))\n return 'many-to-one' as const;\n return '' as const;\n })\n .pipe(z.enum(['one-to-one', 'many-to-one', '']))\n .optional(),\n isPrivate: z.coerce.boolean().default(false).describe('True if password field, else false'),\n});\n\nexport type TFieldSchema = z.infer<typeof fieldSchema>;\n","/**\n * Module (collection) level schema for MongoDB\n */\n\nimport { z } from 'zod';\nimport { fieldSchema } from './field.schema';\n\nexport const moduleSchema = z.object({\n moduleName: z.string().describe('camelCase, single word, never auth/authentication'),\n isUserModule: z.coerce.boolean().default(false),\n authMethod: z\n .string()\n .transform(s => {\n const n = s.toUpperCase().replace(/[\\s-]+/g, '_');\n if (['EMAIL_AND_PASSWORD', 'EMAIL_PASSWORD', 'EMAIL'].includes(n))\n return 'EMAIL_AND_PASSWORD' as const;\n if (['PHONE_AND_OTP', 'PHONE_OTP', 'PHONE', 'SMS'].includes(n))\n return 'PHONE_AND_OTP' as const;\n return '' as const;\n })\n .pipe(z.enum(['EMAIL_AND_PASSWORD', 'PHONE_AND_OTP', '']))\n .optional(),\n emailField: z.string().optional(),\n passwordField: z.string().optional(),\n phoneField: z.string().optional(),\n roleField: z.string().optional(),\n permissions: z\n .record(z.string(), z.array(z.enum(['CREATE', 'READ', 'UPDATE', 'DELETE'])))\n .optional()\n .describe('Permissions per role'),\n fields: z.union([z.array(fieldSchema), z.record(z.string(), z.unknown())]).transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof fieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.fieldName) obj.fieldName = key;\n const result = fieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n});\n\nexport type TModuleSchema = z.infer<typeof moduleSchema>;\n","/**\n * Root project schema for MongoDB database design\n */\n\nimport { z } from 'zod';\nimport { moduleSchema } from './module.schema';\n\nexport const projectSchema = z.object({\n projectName: z.string().default('project').describe('projectName must be in kebab-case'),\n projectDescription: z.string().default(''),\n modules: z\n .union([z.array(moduleSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof moduleSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.moduleName) obj.moduleName = key;\n const result = moduleSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n author: z.string().default('sijeeshmiziha'),\n});\n\nexport type TBackendProjectSchema = z.infer<typeof projectSchema>;\n","/**\n * System prompt for database design - 5-phase analysis framework\n */\n\nexport const DB_DESIGN_SYSTEM_PROMPT = `You are an expert MongoDB database architect with deep expertise in schema design, performance optimization, scalability, and domain-driven design. You analyze requirements systematically using a multi-phase approach to create production-ready database schemas.\n\n## ANALYSIS FRAMEWORK\n\nYou MUST follow this 5-phase analysis process before generating the schema:\n\n### PHASE 1: Entity Discovery\nSystematically extract all entities from the provided requirements:\n\n1. **From dataInvolved fields**: Every item in user stories' dataInvolved[] array indicates a potential entity or field\n - Pattern: \"User Profile\" → user collection with profile fields\n - Pattern: \"Order Items\" → order collection + item collection with relationship\n - Pattern: \"Product Inventory\" → product collection with inventory fields\n\n2. **From User Types (Actors)**: Each actor type may indicate a User variant or role\n - Pattern: \"Admin\", \"Customer\", \"Vendor\" → User collection with role enum\n - Pattern: \"Guest\" → May not need persistence, or limited session data\n\n3. **From User Flow Actions**: Action verbs reveal implicit entities\n - \"creates order\" → Order collection\n - \"submits payment\" → Payment collection\n - \"uploads document\" → Document collection\n - \"sends message\" → Message collection\n\n4. **From Flow States**: Transitions reveal status enums\n - Flow: pending → approved → completed → Order.status enum\n - Flow: draft → published → archived → Content.status enum\n\n### PHASE 2: Relationship Mapping\nFor each entity pair, determine relationships based on:\n\n1. **Ownership Patterns** (from actor actions):\n - \"Customer places Order\" → Order.customer (many-to-one to User)\n - \"Admin approves Request\" → Request.approvedBy (many-to-one to User)\n - \"User creates Post\" → Post.author (many-to-one to User)\n\n2. **Cardinality from Flow Context**:\n - \"User has one profile\" → one-to-one\n - \"User places multiple orders\" → many-to-one (Order → User)\n - \"Order contains items\" → many-to-one (OrderItem → Order)\n\n3. **Shared Entities** (referenced across flows):\n - Entity referenced by multiple actors → likely needs relationships to User\n - Entity in multiple flows → likely a core/central entity\n\n4. **Bidirectional References** (for one-to-one):\n - Include reference field in BOTH collections for one-to-one relationships\n\n### PHASE 3: Permission Derivation\nMap actors to RBAC permissions:\n\n1. **Role Extraction**: Each actor type becomes a role value\n - actors: [Admin, Customer, Vendor] → role enum: ['admin', 'customer', 'vendor']\n\n2. **Permission Mining from User Stories**:\n - \"As Admin, I can delete users\" → admin: ['CREATE', 'READ', 'UPDATE', 'DELETE'] on user\n - \"As Customer, I can view my orders\" → customer: ['READ'] on order (own records)\n - \"As Vendor, I can update products\" → vendor: ['CREATE', 'READ', 'UPDATE'] on product\n\n3. **Data Visibility Rules**:\n - \"view own\" → READ permission with ownership filter\n - \"view all\" → READ permission without filter\n - \"manage\" → full CRUD permissions\n\n### PHASE 4: Query Pattern Inference\nAnalyze flows to predict database access patterns:\n\n1. **Read Patterns** (suggest indexes):\n - \"list orders by date\" → index on order.createdAt\n - \"search products by category\" → index on product.category\n - \"find user by email\" → unique index on user.email\n - \"filter by status\" → index on status field\n\n2. **Write Patterns** (affect schema design):\n - High-frequency writes → consider denormalization\n - Audit requirements → add createdBy, updatedBy fields\n\n3. **Aggregation Needs** (from reporting flows):\n - \"view sales dashboard\" → may need summary collections\n - \"generate reports\" → ensure proper indexing for date ranges\n\n### PHASE 5: Schema Construction\nSynthesize all analyses into the final schema:\n\n1. **Module Definition**:\n - One module per core entity\n - camelCase module names (never 'auth' or 'authentication')\n - Mark user modules with isUserModule: true\n\n2. **Field Completeness**:\n - All fields from dataInvolved\n - Relationship fields (Types.ObjectId with relationTo)\n - Status/lifecycle fields (enum type with values from flow states)\n - Audit fields: createdAt, updatedAt (Date, required)\n - createdBy, updatedBy when flows mention \"who did what\"\n\n3. **Validation Constraints**:\n - isRequired: true for fields mentioned in preconditions\n - isUnique: true for identifier fields (email, slug, code)\n - enum values from flow states and categorical data\n\n4. **Security Fields**:\n - password fields: fieldType: 'password', isPrivate: true\n - email fields: fieldType: 'email', isUnique: true\n\n## CORE CONSTRAINTS (MUST FOLLOW)\n\n1. **Primary Key**: _id with Types.ObjectId (auto-generated, do not include in fields)\n\n2. **Relationships**:\n - One-to-One: Reference field in BOTH collections\n - Many-to-One: Reference in the \"many\" side only\n - Many-to-Many: ONLY when necessary, use intermediate collection\n - One-to-Many: FORBIDDEN - invert to many-to-one from child\n\n3. **Data Types**:\n - NO arrays of ObjectIds for relationships\n - Timestamps: createdAt, updatedAt (Date) in EVERY collection\n - Enums: Use fieldType: 'enum' with values array\n\n4. **Security**:\n - NO separate \"Auth\" or \"Authentication\" collection\n - NO token storage in database\n - Password fields: isPrivate: true\n\n5. **Authorization (RBAC)**:\n - Define permissions per role on user modules\n - Format: {{ \"roleName\": [\"CREATE\", \"READ\", \"UPDATE\", \"DELETE\"] }}`;\n","/**\n * Design prompts - legacy and pro-level, plus structured requirement formatters\n */\n\nimport type {\n Actor,\n ExtractedFlow,\n ExtractedStory,\n StructuredRequirementsInput,\n TechnicalRequirements,\n} from '../types';\nimport { DB_DESIGN_SYSTEM_PROMPT } from './system.prompt';\n\n/**\n * Legacy: build design prompt from plain requirement string\n */\nexport function createDbDesignPrompt(requirement: string): string {\n return `${DB_DESIGN_SYSTEM_PROMPT}\n\nDesign a robust and efficient MongoDB database schema based on the following requirements:\n\n## Requirements\n${requirement}\n\n## Guidelines\n1. Use camelCase for module names and field names\n2. Include createdAt and updatedAt Date fields in every module\n3. Define proper relationships between modules\n4. Set appropriate permissions for user modules\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n\n/**\n * Format actors/user types into prompt-friendly string\n */\nexport function formatUserTypes(actors: Actor[]): string {\n if (!actors || actors.length === 0) {\n return 'No specific user types defined. Assume a general \"User\" role.';\n }\n return actors\n .map((actor, index) => {\n const goals = actor.goals.filter(g => g.trim()).join('\\n - ');\n return `### ${index + 1}. ${actor.name}\n**Description:** ${actor.description}\n**Goals:**\n - ${goals || 'No specific goals defined'}`;\n })\n .join('\\n\\n');\n}\n\n/**\n * Format user flows into prompt-friendly string\n */\nexport function formatUserFlows(flows: ExtractedFlow[], actors: Actor[]): string {\n if (!flows || flows.length === 0) {\n return 'No specific user flows defined.';\n }\n return flows\n .map((flow, index) => {\n const actor = actors.find(a => a.id === flow.actorId);\n const actorName = actor?.name || 'User';\n return `### ${index + 1}. ${flow.name}\n**Actor:** ${actorName}\n**Description:** ${flow.description}\n**Trigger:** ${flow.trigger || 'User initiates action'}\n**Outcome:** ${flow.outcome || 'Action completed'}`;\n })\n .join('\\n\\n');\n}\n\n/**\n * Format user stories with dataInvolved into prompt-friendly string\n */\nexport function formatUserStories(stories: ExtractedStory[], flows: ExtractedFlow[]): string {\n if (!stories || stories.length === 0) {\n return 'No specific user stories defined.';\n }\n const storiesByFlow = new Map<string, ExtractedStory[]>();\n for (const story of stories) {\n const flowStories = storiesByFlow.get(story.flowId) || [];\n flowStories.push(story);\n storiesByFlow.set(story.flowId, flowStories);\n }\n const sections: string[] = [];\n for (const flow of flows) {\n const flowStories = storiesByFlow.get(flow.id) || [];\n if (flowStories.length === 0) continue;\n sections.push(`### Flow: ${flow.name}\\n`);\n for (const story of flowStories) {\n const preconditions = story.preconditions.filter(p => p.trim());\n const postconditions = story.postconditions.filter(p => p.trim());\n const dataInvolved = story.dataInvolved.filter(d => d.trim());\n let storyText = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (preconditions.length > 0) {\n storyText += `\\n**Preconditions:**\\n${preconditions.map(p => `- ${p}`).join('\\n')}\\n`;\n }\n if (postconditions.length > 0) {\n storyText += `\\n**Postconditions:**\\n${postconditions.map(p => `- ${p}`).join('\\n')}\\n`;\n }\n if (dataInvolved.length > 0) {\n storyText += `\\n**Data Involved (IMPORTANT - these indicate entities/fields):**\\n${dataInvolved.map(d => `- ${d}`).join('\\n')}\\n`;\n }\n sections.push(storyText);\n }\n }\n const orphanStories = stories.filter(s => !flows.some(f => f.id === s.flowId));\n if (orphanStories.length > 0) {\n sections.push(`### Other Stories\\n`);\n for (const story of orphanStories) {\n const dataInvolved = story.dataInvolved.filter(d => d.trim());\n let storyText = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (dataInvolved.length > 0) {\n storyText += `\\n**Data Involved:** ${dataInvolved.join(', ')}\\n`;\n }\n sections.push(storyText);\n }\n }\n return sections.join('\\n');\n}\n\n/**\n * Format technical requirements into prompt-friendly string\n */\nexport function formatTechnicalRequirements(tech?: TechnicalRequirements): string {\n if (!tech) {\n return 'No specific technical requirements. Use defaults.';\n }\n const lines: string[] = [];\n lines.push(`**Authentication:** ${tech.authentication || 'none'}`);\n if (tech.authorization) {\n lines.push(`**Authorization (RBAC):** Enabled`);\n if (tech.roles && tech.roles.length > 0) {\n lines.push(`**Defined Roles:** ${tech.roles.join(', ')}`);\n }\n } else {\n lines.push(`**Authorization:** Disabled`);\n }\n if (tech.realtime) {\n lines.push(`**Realtime Features:** Required (consider subscription patterns)`);\n }\n if (tech.fileUpload) {\n lines.push(`**File Upload:** Required (consider file/document collection)`);\n }\n if (tech.search) {\n lines.push(`**Search Functionality:** Required (consider text indexes)`);\n }\n if (tech.integrations && tech.integrations.length > 0) {\n lines.push(`**Integrations:** ${tech.integrations.join(', ')}`);\n }\n return lines.join('\\n');\n}\n\n/**\n * Extract all unique dataInvolved items from stories for entity hints\n */\nexport function extractDataEntities(stories: ExtractedStory[]): string[] {\n const entities = new Set<string>();\n for (const story of stories) {\n for (const data of story.dataInvolved) {\n if (data.trim()) entities.add(data.trim());\n }\n }\n return Array.from(entities);\n}\n\n/**\n * Extract roles from actors for RBAC configuration\n */\nexport function extractRoles(actors: Actor[]): string[] {\n return actors.map(a => a.name.toLowerCase().replaceAll(/\\s+/g, '_'));\n}\n\n/**\n * Build complete prompt variables from structured requirements\n */\nexport function buildPromptVariables(input: StructuredRequirementsInput): Record<string, string> {\n return {\n projectName: input.projectName,\n projectGoal: input.projectGoal,\n projectDescription: input.projectDescription || input.projectGoal,\n userTypes: formatUserTypes(input.actors),\n userFlows: formatUserFlows(input.flows, input.actors),\n userStories: formatUserStories(input.stories, input.flows),\n technicalRequirements: formatTechnicalRequirements(input.technicalRequirements),\n };\n}\n\n/**\n * Pro-level DB design prompt from structured requirements\n */\nexport function createProDbDesignPrompt(input: StructuredRequirementsInput): string {\n const vars = buildPromptVariables(input);\n return `${DB_DESIGN_SYSTEM_PROMPT}\n\n---\n\n## PROJECT CONTEXT\n\n**Project Name:** ${vars.projectName}\n**Project Goal:** ${vars.projectGoal}\n**Description:** ${vars.projectDescription}\n\n---\n\n## USER TYPES (ACTORS)\n\nThese are the different types of users who will interact with the system. Each actor represents a potential role in your RBAC system.\n\n${vars.userTypes}\n\n---\n\n## USER FLOWS\n\nThese represent the key journeys users take through the system. Analyze these for:\n- Entity creation/modification patterns\n- State transitions (status enums)\n- Relationship ownership\n\n${vars.userFlows}\n\n---\n\n## USER STORIES WITH DATA REQUIREMENTS\n\nEach story includes dataInvolved - these are CRITICAL signals for your entity and field design.\n\n${vars.userStories}\n\n---\n\n## TECHNICAL REQUIREMENTS\n\n${vars.technicalRequirements}\n\n---\n\n## YOUR TASK\n\nFollow the 5-phase analysis framework:\n\n### Step 1: Entity Discovery\n- List ALL entities extracted from dataInvolved fields\n- Identify implicit entities from user flow actions\n- Map user types to User collection roles\n- Extract status enums from flow transitions\n\n### Step 2: Relationship Mapping\n- Define ownership: which actor creates/owns each entity\n- Determine cardinality from flow context\n- Identify bidirectional relationships\n\n### Step 3: Permission Derivation\n- Map each actor to a role\n- Extract CRUD permissions from user story actions\n- Define the permissions object for user modules\n\n### Step 4: Query Pattern Inference\n- Identify likely query patterns from flows\n- Note which fields need indexing (for your reference)\n\n### Step 5: Schema Construction\nGenerate the final schema with:\n- Complete module definitions\n- All fields with proper types\n- Relationships with relationTo and relationType\n- Status enums from flow states\n- RBAC permissions on user modules\n- Timestamps on every module\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n","/**\n * Redesign prompt - update existing schema based on user feedback\n */\n\nimport { DB_DESIGN_SYSTEM_PROMPT } from './system.prompt';\n\nexport function createRedesignPrompt(existingSchema: string, userFeedback: string): string {\n return `${DB_DESIGN_SYSTEM_PROMPT}\n\nUpdate the existing MongoDB schema based on user feedback.\n\n## Steps\n1. Analyze the existing MongoDB schema provided\n2. Review the user feedback to understand the required updates\n3. Update the schema to incorporate the requested changes while adhering to best practices\n\n## Existing Schema\n${existingSchema}\n\n## User Feedback\n${userFeedback}\n\nReturn the updated schema as a valid JSON object matching the original schema format.\nIMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`;\n}\n","/**\n * validate_schema tool - validates JSON against projectSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema } from '../schemas';\n\nexport const validateSchemaTool = defineTool({\n name: 'validate_schema',\n description:\n 'Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors array.',\n input: z.object({\n schema: z.string().describe('JSON string of the database project schema to validate'),\n }),\n handler: async ({ schema }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(schema) as unknown;\n projectSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * design_database tool - generates MongoDB schema from plain text requirement (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema, type TBackendProjectSchema } from '../schemas';\nimport { createDbDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_database tool. Requires a model to invoke for schema generation.\n */\nexport function createDesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'design_database',\n description:\n 'Generate a MongoDB database schema from plain text requirements. Use for ad-hoc or legacy requirements. Returns the full project schema as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the database requirements'),\n }),\n handler: async ({ requirement }): Promise<TBackendProjectSchema> => {\n const userPrompt = createDbDesignPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, projectSchema);\n },\n });\n}\n","/**\n * design_database_pro tool - generates MongoDB schema from structured requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema, type TBackendProjectSchema } from '../schemas';\nimport { createProDbDesignPrompt, extractDataEntities, extractRoles } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nconst structuredInputSchema = z.object({\n projectName: z.string(),\n projectGoal: z.string(),\n projectDescription: z.string().optional(),\n actors: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n })\n ),\n flows: z.array(\n z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n })\n ),\n stories: z.array(\n z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n })\n ),\n technicalRequirements: z\n .object({\n authentication: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['none', 'no', ''].includes(n)) return 'none' as const;\n if (['email', 'emailpassword', 'emailandpassword'].includes(n)) return 'email' as const;\n if (['oauth', 'oauth2', 'social'].includes(n)) return 'oauth' as const;\n if (['phone', 'phoneotp', 'sms'].includes(n)) return 'phone' as const;\n if (['emailandphone', 'emailphone', 'both'].includes(n))\n return 'email_and_phone' as const;\n return 'email' as const;\n })\n .pipe(z.enum(['none', 'email', 'oauth', 'phone', 'email_and_phone'])),\n authorization: z.coerce.boolean().default(false),\n roles: z.array(z.string()).optional(),\n integrations: z.array(z.string()).optional(),\n realtime: z.boolean().optional(),\n fileUpload: z.boolean().optional(),\n search: z.boolean().optional(),\n })\n .optional(),\n});\n\n/**\n * Creates the design_database_pro tool. Requires a model for schema generation.\n */\nexport function createDesignDatabaseProTool(model: Model) {\n return defineTool({\n name: 'design_database_pro',\n description:\n 'Generate a MongoDB schema from structured requirements (project name, goal, actors, flows, user stories with dataInvolved, technical requirements). Use for pro-level 5-phase analysis. Returns dbDesign and metadata (entitiesDetected, rolesExtracted).',\n input: structuredInputSchema,\n handler: async (\n input\n ): Promise<{\n dbDesign: TBackendProjectSchema;\n metadata: { entitiesDetected: string[]; rolesExtracted: string[] };\n }> => {\n const userPrompt = createProDbDesignPrompt(input);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n const dbDesign = parseModelJsonResponse(response.text, projectSchema);\n const metadata = {\n entitiesDetected: extractDataEntities(input.stories),\n rolesExtracted: extractRoles(input.actors),\n };\n return { dbDesign, metadata };\n },\n });\n}\n","/**\n * redesign_database tool - updates existing schema based on user feedback (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema, type TBackendProjectSchema } from '../schemas';\nimport { createRedesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the redesign_database tool. Requires a model for schema update.\n */\nexport function createRedesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'redesign_database',\n description:\n 'Update an existing MongoDB project schema based on user feedback. Provide the current schema JSON string and the feedback. Returns the updated schema as JSON.',\n input: z.object({\n existingSchema: z.string().describe('Current project schema as JSON string'),\n feedback: z.string().describe('User feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TBackendProjectSchema> => {\n const userPrompt = createRedesignPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, projectSchema);\n },\n });\n}\n","/**\n * db-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSchemaTool } from './validate-schema.tool';\nimport { createDesignDatabaseTool } from './design-database.tool';\nimport { createDesignDatabaseProTool } from './design-database-pro.tool';\nimport { createRedesignDatabaseTool } from './redesign-database.tool';\n\nexport { validateSchemaTool } from './validate-schema.tool';\nexport { createDesignDatabaseTool } from './design-database.tool';\nexport { createDesignDatabaseProTool } from './design-database-pro.tool';\nexport { createRedesignDatabaseTool } from './redesign-database.tool';\n\n/**\n * Create all db-designer tools for the agent. Pass the model for AI-backed tools.\n */\nexport function createDbDesignerTools(model: Model) {\n return createToolSet({\n validate_schema: validateSchemaTool,\n design_database: createDesignDatabaseTool(model),\n design_database_pro: createDesignDatabaseProTool(model),\n redesign_database: createRedesignDatabaseTool(model),\n });\n}\n","/**\n * entity-analyzer subagent - extracts entities, relationships, and roles from requirements (no tools)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENTITY_ANALYZER_SYSTEM_PROMPT = `You are an expert at analyzing software requirements to extract database design signals.\n\nFocus on PHASES 1-3 of the analysis framework:\n\n## PHASE 1: Entity Discovery\n- List every entity implied by the requirements (from dataInvolved, user types, flow actions, flow states).\n- Identify user/actor types that become roles.\n- Extract status enums from flow transitions.\n\n## PHASE 2: Relationship Mapping\n- For each entity pair, determine ownership (which actor creates/owns it).\n- Determine cardinality (one-to-one, many-to-one).\n- Note bidirectional relationships.\n\n## PHASE 3: Permission Derivation\n- Map each actor type to a role name.\n- From user story actions, infer CRUD permissions per role per entity.\n\nRespond with a clear, structured analysis (you can use headings and bullet points). The user will use this to generate or refine a MongoDB schema.`;\n\nexport const entityAnalyzerSubagent = defineSubagent({\n name: 'entity-analyzer',\n description:\n 'Analyzes raw requirements text to extract entities, relationships, and roles. Use when you need to understand what data and actors the system has before designing the schema. Returns structured analysis (no JSON).',\n systemPrompt: ENTITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * schema-refiner subagent - validates schema and suggests refinements (has validate_schema tool)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\nimport { validateSchemaTool } from '../tools/validate-schema.tool';\n\nconst SCHEMA_REFINER_SYSTEM_PROMPT = `You are an expert MongoDB schema reviewer. Your job is to:\n\n1. Validate the provided schema using the validate_schema tool.\n2. Compare the schema against the original requirements and identify gaps (missing fields, wrong relationships, missing permissions).\n3. Suggest concrete improvements or return a corrected schema description.\n\nWhen the user gives you a schema (as JSON string) and optionally the original requirements, first call validate_schema to check structure. Then analyze completeness and correctness. Respond with either refinement suggestions or a summary of issues.`;\n\nexport function createSchemaRefinerSubagent() {\n return defineSubagent({\n name: 'schema-refiner',\n description:\n 'Validates a MongoDB project schema and suggests refinements based on requirements. Use when you have a draft schema and want to check it or improve it. Has access to validate_schema tool.',\n systemPrompt: SCHEMA_REFINER_SYSTEM_PROMPT,\n tools: { validate_schema: validateSchemaTool },\n maxIterations: 5,\n });\n}\n","/**\n * runDbDesignerAgent - orchestrator for the full DB design workflow\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { DB_DESIGN_SYSTEM_PROMPT } from './prompts';\nimport { createDbDesignerTools } from './tools';\nimport { entityAnalyzerSubagent, createSchemaRefinerSubagent } from './subagents';\nimport type { DbDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${DB_DESIGN_SYSTEM_PROMPT}\n\nYou are the database design orchestrator. When the user asks for a database design:\n\n1. **Analyze first**: For complex or vague requirements, use subagent_entity-analyzer with a prompt that includes the user's requirements to get a structured analysis of entities, relationships, and roles.\n2. **Generate schema**: Use design_database (for plain text requirements) or design_database_pro (when the user provides structured requirements: project name, goal, actors, flows, user stories with dataInvolved, technical requirements) to produce the MongoDB schema.\n3. **Refine (optional)**: If the user wants validation or refinements, use subagent_schema-refiner with the current schema and requirements.\n4. **Validate**: You can use validate_schema to check any schema JSON before returning.\n5. **Redesign**: If the user asks for changes to an existing schema, use redesign_database with the existing schema string and their feedback.\n\nRespond with the final schema (as JSON) or a clear summary and the schema.`;\n\n/**\n * Run the db-designer orchestrator agent with all tools and subagents.\n */\nexport async function runDbDesignerAgent(config: DbDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const dbTools = createDbDesignerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet([entityAnalyzerSubagent, schemaRefiner], {\n parentModel: model,\n });\n const tools = createToolSet({ ...dbTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Branding schema for frontend app config\n */\n\nimport { z } from 'zod';\n\nexport const BrandingSchema = z.object({\n brandName: z.string().describe(\"The brand's display name\"),\n primaryColor: z.string().describe(\"The brand's primary color code (e.g., #FFFFFF)\"),\n secondaryColor: z.string().describe(\"The brand's secondary color code (e.g., #000000)\"),\n logo: z.url().describe(\"URL pointing to the brand's logo\"),\n});\n\nexport type TBrandingSchema = z.infer<typeof BrandingSchema>;\n","/**\n * App configuration schema\n */\n\nimport { z } from 'zod';\nimport { BrandingSchema } from './branding.schema';\n\nexport const AppConfigSchema = z.object({\n name: z.string().describe('Application name'),\n description: z.string().describe('Brief description of the application'),\n author: z\n .string()\n .describe('Author or owner of the application')\n .default('sijeeshmiziha (HubSpire)'),\n branding: BrandingSchema.describe('Branding information for the application'),\n apiEndpoint: z.url().describe(\"URL endpoint for the app's API calls\"),\n});\n\nexport type TAppConfigSchema = z.infer<typeof AppConfigSchema>;\n","/**\n * Form field, validation, options, and column schemas\n */\n\nimport { z } from 'zod';\n\nexport const ValidationSchema = z.object({\n minLength: z.number().optional().describe('Minimum length requirement'),\n zodString: z.string().describe('Raw Zod string validation (e.g. regex)'),\n});\n\nexport const FieldOptionsSchema = z.object({\n hookName: z.string().optional().describe('Name of the hook for dynamic field options'),\n queryString: z.string().optional().describe('Optional query string for fetching field options'),\n labelKey: z.string().optional().describe('Key used as label when displaying options'),\n valueKey: z.string().optional().describe('Key used as value for a field when selecting options'),\n values: z.array(z.string()).optional().describe('Static list of possible field values'),\n});\n\nexport const FormFieldSchema = z.object({\n name: z.string().describe(\"The field's key or identifier\"),\n type: z\n .enum([\n 'text',\n 'email',\n 'password',\n 'number',\n 'multiSelect',\n 'textarea',\n 'hidden',\n 'select',\n 'date',\n 'image',\n ])\n .describe(\n 'Type of input field. If it has options, it should not be \"hidden\". If the field is required, it should not be hidden unless it serves as the current user.'\n ),\n required: z.boolean().optional().describe('Whether this field must be filled'),\n validation: ValidationSchema.optional().describe('Optional field validation requirements'),\n defaultValue: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe('Default value can be string, number, or boolean'),\n options: FieldOptionsSchema.optional().describe(\n 'Additional dynamic or static options for this field'\n ),\n});\n\nexport const ColumnSchema = z.object({\n field: z.string().describe('Key or name of the data field in the table'),\n label: z.string().describe('User-friendly label to show on the table header'),\n});\n\nexport type TFormFieldSchema = z.infer<typeof FormFieldSchema>;\nexport type TColumnSchema = z.infer<typeof ColumnSchema>;\n","/**\n * API, drawer, auth page, listing page, and page union schemas\n */\n\nimport { z } from 'zod';\nimport { FormFieldSchema, ColumnSchema } from './field.schema';\n\nexport const ApiResponseTypeSchema = z\n .object({\n type: z.string().describe(\"Indicates the response type (e.g., 'object')\"),\n properties: z\n .record(\n z.string(),\n z.object({\n type: z.string().describe('Property type as returned by the API'),\n })\n )\n .describe('Key-value record describing each field in the response'),\n })\n .optional()\n .describe('Describes the expected structure of an API response');\n\nexport type TApiResponseTypeSchema = z.infer<typeof ApiResponseTypeSchema>;\n\nexport const ListingPageApiSchema = z.object({\n type: z\n .enum(['list', 'create', 'update', 'delete', 'getById'])\n .describe('Type of API call for CRUD operations'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const AuthPageApiSchema = z.object({\n type: z\n .enum(['login', 'currentUser', 'forgotPassword', 'resetPassword'])\n .describe('Type of API call'),\n graphqlHook: z.string().describe('Name of the GraphQL hook (e.g. useLoginMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const DrawerSchema = z.object({\n title: z.string().describe('Title displayed on the drawer'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)'),\n fields: z.array(FormFieldSchema).describe('List of fields displayed within the drawer'),\n});\n\nexport const AuthPageSchema = z.object({\n name: z\n .enum(['LoginPage', 'ForgotPasswordPage', 'ResetPasswordPage'])\n .describe('Internal name of the auth page'),\n type: z\n .enum(['EmailPassword', 'ForgotPassword', 'ResetPassword'])\n .describe('Type of authentication page'),\n route: z.string().describe(\"URL route for this page (e.g., '/login')\"),\n isPrivate: z.boolean().describe('Whether this page requires an authenticated session'),\n api: z.array(AuthPageApiSchema).describe('List of API calls involved in this page'),\n fields: z\n .array(FormFieldSchema)\n .optional()\n .describe('Optional form fields needed on this auth page'),\n});\n\nexport const ListingPageSchema = z.object({\n type: z.literal('Listing').describe('Indicates that this page is a listing-type page'),\n name: z.string().describe('Internal name of the listing page'),\n route: z.string().describe('URL route for this listing page'),\n isPrivate: z.boolean().describe('Whether this page is private (requires auth)'),\n api: z.array(ListingPageApiSchema).describe('List of API calls that power this listing page'),\n columns: z.array(ColumnSchema).describe('Table columns displayed on the listing page'),\n actions: z\n .array(z.string())\n .describe('List of possible actions on each row (e.g., create, edit, delete, view)'),\n drawerCreate: DrawerSchema.describe('Drawer configuration for creating new records'),\n drawerUpdate: DrawerSchema.describe('Drawer configuration for editing existing records'),\n});\n\nexport const PageSchema = z.discriminatedUnion('type', [AuthPageSchema, ListingPageSchema]);\n\nexport type TPageSchema = z.infer<typeof PageSchema>;\n","/**\n * Module and root application schema\n */\n\nimport { z } from 'zod';\nimport { AppConfigSchema } from './app-config.schema';\nimport { PageSchema } from './page.schema';\n\nexport const ModuleSchema = z.object({\n name: z.string().describe('Name of the module'),\n pages: z.array(PageSchema).describe('Pages included within this module'),\n});\n\nexport const ApplicationSchema = z.object({\n app: AppConfigSchema.describe('Overall application configuration'),\n modules: z\n .array(ModuleSchema)\n .describe(\n 'List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.'\n ),\n});\n\nexport type TApplicationSchema = z.infer<typeof ApplicationSchema>;\nexport type TModuleSchema = z.infer<typeof ModuleSchema>;\n","/**\n * User-related schemas - same as .ref/core/react/zodTypes.ts\n */\n\nimport { z } from 'zod';\n\nexport const LoginInputSchema = z.object({\n email: z.email().describe(\"User's email address, must be valid format\"),\n password: z.string().min(8).describe(\"User's password, minimum length of 8\"),\n});\n\nexport const SpecializationSchema = z.object({\n _id: z.string().describe('Unique identifier of the specialization, type: string'),\n title: z.string().describe('Display title for the specialization, type: string'),\n});\n\nexport const UserSchema = z.object({\n _id: z.string().describe('Unique ID of the user, type: string'),\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Email address in valid format, type: string'),\n phoneNumber: z.string().min(10).describe(\"User's phone number, at least 10 digits, type: string\"),\n profileImage: z\n .string()\n .optional()\n .describe(\"Optional URL to user's profile image, type: string, optional\"),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe(\"User's role in the system (ADMIN, TRAINER, CLIENT)\"),\n rate: z\n .number()\n .min(1)\n .optional()\n .describe(\"User's rate (e.g., hourly, etc.), type: number, optional\"),\n specializations: z\n .array(SpecializationSchema)\n .optional()\n .describe('Array of specialization objects, optional'),\n languages: z\n .array(z.string())\n .optional()\n .describe('Array of languages the user speaks, type: string[], optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Brief bio or description (20-500 chars), type: string, optional'),\n gender: z.string().optional().describe(\"User's gender, type: string, optional\"),\n timezone: z.string().optional().describe(\"User's timezone, type: string, optional\"),\n averageRating: z\n .number()\n .optional()\n .describe('Average rating for this user, type: number, optional'),\n});\n\nexport const CreateUserInputSchema = z.object({\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Valid email for the new user, type: string'),\n phoneNumber: z.string().min(10).describe('Phone number (at least 10 digits), type: string'),\n password: z.string().min(8).describe('Password with min length 8, type: string'),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe('Role of the new user (ADMIN, TRAINER, CLIENT)'),\n rate: z.number().min(1).optional().describe('Rate for the new user, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Array of specialization IDs, optional'),\n languages: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('List of languages user speaks, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe(\"User's about/bio field, 20-500 chars, optional\"),\n});\n\nexport const UpdateUserInputSchema = z.object({\n _id: z.string().describe('ID of the user to be updated, type: string'),\n firstName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated first name, type: string, optional'),\n lastName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated last name, type: string, optional'),\n email: z.email().optional().describe('Updated email, type: string, optional'),\n phoneNumber: z\n .string()\n .min(10)\n .optional()\n .describe('Updated phone number, at least 10 digits, optional'),\n rate: z.number().min(1).optional().describe('Updated rate, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Updated array of specialization IDs, optional'),\n languages: z.array(z.string()).min(1).optional().describe('Updated list of languages, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Updated about/bio (20-500 chars), optional'),\n});\n\nexport const ForgotPasswordSchema = z.object({\n email: z.email().describe('Email to initiate the password reset process, type: string'),\n});\n\nexport const ResetPasswordSchema = z.object({\n type: z.enum(['EMAIL', 'SMS']).describe('How the reset code was sent (EMAIL or SMS)'),\n resetTicket: z.string().describe('Token/ticket to validate the reset request, type: string'),\n newPassword: z.string().min(8).describe('The new password, min length 8, type: string'),\n});\n\nexport type TLoginInputSchema = z.infer<typeof LoginInputSchema>;\nexport type TUserSchema = z.infer<typeof UserSchema>;\nexport type TSpecializationSchema = z.infer<typeof SpecializationSchema>;\nexport type TCreateUserInputSchema = z.infer<typeof CreateUserInputSchema>;\nexport type TUpdateUserInputSchema = z.infer<typeof UpdateUserInputSchema>;\nexport type TForgotPasswordSchema = z.infer<typeof ForgotPasswordSchema>;\nexport type TResetPasswordSchema = z.infer<typeof ResetPasswordSchema>;\n","/**\n * System prompt for GraphQL-to-frontend configuration conversion\n */\n\nexport const REACT_BUILDER_SYSTEM_PROMPT = `You are an expert GraphQL-to-frontend configuration converter. Transform the provided GraphQL schema into a structured JSON configuration for a React + Vite frontend application.\n\n## Target Tech Stack\nThe generated configuration will be consumed by a Vite + React 19 + TypeScript template with:\n- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/\n- **Styling**: Tailwind CSS v4 with OKLCH color space\n- **Routing**: React Router v7 with private route support\n- **Forms**: React Hook Form + Zod validation (zodResolver)\n- **GraphQL Client**: Apollo Client with typed hooks from CodeGen\n- **Path Aliases**: @/{appName}/* maps to ./src/*\n\n**Your output must be valid JSON only.** No markdown code fences, no explanations. Return the raw JSON object matching the application schema (app with name, description, author, branding, apiEndpoint; modules array with name and pages; each page has type, name, route, isPrivate, api, and for listing pages: columns, actions, drawerCreate, drawerUpdate; for auth pages: fields when needed).\n\nStrict guidelines:\n- Use every available CRUD GraphQL query and mutation from the project schema.\n- Map GraphQL types to frontend modules and pages.\n- EmailAddress → \"type\": \"email\" with validation; DateTime → \"type\": \"date\"; enums → select with options.values.\n- Relationships → multiSelect with query-based options where appropriate.\n- Add isPrivate: true for authenticated operations (route guarded by React Router).\n- Form fields should map to React Hook Form + Zod validation schemas.\n- Maintain camelCase. Ensure valid JSON syntax.`;\n","/**\n * Instruction template for GraphQL-to-frontend conversion\n */\n\nexport const REACT_BUILDER_INSTRUCTION = `\nAct as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.\n\n**Conversion Process**\n\n1. Schema Analysis:\n- Identify all modules using 100% of available CRUD operations\n- Catalog all Query/Mutation operations with arguments\n- Map GraphQL types to frontend modules\n- Detect @auth directives and role requirements\n- Analyze relationships through nested types\n\n2. Field Mapping:\n- EmailAddress → \"type\": \"email\" with Zod email validation\n- DateTime → \"type\": \"date\"\n- Enums → dropdowns with options.values\n- Relationships → multiSelect with query-based options\n\n3. API Operations:\n- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape\n\n4. Validation:\n- Generate Zod schemas from @required directives, scalar types (Password → min 8 chars), custom directives\n- Include validation error messages\n\n5. Security:\n- Add isPrivate: true for authenticated operations\n- Implement role checks from @auth directives\n\n6. Output:\n- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks\n- Include Zod validation strings, maintain camelCase, valid JSON only\n`.trim();\n\nexport function buildInstructionPrompt(): string {\n return REACT_BUILDER_INSTRUCTION;\n}\n","/**\n * Few-shot examples: example GraphQL schema and expected JSON output (abbreviated)\n */\n\nexport const EXAMPLE_GRAPHQL_SCHEMA = `\ntype Query {\n getCurrentUser: User\n getAllUser(limit: Int, offset: Int): [User]!\n}\ntype Mutation {\n login(data: LoginInput!): Login!\n createUser(data: CreateUserInput!): User!\n}\ntype User {\n _id: ID!\n firstName: String!\n lastName: String!\n email: String!\n role: Role!\n}\nenum Role { ADMIN TRAINER CLIENT }\ninput LoginInput { email: String! password: String! }\ninput CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }\n`.trim();\n\nexport const EXAMPLE_JSON_OUTPUT = `{\n \"app\": {\n \"name\": \"my-app\",\n \"description\": \"App description\",\n \"author\": \"Author\",\n \"branding\": {\n \"brandName\": \"MyBrand\",\n \"primaryColor\": \"#333\",\n \"secondaryColor\": \"#fff\",\n \"logo\": \"https://example.com/logo.png\"\n },\n \"apiEndpoint\": \"http://localhost:4000/graphql\"\n },\n \"modules\": [\n {\n \"name\": \"auth\",\n \"pages\": [\n {\n \"name\": \"LoginPage\",\n \"type\": \"EmailPassword\",\n \"route\": \"/login\",\n \"isPrivate\": false,\n \"api\": [\n { \"type\": \"login\", \"graphqlHook\": \"useLoginMutation\", \"queryString\": \"mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }\" }\n ]\n }\n ]\n },\n {\n \"name\": \"user\",\n \"pages\": [\n {\n \"type\": \"Listing\",\n \"name\": \"UserListPage\",\n \"route\": \"/users\",\n \"isPrivate\": true,\n \"api\": [\n { \"type\": \"list\", \"graphqlHook\": \"useGetAllUserQuery\", \"queryString\": \"query GetAllUser { getAllUser { _id firstName email } }\" },\n { \"type\": \"create\", \"graphqlHook\": \"useCreateUserMutation\", \"queryString\": \"mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }\" }\n ],\n \"columns\": [{ \"field\": \"firstName\", \"label\": \"First Name\" }, { \"field\": \"email\", \"label\": \"Email\" }],\n \"actions\": [\"create\", \"edit\", \"delete\"],\n \"drawerCreate\": { \"title\": \"Create User\", \"graphqlHook\": \"useCreateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\", \"required\": true }, { \"name\": \"email\", \"type\": \"email\", \"required\": true }] },\n \"drawerUpdate\": { \"title\": \"Edit User\", \"graphqlHook\": \"useUpdateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\" }, { \"name\": \"email\", \"type\": \"email\" }] }\n }\n ]\n }\n ]\n}`;\n\nexport function buildExampleShotPrompt(): string {\n return `\n**Reference Conversion Example**\n\nEXAMPLE GRAPHQL INPUT:\n\\`\\`\\`graphql\n${EXAMPLE_GRAPHQL_SCHEMA}\n\\`\\`\\`\n\nEXPECTED JSON OUTPUT:\n\\`\\`\\`json\n${EXAMPLE_JSON_OUTPUT}\n\\`\\`\\`\n`.trim();\n}\n","/**\n * Feedback prompt - re-generate frontend config incorporating user feedback\n */\n\nexport function buildFeedbackPrompt(userFeedback: string, schemaFile: string): string {\n return `\nReview the user feedback carefully to understand the required updates.\n\nThe user feedback for updating the generated Frontend Config JSON is provided below:\n\"\"\"\n${userFeedback}\n\"\"\"\n\nNow, generate the Frontend Config JSON for this project based on the provided feedback.\n\n**Project GRAPHQL SCHEMA INPUT:**\n\\`\\`\\`graphql\n${schemaFile}\n\\`\\`\\`\n\nUpdate the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.\n`.trim();\n}\n","/**\n * validate_frontend_config tool - validates JSON against ApplicationSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { ApplicationSchema } from '../schemas';\n\nexport const validateFrontendConfigTool = defineTool({\n name: 'validate_frontend_config',\n description:\n 'Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.',\n input: z.object({\n config: z.string().describe('JSON string of the frontend application config to validate'),\n }),\n handler: async ({ config }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(config) as unknown;\n ApplicationSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * generate_frontend tool - converts GraphQL schema to frontend config JSON (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { ApplicationSchema, type TApplicationSchema } from '../schemas';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from '../prompts/system.prompt';\nimport { buildInstructionPrompt, buildExampleShotPrompt } from '../prompts';\nimport type { AppInfo } from '../types';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nfunction buildGeneratePrompt(graphqlSchema: string, appInfo?: AppInfo): string {\n const instruction = buildInstructionPrompt();\n const example = buildExampleShotPrompt();\n const appInfoBlock = appInfo\n ? `\n**Project context:**\n- name: ${appInfo.projectName ?? 'project'}\n- description: ${appInfo.projectDescription ?? ''}\n- modules: ${appInfo.modules ?? ''}\n- apiEndpoint: ${appInfo.apiEndpoint ?? 'http://localhost:4000/graphql'}\n`\n : '';\n return `${instruction}\n\n${example}\n${appInfoBlock}\n\n**Current Project GraphQL Schema:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nGenerate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`;\n}\n\nexport function createGenerateFrontendTool(model: Model) {\n return defineTool({\n name: 'generate_frontend',\n description:\n 'Convert a GraphQL schema into a frontend configuration JSON (app, modules, pages, fields, API hooks). Optionally provide app info (project name, description, apiEndpoint). Returns the full application config as JSON.',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to convert'),\n appInfo: z\n .object({\n projectName: z.string().optional(),\n projectDescription: z.string().optional(),\n modules: z.string().optional(),\n apiEndpoint: z.string().optional(),\n })\n .optional()\n .describe('Optional project/app context'),\n }),\n handler: async ({ graphqlSchema, appInfo }): Promise<TApplicationSchema> => {\n const userPrompt = buildGeneratePrompt(graphqlSchema, appInfo);\n const messages = [\n { role: 'system' as const, content: REACT_BUILDER_SYSTEM_PROMPT },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, ApplicationSchema);\n },\n });\n}\n","/**\n * generate_feature_breakdown tool - breaks down GraphQL schema into components/pages (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { REACT_BUILDER_INSTRUCTION } from '../prompts/instruction.prompt';\n\nexport interface FeatureBreakdownResult {\n summary: string;\n modules: string[];\n operations: string[];\n suggestedPages?: string[];\n}\n\nexport function createGenerateFeatureBreakdownTool(model: Model) {\n return defineTool({\n name: 'generate_feature_breakdown',\n description:\n 'Analyze a GraphQL schema and produce a feature/component breakdown: list of modules, CRUD operations, and suggested pages. Returns a structured summary (not the full frontend JSON).',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to analyze'),\n }),\n handler: async ({ graphqlSchema }): Promise<FeatureBreakdownResult> => {\n const userPrompt = `${REACT_BUILDER_INSTRUCTION}\n\n**Schema to analyze:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nRespond with a structured breakdown only (no full JSON config): list modules, list Query/Mutation operations, and suggested pages for each module. Use clear headings and bullet points.`;\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a GraphQL schema analyst. Return a clear, structured text breakdown.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 4096 });\n return { summary: response.text, modules: [], operations: [], suggestedPages: [] };\n },\n });\n}\n","/**\n * scaffold_vite tool - compiles .ref/templates/vite/ with ApplicationSchema config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult, TemplateContext } from '../../../lib/template-engine';\nimport type { TApplicationSchema } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert ApplicationSchema config to template context */\nfunction toTemplateContext(config: TApplicationSchema): TemplateContext {\n return {\n appName: config.app.name,\n description: config.app.description,\n apiEndpoint: config.app.apiEndpoint,\n branding: {\n brandName: config.app.branding.brandName,\n primaryColor: config.app.branding.primaryColor,\n secondaryColor: config.app.branding.secondaryColor,\n logo: config.app.branding.logo,\n },\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n })),\n author: config.app.author,\n pages: config.modules.flatMap(m => m.pages),\n };\n}\n\nexport const scaffoldViteTool = defineTool({\n name: 'scaffold_vite',\n description:\n 'Scaffold a Vite + React project from a validated ApplicationSchema config. Compiles Handlebars templates from .ref/templates/vite/ and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated ApplicationSchema config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'application schema config') as TApplicationSchema;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/vite');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * react-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nimport { createGenerateFrontendTool } from './generate-frontend.tool';\nimport { createGenerateFeatureBreakdownTool } from './generate-feature-breakdown.tool';\nimport { scaffoldViteTool } from './scaffold-vite';\n\nexport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nexport { createGenerateFrontendTool } from './generate-frontend.tool';\nexport {\n createGenerateFeatureBreakdownTool,\n type FeatureBreakdownResult,\n} from './generate-feature-breakdown.tool';\nexport { scaffoldViteTool } from './scaffold-vite';\n\nexport function createReactBuilderTools(model: Model) {\n return createToolSet({\n validate_frontend_config: validateFrontendConfigTool,\n generate_frontend: createGenerateFrontendTool(model),\n generate_feature_breakdown: createGenerateFeatureBreakdownTool(model),\n scaffold_vite: scaffoldViteTool,\n });\n}\n","/**\n * graphql-analyzer subagent - analyzes GraphQL schemas (no tools)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst GRAPHQL_ANALYZER_SYSTEM_PROMPT = `You are an expert at analyzing GraphQL schemas. Your job is to:\n\n1. **Types**: List all object types, enums, scalars, and input types.\n2. **Queries**: List every Query field with arguments and return type.\n3. **Mutations**: List every Mutation field with arguments and return type.\n4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).\n5. **Auth/directives**: Note any @auth, @directive usage that affects access control.\n\nRespond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`;\n\nexport const graphqlAnalyzerSubagent = defineSubagent({\n name: 'graphql-analyzer',\n description:\n 'Analyzes a GraphQL schema to extract types, queries, mutations, and relationships. Use when you need to understand the schema before generating frontend config. Returns structured analysis (no JSON).',\n systemPrompt: GRAPHQL_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * config-validator subagent - validates frontend config (has validate_frontend_config tool)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\nimport { validateFrontendConfigTool } from '../tools/validate-frontend-config.tool';\n\nconst CONFIG_VALIDATOR_SYSTEM_PROMPT = `You are a frontend configuration validator. Your job is to:\n\n1. Validate the provided frontend config JSON using the validate_frontend_config tool.\n2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.\n3. Report any missing modules, pages, or API hooks.\n\nWhen the user gives you a config (as JSON string) and optionally the GraphQL schema, first call validate_frontend_config to check structure. Then summarize completeness.`;\n\nexport function createConfigValidatorSubagent() {\n return defineSubagent({\n name: 'config-validator',\n description:\n 'Validates a frontend configuration JSON and checks completeness against the GraphQL schema. Use when you have a draft config and want to validate it. Has access to validate_frontend_config tool.',\n systemPrompt: CONFIG_VALIDATOR_SYSTEM_PROMPT,\n tools: { validate_frontend_config: validateFrontendConfigTool },\n maxIterations: 5,\n });\n}\n","/**\n * runReactBuilderAgent - orchestrator for frontend config generation with retry and subagents\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createReactBuilderTools } from './tools';\nimport { graphqlAnalyzerSubagent, createConfigValidatorSubagent } from './subagents';\nimport type { ReactBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${REACT_BUILDER_SYSTEM_PROMPT}\n\nYou are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:\n\n1. **Analyze (optional)**: For complex schemas, use subagent_graphql-analyzer with a prompt that includes the schema to get a structured analysis of types, queries, and mutations.\n2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.\n3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.\n4. **Validate directly**: You can use validate_frontend_config to check any config JSON.\n5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.\n\nRespond with the final frontend config (as JSON) or a clear summary and the config. If the user gives feedback, use generate_frontend again with the same schema and consider their feedback in your instructions.`;\n\n/**\n * Run the react-builder orchestrator agent with all tools and subagents.\n * Use generate_frontend tool for config generation; the tool may throw on parse failure (caller can retry with new input).\n */\nexport async function runReactBuilderAgent(config: ReactBuilderAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const reactTools = createReactBuilderTools(model);\n const configValidator = createConfigValidatorSubagent();\n const subagentTools = createSubagentToolSet([graphqlAnalyzerSubagent, configValidator], {\n parentModel: model,\n });\n const tools = createToolSet({ ...reactTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schema for extract_actors tool output\n */\n\nimport { z } from 'zod';\n\nexport const actorSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n});\n\nexport const actorsResultSchema = z.object({\n actors: z.array(actorSchema),\n message: z.string(),\n});\n\nexport type ActorResult = z.infer<typeof actorsResultSchema>;\n","/**\n * Zod schema for generate_flows tool output\n */\n\nimport { z } from 'zod';\n\nexport const flowSchema = z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n});\n\nexport const flowsResultSchema = z.object({\n flows: z.array(flowSchema),\n message: z.string(),\n});\n\nexport type FlowsResult = z.infer<typeof flowsResultSchema>;\n","/**\n * Zod schema for generate_stories tool output\n */\n\nimport { z } from 'zod';\n\nexport const storySchema = z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n});\n\nexport const storiesResultSchema = z.object({\n stories: z.array(storySchema),\n message: z.string(),\n});\n\nexport type StoriesResult = z.infer<typeof storiesResultSchema>;\n","/**\n * Zod schema for extract_modules tool output\n */\n\nimport { z } from 'zod';\n\nexport const crudApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n operation: z.enum(['create', 'read', 'readAll', 'update', 'delete']),\n description: z.string(),\n inputs: z.array(z.string()),\n outputs: z.array(z.string()),\n});\n\nexport const extractedModuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n entity: z.string(),\n apis: z.array(crudApiSchema),\n});\n\nexport const modulesResultSchema = z.object({\n modules: z.array(extractedModuleSchema),\n summary: z.object({\n totalModules: z.number(),\n totalApis: z.number(),\n }),\n message: z.string(),\n});\n\nexport type ModulesResult = z.infer<typeof modulesResultSchema>;\n","/**\n * Zod schemas for DatabaseDesign, DatabaseEntity, EntityField, EntityIndex, EntityRelation\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.boolean(),\n unique: z.boolean(),\n description: z.string(),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string(),\n fields: z.array(z.string()),\n unique: z.boolean(),\n});\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n description: z.string(),\n});\n\nexport const databaseEntitySchema = z.object({\n name: z.string(),\n description: z.string(),\n fields: z.array(entityFieldSchema),\n indexes: z.array(entityIndexSchema),\n relations: z.array(entityRelationSchema),\n});\n\nexport const databaseDesignSchema = z.object({\n type: z.enum(['mongodb', 'postgresql']),\n reasoning: z.string(),\n entities: z.array(databaseEntitySchema),\n});\n\nexport type EntityField = z.infer<typeof entityFieldSchema>;\nexport type EntityIndex = z.infer<typeof entityIndexSchema>;\nexport type EntityRelation = z.infer<typeof entityRelationSchema>;\nexport type DatabaseEntity = z.infer<typeof databaseEntitySchema>;\nexport type DatabaseDesign = z.infer<typeof databaseDesignSchema>;\n","/**\n * Zod schemas for ApiDesign, RestEndpoint, GraphqlTypeDefinition, GraphqlOperation\n * Uses coercion so LLM output (e.g. \"GET\" vs \"get\", \"true\" vs true) still validates.\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .union([z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toUpperCase() : s))\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nconst optionalStringRecordSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .transform(m =>\n Object.fromEntries(\n Object.entries(m ?? {}).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)])\n )\n );\n\nexport const restEndpointSchema = z.object({\n id: z.string(),\n moduleId: z.string(),\n method: httpMethodSchema,\n path: z.string(),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n requestBody: optionalStringRecordSchema,\n responseBody: optionalStringRecordSchema,\n queryParams: optionalStringRecordSchema,\n});\n\nexport const restApiDesignSchema = z.object({\n baseUrl: z.string().default('/api/v1'),\n endpoints: z.array(restEndpointSchema).default([]),\n});\n\nexport const graphqlTypeFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n description: z.string(),\n});\n\nconst graphqlKindSchema = z\n .union([z.enum(['type', 'input', 'enum']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toLowerCase() : s))\n .pipe(z.enum(['type', 'input', 'enum']));\n\nexport const graphqlTypeDefinitionSchema = z.object({\n name: z.string(),\n kind: graphqlKindSchema,\n fields: z.array(graphqlTypeFieldSchema),\n});\n\nexport const graphqlOperationArgSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n});\n\nexport const graphqlOperationSchema = z.object({\n name: z.string(),\n moduleId: z.string(),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n args: z.array(graphqlOperationArgSchema),\n returnType: z.string(),\n});\n\nexport const graphqlApiDesignSchema = z.object({\n types: z.array(graphqlTypeDefinitionSchema).default([]),\n queries: z.array(graphqlOperationSchema).default([]),\n mutations: z.array(graphqlOperationSchema).default([]),\n});\n\nconst apiStyleSchema = z\n .union([z.enum(['rest', 'graphql']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toLowerCase() : s))\n .pipe(z.enum(['rest', 'graphql']));\n\nexport const apiDesignSchema = z.object({\n style: apiStyleSchema,\n rest: restApiDesignSchema.optional(),\n graphql: graphqlApiDesignSchema.optional(),\n});\n\nexport type RestEndpoint = z.infer<typeof restEndpointSchema>;\nexport type RestApiDesign = z.infer<typeof restApiDesignSchema>;\nexport type GraphqlTypeDefinition = z.infer<typeof graphqlTypeDefinitionSchema>;\nexport type GraphqlOperation = z.infer<typeof graphqlOperationSchema>;\nexport type GraphqlApiDesign = z.infer<typeof graphqlApiDesignSchema>;\nexport type ApiDesign = z.infer<typeof apiDesignSchema>;\n","/**\n * Zod schemas for RequirementContext, ProjectBrief, Question, ChatEntry\n */\n\nimport { z } from 'zod';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\nimport { apiDesignSchema } from './api-design.schema';\n\nexport const projectBriefSchema = z.object({\n name: z.string(),\n goal: z.string(),\n features: z.array(z.string()),\n domain: z.string(),\n database: z.enum(['mongodb', 'postgresql']),\n backendRuntime: z.literal('nodejs'),\n apiStyle: z.enum(['rest', 'graphql']),\n});\n\nexport const questionSchema = z.object({\n id: z.string(),\n question: z.string(),\n context: z.string(),\n suggestions: z.array(z.string()),\n multiSelect: z.boolean(),\n required: z.boolean(),\n});\n\nexport const chatEntrySchema = z.object({\n role: z.enum(['user', 'assistant']),\n content: z.string(),\n});\n\nexport const requirementContextSchema = z.object({\n stage: z.enum(['discovery', 'requirements', 'design', 'complete']),\n projectBrief: projectBriefSchema.nullable(),\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema.nullable(),\n apiDesign: apiDesignSchema.nullable(),\n history: z.array(chatEntrySchema),\n pendingQuestions: z.array(questionSchema),\n});\n\nexport type ProjectBrief = z.infer<typeof projectBriefSchema>;\nexport type Question = z.infer<typeof questionSchema>;\nexport type ChatEntry = z.infer<typeof chatEntrySchema>;\nexport type RequirementContext = z.infer<typeof requirementContextSchema>;\n","/**\n * Zod schemas for FinalRequirement, RequirementSummary\n */\n\nimport { z } from 'zod';\nimport { projectBriefSchema } from './context.schema';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\nimport { apiDesignSchema } from './api-design.schema';\n\nexport const requirementSummarySchema = z.object({\n totalActors: z.number(),\n totalFlows: z.number(),\n totalStories: z.number(),\n totalModules: z.number(),\n totalEntities: z.number(),\n totalEndpoints: z.number(),\n overview: z.string(),\n});\n\nexport const finalRequirementSchema = z.object({\n project: projectBriefSchema,\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema,\n apiDesign: apiDesignSchema,\n summary: requirementSummarySchema,\n});\n\nexport type RequirementSummary = z.infer<typeof requirementSummarySchema>;\nexport type FinalRequirement = z.infer<typeof finalRequirementSchema>;\n","/**\n * System prompt for chat-based requirement gathering\n */\n\nexport const REQUIREMENT_GATHERER_SYSTEM_PROMPT = `You are a senior fullstack developer helping scope and plan a project. Your role is to understand what the user wants to build and produce a clear, actionable requirement document.\n\nYou work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).\n\nThink about the project the way a developer would: core problem, user interactions, data model, auth, integrations, real-time needs. Do NOT ask generic template questions (e.g. scale, complexity level, \"how many users?\"). Ask only questions that directly unblock design decisions.\n\nGuidelines:\n- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.\n- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.\n- Never repeat a question already answered in the conversation history.\n- When the user says \"continue\", \"yes\", \"looks good\", or similar, treat it as confirmation and advance.\n- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).\n- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;\n","/**\n * Discovery stage prompt - understand project and optionally ask questions\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `You are in the discovery stage. Parse the user's message (and prior context) into a structured project brief. Ask clarifying questions only when something genuinely blocks design decisions.\n\nDetermine from the user's words:\n- Project name and goal\n- Key features (array of strings)\n- Domain (e.g. e-commerce, healthcare, saas)\n- API style: \"rest\" | \"graphql\" — infer from context or ask with predefined options\n- Database: \"mongodb\" | \"postgresql\" — ask which they are comfortable with, with predefined options\n- Backend is always \"nodejs\"\n\nQuestion rules:\n- Tech stack (API style, database): Always provide \"suggestions\" with predefined options (e.g. [\"REST\", \"GraphQL\"], [\"MongoDB\", \"PostgreSQL\"]). Frame as \"which are you comfortable with?\"\n- All other questions: Use \"suggestions\": []. Ask open-ended, specific to what the user described (e.g. file uploads, real-time features, auth provider, core user action).\n- Never ask: scale, \"how many users?\", \"what's the complexity?\", or generic intake-form questions.\n- Before asking, check conversation history — never repeat something already answered.\n- If the user's message is clear enough (e.g. \"Instagram clone with photo sharing, messaging, stories\"), infer the obvious and ask only about genuine gaps. If you have enough for the brief, set needsClarification to false and empty questions.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nAnalyze the message and prior context. If you have enough to fill the project brief, return it and set needsClarification to false. Otherwise ask 1-3 short, problem-focused questions.\n\nReturn ONLY valid JSON (no markdown, no explanation) in this shape:\n{\n \"needsClarification\": boolean,\n \"questions\": [\n {\n \"id\": \"q1\",\n \"question\": \"Question text\",\n \"context\": \"Why this helps\",\n \"suggestions\": [],\n \"multiSelect\": false,\n \"required\": true\n }\n ],\n \"conversationalMessage\": \"Brief friendly message to the user\",\n \"projectBrief\": {\n \"name\": \"string\",\n \"goal\": \"string\",\n \"features\": [\"string\"],\n \"domain\": \"string\",\n \"database\": \"mongodb\" | \"postgresql\",\n \"backendRuntime\": \"nodejs\",\n \"apiStyle\": \"rest\" | \"graphql\"\n }\n}\n\nFor tech choices (API style, database), populate \"suggestions\" with the predefined options. For all other questions, use \"suggestions\": [].\nIf needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - actors, flows, stories, modules (chained)\n */\n\nconst PROJECT_BLOCK = `## Project:\n- **Name**: {projectName}\n- **Goal**: {projectGoal}\n- **Features**: {projectFeatures}`;\n\nexport const EXTRACT_ACTORS_PROMPT = `${PROJECT_BLOCK}\n\nIdentify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.\n\nReturn ONLY valid JSON:\n{\n \"actors\": [\n { \"id\": \"actor-1\", \"name\": \"Name\", \"description\": \"Who they are\", \"goals\": [\"goal1\", \"goal2\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_FLOWS_PROMPT = `${PROJECT_BLOCK}\n\n## Actors (JSON):\n{actors}\n\nFor EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.\n\nReturn ONLY valid JSON:\n{\n \"flows\": [\n { \"id\": \"flow-1\", \"actorId\": \"actor-1\", \"name\": \"Flow Name\", \"description\": \"...\", \"trigger\": \"...\", \"outcome\": \"...\" }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_STORIES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n\n## Flows (JSON):\n{flows}\n\nFor EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.\n\nReturn ONLY valid JSON:\n{\n \"stories\": [\n { \"id\": \"story-1\", \"flowId\": \"flow-1\", \"actor\": \"ActorName\", \"action\": \"...\", \"benefit\": \"...\", \"preconditions\": [], \"postconditions\": [], \"dataInvolved\": [\"User.email\", \"Order.total\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const EXTRACT_MODULES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n## Flows: {flows}\n## Stories (JSON):\n{stories}\n\nExtract modules (one per major entity). Each module has apis: create, read, readAll, update, delete plus any extra (e.g. searchUsers). CamelCase names. Clear inputs/outputs.\n\nReturn ONLY valid JSON:\n{\n \"modules\": [\n { \"id\": \"module-1\", \"name\": \"User\", \"description\": \"...\", \"entity\": \"User\", \"apis\": [ { \"id\": \"api-1-1\", \"name\": \"createUser\", \"operation\": \"create\", \"description\": \"...\", \"inputs\": [], \"outputs\": [] } ] }\n ],\n \"summary\": { \"totalModules\": 0, \"totalApis\": 0 },\n \"message\": \"Brief explanation\"\n}`;\n\nexport function buildExtractActorsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string\n): string {\n return EXTRACT_ACTORS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures);\n}\n\nexport function buildGenerateFlowsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string\n): string {\n return GENERATE_FLOWS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson);\n}\n\nexport function buildGenerateStoriesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string\n): string {\n return GENERATE_STORIES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson);\n}\n\nexport function buildExtractModulesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string,\n storiesJson: string\n): string {\n return EXTRACT_MODULES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson)\n .replace('{stories}', storiesJson);\n}\n","/**\n * Design stage prompts - direct LLM invocation for database and API design\n */\n\nconst DESIGN_DB_PROMPT = `You are a database architect. The project brief includes a \"database\" field (mongodb or postgresql)—use that database. Do not choose a different one. Output a single JSON object.\n\n## Project brief (includes database: \"mongodb\" | \"postgresql\"):\n{projectBrief}\n\n## Modules (entities and CRUD):\n{modules}\n\n## User stories (data involved):\n{stories}\n\nDesign the schema for the chosen database. For MongoDB use types like ObjectId, string, number, date, array; for PostgreSQL use varchar(n), text, integer, uuid, timestamp, jsonb, and proper foreign key relations.\n\nReturn ONLY valid JSON (no markdown) in this exact shape. Set \"type\" to the database from the project brief.\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences on how the schema fits the project\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"index_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nconst DESIGN_APIS_PROMPT = `You are an API architect for Node.js backends. Design the API according to apiStyle in the project brief.\n\n## Project brief (includes apiStyle: \"rest\" | \"graphql\"):\n{projectBrief}\n\n## Modules:\n{modules}\n\n## Actors:\n{actors}\n\n## Stories:\n{stories}\n\n## Database design (entities and fields):\n{database}\n\nProduce an API design:\n- If apiStyle is \"rest\": include \"rest\" with baseUrl (e.g. \"/api/v1\") and endpoints array. Each endpoint: id, moduleId, method (exactly one of GET, POST, PUT, PATCH, DELETE), path, description, auth (boolean), roles (array of strings), requestBody/responseBody/queryParams (flat object of string keys to string values, or {}). responseBody must always be a flat object, never an array—even for list endpoints use a single object describing the shape (e.g. for GET /users use \"responseBody\": { \"items\": \"array of user objects\", \"total\": \"number\" }).\n- If apiStyle is \"graphql\": include \"graphql\" with types (kind: \"type\" | \"input\" | \"enum\", fields array), queries, mutations. Each operation: name, moduleId, description, auth (boolean), roles (array), args (name, type, required boolean), returnType.\n\nReturn ONLY valid JSON (no markdown, no code fences). Required shape:\n{\n \"style\": \"rest\" or \"graphql\",\n \"rest\": { \"baseUrl\": \"/api/v1\", \"endpoints\": [ { \"id\": \"ep-1\", \"moduleId\": \"module-1\", \"method\": \"GET\", \"path\": \"/users\", \"description\": \"List users\", \"auth\": true, \"roles\": [], \"requestBody\": {}, \"responseBody\": { \"items\": \"array of user objects\", \"total\": \"number\" }, \"queryParams\": {} } ] },\n \"graphql\": { \"types\": [], \"queries\": [], \"mutations\": [] }\n}\n- Use lowercase \"rest\" or \"graphql\" for style. Omit the branch not used (omit \"graphql\" when style is \"rest\", omit \"rest\" when style is \"graphql\").`;\n\nexport const DESIGN_DATABASE_SYSTEM_PROMPT =\n 'You output only valid JSON. No markdown, no explanation.';\n\nexport const DESIGN_APIS_SYSTEM_PROMPT = 'You output only valid JSON. No markdown, no explanation.';\n\nexport function buildDesignDatabasePrompt(\n projectBrief: string,\n modules: string,\n stories: string\n): string {\n return DESIGN_DB_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{stories}', stories);\n}\n\nexport function buildDesignApisPrompt(\n projectBrief: string,\n modules: string,\n actors: string,\n stories: string,\n database: string\n): string {\n return DESIGN_APIS_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{actors}', actors)\n .replace('{stories}', stories)\n .replace('{database}', database);\n}\n","/**\n * Synthesis stage prompt - compile FinalRequirement document\n */\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `You are in the complete stage. You have the full context: project brief, actors, flows, stories, modules, database design, and API design. Your job is to produce a single final requirement document (JSON) that matches the FinalRequirement schema, with a summary that includes totalActors, totalFlows, totalStories, totalModules, totalEntities, totalEndpoints, and a short overview paragraph.`;\n\nexport const SYNTHESIS_USER_PROMPT = `## Project brief (JSON):\n{projectBrief}\n\n## Actors (JSON):\n{actors}\n\n## Flows (JSON):\n{flows}\n\n## Stories (JSON):\n{stories}\n\n## Modules (JSON):\n{modules}\n\n## Database design (JSON):\n{database}\n\n## API design (JSON):\n{apiDesign}\n\nCompile the above into one FinalRequirement JSON. Include a \"summary\" object with: totalActors, totalFlows, totalStories, totalModules, totalEntities (from database.entities.length), totalEndpoints (count of REST endpoints or GraphQL queries+mutations as appropriate), and \"overview\" (2-4 sentence paragraph summarizing the project and tech choices).\n\nReturn ONLY valid JSON in this shape (no markdown, no extra text):\n{\n \"project\": { ... },\n \"actors\": [ ... ],\n \"flows\": [ ... ],\n \"stories\": [ ... ],\n \"modules\": [ ... ],\n \"database\": { ... },\n \"apiDesign\": { ... },\n \"summary\": {\n \"totalActors\": 0,\n \"totalFlows\": 0,\n \"totalStories\": 0,\n \"totalModules\": 0,\n \"totalEntities\": 0,\n \"totalEndpoints\": 0,\n \"overview\": \"string\"\n }\n}`;\n\nexport function buildSynthesisPrompt(\n projectBrief: string,\n actors: string,\n flows: string,\n stories: string,\n modules: string,\n database: string,\n apiDesign: string\n): string {\n return SYNTHESIS_USER_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{actors}', actors)\n .replace('{flows}', flows)\n .replace('{stories}', stories)\n .replace('{modules}', modules)\n .replace('{database}', database)\n .replace('{apiDesign}', apiDesign);\n}\n","/**\n * Context management for requirement chat\n */\n\nimport type { RequirementContext, StageResult, Stage, ChatEntry } from './types';\n\nexport function createInitialContext(): RequirementContext {\n return {\n stage: 'discovery',\n projectBrief: null,\n actors: [],\n flows: [],\n stories: [],\n modules: [],\n database: null,\n apiDesign: null,\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: RequirementContext,\n result: StageResult\n): RequirementContext {\n const data = result.data;\n return {\n ...context,\n ...(data.stage !== undefined && { stage: data.stage }),\n ...(data.projectBrief !== undefined && { projectBrief: data.projectBrief }),\n ...(data.actors !== undefined && { actors: data.actors }),\n ...(data.flows !== undefined && { flows: data.flows }),\n ...(data.stories !== undefined && { stories: data.stories }),\n ...(data.modules !== undefined && { modules: data.modules }),\n ...(data.database !== undefined && { database: data.database }),\n ...(data.apiDesign !== undefined && { apiDesign: data.apiDesign }),\n ...(data.pendingQuestions !== undefined && { pendingQuestions: data.pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: RequirementContext,\n role: 'user' | 'assistant',\n content: string\n): RequirementContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: RequirementContext): RequirementContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Stage processor interface and shared helpers\n */\n\nimport type { RequirementContext, Module, Story } from '../types';\n\nexport type { StageProcessor } from '../types';\n\n/** Summarize modules for token-efficient prompts (name, entity, API count) */\nexport function summarizeModules(modules: Module[]): string {\n return modules.map(m => `${m.name}: ${m.entity} (${m.apis.length} APIs)`).join('\\n');\n}\n\n/** Summarize stories for token-efficient prompts (actor + action) */\nexport function summarizeStories(stories: Story[]): string {\n return stories.map(s => `- ${s.actor}: ${s.action}`).join('\\n');\n}\n\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\nexport function safeParseJson(\n text: string\n): { success: true; data: unknown } | { success: false; error: string } {\n try {\n return { success: true, data: JSON.parse(text) };\n } catch (e) {\n return {\n success: false,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n\n/** Build a short text summary of context for inclusion in prompts */\nexport function buildContextSummary(ctx: RequirementContext): string {\n const parts: string[] = [];\n if (ctx.projectBrief) {\n parts.push(\n `Project: ${ctx.projectBrief.name}, Goal: ${ctx.projectBrief.goal}, API: ${ctx.projectBrief.apiStyle}`\n );\n }\n if (ctx.actors.length) parts.push(`Actors: ${ctx.actors.length}`);\n if (ctx.flows.length) parts.push(`Flows: ${ctx.flows.length}`);\n if (ctx.stories.length) parts.push(`Stories: ${ctx.stories.length}`);\n if (ctx.modules.length) parts.push(`Modules: ${ctx.modules.length}`);\n if (ctx.database) parts.push(`Database: ${ctx.database.type}`);\n if (ctx.apiDesign) parts.push(`API design: ${ctx.apiDesign.style}`);\n return parts.join('. ') || 'No context yet';\n}\n\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n","/**\n * Discovery stage - understand project, optional clarifying questions\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { projectBriefSchema, questionSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { DISCOVERY_SYSTEM_FRAGMENT, buildDiscoveryPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n const history = context.history\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Discovery response was not valid JSON', { error: parsed.error });\n return {\n message: \"I couldn't parse that. Could you describe your project in a few sentences?\",\n advance: false,\n data: {},\n };\n }\n const data = parsed.data as {\n needsClarification?: boolean;\n questions?: unknown[];\n conversationalMessage?: string;\n projectBrief?: unknown;\n };\n const message =\n data.conversationalMessage ?? response.text?.slice(0, 500) ?? 'Thanks for the details.';\n const needsClarification = data.needsClarification === true;\n const questions: RequirementContext['pendingQuestions'] = [];\n if (Array.isArray(data.questions)) {\n for (const q of data.questions) {\n const validated = questionSchema.safeParse(q);\n if (validated.success) questions.push(validated.data);\n }\n }\n let projectBrief: RequirementContext['projectBrief'] = null;\n if (data.projectBrief && !needsClarification) {\n const pb = projectBriefSchema.safeParse(data.projectBrief);\n if (pb.success) projectBrief = pb.data;\n }\n logger?.debug('Discovery stage complete', {\n advance: !needsClarification && projectBrief !== null,\n hasProjectBrief: !!projectBrief,\n questionsCount: questions.length,\n });\n return {\n message,\n questions: questions.length ? questions : undefined,\n advance: !needsClarification && projectBrief !== null,\n data: {\n ...(projectBrief && { projectBrief }),\n pendingQuestions: questions,\n },\n };\n}\n","/**\n * Requirements stage: structured output via invokeObject, or invoke + parse\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { ActorResult, FlowsResult, StoriesResult, ModulesResult } from '../schemas';\nimport {\n actorsResultSchema,\n flowsResultSchema,\n storiesResultSchema,\n modulesResultSchema,\n} from '../schemas';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function getActors(\n model: Model,\n messages: ModelMessage[],\n _logger?: Logger\n): Promise<ActorResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ActorResult>(messages, actorsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 4096,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Actors: ${parsed.error}`);\n const validated = actorsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Actors schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getFlows(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _logger?: Logger\n): Promise<FlowsResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<FlowsResult>(messages, flowsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 8192,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 8192 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Flows: ${parsed.error}`);\n const validated = flowsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Flows schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getStories(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _logger?: Logger\n): Promise<StoriesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<StoriesResult>(messages, storiesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Stories: ${parsed.error}`);\n const validated = storiesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Stories schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getModules(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _stories: StoriesResult['stories'],\n _logger?: Logger\n): Promise<ModulesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ModulesResult>(messages, modulesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Modules: ${parsed.error}`);\n const validated = modulesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Modules schema: ${validated.error.message}`);\n return validated.data;\n}\n","/**\n * Requirements stage - chain actors -> flows -> stories -> modules\n * Uses AI SDK structured output (invokeObject); no fallback data.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { RequirementContext, StageResult } from '../types';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport {\n buildExtractActorsPrompt,\n buildGenerateFlowsPrompt,\n buildGenerateStoriesPrompt,\n buildExtractModulesPrompt,\n} from '../prompts';\nimport { getActors, getFlows, getStories, getModules } from './requirements-invoke';\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Requirements stage started');\n\n const brief = context.projectBrief;\n if (!brief) {\n return {\n message: 'Project brief is missing. Complete discovery first.',\n advance: false,\n data: {},\n };\n }\n const projectName = brief.name;\n const projectGoal = brief.goal;\n const projectFeatures = brief.features.join('. ');\n\n const messages: ModelMessage[] = [\n { role: 'system', content: REQUIREMENT_GATHERER_SYSTEM_PROMPT },\n ];\n\n try {\n messages.push({\n role: 'user',\n content: buildExtractActorsPrompt(projectName, projectGoal, projectFeatures),\n });\n const actorsResult = await getActors(model, messages, logger);\n const actors = actorsResult.actors;\n logger?.debug('Requirements: actors', { count: actors.length });\n\n messages.push({\n role: 'assistant',\n content: `[Extracted ${actors.length} actors]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateFlowsPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors)\n ),\n });\n const flowsResult = await getFlows(model, messages, actors, logger);\n const flows = flowsResult.flows;\n logger?.debug('Requirements: flows', { count: flows.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${flows.length} flows]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateStoriesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows)\n ),\n });\n const storiesResult = await getStories(model, messages, actors, flows, logger);\n const stories = storiesResult.stories;\n logger?.debug('Requirements: stories', { count: stories.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${stories.length} stories]`,\n });\n messages.push({\n role: 'user',\n content: buildExtractModulesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows),\n JSON.stringify(stories)\n ),\n });\n const modulesResult = await getModules(model, messages, actors, flows, stories, logger);\n const modules = modulesResult.modules;\n logger?.debug('Requirements stage complete', {\n actors: actors.length,\n flows: flows.length,\n stories: stories.length,\n modules: modules.length,\n });\n\n return {\n message: `I've identified ${actors.length} actors, ${flows.length} flows, ${stories.length} stories, and ${modules.length} modules. Proceeding to technical design.`,\n advance: true,\n data: { actors, flows, stories, modules, pendingQuestions: [] },\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger?.warn('Requirements stage failed', { error: message });\n return {\n message: `Requirements step failed: ${message}. Please try again.`,\n advance: false,\n data: {},\n };\n }\n}\n","/**\n * Design stage - direct LLM calls for database and API design (prompt chaining)\n */\n\nimport { z } from 'zod';\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { databaseDesignSchema, apiDesignSchema } from '../schemas';\nimport { extractJson, safeParseJson, summarizeModules, summarizeStories } from './base';\nimport {\n DESIGN_DATABASE_SYSTEM_PROMPT,\n DESIGN_APIS_SYSTEM_PROMPT,\n buildDesignDatabasePrompt,\n buildDesignApisPrompt,\n} from '../prompts';\n\nexport async function runDesignStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n const brief = context.projectBrief;\n if (!brief) {\n return { message: 'Project brief is missing.', advance: false, data: {} };\n }\n if (!context.modules.length || !context.stories.length) {\n return {\n message: 'Requirements (modules and stories) are missing. Run requirements stage first.',\n advance: false,\n data: {},\n };\n }\n\n logger?.info('Design stage: database and API design', {\n modules: context.modules.length,\n stories: context.stories.length,\n });\n\n const projectBriefStr = JSON.stringify(brief);\n const modulesSummary = summarizeModules(context.modules);\n const storiesSummary = summarizeStories(context.stories);\n const actorsSummary = context.actors.map(a => `${a.name}: ${a.description}`).join('\\n');\n\n const dbPrompt = buildDesignDatabasePrompt(projectBriefStr, modulesSummary, storiesSummary);\n const dbMessages = [\n { role: 'system' as const, content: DESIGN_DATABASE_SYSTEM_PROMPT },\n { role: 'user' as const, content: dbPrompt },\n ];\n const dbResponse = await model.invoke(dbMessages, {\n temperature: 0.3,\n maxOutputTokens: 8192,\n });\n const dbJsonStr = extractJson(dbResponse.text);\n const dbParsed = safeParseJson(dbJsonStr);\n if (!dbParsed.success) {\n logger?.warn('Database design response was not valid JSON', { error: dbParsed.error });\n return {\n message: 'Failed to parse database design response. Please try again.',\n advance: false,\n data: {},\n };\n }\n const databaseResult = databaseDesignSchema.safeParse(dbParsed.data);\n if (!databaseResult.success) {\n const err = databaseResult.error;\n logger?.warn('Database design schema validation failed', { error: z.treeifyError(err) });\n return {\n message: 'Failed to produce database design. Please try again.',\n advance: false,\n data: {},\n };\n }\n const database = databaseResult.data;\n\n const apiPrompt = buildDesignApisPrompt(\n projectBriefStr,\n modulesSummary,\n actorsSummary,\n storiesSummary,\n JSON.stringify(database)\n );\n const apiMessages = [\n { role: 'system' as const, content: DESIGN_APIS_SYSTEM_PROMPT },\n { role: 'user' as const, content: apiPrompt },\n ];\n const apiResponse = await model.invoke(apiMessages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n const apiJsonStr = extractJson(apiResponse.text);\n const apiParsed = safeParseJson(apiJsonStr);\n if (!apiParsed.success) {\n logger?.warn('API design response was not valid JSON', { error: apiParsed.error });\n return {\n message: 'Failed to parse API design response. Please try again.',\n advance: false,\n data: { database },\n };\n }\n const apiDesignResult = apiDesignSchema.safeParse(apiParsed.data);\n if (!apiDesignResult.success) {\n const err = apiDesignResult.error;\n logger?.warn('API design schema validation failed', { error: z.treeifyError(err) });\n return {\n message: 'Failed to produce API design. Please try again.',\n advance: false,\n data: { database },\n };\n }\n const apiDesign = apiDesignResult.data;\n\n return {\n message: `Database: ${database.type}. API: ${apiDesign.style}.`,\n advance: true,\n data: { database, apiDesign, pendingQuestions: [] },\n };\n}\n","/**\n * Synthesis stage - compile FinalRequirement document\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport type { FinalRequirement } from '../types';\nimport { finalRequirementSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Synthesis stage started');\n\n const brief = context.projectBrief;\n if (!brief || !context.database || !context.apiDesign) {\n return {\n message:\n 'Missing project brief, database design, or API design. Complete earlier stages first.',\n advance: false,\n data: {},\n };\n }\n const prompt = buildSynthesisPrompt(\n JSON.stringify(brief),\n JSON.stringify(context.actors),\n JSON.stringify(context.flows),\n JSON.stringify(context.stories),\n JSON.stringify(context.modules),\n JSON.stringify(context.database),\n JSON.stringify(context.apiDesign)\n );\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Synthesis response was not valid JSON', { error: parsed.error });\n return {\n message: 'Failed to compile final requirement document. Please try again.',\n advance: false,\n data: {},\n };\n }\n const validated = finalRequirementSchema.safeParse(parsed.data);\n if (!validated.success) {\n logger?.warn('Synthesis: final requirement schema validation failed', {\n error: validated.error.message,\n });\n return {\n message: 'Final document did not match schema. ' + (response.text?.slice(0, 300) ?? ''),\n advance: false,\n data: {},\n };\n }\n const finalRequirement: FinalRequirement = validated.data;\n logger?.info('Synthesis stage complete', { overview: finalRequirement.summary?.overview });\n return {\n message: `Requirement document ready. ${finalRequirement.summary.overview}`,\n advance: true,\n data: { finalRequirement },\n };\n}\n","/**\n * Discovery stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements RequirementStageState {\n readonly stageName: Stage = 'discovery';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'requirements';\n }\n}\n","/**\n * Requirements stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements RequirementStageState {\n readonly stageName: Stage = 'requirements';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'design';\n }\n}\n","/**\n * Design stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements RequirementStageState {\n readonly stageName: Stage = 'design';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'complete';\n }\n}\n","/**\n * Synthesis (complete) stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements RequirementStageState {\n readonly stageName: Stage = 'complete';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return null;\n }\n}\n","/**\n * Registry: map Stage (string) to State instance for State pattern routing.\n */\n\nimport type { Stage } from '../types';\nimport type { RequirementStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, RequirementStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): RequirementStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { RequirementContext, Stage, FinalRequirement } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\n/**\n * Determine which stage to run for this turn.\n */\nexport function getStageForTurn(context: RequirementContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern: get state for context.stage, process, merge result.\n * If result.advance, context.stage is advanced to the next state's stage name.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n questions: RequirementContext['pendingQuestions'];\n advance: boolean;\n data: RequirementContext;\n finalRequirement?: FinalRequirement;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const finalReq = 'finalRequirement' in result.data ? result.data.finalRequirement : undefined;\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasFinalRequirement: !!finalReq,\n });\n const data: RequirementContext = {\n ...merged,\n pendingQuestions: result.questions ?? merged.pendingQuestions,\n };\n return {\n message: result.message,\n questions: result.questions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n finalRequirement: finalReq,\n };\n}\n\n/**\n * Whether the user message is a confirmation (continue / yes / looks good)\n */\nexport { isConfirmation };\n\n/**\n * Advance context to next stage\n */\nexport { advanceStage };\n\n/**\n * Add a chat entry to context history\n */\nexport { addChatEntry };\n","/**\n * processRequirementChat - main entry point for chat-based requirement gathering\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { RequirementContext, ChatTurnResult, RequirementChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processRequirementChat(\n userMessage: string,\n context: RequirementContext | null,\n config: RequirementChatConfig\n): Promise<ChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: RequirementContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let questions: RequirementContext['pendingQuestions'] = [];\n let finalRequirement: ChatTurnResult['finalRequirement'] = null;\n\n const runOne = async (\n stage: Stage\n ): Promise<{ advance: boolean; finalReq?: ChatTurnResult['finalRequirement'] }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n questions = result.questions;\n ctx = result.data;\n if (result.finalRequirement) finalRequirement = result.finalRequirement;\n return { advance: result.advance, finalReq: result.finalRequirement };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n\n while (runResult.advance && !finalRequirement) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Chat turn done', { stage, hasFinalRequirement: !!finalRequirement });\n return {\n message,\n context: ctx,\n questions,\n finalRequirement,\n };\n}\n","/**\n * runRequirementGathererAgent - one-shot wrapper around processRequirementChat\n * Runs the full chat flow non-interactively, auto-advancing with \"continue\" when questions are asked.\n */\n\nimport type { RequirementGathererAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processRequirementChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the requirement gatherer in one-shot mode: single input, auto-advance through stages,\n * return final requirement document or last message as AgentResult.\n */\nexport async function runRequirementGathererAgent(\n config: RequirementGathererAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting requirement gatherer agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processRequirementChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.finalRequirement && turns < MAX_TURNS) {\n logger?.debug('Requirement gatherer turn', { turn: turns });\n lastResult = await processRequirementChat('continue', context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.finalRequirement\n ? JSON.stringify(lastResult.finalRequirement, null, 2)\n : lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Requirement gatherer agent completed', {\n turns,\n hasFinalRequirement: !!lastResult.finalRequirement,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * Builder for RequirementContext - fluent API, max 150 lines.\n */\n\nimport type {\n RequirementContext,\n Stage,\n ProjectBrief,\n Actor,\n Flow,\n Story,\n Module,\n DatabaseDesign,\n ApiDesign,\n ChatEntry,\n Question,\n} from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nexport class RequirementContextBuilder {\n private data: Partial<RequirementContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectBrief(projectBrief: ProjectBrief | null): this {\n this.data.projectBrief = projectBrief;\n return this;\n }\n\n withActors(actors: Actor[]): this {\n this.data.actors = actors;\n return this;\n }\n\n withFlows(flows: Flow[]): this {\n this.data.flows = flows;\n return this;\n }\n\n withStories(stories: Story[]): this {\n this.data.stories = stories;\n return this;\n }\n\n withModules(modules: Module[]): this {\n this.data.modules = modules;\n return this;\n }\n\n withDatabase(database: DatabaseDesign | null): this {\n this.data.database = database;\n return this;\n }\n\n withApiDesign(apiDesign: ApiDesign | null): this {\n this.data.apiDesign = apiDesign;\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: Question[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): RequirementContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectBrief: this.data.projectBrief ?? null,\n actors: this.data.actors ?? [],\n flows: this.data.flows ?? [],\n stories: this.data.stories ?? [],\n modules: this.data.modules ?? [],\n database: this.data.database ?? null,\n apiDesign: this.data.apiDesign ?? null,\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createRequirementContextBuilder(): RequirementContextBuilder {\n return new RequirementContextBuilder();\n}\n","/**\n * Context management for planning chat\n */\n\nimport type { PlanningContext, PlanStageResult, PlanSections, Stage, ChatEntry } from './types';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport function createInitialContext(): PlanningContext {\n return {\n stage: 'discovery',\n projectDescription: null,\n sections: { ...EMPTY_SECTIONS },\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: PlanningContext,\n result: PlanStageResult\n): PlanningContext {\n const { sections: newSections, projectDescription, pendingQuestions } = result;\n const sections: PlanSections = { ...context.sections };\n if (newSections) {\n for (const key of Object.keys(newSections) as (keyof PlanSections)[]) {\n const v = newSections[key];\n if (v !== undefined && v !== null) sections[key] = v;\n }\n }\n return {\n ...context,\n ...(projectDescription !== undefined && { projectDescription }),\n sections,\n ...(pendingQuestions !== undefined && { pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: PlanningContext,\n role: 'user' | 'assistant',\n content: string\n): PlanningContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: PlanningContext): PlanningContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Shared utilities for planning stages - no JSON extraction or parsing\n */\n\nimport type { PlanningContext } from '../types';\n\n/** Whether the user message is a confirmation (continue / yes / looks good) */\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n\n/** Build a short text summary of context for logging */\nexport function buildContextSummary(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push('Project description set');\n const sections = Object.entries(ctx.sections).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].length > 0\n );\n if (sections.length) parts.push(`Sections: ${sections.map(([k]) => k).join(', ')}`);\n return parts.join('. ') || 'No context yet';\n}\n","/**\n * System prompt for planning module - markdown-only, pro-level output\n */\n\nexport const PLANNING_SYSTEM_PROMPT = `You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.\n\nCRITICAL RULES:\n- Output ONLY raw markdown text. Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets. No JSON or structured data outside those code blocks.\n- Use consistent structure: ## for main sections, ### for subsections, #### for per-item headings (e.g. per route, per endpoint). Use **bold** for labels (e.g. **Purpose**, **Request Body**, **Response on Success**).\n- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows. Every section should give enough detail to implement from the plan alone.`;\n","/**\n * Discovery stage prompt - understand project, ask questions; pro format when ready\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `You are in the discovery stage. Your goal is to understand what the user wants to build.\n\nRespond in natural language only. Do NOT output JSON.\n\n- If you need more information: ask 1-3 short, specific questions. Focus on tech choices (REST vs GraphQL, MongoDB vs PostgreSQL) and any gaps that block design.\n- When you have enough to proceed: output the project overview in this exact pro format so it matches the rest of the plan:\n - **## Overview** — One paragraph (2–4 sentences) summarizing the project and its purpose.\n - **## Core Features** — Numbered list: 1. **Feature Name** - Short description. (one line per feature)\n - **## Tech Stack** — Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.\n\nWhen the user says \"continue\", \"yes\", \"looks good\", or similar, treat it as confirmation to proceed. Do NOT keep asking questions. Make reasonable assumptions for any missing details (choose sensible defaults for tech stack, features, scope, etc.) and immediately output the project overview in the format above.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nRespond in plain markdown. Either ask clarifying questions, or if you have enough information, output the project overview in pro format: ## Overview (one paragraph), ## Core Features (numbered list with **Feature Name** - description), ## Tech Stack (bullets with **Category**: detail). Do NOT output JSON.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - pro-level markdown sections\n */\n\nconst CONTEXT_BLOCK = `## Project description / context:\n{context}`;\n\nexport const REQUIREMENTS_OVERVIEW_PROMPT = `${CONTEXT_BLOCK}\n\nUsing the project description above, write two markdown sections in this exact format:\n\n1. **## Overview** — One paragraph only (2–4 sentences) summarizing the project and its purpose.\n2. **## Tech Stack** — Bullet list with category labels: - **Frontend**: ... (include framework and versions if applicable, e.g. Next.js 16, React 19, TypeScript, Tailwind v4), - **Database**: ... (e.g. MongoDB with Mongoose), - **Authentication**: ... (e.g. JWT in HTTP-only cookies, bcrypt), - **API**: ... (REST or GraphQL), - **Backend**: ... Include versions and key libraries where applicable.\n\nOutput only these two sections in markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_FEATURE_DATA_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written (Overview + Tech Stack):\n{overviewAndTechStack}\n\nWrite the next two markdown sections in this exact format:\n\n1. **## Feature Decisions** — Use ### per feature/area (e.g. ### Workout Tracking, ### Nutrition Tracking). Under each, bullets for key product decisions; use sub-bullets for options where relevant (e.g. goal types: weight, strength, consistency, custom).\n2. **## Data Models** — For each entity use ### EntityName. For each field use exactly one line: \\`field_name\\`: description (type, required/optional, unique if applicable). For references write \"Reference to EntityName\". Include User, profile/settings, and all domain entities.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_PAGES_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Pages and Routes**\n- **### Public Pages (No Authentication Required)** and **### Protected Pages (Authentication Required)**.\n- For each page use: #### \\`/path\\` - Page Title\n- Under each page, include bullets for: purpose, form fields and validation (e.g. \"Form validation: Required fields, valid email format\"), buttons/actions, empty states, redirects on success/error (e.g. \"On success: Redirect to /dashboard\"), key UI (cards, sidebar, charts). Match the depth of a pro implementation spec so a developer can build the page from this alone.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_AUTH_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Authentication Flow** — Use these subsections: ### Sign Up Flow, ### Login Flow, ### Logout Flow, ### Protected Route Middleware, ### API Authentication Middleware.\n- Use **numbered steps** in each flow. Include both frontend and backend steps (e.g. \"4. Frontend sends POST to /api/auth/signup with { name, email, password }\", \"5. Backend validates input\", \"6. Backend hashes password with bcrypt (10 rounds)\", \"7. Backend sets JWT in HTTP-only cookie (name, maxAge, httpOnly, secure, sameSite)\").\n- For middleware: steps for cookie check, JWT verify, attach userId to request, return 401 when invalid.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildRequirementsOverviewPrompt(context: string): string {\n return REQUIREMENTS_OVERVIEW_PROMPT.replace('{context}', context);\n}\n\nexport function buildRequirementsFeatureDataPrompt(\n context: string,\n overviewAndTechStack: string\n): string {\n return REQUIREMENTS_FEATURE_DATA_PROMPT.replace('{context}', context).replace(\n '{overviewAndTechStack}',\n overviewAndTechStack\n );\n}\n\nexport function buildRequirementsPagesPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_PAGES_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n\nexport function buildRequirementsAuthPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_AUTH_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n","/**\n * Design stage prompts - pro-level API routes and implementation details\n */\n\nconst DESIGN_CONTEXT = `## Project context (all sections so far):\n{priorSections}`;\n\nexport const DESIGN_API_ROUTES_PROMPT = `${DESIGN_CONTEXT}\n\nWrite the next markdown section in this exact format:\n\n**## API Routes**\n- Group by domain: ### Authentication Endpoints, ### Exercise Endpoints, ### Workout Endpoints, etc.\n- For each endpoint use: #### METHOD \\`/path\\` (e.g. #### POST \\`/api/auth/signup\\`)\n- Under each endpoint include:\n - **Purpose**: one line\n - **Request Body** or **Query Parameters** (and **Validation** bullets: required, format, lengths)\n - **Response on Success (status)**: code block with example JSON (e.g. 200, 201)\n - **Response on Error**: bullets (e.g. 400 validation, 401, 403, 404, 500 with message)\n - **Side Effects** or **Implementation** where relevant (e.g. \"Creates User and UserProfile; sets auth cookie\")\n- Use code blocks ONLY for request/response JSON examples. No JSON elsewhere.\n\nOutput only markdown. Do NOT output JSON except inside code blocks.`;\n\nexport const DESIGN_IMPLEMENTATION_PROMPT = `${DESIGN_CONTEXT}\n\n## API Routes (already written):\n{apiRoutes}\n\nWrite the next markdown section in this exact format:\n\n**## Implementation Details**\n- **### File Structure** — Full directory tree in a **code block** (e.g. src/app/(auth)/login/page.tsx, src/app/api/auth/signup/route.ts, src/components/..., src/lib/, src/models/). Show the real layout a developer would create.\n- **### Environment Variables** — List with comments (e.g. MONGODB_URI=... # connection string, JWT_SECRET=... # change in production).\n- **### Dependencies to Install** — npm install line and short explanation per dependency (e.g. mongoose: MongoDB ODM; bcryptjs: password hashing; jsonwebtoken: JWT; cookie: cookie parsing).\n- **### Key Setup** — One subsection per concern: **MongoDB connection** (file path, purpose, 3–5 bullets), **JWT utilities** (file path, purpose; cookie name, maxAge, httpOnly, secure; generateToken/verifyToken/setAuthCookie/clearAuthCookie), **Auth middleware** (file path, authenticateRequest behavior), **External API client** if any (file path, purpose).\n- If the plan is UI-heavy, add **### UI Component Guidelines** (controlled inputs, validation, loading/error states) and **### Error Handling Standards** (API error JSON shape, HTTP status codes: 200, 201, 400, 401, 403, 404, 500).\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildDesignApiRoutesPrompt(priorSections: string): string {\n return DESIGN_API_ROUTES_PROMPT.replace('{priorSections}', priorSections);\n}\n\nexport function buildDesignImplementationPrompt(priorSections: string, apiRoutes: string): string {\n return DESIGN_IMPLEMENTATION_PROMPT.replace('{priorSections}', priorSections).replace(\n '{apiRoutes}',\n apiRoutes\n );\n}\n","/**\n * Synthesis stage prompt - pro-level final sections (order matters for splitting)\n */\n\nconst SYNTHESIS_CONTEXT = `## Full plan so far (all sections):\n{priorSections}`;\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `You are in the complete stage. You have the full implementation plan. Output the final sections in markdown, in the exact order specified below, so they can be assembled into the plan.`;\n\nexport const SYNTHESIS_USER_PROMPT = `${SYNTHESIS_CONTEXT}\n\nWrite the following sections in this exact order. Output only markdown. Do NOT output JSON.\n\n**Block 1 — Implementation Order, Current State, Desired End State**\n\n1. **## Implementation Order** — Phased: ### Phase 1: Foundation, ### Phase 2: Authentication, etc. Under each phase, numbered steps (e.g. \"1. Install dependencies\", \"2. Create User model\", \"3. Implement POST /api/auth/signup\", \"4. Create login page\"). Be concrete so a developer can follow step-by-step.\n\n2. **## Current State Analysis** — What the project starts with (e.g. vanilla Next.js, no DB, no auth). Then a short bullet list: \"What needs to be built from scratch\" (all auth, models, API routes, pages, etc.).\n\n3. **## Desired End State** — Short subsections or bullets: (1) For users: what they can do when the app is done; (2) Technical verification: what must work (DB connected, auth working, endpoints returning correct data, etc.); (3) Testing approach: manual flows, API checks, DB checks.\n\n**Block 2 — Edge Cases, Security, Performance, Future Enhancements**\n\n4. **## Edge Cases and Considerations** — ### per area (e.g. ### Authentication, ### Workouts, ### Nutrition, ### Goals, ### Profile, ### General). Under each, bullets for edge cases and how to handle them (e.g. \"Email already exists: return 400 with clear message\"; \"External API down: show error, allow manual entry\").\n\n5. **## Security Considerations** — Numbered list: passwords (bcrypt, min length); JWT (HTTP-only cookie, secure flag, strong secret, expiry); API (verify JWT on protected routes, check resource ownership); env (never commit secrets, different values in production).\n\n6. **## Performance Considerations** — Numbered list: DB (index user id and date fields, lean queries, avoid N+1); API (debounce search, cache external API if applicable); frontend (RSC where possible, lazy load heavy components); optional future caching.\n\n7. **## Future Enhancements (Not in Current Scope)** — Short grouped list (e.g. Social, Analytics, Integrations, Mobile, Premium) so scope is clear. One line per group is enough.\n\n**Block 3 — Manual Testing Checklist**\n\n8. **## Manual Testing Checklist** — ### per flow (e.g. ### Authentication Flow, ### Workout Flow, ### Nutrition Flow, ### Goals Flow, ### Profile Flow). Under each, checklist items: - [ ] Description of what to verify (e.g. \"- [ ] Sign up with valid credentials creates account\", \"- [ ] Login with invalid credentials shows error\").\n\nOutput all eight sections in the order above. Do NOT output JSON.`;\n\nexport function buildSynthesisPrompt(priorSections: string): string {\n return SYNTHESIS_USER_PROMPT.replace('{priorSections}', priorSections);\n}\n","/**\n * System prompt for the edit-plan pipeline.\n * Instructs the LLM to revise an existing plan based on feedback.\n */\n\nexport const EDIT_PLAN_SYSTEM_PROMPT = `You are a senior software architect revising an existing implementation plan.\n\nCRITICAL RULES:\n- You will receive the FULL existing plan and the user's feedback or edit instructions.\n- Output ONLY the complete revised plan in markdown. Do NOT output partial plans, explanations, or commentary.\n- Preserve the same section structure (## headings) as the original plan.\n- Only modify sections that are affected by the feedback. Leave unrelated sections intact.\n- Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets.\n- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows.\n- If the feedback adds new requirements, integrate them into the appropriate existing sections rather than appending a separate section (unless a new section is clearly needed).`;\n\nexport function buildEditPlanPrompt(existingPlan: string, feedback: string): string {\n return `## Existing Plan\\n\\n${existingPlan}\\n\\n---\\n\\n## Edit Instructions\\n\\n${feedback}`;\n}\n","/**\n * Discovery stage - understand project, optional questions; output is raw markdown\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport {\n PLANNING_SYSTEM_PROMPT,\n DISCOVERY_SYSTEM_FRAGMENT,\n buildDiscoveryPrompt,\n} from '../prompts';\nimport { isConfirmation } from './base';\n\n/** Heuristic: response contains project overview (markdown headers we expect when ready to advance) */\nfunction hasProjectOverview(text: string): boolean {\n const t = text.trim();\n if (t.length < 100) return false;\n // Primary: exact markdown headers\n if (t.includes('## Overview') || t.includes('## Core Features')) return true;\n // Secondary: bold-label or h1 variants the LLM might use\n const lower = t.toLowerCase();\n if (\n (lower.includes('overview') || lower.includes('core features')) &&\n (lower.includes('tech stack') || lower.includes('technology'))\n ) {\n return true;\n }\n return false;\n}\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n // Exclude the last entry from history if it duplicates the current userMessage\n // (processPlanningChat calls addChatEntry before runStage)\n const historyEntries = context.history.slice(0, -1);\n const history = historyEntries\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${PLANNING_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const message = response.text?.trim() ?? '';\n\n const hasOverview = hasProjectOverview(message);\n const userConfirmed = isConfirmation(userMessage);\n // Safety net: after enough discovery turns with confirmations, force advance\n const forceAdvance = userConfirmed && context.history.length >= 7 && message.length > 50;\n // Advance when: (1) we got overview, (2) user confirmed & description exists, or (3) safety net\n const advance =\n (hasOverview && (context.projectDescription == null || userConfirmed)) ||\n (userConfirmed && context.projectDescription != null) ||\n forceAdvance;\n const storeDescription = hasOverview || (forceAdvance && message.length > 50);\n\n logger?.debug('Discovery stage complete', {\n advance,\n hasOverview,\n userConfirmed,\n forceAdvance,\n });\n\n return {\n message,\n advance,\n sections: {},\n ...(storeDescription && { projectDescription: message }),\n };\n}\n","/**\n * Discovery state - placeholder until discovery.stage is implemented\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements PlanningStageState {\n readonly stageName = 'discovery' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'requirements' | null {\n return 'requirements';\n }\n}\n","/**\n * entity-analyzer subagent - extracts entities, fields, and relationships from requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENTITY_ANALYZER_SYSTEM_PROMPT = `You are an expert database entity analyst. Your job is to extract data model signals from requirements.\n\nPerform these analyses:\n\n## Entity Discovery\n- List every entity implied by the requirements (users, domain objects, settings, logs).\n- For each entity: name, purpose, key fields (with types), and which user type owns it.\n- Identify status enums from flow transitions (e.g. pending -> active -> completed).\n\n## Field Analysis\n- For each entity, list fields with: name, likely type, required/optional, unique constraints.\n- Identify computed vs stored fields.\n- Note fields that need indexing (lookups, sorting, filtering).\n\n## Relationship Signals\n- List entity pairs that reference each other.\n- Note ownership direction (which entity \"belongs to\" which).\n- Identify potential M:N relationships that may need join tables.\n\nRespond with a clear, structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const entityAnalyzerSubagent = defineSubagent({\n name: 'entity-analyzer',\n description:\n 'Analyzes requirements to extract entities, fields, relationships, and data model signals. Use when you need to understand the data before designing the schema.',\n systemPrompt: ENTITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * relationship-mapper subagent - maps cardinality, foreign keys, indexes\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RELATIONSHIP_MAPPER_SYSTEM_PROMPT = `You are a database relationship specialist. Given a list of entities and their fields, you determine:\n\n## Cardinality Analysis\n- For every entity pair that references each other, classify: 1:1, 1:N, or M:N.\n- Explain the reasoning (e.g. \"A User has many Orders, but an Order belongs to one User -> 1:N\").\n\n## Foreign Key / Reference Strategy\n- For MongoDB: recommend ObjectId references vs embedding. Embed when: data is small, always read together, rarely updated independently.\n- For PostgreSQL: define foreign key columns, ON DELETE behavior (CASCADE, SET NULL, RESTRICT).\n\n## Join Table Design (M:N)\n- When M:N is detected, design the join table with: both foreign keys, any extra fields (e.g. role in a membership), indexes.\n\n## Index Recommendations\n- Suggest compound indexes for common query patterns.\n- Suggest unique indexes for natural keys (email, slug, etc.).\n- Note partial indexes where applicable (e.g. only active records).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const relationshipMapperSubagent = defineSubagent({\n name: 'relationship-mapper',\n description:\n 'Maps cardinality (1:1, 1:N, M:N), foreign keys, join tables, and index recommendations for entity relationships. Use after entity analysis.',\n systemPrompt: RELATIONSHIP_MAPPER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * schema-refiner subagent - reviews schema for completeness and performance\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_REFINER_SYSTEM_PROMPT = `You are an expert database schema reviewer. Your job is to:\n\n1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.\n2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.\n3. Check normalization: no redundant data, proper use of references vs embedding.\n4. Check performance: indexes cover common query patterns, no missing indexes on foreign keys.\n5. Check security: passwords are marked as hashed, sensitive fields noted, no plaintext secrets.\n6. Check conventions: consistent naming (camelCase or snake_case), timestamps on all entities.\n\nIf you have access to the validate_schema tool, use it first. Then provide a detailed review with:\n- Issues found (with severity: critical, warning, suggestion)\n- Specific fixes for each issue\n- Overall assessment (ready / needs work)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport function createSchemaRefinerSubagent() {\n return defineSubagent({\n name: 'schema-refiner',\n description:\n 'Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.',\n systemPrompt: SCHEMA_REFINER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 3,\n });\n}\n","/**\n * page-planner subagent - designs page structure, routes, and layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst PAGE_PLANNER_SYSTEM_PROMPT = `You are a UX-focused frontend architect. You design detailed page specifications.\n\n## Page Planning\nFor each page in the application:\n\n### Route Definition\n- Path (e.g. /login, /dashboard, /workouts/:id)\n- Access level: public (no auth) or protected (requires auth)\n- Page name and purpose (one sentence)\n\n### Page Detail\n- **Form fields**: name, type (text, email, password, number, select, textarea, date, checkbox), required flag, validation rule.\n- **Actions**: buttons and what they do (e.g. \"Submit form\", \"Delete item\", \"Export CSV\").\n- **Empty state**: what to show when there's no data (e.g. \"No workouts yet. Click + to add one.\").\n- **Error state**: how to handle errors (e.g. \"Show inline validation errors\", \"Toast notification\").\n- **Redirect on success**: where to go after successful action (e.g. \"/dashboard\").\n- **Key UI elements**: cards, tables, charts, sidebar, modals, tabs.\n\n### Page Grouping\n- Group by access: public pages first, then protected.\n- Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.\n\nRespond with structured page specs. Do NOT return JSON.`;\n\nexport const pagePlannerSubagent = defineSubagent({\n name: 'page-planner',\n description:\n 'Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.',\n systemPrompt: PAGE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * component-analyzer subagent - identifies reusable components and shared layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst COMPONENT_ANALYZER_SYSTEM_PROMPT = `You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.\n\n## Component Identification\n- **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.\n- **Navigation components**: navbar, sidebar, breadcrumbs, mobile menu.\n- **Form components**: reusable form inputs, form wrappers, validation display.\n- **Display components**: cards, tables, lists, stat widgets, charts, badges.\n- **Shared components**: modals, toasts, loading spinners, empty state illustrations, error boundaries.\n\n## Component Analysis\nFor each component:\n- Name (PascalCase)\n- Type: layout, shared, form, display, navigation\n- Purpose (one sentence)\n- Props it accepts (e.g. \"user\", \"items\", \"onSubmit\", \"isLoading\")\n- Which pages use it\n\n## State Management\n- Identify which state is per-page (form state, UI state) vs global (auth state, user preferences).\n- Recommend server vs client state strategy.\n- Identify data fetching patterns (on mount, on action, real-time).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const componentAnalyzerSubagent = defineSubagent({\n name: 'component-analyzer',\n description:\n 'Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.',\n systemPrompt: COMPONENT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - recommends React/Vite or Next.js\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.\n\n## Decision Criteria\n\n### Choose \"react-vite\" (Vite + React SPA) when:\n- The app is a single-page application (SPA) behind authentication\n- No SEO requirements (admin dashboards, internal tools, B2B apps)\n- Backend is a separate API (GraphQL or REST) already built\n- Simple routing with client-side navigation\n- Team prefers traditional React patterns (hooks, context)\n\n### Choose \"nextjs\" (Next.js App Router) when:\n- SEO is important (marketing pages, blogs, e-commerce storefronts)\n- Need server-side rendering (SSR) or static site generation (SSG)\n- Want unified frontend + API in one project (server actions, API routes)\n- Need streaming and progressive rendering\n- Complex data fetching with caching requirements\n- Mix of public and authenticated pages\n\n## Output Format\nState your recommendation clearly:\n- Framework: react-vite | nextjs\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you would lose with the alternative\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends React/Vite SPA or Next.js. Use to determine the frontend framework before delegating to a builder.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * security-analyzer subagent - analyzes security requirements and threat vectors\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SECURITY_ANALYZER_SYSTEM_PROMPT = `You are a web security specialist. You analyze project requirements for security concerns and design security policies.\n\n## Authentication Analysis\n- Determine the best auth strategy (JWT, session, OAuth) based on requirements.\n- JWT: token expiry, refresh strategy, cookie vs header, httpOnly/secure/sameSite flags.\n- Session: session store (memory, Redis, DB), cookie config, session expiry.\n- OAuth: which providers, callback flow, token exchange, account linking.\n\n## Password Security\n- Hashing algorithm (bcrypt recommended), cost factor (10+ rounds).\n- Password requirements: minimum length, complexity rules.\n- Password reset flow: token generation, expiry, one-time use.\n\n## Authorization Analysis\n- Identify role hierarchy (e.g. admin > moderator > user).\n- Map roles to permissions per resource (CRUD matrix).\n- Resource ownership checks (users can only modify their own data).\n\n## Threat Analysis\n- Rate limiting: login attempts, API calls, password reset requests.\n- CORS: allowed origins, methods, headers.\n- Input sanitization: XSS prevention, SQL injection prevention.\n- Brute force protection: account lockout, exponential backoff.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const securityAnalyzerSubagent = defineSubagent({\n name: 'security-analyzer',\n description:\n 'Analyzes security requirements, threat vectors, and designs security policies. Use to understand auth needs before designing flows.',\n systemPrompt: SECURITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * flow-designer subagent - designs step-by-step auth flows\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FLOW_DESIGNER_SYSTEM_PROMPT = `You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.\n\nFor each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):\n\n## Flow Design Pattern\n1. Number each step sequentially.\n2. Mark each step as \"frontend\" or \"backend\".\n3. Describe the action clearly (e.g. \"Frontend sends POST to /api/auth/signup with { name, email, password }\").\n4. Include implementation details (e.g. \"Backend hashes password with bcrypt (10 rounds)\").\n\n## Signup Flow\n- Frontend: form validation, submit request.\n- Backend: validate input, check existing user, hash password, create user + profile, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Login Flow\n- Frontend: form validation, submit credentials.\n- Backend: find user, compare password hash, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Password Reset Flow\n- Frontend: request reset (email).\n- Backend: generate reset token, send email.\n- Frontend: enter new password with token.\n- Backend: validate token, hash new password, update user, invalidate token.\n\n## Middleware Flows\n- Protected route: check cookie/header, verify token, attach user to request, reject if invalid.\n- API auth: same as above but for API routes, return 401 JSON.\n\nRespond with structured numbered flows. Do NOT return JSON.`;\n\nexport const flowDesignerSubagent = defineSubagent({\n name: 'flow-designer',\n description:\n 'Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.',\n systemPrompt: FLOW_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Requirements stage - delegates to specialist agents:\n * data-modeler (data models), auth-designer (auth flow), frontend-architect (pages/routes)\n * Overview, tech stack, and feature decisions use direct LLM calls for markdown output.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildRequirementsOverviewPrompt, buildRequirementsFeatureDataPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { entityAnalyzerSubagent } from '../../data-modeler/subagents';\nimport { pagePlannerSubagent } from '../../frontend-architect/subagents';\nimport { flowDesignerSubagent } from '../../auth-designer/subagents';\n\nfunction invokeMarkdown(model: Model, systemPrompt: string, userPrompt: string): Promise<string> {\n const messages = [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: userPrompt },\n ];\n return model\n .invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 })\n .then(r => r.text?.trim() ?? '');\n}\n\nfunction splitOverviewAndTechStack(text: string): { overview: string; techStack: string } {\n const idx = text.indexOf('## Tech Stack');\n if (idx < 0) return { overview: text, techStack: '' };\n return { overview: text.slice(0, idx).trim(), techStack: text.slice(idx).trim() };\n}\n\nfunction splitFeatureDecisionsAndDataModels(text: string): {\n featureDecisions: string;\n dataModels: string;\n} {\n const idx = text.indexOf('## Data Models');\n if (idx < 0) return { featureDecisions: text, dataModels: '' };\n return { featureDecisions: text.slice(0, idx).trim(), dataModels: text.slice(idx).trim() };\n}\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Requirements stage started (specialist agents)');\n\n const ctx = context.projectDescription ?? '';\n if (!ctx) {\n return {\n message: 'No project description yet. Complete discovery first.',\n advance: false,\n sections: {},\n };\n }\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n\n // Part 1: Overview + Tech Stack (direct LLM call)\n const part1 = await invokeMarkdown(model, systemPrompt, buildRequirementsOverviewPrompt(ctx));\n const { overview, techStack } = splitOverviewAndTechStack(part1);\n\n // Part 2: Feature Decisions + Data Models via entity-analyzer specialist\n const part2 = await invokeMarkdown(\n model,\n systemPrompt,\n buildRequirementsFeatureDataPrompt(ctx, part1)\n );\n const { featureDecisions } = splitFeatureDecisionsAndDataModels(part2);\n\n logger?.info('Delegating to data-modeler specialist');\n const dataModelResult = await runSubagent(\n entityAnalyzerSubagent,\n `Analyze the data model for this project:\\n\\n${ctx}\\n\\nFeatures:\\n${featureDecisions}`,\n { parentModel: model }\n );\n const dataModels = dataModelResult.output;\n\n // Part 3: Pages and Routes via frontend-architect specialist\n logger?.info('Delegating to frontend-architect specialist');\n const priorContext = [part1, featureDecisions, dataModels].join('\\n\\n---\\n\\n');\n const pagesResult = await runSubagent(\n pagePlannerSubagent,\n `Design the pages and routes for this project:\\n\\n${ctx}\\n\\nContext:\\n${priorContext}`,\n { parentModel: model }\n );\n const pagesAndRoutes = pagesResult.output;\n\n // Part 4: Auth Flow via auth-designer specialist\n logger?.info('Delegating to auth-designer specialist');\n const fullContext = [priorContext, pagesAndRoutes].join('\\n\\n---\\n\\n');\n const authResult = await runSubagent(\n flowDesignerSubagent,\n `Design the authentication flows for this project:\\n\\n${ctx}\\n\\nContext:\\n${fullContext}`,\n { parentModel: model }\n );\n const authFlow = authResult.output;\n\n logger?.info('Requirements stage complete (specialist agents)');\n return {\n message:\n 'Requirements generated via specialist agents (Data Modeler, Frontend Architect, Auth Designer).',\n advance: true,\n sections: { overview, techStack, featureDecisions, dataModels, pagesAndRoutes, authFlow },\n };\n}\n","/**\n * Requirements state - delegates to requirements stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements PlanningStageState {\n readonly stageName = 'requirements' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'design' | null {\n return 'design';\n }\n}\n","/**\n * endpoint-analyzer subagent - derives API endpoints from data model and requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENDPOINT_ANALYZER_SYSTEM_PROMPT = `You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.\n\n## Endpoint Discovery\n- For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.\n- From user stories/flows, identify custom operations beyond CRUD (e.g. searchUsers, bulkImport, exportCsv, toggleStatus).\n- Group endpoints by resource name (pluralized entity name).\n\n## Route Design\n- Design RESTful routes: POST /resource, GET /resource/:id, GET /resource, PUT /resource/:id, DELETE /resource/:id.\n- For nested resources: GET /users/:userId/orders, POST /users/:userId/orders.\n- For custom operations: POST /resource/:id/actions/activate, GET /resource/search.\n\n## Auth Annotations\n- Mark which endpoints require authentication.\n- Mark which endpoints require specific roles (admin, owner).\n- Identify resource-ownership checks (user can only access their own data).\n\nRespond with structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const endpointAnalyzerSubagent = defineSubagent({\n name: 'endpoint-analyzer',\n description:\n 'Analyzes data model and requirements to derive API endpoints, routes, and auth annotations. Use before generating the API design.',\n systemPrompt: ENDPOINT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * contract-designer subagent - designs request/response contracts per endpoint\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst CONTRACT_DESIGNER_SYSTEM_PROMPT = `You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.\n\n## Request Design\n- For each endpoint, define: required fields, optional fields, field types, validation rules.\n- Validation rules: required, min/max length, email format, enum values, numeric ranges.\n- For list endpoints: pagination (page, limit, offset), sorting (sortBy, order), filtering (query params).\n\n## Response Design\n- Success responses: HTTP status (200, 201, 204), response body shape.\n- For list endpoints: { items: T[], total: number, page: number, limit: number }.\n- For single item: the entity shape with all fields.\n\n## Error Responses\n- 400: validation errors with field-level messages.\n- 401: unauthenticated (missing or invalid token).\n- 403: forbidden (insufficient role or not resource owner).\n- 404: resource not found.\n- 409: conflict (duplicate unique field).\n- 500: internal server error.\n\n## Naming Conventions\n- Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).\n- Use ISO 8601 for dates in responses.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const contractDesignerSubagent = defineSubagent({\n name: 'contract-designer',\n description:\n 'Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.',\n systemPrompt: CONTRACT_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Design stage - delegates to api-designer specialists:\n * endpoint-analyzer (API routes), contract-designer (implementation details)\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildDesignImplementationPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from '../../api-designer/subagents';\n\nfunction gatherPriorSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n if (s.overview) parts.push(s.overview);\n if (s.techStack) parts.push(s.techStack);\n if (s.featureDecisions) parts.push(s.featureDecisions);\n if (s.dataModels) parts.push(s.dataModels);\n if (s.pagesAndRoutes) parts.push(s.pagesAndRoutes);\n if (s.authFlow) parts.push(s.authFlow);\n return parts.join('\\n\\n---\\n\\n');\n}\n\nexport async function runDesignStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Design stage started (specialist agents)');\n\n const priorSections = gatherPriorSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete discovery and requirements first.',\n advance: false,\n sections: {},\n };\n }\n\n // API Routes via endpoint-analyzer specialist\n logger?.info('Delegating to api-designer endpoint-analyzer specialist');\n const apiResult = await runSubagent(\n endpointAnalyzerSubagent,\n `Design the API routes for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const apiRoutes = apiResult.output;\n\n // Implementation Details via contract-designer specialist + direct LLM call\n logger?.info('Delegating to api-designer contract-designer specialist');\n const contractResult = await runSubagent(\n contractDesignerSubagent,\n `Design detailed request/response contracts for these API endpoints:\\n\\n${apiRoutes}\\n\\nProject context:\\n${priorSections}`,\n { parentModel: model }\n );\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const implementation = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n {\n role: 'user' as const,\n content: buildDesignImplementationPrompt(\n priorSections,\n apiRoutes + '\\n\\n' + contractResult.output\n ),\n },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n logger?.info('Design stage complete (specialist agents)');\n return {\n message: 'Design generated via specialist agents (Endpoint Analyzer, Contract Designer).',\n advance: true,\n sections: { apiRoutes, implementation },\n };\n}\n","/**\n * Design state - delegates to design stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements PlanningStageState {\n readonly stageName = 'design' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'complete' | null {\n return 'complete';\n }\n}\n","/**\n * Assemble plan sections into markdown and write to file\n */\n\nimport { writeFile } from 'fs/promises';\nimport type { PlanSections } from './types';\n\nexport function assemblePlan(projectName: string, sections: PlanSections): string {\n const parts: (string | null)[] = [\n `# ${projectName} Implementation Plan\\n`,\n sections.overview,\n sections.techStack,\n sections.featureDecisions,\n '---',\n sections.dataModels,\n '---',\n sections.pagesAndRoutes,\n '---',\n sections.authFlow,\n '---',\n sections.apiRoutes,\n '---',\n sections.implementation,\n '---',\n sections.executionPlan,\n '---',\n sections.edgeCases,\n '---',\n sections.testingChecklist,\n ];\n return parts.filter(Boolean).join('\\n\\n');\n}\n\nexport async function writePlanToFile(markdown: string, outputPath: string): Promise<void> {\n await writeFile(outputPath, markdown, 'utf-8');\n}\n","/**\n * edge-case-analyzer subagent - identifies edge cases per domain area\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst EDGE_CASE_ANALYZER_SYSTEM_PROMPT = `You are a QA-minded tech lead. You identify edge cases that developers often miss.\n\nFor each domain area (Authentication, Data, API, Frontend, Integrations):\n\n## Edge Case Analysis\n- **Scenario**: Describe the edge case concretely (e.g. \"User submits signup form with email that already exists\").\n- **Handling**: How to handle it (e.g. \"Return 400 with message 'Email already in use'\").\n- **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).\n\n## Common Areas to Check\n- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.\n- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.\n- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).\n- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.\n- **Integrations**: external API down, timeout, rate limited, invalid response format.\n\nRespond with structured edge cases grouped by area. Do NOT return JSON.`;\n\nexport const edgeCaseAnalyzerSubagent = defineSubagent({\n name: 'edge-case-analyzer',\n description:\n 'Identifies edge cases per domain area with scenarios, handling strategies, and severity levels. Use for comprehensive edge case analysis.',\n systemPrompt: EDGE_CASE_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * testing-strategist subagent - designs manual testing checklists\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst TESTING_STRATEGIST_SYSTEM_PROMPT = `You are a testing strategy specialist. You design comprehensive manual testing checklists.\n\n## Testing Checklist Design\nGroup test items by flow (Authentication, CRUD operations, Edge cases, etc.).\n\nFor each test item:\n- **Flow name**: which feature flow this tests (e.g. \"Authentication Flow\", \"Workout CRUD Flow\").\n- **Test item**: what to verify (e.g. \"Sign up with valid credentials creates account\").\n- **Expected result**: what should happen (e.g. \"User created in DB, JWT cookie set, redirected to /dashboard\").\n\n## Coverage Areas\n- **Happy paths**: normal user flows work end-to-end.\n- **Validation**: invalid inputs are rejected with clear messages.\n- **Authorization**: users can only access what they should.\n- **Error handling**: errors are caught and displayed properly.\n- **Data integrity**: data is saved correctly, relationships maintained.\n- **UI states**: loading, empty, error, success states display correctly.\n\n## Checklist Format\nPresent as grouped checklist items using markdown checkboxes:\n### Flow Name\n- [ ] Test item description -> Expected result\n\nRespond with structured checklist. Do NOT return JSON.`;\n\nexport const testingStrategistSubagent = defineSubagent({\n name: 'testing-strategist',\n description:\n 'Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.',\n systemPrompt: TESTING_STRATEGIST_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Synthesis stage - delegates to execution-planner specialists:\n * edge-case-analyzer (edge cases), testing-strategist (testing checklist)\n * Then assembles plan.md from all sections.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { assemblePlan } from '../writer';\nimport { runSubagent } from '../../../lib/subagents';\nimport {\n edgeCaseAnalyzerSubagent,\n testingStrategistSubagent,\n} from '../../execution-planner/subagents';\n\nfunction gatherAllSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n [\n s.overview,\n s.techStack,\n s.featureDecisions,\n s.dataModels,\n s.pagesAndRoutes,\n s.authFlow,\n s.apiRoutes,\n s.implementation,\n ].forEach(p => {\n if (p) parts.push(p);\n });\n return parts.join('\\n\\n---\\n\\n');\n}\n\nfunction extractProjectName(ctx: PlanningContext): string {\n const raw = ctx.sections.overview ?? ctx.projectDescription ?? '';\n const firstLine = raw.split('\\n')[0]?.trim() ?? '';\n const regex = /^#+\\s*(.+?)(?:\\s+Implementation Plan)?$/i;\n const match = regex.exec(firstLine);\n if (match?.[1]) return match[1].trim();\n if (firstLine.length > 0 && firstLine.length < 80) return firstLine.replace(/^#+\\s*/, '').trim();\n return 'Project Implementation Plan';\n}\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Synthesis stage started (specialist agents)');\n\n const priorSections = gatherAllSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete earlier stages first.',\n advance: false,\n sections: {},\n };\n }\n\n // Execution plan via direct LLM call (phased implementation order)\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const executionPlan = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: buildSynthesisPrompt(priorSections) },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n // Edge cases via edge-case-analyzer specialist\n logger?.info('Delegating to execution-planner edge-case-analyzer specialist');\n const edgeCaseResult = await runSubagent(\n edgeCaseAnalyzerSubagent,\n `Identify edge cases for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const edgeCases = edgeCaseResult.output;\n\n // Testing checklist via testing-strategist specialist\n logger?.info('Delegating to execution-planner testing-strategist specialist');\n const testingResult = await runSubagent(\n testingStrategistSubagent,\n `Design the manual testing checklist for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const testingChecklist = testingResult.output;\n\n const projectName = extractProjectName(context);\n const fullSections = {\n ...context.sections,\n executionPlan: executionPlan || null,\n edgeCases: edgeCases || null,\n testingChecklist: testingChecklist || null,\n };\n const fullMarkdown = assemblePlan(projectName, fullSections);\n\n logger?.info('Synthesis stage complete (specialist agents)', { projectName });\n return {\n message: `Plan complete: ${projectName}. Generated via specialist agents.`,\n advance: true,\n sections: { executionPlan, edgeCases, testingChecklist },\n planMarkdown: fullMarkdown,\n };\n}\n","/**\n * Synthesis state - delegates to synthesis stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements PlanningStageState {\n readonly stageName = 'complete' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): null {\n return null;\n }\n}\n","/**\n * Registry: map Stage to State instance for State pattern routing\n */\n\nimport type { Stage } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, PlanningStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): PlanningStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { PlanningContext, Stage } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\nexport function getStageForTurn(context: PlanningContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern; merge result into context.\n * Returns planMarkdown when synthesis stage completes.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n pendingQuestions: string[];\n advance: boolean;\n data: PlanningContext;\n planMarkdown?: string;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const data: PlanningContext = {\n ...merged,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n };\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasPlanMarkdown: !!result.planMarkdown,\n });\n return {\n message: result.message,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n planMarkdown: result.planMarkdown,\n };\n}\n\nexport { isConfirmation, advanceStage, addChatEntry };\n","/**\n * processPlanningChat - main entry point for chat-based planning\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { PlanningContext, PlanChatTurnResult, PlanningChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processPlanningChat(\n userMessage: string,\n context: PlanningContext | null,\n config: PlanningChatConfig\n): Promise<PlanChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: PlanningContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Planning chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let pendingQuestions: string[] = [];\n let planMarkdown: string | null = null;\n\n const runOne = async (stage: Stage): Promise<{ advance: boolean; planMarkdown?: string }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n pendingQuestions = result.pendingQuestions;\n ctx = result.data;\n if (result.planMarkdown) planMarkdown = result.planMarkdown;\n return { advance: result.advance, planMarkdown: result.planMarkdown };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n\n while (runResult.advance && !planMarkdown) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Planning chat turn done', { stage, hasPlanMarkdown: !!planMarkdown });\n return {\n message,\n context: ctx,\n pendingQuestions,\n planMarkdown,\n };\n}\n","/**\n * runPlanningAgent - one-shot wrapper around processPlanningChat\n * Auto-advances with \"continue\"; returns plan markdown. Does not write to file.\n */\n\nimport type { PlanningAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processPlanningChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the planning agent in one-shot mode: single input, auto-advance through stages,\n * return plan markdown as AgentResult. Does not write to file.\n */\nexport async function runPlanningAgent(config: PlanningAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting planning agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processPlanningChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning agent turn', { turn: turns });\n const continueMsg =\n `continue - proceed with the project: \"${input}\". ` +\n 'Make reasonable assumptions for any unresolved details and produce the required output format.';\n lastResult = await processPlanningChat(continueMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning agent completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * editPlan - single LLM call to revise an existing plan based on feedback.\n * Takes existing plan markdown + edit instructions, returns updated markdown.\n */\n\nimport type { EditPlanConfig } from './types';\nimport { createModel } from '../../lib/models/create-model';\nimport { EDIT_PLAN_SYSTEM_PROMPT, buildEditPlanPrompt } from './prompts';\n\n/**\n * Edit an existing plan based on feedback or additional context.\n * Single focused LLM call -- no multi-stage pipeline needed.\n * Returns the full revised plan as a markdown string.\n */\nexport async function editPlan(config: EditPlanConfig): Promise<string> {\n const { existingPlan, feedback, logger } = config;\n logger?.info('Editing plan', { feedbackLength: feedback.length });\n\n if (!existingPlan || existingPlan.trim().length < 50) {\n throw new Error('existingPlan is too short or empty. Provide a valid plan to edit.');\n }\n if (!feedback || feedback.trim().length === 0) {\n throw new Error('feedback is empty. Provide edit instructions.');\n }\n\n const modelConfig = config.model ?? { provider: 'openai' as const, model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n const response = await model.invoke(\n [\n { role: 'system' as const, content: EDIT_PLAN_SYSTEM_PROMPT },\n { role: 'user' as const, content: buildEditPlanPrompt(existingPlan, feedback) },\n ],\n { temperature: 0.3, maxOutputTokens: 16384 }\n );\n\n const revised = response.text?.trim() ?? '';\n if (!revised) {\n throw new Error('Model returned empty response when editing plan.');\n }\n\n logger?.info('Plan edited successfully', { outputLength: revised.length });\n return revised;\n}\n","/**\n * Builder for PlanningContext - fluent API\n */\n\nimport type { PlanningContext, Stage, PlanSections, ChatEntry } from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport class PlanningContextBuilder {\n private data: Partial<PlanningContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectDescription(projectDescription: string | null): this {\n this.data.projectDescription = projectDescription;\n return this;\n }\n\n withSections(sections: Partial<PlanSections>): this {\n this.data.sections = { ...(this.data.sections ?? EMPTY_SECTIONS), ...sections };\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: string[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): PlanningContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectDescription: this.data.projectDescription ?? null,\n sections: this.data.sections ?? { ...EMPTY_SECTIONS },\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createPlanningContextBuilder(): PlanningContextBuilder {\n return new PlanningContextBuilder();\n}\n","/**\n * Zod schemas for DataModelDesign\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n description: z.string().default(''),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string().default(''),\n fields: z.array(z.string()).default([]),\n unique: z.coerce.boolean().default(false),\n});\n\n/** Normalize common relation type variants to canonical form. */\nconst relationTypeSchema = z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['1:1', 'onetoone'].includes(n)) return '1:1' as const;\n if (['1:n', '1:m', 'n:1', 'onetomany', 'manytoone'].includes(n)) return '1:N' as const;\n if (['m:n', 'n:m', 'manytomany'].includes(n)) return 'M:N' as const;\n return s;\n })\n .pipe(z.enum(['1:1', '1:N', 'M:N']));\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n type: relationTypeSchema,\n description: z.string().default(''),\n});\n\nexport const dataEntitySchema = z.object({\n name: z.string(),\n description: z.string().default(''),\n fields: z\n .union([z.array(entityFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof entityFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.name) obj.name = key;\n const result = entityFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n indexes: z.array(entityIndexSchema).default([]),\n relations: z.array(entityRelationSchema).default([]),\n});\n\n/** Case-insensitive database type */\nconst dbTypeSchema = z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['mongodb', 'postgresql']));\n\nexport const dataModelDesignSchema = z.object({\n type: dbTypeSchema,\n reasoning: z.string().default(''),\n entities: z.array(dataEntitySchema).default([]),\n});\n\nexport type TDataModelDesign = z.infer<typeof dataModelDesignSchema>;\n","/**\n * System prompt for data-modeler orchestrator\n */\n\nexport const DATA_MODELER_SYSTEM_PROMPT = `You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.\n\nYou analyze requirements and produce enterprise-quality data models with:\n- Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)\n- Indexes optimized for query patterns\n- Relationships with correct cardinality (1:1, 1:N, M:N)\n- Validation constraints and default values\n- Security considerations (hashed passwords, encrypted fields)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for data-modeler\n */\n\nexport const DESIGN_SCHEMA_PROMPT = `## Requirements:\n{requirement}\n\nDesign the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.\n\nFor MongoDB use types: ObjectId, string, number, boolean, date, array, mixed.\nFor PostgreSQL use types: uuid, varchar(n), text, integer, bigint, boolean, timestamp, jsonb, and proper foreign key relations.\n\nReturn ONLY valid JSON:\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences explaining the choice and design approach\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"idx_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"type\": \"1:N\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nexport const REFINE_SCHEMA_PROMPT = `## Current Schema (JSON):\n{existingSchema}\n\n## Feedback:\n{feedback}\n\nUpdate the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;\n\nexport function buildDesignSchemaPrompt(requirement: string): string {\n return DESIGN_SCHEMA_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildRefineSchemaPrompt(existingSchema: string, feedback: string): string {\n return REFINE_SCHEMA_PROMPT.replace('{existingSchema}', existingSchema).replace(\n '{feedback}',\n feedback\n );\n}\n","/**\n * Pro-level 5-phase data modeling prompt\n */\n\nexport const PRO_DESIGN_PROMPT = `## Project: {projectName}\n## Goal: {projectGoal}\n## Database: {databaseType}\n\n## Context:\n{context}\n\nApply the 5-phase enterprise data modeling process:\n\n### Phase 1: Entity Discovery\n- Extract every entity from the context (user types, domain objects, settings, logs).\n- Identify status enums from flow transitions.\n\n### Phase 2: Relationship Mapping\n- For each entity pair, determine ownership and cardinality (1:1, 1:N, M:N).\n- Note bidirectional references and join tables (PostgreSQL) or embedded arrays (MongoDB).\n\n### Phase 3: Permission Derivation\n- Map actor types to role names.\n- From actions, derive which role can CRUD which entity.\n\n### Phase 4: Schema Generation\n- Generate fields with DB-native types, required/unique flags, defaults.\n- Add indexes for common queries (user lookups, date ranges, foreign keys).\n- Include timestamps (createdAt, updatedAt) on all entities.\n\n### Phase 5: Validation\n- Verify every entity referenced in relations exists.\n- Verify no orphan fields or missing indexes.\n\nReturn ONLY valid JSON in the DataModelDesign format.`;\n\nexport function buildProDesignPrompt(\n projectName: string,\n projectGoal: string,\n databaseType: string,\n context: string\n): string {\n return PRO_DESIGN_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{databaseType}', databaseType)\n .replace('{context}', context);\n}\n","/**\n * validate_schema tool - validates JSON against dataModelDesignSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema } from '../schemas';\n\nexport const validateSchemaTool = defineTool({\n name: 'validate_data_model',\n description:\n 'Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n schema: z.string().describe('JSON string of the data model to validate'),\n }),\n handler: async ({ schema }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(schema) as unknown;\n dataModelDesignSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * design_schema tool - generates data model from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildDesignSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema tool. Requires a model for generation.\n */\nexport function createDesignSchemaTool(model: Model) {\n return defineTool({\n name: 'design_schema',\n description:\n 'Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the data modeling requirements'),\n }),\n handler: async ({ requirement }): Promise<TDataModelDesign> => {\n const userPrompt = buildDesignSchemaPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * design_schema_pro tool - 5-phase structured data modeling (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildProDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema_pro tool for structured 5-phase data modeling.\n */\nexport function createDesignSchemaProTool(model: Model) {\n return defineTool({\n name: 'design_schema_pro',\n description:\n 'Generate an enterprise-quality database schema using 5-phase analysis (Entity Discovery, Relationship Mapping, Permission Derivation, Schema Generation, Validation). Use when structured context is available.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n projectGoal: z.string().describe('Project goal / purpose'),\n databaseType: z.enum(['mongodb', 'postgresql']).describe('Target database type'),\n context: z.string().describe('Full project context: features, actors, flows, stories'),\n }),\n handler: async ({\n projectName,\n projectGoal,\n databaseType,\n context,\n }): Promise<TDataModelDesign> => {\n const userPrompt = buildProDesignPrompt(projectName, projectGoal, databaseType, context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * refine_schema tool - updates existing schema based on feedback (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildRefineSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the refine_schema tool for iterating on an existing data model.\n */\nexport function createRefineSchemaTools(model: Model) {\n return defineTool({\n name: 'refine_schema',\n description:\n 'Update an existing data model schema based on user feedback. Provide the current schema JSON and feedback describing desired changes.',\n input: z.object({\n existingSchema: z.string().describe('Current data model schema as JSON string'),\n feedback: z.string().describe('Feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TDataModelDesign> => {\n const userPrompt = buildRefineSchemaPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * data-modeler tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSchemaTool } from './validate-schema';\nimport { createDesignSchemaTool } from './design-schema';\nimport { createDesignSchemaProTool } from './design-schema-pro';\nimport { createRefineSchemaTools } from './refine-schema';\n\nexport { validateSchemaTool } from './validate-schema';\nexport { createDesignSchemaTool } from './design-schema';\nexport { createDesignSchemaProTool } from './design-schema-pro';\nexport { createRefineSchemaTools } from './refine-schema';\n\n/**\n * Create all data-modeler tools. Pass the model for AI-backed tools.\n */\nexport function createDataModelerTools(model: Model) {\n return createToolSet({\n validate_data_model: validateSchemaTool,\n design_schema: createDesignSchemaTool(model),\n design_schema_pro: createDesignSchemaProTool(model),\n refine_schema: createRefineSchemaTools(model),\n });\n}\n","/**\n * runDataModelerAgent - orchestrator for data model design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { DATA_MODELER_SYSTEM_PROMPT } from './prompts';\nimport { createDataModelerTools } from './tools';\nimport {\n entityAnalyzerSubagent,\n relationshipMapperSubagent,\n createSchemaRefinerSubagent,\n} from './subagents';\nimport type { DataModelerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${DATA_MODELER_SYSTEM_PROMPT}\n\nYou are the data modeling orchestrator. When the user asks for a data model:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, fields, and relationships from the requirements.\n2. **Map relationships**: Use subagent_relationship-mapper with the entity analysis to determine cardinality, foreign keys, and indexes.\n3. **Generate schema**: Use design_schema (plain text) or design_schema_pro (when structured context is available) to produce the data model.\n4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.\n5. **Validate**: Use validate_data_model to check the final schema JSON before returning.\n\nRespond with the final data model schema as JSON.`;\n\n/**\n * Run the data-modeler orchestrator agent with all tools and subagents.\n */\nexport async function runDataModelerAgent(config: DataModelerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createDataModelerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet(\n [entityAnalyzerSubagent, relationshipMapperSubagent, schemaRefiner],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ApiDesign\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .union([z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toUpperCase() : s))\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nconst stringRecordSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .transform(m =>\n Object.fromEntries(\n Object.entries(m ?? {}).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)])\n )\n );\n\n/** Coerce arrays of mixed strings/objects to string arrays (models often return objects). */\nconst stringOrObjectArraySchema = z\n .array(z.unknown())\n .default([])\n .transform(arr => arr.map(v => (typeof v === 'string' ? v : JSON.stringify(v))));\n\nexport const restEndpointSchema = z.object({\n id: z.string(),\n resource: z.string(),\n method: httpMethodSchema,\n path: z.string(),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n requestBody: stringRecordSchema,\n responseBody: stringRecordSchema,\n queryParams: stringRecordSchema,\n validation: stringOrObjectArraySchema,\n errorResponses: stringOrObjectArraySchema,\n});\n\nexport const graphqlOperationSchema = z.object({\n name: z.string(),\n type: z.enum(['query', 'mutation', 'subscription']),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n args: z.array(\n z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n })\n ),\n returnType: z.string(),\n});\n\nconst apiStyleSchema = z.unknown().transform(v => {\n const s = typeof v === 'string' ? v.toLowerCase().trim() : 'rest';\n if (s.includes('graphql')) return 'graphql' as const;\n return 'rest' as const;\n});\n\nexport const apiDesignSchema = z.object({\n style: apiStyleSchema,\n baseUrl: z.string().default('/api/v1'),\n endpoints: z.array(restEndpointSchema).default([]),\n graphqlOperations: z.array(graphqlOperationSchema).default([]),\n});\n\nexport type TApiDesign = z.infer<typeof apiDesignSchema>;\n","/**\n * System prompt for api-designer orchestrator\n */\n\nexport const API_DESIGNER_SYSTEM_PROMPT = `You are a senior API architect specializing in REST and GraphQL API design.\n\nYou analyze data models and requirements to produce enterprise-quality API designs with:\n- RESTful endpoints grouped by resource with proper HTTP methods\n- Request/response contracts with field types and validation rules\n- Error responses with appropriate HTTP status codes (400, 401, 403, 404, 500)\n- Pagination, filtering, and sorting patterns\n- Authentication and authorization annotations per endpoint\n- GraphQL types, queries, mutations, and subscriptions when applicable\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for api-designer\n */\n\nexport const DESIGN_API_PROMPT = `## Requirements:\n{requirement}\n\nDesign the API. Determine the best API style (rest or graphql) based on the requirements, or use the one specified.\n\nFor REST: group endpoints by resource. Each endpoint needs method, path, description, auth flag, roles, requestBody, responseBody, queryParams, validation rules, and error responses.\nFor GraphQL: define operations (queries, mutations, subscriptions) with args and return types.\n\nReturn ONLY valid JSON:\n{\n \"style\": \"rest\" | \"graphql\",\n \"baseUrl\": \"/api/v1\",\n \"endpoints\": [\n { \"id\": \"ep-1\", \"resource\": \"users\", \"method\": \"POST\", \"path\": \"/api/v1/users\", \"description\": \"Create user\", \"auth\": false, \"roles\": [], \"requestBody\": {}, \"responseBody\": {}, \"queryParams\": {}, \"validation\": [], \"errorResponses\": [] }\n ],\n \"graphqlOperations\": []\n}`;\n\nexport const PRO_DESIGN_API_PROMPT = `## Project: {projectName}\n## API Style: {apiStyle}\n## Data Model:\n{dataModel}\n## Requirements:\n{context}\n\nDesign a comprehensive API surface from the data model and requirements. For each entity in the data model, generate CRUD endpoints plus any custom operations implied by the requirements.\n\nInclude per-endpoint: validation rules (required fields, formats, lengths), error responses (400 validation, 401 unauthenticated, 403 forbidden, 404 not found, 500 server error), and auth/role annotations.\n\nReturn ONLY valid JSON in the ApiDesign format.`;\n\nexport function buildDesignApiPrompt(requirement: string): string {\n return DESIGN_API_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildProDesignApiPrompt(\n projectName: string,\n apiStyle: string,\n dataModel: string,\n context: string\n): string {\n return PRO_DESIGN_API_PROMPT.replace('{projectName}', projectName)\n .replace('{apiStyle}', apiStyle)\n .replace('{dataModel}', dataModel)\n .replace('{context}', context);\n}\n","/**\n * validate_api tool - validates JSON against apiDesignSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema } from '../schemas';\n\nexport const validateApiTool = defineTool({\n name: 'validate_api',\n description:\n 'Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n design: z.string().describe('JSON string of the API design to validate'),\n }),\n handler: async ({ design }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(design) as unknown;\n apiDesignSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * design_api tool - generates API design from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api tool for plain text requirements.\n */\nexport function createDesignApiTool(model: Model) {\n return defineTool({\n name: 'design_api',\n description:\n 'Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the API requirements'),\n }),\n handler: async ({ requirement }): Promise<TApiDesign> => {\n const userPrompt = buildDesignApiPrompt(requirement);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * design_api_pro tool - structured API design from data model + context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildProDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api_pro tool for structured API design.\n */\nexport function createDesignApiProTool(model: Model) {\n return defineTool({\n name: 'design_api_pro',\n description:\n 'Generate a comprehensive API design from a data model and project context. Produces detailed endpoints with validation, error responses, and auth annotations.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n apiStyle: z.enum(['rest', 'graphql']).describe('Target API style'),\n dataModel: z.string().describe('Data model JSON or description'),\n context: z.string().describe('Project context: features, actors, stories'),\n }),\n handler: async ({ projectName, apiStyle, dataModel, context }): Promise<TApiDesign> => {\n const userPrompt = buildProDesignApiPrompt(projectName, apiStyle, dataModel, context);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * api-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateApiTool } from './validate-api';\nimport { createDesignApiTool } from './design-api';\nimport { createDesignApiProTool } from './design-api-pro';\n\nexport { validateApiTool } from './validate-api';\nexport { createDesignApiTool } from './design-api';\nexport { createDesignApiProTool } from './design-api-pro';\n\n/**\n * Create all api-designer tools. Pass the model for AI-backed tools.\n */\nexport function createApiDesignerTools(model: Model) {\n return createToolSet({\n validate_api: validateApiTool,\n design_api: createDesignApiTool(model),\n design_api_pro: createDesignApiProTool(model),\n });\n}\n","/**\n * runApiDesignerAgent - orchestrator for API design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { API_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createApiDesignerTools } from './tools';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from './subagents';\nimport type { ApiDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${API_DESIGNER_SYSTEM_PROMPT}\n\nYou are the API design orchestrator. When the user asks for an API design:\n\n1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.\n2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.\n3. **Generate design**: Use design_api (plain text) or design_api_pro (when data model and structured context are available) to produce the API design.\n4. **Validate**: Use validate_api to check the final API design JSON before returning.\n\nRespond with the final API design as JSON.`;\n\n/**\n * Run the api-designer orchestrator agent with all tools and subagents.\n */\nexport async function runApiDesignerAgent(config: ApiDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApiDesignerTools(model);\n const subagentTools = createSubagentToolSet(\n [endpointAnalyzerSubagent, contractDesignerSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for AuthDesign\n */\n\nimport { z } from 'zod';\n\nexport const authFlowStepSchema = z.object({\n order: z.number(),\n side: z.enum(['frontend', 'backend']),\n action: z.string(),\n details: z.string(),\n});\n\nexport const authFlowSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(authFlowStepSchema),\n});\n\nexport const authMiddlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n behavior: z.array(z.string()),\n});\n\nexport const roleDefinitionSchema = z.object({\n name: z.string(),\n description: z.string(),\n permissions: z.array(z.string()),\n});\n\nexport const securityPolicySchema = z.object({\n area: z.string(),\n rules: z.array(z.string()),\n});\n\nexport const authDesignSchema = z.object({\n strategy: z.enum(['jwt', 'session', 'oauth']),\n flows: z.array(authFlowSchema),\n middleware: z.array(authMiddlewareSchema),\n roles: z.array(roleDefinitionSchema),\n policies: z.array(securityPolicySchema),\n});\n\nexport type TAuthDesign = z.infer<typeof authDesignSchema>;\n","/**\n * System prompt for auth-designer orchestrator\n */\n\nexport const AUTH_DESIGNER_SYSTEM_PROMPT = `You are a senior security engineer specializing in authentication, authorization, and web security.\n\nYou design enterprise-quality auth systems with:\n- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps\n- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)\n- Role-based access control (RBAC) with permission matrices\n- Middleware chains for route protection and API authentication\n- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection\n- OAuth integration patterns when needed\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for auth-designer\n */\n\nexport const DESIGN_AUTH_PROMPT = `## Requirements:\n{requirement}\n\nDesign the authentication and authorization system. Include:\n\n1. Strategy: jwt, session, or oauth (choose based on requirements).\n2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.\n3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.\n4. Roles: role definitions with name, description, and permissions list.\n5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).\n\nReturn ONLY valid JSON:\n{\n \"strategy\": \"jwt\" | \"session\" | \"oauth\",\n \"flows\": [{ \"name\": \"signup\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"side\": \"frontend\", \"action\": \"...\", \"details\": \"...\" }] }],\n \"middleware\": [{ \"name\": \"authenticateRequest\", \"purpose\": \"...\", \"behavior\": [\"...\"] }],\n \"roles\": [{ \"name\": \"user\", \"description\": \"...\", \"permissions\": [\"...\"] }],\n \"policies\": [{ \"area\": \"passwords\", \"rules\": [\"...\"] }]\n}`;\n\nexport function buildDesignAuthPrompt(requirement: string): string {\n return DESIGN_AUTH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_auth tool - validates JSON against authDesignSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { authDesignSchema } from '../schemas';\n\nexport const validateAuthTool = defineTool({\n name: 'validate_auth',\n description:\n 'Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n design: z.string().describe('JSON string of the auth design to validate'),\n }),\n handler: async ({ design }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(design) as unknown;\n authDesignSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * design_auth tool - generates auth design from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { authDesignSchema, type TAuthDesign } from '../schemas';\nimport { buildDesignAuthPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_auth tool for auth flow generation.\n */\nexport function createDesignAuthTool(model: Model) {\n return defineTool({\n name: 'design_auth',\n description:\n 'Generate a complete authentication and authorization design from project requirements. Returns auth flows, middleware, roles, and security policies as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context and auth requirements'),\n }),\n handler: async ({ requirement }): Promise<TAuthDesign> => {\n const userPrompt = buildDesignAuthPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a security engineer. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, authDesignSchema);\n },\n });\n}\n","/**\n * auth-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateAuthTool } from './validate-auth';\nimport { createDesignAuthTool } from './design-auth';\n\nexport { validateAuthTool } from './validate-auth';\nexport { createDesignAuthTool } from './design-auth';\n\n/**\n * Create all auth-designer tools. Pass the model for AI-backed tools.\n */\nexport function createAuthDesignerTools(model: Model) {\n return createToolSet({\n validate_auth: validateAuthTool,\n design_auth: createDesignAuthTool(model),\n });\n}\n","/**\n * runAuthDesignerAgent - orchestrator for auth design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { AUTH_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createAuthDesignerTools } from './tools';\nimport { securityAnalyzerSubagent, flowDesignerSubagent } from './subagents';\nimport type { AuthDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${AUTH_DESIGNER_SYSTEM_PROMPT}\n\nYou are the auth design orchestrator. When the user asks for an auth design:\n\n1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.\n2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).\n3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.\n4. **Validate**: Use validate_auth to check the final auth design JSON before returning.\n\nRespond with the final auth design as JSON.`;\n\n/**\n * Run the auth-designer orchestrator agent with all tools and subagents.\n */\nexport async function runAuthDesignerAgent(config: AuthDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createAuthDesignerTools(model);\n const subagentTools = createSubagentToolSet([securityAnalyzerSubagent, flowDesignerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for FrontendDesign\n */\n\nimport { z } from 'zod';\n\nexport const formFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n validation: z.string(),\n});\n\nexport const pageDesignSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['public', 'protected'])),\n purpose: z.string(),\n formFields: z.array(formFieldSchema).default([]),\n actions: z.array(z.string()).default([]),\n emptyState: z.string().default(''),\n errorState: z.string().default(''),\n redirectOnSuccess: z.string().default(''),\n keyUiElements: z.array(z.string()).default([]),\n});\n\nexport const componentDesignSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['layout', 'shared', 'form', 'display', 'navigation'])),\n purpose: z.string(),\n props: z.array(z.string()).default([]),\n usedIn: z.array(z.string()).default([]),\n});\n\nexport const frontendDesignSchema = z.object({\n pages: z.array(pageDesignSchema).default([]),\n components: z.array(componentDesignSchema).default([]),\n stateManagement: z.string().default(''),\n routingNotes: z.string().default(''),\n});\n\nexport type TFrontendDesign = z.infer<typeof frontendDesignSchema>;\n","/**\n * System prompt for frontend-architect orchestrator\n */\n\nexport const FRONTEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior frontend architect specializing in page design, routing, and component architecture.\n\nYou design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:\n- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)\n- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support\n- **Routing**: React Router v7 with private route guards\n- **Forms**: React Hook Form + Zod validation\n- **GraphQL**: Apollo Client with CodeGen-typed hooks\n- **Path Aliases**: @/{appName}/* mapping to ./src/*\n\nArchitecture outputs:\n- Public and protected pages with detailed route definitions\n- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects\n- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)\n- State management strategy (per-page vs global, Apollo cache vs local state)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for frontend-architect\n */\n\nexport const DESIGN_FRONTEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the frontend architecture. Include:\n\n1. Pages: public and protected pages. For each page: path, name, access level, purpose, form fields (with validation), actions, empty state, error state, redirect on success, key UI elements.\n2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.\n3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).\n4. Routing notes: any special routing behavior (redirects, guards, nested routes).\n\nReturn ONLY valid JSON:\n{\n \"pages\": [{ \"path\": \"/login\", \"name\": \"Login\", \"access\": \"public\", \"purpose\": \"...\", \"formFields\": [{ \"name\": \"email\", \"type\": \"email\", \"required\": true, \"validation\": \"valid email format\" }], \"actions\": [\"Submit login form\"], \"emptyState\": \"\", \"errorState\": \"Show error message\", \"redirectOnSuccess\": \"/dashboard\", \"keyUiElements\": [\"Email input\", \"Password input\", \"Submit button\"] }],\n \"components\": [{ \"name\": \"Navbar\", \"type\": \"navigation\", \"purpose\": \"...\", \"props\": [\"user\"], \"usedIn\": [\"/dashboard\", \"/profile\"] }],\n \"stateManagement\": \"...\",\n \"routingNotes\": \"...\"\n}`;\n\nexport function buildDesignFrontendPrompt(requirement: string): string {\n return DESIGN_FRONTEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_frontend tool - validates JSON against frontendDesignSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { frontendDesignSchema } from '../schemas';\n\nexport const validateFrontendTool = defineTool({\n name: 'validate_frontend',\n description:\n 'Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n design: z.string().describe('JSON string of the frontend design to validate'),\n }),\n handler: async ({ design }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(design) as unknown;\n frontendDesignSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * design_frontend tool - generates frontend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { frontendDesignSchema, type TFrontendDesign } from '../schemas';\nimport { buildDesignFrontendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_frontend tool for frontend architecture generation.\n */\nexport function createDesignFrontendTool(model: Model) {\n return defineTool({\n name: 'design_frontend',\n description:\n 'Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context, API surface, and frontend requirements'),\n }),\n handler: async ({ requirement }): Promise<TFrontendDesign> => {\n const userPrompt = buildDesignFrontendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a frontend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, frontendDesignSchema);\n },\n });\n}\n","/**\n * frontend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendTool } from './validate-frontend';\nimport { createDesignFrontendTool } from './design-frontend';\n\nexport { validateFrontendTool } from './validate-frontend';\nexport { createDesignFrontendTool } from './design-frontend';\n\n/**\n * Create all frontend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createFrontendArchitectTools(model: Model) {\n return createToolSet({\n validate_frontend: validateFrontendTool,\n design_frontend: createDesignFrontendTool(model),\n });\n}\n","/**\n * runFrontendArchitectAgent - routing orchestrator for frontend architecture design.\n * Delegates to react-builder or nextjs-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet, defineSubagent } from '../../lib/subagents';\nimport { FRONTEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createFrontendArchitectTools } from './tools';\nimport {\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n} from './subagents';\nimport type { FrontendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\n/** Subagent wrapper for react-builder orchestrator */\nconst reactBuilderSubagent = defineSubagent({\n name: 'react-builder',\n description:\n 'Generates a Vite + React SPA configuration from a frontend design and GraphQL schema. Use when the framework-selector recommends react-vite.',\n systemPrompt:\n 'You are a React/Vite frontend builder. Generate a complete frontend config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\n/** Subagent wrapper for nextjs-builder orchestrator */\nconst nextjsBuilderSubagent = defineSubagent({\n name: 'nextjs-builder',\n description:\n 'Generates a Next.js App Router configuration from a frontend design. Use when the framework-selector recommends nextjs.',\n systemPrompt:\n 'You are a Next.js App Router builder. Generate a complete Next.js config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${FRONTEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the frontend architecture routing orchestrator. When the user asks for a frontend design:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.\n2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.\n3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.\n4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.\n5. **Validate**: Use validate_frontend to check the final design JSON before returning.\n6. **Delegate to builder**: Based on the framework-selector recommendation:\n - If \"react-vite\": use subagent_react-builder with the design to generate a Vite + React SPA config.\n - If \"nextjs\": use subagent_nextjs-builder with the design to generate a Next.js App Router config.\n\nRespond with the final frontend design as JSON, including the builder output.`;\n\n/**\n * Run the frontend-architect routing orchestrator with all tools and subagents.\n */\nexport async function runFrontendArchitectAgent(\n config: FrontendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createFrontendArchitectTools(model);\n const subagentTools = createSubagentToolSet(\n [\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n reactBuilderSubagent,\n nextjsBuilderSubagent,\n ],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ExecutionPlan\n */\n\nimport { z } from 'zod';\n\nexport const phaseStepSchema = z.object({\n order: z.number(),\n action: z.string(),\n details: z.string(),\n});\n\nexport const implementationPhaseSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(phaseStepSchema),\n});\n\nexport const edgeCaseSchema = z.object({\n area: z.string(),\n scenario: z.string(),\n handling: z.string(),\n severity: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['critical', 'warning', 'info'])),\n});\n\nexport const testChecklistItemSchema = z.object({\n flow: z.string(),\n item: z.string(),\n expectedResult: z.string(),\n});\n\nexport const executionPlanSchema = z.object({\n phases: z.array(implementationPhaseSchema).default([]),\n currentState: z.string().default(''),\n desiredEndState: z.string().default(''),\n edgeCases: z.array(edgeCaseSchema).default([]),\n securityNotes: z.array(z.string()).default([]),\n performanceNotes: z.array(z.string()).default([]),\n testingChecklist: z.array(testChecklistItemSchema).default([]),\n});\n\nexport type TExecutionPlan = z.infer<typeof executionPlanSchema>;\n","/**\n * System prompt for execution-planner orchestrator\n */\n\nexport const EXECUTION_PLANNER_SYSTEM_PROMPT = `You are a senior tech lead specializing in implementation strategy and project execution planning.\n\nYou create enterprise-quality execution plans with:\n- Phased implementation order with concrete, numbered steps per phase\n- Current state analysis and desired end state definition\n- Edge cases per domain area with handling strategies and severity levels\n- Security considerations (passwords, tokens, CORS, input validation)\n- Performance considerations (indexing, caching, lazy loading, N+1 prevention)\n- Manual testing checklists grouped by feature flow\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for execution-planner\n */\n\nexport const CREATE_EXECUTION_PLAN_PROMPT = `## Full Plan Context:\n{context}\n\nCreate a comprehensive execution plan. Include:\n\n1. **phases**: Implementation phases (Foundation, Auth, Core Features, etc.). Each phase has numbered steps with concrete actions (e.g. \"1. Install dependencies\", \"2. Create User model\").\n2. **currentState**: What the project starts with (e.g. \"vanilla Next.js, no DB, no auth\").\n3. **desiredEndState**: What must work when done (user capabilities + technical verification).\n4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).\n5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).\n6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).\n7. **testingChecklist**: Manual testing items per flow with expected results.\n\nReturn ONLY valid JSON:\n{\n \"phases\": [{ \"name\": \"Phase 1: Foundation\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"action\": \"Install dependencies\", \"details\": \"npm install mongoose bcryptjs jsonwebtoken\" }] }],\n \"currentState\": \"...\",\n \"desiredEndState\": \"...\",\n \"edgeCases\": [{ \"area\": \"Authentication\", \"scenario\": \"Email already exists\", \"handling\": \"Return 400 with clear message\", \"severity\": \"critical\" }],\n \"securityNotes\": [\"...\"],\n \"performanceNotes\": [\"...\"],\n \"testingChecklist\": [{ \"flow\": \"Auth Flow\", \"item\": \"Sign up with valid credentials\", \"expectedResult\": \"Account created, redirected to dashboard\" }]\n}`;\n\nexport function buildCreateExecutionPlanPrompt(context: string): string {\n return CREATE_EXECUTION_PLAN_PROMPT.replace('{context}', context);\n}\n","/**\n * validate_execution_plan tool - validates JSON against executionPlanSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { executionPlanSchema } from '../schemas';\n\nexport const validateExecutionPlanTool = defineTool({\n name: 'validate_execution_plan',\n description:\n 'Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n plan: z.string().describe('JSON string of the execution plan to validate'),\n }),\n handler: async ({ plan }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(plan) as unknown;\n executionPlanSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * create_execution_plan tool - generates execution plan from context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { executionPlanSchema, type TExecutionPlan } from '../schemas';\nimport { buildCreateExecutionPlanPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the create_execution_plan tool for generating phased plans.\n */\nexport function createExecutionPlanTool(model: Model) {\n return defineTool({\n name: 'create_execution_plan',\n description:\n 'Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.',\n input: z.object({\n context: z.string().describe('Full plan context: all sections generated so far'),\n }),\n handler: async ({ context }): Promise<TExecutionPlan> => {\n const userPrompt = buildCreateExecutionPlanPrompt(context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a tech lead. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, executionPlanSchema);\n },\n });\n}\n","/**\n * execution-planner tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExecutionPlanTool } from './validate-plan';\nimport { createExecutionPlanTool } from './create-plan';\n\nexport { validateExecutionPlanTool } from './validate-plan';\nexport { createExecutionPlanTool } from './create-plan';\n\n/**\n * Create all execution-planner tools. Pass the model for AI-backed tools.\n */\nexport function createExecutionPlannerTools(model: Model) {\n return createToolSet({\n validate_execution_plan: validateExecutionPlanTool,\n create_execution_plan: createExecutionPlanTool(model),\n });\n}\n","/**\n * runExecutionPlannerAgent - orchestrator for execution plan design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXECUTION_PLANNER_SYSTEM_PROMPT } from './prompts';\nimport { createExecutionPlannerTools } from './tools';\nimport { edgeCaseAnalyzerSubagent, testingStrategistSubagent } from './subagents';\nimport type { ExecutionPlannerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXECUTION_PLANNER_SYSTEM_PROMPT}\n\nYou are the execution planning orchestrator. When the user provides plan sections:\n\n1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.\n2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.\n3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.\n4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.\n\nRespond with the final execution plan as JSON.`;\n\n/**\n * Run the execution-planner orchestrator agent with all tools and subagents.\n */\nexport async function runExecutionPlannerAgent(\n config: ExecutionPlannerAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExecutionPlannerTools(model);\n const subagentTools = createSubagentToolSet(\n [edgeCaseAnalyzerSubagent, testingStrategistSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for BackendDesign\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum helper */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const middlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n appliesTo: z\n .string()\n .default('global')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['global', 'all', 'app', 'application', 'every', 'server'].includes(n)) return 'global';\n if (\n [\n 'route',\n 'routes',\n 'specific',\n 'specific routes',\n 'endpoint',\n 'endpoints',\n 'path',\n ].includes(n)\n )\n return 'route';\n if (['resource', 'entity', 'module', 'controller', 'model'].includes(n)) return 'resource';\n return 'global';\n })\n .pipe(z.enum(['global', 'route', 'resource'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const serviceSchema = z.object({\n name: z.string(),\n entity: z.string(),\n operations: z.array(z.string()).default([]),\n dependencies: z.array(z.string()).default([]),\n});\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routeGroupSchema = z.object({\n resource: z.string(),\n basePath: z.string(),\n endpoints: z\n .array(\n z.object({\n method: httpMethodSchema,\n path: z.string(),\n handler: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n })\n )\n .default([]),\n});\n\nexport const backendDesignSchema = z.object({\n framework: ciEnum(['express', 'apollo', 'both']),\n language: ciEnum(['typescript', 'javascript']).default('typescript'),\n database: z.string().default('mongodb'),\n services: z.array(serviceSchema).default([]),\n middleware: z.array(middlewareSchema).default([]),\n routes: z.array(routeGroupSchema).default([]),\n folderStructure: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n notes: z.string().default(''),\n});\n\nexport type TBackendDesign = z.infer<typeof backendDesignSchema>;\n","/**\n * System prompt for backend-architect orchestrator\n */\n\nexport const BACKEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior backend architect specializing in Node.js server design.\n\nYou analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:\n- Framework selection (Express REST, Apollo GraphQL, or both)\n- Service layer design with clear operation contracts per entity\n- Middleware stack (auth, validation, error handling, CORS, rate limiting)\n- Route/resolver organization grouped by resource\n- Folder structure following domain-driven conventions\n- Environment variable inventory\n- Database connection and ORM/ODM strategy\n\nWhen \"both\" is selected (Express + Apollo), use the Apollo Gateway pattern:\n- Apollo Gateway as the single public entry point for GraphQL queries\n- Subgraphs as internal services composed via IntrospectAndCompose\n- RemoteGraphQLDataSource for header forwarding (auth tokens, service tokens)\n- Express for webhooks, file uploads, and health checks only\n- Gateway has no business logic, all logic lives in subgraphs\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for backend architecture generation\n */\n\nexport const DESIGN_BACKEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the backend architecture. Include:\n\n1. Framework: choose \"express\" (REST API), \"apollo\" (GraphQL subgraph), or \"both\" (Apollo subgraph + Express gateway).\n2. Services: one per entity with CRUD operations and dependencies.\n3. Middleware: auth (JWT/session), validation (Zod/Joi), error handling, CORS, rate limiting.\n4. Routes (if Express): RESTful routes grouped by resource with method, path, handler, auth, and roles.\n5. Folder structure: list of directories and key files.\n6. Env vars: list all required environment variables.\n\nReturn ONLY valid JSON:\n{\n \"framework\": \"express\" | \"apollo\" | \"both\",\n \"language\": \"typescript\",\n \"database\": \"mongodb\",\n \"services\": [{ \"name\": \"UserService\", \"entity\": \"User\", \"operations\": [\"create\", \"findById\", \"findAll\", \"update\", \"delete\"], \"dependencies\": [] }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"purpose\": \"JWT token verification\", \"appliesTo\": \"global\", \"config\": {} }],\n \"routes\": [{ \"resource\": \"users\", \"basePath\": \"/api/users\", \"endpoints\": [{ \"method\": \"GET\", \"path\": \"/\", \"handler\": \"getAll\", \"auth\": true, \"roles\": [\"admin\"] }] }],\n \"folderStructure\": [\"src/\", \"src/routes/\", \"src/services/\", \"src/middleware/\", \"src/models/\", \"src/config/\"],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\"],\n \"notes\": \"\"\n}`;\n\nexport function buildDesignBackendPrompt(requirement: string): string {\n return DESIGN_BACKEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_backend tool - validates JSON against backendDesignSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { backendDesignSchema } from '../schemas';\n\nexport const validateBackendTool = defineTool({\n name: 'validate_backend',\n description:\n 'Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n design: z.string().describe('JSON string of the backend design to validate'),\n }),\n handler: async ({ design }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(design) as unknown;\n backendDesignSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * design_backend tool - generates backend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { backendDesignSchema, type TBackendDesign } from '../schemas';\nimport { buildDesignBackendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_backend tool for backend architecture generation.\n */\nexport function createDesignBackendTool(model: Model) {\n return defineTool({\n name: 'design_backend',\n description:\n 'Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TBackendDesign> => {\n const userPrompt = buildDesignBackendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a backend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, backendDesignSchema);\n },\n });\n}\n","/**\n * backend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateBackendTool } from './validate-backend';\nimport { createDesignBackendTool } from './design-backend';\n\nexport { validateBackendTool } from './validate-backend';\nexport { createDesignBackendTool } from './design-backend';\n\n/**\n * Create all backend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createBackendArchitectTools(model: Model) {\n return createToolSet({\n validate_backend: validateBackendTool,\n design_backend: createDesignBackendTool(model),\n });\n}\n","/**\n * service-planner subagent - plans service layer, middleware stack, folder structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SERVICE_PLANNER_SYSTEM_PROMPT = `You are a backend service architect. Given a data model and API design, you plan the service layer.\n\n## Service Design\nFor each entity:\n- Service name (PascalCase + \"Service\")\n- CRUD operations: create, findById, findAll, update, delete\n- Custom operations from user flows (e.g. searchByName, bulkImport)\n- Dependencies on other services (e.g. OrderService depends on UserService)\n\n## Middleware Stack\n- Authentication middleware: JWT verification, session check\n- Authorization middleware: role-based access, resource ownership\n- Validation middleware: request body/params validation\n- Error handling: centralized error handler with typed errors\n- Logging: request/response logging\n- Rate limiting: per-IP or per-user limits\n- CORS: origin whitelist\n\n## Folder Structure\nRecommend a clean folder layout:\n- src/services/ (one file per service)\n- src/middleware/ (one file per middleware)\n- src/models/ (one file per entity)\n- src/routes/ or src/modules/ (grouped by resource)\n- src/config/ (env, database, auth config)\n- src/utils/ (shared helpers)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const servicePlannerSubagent = defineSubagent({\n name: 'service-planner',\n description:\n 'Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.',\n systemPrompt: SERVICE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - analyzes requirements and selects Express vs Apollo vs both\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a backend technology advisor. Given project requirements, you recommend the best backend framework.\n\n## Decision Criteria\n\n### Choose \"express\" (REST API) when:\n- The API is primarily CRUD with RESTful resources\n- The frontend is a traditional SPA (React/Vue) consuming REST\n- Simple request/response patterns without complex data fetching\n- No need for real-time subscriptions\n- Team is more familiar with REST\n\n### Choose \"apollo\" (GraphQL subgraph) when:\n- The frontend needs flexible data fetching (avoid over/under-fetching)\n- Multiple frontends consume the same API (web, mobile, admin)\n- Complex nested data relationships\n- Need for real-time subscriptions\n- Part of a federated GraphQL architecture\n\n### Choose \"both\" when:\n- Apollo subgraph for main data API + Express for webhooks, file uploads, health checks\n- Need both REST endpoints (for external integrations) and GraphQL (for frontend)\n- When \"both\" is selected, an Apollo Gateway is used to compose subgraphs into a unified API:\n - Gateway is the only public entry point for GraphQL\n - Subgraphs are internal services, not exposed to clients directly\n - Gateway uses IntrospectAndCompose for schema discovery\n - RemoteGraphQLDataSource forwards auth headers to subgraphs\n - Express handles non-GraphQL concerns (webhooks, file uploads)\n\n## Output Format\nState your recommendation clearly:\n- Framework: express | apollo | both\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you'd lose with the alternative\n- If \"both\": describe which concerns go to Express vs Apollo Gateway vs subgraphs\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runBackendArchitectAgent - routing orchestrator for backend design\n * Delegates to express-builder or apollo-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { BACKEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createBackendArchitectTools } from './tools';\nimport { servicePlannerSubagent, frameworkSelectorSubagent } from './subagents';\nimport type { BackendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${BACKEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the backend architecture orchestrator. When the user provides requirements:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements and recommend Express, Apollo, or both.\n2. **Plan services**: Use subagent_service-planner to design the service layer, middleware stack, and folder structure.\n3. **Generate design**: Use design_backend to produce the complete backend architecture as JSON.\n4. **Validate**: Use validate_backend to check the final design JSON before returning.\n\nAfter generating the design, note the \"framework\" field in the result:\n- If \"express\": the downstream express-builder should be used to scaffold the project.\n- If \"apollo\": the downstream apollo-builder should be used to scaffold the project.\n- If \"both\": both builders should be invoked sequentially.\n\nRespond with the final backend design as JSON.`;\n\n/**\n * Run the backend-architect orchestrator agent.\n */\nexport async function runBackendArchitectAgent(\n config: BackendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createBackendArchitectTools(model);\n const subagentTools = createSubagentToolSet([servicePlannerSubagent, frameworkSelectorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Apollo subgraph configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const graphqlFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n nullable: z.coerce.boolean().default(false),\n isList: z.coerce.boolean().default(false),\n description: z.string().default(''),\n});\n\nexport const graphqlTypeSchema = z.object({\n name: z.string(),\n kind: ciEnum(['type', 'input', 'enum', 'interface', 'union']),\n fields: z.array(graphqlFieldSchema).default([]),\n values: z.array(z.string()).default([]),\n description: z.string().default(''),\n isEntity: z.coerce.boolean().default(false),\n keyFields: z.array(z.string()).default([]),\n});\n\nexport const resolverOperationSchema = z.object({\n name: z.string(),\n type: ciEnum(['query', 'mutation', 'subscription']),\n args: z.array(graphqlFieldSchema).default([]),\n returnType: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n description: z.string().default(''),\n});\n\nexport const subgraphModuleSchema = z.object({\n name: z.string(),\n entity: z.string(),\n types: z.array(graphqlTypeSchema).default([]),\n operations: z.array(resolverOperationSchema).default([]),\n datasource: z.string().default(''),\n loader: z.string().default(''),\n});\n\nexport const subgraphConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(4000),\n database: z.string().default('mongodb'),\n modules: z.array(subgraphModuleSchema).default([]),\n sharedTypes: z.array(graphqlTypeSchema).default([]),\n authDirective: z.coerce.boolean().default(true),\n cacheDirective: z.coerce.boolean().default(false),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TSubgraphConfig = z.infer<typeof subgraphConfigSchema>;\n","/**\n * System prompt for apollo-builder orchestrator\n */\n\nexport const APOLLO_BUILDER_SYSTEM_PROMPT = `You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.\n\nYou generate production-ready Apollo subgraph configurations from data models and API designs:\n- 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts\n- GraphQL type definitions with proper nullability, lists, and descriptions\n- Input types for mutations with validation annotations\n- Enum types from domain values\n- Federation directives: @key for entity references, @external for fields owned by other subgraphs, @requires for field dependencies, @provides for fields resolvable by this subgraph\n- __resolveReference for cross-subgraph entity resolution via buildSubgraphSchema\n- DataLoader per module for batching and caching database lookups (solves N+1)\n- Query and mutation resolvers with auth/role requirements\n- Datasource classes per entity (MongoDB datasource pattern)\n- Auth directive (@auth) configuration\n- Redis cache directives: @cacheSet on queries, @cachePurge on mutations\n- GraphQL CodeGen for TypeScript types (generates base-types.ts)\n- Module-based organization (one module per entity/domain)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for subgraph config generation\n */\n\nexport const DESIGN_SUBGRAPH_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Apollo GraphQL subgraph configuration (Federation v2). Include:\n\n1. Modules: one per entity with 4 files each ({module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts).\n2. Types: GraphQL object types with isEntity/keyFields for federation, input types, enums with fields/values.\n3. Operations: queries (getById, getAll, search) and mutations (create, update, delete) per module.\n4. Auth: mark which operations require authentication and which roles.\n5. DataLoader: one loader per module for batching lookups (loader name).\n6. Shared types: types used across modules (e.g. Pagination, SortOrder).\n7. Cache: set cacheDirective to true if Redis caching (@cacheSet/@cachePurge) is needed.\n8. Env vars: PORT, DATABASE_URL, JWT_SECRET, REDIS_URL, etc.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-subgraph\",\n \"port\": 4000,\n \"database\": \"mongodb\",\n \"modules\": [{\n \"name\": \"user\",\n \"entity\": \"User\",\n \"types\": [{ \"name\": \"User\", \"kind\": \"type\", \"fields\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"isEntity\": true, \"keyFields\": [\"id\"] }],\n \"operations\": [{ \"name\": \"getUser\", \"type\": \"query\", \"args\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"returnType\": \"User\", \"auth\": true, \"roles\": [] }],\n \"datasource\": \"UserDataSource\",\n \"loader\": \"UserLoader\"\n }],\n \"sharedTypes\": [],\n \"authDirective\": true,\n \"cacheDirective\": false,\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"REDIS_URL\"]\n}`;\n\nexport function buildDesignSubgraphPrompt(requirement: string): string {\n return DESIGN_SUBGRAPH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_subgraph tool - validates JSON against subgraphConfigSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { subgraphConfigSchema } from '../schemas';\n\nexport const validateSubgraphTool = defineTool({\n name: 'validate_subgraph',\n description:\n 'Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n config: z.string().describe('JSON string of the subgraph config to validate'),\n }),\n handler: async ({ config }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(config) as unknown;\n subgraphConfigSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * generate_subgraph tool - generates subgraph config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { subgraphConfigSchema, type TSubgraphConfig } from '../schemas';\nimport { buildDesignSubgraphPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_subgraph tool for Apollo subgraph config generation.\n */\nexport function createGenerateSubgraphTool(model: Model) {\n return defineTool({\n name: 'generate_subgraph',\n description:\n 'Generate a complete Apollo GraphQL subgraph configuration from data model and API design. Returns modules, types, operations, and datasources as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TSubgraphConfig> => {\n const userPrompt = buildDesignSubgraphPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Apollo GraphQL architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, subgraphConfigSchema);\n },\n });\n}\n","/**\n * scaffold_subgraph tool - compiles .ref/templates/subgraph/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TSubgraphConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert subgraph config to template context */\nfunction toTemplateContext(config: TSubgraphConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n entity: m.entity,\n datasource: m.datasource,\n types: m.types,\n operations: m.operations,\n })),\n authDirective: config.authDirective,\n envVars: config.envVars,\n sharedTypes: config.sharedTypes,\n };\n}\n\nexport const scaffoldSubgraphTool = defineTool({\n name: 'scaffold_subgraph',\n description:\n 'Scaffold an Apollo GraphQL subgraph project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated subgraph config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'subgraph config') as TSubgraphConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/subgraph');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * apollo-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSubgraphTool } from './validate-subgraph';\nimport { createGenerateSubgraphTool } from './generate-subgraph';\nimport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\nexport { validateSubgraphTool } from './validate-subgraph';\nexport { createGenerateSubgraphTool } from './generate-subgraph';\nexport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\n/**\n * Create all apollo-builder tools. Pass the model for AI-backed tools.\n */\nexport function createApolloBuilderTools(model: Model) {\n return createToolSet({\n validate_subgraph: validateSubgraphTool,\n generate_subgraph: createGenerateSubgraphTool(model),\n scaffold_subgraph: scaffoldSubgraphTool,\n });\n}\n","/**\n * schema-generator subagent - generates GraphQL type definitions from data model\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_GENERATOR_SYSTEM_PROMPT = `You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.\n\n## Type Generation\nFor each entity in the data model:\n- Create the main object type with all fields mapped to GraphQL scalars (String, Int, Float, Boolean, ID)\n- Create input types for create and update mutations (omit auto-generated fields like id, createdAt)\n- Create enum types for status fields and role fields\n- Add proper nullability (! for required fields)\n- Add [Type] for array/list fields\n\n## Federation Directives\n- @key(fields: \"id\") on entity types that can be referenced across subgraphs\n- @external marks a field as owned by another subgraph\n- @requires(fields: \"weight\") declares fields needed from the entity to resolve a field\n- @provides(fields: \"name\") declares fields on a return type that this subgraph can resolve\n- @auth directive on types/fields that require authentication\n\n## Cache Directives (Redis)\n- @cacheSet(type: \"Entity\", identifier: \"_id\") on query resolvers\n- @cachePurge(type: \"Entity\", identifier: \"_id\") on mutation resolvers\n\n## Relationships\n- Reference types for foreign keys (e.g. author: User instead of authorId: ID)\n- Use [Type] for one-to-many relationships\n\n## Naming Conventions\n- Types: PascalCase (User, BlogPost)\n- Fields: camelCase (firstName, createdAt)\n- Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)\n- Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)\n\nRespond with the full GraphQL SDL. Do NOT return JSON.`;\n\nexport const schemaGeneratorSubagent = defineSubagent({\n name: 'schema-generator',\n description:\n 'Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.',\n systemPrompt: SCHEMA_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * resolver-planner subagent - plans resolver implementations per module\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RESOLVER_PLANNER_SYSTEM_PROMPT = `You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.\n\n## 4-File Module Pattern\nEach module has four files:\n- {module}.graphql -- Type definitions with federation directives\n- {module}.resolver.ts -- Query/Mutation/Field resolvers including __resolveReference\n- {module}.datasource.ts -- Business logic and database access\n- {module}.loader.ts -- DataLoader for batching and caching lookups\n\n## Resolver Planning\nFor each module/entity:\n\n### __resolveReference (Federation)\n- Every entity type with @key must implement __resolveReference\n- Called by the gateway when another subgraph references this entity\n- Receives { __typename, id } and returns the full entity from datasource\n\n### Query Resolvers\n- getById: fetch single record by ID from datasource\n- getAll: fetch paginated list with filters and sorting\n- search: text search across relevant fields\n\n### Mutation Resolvers\n- create: validate input, create record, return created entity\n- update: validate input, find existing, merge changes, return updated entity\n- delete: find existing, remove, return success status\n\n### Field Resolvers\n- For relationship fields: resolve references via DataLoader (NOT direct DB calls)\n- For computed fields: calculate from existing data\n\n## DataLoader Pattern\nEach module has a loader file that creates DataLoader instances:\n- Batches multiple lookups into a single database query\n- Caches results within a single request to solve the N+1 problem\n- Created per-request in the context, not shared across requests\n\n## Datasource Pattern\n- Each module has a datasource class extending MongoDataSource or similar\n- Datasource handles all database operations\n- Resolvers call datasource methods, never touch the DB directly\n\n## Auth Integration\n- Check auth context in resolver before executing\n- Verify role permissions per operation\n- Resource ownership checks for user-specific data\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const resolverPlannerSubagent = defineSubagent({\n name: 'resolver-planner',\n description:\n 'Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.',\n systemPrompt: RESOLVER_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runApolloBuilderAgent - orchestrator for Apollo GraphQL subgraph generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { APOLLO_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createApolloBuilderTools } from './tools';\nimport { schemaGeneratorSubagent, resolverPlannerSubagent } from './subagents';\nimport type { ApolloBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${APOLLO_BUILDER_SYSTEM_PROMPT}\n\nYou are the Apollo subgraph builder orchestrator. When the user provides requirements:\n\n1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.\n2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.\n3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.\n4. **Validate**: Use validate_subgraph to check the config JSON before returning.\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.\n\nRespond with the final subgraph config as JSON.`;\n\n/**\n * Run the apollo-builder orchestrator agent.\n */\nexport async function runApolloBuilderAgent(\n config: ApolloBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApolloBuilderTools(model);\n const subagentTools = createSubagentToolSet([schemaGeneratorSubagent, resolverPlannerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Express app configuration\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routerMethodSchema = z.object({\n name: z.string(),\n httpMethod: httpMethodSchema,\n path: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n validation: z.string().default(''),\n description: z.string().default(''),\n});\n\nexport const routerSchema = z.object({\n name: z.string(),\n resource: z.string(),\n basePath: z.string(),\n methods: z.array(routerMethodSchema).default([]),\n});\n\nexport const modelFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n ref: z.string().optional(),\n default: z.string().optional(),\n});\n\nexport const modelSchema = z.object({\n name: z.string(),\n collection: z.string(),\n fields: z.array(modelFieldSchema).default([]),\n timestamps: z.coerce.boolean().default(true),\n indexes: z.array(z.string()).default([]),\n});\n\nexport const middlewareConfigSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['auth', 'authentication', 'jwt', 'token'].includes(n)) return 'auth' as const;\n if (['validation', 'validate', 'validator', 'input'].includes(n))\n return 'validation' as const;\n if (['errorhandler', 'error', 'errorhandling', 'errors'].includes(n))\n return 'errorHandler' as const;\n if (['cors', 'crossorigin'].includes(n)) return 'cors' as const;\n if (['ratelimit', 'ratelimiter', 'ratelimiting', 'throttle'].includes(n))\n return 'rateLimit' as const;\n if (['logging', 'logger', 'log', 'morgan'].includes(n)) return 'logging' as const;\n return 'custom' as const;\n })\n .pipe(z.enum(['auth', 'validation', 'errorHandler', 'cors', 'rateLimit', 'logging', 'custom'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const expressConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(3000),\n database: z.string().default('mongodb'),\n routers: z.array(routerSchema).default([]),\n models: z.array(modelSchema).default([]),\n middleware: z.array(middlewareConfigSchema).default([]),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TExpressConfig = z.infer<typeof expressConfigSchema>;\n","/**\n * System prompt for express-builder orchestrator\n */\n\nexport const EXPRESS_BUILDER_SYSTEM_PROMPT = `You are an expert Express.js backend architect.\n\nYou generate production-ready Express application configurations from data models and API designs:\n- Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts\n- Mongoose/Prisma models with field types, validation, and relationships\n- Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)\n- Route organization with proper HTTP methods and paths\n- Health check endpoint at /health (included by default)\n- Jest tests per router using supertest\n- Environment variable inventory\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Express config generation\n */\n\nexport const DESIGN_EXPRESS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Express.js application configuration. Include:\n\n1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).\n2. Health check: a default /health router is always included.\n3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.\n4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.\n5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.\n6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-api\",\n \"port\": 3000,\n \"database\": \"mongodb\",\n \"routers\": [{\n \"name\": \"users\",\n \"resource\": \"users\",\n \"basePath\": \"/api/users\",\n \"methods\": [{\n \"name\": \"getAll\",\n \"httpMethod\": \"GET\",\n \"path\": \"/\",\n \"auth\": true,\n \"roles\": [\"admin\"],\n \"validation\": \"\",\n \"description\": \"Get all users with pagination\"\n }]\n }],\n \"models\": [{\n \"name\": \"User\",\n \"collection\": \"users\",\n \"fields\": [{ \"name\": \"email\", \"type\": \"String\", \"required\": true, \"unique\": true }],\n \"timestamps\": true,\n \"indexes\": [\"email\"]\n }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"type\": \"auth\", \"config\": {} }],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"NODE_ENV\"]\n}`;\n\nexport function buildDesignExpressPrompt(requirement: string): string {\n return DESIGN_EXPRESS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_express tool - validates JSON against expressConfigSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { expressConfigSchema } from '../schemas';\n\nexport const validateExpressTool = defineTool({\n name: 'validate_express',\n description:\n 'Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n config: z.string().describe('JSON string of the Express config to validate'),\n }),\n handler: async ({ config }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(config) as unknown;\n expressConfigSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * generate_express tool - generates Express config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { expressConfigSchema, type TExpressConfig } from '../schemas';\nimport { buildDesignExpressPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_express tool for Express config generation.\n */\nexport function createGenerateExpressTool(model: Model) {\n return defineTool({\n name: 'generate_express',\n description:\n 'Generate a complete Express.js application configuration from data model and API design. Returns routers, models, middleware, and env vars as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TExpressConfig> => {\n const userPrompt = buildDesignExpressPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Express.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, expressConfigSchema);\n },\n });\n}\n","/**\n * scaffold_express tool - compiles .ref/templates/express/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TExpressConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert express config to template context */\nfunction toTemplateContext(config: TExpressConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n routers: config.routers,\n models: config.models,\n middleware: config.middleware,\n envVars: config.envVars,\n modules: config.routers.map(r => ({\n name: r.resource,\n pascalName: r.name.charAt(0).toUpperCase() + r.name.slice(1),\n camelName: r.resource,\n methods: r.methods,\n })),\n };\n}\n\nexport const scaffoldExpressTool = defineTool({\n name: 'scaffold_express',\n description:\n 'Scaffold an Express.js project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated Express config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'express config') as TExpressConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/express');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * express-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExpressTool } from './validate-express';\nimport { createGenerateExpressTool } from './generate-express';\nimport { scaffoldExpressTool } from './scaffold-express';\n\nexport { validateExpressTool } from './validate-express';\nexport { createGenerateExpressTool } from './generate-express';\nexport { scaffoldExpressTool } from './scaffold-express';\n\n/**\n * Create all express-builder tools. Pass the model for AI-backed tools.\n */\nexport function createExpressBuilderTools(model: Model) {\n return createToolSet({\n validate_express: validateExpressTool,\n generate_express: createGenerateExpressTool(model),\n scaffold_express: scaffoldExpressTool,\n });\n}\n","/**\n * route-generator subagent - generates route files from API design\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_GENERATOR_SYSTEM_PROMPT = `You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.\n\n## Co-located Router Pattern\nEach feature lives in src/routers/{name}/ with three files:\n- {name}.router.ts -- Express Router with route definitions\n- {name}.controller.ts -- Request handler logic\n- {name}.spec.ts -- Jest tests using supertest\n\n## Route Design\nFor each resource:\n- Base path: /api/{resource} (pluralized, lowercase)\n- GET / -> list all (with pagination: page, limit, sort query params)\n- GET /:id -> get by ID\n- POST / -> create new\n- PUT /:id -> update by ID\n- DELETE /:id -> delete by ID\n- Custom routes for non-CRUD operations\n\n## Health Check\nEvery app includes a /health router in src/routers/health/:\n- health.router.ts -- GET /health returning server status\n- health.controller.ts -- Health check handler\n- health.spec.ts -- Health check tests\n\n## Route Organization\n- One router directory per resource with co-located controller and spec\n- Central src/routers/index.ts mounts all routers\n- Middleware applied per-route or per-router\n\n## Controller Mapping\n- Each route maps to a controller method in the co-located controller file\n- Controller method name follows convention: getAll, getById, create, update, delete\n\n## Validation\n- Request body validation using Zod schemas\n- Param validation (e.g. valid ObjectId)\n- Query param parsing and defaults\n\nRespond with structured route definitions. Do NOT return JSON.`;\n\nexport const routeGeneratorSubagent = defineSubagent({\n name: 'route-generator',\n description:\n 'Generates Express route definitions from API design using the co-located router pattern ({name}.router.ts, {name}.controller.ts, {name}.spec.ts). Use before generating the Express config.',\n systemPrompt: ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * middleware-configurator subagent - designs middleware stack\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT = `You are an Express.js middleware specialist. You design the complete middleware stack.\n\n## Core Middleware\n1. **CORS**: Configure allowed origins, methods, headers, credentials\n2. **Body parser**: JSON and URL-encoded body parsing with size limits\n3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)\n4. **Morgan/Logger**: Request logging with format and stream\n\n## Auth Middleware\n1. **JWT verification**: Extract token from Authorization header or cookie\n2. **Role check**: Verify user role against required roles\n3. **Resource ownership**: Check if user owns the resource they're accessing\n\n## Validation Middleware\n1. **Request validation**: Validate body, params, query using Zod schemas\n2. **Sanitization**: Strip HTML, trim whitespace\n\n## Error Handling\n1. **Not found handler**: 404 for unmatched routes\n2. **Error handler**: Centralized error response with status codes\n3. **Async wrapper**: Catch async errors without try-catch\n\n## Rate Limiting\n1. **Global**: Limit requests per IP per time window\n2. **Auth routes**: Stricter limits on login/signup\n\nRespond with structured middleware analysis. Do NOT return JSON.`;\n\nexport const middlewareConfiguratorSubagent = defineSubagent({\n name: 'middleware-configurator',\n description:\n 'Designs the Express middleware stack including auth, validation, error handling, CORS, and rate limiting. Use before generating the Express config.',\n systemPrompt: MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runExpressBuilderAgent - orchestrator for Express.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXPRESS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createExpressBuilderTools } from './tools';\nimport { routeGeneratorSubagent, middlewareConfiguratorSubagent } from './subagents';\nimport type { ExpressBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXPRESS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Express builder orchestrator. When the user provides requirements:\n\n1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.\n2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.\n3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.\n4. **Validate**: Use validate_express to check the config JSON before returning.\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.\n\nRespond with the final Express config as JSON.`;\n\n/**\n * Run the express-builder orchestrator agent.\n */\nexport async function runExpressBuilderAgent(\n config: ExpressBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExpressBuilderTools(model);\n const subagentTools = createSubagentToolSet(\n [routeGeneratorSubagent, middlewareConfiguratorSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Next.js application configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const nextjsPageSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: ciEnum(['public', 'protected']),\n routeGroup: z.string().default(''),\n purpose: z.string(),\n hasForm: z.coerce.boolean().default(false),\n formFields: z.array(z.string()).default([]),\n dataFetching: ciEnum(['server', 'client', 'hybrid']).default('server'),\n actions: z.array(z.string()).default([]),\n});\n\nexport const nextjsLayoutSchema = z.object({\n name: z.string(),\n path: z.string(),\n routeGroup: z.string().default(''),\n components: z.array(z.string()).default([]),\n purpose: z.string(),\n});\n\nexport const nextjsApiRouteSchema = z.object({\n path: z.string(),\n methods: z.array(httpMethodSchema).default([]),\n auth: z.coerce.boolean().default(true),\n description: z.string(),\n});\n\nexport const serverActionSchema = z.object({\n name: z.string(),\n module: z.string(),\n description: z.string(),\n revalidates: z.array(z.string()).default([]),\n});\n\nexport const nextjsConfigSchema = z.object({\n appName: z.string().default('app'),\n pages: z.array(nextjsPageSchema).default([]),\n layouts: z.array(nextjsLayoutSchema).default([]),\n apiRoutes: z.array(nextjsApiRouteSchema).default([]),\n serverActions: z.array(serverActionSchema).default([]),\n middleware: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n packages: z.array(z.string()).default([]),\n});\n\nexport type TNextjsConfig = z.infer<typeof nextjsConfigSchema>;\n","/**\n * System prompt for nextjs-builder orchestrator\n */\n\nexport const NEXTJS_BUILDER_SYSTEM_PROMPT = `You are an expert Next.js application architect using the App Router.\n\nYou generate production-ready Next.js configurations from frontend designs and API designs:\n- App Router file structure with route groups, layouts, pages, loading, and error boundaries\n- Server Components by default, Client Components only when interactivity is needed\n- Server Actions for mutations (form submissions, data writes)\n- API Route Handlers for external integrations, webhooks, and file uploads\n- Next.js middleware for auth guards and redirects\n- Data fetching strategy (server vs client vs hybrid per page)\n- Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Next.js config generation\n */\n\nexport const DESIGN_NEXTJS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate a Next.js App Router application configuration. Include:\n\n1. Pages: app router pages with path, name, access level, route group, purpose, data fetching strategy.\n2. Layouts: shared layouts with route groups (e.g. (auth), (dashboard)), components they include.\n3. API Routes: route handlers with path, HTTP methods, auth requirement, description.\n4. Server Actions: named actions with module, description, and paths they revalidate.\n5. Middleware: list of middleware behaviors (e.g. \"redirect unauthenticated to /login\").\n6. Env vars: NEXTAUTH_SECRET, DATABASE_URL, etc.\n7. Packages: recommended npm packages.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-app\",\n \"pages\": [{\n \"path\": \"/dashboard\",\n \"name\": \"Dashboard\",\n \"access\": \"protected\",\n \"routeGroup\": \"(dashboard)\",\n \"purpose\": \"Main dashboard with stats\",\n \"hasForm\": false,\n \"formFields\": [],\n \"dataFetching\": \"server\",\n \"actions\": []\n }],\n \"layouts\": [{\n \"name\": \"DashboardLayout\",\n \"path\": \"app/(dashboard)/layout.tsx\",\n \"routeGroup\": \"(dashboard)\",\n \"components\": [\"Sidebar\", \"Header\"],\n \"purpose\": \"Shared layout for authenticated pages\"\n }],\n \"apiRoutes\": [{\n \"path\": \"/api/users\",\n \"methods\": [\"GET\", \"POST\"],\n \"auth\": true,\n \"description\": \"User CRUD endpoints\"\n }],\n \"serverActions\": [{\n \"name\": \"createUser\",\n \"module\": \"users\",\n \"description\": \"Create a new user\",\n \"revalidates\": [\"/dashboard/users\"]\n }],\n \"middleware\": [\"Redirect unauthenticated users to /login\"],\n \"envVars\": [\"DATABASE_URL\", \"NEXTAUTH_SECRET\"],\n \"packages\": [\"next-auth\", \"prisma\", \"@prisma/client\", \"tailwindcss\"]\n}`;\n\nexport function buildDesignNextjsPrompt(requirement: string): string {\n return DESIGN_NEXTJS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_nextjs tool - validates JSON against nextjsConfigSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { nextjsConfigSchema } from '../schemas';\n\nexport const validateNextjsTool = defineTool({\n name: 'validate_nextjs',\n description:\n 'Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.',\n input: z.object({\n config: z.string().describe('JSON string of the Next.js config to validate'),\n }),\n handler: async ({ config }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(config) as unknown;\n nextjsConfigSchema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n});\n","/**\n * generate_nextjs tool - generates Next.js config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { nextjsConfigSchema, type TNextjsConfig } from '../schemas';\nimport { buildDesignNextjsPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_nextjs tool for Next.js config generation.\n */\nexport function createGenerateNextjsTool(model: Model) {\n return defineTool({\n name: 'generate_nextjs',\n description:\n 'Generate a complete Next.js App Router configuration from frontend design and requirements. Returns pages, layouts, API routes, server actions, and middleware as JSON.',\n input: z.object({\n requirement: z.string().describe('Frontend design, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TNextjsConfig> => {\n const userPrompt = buildDesignNextjsPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a Next.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, nextjsConfigSchema);\n },\n });\n}\n","/**\n * nextjs-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateNextjsTool } from './validate-nextjs';\nimport { createGenerateNextjsTool } from './generate-nextjs';\n\nexport { validateNextjsTool } from './validate-nextjs';\nexport { createGenerateNextjsTool } from './generate-nextjs';\n\n/**\n * Create all nextjs-builder tools. Pass the model for AI-backed tools.\n */\nexport function createNextjsBuilderTools(model: Model) {\n return createToolSet({\n validate_nextjs: validateNextjsTool,\n generate_nextjs: createGenerateNextjsTool(model),\n });\n}\n","/**\n * route-planner subagent - plans Next.js App Router file structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_PLANNER_SYSTEM_PROMPT = `You are a Next.js App Router specialist. Given page specs, you plan the file structure.\n\n## Route Groups\n- (auth) for public auth pages: login, signup, forgot-password\n- (dashboard) or (app) for protected pages\n- (marketing) for public landing pages\n\n## File Structure Per Route\n- page.tsx: the page component (Server Component by default)\n- layout.tsx: shared layout for the route group\n- loading.tsx: Suspense fallback\n- error.tsx: error boundary (must be Client Component)\n- not-found.tsx: 404 page\n\n## Data Fetching\n- Server Components: fetch data directly in the component (async function)\n- Client Components: use SWR or React Query for client-side fetching\n- Server Actions: for form submissions and mutations\n\n## Conventions\n- Use lowercase kebab-case for route segments\n- Dynamic segments: [id], [slug]\n- Catch-all: [...slug]\n- Parallel routes: @modal, @sidebar\n- Intercepting routes: (.)photo, (..)details\n\nRespond with the full file tree and route structure. Do NOT return JSON.`;\n\nexport const routePlannerSubagent = defineSubagent({\n name: 'route-planner',\n description:\n 'Plans Next.js App Router file structure with route groups, layouts, and page files. Use before generating the Next.js config.',\n systemPrompt: ROUTE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * api-route-generator subagent - generates Next.js API routes and server actions\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst API_ROUTE_GENERATOR_SYSTEM_PROMPT = `You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.\n\n## API Route Handlers (app/api/)\nFor external integrations, webhooks, and file uploads:\n- One route.ts file per resource: app/api/[resource]/route.ts\n- Export named functions: GET, POST, PUT, DELETE\n- Use NextRequest and NextResponse\n- Add auth checks using next-auth getServerSession\n\n## Server Actions (preferred for mutations)\nFor form submissions and data writes:\n- Define in separate files: app/actions/[module].ts\n- Use 'use server' directive\n- Use revalidatePath or revalidateTag after mutations\n- Return typed results with error handling\n\n## When to Use Which\n- Server Actions: form submissions, data CRUD, anything triggered by user action\n- API Routes: webhooks from external services, file uploads, OAuth callbacks, public APIs\n\n## Auth Integration\n- API Routes: check session with getServerSession\n- Server Actions: check session at the start of each action\n- Middleware: protect route groups with matcher patterns\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const apiRouteGeneratorSubagent = defineSubagent({\n name: 'api-route-generator',\n description:\n 'Generates Next.js API route handlers and server actions from API design. Use after route planning.',\n systemPrompt: API_ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runNextjsBuilderAgent - orchestrator for Next.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { NEXTJS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createNextjsBuilderTools } from './tools';\nimport { routePlannerSubagent, apiRouteGeneratorSubagent } from './subagents';\nimport type { NextjsBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${NEXTJS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Next.js builder orchestrator. When the user provides requirements:\n\n1. **Plan routes**: Use subagent_route-planner to design the App Router file structure with route groups and layouts.\n2. **Generate API routes**: Use subagent_api-route-generator to design API route handlers and server actions.\n3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.\n4. **Validate**: Use validate_nextjs to check the config JSON before returning.\n\nRespond with the final Next.js config as JSON.`;\n\n/**\n * Run the nextjs-builder orchestrator agent.\n */\nexport async function runNextjsBuilderAgent(\n config: NextjsBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createNextjsBuilderTools(model);\n const subagentTools = createSubagentToolSet([routePlannerSubagent, apiRouteGeneratorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/utils/errors.ts","../src/lib/utils/json-parse.ts","../src/lib/utils/logger.ts","../src/lib/utils/utils.ts","../src/lib/tools/tools.ts","../src/lib/tools/validation-factory.ts","../src/lib/agents/agent-observers.ts","../src/lib/agents/agent.ts","../src/lib/models/providers/base.ts","../src/lib/models/providers/openai.ts","../src/lib/models/providers/anthropic.ts","../src/lib/models/providers/google.ts","../src/lib/models/create-model.ts","../src/lib/subagents/subagent.ts","../src/lib/template-engine/compiler.ts","../src/lib/mcp/transports.ts","../src/lib/mcp/client.ts","../src/modules/hello-world/tool.ts","../src/modules/hello-world/agent.ts","../src/modules/react-builder/schemas/branding.schema.ts","../src/modules/react-builder/schemas/app-config.schema.ts","../src/modules/react-builder/schemas/field.schema.ts","../src/modules/react-builder/schemas/page.schema.ts","../src/modules/react-builder/schemas/application.schema.ts","../src/modules/react-builder/schemas/user.schema.ts","../src/modules/react-builder/prompts/system.prompt.ts","../src/modules/react-builder/prompts/instruction.prompt.ts","../src/modules/react-builder/prompts/examples.prompt.ts","../src/modules/react-builder/prompts/feedback.prompt.ts","../src/modules/react-builder/tools/validate-frontend-config.tool.ts","../src/modules/react-builder/tools/generate-frontend.tool.ts","../src/modules/react-builder/tools/generate-feature-breakdown.tool.ts","../src/modules/react-builder/tools/scaffold-vite.ts","../src/modules/react-builder/tools/index.ts","../src/modules/react-builder/subagents/graphql-analyzer.subagent.ts","../src/modules/react-builder/subagents/config-validator.subagent.ts","../src/modules/react-builder/agent.ts","../src/modules/requirement-gatherer/schemas/actor.schema.ts","../src/modules/requirement-gatherer/schemas/flow.schema.ts","../src/modules/requirement-gatherer/schemas/story.schema.ts","../src/modules/requirement-gatherer/schemas/module.schema.ts","../src/modules/requirement-gatherer/schemas/database.schema.ts","../src/modules/requirement-gatherer/schemas/context.schema.ts","../src/modules/requirement-gatherer/schemas/requirement.schema.ts","../src/modules/requirement-gatherer/prompts/system.prompt.ts","../src/modules/requirement-gatherer/prompts/discovery.prompt.ts","../src/modules/requirement-gatherer/prompts/requirements.prompt.ts","../src/modules/requirement-gatherer/prompts/design.prompt.ts","../src/modules/requirement-gatherer/prompts/synthesis.prompt.ts","../src/modules/requirement-gatherer/context.ts","../src/modules/requirement-gatherer/stages/base.ts","../src/modules/requirement-gatherer/stages/discovery.stage.ts","../src/modules/requirement-gatherer/stages/requirements-invoke.ts","../src/modules/requirement-gatherer/stages/requirements.stage.ts","../src/modules/requirement-gatherer/stages/design.stage.ts","../src/modules/requirement-gatherer/stages/synthesis.stage.ts","../src/modules/requirement-gatherer/stages/discovery.state.ts","../src/modules/requirement-gatherer/stages/requirements.state.ts","../src/modules/requirement-gatherer/stages/design.state.ts","../src/modules/requirement-gatherer/stages/synthesis.state.ts","../src/modules/requirement-gatherer/stages/state-registry.ts","../src/modules/requirement-gatherer/router.ts","../src/modules/requirement-gatherer/chat.ts","../src/modules/requirement-gatherer/agent.ts","../src/modules/requirement-gatherer/context-builder.ts","../src/modules/planning/context.ts","../src/modules/planning/stages/base.ts","../src/modules/planning/prompts/system.prompt.ts","../src/modules/planning/prompts/discovery.prompt.ts","../src/modules/planning/prompts/requirements.prompt.ts","../src/modules/planning/prompts/design.prompt.ts","../src/modules/planning/prompts/synthesis.prompt.ts","../src/modules/planning/prompts/edit.prompt.ts","../src/modules/planning/stages/discovery.stage.ts","../src/modules/planning/stages/discovery.state.ts","../src/modules/data-modeler/subagents/entity-analyzer.ts","../src/modules/data-modeler/subagents/relationship-mapper.ts","../src/modules/data-modeler/subagents/schema-refiner.ts","../src/modules/frontend-architect/subagents/page-planner.ts","../src/modules/frontend-architect/subagents/component-analyzer.ts","../src/modules/frontend-architect/subagents/framework-selector.ts","../src/modules/auth-designer/subagents/security-analyzer.ts","../src/modules/auth-designer/subagents/flow-designer.ts","../src/modules/planning/stages/requirements.stage.ts","../src/modules/planning/stages/requirements.state.ts","../src/modules/api-designer/subagents/endpoint-analyzer.ts","../src/modules/api-designer/subagents/contract-designer.ts","../src/modules/planning/stages/design.stage.ts","../src/modules/planning/stages/design.state.ts","../src/modules/planning/writer.ts","../src/modules/execution-planner/subagents/edge-case-analyzer.ts","../src/modules/execution-planner/subagents/testing-strategist.ts","../src/modules/planning/stages/synthesis.stage.ts","../src/modules/planning/stages/synthesis.state.ts","../src/modules/planning/stages/state-registry.ts","../src/modules/planning/router.ts","../src/modules/planning/chat.ts","../src/modules/planning/agent.ts","../src/modules/planning/edit-agent.ts","../src/modules/planning/from-requirements.ts","../src/modules/planning/context-builder.ts","../src/modules/data-modeler/schemas/data-model.schema.ts","../src/modules/data-modeler/schemas/mongodb-field.schema.ts","../src/modules/data-modeler/schemas/mongodb-module.schema.ts","../src/modules/data-modeler/schemas/mongodb-project.schema.ts","../src/modules/data-modeler/prompts/system.prompt.ts","../src/modules/data-modeler/prompts/design.prompt.ts","../src/modules/data-modeler/prompts/pro-design.prompt.ts","../src/modules/data-modeler/prompts/mongodb-system.prompt.ts","../src/modules/data-modeler/prompts/mongodb-formatters.ts","../src/modules/data-modeler/prompts/mongodb-design.prompt.ts","../src/modules/data-modeler/prompts/mongodb-redesign.prompt.ts","../src/modules/data-modeler/tools/validate-schema.ts","../src/modules/data-modeler/tools/design-schema.ts","../src/modules/data-modeler/tools/design-schema-pro.ts","../src/modules/data-modeler/tools/refine-schema.ts","../src/modules/data-modeler/tools/validate-mongodb.ts","../src/modules/data-modeler/tools/design-mongodb.ts","../src/modules/data-modeler/tools/design-mongodb-pro.ts","../src/modules/data-modeler/tools/redesign-mongodb.ts","../src/modules/data-modeler/tools/index.ts","../src/modules/data-modeler/agent.ts","../src/modules/data-modeler/mongodb-agent.ts","../src/modules/api-designer/schemas/api-design.schema.ts","../src/modules/api-designer/prompts/system.prompt.ts","../src/modules/api-designer/prompts/design.prompt.ts","../src/modules/api-designer/tools/validate-api.ts","../src/modules/api-designer/tools/design-api.ts","../src/modules/api-designer/tools/design-api-pro.ts","../src/modules/api-designer/tools/index.ts","../src/modules/api-designer/agent.ts","../src/modules/auth-designer/schemas/auth-design.schema.ts","../src/modules/auth-designer/prompts/system.prompt.ts","../src/modules/auth-designer/prompts/design.prompt.ts","../src/modules/auth-designer/tools/validate-auth.ts","../src/modules/auth-designer/tools/design-auth.ts","../src/modules/auth-designer/tools/index.ts","../src/modules/auth-designer/agent.ts","../src/modules/frontend-architect/schemas/frontend-design.schema.ts","../src/modules/frontend-architect/prompts/system.prompt.ts","../src/modules/frontend-architect/prompts/design.prompt.ts","../src/modules/frontend-architect/tools/validate-frontend.ts","../src/modules/frontend-architect/tools/design-frontend.ts","../src/modules/frontend-architect/tools/index.ts","../src/modules/frontend-architect/agent.ts","../src/modules/execution-planner/schemas/execution-plan.schema.ts","../src/modules/execution-planner/prompts/system.prompt.ts","../src/modules/execution-planner/prompts/design.prompt.ts","../src/modules/execution-planner/tools/validate-plan.ts","../src/modules/execution-planner/tools/create-plan.ts","../src/modules/execution-planner/tools/index.ts","../src/modules/execution-planner/agent.ts","../src/modules/backend-architect/schemas/backend-design.schema.ts","../src/modules/backend-architect/prompts/system.prompt.ts","../src/modules/backend-architect/prompts/design.prompt.ts","../src/modules/backend-architect/tools/validate-backend.ts","../src/modules/backend-architect/tools/design-backend.ts","../src/modules/backend-architect/tools/index.ts","../src/modules/backend-architect/subagents/service-planner.ts","../src/modules/backend-architect/subagents/framework-selector.ts","../src/modules/backend-architect/agent.ts","../src/modules/apollo-builder/schemas/subgraph-config.schema.ts","../src/modules/apollo-builder/prompts/system.prompt.ts","../src/modules/apollo-builder/prompts/design.prompt.ts","../src/modules/apollo-builder/tools/validate-subgraph.ts","../src/modules/apollo-builder/tools/generate-subgraph.ts","../src/modules/apollo-builder/tools/scaffold-subgraph.ts","../src/modules/apollo-builder/tools/index.ts","../src/modules/apollo-builder/subagents/schema-generator.ts","../src/modules/apollo-builder/subagents/resolver-planner.ts","../src/modules/apollo-builder/agent.ts","../src/modules/express-builder/schemas/express-config.schema.ts","../src/modules/express-builder/prompts/system.prompt.ts","../src/modules/express-builder/prompts/design.prompt.ts","../src/modules/express-builder/tools/validate-express.ts","../src/modules/express-builder/tools/generate-express.ts","../src/modules/express-builder/tools/scaffold-express.ts","../src/modules/express-builder/tools/index.ts","../src/modules/express-builder/subagents/route-generator.ts","../src/modules/express-builder/subagents/middleware-configurator.ts","../src/modules/express-builder/agent.ts","../src/modules/nextjs-builder/schemas/nextjs-config.schema.ts","../src/modules/nextjs-builder/prompts/system.prompt.ts","../src/modules/nextjs-builder/prompts/design.prompt.ts","../src/modules/nextjs-builder/tools/validate-nextjs.ts","../src/modules/nextjs-builder/tools/generate-nextjs.ts","../src/modules/nextjs-builder/tools/index.ts","../src/modules/nextjs-builder/subagents/route-planner.ts","../src/modules/nextjs-builder/subagents/api-route-generator.ts","../src/modules/nextjs-builder/agent.ts"],"names":["LibraryError","message","cause","ModelError","provider","ToolError","toolName","ValidationError","errors","AgentError","iteration","SubagentError","subagentName","extractJson","text","trimmed","codeBlock","parseModelJsonResponse","schema","jsonStr","parsed","err","preview","result","issues","i","safeJsonParse","label","NOOP_LOGGER","createLogger","config","name","level","pretty","file","stream","destination","streamFd","pinoLogger","pino","targets","transport","wrapPino","loggerConfigFromEnv","overrides","raw","enabledRaw","enabled","levelRaw","streamRaw","prettyRaw","p","msg","data","bindings","emptyDetails","emptyOutputDetails","sumTokenUsage","usages","inputTokens","outputTokens","totalTokens","usage","defineTool","description","inputSchema","handler","tool","args","e","createToolSet","tools","getTools","toolSet","getTool","executeTool","toolImpl","input","options","logger","out","executeToolByName","createValidationTool","inputParamName","z","notifyObserversStep","observers","step","notifyObserversTool","o","notifyObserversError","error","runAgent","model","systemPrompt","maxIterations","onStep","messages","steps","response","s","tc","assistantContent","toolResults","toolCall","execResult","agentResult","outputVal","createAIModel","params","modelName","getModel","schemaOnlyTools","t","_execute","rest","generateText","toolCalls","prompt","images","content","img","schemaWrapped","zodSchema","generateObject","createOpenAIModel","apiKey","baseUrl","createOpenAI","createAnthropicModel","createAnthropic","createGoogleModel","createGoogleGenerativeAI","createModel","NAME_REGEX","defineSubagent","resolveTools","definition","parentTools","base","disallowed","filtered","key","runSubagent","parentModel","createSubagentTool","createSubagentToolSet","definitions","def","compileTemplate","template","context","Handlebars","findHbsFiles","dir","results","X","entries","entry","fullPath","ie","toOutputPath","hbsRelPath","shouldSkip","relativePath","skipPatterns","pattern","scaffoldProject","templateDir","outputDir","hbsFiles","files","hbsFile","outputRelPath","inputPath","outputPath","templateSource","compiled","registerHelpers","a","b","obj","str","_","c","getSdkRoot","createRequire","path","sdkRoot","parseToolResult","first","createHttpTransport","url","headers","modPath","mod","pathToFileURL","requestInit","createStdioTransport","command","BaseMcpClient","info","resolveOpts","envPrefix","serverLabel","apiKeyHeader","argsEnv","client","Client","helloWorldTool","DEFAULT_SYSTEM_PROMPT","runHelloWorldAgent","modelConfig","BrandingSchema","AppConfigSchema","ValidationSchema","FieldOptionsSchema","FormFieldSchema","ColumnSchema","ApiResponseTypeSchema","ListingPageApiSchema","AuthPageApiSchema","DrawerSchema","AuthPageSchema","ListingPageSchema","PageSchema","ModuleSchema","ApplicationSchema","LoginInputSchema","SpecializationSchema","UserSchema","CreateUserInputSchema","UpdateUserInputSchema","ForgotPasswordSchema","ResetPasswordSchema","REACT_BUILDER_SYSTEM_PROMPT","REACT_BUILDER_INSTRUCTION","buildInstructionPrompt","EXAMPLE_GRAPHQL_SCHEMA","EXAMPLE_JSON_OUTPUT","buildExampleShotPrompt","buildFeedbackPrompt","userFeedback","schemaFile","validateFrontendConfigTool","buildGeneratePrompt","graphqlSchema","appInfo","instruction","example","appInfoBlock","createGenerateFrontendTool","userPrompt","createGenerateFeatureBreakdownTool","toTemplateContext","m","scaffoldViteTool","Yn","createReactBuilderTools","GRAPHQL_ANALYZER_SYSTEM_PROMPT","graphqlAnalyzerSubagent","CONFIG_VALIDATOR_SYSTEM_PROMPT","createConfigValidatorSubagent","ORCHESTRATOR_SYSTEM_PROMPT","runReactBuilderAgent","reactTools","configValidator","subagentTools","actorSchema","actorsResultSchema","flowSchema","flowsResultSchema","storySchema","storiesResultSchema","crudApiSchema","extractedModuleSchema","modulesResultSchema","entityFieldSchema","entityIndexSchema","entityRelationSchema","databaseEntitySchema","databaseDesignSchema","projectBriefSchema","questionSchema","chatEntrySchema","requirementContextSchema","requirementSummarySchema","finalRequirementSchema","REQUIREMENT_GATHERER_SYSTEM_PROMPT","DISCOVERY_SYSTEM_FRAGMENT","DISCOVERY_USER_PROMPT","buildDiscoveryPrompt","userMessage","history","PROJECT_BLOCK","EXTRACT_ACTORS_PROMPT","GENERATE_FLOWS_PROMPT","GENERATE_STORIES_PROMPT","EXTRACT_MODULES_PROMPT","buildExtractActorsPrompt","projectName","projectGoal","projectFeatures","buildGenerateFlowsPrompt","actorsJson","buildGenerateStoriesPrompt","flowsJson","buildExtractModulesPrompt","storiesJson","DESIGN_DB_PROMPT","DESIGN_DATABASE_SYSTEM_PROMPT","buildDesignDatabasePrompt","projectBrief","modules","stories","SYNTHESIS_SYSTEM_FRAGMENT","SYNTHESIS_USER_PROMPT","buildSynthesisPrompt","actors","flows","database","createInitialContext","mergeStageResult","addChatEntry","role","advanceStage","order","idx","next","summarizeModules","summarizeStories","safeParseJson","runDiscoveryStage","needsClarification","questions","q","validated","pb","getActors","_logger","getFlows","_actors","getStories","_flows","getModules","_stories","runRequirementsStage","_userMessage","brief","runDesignStage","projectBriefStr","modulesSummary","storiesSummary","dbPrompt","dbMessages","dbResponse","dbJsonStr","dbParsed","databaseResult","runSynthesisStage","finalRequirement","DiscoveryState","RequirementsState","DesignState","SynthesisState","states","getStateForStage","stage","runStage","merged","finalReq","STAGE_ORDER","processRequirementChat","ctx","runOne","runResult","nextStage","MAX_TURNS","runRequirementGathererAgent","lastResult","turns","output","DEFAULT_STAGE","RequirementContextBuilder","pendingQuestions","createRequirementContextBuilder","EMPTY_SECTIONS","newSections","projectDescription","sections","v","isConfirmation","normalized","PLANNING_SYSTEM_PROMPT","CONTEXT_BLOCK","REQUIREMENTS_OVERVIEW_PROMPT","REQUIREMENTS_FEATURE_DATA_PROMPT","buildRequirementsOverviewPrompt","buildRequirementsFeatureDataPrompt","overviewAndTechStack","DESIGN_CONTEXT","DESIGN_IMPLEMENTATION_PROMPT","buildDesignImplementationPrompt","priorSections","apiRoutes","SYNTHESIS_CONTEXT","EDIT_PLAN_SYSTEM_PROMPT","buildEditPlanPrompt","existingPlan","feedback","hasProjectOverview","lower","hasOverview","userConfirmed","forceAdvance","advance","storeDescription","ENTITY_ANALYZER_SYSTEM_PROMPT","entityAnalyzerSubagent","RELATIONSHIP_MAPPER_SYSTEM_PROMPT","relationshipMapperSubagent","SCHEMA_REFINER_SYSTEM_PROMPT","createSchemaRefinerSubagent","PAGE_PLANNER_SYSTEM_PROMPT","pagePlannerSubagent","COMPONENT_ANALYZER_SYSTEM_PROMPT","componentAnalyzerSubagent","FRAMEWORK_SELECTOR_SYSTEM_PROMPT","frameworkSelectorSubagent","SECURITY_ANALYZER_SYSTEM_PROMPT","securityAnalyzerSubagent","FLOW_DESIGNER_SYSTEM_PROMPT","flowDesignerSubagent","invokeMarkdown","r","splitOverviewAndTechStack","splitFeatureDecisionsAndDataModels","part1","overview","techStack","part2","featureDecisions","dataModels","priorContext","pagesAndRoutes","fullContext","authFlow","ENDPOINT_ANALYZER_SYSTEM_PROMPT","endpointAnalyzerSubagent","CONTRACT_DESIGNER_SYSTEM_PROMPT","contractDesignerSubagent","gatherPriorSections","parts","contractResult","implementation","assemblePlan","writePlanToFile","markdown","writeFile","EDGE_CASE_ANALYZER_SYSTEM_PROMPT","edgeCaseAnalyzerSubagent","TESTING_STRATEGIST_SYSTEM_PROMPT","testingStrategistSubagent","gatherAllSections","extractProjectName","firstLine","match","executionPlan","edgeCases","testingChecklist","fullSections","fullMarkdown","processPlanningChat","planMarkdown","runPlanningAgent","continueMsg","editPlan","revised","formatEntityFields","entity","f","flags","formatDatabaseAsMarkdown","db","header","entities","fields","relParts","relations","idxParts","indexes","formatModulesAsMarkdown","apis","formatProjectOverview","req","features","formatTechStack","formatActorsContext","actor","actorFlows","convertRequirementToContext","runPlanningFromRequirements","requirement","triggerMsg","PlanningContextBuilder","createPlanningContextBuilder","relationTypeSchema","n","dataEntitySchema","issue","dbTypeSchema","dataModelDesignSchema","mongoFieldSchema","mongoModuleSchema","mongoProjectSchema","DATA_MODELER_SYSTEM_PROMPT","DESIGN_SCHEMA_PROMPT","REFINE_SCHEMA_PROMPT","buildDesignSchemaPrompt","buildRefineSchemaPrompt","existingSchema","PRO_DESIGN_PROMPT","buildProDesignPrompt","databaseType","MONGODB_SYSTEM_PROMPT","formatUserTypes","goals","g","formatUserFlows","flow","formatUserStories","byFlow","arr","flowStories","story","pre","post","d","orphans","formatTechnicalRequirements","tech","lines","extractDataEntities","extractRoles","buildPromptVariables","createMongoDesignPrompt","createMongoProDesignPrompt","vars","createMongoRedesignPrompt","validateSchemaTool","createDesignSchemaTool","createDesignSchemaProTool","createRefineSchemaTools","validateMongoSchemaTool","createDesignDatabaseTool","structuredInputSchema","createDesignDatabaseProTool","dbDesign","metadata","createRedesignDatabaseTool","createDataModelerTools","createDbDesignerTools","runDataModelerAgent","schemaRefiner","allTools","runDbDesignerAgent","dbTools","httpMethodSchema","stringRecordSchema","k","stringOrObjectArraySchema","restEndpointSchema","graphqlOperationSchema","apiStyleSchema","apiDesignSchema","API_DESIGNER_SYSTEM_PROMPT","DESIGN_API_PROMPT","PRO_DESIGN_API_PROMPT","buildDesignApiPrompt","buildProDesignApiPrompt","apiStyle","dataModel","validateApiTool","createDesignApiTool","createDesignApiProTool","createApiDesignerTools","runApiDesignerAgent","authFlowStepSchema","authFlowSchema","authMiddlewareSchema","roleDefinitionSchema","securityPolicySchema","authDesignSchema","AUTH_DESIGNER_SYSTEM_PROMPT","DESIGN_AUTH_PROMPT","buildDesignAuthPrompt","validateAuthTool","createDesignAuthTool","createAuthDesignerTools","runAuthDesignerAgent","formFieldSchema","pageDesignSchema","componentDesignSchema","frontendDesignSchema","FRONTEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_FRONTEND_PROMPT","buildDesignFrontendPrompt","validateFrontendTool","createDesignFrontendTool","createFrontendArchitectTools","reactBuilderSubagent","nextjsBuilderSubagent","runFrontendArchitectAgent","phaseStepSchema","implementationPhaseSchema","edgeCaseSchema","testChecklistItemSchema","executionPlanSchema","EXECUTION_PLANNER_SYSTEM_PROMPT","CREATE_EXECUTION_PLAN_PROMPT","buildCreateExecutionPlanPrompt","validateExecutionPlanTool","createExecutionPlanTool","createExecutionPlannerTools","runExecutionPlannerAgent","ciEnum","values","middlewareSchema","serviceSchema","routeGroupSchema","backendDesignSchema","BACKEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_BACKEND_PROMPT","buildDesignBackendPrompt","validateBackendTool","createDesignBackendTool","createBackendArchitectTools","SERVICE_PLANNER_SYSTEM_PROMPT","servicePlannerSubagent","runBackendArchitectAgent","graphqlFieldSchema","graphqlTypeSchema","resolverOperationSchema","subgraphModuleSchema","subgraphConfigSchema","APOLLO_BUILDER_SYSTEM_PROMPT","DESIGN_SUBGRAPH_PROMPT","buildDesignSubgraphPrompt","validateSubgraphTool","createGenerateSubgraphTool","scaffoldSubgraphTool","da","createApolloBuilderTools","SCHEMA_GENERATOR_SYSTEM_PROMPT","schemaGeneratorSubagent","RESOLVER_PLANNER_SYSTEM_PROMPT","resolverPlannerSubagent","runApolloBuilderAgent","routerMethodSchema","routerSchema","modelFieldSchema","modelSchema","middlewareConfigSchema","expressConfigSchema","EXPRESS_BUILDER_SYSTEM_PROMPT","DESIGN_EXPRESS_PROMPT","buildDesignExpressPrompt","validateExpressTool","createGenerateExpressTool","scaffoldExpressTool","ba","createExpressBuilderTools","ROUTE_GENERATOR_SYSTEM_PROMPT","routeGeneratorSubagent","MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT","middlewareConfiguratorSubagent","runExpressBuilderAgent","nextjsPageSchema","nextjsLayoutSchema","nextjsApiRouteSchema","serverActionSchema","nextjsConfigSchema","NEXTJS_BUILDER_SYSTEM_PROMPT","DESIGN_NEXTJS_PROMPT","buildDesignNextjsPrompt","validateNextjsTool","createGenerateNextjsTool","createNextjsBuilderTools","ROUTE_PLANNER_SYSTEM_PROMPT","routePlannerSubagent","API_ROUTE_GENERATOR_SYSTEM_PROMPT","apiRouteGeneratorSubagent","runNextjsBuilderAgent"],"mappings":"mgCAOO,IAAMA,EAAAA,CAAN,cAA2B,KAAM,CACtC,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAe,CAC1C,KAAA,CAAMD,CAAAA,CAASC,CAAAA,GAAU,MAAA,CAAY,MAAA,CAAY,CAAE,KAAA,CAAAA,CAAM,CAAC,CAAA,CAC1D,IAAA,CAAK,IAAA,CAAO,cAAA,CACRA,CAAAA,EAAO,KAAA,GACT,IAAA,CAAK,KAAA,CAAQ,CAAA,EAAG,IAAA,CAAK,KAAK;AAAA,WAAA,EAAgBA,CAAAA,CAAM,KAAK,CAAA,CAAA,EAEzD,CACF,EAKaC,EAAAA,CAAN,cAAyBH,EAAa,CAC3C,WAAA,CACEC,CAAAA,CACgBG,EAChBF,CAAAA,CACA,CACA,MAAMD,CAAAA,CAASC,CAAK,EAHJ,IAAA,CAAA,QAAA,CAAAE,CAAAA,CAIhB,IAAA,CAAK,IAAA,CAAO,aACd,CACF,EAKaC,CAAAA,CAAN,cAAwBL,EAAa,CAC1C,WAAA,CACEC,EACgBK,CAAAA,CAChBJ,CAAAA,CACA,CACA,KAAA,CAAMD,CAAAA,CAASC,CAAK,EAHJ,IAAA,CAAA,QAAA,CAAAI,CAAAA,CAIhB,IAAA,CAAK,IAAA,CAAO,YACd,CACF,EAKaC,EAAAA,CAAN,cAA8BP,EA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,EAAAA,CAAyBllB,CAAK,CAAA,CACtC8K,CAAAA,CAAgBzH,CAAAA,CAAsB,CAAC+hB,EAAAA,CAAsBE,EAAyB,CAAA,CAAG,CAC7F,YAAatlB,CACf,CAAC,CAAA,CACKud,CAAAA,CAAyB,CAAE,GAAG7e,CAAAA,CAAO,GAAGoM,CAAc,CAAA,CAE5D,OAAO/K,CAAAA,CAAS,CACd,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAOud,CAAAA,CACP,aAAc7S,EAAAA,CACd,KAAA,CAAA1L,CAAAA,CACA,aAAA,CAAAkB,EACA,MAAA,CAAAC,CAAAA,CACA,MAAA,CAAAjB,CACF,CAAC,CACH","file":"index.cjs","sourcesContent":["/**\n * Custom error classes for the library\n */\n\n/**\n * Base error class for all library errors\n */\nexport class LibraryError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'LibraryError';\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n}\n\n/**\n * Error thrown when model operations fail\n */\nexport class ModelError extends LibraryError {\n constructor(\n message: string,\n public readonly provider?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ModelError';\n }\n}\n\n/**\n * Error thrown when tool execution fails\n */\nexport class ToolError extends LibraryError {\n constructor(\n message: string,\n public readonly toolName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ToolError';\n }\n}\n\n/**\n * Error thrown when tool input validation fails\n */\nexport class ValidationError extends LibraryError {\n constructor(\n message: string,\n public readonly errors?: unknown[]\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Error thrown when agent execution fails\n */\nexport class AgentError extends LibraryError {\n constructor(\n message: string,\n public readonly iteration?: number,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'AgentError';\n }\n}\n\n/**\n * Error thrown when subagent execution fails\n */\nexport class SubagentError extends LibraryError {\n constructor(\n message: string,\n public readonly subagentName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'SubagentError';\n }\n}\n","/**\n * Shared utilities for extracting and parsing JSON from model responses.\n *\n * Models frequently wrap JSON in markdown code blocks or include extra text.\n * These helpers handle extraction, parsing, and Zod validation with clear errors\n * so the agent can retry on failure.\n */\n\nimport type { z } from 'zod';\n\n/**\n * Extract a JSON string from model output.\n * Handles markdown code blocks (```json ... ``` or ``` ... ```) and bare JSON.\n */\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\n/**\n * Parse a model text response as JSON then validate with a Zod schema.\n * Throws a descriptive error on failure (JSON syntax or validation) so the\n * wrapping ToolError gives the agent enough context to retry.\n */\nexport function parseModelJsonResponse<T>(text: string, schema: z.ZodType<T>): T {\n const jsonStr = extractJson(text);\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonStr);\n } catch (err) {\n const preview = jsonStr.length > 300 ? jsonStr.slice(0, 300) + '...' : jsonStr;\n throw new Error(\n `Failed to parse model response as JSON: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n const result = schema.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues\n .slice(0, 5)\n .map(i => ` ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n throw new Error(`Model JSON does not match expected schema:\\n${issues}`);\n }\n return result.data;\n}\n\n/**\n * Parse a raw JSON string (e.g. tool input) with a descriptive error on failure.\n */\nexport function safeJsonParse(jsonStr: string, label?: string): unknown {\n try {\n return JSON.parse(jsonStr) as unknown;\n } catch (err) {\n const preview = jsonStr.length > 200 ? jsonStr.slice(0, 200) + '...' : jsonStr;\n throw new Error(\n `Invalid JSON${label ? ` for ${label}` : ''}: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n}\n","/**\n * Structured logger using Pino (JSON by default, optional pretty/file).\n * Use loggerConfigFromEnv() for .env-driven config (SWE_LOG_* vars).\n */\n\nimport pino from 'pino';\nimport type { Logger } from '../types/common';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LoggerConfig {\n /** Logger name (appears in logs) */\n name?: string;\n /** Minimum log level */\n level?: LogLevel;\n /** Use pino-pretty for readable output */\n pretty?: boolean;\n /** File path for JSON logs */\n file?: string;\n /** Console stream: stderr avoids mixing with stdout prompts (e.g. inquirer). Default: stderr when pretty, else stdout. */\n stream?: 'stdout' | 'stderr';\n /** When false, returns a no-op logger (no output). Set via SWE_LOG_ENABLED=0. */\n enabled?: boolean;\n /** Optional stream for testing (bypasses transport) */\n destination?: pino.DestinationStream;\n}\n\nconst NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n\nexport function createLogger(config: LoggerConfig = {}): Logger {\n if (config.enabled === false) {\n return NOOP_LOGGER;\n }\n\n const { name, level = 'info', pretty = false, file, stream, destination } = config;\n\n const streamFd = stream === 'stderr' ? 2 : stream === 'stdout' ? 1 : pretty ? 2 : 1;\n\n let pinoLogger: pino.Logger;\n\n if (destination) {\n pinoLogger = pino({ name, level }, destination);\n } else {\n const targets: pino.TransportTargetOptions[] = [];\n\n if (pretty) {\n targets.push({\n target: 'pino-pretty',\n options: {\n colorize: true,\n destination: streamFd,\n singleLine: true,\n ignore: 'time,pid,hostname',\n translateTime: false,\n },\n level,\n });\n } else {\n targets.push({\n target: 'pino/file',\n options: { destination: streamFd },\n level,\n });\n }\n\n if (file) {\n targets.push({\n target: 'pino/file',\n options: { destination: file, mkdir: true },\n level,\n });\n }\n\n const transport = pino.transport({ targets }) as pino.DestinationStream;\n pinoLogger = pino({ name, level }, transport);\n }\n\n return wrapPino(pinoLogger);\n}\n\n/**\n * Build logger config from process.env (SWE_* vars). Caller loads .env if desired (e.g. dotenv or `node --env-file=.env`).\n *\n * Env vars (all optional):\n * - SWE_LOG_ENABLED: 1|true|yes (default) = on; 0|false|no|disabled = off (no-op logger).\n * - SWE_LOG_LEVEL: debug|info|warn|error (default: info).\n * - SWE_LOG_STREAM: stdout|stderr; default stderr when SWE_LOG_PRETTY is true, else stdout.\n * - SWE_LOG_PRETTY: 1|true|yes = human-readable (pino-pretty); 0|false (default) = JSON.\n * - SWE_LOG_FILE: path to also write JSON logs to a file.\n * - SWE_LOG_NAME: logger name in output.\n *\n * For interactive CLIs (e.g. inquirer), use pretty and stderr so logs do not mix with stdout prompts.\n */\nexport function loggerConfigFromEnv(overrides: Partial<LoggerConfig> = {}): LoggerConfig {\n const raw = process.env;\n const enabledRaw = (raw.SWE_LOG_ENABLED ?? 'true').trim().toLowerCase();\n const enabled =\n enabledRaw !== '0' &&\n enabledRaw !== 'false' &&\n enabledRaw !== 'no' &&\n enabledRaw !== 'disabled';\n\n const levelRaw = (raw.SWE_LOG_LEVEL ?? 'info').trim().toLowerCase();\n const level: LogLevel =\n levelRaw === 'debug' || levelRaw === 'info' || levelRaw === 'warn' || levelRaw === 'error'\n ? levelRaw\n : 'info';\n\n const streamRaw = (raw.SWE_LOG_STREAM ?? '').trim().toLowerCase();\n const prettyRaw = (raw.SWE_LOG_PRETTY ?? '0').trim().toLowerCase();\n const pretty = prettyRaw === '1' || prettyRaw === 'true' || prettyRaw === 'yes';\n const stream: 'stdout' | 'stderr' =\n streamRaw === 'stdout'\n ? 'stdout'\n : streamRaw === 'stderr'\n ? 'stderr'\n : pretty\n ? 'stderr'\n : 'stdout';\n\n const file = raw.SWE_LOG_FILE?.trim() || undefined;\n const name = raw.SWE_LOG_NAME?.trim() || undefined;\n\n return {\n enabled,\n level,\n stream,\n pretty,\n ...(file && { file }),\n ...(name && { name }),\n ...overrides,\n };\n}\n\nfunction wrapPino(p: pino.Logger): Logger {\n return {\n debug: (msg, data) => {\n p.debug(data ?? {}, msg);\n },\n info: (msg, data) => {\n p.info(data ?? {}, msg);\n },\n warn: (msg, data) => {\n p.warn(data ?? {}, msg);\n },\n error: (msg, err) => {\n if (err instanceof Error) {\n p.error({ err }, msg);\n } else {\n p.error(err ?? {}, msg);\n }\n },\n child: (bindings: Record<string, unknown>) => wrapPino(p.child(bindings as pino.Bindings)),\n };\n}\n","/**\n * Utility functions\n */\n\nimport type { LanguageModelUsage } from 'ai';\n\nconst emptyDetails = {\n noCacheTokens: undefined as number | undefined,\n cacheReadTokens: undefined as number | undefined,\n cacheWriteTokens: undefined as number | undefined,\n};\nconst emptyOutputDetails = {\n textTokens: undefined as number | undefined,\n reasoningTokens: undefined as number | undefined,\n};\n\n/**\n * Sum token usage from multiple steps (AI SDK LanguageModelUsage)\n */\nexport function sumTokenUsage(usages: (LanguageModelUsage | undefined)[]): LanguageModelUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n let totalTokens = 0;\n\n for (const usage of usages) {\n if (usage) {\n inputTokens += usage.inputTokens ?? 0;\n outputTokens += usage.outputTokens ?? 0;\n totalTokens += usage.totalTokens ?? 0;\n }\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens,\n inputTokenDetails: emptyDetails,\n outputTokenDetails: emptyOutputDetails,\n };\n}\n","/**\n * Tools: defineTool, createToolSet, execute, zodToJsonSchema\n */\n\nimport { z } from 'zod';\nimport { tool } from 'ai';\nimport type { Tool, ToolExecutionOptions } from 'ai';\nimport type { Logger } from '../types/common';\nimport type { ToolConfig, ToolContext, ToolExecutionResult } from '../types/tool';\nimport { ToolError } from '../utils/errors';\n\n/** Tool has description (and optional title) in config; name is the key in createToolSet. */\nexport function defineTool<TInput extends z.ZodType, TOutput>(\n config: ToolConfig<TInput, TOutput>\n): Tool {\n const { name, description, input: inputSchema, handler } = config;\n return tool({\n description,\n inputSchema,\n execute: async (args: unknown): Promise<TOutput> => {\n const parsed = inputSchema.safeParse(args);\n if (!parsed.success)\n throw new ToolError(`Invalid input: ${parsed.error.message}`, name, parsed.error);\n try {\n return await handler(parsed.data as z.infer<TInput>, undefined as ToolContext | undefined);\n } catch (e) {\n if (e instanceof ToolError) throw e;\n throw new ToolError(\n `Tool \"${name}\" failed: ${e instanceof Error ? e.message : String(e)}`,\n name,\n e instanceof Error ? e : undefined\n );\n }\n },\n } as unknown as Parameters<typeof tool>[0]);\n}\n\nexport type ToolSet = Record<string, Tool>;\n\n/** Pass a record: key = tool name (same as in defineTool config). */\nexport function createToolSet(tools: ToolSet): ToolSet {\n return tools;\n}\n\nexport function getTools(toolSet: ToolSet): Tool[] {\n return Object.values(toolSet);\n}\n\nexport function getTool(toolSet: ToolSet, name: string): Tool | undefined {\n return toolSet[name];\n}\n\nexport interface ExecuteToolOptions {\n toolCallId?: string;\n abortSignal?: AbortSignal;\n logger?: Logger;\n}\n\nexport async function executeTool<TInput, TOutput>(\n toolImpl: Tool<TInput, TOutput>,\n input: TInput,\n options?: ExecuteToolOptions & { toolName?: string }\n): Promise<ToolExecutionResult<TOutput>> {\n const { logger } = options ?? {};\n const toolName =\n options?.toolName ??\n ('name' in toolImpl && typeof toolImpl.name === 'string' ? toolImpl.name : 'unknown');\n\n if (!toolImpl.execute) {\n logger?.error('Tool has no execute function', { toolName });\n return { success: false, error: 'Tool has no execute function' };\n }\n logger?.debug('Executing tool', { toolName, toolCallId: options?.toolCallId });\n try {\n const out = await toolImpl.execute(input, {\n toolCallId: options?.toolCallId ?? '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as ToolExecutionOptions);\n logger?.info('Tool completed', { toolName, toolCallId: options?.toolCallId });\n return { success: true, output: out as TOutput };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n logger?.error('Tool failed', {\n toolName,\n toolCallId: options?.toolCallId,\n error: msg,\n });\n return { success: false, error: msg };\n }\n}\n\nexport async function executeToolByName(\n tools: ToolSet,\n name: string,\n input: unknown,\n options?: ExecuteToolOptions\n): Promise<ToolExecutionResult> {\n const toolImpl = tools[name];\n if (!toolImpl) {\n options?.logger?.error('Tool not found', {\n name,\n availableTools: Object.keys(tools),\n });\n throw new ToolError(`Tool not found: ${name}`);\n }\n return executeTool(toolImpl, input, { ...options, toolName: name });\n}\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport function zodToJsonSchema(schema: z.ZodType): JsonSchemaObject {\n const result = z.toJSONSchema(schema) as JsonSchemaObject & {\n $schema?: string;\n definitions?: unknown;\n };\n const { $schema: _s, definitions: _d, ...rest } = result;\n return rest as JsonSchemaObject;\n}\n","/**\n * Shared validation tool factory - generates a validate_* tool from a Zod schema.\n * Eliminates boilerplate across modules that all follow the same pattern.\n */\n\nimport { z } from 'zod';\nimport type { Tool } from 'ai';\nimport { defineTool } from './tools';\n\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Create a validation tool that parses JSON input against a Zod schema.\n * Every module can replace its hand-written validate_* tool with this one-liner.\n *\n * @param name - Tool name (e.g. 'validate_schema', 'validate_api')\n * @param schema - Zod schema to validate against\n * @param description - Tool description for the agent\n * @param inputParamName - Name of the input parameter (default: 'json')\n */\nexport function createValidationTool(\n name: string,\n schema: z.ZodType,\n description: string,\n inputParamName = 'json'\n): Tool {\n return defineTool({\n name,\n description,\n input: z.object({\n [inputParamName]: z.string().describe('JSON string to validate'),\n }),\n handler: async (args: Record<string, string>): Promise<ValidationResult> => {\n const raw = args[inputParamName] ?? '';\n try {\n const parsed = JSON.parse(raw) as unknown;\n schema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n });\n}\n","/**\n * Notify agent observers (step, tool, error). Keeps agent.ts under 150 lines.\n */\n\nimport type { AgentObserver, AgentStep } from '../types/agent';\n\nexport function notifyObserversStep(observers: AgentObserver[] | undefined, step: AgentStep): void {\n observers?.forEach(o => o.onStep?.(step));\n}\n\nexport function notifyObserversTool(\n observers: AgentObserver[] | undefined,\n toolName: string,\n result: unknown\n): void {\n observers?.forEach(o => o.onToolExecution?.(toolName, result));\n}\n\nexport function notifyObserversError(observers: AgentObserver[] | undefined, error: Error): void {\n observers?.forEach(o => o.onError?.(error));\n}\n","/**\n * Agent loop: model + tools, AI SDK message shapes\n */\n\nimport type { AgentConfig, AgentResult, AgentStep, AgentToolResult } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport type { ModelToolCall } from '../types/model';\nimport { AgentError } from '../utils/errors';\nimport { sumTokenUsage } from '../utils/utils';\nimport { executeToolByName } from '../tools';\nimport { notifyObserversStep, notifyObserversTool, notifyObserversError } from './agent-observers';\n\n/**\n * Run an agent with the given configuration.\n *\n * 1. Calls the model with ModelMessage[] and tools\n * 2. If no tool calls, returns the response\n * 3. If tool calls, executes them and appends assistant + tool messages (AI SDK shape)\n * 4. Repeats until done or max iterations reached\n *\n * @example\n * ```typescript\n * const result = await runAgent({\n * model: createModel({ provider: 'openai', model: 'gpt-4o' }),\n * tools: createToolSet({ search: searchTool, calculator: calculatorTool }),\n * systemPrompt: 'You are a helpful assistant.',\n * input: 'What is 2 + 2?',\n * maxIterations: 10\n * });\n * console.log(result.output);\n * ```\n */\nexport async function runAgent(config: AgentConfig): Promise<AgentResult> {\n const {\n model,\n tools,\n systemPrompt,\n input,\n maxIterations = 10,\n onStep,\n observers,\n logger,\n } = config;\n\n logger?.info('Starting agent', { maxIterations });\n\n const messages: ModelMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: input },\n ];\n\n const steps: AgentStep[] = [];\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n if (iteration > 0 && iteration >= maxIterations - 2) {\n logger?.warn('Approaching max iterations', { iteration, maxIterations });\n }\n logger?.debug('Agent iteration', { iteration });\n\n const response = await model.invoke(messages, { tools });\n\n const step: AgentStep = {\n iteration,\n content: response.text,\n toolCalls: response.toolCalls,\n usage: response.usage,\n };\n\n if (response.text) {\n logger?.debug('Model response', { iteration, textLength: response.text.length });\n }\n\n if (!response.toolCalls?.length) {\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n logger?.info('Agent completed', {\n steps: steps.length,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n });\n return {\n output: response.text,\n steps,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n messages,\n };\n }\n\n logger?.debug('Tool calls', {\n iteration,\n toolCalls: response.toolCalls.map((tc: ModelToolCall) => ({\n name: tc.toolName,\n toolCallId: tc.toolCallId,\n })),\n });\n\n const assistantContent = [\n ...(response.text ? [{ type: 'text' as const, text: response.text }] : []),\n ...response.toolCalls.map((tc: ModelToolCall) => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n })),\n ];\n messages.push({ role: 'assistant', content: assistantContent });\n\n const toolResults: AgentToolResult[] = [];\n\n for (const toolCall of response.toolCalls) {\n const execResult = await executeToolByName(tools, toolCall.toolName, toolCall.input, {\n toolCallId: toolCall.toolCallId,\n logger,\n });\n\n const agentResult: AgentToolResult = {\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: execResult.success ? execResult.output : execResult.error,\n isError: !execResult.success,\n };\n toolResults.push(agentResult);\n notifyObserversTool(observers, toolCall.toolName, agentResult.output);\n\n const outputVal = agentResult.isError\n ? { type: 'error-text' as const, value: String(agentResult.output) }\n : {\n type: 'text' as const,\n value:\n typeof agentResult.output === 'string'\n ? agentResult.output\n : JSON.stringify(agentResult.output),\n };\n\n messages.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: outputVal,\n },\n ],\n });\n }\n\n step.toolResults = toolResults;\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n }\n\n const err = new AgentError(\n `Agent reached maximum iterations (${maxIterations}) without completing`,\n maxIterations - 1\n );\n notifyObserversError(observers, err);\n logger?.error('Agent failed: max iterations reached', { maxIterations, error: err });\n throw err;\n}\n","/**\n * Shared AI SDK adapter - pass-through to generateText (no conversions)\n */\n\nimport { generateText, generateObject, zodSchema } from 'ai';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\n InvokeObjectOptions,\n InvokeObjectResult,\n VisionOptions,\n ModelProvider,\n ModelTool,\n ModelToolCall,\n} from '../../types/model';\nimport type { ModelMessage, ImageInput } from '../../types/common';\nimport { ModelError } from '../../utils/errors';\n\nexport interface CreateAIModelParams {\n provider: ModelProvider;\n modelName: string;\n getModel: () => LanguageModelV3 | Promise<LanguageModelV3>;\n}\n\n/**\n * Create a sweagent Model that uses an AI SDK LanguageModel.\n * Messages and tools are passed through to generateText; result returned as ModelResponse.\n */\nexport function createAIModel(params: CreateAIModelParams): Model {\n const { provider, modelName, getModel } = params;\n\n return {\n provider,\n modelName,\n\n async invoke(messages: ModelMessage[], options?: InvokeOptions): Promise<ModelResponse> {\n try {\n const model = await getModel();\n const schemaOnlyTools: Record<string, ModelTool> | undefined = options?.tools\n ? (Object.fromEntries(\n Object.entries(options.tools).map(([name, t]) => {\n const { execute: _execute, ...rest } = t as Record<string, unknown>;\n return [name, rest];\n })\n ) as Record<string, ModelTool>)\n : undefined;\n const result = await generateText({\n model,\n messages,\n tools: schemaOnlyTools,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n stopSequences: options?.stop,\n });\n\n const toolCalls: ModelToolCall[] = result.toolCalls.map(tc => ({\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input as unknown,\n }));\n\n return {\n text: result.text,\n toolCalls,\n usage: result.usage,\n finishReason: result.finishReason,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to invoke ${provider} model`, provider, err);\n }\n },\n\n async generateVision(\n prompt: string,\n images: ImageInput[],\n options?: VisionOptions\n ): Promise<ModelResponse> {\n try {\n const model = await getModel();\n\n const content: (\n | { type: 'text'; text: string }\n | { type: 'image'; image: string; mimeType?: string }\n )[] = [];\n for (const img of images) {\n content.push({\n type: 'image',\n image: `data:${img.mimeType};base64,${img.base64}`,\n mimeType: img.mimeType,\n });\n }\n content.push({ type: 'text', text: prompt });\n\n const messages: ModelMessage[] = [];\n if (options?.systemPrompt) {\n messages.push({ role: 'system', content: options.systemPrompt });\n }\n messages.push({ role: 'user', content });\n\n const result = await generateText({\n model,\n messages,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n });\n\n return {\n text: result.text,\n toolCalls: [],\n usage: result.usage,\n finishReason: result.finishReason,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to generate vision response`, provider, err);\n }\n },\n\n async invokeObject<T>(\n messages: ModelMessage[],\n schema: unknown,\n options?: InvokeObjectOptions\n ): Promise<InvokeObjectResult<T>> {\n try {\n const model = await getModel();\n const schemaWrapped = zodSchema(schema as Parameters<typeof zodSchema>[0]);\n // Structured output; prefer generateObject until migrate to generateText+output\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const result = await generateObject({\n model,\n messages,\n schema: schemaWrapped,\n temperature: options?.temperature,\n maxOutputTokens: options?.maxOutputTokens,\n });\n return {\n data: result.object as T,\n usage: result.usage,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to invokeObject ${provider} model`, provider, err);\n }\n },\n };\n}\n","/**\n * OpenAI model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createOpenAI } from '@ai-sdk/openai';\n\n/**\n * Create an OpenAI model instance\n */\nexport function createOpenAIModel(config: ModelConfig): Model {\n const { model: modelName, apiKey, baseUrl } = config;\n\n const provider = createOpenAI({\n apiKey: apiKey ?? process.env.OPENAI_API_KEY,\n baseURL: baseUrl,\n });\n\n return createAIModel({\n provider: 'openai',\n modelName,\n getModel: () => provider.chat(modelName),\n });\n}\n","/**\n * Anthropic model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createAnthropic } from '@ai-sdk/anthropic';\n\n/**\n * Create an Anthropic model instance\n */\nexport function createAnthropicModel(config: ModelConfig): Model {\n const { model: modelName, apiKey } = config;\n\n const provider = createAnthropic({\n apiKey: apiKey ?? process.env.ANTHROPIC_API_KEY,\n });\n\n return createAIModel({\n provider: 'anthropic',\n modelName,\n getModel: () => provider(modelName),\n });\n}\n","/**\n * Google (Gemini) model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createGoogleGenerativeAI } from '@ai-sdk/google';\n\n/**\n * Create a Google (Gemini) model instance\n */\nexport function createGoogleModel(config: ModelConfig): Model {\n const { model: modelName, apiKey } = config;\n\n const provider = createGoogleGenerativeAI({\n apiKey: apiKey ?? process.env.GOOGLE_GENERATIVE_AI_API_KEY,\n });\n\n return createAIModel({\n provider: 'google',\n modelName,\n getModel: () => provider(modelName),\n });\n}\n","/**\n * Create a model instance based on provider\n */\n\nimport type { Model, ModelConfig } from '../types/model';\nimport { ModelError } from '../utils/errors';\nimport { createOpenAIModel } from './providers/openai';\nimport { createAnthropicModel } from './providers/anthropic';\nimport { createGoogleModel } from './providers/google';\n\n/**\n * Create a model instance for the given provider\n *\n * @example\n * ```typescript\n * const model = createModel({\n * provider: 'openai',\n * model: 'gpt-4o',\n * temperature: 0.7\n * });\n *\n * const response = await model.invoke([\n * { role: 'user', content: 'Hello!' }\n * ]);\n * ```\n */\nexport function createModel(config: ModelConfig): Model {\n const { provider } = config;\n\n switch (provider) {\n case 'openai':\n return createOpenAIModel(config);\n case 'anthropic':\n return createAnthropicModel(config);\n case 'google':\n return createGoogleModel(config);\n default:\n throw new ModelError(\n `Unsupported provider: ${provider}. Supported providers: openai, anthropic, google`\n );\n }\n}\n","/**\n * Subagents: define, run, and expose as tools to a parent agent\n */\n\nimport { z } from 'zod';\nimport type { SubagentConfig, SubagentDefinition, SubagentResult } from '../types/subagent';\nimport type { AgentTool } from '../types/agent';\nimport type { Model } from '../types/model';\nimport { runAgent } from '../agents';\nimport { createModel } from '../models/create-model';\nimport { defineTool } from '../tools';\nimport type { ToolSet } from '../tools';\nimport { SubagentError } from '../utils/errors';\n\nconst NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n/**\n * Validates and creates a subagent definition (analogous to defineTool).\n * Name must be kebab-case.\n */\nexport function defineSubagent(config: SubagentConfig): SubagentDefinition {\n if (!config.name.trim()) {\n throw new SubagentError('Subagent name is required', undefined);\n }\n if (!NAME_REGEX.test(config.name)) {\n throw new SubagentError(\n `Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${config.name}`,\n config.name\n );\n }\n return { ...config };\n}\n\nexport interface RunSubagentOptions {\n /** Parent's tools; used when definition does not specify tools (filtered by disallowedTools) */\n parentTools?: Record<string, AgentTool>;\n /** Parent's model; used when definition does not specify model */\n parentModel?: Model;\n}\n\n/**\n * Resolves the tool set for a subagent: definition.tools if set,\n * otherwise parentTools with disallowedTools removed.\n * Subagent tools (keys starting with \"subagent_\") are never inherited (no nesting).\n */\nfunction resolveTools(\n definition: SubagentDefinition,\n parentTools?: Record<string, AgentTool>\n): Record<string, AgentTool> {\n if (definition.tools != null && Object.keys(definition.tools).length > 0) {\n return definition.tools;\n }\n const base = parentTools ?? {};\n const disallowed = new Set(definition.disallowedTools ?? []);\n const filtered: Record<string, AgentTool> = {};\n for (const [key, t] of Object.entries(base)) {\n if (key.startsWith('subagent_')) continue; // no nesting\n if (!disallowed.has(key)) {\n filtered[key] = t;\n }\n }\n return filtered;\n}\n\n/**\n * Executes the subagent in isolation: resolves tools and model, runs runAgent, returns SubagentResult.\n */\nexport async function runSubagent(\n definition: SubagentDefinition,\n input: string,\n options?: RunSubagentOptions\n): Promise<SubagentResult> {\n const { parentTools, parentModel } = options ?? {};\n const tools = resolveTools(definition, parentTools);\n\n const model = definition.model == null ? parentModel : createModel(definition.model);\n if (!model) {\n throw new SubagentError(\n 'Subagent has no model: set definition.model or pass parentModel in options',\n definition.name\n );\n }\n const result = await runAgent({\n model,\n tools,\n systemPrompt: definition.systemPrompt,\n input,\n maxIterations: definition.maxIterations ?? 10,\n onStep: definition.onStep,\n });\n return { ...result, subagentName: definition.name };\n}\n\nexport interface CreateSubagentToolOptions {\n parentTools?: Record<string, AgentTool>;\n parentModel?: Model;\n}\n\n/**\n * Wraps a subagent as an AI SDK Tool so a parent agent can delegate via a tool call.\n * Input: { prompt: string }. Returns the subagent's final output string.\n */\nexport function createSubagentTool(\n definition: SubagentDefinition,\n options?: CreateSubagentToolOptions\n): AgentTool {\n const toolName = `subagent_${definition.name}`;\n return defineTool({\n name: toolName,\n description: definition.description,\n input: z.object({\n prompt: z.string().describe('The task or question to delegate to this subagent'),\n }),\n handler: async ({ prompt }) => {\n const result = await runSubagent(definition, prompt, {\n parentTools: options?.parentTools,\n parentModel: options?.parentModel,\n });\n return result.output;\n },\n });\n}\n\n/**\n * Creates a Record<string, Tool> from multiple subagent definitions, keyed by subagent_<name>.\n */\nexport function createSubagentToolSet(\n definitions: SubagentDefinition[],\n options?: CreateSubagentToolOptions\n): ToolSet {\n const out: ToolSet = {};\n for (const def of definitions) {\n const tool = createSubagentTool(def, options);\n out[`subagent_${def.name}`] = tool;\n }\n return out;\n}\n","/**\n * Handlebars template compiler - reads .hbs files, compiles with context, writes output\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport Handlebars from 'handlebars';\nimport type { TemplateContext, ScaffoldConfig, ScaffoldResult, ScaffoldError } from './types';\n\n/** Compile a single Handlebars template string with context */\nexport function compileTemplate(template: string, context: TemplateContext): string {\n const compiled = Handlebars.compile(template, { noEscape: true });\n return compiled(context);\n}\n\n/** Recursively find all .hbs files in a directory */\nfunction findHbsFiles(dir: string, base: string = dir): string[] {\n const results: string[] = [];\n if (!fs.existsSync(dir)) return results;\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...findHbsFiles(fullPath, base));\n } else if (entry.name.endsWith('.hbs')) {\n results.push(path.relative(base, fullPath));\n }\n }\n return results;\n}\n\n/** Convert a .hbs relative path to the output file path (strip .hbs extension) */\nfunction toOutputPath(hbsRelPath: string): string {\n return hbsRelPath.replace(/\\.hbs$/, '');\n}\n\n/** Check if a path matches any skip pattern (simple glob: * matches any segment) */\nfunction shouldSkip(relativePath: string, skipPatterns: string[]): boolean {\n for (const pattern of skipPatterns) {\n const regex = new RegExp(\n '^' +\n pattern\n .replace(/\\./g, '\\\\.')\n .replace(/\\*\\*/g, '<<GLOBSTAR>>')\n .replace(/\\*/g, '[^/]*')\n .replace(/<<GLOBSTAR>>/g, '.*') +\n '$'\n );\n if (regex.test(relativePath)) return true;\n }\n return false;\n}\n\n/**\n * Scaffold a project: compile all .hbs templates in templateDir with context,\n * write results to outputDir, return summary.\n */\nexport async function scaffoldProject(config: ScaffoldConfig): Promise<ScaffoldResult> {\n const { templateDir, outputDir, context, skipPatterns = [] } = config;\n const hbsFiles = findHbsFiles(templateDir);\n const files: string[] = [];\n const errors: ScaffoldError[] = [];\n\n for (const hbsFile of hbsFiles) {\n if (shouldSkip(hbsFile, skipPatterns)) continue;\n\n const outputRelPath = toOutputPath(hbsFile);\n const inputPath = path.join(templateDir, hbsFile);\n const outputPath = path.join(outputDir, outputRelPath);\n\n try {\n const templateSource = fs.readFileSync(inputPath, 'utf-8');\n const compiled = compileTemplate(templateSource, context);\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, compiled, 'utf-8');\n files.push(outputRelPath);\n } catch (err) {\n errors.push({\n file: hbsFile,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { fileCount: files.length, files, errors };\n}\n\n/** Register common Handlebars helpers */\nexport function registerHelpers(): void {\n Handlebars.registerHelper('eq', (a, b) => a === b);\n Handlebars.registerHelper('neq', (a, b) => a !== b);\n Handlebars.registerHelper('json', obj => JSON.stringify(obj, null, 2));\n Handlebars.registerHelper('uppercase', (str: string) =>\n typeof str === 'string' ? str.toUpperCase() : ''\n );\n Handlebars.registerHelper('lowercase', (str: string) =>\n typeof str === 'string' ? str.toLowerCase() : ''\n );\n Handlebars.registerHelper('capitalize', (str: string) =>\n typeof str === 'string' ? str.charAt(0).toUpperCase() + str.slice(1) : ''\n );\n Handlebars.registerHelper('camelCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toLowerCase());\n });\n Handlebars.registerHelper('pascalCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toUpperCase());\n });\n}\n\n// Register helpers on module load\nregisterHelpers();\n","/**\n * MCP SDK transport creation and result parsing. Isolates SDK path and dynamic imports.\n */\n\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { McpTransport, McpToolContent } from './types';\n\nfunction getSdkRoot(): string {\n const require = createRequire(import.meta.url);\n const entry = require.resolve('@modelcontextprotocol/sdk/client');\n return path.dirname(path.dirname(path.dirname(path.dirname(entry))));\n}\n\nconst sdkRoot = getSdkRoot();\n\n/** Parse first text content block of an MCP tool result to JSON or { text } / { raw }. */\nexport function parseToolResult(result: { content?: McpToolContent[] }): unknown {\n const content = result.content;\n if (!content?.length) return {};\n const first = content[0];\n if (first?.type === 'text' && typeof first.text === 'string') {\n const text = first.text.trim();\n if (text.startsWith('{') || text.startsWith('[')) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return { raw: text };\n }\n }\n return { text };\n }\n return result;\n}\n\n/** Build StreamableHTTPClientTransport from the MCP SDK. */\nexport async function createHttpTransport(\n url: string,\n headers?: Record<string, string>\n): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'streamableHttp.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StreamableHTTPClientTransport: new (\n url: URL,\n opts?: { requestInit?: RequestInit }\n ) => McpTransport;\n };\n const requestInit: RequestInit | undefined = headers\n ? { headers: new Headers(headers) }\n : undefined;\n return new mod.StreamableHTTPClientTransport(\n new URL(url),\n requestInit ? { requestInit } : undefined\n );\n}\n\n/** Build StdioClientTransport from the MCP SDK. */\nexport async function createStdioTransport(command: string, args: string[]): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'stdio.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StdioClientTransport: new (params: { command: string; args: string[] }) => McpTransport;\n };\n return new mod.StdioClientTransport({ command, args });\n}\n","/**\n * BaseMcpClient - reusable MCP client with lazy connection and typed tool invocation.\n * Extend and add domain methods that call this.callTool(name, args).\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client';\nimport { ToolError } from '../utils/errors';\nimport { createHttpTransport, createStdioTransport, parseToolResult } from './transports';\nimport type {\n McpClientConfig,\n McpClientInfo,\n McpToolContent,\n McpTransport,\n McpResolveOptions,\n} from './types';\n\nexport class BaseMcpClient {\n private readonly info: McpClientInfo;\n private readonly config: McpClientConfig;\n private client: Client | null = null;\n private transport: McpTransport | null = null;\n private connectPromise: Promise<void> | null = null;\n\n constructor(info: McpClientInfo, config: McpClientConfig) {\n this.info = info;\n this.config = config;\n }\n\n /** Build config from options + env (<PREFIX>_URL, _API_KEY, _COMMAND, _ARGS). */\n static resolveConfig(\n options?: McpClientConfig,\n resolveOpts: McpResolveOptions = { envPrefix: 'MCP' }\n ): McpClientConfig {\n const { envPrefix, serverLabel, apiKeyHeader } = resolveOpts;\n const url = options?.url ?? process.env[`${envPrefix}_URL`];\n const apiKey = process.env[`${envPrefix}_API_KEY`];\n const command = options?.command ?? process.env[`${envPrefix}_COMMAND`];\n const argsEnv = process.env[`${envPrefix}_ARGS`];\n const args = options?.args ?? (argsEnv ? argsEnv.split(',').map(a => a.trim()) : undefined);\n\n let headers = options?.headers ? { ...options.headers } : undefined;\n if (apiKey) {\n const name = apiKeyHeader ?? 'Authorization';\n\n headers = headers ?? {};\n\n headers[name] = name === 'Authorization' ? `Bearer ${apiKey}` : apiKey;\n }\n\n if (url) return { url, headers };\n if (command) return { command, args: args?.length ? args : [] };\n throw new ToolError(\n `${serverLabel ?? envPrefix} uses MCP only. Set ${envPrefix}_URL or ${envPrefix}_COMMAND (and optionally ${envPrefix}_ARGS).`,\n 'mcp_client'\n );\n }\n\n private async ensureConnected(): Promise<Client> {\n if (this.client) return this.client;\n if (this.connectPromise) {\n await this.connectPromise;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n this.connectPromise = this.doConnect();\n await this.connectPromise;\n this.connectPromise = null;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n\n private async doConnect(): Promise<void> {\n const client = new Client(\n { name: this.info.name, version: this.info.version },\n { capabilities: {} }\n );\n if (this.config.url) {\n this.transport = await createHttpTransport(this.config.url, this.config.headers);\n } else if (this.config.command) {\n this.transport = await createStdioTransport(this.config.command, this.config.args ?? []);\n } else {\n throw new ToolError('MCP config missing: provide url or command.', 'mcp_client');\n }\n await client.connect(this.transport as Parameters<Client['connect']>[0]);\n this.client = client;\n }\n\n /** Call MCP tool and parse result. Subclasses use this for typed domain methods. */\n protected async callTool<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {\n const client = await this.ensureConnected();\n const result = await client.callTool({ name, arguments: args });\n if (result && typeof result === 'object' && 'content' in result) {\n return parseToolResult(result as { content?: McpToolContent[] }) as T;\n }\n return result as T;\n }\n\n async close(): Promise<void> {\n if (this.transport) {\n await this.transport.close();\n this.transport = null;\n }\n this.client = null;\n this.connectPromise = null;\n }\n}\n","/**\n * Hello World tool\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../lib/tools';\n\nexport const helloWorldTool = defineTool({\n name: 'hello_world',\n description: 'Returns a greeting message for the given name',\n input: z.object({\n name: z.string().describe('Name to greet'),\n }),\n handler: async ({ name }) => {\n return { greeting: `Hello, ${name}! Welcome to sweagent.` };\n },\n});\n","/**\n * Hello World agent - runs an agent with the hello world tool\n */\n\nimport type { AgentResult, AgentStep } from '../../lib/types/agent';\nimport type { Logger } from '../../lib/types/common';\nimport type { ModelConfig } from '../../lib/types/model';\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { helloWorldTool } from './tool';\n\nexport interface HelloWorldAgentConfig {\n /** User input (e.g. \"Say hello to Alice\") */\n input: string;\n /** Model config; defaults to OpenAI gpt-4o-mini */\n model?: ModelConfig;\n /** System prompt override */\n systemPrompt?: string;\n /** Max iterations; default 3 */\n maxIterations?: number;\n /** Callback for each step */\n onStep?: (step: AgentStep) => void;\n /** Optional logger for execution logs */\n logger?: Logger;\n}\n\nconst DEFAULT_SYSTEM_PROMPT =\n 'You are a friendly greeter. Use the hello_world tool to greet users.';\n\nexport async function runHelloWorldAgent(config: HelloWorldAgentConfig): Promise<AgentResult> {\n const {\n input,\n model: modelConfig,\n systemPrompt = DEFAULT_SYSTEM_PROMPT,\n maxIterations = 3,\n onStep,\n logger,\n } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n\n return runAgent({\n model,\n tools: createToolSet({ hello_world: helloWorldTool }),\n systemPrompt,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Branding schema for frontend app config\n */\n\nimport { z } from 'zod';\n\nexport const BrandingSchema = z.object({\n brandName: z.string().describe(\"The brand's display name\"),\n primaryColor: z.string().describe(\"The brand's primary color code (e.g., #FFFFFF)\"),\n secondaryColor: z.string().describe(\"The brand's secondary color code (e.g., #000000)\"),\n logo: z.url().describe(\"URL pointing to the brand's logo\"),\n});\n\nexport type TBrandingSchema = z.infer<typeof BrandingSchema>;\n","/**\n * App configuration schema\n */\n\nimport { z } from 'zod';\nimport { BrandingSchema } from './branding.schema';\n\nexport const AppConfigSchema = z.object({\n name: z.string().describe('Application name'),\n description: z.string().describe('Brief description of the application'),\n author: z\n .string()\n .describe('Author or owner of the application')\n .default('sijeeshmiziha (HubSpire)'),\n branding: BrandingSchema.describe('Branding information for the application'),\n apiEndpoint: z.url().describe(\"URL endpoint for the app's API calls\"),\n});\n\nexport type TAppConfigSchema = z.infer<typeof AppConfigSchema>;\n","/**\n * Form field, validation, options, and column schemas\n */\n\nimport { z } from 'zod';\n\nexport const ValidationSchema = z.object({\n minLength: z.number().optional().describe('Minimum length requirement'),\n zodString: z.string().describe('Raw Zod string validation (e.g. regex)'),\n});\n\nexport const FieldOptionsSchema = z.object({\n hookName: z.string().optional().describe('Name of the hook for dynamic field options'),\n queryString: z.string().optional().describe('Optional query string for fetching field options'),\n labelKey: z.string().optional().describe('Key used as label when displaying options'),\n valueKey: z.string().optional().describe('Key used as value for a field when selecting options'),\n values: z.array(z.string()).optional().describe('Static list of possible field values'),\n});\n\nexport const FormFieldSchema = z.object({\n name: z.string().describe(\"The field's key or identifier\"),\n type: z\n .enum([\n 'text',\n 'email',\n 'password',\n 'number',\n 'multiSelect',\n 'textarea',\n 'hidden',\n 'select',\n 'date',\n 'image',\n ])\n .describe(\n 'Type of input field. If it has options, it should not be \"hidden\". If the field is required, it should not be hidden unless it serves as the current user.'\n ),\n required: z.boolean().optional().describe('Whether this field must be filled'),\n validation: ValidationSchema.optional().describe('Optional field validation requirements'),\n defaultValue: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe('Default value can be string, number, or boolean'),\n options: FieldOptionsSchema.optional().describe(\n 'Additional dynamic or static options for this field'\n ),\n});\n\nexport const ColumnSchema = z.object({\n field: z.string().describe('Key or name of the data field in the table'),\n label: z.string().describe('User-friendly label to show on the table header'),\n});\n\nexport type TFormFieldSchema = z.infer<typeof FormFieldSchema>;\nexport type TColumnSchema = z.infer<typeof ColumnSchema>;\n","/**\n * API, drawer, auth page, listing page, and page union schemas\n */\n\nimport { z } from 'zod';\nimport { FormFieldSchema, ColumnSchema } from './field.schema';\n\nexport const ApiResponseTypeSchema = z\n .object({\n type: z.string().describe(\"Indicates the response type (e.g., 'object')\"),\n properties: z\n .record(\n z.string(),\n z.object({\n type: z.string().describe('Property type as returned by the API'),\n })\n )\n .describe('Key-value record describing each field in the response'),\n })\n .optional()\n .describe('Describes the expected structure of an API response');\n\nexport type TApiResponseTypeSchema = z.infer<typeof ApiResponseTypeSchema>;\n\nexport const ListingPageApiSchema = z.object({\n type: z\n .enum(['list', 'create', 'update', 'delete', 'getById'])\n .describe('Type of API call for CRUD operations'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const AuthPageApiSchema = z.object({\n type: z\n .enum(['login', 'currentUser', 'forgotPassword', 'resetPassword'])\n .describe('Type of API call'),\n graphqlHook: z.string().describe('Name of the GraphQL hook (e.g. useLoginMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const DrawerSchema = z.object({\n title: z.string().describe('Title displayed on the drawer'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)'),\n fields: z.array(FormFieldSchema).describe('List of fields displayed within the drawer'),\n});\n\nexport const AuthPageSchema = z.object({\n name: z\n .enum(['LoginPage', 'ForgotPasswordPage', 'ResetPasswordPage'])\n .describe('Internal name of the auth page'),\n type: z\n .enum(['EmailPassword', 'ForgotPassword', 'ResetPassword'])\n .describe('Type of authentication page'),\n route: z.string().describe(\"URL route for this page (e.g., '/login')\"),\n isPrivate: z.boolean().describe('Whether this page requires an authenticated session'),\n api: z.array(AuthPageApiSchema).describe('List of API calls involved in this page'),\n fields: z\n .array(FormFieldSchema)\n .optional()\n .describe('Optional form fields needed on this auth page'),\n});\n\nexport const ListingPageSchema = z.object({\n type: z.literal('Listing').describe('Indicates that this page is a listing-type page'),\n name: z.string().describe('Internal name of the listing page'),\n route: z.string().describe('URL route for this listing page'),\n isPrivate: z.boolean().describe('Whether this page is private (requires auth)'),\n api: z.array(ListingPageApiSchema).describe('List of API calls that power this listing page'),\n columns: z.array(ColumnSchema).describe('Table columns displayed on the listing page'),\n actions: z\n .array(z.string())\n .describe('List of possible actions on each row (e.g., create, edit, delete, view)'),\n drawerCreate: DrawerSchema.describe('Drawer configuration for creating new records'),\n drawerUpdate: DrawerSchema.describe('Drawer configuration for editing existing records'),\n});\n\nexport const PageSchema = z.discriminatedUnion('type', [AuthPageSchema, ListingPageSchema]);\n\nexport type TPageSchema = z.infer<typeof PageSchema>;\n","/**\n * Module and root application schema\n */\n\nimport { z } from 'zod';\nimport { AppConfigSchema } from './app-config.schema';\nimport { PageSchema } from './page.schema';\n\nexport const ModuleSchema = z.object({\n name: z.string().describe('Name of the module'),\n pages: z.array(PageSchema).describe('Pages included within this module'),\n});\n\nexport const ApplicationSchema = z.object({\n app: AppConfigSchema.describe('Overall application configuration'),\n modules: z\n .array(ModuleSchema)\n .describe(\n 'List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.'\n ),\n});\n\nexport type TApplicationSchema = z.infer<typeof ApplicationSchema>;\nexport type TModuleSchema = z.infer<typeof ModuleSchema>;\n","/**\n * User-related schemas - same as .ref/core/react/zodTypes.ts\n */\n\nimport { z } from 'zod';\n\nexport const LoginInputSchema = z.object({\n email: z.email().describe(\"User's email address, must be valid format\"),\n password: z.string().min(8).describe(\"User's password, minimum length of 8\"),\n});\n\nexport const SpecializationSchema = z.object({\n _id: z.string().describe('Unique identifier of the specialization, type: string'),\n title: z.string().describe('Display title for the specialization, type: string'),\n});\n\nexport const UserSchema = z.object({\n _id: z.string().describe('Unique ID of the user, type: string'),\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Email address in valid format, type: string'),\n phoneNumber: z.string().min(10).describe(\"User's phone number, at least 10 digits, type: string\"),\n profileImage: z\n .string()\n .optional()\n .describe(\"Optional URL to user's profile image, type: string, optional\"),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe(\"User's role in the system (ADMIN, TRAINER, CLIENT)\"),\n rate: z\n .number()\n .min(1)\n .optional()\n .describe(\"User's rate (e.g., hourly, etc.), type: number, optional\"),\n specializations: z\n .array(SpecializationSchema)\n .optional()\n .describe('Array of specialization objects, optional'),\n languages: z\n .array(z.string())\n .optional()\n .describe('Array of languages the user speaks, type: string[], optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Brief bio or description (20-500 chars), type: string, optional'),\n gender: z.string().optional().describe(\"User's gender, type: string, optional\"),\n timezone: z.string().optional().describe(\"User's timezone, type: string, optional\"),\n averageRating: z\n .number()\n .optional()\n .describe('Average rating for this user, type: number, optional'),\n});\n\nexport const CreateUserInputSchema = z.object({\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Valid email for the new user, type: string'),\n phoneNumber: z.string().min(10).describe('Phone number (at least 10 digits), type: string'),\n password: z.string().min(8).describe('Password with min length 8, type: string'),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe('Role of the new user (ADMIN, TRAINER, CLIENT)'),\n rate: z.number().min(1).optional().describe('Rate for the new user, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Array of specialization IDs, optional'),\n languages: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('List of languages user speaks, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe(\"User's about/bio field, 20-500 chars, optional\"),\n});\n\nexport const UpdateUserInputSchema = z.object({\n _id: z.string().describe('ID of the user to be updated, type: string'),\n firstName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated first name, type: string, optional'),\n lastName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated last name, type: string, optional'),\n email: z.email().optional().describe('Updated email, type: string, optional'),\n phoneNumber: z\n .string()\n .min(10)\n .optional()\n .describe('Updated phone number, at least 10 digits, optional'),\n rate: z.number().min(1).optional().describe('Updated rate, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Updated array of specialization IDs, optional'),\n languages: z.array(z.string()).min(1).optional().describe('Updated list of languages, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Updated about/bio (20-500 chars), optional'),\n});\n\nexport const ForgotPasswordSchema = z.object({\n email: z.email().describe('Email to initiate the password reset process, type: string'),\n});\n\nexport const ResetPasswordSchema = z.object({\n type: z.enum(['EMAIL', 'SMS']).describe('How the reset code was sent (EMAIL or SMS)'),\n resetTicket: z.string().describe('Token/ticket to validate the reset request, type: string'),\n newPassword: z.string().min(8).describe('The new password, min length 8, type: string'),\n});\n\nexport type TLoginInputSchema = z.infer<typeof LoginInputSchema>;\nexport type TUserSchema = z.infer<typeof UserSchema>;\nexport type TSpecializationSchema = z.infer<typeof SpecializationSchema>;\nexport type TCreateUserInputSchema = z.infer<typeof CreateUserInputSchema>;\nexport type TUpdateUserInputSchema = z.infer<typeof UpdateUserInputSchema>;\nexport type TForgotPasswordSchema = z.infer<typeof ForgotPasswordSchema>;\nexport type TResetPasswordSchema = z.infer<typeof ResetPasswordSchema>;\n","/**\n * System prompt for GraphQL-to-frontend configuration conversion\n */\n\nexport const REACT_BUILDER_SYSTEM_PROMPT = `You are an expert GraphQL-to-frontend configuration converter. Transform the provided GraphQL schema into a structured JSON configuration for a React + Vite frontend application.\n\n## Target Tech Stack\nThe generated configuration will be consumed by a Vite + React 19 + TypeScript template with:\n- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/\n- **Styling**: Tailwind CSS v4 with OKLCH color space\n- **Routing**: React Router v7 with private route support\n- **Forms**: React Hook Form + Zod validation (zodResolver)\n- **GraphQL Client**: Apollo Client with typed hooks from CodeGen\n- **Path Aliases**: @/{appName}/* maps to ./src/*\n\n**Your output must be valid JSON only.** No markdown code fences, no explanations. Return the raw JSON object matching the application schema (app with name, description, author, branding, apiEndpoint; modules array with name and pages; each page has type, name, route, isPrivate, api, and for listing pages: columns, actions, drawerCreate, drawerUpdate; for auth pages: fields when needed).\n\nStrict guidelines:\n- Use every available CRUD GraphQL query and mutation from the project schema.\n- Map GraphQL types to frontend modules and pages.\n- EmailAddress → \"type\": \"email\" with validation; DateTime → \"type\": \"date\"; enums → select with options.values.\n- Relationships → multiSelect with query-based options where appropriate.\n- Add isPrivate: true for authenticated operations (route guarded by React Router).\n- Form fields should map to React Hook Form + Zod validation schemas.\n- Maintain camelCase. Ensure valid JSON syntax.`;\n","/**\n * Instruction template for GraphQL-to-frontend conversion\n */\n\nexport const REACT_BUILDER_INSTRUCTION = `\nAct as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.\n\n**Conversion Process**\n\n1. Schema Analysis:\n- Identify all modules using 100% of available CRUD operations\n- Catalog all Query/Mutation operations with arguments\n- Map GraphQL types to frontend modules\n- Detect @auth directives and role requirements\n- Analyze relationships through nested types\n\n2. Field Mapping:\n- EmailAddress → \"type\": \"email\" with Zod email validation\n- DateTime → \"type\": \"date\"\n- Enums → dropdowns with options.values\n- Relationships → multiSelect with query-based options\n\n3. API Operations:\n- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape\n\n4. Validation:\n- Generate Zod schemas from @required directives, scalar types (Password → min 8 chars), custom directives\n- Include validation error messages\n\n5. Security:\n- Add isPrivate: true for authenticated operations\n- Implement role checks from @auth directives\n\n6. Output:\n- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks\n- Include Zod validation strings, maintain camelCase, valid JSON only\n`.trim();\n\nexport function buildInstructionPrompt(): string {\n return REACT_BUILDER_INSTRUCTION;\n}\n","/**\n * Few-shot examples: example GraphQL schema and expected JSON output (abbreviated)\n */\n\nexport const EXAMPLE_GRAPHQL_SCHEMA = `\ntype Query {\n getCurrentUser: User\n getAllUser(limit: Int, offset: Int): [User]!\n}\ntype Mutation {\n login(data: LoginInput!): Login!\n createUser(data: CreateUserInput!): User!\n}\ntype User {\n _id: ID!\n firstName: String!\n lastName: String!\n email: String!\n role: Role!\n}\nenum Role { ADMIN TRAINER CLIENT }\ninput LoginInput { email: String! password: String! }\ninput CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }\n`.trim();\n\nexport const EXAMPLE_JSON_OUTPUT = `{\n \"app\": {\n \"name\": \"my-app\",\n \"description\": \"App description\",\n \"author\": \"Author\",\n \"branding\": {\n \"brandName\": \"MyBrand\",\n \"primaryColor\": \"#333\",\n \"secondaryColor\": \"#fff\",\n \"logo\": \"https://example.com/logo.png\"\n },\n \"apiEndpoint\": \"http://localhost:4000/graphql\"\n },\n \"modules\": [\n {\n \"name\": \"auth\",\n \"pages\": [\n {\n \"name\": \"LoginPage\",\n \"type\": \"EmailPassword\",\n \"route\": \"/login\",\n \"isPrivate\": false,\n \"api\": [\n { \"type\": \"login\", \"graphqlHook\": \"useLoginMutation\", \"queryString\": \"mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }\" }\n ]\n }\n ]\n },\n {\n \"name\": \"user\",\n \"pages\": [\n {\n \"type\": \"Listing\",\n \"name\": \"UserListPage\",\n \"route\": \"/users\",\n \"isPrivate\": true,\n \"api\": [\n { \"type\": \"list\", \"graphqlHook\": \"useGetAllUserQuery\", \"queryString\": \"query GetAllUser { getAllUser { _id firstName email } }\" },\n { \"type\": \"create\", \"graphqlHook\": \"useCreateUserMutation\", \"queryString\": \"mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }\" }\n ],\n \"columns\": [{ \"field\": \"firstName\", \"label\": \"First Name\" }, { \"field\": \"email\", \"label\": \"Email\" }],\n \"actions\": [\"create\", \"edit\", \"delete\"],\n \"drawerCreate\": { \"title\": \"Create User\", \"graphqlHook\": \"useCreateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\", \"required\": true }, { \"name\": \"email\", \"type\": \"email\", \"required\": true }] },\n \"drawerUpdate\": { \"title\": \"Edit User\", \"graphqlHook\": \"useUpdateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\" }, { \"name\": \"email\", \"type\": \"email\" }] }\n }\n ]\n }\n ]\n}`;\n\nexport function buildExampleShotPrompt(): string {\n return `\n**Reference Conversion Example**\n\nEXAMPLE GRAPHQL INPUT:\n\\`\\`\\`graphql\n${EXAMPLE_GRAPHQL_SCHEMA}\n\\`\\`\\`\n\nEXPECTED JSON OUTPUT:\n\\`\\`\\`json\n${EXAMPLE_JSON_OUTPUT}\n\\`\\`\\`\n`.trim();\n}\n","/**\n * Feedback prompt - re-generate frontend config incorporating user feedback\n */\n\nexport function buildFeedbackPrompt(userFeedback: string, schemaFile: string): string {\n return `\nReview the user feedback carefully to understand the required updates.\n\nThe user feedback for updating the generated Frontend Config JSON is provided below:\n\"\"\"\n${userFeedback}\n\"\"\"\n\nNow, generate the Frontend Config JSON for this project based on the provided feedback.\n\n**Project GRAPHQL SCHEMA INPUT:**\n\\`\\`\\`graphql\n${schemaFile}\n\\`\\`\\`\n\nUpdate the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.\n`.trim();\n}\n","/**\n * validate_frontend_config tool - validates JSON against ApplicationSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { ApplicationSchema } from '../schemas';\n\nexport const validateFrontendConfigTool = createValidationTool(\n 'validate_frontend_config',\n ApplicationSchema,\n 'Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.',\n 'config'\n);\n","/**\n * generate_frontend tool - converts GraphQL schema to frontend config JSON (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { ApplicationSchema, type TApplicationSchema } from '../schemas';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from '../prompts/system.prompt';\nimport { buildInstructionPrompt, buildExampleShotPrompt } from '../prompts';\nimport type { AppInfo } from '../types';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nfunction buildGeneratePrompt(graphqlSchema: string, appInfo?: AppInfo): string {\n const instruction = buildInstructionPrompt();\n const example = buildExampleShotPrompt();\n const appInfoBlock = appInfo\n ? `\n**Project context:**\n- name: ${appInfo.projectName ?? 'project'}\n- description: ${appInfo.projectDescription ?? ''}\n- modules: ${appInfo.modules ?? ''}\n- apiEndpoint: ${appInfo.apiEndpoint ?? 'http://localhost:4000/graphql'}\n`\n : '';\n return `${instruction}\n\n${example}\n${appInfoBlock}\n\n**Current Project GraphQL Schema:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nGenerate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`;\n}\n\nexport function createGenerateFrontendTool(model: Model) {\n return defineTool({\n name: 'generate_frontend',\n description:\n 'Convert a GraphQL schema into a frontend configuration JSON (app, modules, pages, fields, API hooks). Optionally provide app info (project name, description, apiEndpoint). Returns the full application config as JSON.',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to convert'),\n appInfo: z\n .object({\n projectName: z.string().optional(),\n projectDescription: z.string().optional(),\n modules: z.string().optional(),\n apiEndpoint: z.string().optional(),\n })\n .optional()\n .describe('Optional project/app context'),\n }),\n handler: async ({ graphqlSchema, appInfo }): Promise<TApplicationSchema> => {\n const userPrompt = buildGeneratePrompt(graphqlSchema, appInfo);\n const messages = [\n { role: 'system' as const, content: REACT_BUILDER_SYSTEM_PROMPT },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, ApplicationSchema);\n },\n });\n}\n","/**\n * generate_feature_breakdown tool - breaks down GraphQL schema into components/pages (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { REACT_BUILDER_INSTRUCTION } from '../prompts/instruction.prompt';\n\nexport interface FeatureBreakdownResult {\n summary: string;\n modules: string[];\n operations: string[];\n suggestedPages?: string[];\n}\n\nexport function createGenerateFeatureBreakdownTool(model: Model) {\n return defineTool({\n name: 'generate_feature_breakdown',\n description:\n 'Analyze a GraphQL schema and produce a feature/component breakdown: list of modules, CRUD operations, and suggested pages. Returns a structured summary (not the full frontend JSON).',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to analyze'),\n }),\n handler: async ({ graphqlSchema }): Promise<FeatureBreakdownResult> => {\n const userPrompt = `${REACT_BUILDER_INSTRUCTION}\n\n**Schema to analyze:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nRespond with a structured breakdown only (no full JSON config): list modules, list Query/Mutation operations, and suggested pages for each module. Use clear headings and bullet points.`;\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a GraphQL schema analyst. Return a clear, structured text breakdown.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 4096 });\n return { summary: response.text, modules: [], operations: [], suggestedPages: [] };\n },\n });\n}\n","/**\n * scaffold_vite tool - compiles .ref/templates/vite/ with ApplicationSchema config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult, TemplateContext } from '../../../lib/template-engine';\nimport type { TApplicationSchema } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert ApplicationSchema config to template context */\nfunction toTemplateContext(config: TApplicationSchema): TemplateContext {\n return {\n appName: config.app.name,\n description: config.app.description,\n apiEndpoint: config.app.apiEndpoint,\n branding: {\n brandName: config.app.branding.brandName,\n primaryColor: config.app.branding.primaryColor,\n secondaryColor: config.app.branding.secondaryColor,\n logo: config.app.branding.logo,\n },\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n })),\n author: config.app.author,\n pages: config.modules.flatMap(m => m.pages),\n };\n}\n\nexport const scaffoldViteTool = defineTool({\n name: 'scaffold_vite',\n description:\n 'Scaffold a Vite + React project from a validated ApplicationSchema config. Compiles Handlebars templates from .ref/templates/vite/ and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated ApplicationSchema config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'application schema config') as TApplicationSchema;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/vite');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * react-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nimport { createGenerateFrontendTool } from './generate-frontend.tool';\nimport { createGenerateFeatureBreakdownTool } from './generate-feature-breakdown.tool';\nimport { scaffoldViteTool } from './scaffold-vite';\n\nexport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nexport { createGenerateFrontendTool } from './generate-frontend.tool';\nexport {\n createGenerateFeatureBreakdownTool,\n type FeatureBreakdownResult,\n} from './generate-feature-breakdown.tool';\nexport { scaffoldViteTool } from './scaffold-vite';\n\nexport function createReactBuilderTools(model: Model) {\n return createToolSet({\n validate_frontend_config: validateFrontendConfigTool,\n generate_frontend: createGenerateFrontendTool(model),\n generate_feature_breakdown: createGenerateFeatureBreakdownTool(model),\n scaffold_vite: scaffoldViteTool,\n });\n}\n","/**\n * graphql-analyzer subagent - analyzes GraphQL schemas (no tools)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst GRAPHQL_ANALYZER_SYSTEM_PROMPT = `You are an expert at analyzing GraphQL schemas. Your job is to:\n\n1. **Types**: List all object types, enums, scalars, and input types.\n2. **Queries**: List every Query field with arguments and return type.\n3. **Mutations**: List every Mutation field with arguments and return type.\n4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).\n5. **Auth/directives**: Note any @auth, @directive usage that affects access control.\n\nRespond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`;\n\nexport const graphqlAnalyzerSubagent = defineSubagent({\n name: 'graphql-analyzer',\n description:\n 'Analyzes a GraphQL schema to extract types, queries, mutations, and relationships. Use when you need to understand the schema before generating frontend config. Returns structured analysis (no JSON).',\n systemPrompt: GRAPHQL_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * config-validator subagent - validates frontend config (has validate_frontend_config tool)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\nimport { validateFrontendConfigTool } from '../tools/validate-frontend-config.tool';\n\nconst CONFIG_VALIDATOR_SYSTEM_PROMPT = `You are a frontend configuration validator. Your job is to:\n\n1. Validate the provided frontend config JSON using the validate_frontend_config tool.\n2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.\n3. Report any missing modules, pages, or API hooks.\n\nWhen the user gives you a config (as JSON string) and optionally the GraphQL schema, first call validate_frontend_config to check structure. Then summarize completeness.`;\n\nexport function createConfigValidatorSubagent() {\n return defineSubagent({\n name: 'config-validator',\n description:\n 'Validates a frontend configuration JSON and checks completeness against the GraphQL schema. Use when you have a draft config and want to validate it. Has access to validate_frontend_config tool.',\n systemPrompt: CONFIG_VALIDATOR_SYSTEM_PROMPT,\n tools: { validate_frontend_config: validateFrontendConfigTool },\n maxIterations: 5,\n });\n}\n","/**\n * runReactBuilderAgent - orchestrator for frontend config generation with retry and subagents\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createReactBuilderTools } from './tools';\nimport { graphqlAnalyzerSubagent, createConfigValidatorSubagent } from './subagents';\nimport type { ReactBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${REACT_BUILDER_SYSTEM_PROMPT}\n\nYou are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:\n\n1. **Analyze (optional)**: For complex schemas, use subagent_graphql-analyzer with a prompt that includes the schema to get a structured analysis of types, queries, and mutations.\n2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.\n3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.\n4. **Validate directly**: You can use validate_frontend_config to check any config JSON.\n5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.\n\nRespond with the final frontend config (as JSON) or a clear summary and the config. If the user gives feedback, use generate_frontend again with the same schema and consider their feedback in your instructions.`;\n\n/**\n * Run the react-builder orchestrator agent with all tools and subagents.\n * Use generate_frontend tool for config generation; the tool may throw on parse failure (caller can retry with new input).\n */\nexport async function runReactBuilderAgent(config: ReactBuilderAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const reactTools = createReactBuilderTools(model);\n const configValidator = createConfigValidatorSubagent();\n const subagentTools = createSubagentToolSet([graphqlAnalyzerSubagent, configValidator], {\n parentModel: model,\n });\n const tools = createToolSet({ ...reactTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schema for extract_actors tool output\n */\n\nimport { z } from 'zod';\n\nexport const actorSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n});\n\nexport const actorsResultSchema = z.object({\n actors: z.array(actorSchema),\n message: z.string(),\n});\n\nexport type ActorResult = z.infer<typeof actorsResultSchema>;\n","/**\n * Zod schema for generate_flows tool output\n */\n\nimport { z } from 'zod';\n\nexport const flowSchema = z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n});\n\nexport const flowsResultSchema = z.object({\n flows: z.array(flowSchema),\n message: z.string(),\n});\n\nexport type FlowsResult = z.infer<typeof flowsResultSchema>;\n","/**\n * Zod schema for generate_stories tool output\n */\n\nimport { z } from 'zod';\n\nexport const storySchema = z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n});\n\nexport const storiesResultSchema = z.object({\n stories: z.array(storySchema),\n message: z.string(),\n});\n\nexport type StoriesResult = z.infer<typeof storiesResultSchema>;\n","/**\n * Zod schema for extract_modules tool output\n */\n\nimport { z } from 'zod';\n\nexport const crudApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n operation: z.enum(['create', 'read', 'readAll', 'update', 'delete']),\n description: z.string(),\n inputs: z.array(z.string()),\n outputs: z.array(z.string()),\n});\n\nexport const extractedModuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n entity: z.string(),\n apis: z.array(crudApiSchema),\n});\n\nexport const modulesResultSchema = z.object({\n modules: z.array(extractedModuleSchema),\n summary: z.object({\n totalModules: z.number(),\n totalApis: z.number(),\n }),\n message: z.string(),\n});\n\nexport type ModulesResult = z.infer<typeof modulesResultSchema>;\n","/**\n * Zod schemas for DatabaseDesign, DatabaseEntity, EntityField, EntityIndex, EntityRelation\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.boolean(),\n unique: z.boolean(),\n description: z.string(),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string(),\n fields: z.array(z.string()),\n unique: z.boolean(),\n});\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n description: z.string(),\n});\n\nexport const databaseEntitySchema = z.object({\n name: z.string(),\n description: z.string(),\n fields: z.array(entityFieldSchema),\n indexes: z.array(entityIndexSchema),\n relations: z.array(entityRelationSchema),\n});\n\nexport const databaseDesignSchema = z.object({\n type: z.enum(['mongodb', 'postgresql']),\n reasoning: z.string(),\n entities: z.array(databaseEntitySchema),\n});\n\nexport type EntityField = z.infer<typeof entityFieldSchema>;\nexport type EntityIndex = z.infer<typeof entityIndexSchema>;\nexport type EntityRelation = z.infer<typeof entityRelationSchema>;\nexport type DatabaseEntity = z.infer<typeof databaseEntitySchema>;\nexport type DatabaseDesign = z.infer<typeof databaseDesignSchema>;\n","/**\n * Zod schemas for RequirementContext, ProjectBrief, Question, ChatEntry\n * Note: apiDesign removed -- API design is delegated to the api-designer module.\n */\n\nimport { z } from 'zod';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\n\nexport const projectBriefSchema = z.object({\n name: z.string(),\n goal: z.string(),\n features: z.array(z.string()),\n domain: z.string(),\n database: z.enum(['mongodb', 'postgresql']),\n backendRuntime: z.literal('nodejs'),\n apiStyle: z.enum(['rest', 'graphql']),\n});\n\nexport const questionSchema = z.object({\n id: z.string(),\n question: z.string(),\n context: z.string(),\n suggestions: z.array(z.string()),\n multiSelect: z.boolean(),\n required: z.boolean(),\n});\n\nexport const chatEntrySchema = z.object({\n role: z.enum(['user', 'assistant']),\n content: z.string(),\n});\n\nexport const requirementContextSchema = z.object({\n stage: z.enum(['discovery', 'requirements', 'design', 'complete']),\n projectBrief: projectBriefSchema.nullable(),\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema.nullable(),\n history: z.array(chatEntrySchema),\n pendingQuestions: z.array(questionSchema),\n});\n\nexport type ProjectBrief = z.infer<typeof projectBriefSchema>;\nexport type Question = z.infer<typeof questionSchema>;\nexport type ChatEntry = z.infer<typeof chatEntrySchema>;\nexport type RequirementContext = z.infer<typeof requirementContextSchema>;\n","/**\n * Zod schemas for FinalRequirement, RequirementSummary\n * Note: apiDesign removed -- API design is delegated to the api-designer module.\n */\n\nimport { z } from 'zod';\nimport { projectBriefSchema } from './context.schema';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\n\nexport const requirementSummarySchema = z.object({\n totalActors: z.number(),\n totalFlows: z.number(),\n totalStories: z.number(),\n totalModules: z.number(),\n totalEntities: z.number(),\n overview: z.string(),\n});\n\nexport const finalRequirementSchema = z.object({\n project: projectBriefSchema,\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema,\n summary: requirementSummarySchema,\n});\n\nexport type RequirementSummary = z.infer<typeof requirementSummarySchema>;\nexport type FinalRequirement = z.infer<typeof finalRequirementSchema>;\n","/**\n * System prompt for chat-based requirement gathering\n */\n\nexport const REQUIREMENT_GATHERER_SYSTEM_PROMPT = `You are a senior fullstack developer helping scope and plan a project. Your role is to understand what the user wants to build and produce a clear, actionable requirement document.\n\nYou work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).\n\nThink about the project the way a developer would: core problem, user interactions, data model, auth, integrations, real-time needs. Do NOT ask generic template questions (e.g. scale, complexity level, \"how many users?\"). Ask only questions that directly unblock design decisions.\n\nGuidelines:\n- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.\n- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.\n- Never repeat a question already answered in the conversation history.\n- When the user says \"continue\", \"yes\", \"looks good\", or similar, treat it as confirmation and advance.\n- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).\n- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;\n","/**\n * Discovery stage prompt - understand project and optionally ask questions\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `You are in the discovery stage. Parse the user's message (and prior context) into a structured project brief. Ask clarifying questions only when something genuinely blocks design decisions.\n\nDetermine from the user's words:\n- Project name and goal\n- Key features (array of strings)\n- Domain (e.g. e-commerce, healthcare, saas)\n- API style: \"rest\" | \"graphql\" — infer from context or ask with predefined options\n- Database: \"mongodb\" | \"postgresql\" — ask which they are comfortable with, with predefined options\n- Backend is always \"nodejs\"\n\nQuestion rules:\n- Tech stack (API style, database): Always provide \"suggestions\" with predefined options (e.g. [\"REST\", \"GraphQL\"], [\"MongoDB\", \"PostgreSQL\"]). Frame as \"which are you comfortable with?\"\n- All other questions: Use \"suggestions\": []. Ask open-ended, specific to what the user described (e.g. file uploads, real-time features, auth provider, core user action).\n- Never ask: scale, \"how many users?\", \"what's the complexity?\", or generic intake-form questions.\n- Before asking, check conversation history — never repeat something already answered.\n- If the user's message is clear enough (e.g. \"Instagram clone with photo sharing, messaging, stories\"), infer the obvious and ask only about genuine gaps. If you have enough for the brief, set needsClarification to false and empty questions.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nAnalyze the message and prior context. If you have enough to fill the project brief, return it and set needsClarification to false. Otherwise ask 1-3 short, problem-focused questions.\n\nReturn ONLY valid JSON (no markdown, no explanation) in this shape:\n{\n \"needsClarification\": boolean,\n \"questions\": [\n {\n \"id\": \"q1\",\n \"question\": \"Question text\",\n \"context\": \"Why this helps\",\n \"suggestions\": [],\n \"multiSelect\": false,\n \"required\": true\n }\n ],\n \"conversationalMessage\": \"Brief friendly message to the user\",\n \"projectBrief\": {\n \"name\": \"string\",\n \"goal\": \"string\",\n \"features\": [\"string\"],\n \"domain\": \"string\",\n \"database\": \"mongodb\" | \"postgresql\",\n \"backendRuntime\": \"nodejs\",\n \"apiStyle\": \"rest\" | \"graphql\"\n }\n}\n\nFor tech choices (API style, database), populate \"suggestions\" with the predefined options. For all other questions, use \"suggestions\": [].\nIf needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - actors, flows, stories, modules (chained)\n */\n\nconst PROJECT_BLOCK = `## Project:\n- **Name**: {projectName}\n- **Goal**: {projectGoal}\n- **Features**: {projectFeatures}`;\n\nexport const EXTRACT_ACTORS_PROMPT = `${PROJECT_BLOCK}\n\nIdentify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.\n\nReturn ONLY valid JSON:\n{\n \"actors\": [\n { \"id\": \"actor-1\", \"name\": \"Name\", \"description\": \"Who they are\", \"goals\": [\"goal1\", \"goal2\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_FLOWS_PROMPT = `${PROJECT_BLOCK}\n\n## Actors (JSON):\n{actors}\n\nFor EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.\n\nReturn ONLY valid JSON:\n{\n \"flows\": [\n { \"id\": \"flow-1\", \"actorId\": \"actor-1\", \"name\": \"Flow Name\", \"description\": \"...\", \"trigger\": \"...\", \"outcome\": \"...\" }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_STORIES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n\n## Flows (JSON):\n{flows}\n\nFor EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.\n\nReturn ONLY valid JSON:\n{\n \"stories\": [\n { \"id\": \"story-1\", \"flowId\": \"flow-1\", \"actor\": \"ActorName\", \"action\": \"...\", \"benefit\": \"...\", \"preconditions\": [], \"postconditions\": [], \"dataInvolved\": [\"User.email\", \"Order.total\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const EXTRACT_MODULES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n## Flows: {flows}\n## Stories (JSON):\n{stories}\n\nExtract modules (one per major entity). Each module has apis: create, read, readAll, update, delete plus any extra (e.g. searchUsers). CamelCase names. Clear inputs/outputs.\n\nReturn ONLY valid JSON:\n{\n \"modules\": [\n { \"id\": \"module-1\", \"name\": \"User\", \"description\": \"...\", \"entity\": \"User\", \"apis\": [ { \"id\": \"api-1-1\", \"name\": \"createUser\", \"operation\": \"create\", \"description\": \"...\", \"inputs\": [], \"outputs\": [] } ] }\n ],\n \"summary\": { \"totalModules\": 0, \"totalApis\": 0 },\n \"message\": \"Brief explanation\"\n}`;\n\nexport function buildExtractActorsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string\n): string {\n return EXTRACT_ACTORS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures);\n}\n\nexport function buildGenerateFlowsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string\n): string {\n return GENERATE_FLOWS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson);\n}\n\nexport function buildGenerateStoriesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string\n): string {\n return GENERATE_STORIES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson);\n}\n\nexport function buildExtractModulesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string,\n storiesJson: string\n): string {\n return EXTRACT_MODULES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson)\n .replace('{stories}', storiesJson);\n}\n","/**\n * Design stage prompts - direct LLM invocation for database and API design\n */\n\nconst DESIGN_DB_PROMPT = `You are a database architect. The project brief includes a \"database\" field (mongodb or postgresql)—use that database. Do not choose a different one. Output a single JSON object.\n\n## Project brief (includes database: \"mongodb\" | \"postgresql\"):\n{projectBrief}\n\n## Modules (entities and CRUD):\n{modules}\n\n## User stories (data involved):\n{stories}\n\nDesign the schema for the chosen database. For MongoDB use types like ObjectId, string, number, date, array; for PostgreSQL use varchar(n), text, integer, uuid, timestamp, jsonb, and proper foreign key relations.\n\nReturn ONLY valid JSON (no markdown) in this exact shape. Set \"type\" to the database from the project brief.\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences on how the schema fits the project\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"index_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nconst DESIGN_APIS_PROMPT = `You are an API architect for Node.js backends. Design the API according to apiStyle in the project brief.\n\n## Project brief (includes apiStyle: \"rest\" | \"graphql\"):\n{projectBrief}\n\n## Modules:\n{modules}\n\n## Actors:\n{actors}\n\n## Stories:\n{stories}\n\n## Database design (entities and fields):\n{database}\n\nProduce an API design:\n- If apiStyle is \"rest\": include \"rest\" with baseUrl (e.g. \"/api/v1\") and endpoints array. Each endpoint: id, moduleId, method (exactly one of GET, POST, PUT, PATCH, DELETE), path, description, auth (boolean), roles (array of strings), requestBody/responseBody/queryParams (flat object of string keys to string values, or {}). responseBody must always be a flat object, never an array—even for list endpoints use a single object describing the shape (e.g. for GET /users use \"responseBody\": { \"items\": \"array of user objects\", \"total\": \"number\" }).\n- If apiStyle is \"graphql\": include \"graphql\" with types (kind: \"type\" | \"input\" | \"enum\", fields array), queries, mutations. Each operation: name, moduleId, description, auth (boolean), roles (array), args (name, type, required boolean), returnType.\n\nReturn ONLY valid JSON (no markdown, no code fences). Required shape:\n{\n \"style\": \"rest\" or \"graphql\",\n \"rest\": { \"baseUrl\": \"/api/v1\", \"endpoints\": [ { \"id\": \"ep-1\", \"moduleId\": \"module-1\", \"method\": \"GET\", \"path\": \"/users\", \"description\": \"List users\", \"auth\": true, \"roles\": [], \"requestBody\": {}, \"responseBody\": { \"items\": \"array of user objects\", \"total\": \"number\" }, \"queryParams\": {} } ] },\n \"graphql\": { \"types\": [], \"queries\": [], \"mutations\": [] }\n}\n- Use lowercase \"rest\" or \"graphql\" for style. Omit the branch not used (omit \"graphql\" when style is \"rest\", omit \"rest\" when style is \"graphql\").`;\n\nexport const DESIGN_DATABASE_SYSTEM_PROMPT =\n 'You output only valid JSON. No markdown, no explanation.';\n\nexport const DESIGN_APIS_SYSTEM_PROMPT = 'You output only valid JSON. No markdown, no explanation.';\n\nexport function buildDesignDatabasePrompt(\n projectBrief: string,\n modules: string,\n stories: string\n): string {\n return DESIGN_DB_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{stories}', stories);\n}\n\nexport function buildDesignApisPrompt(\n projectBrief: string,\n modules: string,\n actors: string,\n stories: string,\n database: string\n): string {\n return DESIGN_APIS_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{actors}', actors)\n .replace('{stories}', stories)\n .replace('{database}', database);\n}\n","/**\n * Synthesis stage prompt - compile FinalRequirement document\n * Note: apiDesign removed; API design is delegated to the api-designer module.\n */\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `You are in the complete stage. You have the full context: project brief, actors, flows, stories, modules, and database design. Your job is to produce a single final requirement document (JSON) that matches the FinalRequirement schema, with a summary that includes totalActors, totalFlows, totalStories, totalModules, totalEntities, and a short overview paragraph.`;\n\nexport const SYNTHESIS_USER_PROMPT = `## Project brief (JSON):\n{projectBrief}\n\n## Actors (JSON):\n{actors}\n\n## Flows (JSON):\n{flows}\n\n## Stories (JSON):\n{stories}\n\n## Modules (JSON):\n{modules}\n\n## Database design (JSON):\n{database}\n\nCompile the above into one FinalRequirement JSON. Include a \"summary\" object with: totalActors, totalFlows, totalStories, totalModules, totalEntities (from database.entities.length), and \"overview\" (2-4 sentence paragraph summarizing the project and tech choices).\n\nReturn ONLY valid JSON in this shape (no markdown, no extra text):\n{\n \"project\": { ... },\n \"actors\": [ ... ],\n \"flows\": [ ... ],\n \"stories\": [ ... ],\n \"modules\": [ ... ],\n \"database\": { ... },\n \"summary\": {\n \"totalActors\": 0,\n \"totalFlows\": 0,\n \"totalStories\": 0,\n \"totalModules\": 0,\n \"totalEntities\": 0,\n \"overview\": \"string\"\n }\n}`;\n\nexport function buildSynthesisPrompt(\n projectBrief: string,\n actors: string,\n flows: string,\n stories: string,\n modules: string,\n database: string\n): string {\n return SYNTHESIS_USER_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{actors}', actors)\n .replace('{flows}', flows)\n .replace('{stories}', stories)\n .replace('{modules}', modules)\n .replace('{database}', database);\n}\n","/**\n * Context management for requirement chat\n */\n\nimport type { RequirementContext, StageResult, Stage, ChatEntry } from './types';\n\nexport function createInitialContext(): RequirementContext {\n return {\n stage: 'discovery',\n projectBrief: null,\n actors: [],\n flows: [],\n stories: [],\n modules: [],\n database: null,\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: RequirementContext,\n result: StageResult\n): RequirementContext {\n const data = result.data;\n return {\n ...context,\n ...(data.stage !== undefined && { stage: data.stage }),\n ...(data.projectBrief !== undefined && { projectBrief: data.projectBrief }),\n ...(data.actors !== undefined && { actors: data.actors }),\n ...(data.flows !== undefined && { flows: data.flows }),\n ...(data.stories !== undefined && { stories: data.stories }),\n ...(data.modules !== undefined && { modules: data.modules }),\n ...(data.database !== undefined && { database: data.database }),\n ...(data.pendingQuestions !== undefined && { pendingQuestions: data.pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: RequirementContext,\n role: 'user' | 'assistant',\n content: string\n): RequirementContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: RequirementContext): RequirementContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Stage processor interface and shared helpers\n */\n\nimport type { RequirementContext, Module, Story } from '../types';\n\nexport type { StageProcessor } from '../types';\n\n/** Summarize modules for token-efficient prompts (name, entity, API count) */\nexport function summarizeModules(modules: Module[]): string {\n return modules.map(m => `${m.name}: ${m.entity} (${m.apis.length} APIs)`).join('\\n');\n}\n\n/** Summarize stories for token-efficient prompts (actor + action) */\nexport function summarizeStories(stories: Story[]): string {\n return stories.map(s => `- ${s.actor}: ${s.action}`).join('\\n');\n}\n\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\nexport function safeParseJson(\n text: string\n): { success: true; data: unknown } | { success: false; error: string } {\n try {\n return { success: true, data: JSON.parse(text) };\n } catch (e) {\n return {\n success: false,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n\n/** Build a short text summary of context for inclusion in prompts */\nexport function buildContextSummary(ctx: RequirementContext): string {\n const parts: string[] = [];\n if (ctx.projectBrief) {\n parts.push(\n `Project: ${ctx.projectBrief.name}, Goal: ${ctx.projectBrief.goal}, API: ${ctx.projectBrief.apiStyle}`\n );\n }\n if (ctx.actors.length) parts.push(`Actors: ${ctx.actors.length}`);\n if (ctx.flows.length) parts.push(`Flows: ${ctx.flows.length}`);\n if (ctx.stories.length) parts.push(`Stories: ${ctx.stories.length}`);\n if (ctx.modules.length) parts.push(`Modules: ${ctx.modules.length}`);\n if (ctx.database) parts.push(`Database: ${ctx.database.type}`);\n return parts.join('. ') || 'No context yet';\n}\n\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n","/**\n * Discovery stage - understand project, optional clarifying questions\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { projectBriefSchema, questionSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { DISCOVERY_SYSTEM_FRAGMENT, buildDiscoveryPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n const history = context.history\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Discovery response was not valid JSON', { error: parsed.error });\n return {\n message: \"I couldn't parse that. Could you describe your project in a few sentences?\",\n advance: false,\n data: {},\n };\n }\n const data = parsed.data as {\n needsClarification?: boolean;\n questions?: unknown[];\n conversationalMessage?: string;\n projectBrief?: unknown;\n };\n const message =\n data.conversationalMessage ?? response.text?.slice(0, 500) ?? 'Thanks for the details.';\n const needsClarification = data.needsClarification === true;\n const questions: RequirementContext['pendingQuestions'] = [];\n if (Array.isArray(data.questions)) {\n for (const q of data.questions) {\n const validated = questionSchema.safeParse(q);\n if (validated.success) questions.push(validated.data);\n }\n }\n let projectBrief: RequirementContext['projectBrief'] = null;\n if (data.projectBrief && !needsClarification) {\n const pb = projectBriefSchema.safeParse(data.projectBrief);\n if (pb.success) projectBrief = pb.data;\n }\n logger?.debug('Discovery stage complete', {\n advance: !needsClarification && projectBrief !== null,\n hasProjectBrief: !!projectBrief,\n questionsCount: questions.length,\n });\n return {\n message,\n questions: questions.length ? questions : undefined,\n advance: !needsClarification && projectBrief !== null,\n data: {\n ...(projectBrief && { projectBrief }),\n pendingQuestions: questions,\n },\n };\n}\n","/**\n * Requirements stage: structured output via invokeObject, or invoke + parse\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { ActorResult, FlowsResult, StoriesResult, ModulesResult } from '../schemas';\nimport {\n actorsResultSchema,\n flowsResultSchema,\n storiesResultSchema,\n modulesResultSchema,\n} from '../schemas';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function getActors(\n model: Model,\n messages: ModelMessage[],\n _logger?: Logger\n): Promise<ActorResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ActorResult>(messages, actorsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 4096,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Actors: ${parsed.error}`);\n const validated = actorsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Actors schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getFlows(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _logger?: Logger\n): Promise<FlowsResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<FlowsResult>(messages, flowsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 8192,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 8192 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Flows: ${parsed.error}`);\n const validated = flowsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Flows schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getStories(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _logger?: Logger\n): Promise<StoriesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<StoriesResult>(messages, storiesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Stories: ${parsed.error}`);\n const validated = storiesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Stories schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getModules(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _stories: StoriesResult['stories'],\n _logger?: Logger\n): Promise<ModulesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ModulesResult>(messages, modulesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Modules: ${parsed.error}`);\n const validated = modulesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Modules schema: ${validated.error.message}`);\n return validated.data;\n}\n","/**\n * Requirements stage - chain actors -> flows -> stories -> modules\n * Uses AI SDK structured output (invokeObject); no fallback data.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { RequirementContext, StageResult } from '../types';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport {\n buildExtractActorsPrompt,\n buildGenerateFlowsPrompt,\n buildGenerateStoriesPrompt,\n buildExtractModulesPrompt,\n} from '../prompts';\nimport { getActors, getFlows, getStories, getModules } from './requirements-invoke';\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Requirements stage started');\n\n const brief = context.projectBrief;\n if (!brief) {\n return {\n message: 'Project brief is missing. Complete discovery first.',\n advance: false,\n data: {},\n };\n }\n const projectName = brief.name;\n const projectGoal = brief.goal;\n const projectFeatures = brief.features.join('. ');\n\n const messages: ModelMessage[] = [\n { role: 'system', content: REQUIREMENT_GATHERER_SYSTEM_PROMPT },\n ];\n\n try {\n messages.push({\n role: 'user',\n content: buildExtractActorsPrompt(projectName, projectGoal, projectFeatures),\n });\n const actorsResult = await getActors(model, messages, logger);\n const actors = actorsResult.actors;\n logger?.debug('Requirements: actors', { count: actors.length });\n\n messages.push({\n role: 'assistant',\n content: `[Extracted ${actors.length} actors]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateFlowsPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors)\n ),\n });\n const flowsResult = await getFlows(model, messages, actors, logger);\n const flows = flowsResult.flows;\n logger?.debug('Requirements: flows', { count: flows.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${flows.length} flows]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateStoriesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows)\n ),\n });\n const storiesResult = await getStories(model, messages, actors, flows, logger);\n const stories = storiesResult.stories;\n logger?.debug('Requirements: stories', { count: stories.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${stories.length} stories]`,\n });\n messages.push({\n role: 'user',\n content: buildExtractModulesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows),\n JSON.stringify(stories)\n ),\n });\n const modulesResult = await getModules(model, messages, actors, flows, stories, logger);\n const modules = modulesResult.modules;\n logger?.debug('Requirements stage complete', {\n actors: actors.length,\n flows: flows.length,\n stories: stories.length,\n modules: modules.length,\n });\n\n return {\n message: `I've identified ${actors.length} actors, ${flows.length} flows, ${stories.length} stories, and ${modules.length} modules. Proceeding to technical design.`,\n advance: true,\n data: { actors, flows, stories, modules, pendingQuestions: [] },\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger?.warn('Requirements stage failed', { error: message });\n return {\n message: `Requirements step failed: ${message}. Please try again.`,\n advance: false,\n data: {},\n };\n }\n}\n","/**\n * Design stage - direct LLM call for database design (prompt chaining)\n * Note: API design removed; delegated to the api-designer module downstream.\n */\n\nimport { z } from 'zod';\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { databaseDesignSchema } from '../schemas';\nimport { extractJson, safeParseJson, summarizeModules, summarizeStories } from './base';\nimport { DESIGN_DATABASE_SYSTEM_PROMPT, buildDesignDatabasePrompt } from '../prompts';\n\nexport async function runDesignStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n const brief = context.projectBrief;\n if (!brief) {\n return { message: 'Project brief is missing.', advance: false, data: {} };\n }\n if (!context.modules.length || !context.stories.length) {\n return {\n message: 'Requirements (modules and stories) are missing. Run requirements stage first.',\n advance: false,\n data: {},\n };\n }\n\n logger?.info('Design stage: database design', {\n modules: context.modules.length,\n stories: context.stories.length,\n });\n\n const projectBriefStr = JSON.stringify(brief);\n const modulesSummary = summarizeModules(context.modules);\n const storiesSummary = summarizeStories(context.stories);\n\n const dbPrompt = buildDesignDatabasePrompt(projectBriefStr, modulesSummary, storiesSummary);\n const dbMessages = [\n { role: 'system' as const, content: DESIGN_DATABASE_SYSTEM_PROMPT },\n { role: 'user' as const, content: dbPrompt },\n ];\n const dbResponse = await model.invoke(dbMessages, {\n temperature: 0.3,\n maxOutputTokens: 8192,\n });\n const dbJsonStr = extractJson(dbResponse.text);\n const dbParsed = safeParseJson(dbJsonStr);\n if (!dbParsed.success) {\n logger?.warn('Database design response was not valid JSON', { error: dbParsed.error });\n return {\n message: 'Failed to parse database design response. Please try again.',\n advance: false,\n data: {},\n };\n }\n const databaseResult = databaseDesignSchema.safeParse(dbParsed.data);\n if (!databaseResult.success) {\n const err = databaseResult.error;\n logger?.warn('Database design schema validation failed', { error: z.treeifyError(err) });\n return {\n message: 'Failed to produce database design. Please try again.',\n advance: false,\n data: {},\n };\n }\n const database = databaseResult.data;\n\n return {\n message: `Database design complete: ${database.type}. API design will be handled by the api-designer module.`,\n advance: true,\n data: { database, pendingQuestions: [] },\n };\n}\n","/**\n * Synthesis stage - compile FinalRequirement document\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport type { FinalRequirement } from '../types';\nimport { finalRequirementSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Synthesis stage started');\n\n const brief = context.projectBrief;\n if (!brief || !context.database) {\n return {\n message: 'Missing project brief or database design. Complete earlier stages first.',\n advance: false,\n data: {},\n };\n }\n const prompt = buildSynthesisPrompt(\n JSON.stringify(brief),\n JSON.stringify(context.actors),\n JSON.stringify(context.flows),\n JSON.stringify(context.stories),\n JSON.stringify(context.modules),\n JSON.stringify(context.database)\n );\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Synthesis response was not valid JSON', { error: parsed.error });\n return {\n message: 'Failed to compile final requirement document. Please try again.',\n advance: false,\n data: {},\n };\n }\n const validated = finalRequirementSchema.safeParse(parsed.data);\n if (!validated.success) {\n logger?.warn('Synthesis: final requirement schema validation failed', {\n error: validated.error.message,\n });\n return {\n message: 'Final document did not match schema. ' + (response.text?.slice(0, 300) ?? ''),\n advance: false,\n data: {},\n };\n }\n const finalRequirement: FinalRequirement = validated.data;\n logger?.info('Synthesis stage complete', { overview: finalRequirement.summary?.overview });\n return {\n message: `Requirement document ready. ${finalRequirement.summary.overview}`,\n advance: true,\n data: { finalRequirement },\n };\n}\n","/**\n * Discovery stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements RequirementStageState {\n readonly stageName: Stage = 'discovery';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'requirements';\n }\n}\n","/**\n * Requirements stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements RequirementStageState {\n readonly stageName: Stage = 'requirements';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'design';\n }\n}\n","/**\n * Design stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements RequirementStageState {\n readonly stageName: Stage = 'design';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'complete';\n }\n}\n","/**\n * Synthesis (complete) stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements RequirementStageState {\n readonly stageName: Stage = 'complete';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return null;\n }\n}\n","/**\n * Registry: map Stage (string) to State instance for State pattern routing.\n */\n\nimport type { Stage } from '../types';\nimport type { RequirementStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, RequirementStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): RequirementStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { RequirementContext, Stage, FinalRequirement } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\n/**\n * Determine which stage to run for this turn.\n */\nexport function getStageForTurn(context: RequirementContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern: get state for context.stage, process, merge result.\n * If result.advance, context.stage is advanced to the next state's stage name.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n questions: RequirementContext['pendingQuestions'];\n advance: boolean;\n data: RequirementContext;\n finalRequirement?: FinalRequirement;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const finalReq = 'finalRequirement' in result.data ? result.data.finalRequirement : undefined;\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasFinalRequirement: !!finalReq,\n });\n const data: RequirementContext = {\n ...merged,\n pendingQuestions: result.questions ?? merged.pendingQuestions,\n };\n return {\n message: result.message,\n questions: result.questions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n finalRequirement: finalReq,\n };\n}\n\n/**\n * Whether the user message is a confirmation (continue / yes / looks good)\n */\nexport { isConfirmation };\n\n/**\n * Advance context to next stage\n */\nexport { advanceStage };\n\n/**\n * Add a chat entry to context history\n */\nexport { addChatEntry };\n","/**\n * processRequirementChat - main entry point for chat-based requirement gathering\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { RequirementContext, ChatTurnResult, RequirementChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processRequirementChat(\n userMessage: string,\n context: RequirementContext | null,\n config: RequirementChatConfig\n): Promise<ChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: RequirementContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let questions: RequirementContext['pendingQuestions'] = [];\n let finalRequirement: ChatTurnResult['finalRequirement'] = null;\n\n const runOne = async (\n stage: Stage\n ): Promise<{ advance: boolean; finalReq?: ChatTurnResult['finalRequirement'] }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n questions = result.questions;\n ctx = result.data;\n if (result.finalRequirement) finalRequirement = result.finalRequirement;\n return { advance: result.advance, finalReq: result.finalRequirement };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n\n while (runResult.advance && !finalRequirement) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Chat turn done', { stage, hasFinalRequirement: !!finalRequirement });\n return {\n message,\n context: ctx,\n questions,\n finalRequirement,\n };\n}\n","/**\n * runRequirementGathererAgent - one-shot wrapper around processRequirementChat\n * Runs the full chat flow non-interactively, auto-advancing with \"continue\" when questions are asked.\n */\n\nimport type { RequirementGathererAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processRequirementChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the requirement gatherer in one-shot mode: single input, auto-advance through stages,\n * return final requirement document or last message as AgentResult.\n */\nexport async function runRequirementGathererAgent(\n config: RequirementGathererAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting requirement gatherer agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processRequirementChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.finalRequirement && turns < MAX_TURNS) {\n logger?.debug('Requirement gatherer turn', { turn: turns });\n lastResult = await processRequirementChat('continue', context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.finalRequirement\n ? JSON.stringify(lastResult.finalRequirement, null, 2)\n : lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Requirement gatherer agent completed', {\n turns,\n hasFinalRequirement: !!lastResult.finalRequirement,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * Builder for RequirementContext - fluent API, max 150 lines.\n */\n\nimport type {\n RequirementContext,\n Stage,\n ProjectBrief,\n Actor,\n Flow,\n Story,\n Module,\n DatabaseDesign,\n ChatEntry,\n Question,\n} from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nexport class RequirementContextBuilder {\n private data: Partial<RequirementContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectBrief(projectBrief: ProjectBrief | null): this {\n this.data.projectBrief = projectBrief;\n return this;\n }\n\n withActors(actors: Actor[]): this {\n this.data.actors = actors;\n return this;\n }\n\n withFlows(flows: Flow[]): this {\n this.data.flows = flows;\n return this;\n }\n\n withStories(stories: Story[]): this {\n this.data.stories = stories;\n return this;\n }\n\n withModules(modules: Module[]): this {\n this.data.modules = modules;\n return this;\n }\n\n withDatabase(database: DatabaseDesign | null): this {\n this.data.database = database;\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: Question[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): RequirementContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectBrief: this.data.projectBrief ?? null,\n actors: this.data.actors ?? [],\n flows: this.data.flows ?? [],\n stories: this.data.stories ?? [],\n modules: this.data.modules ?? [],\n database: this.data.database ?? null,\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createRequirementContextBuilder(): RequirementContextBuilder {\n return new RequirementContextBuilder();\n}\n","/**\n * Context management for planning chat\n */\n\nimport type { PlanningContext, PlanStageResult, PlanSections, Stage, ChatEntry } from './types';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport function createInitialContext(): PlanningContext {\n return {\n stage: 'discovery',\n projectDescription: null,\n sections: { ...EMPTY_SECTIONS },\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: PlanningContext,\n result: PlanStageResult\n): PlanningContext {\n const { sections: newSections, projectDescription, pendingQuestions } = result;\n const sections: PlanSections = { ...context.sections };\n if (newSections) {\n for (const key of Object.keys(newSections) as (keyof PlanSections)[]) {\n const v = newSections[key];\n if (v !== undefined && v !== null) sections[key] = v;\n }\n }\n return {\n ...context,\n ...(projectDescription !== undefined && { projectDescription }),\n sections,\n ...(pendingQuestions !== undefined && { pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: PlanningContext,\n role: 'user' | 'assistant',\n content: string\n): PlanningContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: PlanningContext): PlanningContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Shared utilities for planning stages - no JSON extraction or parsing\n */\n\nimport type { PlanningContext } from '../types';\n\n/** Whether the user message is a confirmation (continue / yes / looks good) */\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n\n/** Build a short text summary of context for logging */\nexport function buildContextSummary(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push('Project description set');\n const sections = Object.entries(ctx.sections).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].length > 0\n );\n if (sections.length) parts.push(`Sections: ${sections.map(([k]) => k).join(', ')}`);\n return parts.join('. ') || 'No context yet';\n}\n","/**\n * System prompt for planning module - markdown-only, pro-level output\n */\n\nexport const PLANNING_SYSTEM_PROMPT = `You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.\n\nCRITICAL RULES:\n- Output ONLY raw markdown text. Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets. No JSON or structured data outside those code blocks.\n- Use consistent structure: ## for main sections, ### for subsections, #### for per-item headings (e.g. per route, per endpoint). Use **bold** for labels (e.g. **Purpose**, **Request Body**, **Response on Success**).\n- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows. Every section should give enough detail to implement from the plan alone.`;\n","/**\n * Discovery stage prompt - understand project, ask questions; pro format when ready\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `You are in the discovery stage. Your goal is to understand what the user wants to build.\n\nRespond in natural language only. Do NOT output JSON.\n\n- If you need more information: ask 1-3 short, specific questions. Focus on tech choices (REST vs GraphQL, MongoDB vs PostgreSQL) and any gaps that block design.\n- When you have enough to proceed: output the project overview in this exact pro format so it matches the rest of the plan:\n - **## Overview** — One paragraph (2–4 sentences) summarizing the project and its purpose.\n - **## Core Features** — Numbered list: 1. **Feature Name** - Short description. (one line per feature)\n - **## Tech Stack** — Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.\n\nWhen the user says \"continue\", \"yes\", \"looks good\", or similar, treat it as confirmation to proceed. Do NOT keep asking questions. Make reasonable assumptions for any missing details (choose sensible defaults for tech stack, features, scope, etc.) and immediately output the project overview in the format above.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nRespond in plain markdown. Either ask clarifying questions, or if you have enough information, output the project overview in pro format: ## Overview (one paragraph), ## Core Features (numbered list with **Feature Name** - description), ## Tech Stack (bullets with **Category**: detail). Do NOT output JSON.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - pro-level markdown sections\n */\n\nconst CONTEXT_BLOCK = `## Project description / context:\n{context}`;\n\nexport const REQUIREMENTS_OVERVIEW_PROMPT = `${CONTEXT_BLOCK}\n\nUsing the project description above, write two markdown sections in this exact format:\n\n1. **## Overview** — One paragraph only (2–4 sentences) summarizing the project and its purpose.\n2. **## Tech Stack** — Bullet list with category labels: - **Frontend**: ... (include framework and versions if applicable, e.g. Next.js 16, React 19, TypeScript, Tailwind v4), - **Database**: ... (e.g. MongoDB with Mongoose), - **Authentication**: ... (e.g. JWT in HTTP-only cookies, bcrypt), - **API**: ... (REST or GraphQL), - **Backend**: ... Include versions and key libraries where applicable.\n\nOutput only these two sections in markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_FEATURE_DATA_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written (Overview + Tech Stack):\n{overviewAndTechStack}\n\nWrite the next two markdown sections in this exact format:\n\n1. **## Feature Decisions** — Use ### per feature/area (e.g. ### Workout Tracking, ### Nutrition Tracking). Under each, bullets for key product decisions; use sub-bullets for options where relevant (e.g. goal types: weight, strength, consistency, custom).\n2. **## Data Models** — For each entity use ### EntityName. For each field use exactly one line: \\`field_name\\`: description (type, required/optional, unique if applicable). For references write \"Reference to EntityName\". Include User, profile/settings, and all domain entities.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_PAGES_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Pages and Routes**\n- **### Public Pages (No Authentication Required)** and **### Protected Pages (Authentication Required)**.\n- For each page use: #### \\`/path\\` - Page Title\n- Under each page, include bullets for: purpose, form fields and validation (e.g. \"Form validation: Required fields, valid email format\"), buttons/actions, empty states, redirects on success/error (e.g. \"On success: Redirect to /dashboard\"), key UI (cards, sidebar, charts). Match the depth of a pro implementation spec so a developer can build the page from this alone.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_AUTH_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Authentication Flow** — Use these subsections: ### Sign Up Flow, ### Login Flow, ### Logout Flow, ### Protected Route Middleware, ### API Authentication Middleware.\n- Use **numbered steps** in each flow. Include both frontend and backend steps (e.g. \"4. Frontend sends POST to /api/auth/signup with { name, email, password }\", \"5. Backend validates input\", \"6. Backend hashes password with bcrypt (10 rounds)\", \"7. Backend sets JWT in HTTP-only cookie (name, maxAge, httpOnly, secure, sameSite)\").\n- For middleware: steps for cookie check, JWT verify, attach userId to request, return 401 when invalid.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildRequirementsOverviewPrompt(context: string): string {\n return REQUIREMENTS_OVERVIEW_PROMPT.replace('{context}', context);\n}\n\nexport function buildRequirementsFeatureDataPrompt(\n context: string,\n overviewAndTechStack: string\n): string {\n return REQUIREMENTS_FEATURE_DATA_PROMPT.replace('{context}', context).replace(\n '{overviewAndTechStack}',\n overviewAndTechStack\n );\n}\n\nexport function buildRequirementsPagesPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_PAGES_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n\nexport function buildRequirementsAuthPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_AUTH_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n","/**\n * Design stage prompts - pro-level API routes and implementation details\n */\n\nconst DESIGN_CONTEXT = `## Project context (all sections so far):\n{priorSections}`;\n\nexport const DESIGN_API_ROUTES_PROMPT = `${DESIGN_CONTEXT}\n\nWrite the next markdown section in this exact format:\n\n**## API Routes**\n- Group by domain: ### Authentication Endpoints, ### Exercise Endpoints, ### Workout Endpoints, etc.\n- For each endpoint use: #### METHOD \\`/path\\` (e.g. #### POST \\`/api/auth/signup\\`)\n- Under each endpoint include:\n - **Purpose**: one line\n - **Request Body** or **Query Parameters** (and **Validation** bullets: required, format, lengths)\n - **Response on Success (status)**: code block with example JSON (e.g. 200, 201)\n - **Response on Error**: bullets (e.g. 400 validation, 401, 403, 404, 500 with message)\n - **Side Effects** or **Implementation** where relevant (e.g. \"Creates User and UserProfile; sets auth cookie\")\n- Use code blocks ONLY for request/response JSON examples. No JSON elsewhere.\n\nOutput only markdown. Do NOT output JSON except inside code blocks.`;\n\nexport const DESIGN_IMPLEMENTATION_PROMPT = `${DESIGN_CONTEXT}\n\n## API Routes (already written):\n{apiRoutes}\n\nWrite the next markdown section in this exact format:\n\n**## Implementation Details**\n- **### File Structure** — Full directory tree in a **code block** (e.g. src/app/(auth)/login/page.tsx, src/app/api/auth/signup/route.ts, src/components/..., src/lib/, src/models/). Show the real layout a developer would create.\n- **### Environment Variables** — List with comments (e.g. MONGODB_URI=... # connection string, JWT_SECRET=... # change in production).\n- **### Dependencies to Install** — npm install line and short explanation per dependency (e.g. mongoose: MongoDB ODM; bcryptjs: password hashing; jsonwebtoken: JWT; cookie: cookie parsing).\n- **### Key Setup** — One subsection per concern: **MongoDB connection** (file path, purpose, 3–5 bullets), **JWT utilities** (file path, purpose; cookie name, maxAge, httpOnly, secure; generateToken/verifyToken/setAuthCookie/clearAuthCookie), **Auth middleware** (file path, authenticateRequest behavior), **External API client** if any (file path, purpose).\n- If the plan is UI-heavy, add **### UI Component Guidelines** (controlled inputs, validation, loading/error states) and **### Error Handling Standards** (API error JSON shape, HTTP status codes: 200, 201, 400, 401, 403, 404, 500).\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildDesignApiRoutesPrompt(priorSections: string): string {\n return DESIGN_API_ROUTES_PROMPT.replace('{priorSections}', priorSections);\n}\n\nexport function buildDesignImplementationPrompt(priorSections: string, apiRoutes: string): string {\n return DESIGN_IMPLEMENTATION_PROMPT.replace('{priorSections}', priorSections).replace(\n '{apiRoutes}',\n apiRoutes\n );\n}\n","/**\n * Synthesis stage prompt - pro-level final sections (order matters for splitting)\n */\n\nconst SYNTHESIS_CONTEXT = `## Full plan so far (all sections):\n{priorSections}`;\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `You are in the complete stage. You have the full implementation plan. Output the final sections in markdown, in the exact order specified below, so they can be assembled into the plan.`;\n\nexport const SYNTHESIS_USER_PROMPT = `${SYNTHESIS_CONTEXT}\n\nWrite the following sections in this exact order. Output only markdown. Do NOT output JSON.\n\n**Block 1 — Implementation Order, Current State, Desired End State**\n\n1. **## Implementation Order** — Phased: ### Phase 1: Foundation, ### Phase 2: Authentication, etc. Under each phase, numbered steps (e.g. \"1. Install dependencies\", \"2. Create User model\", \"3. Implement POST /api/auth/signup\", \"4. Create login page\"). Be concrete so a developer can follow step-by-step.\n\n2. **## Current State Analysis** — What the project starts with (e.g. vanilla Next.js, no DB, no auth). Then a short bullet list: \"What needs to be built from scratch\" (all auth, models, API routes, pages, etc.).\n\n3. **## Desired End State** — Short subsections or bullets: (1) For users: what they can do when the app is done; (2) Technical verification: what must work (DB connected, auth working, endpoints returning correct data, etc.); (3) Testing approach: manual flows, API checks, DB checks.\n\n**Block 2 — Edge Cases, Security, Performance, Future Enhancements**\n\n4. **## Edge Cases and Considerations** — ### per area (e.g. ### Authentication, ### Workouts, ### Nutrition, ### Goals, ### Profile, ### General). Under each, bullets for edge cases and how to handle them (e.g. \"Email already exists: return 400 with clear message\"; \"External API down: show error, allow manual entry\").\n\n5. **## Security Considerations** — Numbered list: passwords (bcrypt, min length); JWT (HTTP-only cookie, secure flag, strong secret, expiry); API (verify JWT on protected routes, check resource ownership); env (never commit secrets, different values in production).\n\n6. **## Performance Considerations** — Numbered list: DB (index user id and date fields, lean queries, avoid N+1); API (debounce search, cache external API if applicable); frontend (RSC where possible, lazy load heavy components); optional future caching.\n\n7. **## Future Enhancements (Not in Current Scope)** — Short grouped list (e.g. Social, Analytics, Integrations, Mobile, Premium) so scope is clear. One line per group is enough.\n\n**Block 3 — Manual Testing Checklist**\n\n8. **## Manual Testing Checklist** — ### per flow (e.g. ### Authentication Flow, ### Workout Flow, ### Nutrition Flow, ### Goals Flow, ### Profile Flow). Under each, checklist items: - [ ] Description of what to verify (e.g. \"- [ ] Sign up with valid credentials creates account\", \"- [ ] Login with invalid credentials shows error\").\n\nOutput all eight sections in the order above. Do NOT output JSON.`;\n\nexport function buildSynthesisPrompt(priorSections: string): string {\n return SYNTHESIS_USER_PROMPT.replace('{priorSections}', priorSections);\n}\n","/**\n * System prompt for the edit-plan pipeline.\n * Instructs the LLM to revise an existing plan based on feedback.\n */\n\nexport const EDIT_PLAN_SYSTEM_PROMPT = `You are a senior software architect revising an existing implementation plan.\n\nCRITICAL RULES:\n- You will receive the FULL existing plan and the user's feedback or edit instructions.\n- Output ONLY the complete revised plan in markdown. Do NOT output partial plans, explanations, or commentary.\n- Preserve the same section structure (## headings) as the original plan.\n- Only modify sections that are affected by the feedback. Leave unrelated sections intact.\n- Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets.\n- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows.\n- If the feedback adds new requirements, integrate them into the appropriate existing sections rather than appending a separate section (unless a new section is clearly needed).`;\n\nexport function buildEditPlanPrompt(existingPlan: string, feedback: string): string {\n return `## Existing Plan\\n\\n${existingPlan}\\n\\n---\\n\\n## Edit Instructions\\n\\n${feedback}`;\n}\n","/**\n * Discovery stage - understand project, optional questions; output is raw markdown\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport {\n PLANNING_SYSTEM_PROMPT,\n DISCOVERY_SYSTEM_FRAGMENT,\n buildDiscoveryPrompt,\n} from '../prompts';\nimport { isConfirmation } from './base';\n\n/** Heuristic: response contains project overview (markdown headers we expect when ready to advance) */\nfunction hasProjectOverview(text: string): boolean {\n const t = text.trim();\n if (t.length < 100) return false;\n // Primary: exact markdown headers\n if (t.includes('## Overview') || t.includes('## Core Features')) return true;\n // Secondary: bold-label or h1 variants the LLM might use\n const lower = t.toLowerCase();\n if (\n (lower.includes('overview') || lower.includes('core features')) &&\n (lower.includes('tech stack') || lower.includes('technology'))\n ) {\n return true;\n }\n return false;\n}\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n // Exclude the last entry from history if it duplicates the current userMessage\n // (processPlanningChat calls addChatEntry before runStage)\n const historyEntries = context.history.slice(0, -1);\n const history = historyEntries\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${PLANNING_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const message = response.text?.trim() ?? '';\n\n const hasOverview = hasProjectOverview(message);\n const userConfirmed = isConfirmation(userMessage);\n // Safety net: after enough discovery turns with confirmations, force advance\n const forceAdvance = userConfirmed && context.history.length >= 7 && message.length > 50;\n // Advance when: (1) we got overview, (2) user confirmed & description exists, or (3) safety net\n const advance =\n (hasOverview && (context.projectDescription == null || userConfirmed)) ||\n (userConfirmed && context.projectDescription != null) ||\n forceAdvance;\n const storeDescription = hasOverview || (forceAdvance && message.length > 50);\n\n logger?.debug('Discovery stage complete', {\n advance,\n hasOverview,\n userConfirmed,\n forceAdvance,\n });\n\n return {\n message,\n advance,\n sections: {},\n ...(storeDescription && { projectDescription: message }),\n };\n}\n","/**\n * Discovery state - placeholder until discovery.stage is implemented\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements PlanningStageState {\n readonly stageName = 'discovery' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'requirements' | null {\n return 'requirements';\n }\n}\n","/**\n * entity-analyzer subagent - extracts entities, fields, and relationships from requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENTITY_ANALYZER_SYSTEM_PROMPT = `You are an expert database entity analyst. Your job is to extract data model signals from requirements.\n\nPerform these analyses:\n\n## Entity Discovery\n- List every entity implied by the requirements (users, domain objects, settings, logs).\n- For each entity: name, purpose, key fields (with types), and which user type owns it.\n- Identify status enums from flow transitions (e.g. pending -> active -> completed).\n\n## Field Analysis\n- For each entity, list fields with: name, likely type, required/optional, unique constraints.\n- Identify computed vs stored fields.\n- Note fields that need indexing (lookups, sorting, filtering).\n\n## Relationship Signals\n- List entity pairs that reference each other.\n- Note ownership direction (which entity \"belongs to\" which).\n- Identify potential M:N relationships that may need join tables.\n\nRespond with a clear, structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const entityAnalyzerSubagent = defineSubagent({\n name: 'entity-analyzer',\n description:\n 'Analyzes requirements to extract entities, fields, relationships, and data model signals. Use when you need to understand the data before designing the schema.',\n systemPrompt: ENTITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * relationship-mapper subagent - maps cardinality, foreign keys, indexes\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RELATIONSHIP_MAPPER_SYSTEM_PROMPT = `You are a database relationship specialist. Given a list of entities and their fields, you determine:\n\n## Cardinality Analysis\n- For every entity pair that references each other, classify: 1:1, 1:N, or M:N.\n- Explain the reasoning (e.g. \"A User has many Orders, but an Order belongs to one User -> 1:N\").\n\n## Foreign Key / Reference Strategy\n- For MongoDB: recommend ObjectId references vs embedding. Embed when: data is small, always read together, rarely updated independently.\n- For PostgreSQL: define foreign key columns, ON DELETE behavior (CASCADE, SET NULL, RESTRICT).\n\n## Join Table Design (M:N)\n- When M:N is detected, design the join table with: both foreign keys, any extra fields (e.g. role in a membership), indexes.\n\n## Index Recommendations\n- Suggest compound indexes for common query patterns.\n- Suggest unique indexes for natural keys (email, slug, etc.).\n- Note partial indexes where applicable (e.g. only active records).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const relationshipMapperSubagent = defineSubagent({\n name: 'relationship-mapper',\n description:\n 'Maps cardinality (1:1, 1:N, M:N), foreign keys, join tables, and index recommendations for entity relationships. Use after entity analysis.',\n systemPrompt: RELATIONSHIP_MAPPER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * schema-refiner subagent - reviews schema for completeness and performance\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_REFINER_SYSTEM_PROMPT = `You are an expert database schema reviewer. Your job is to:\n\n1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.\n2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.\n3. Check normalization: no redundant data, proper use of references vs embedding.\n4. Check performance: indexes cover common query patterns, no missing indexes on foreign keys.\n5. Check security: passwords are marked as hashed, sensitive fields noted, no plaintext secrets.\n6. Check conventions: consistent naming (camelCase or snake_case), timestamps on all entities.\n\nIf you have access to the validate_schema tool, use it first. Then provide a detailed review with:\n- Issues found (with severity: critical, warning, suggestion)\n- Specific fixes for each issue\n- Overall assessment (ready / needs work)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport function createSchemaRefinerSubagent() {\n return defineSubagent({\n name: 'schema-refiner',\n description:\n 'Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.',\n systemPrompt: SCHEMA_REFINER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 3,\n });\n}\n","/**\n * page-planner subagent - designs page structure, routes, and layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst PAGE_PLANNER_SYSTEM_PROMPT = `You are a UX-focused frontend architect. You design detailed page specifications.\n\n## Page Planning\nFor each page in the application:\n\n### Route Definition\n- Path (e.g. /login, /dashboard, /workouts/:id)\n- Access level: public (no auth) or protected (requires auth)\n- Page name and purpose (one sentence)\n\n### Page Detail\n- **Form fields**: name, type (text, email, password, number, select, textarea, date, checkbox), required flag, validation rule.\n- **Actions**: buttons and what they do (e.g. \"Submit form\", \"Delete item\", \"Export CSV\").\n- **Empty state**: what to show when there's no data (e.g. \"No workouts yet. Click + to add one.\").\n- **Error state**: how to handle errors (e.g. \"Show inline validation errors\", \"Toast notification\").\n- **Redirect on success**: where to go after successful action (e.g. \"/dashboard\").\n- **Key UI elements**: cards, tables, charts, sidebar, modals, tabs.\n\n### Page Grouping\n- Group by access: public pages first, then protected.\n- Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.\n\nRespond with structured page specs. Do NOT return JSON.`;\n\nexport const pagePlannerSubagent = defineSubagent({\n name: 'page-planner',\n description:\n 'Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.',\n systemPrompt: PAGE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * component-analyzer subagent - identifies reusable components and shared layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst COMPONENT_ANALYZER_SYSTEM_PROMPT = `You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.\n\n## Component Identification\n- **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.\n- **Navigation components**: navbar, sidebar, breadcrumbs, mobile menu.\n- **Form components**: reusable form inputs, form wrappers, validation display.\n- **Display components**: cards, tables, lists, stat widgets, charts, badges.\n- **Shared components**: modals, toasts, loading spinners, empty state illustrations, error boundaries.\n\n## Component Analysis\nFor each component:\n- Name (PascalCase)\n- Type: layout, shared, form, display, navigation\n- Purpose (one sentence)\n- Props it accepts (e.g. \"user\", \"items\", \"onSubmit\", \"isLoading\")\n- Which pages use it\n\n## State Management\n- Identify which state is per-page (form state, UI state) vs global (auth state, user preferences).\n- Recommend server vs client state strategy.\n- Identify data fetching patterns (on mount, on action, real-time).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const componentAnalyzerSubagent = defineSubagent({\n name: 'component-analyzer',\n description:\n 'Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.',\n systemPrompt: COMPONENT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - recommends React/Vite or Next.js\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.\n\n## Decision Criteria\n\n### Choose \"react-vite\" (Vite + React SPA) when:\n- The app is a single-page application (SPA) behind authentication\n- No SEO requirements (admin dashboards, internal tools, B2B apps)\n- Backend is a separate API (GraphQL or REST) already built\n- Simple routing with client-side navigation\n- Team prefers traditional React patterns (hooks, context)\n\n### Choose \"nextjs\" (Next.js App Router) when:\n- SEO is important (marketing pages, blogs, e-commerce storefronts)\n- Need server-side rendering (SSR) or static site generation (SSG)\n- Want unified frontend + API in one project (server actions, API routes)\n- Need streaming and progressive rendering\n- Complex data fetching with caching requirements\n- Mix of public and authenticated pages\n\n## Output Format\nState your recommendation clearly:\n- Framework: react-vite | nextjs\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you would lose with the alternative\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends React/Vite SPA or Next.js. Use to determine the frontend framework before delegating to a builder.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * security-analyzer subagent - analyzes security requirements and threat vectors\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SECURITY_ANALYZER_SYSTEM_PROMPT = `You are a web security specialist. You analyze project requirements for security concerns and design security policies.\n\n## Authentication Analysis\n- Determine the best auth strategy (JWT, session, OAuth) based on requirements.\n- JWT: token expiry, refresh strategy, cookie vs header, httpOnly/secure/sameSite flags.\n- Session: session store (memory, Redis, DB), cookie config, session expiry.\n- OAuth: which providers, callback flow, token exchange, account linking.\n\n## Password Security\n- Hashing algorithm (bcrypt recommended), cost factor (10+ rounds).\n- Password requirements: minimum length, complexity rules.\n- Password reset flow: token generation, expiry, one-time use.\n\n## Authorization Analysis\n- Identify role hierarchy (e.g. admin > moderator > user).\n- Map roles to permissions per resource (CRUD matrix).\n- Resource ownership checks (users can only modify their own data).\n\n## Threat Analysis\n- Rate limiting: login attempts, API calls, password reset requests.\n- CORS: allowed origins, methods, headers.\n- Input sanitization: XSS prevention, SQL injection prevention.\n- Brute force protection: account lockout, exponential backoff.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const securityAnalyzerSubagent = defineSubagent({\n name: 'security-analyzer',\n description:\n 'Analyzes security requirements, threat vectors, and designs security policies. Use to understand auth needs before designing flows.',\n systemPrompt: SECURITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * flow-designer subagent - designs step-by-step auth flows\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FLOW_DESIGNER_SYSTEM_PROMPT = `You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.\n\nFor each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):\n\n## Flow Design Pattern\n1. Number each step sequentially.\n2. Mark each step as \"frontend\" or \"backend\".\n3. Describe the action clearly (e.g. \"Frontend sends POST to /api/auth/signup with { name, email, password }\").\n4. Include implementation details (e.g. \"Backend hashes password with bcrypt (10 rounds)\").\n\n## Signup Flow\n- Frontend: form validation, submit request.\n- Backend: validate input, check existing user, hash password, create user + profile, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Login Flow\n- Frontend: form validation, submit credentials.\n- Backend: find user, compare password hash, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Password Reset Flow\n- Frontend: request reset (email).\n- Backend: generate reset token, send email.\n- Frontend: enter new password with token.\n- Backend: validate token, hash new password, update user, invalidate token.\n\n## Middleware Flows\n- Protected route: check cookie/header, verify token, attach user to request, reject if invalid.\n- API auth: same as above but for API routes, return 401 JSON.\n\nRespond with structured numbered flows. Do NOT return JSON.`;\n\nexport const flowDesignerSubagent = defineSubagent({\n name: 'flow-designer',\n description:\n 'Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.',\n systemPrompt: FLOW_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Requirements stage - delegates to specialist agents:\n * data-modeler (data models), auth-designer (auth flow), frontend-architect (pages/routes)\n * Overview, tech stack, and feature decisions use direct LLM calls for markdown output.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildRequirementsOverviewPrompt, buildRequirementsFeatureDataPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { entityAnalyzerSubagent } from '../../data-modeler/subagents';\nimport { pagePlannerSubagent } from '../../frontend-architect/subagents';\nimport { flowDesignerSubagent } from '../../auth-designer/subagents';\n\nfunction invokeMarkdown(model: Model, systemPrompt: string, userPrompt: string): Promise<string> {\n const messages = [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: userPrompt },\n ];\n return model\n .invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 })\n .then(r => r.text?.trim() ?? '');\n}\n\nfunction splitOverviewAndTechStack(text: string): { overview: string; techStack: string } {\n const idx = text.indexOf('## Tech Stack');\n if (idx < 0) return { overview: text, techStack: '' };\n return { overview: text.slice(0, idx).trim(), techStack: text.slice(idx).trim() };\n}\n\nfunction splitFeatureDecisionsAndDataModels(text: string): {\n featureDecisions: string;\n dataModels: string;\n} {\n const idx = text.indexOf('## Data Models');\n if (idx < 0) return { featureDecisions: text, dataModels: '' };\n return { featureDecisions: text.slice(0, idx).trim(), dataModels: text.slice(idx).trim() };\n}\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Requirements stage started (specialist agents)');\n\n const ctx = context.projectDescription ?? '';\n if (!ctx) {\n return {\n message: 'No project description yet. Complete discovery first.',\n advance: false,\n sections: {},\n };\n }\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n\n // Part 1: Overview + Tech Stack (direct LLM call)\n const part1 = await invokeMarkdown(model, systemPrompt, buildRequirementsOverviewPrompt(ctx));\n const { overview, techStack } = splitOverviewAndTechStack(part1);\n\n // Part 2: Feature Decisions + Data Models via entity-analyzer specialist\n const part2 = await invokeMarkdown(\n model,\n systemPrompt,\n buildRequirementsFeatureDataPrompt(ctx, part1)\n );\n const { featureDecisions } = splitFeatureDecisionsAndDataModels(part2);\n\n logger?.info('Delegating to data-modeler specialist');\n const dataModelResult = await runSubagent(\n entityAnalyzerSubagent,\n `Analyze the data model for this project:\\n\\n${ctx}\\n\\nFeatures:\\n${featureDecisions}`,\n { parentModel: model }\n );\n const dataModels = dataModelResult.output;\n\n // Part 3: Pages and Routes via frontend-architect specialist\n logger?.info('Delegating to frontend-architect specialist');\n const priorContext = [part1, featureDecisions, dataModels].join('\\n\\n---\\n\\n');\n const pagesResult = await runSubagent(\n pagePlannerSubagent,\n `Design the pages and routes for this project:\\n\\n${ctx}\\n\\nContext:\\n${priorContext}`,\n { parentModel: model }\n );\n const pagesAndRoutes = pagesResult.output;\n\n // Part 4: Auth Flow via auth-designer specialist\n logger?.info('Delegating to auth-designer specialist');\n const fullContext = [priorContext, pagesAndRoutes].join('\\n\\n---\\n\\n');\n const authResult = await runSubagent(\n flowDesignerSubagent,\n `Design the authentication flows for this project:\\n\\n${ctx}\\n\\nContext:\\n${fullContext}`,\n { parentModel: model }\n );\n const authFlow = authResult.output;\n\n logger?.info('Requirements stage complete (specialist agents)');\n return {\n message:\n 'Requirements generated via specialist agents (Data Modeler, Frontend Architect, Auth Designer).',\n advance: true,\n sections: { overview, techStack, featureDecisions, dataModels, pagesAndRoutes, authFlow },\n };\n}\n","/**\n * Requirements state - delegates to requirements stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements PlanningStageState {\n readonly stageName = 'requirements' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'design' | null {\n return 'design';\n }\n}\n","/**\n * endpoint-analyzer subagent - derives API endpoints from data model and requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENDPOINT_ANALYZER_SYSTEM_PROMPT = `You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.\n\n## Endpoint Discovery\n- For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.\n- From user stories/flows, identify custom operations beyond CRUD (e.g. searchUsers, bulkImport, exportCsv, toggleStatus).\n- Group endpoints by resource name (pluralized entity name).\n\n## Route Design\n- Design RESTful routes: POST /resource, GET /resource/:id, GET /resource, PUT /resource/:id, DELETE /resource/:id.\n- For nested resources: GET /users/:userId/orders, POST /users/:userId/orders.\n- For custom operations: POST /resource/:id/actions/activate, GET /resource/search.\n\n## Auth Annotations\n- Mark which endpoints require authentication.\n- Mark which endpoints require specific roles (admin, owner).\n- Identify resource-ownership checks (user can only access their own data).\n\nRespond with structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const endpointAnalyzerSubagent = defineSubagent({\n name: 'endpoint-analyzer',\n description:\n 'Analyzes data model and requirements to derive API endpoints, routes, and auth annotations. Use before generating the API design.',\n systemPrompt: ENDPOINT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * contract-designer subagent - designs request/response contracts per endpoint\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst CONTRACT_DESIGNER_SYSTEM_PROMPT = `You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.\n\n## Request Design\n- For each endpoint, define: required fields, optional fields, field types, validation rules.\n- Validation rules: required, min/max length, email format, enum values, numeric ranges.\n- For list endpoints: pagination (page, limit, offset), sorting (sortBy, order), filtering (query params).\n\n## Response Design\n- Success responses: HTTP status (200, 201, 204), response body shape.\n- For list endpoints: { items: T[], total: number, page: number, limit: number }.\n- For single item: the entity shape with all fields.\n\n## Error Responses\n- 400: validation errors with field-level messages.\n- 401: unauthenticated (missing or invalid token).\n- 403: forbidden (insufficient role or not resource owner).\n- 404: resource not found.\n- 409: conflict (duplicate unique field).\n- 500: internal server error.\n\n## Naming Conventions\n- Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).\n- Use ISO 8601 for dates in responses.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const contractDesignerSubagent = defineSubagent({\n name: 'contract-designer',\n description:\n 'Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.',\n systemPrompt: CONTRACT_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Design stage - delegates to api-designer specialists:\n * endpoint-analyzer (API routes), contract-designer (implementation details)\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildDesignImplementationPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from '../../api-designer/subagents';\n\nfunction gatherPriorSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n if (s.overview) parts.push(s.overview);\n if (s.techStack) parts.push(s.techStack);\n if (s.featureDecisions) parts.push(s.featureDecisions);\n if (s.dataModels) parts.push(s.dataModels);\n if (s.pagesAndRoutes) parts.push(s.pagesAndRoutes);\n if (s.authFlow) parts.push(s.authFlow);\n return parts.join('\\n\\n---\\n\\n');\n}\n\nexport async function runDesignStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Design stage started (specialist agents)');\n\n const priorSections = gatherPriorSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete discovery and requirements first.',\n advance: false,\n sections: {},\n };\n }\n\n // API Routes via endpoint-analyzer specialist\n logger?.info('Delegating to api-designer endpoint-analyzer specialist');\n const apiResult = await runSubagent(\n endpointAnalyzerSubagent,\n `Design the API routes for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const apiRoutes = apiResult.output;\n\n // Implementation Details via contract-designer specialist + direct LLM call\n logger?.info('Delegating to api-designer contract-designer specialist');\n const contractResult = await runSubagent(\n contractDesignerSubagent,\n `Design detailed request/response contracts for these API endpoints:\\n\\n${apiRoutes}\\n\\nProject context:\\n${priorSections}`,\n { parentModel: model }\n );\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const implementation = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n {\n role: 'user' as const,\n content: buildDesignImplementationPrompt(\n priorSections,\n apiRoutes + '\\n\\n' + contractResult.output\n ),\n },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n logger?.info('Design stage complete (specialist agents)');\n return {\n message: 'Design generated via specialist agents (Endpoint Analyzer, Contract Designer).',\n advance: true,\n sections: { apiRoutes, implementation },\n };\n}\n","/**\n * Design state - delegates to design stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements PlanningStageState {\n readonly stageName = 'design' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'complete' | null {\n return 'complete';\n }\n}\n","/**\n * Assemble plan sections into markdown and write to file\n */\n\nimport { writeFile } from 'fs/promises';\nimport type { PlanSections } from './types';\n\nexport function assemblePlan(projectName: string, sections: PlanSections): string {\n const parts: (string | null)[] = [\n `# ${projectName} Implementation Plan\\n`,\n sections.overview,\n sections.techStack,\n sections.featureDecisions,\n '---',\n sections.dataModels,\n '---',\n sections.pagesAndRoutes,\n '---',\n sections.authFlow,\n '---',\n sections.apiRoutes,\n '---',\n sections.implementation,\n '---',\n sections.executionPlan,\n '---',\n sections.edgeCases,\n '---',\n sections.testingChecklist,\n ];\n return parts.filter(Boolean).join('\\n\\n');\n}\n\nexport async function writePlanToFile(markdown: string, outputPath: string): Promise<void> {\n await writeFile(outputPath, markdown, 'utf-8');\n}\n","/**\n * edge-case-analyzer subagent - identifies edge cases per domain area\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst EDGE_CASE_ANALYZER_SYSTEM_PROMPT = `You are a QA-minded tech lead. You identify edge cases that developers often miss.\n\nFor each domain area (Authentication, Data, API, Frontend, Integrations):\n\n## Edge Case Analysis\n- **Scenario**: Describe the edge case concretely (e.g. \"User submits signup form with email that already exists\").\n- **Handling**: How to handle it (e.g. \"Return 400 with message 'Email already in use'\").\n- **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).\n\n## Common Areas to Check\n- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.\n- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.\n- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).\n- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.\n- **Integrations**: external API down, timeout, rate limited, invalid response format.\n\nRespond with structured edge cases grouped by area. Do NOT return JSON.`;\n\nexport const edgeCaseAnalyzerSubagent = defineSubagent({\n name: 'edge-case-analyzer',\n description:\n 'Identifies edge cases per domain area with scenarios, handling strategies, and severity levels. Use for comprehensive edge case analysis.',\n systemPrompt: EDGE_CASE_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * testing-strategist subagent - designs manual testing checklists\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst TESTING_STRATEGIST_SYSTEM_PROMPT = `You are a testing strategy specialist. You design comprehensive manual testing checklists.\n\n## Testing Checklist Design\nGroup test items by flow (Authentication, CRUD operations, Edge cases, etc.).\n\nFor each test item:\n- **Flow name**: which feature flow this tests (e.g. \"Authentication Flow\", \"Workout CRUD Flow\").\n- **Test item**: what to verify (e.g. \"Sign up with valid credentials creates account\").\n- **Expected result**: what should happen (e.g. \"User created in DB, JWT cookie set, redirected to /dashboard\").\n\n## Coverage Areas\n- **Happy paths**: normal user flows work end-to-end.\n- **Validation**: invalid inputs are rejected with clear messages.\n- **Authorization**: users can only access what they should.\n- **Error handling**: errors are caught and displayed properly.\n- **Data integrity**: data is saved correctly, relationships maintained.\n- **UI states**: loading, empty, error, success states display correctly.\n\n## Checklist Format\nPresent as grouped checklist items using markdown checkboxes:\n### Flow Name\n- [ ] Test item description -> Expected result\n\nRespond with structured checklist. Do NOT return JSON.`;\n\nexport const testingStrategistSubagent = defineSubagent({\n name: 'testing-strategist',\n description:\n 'Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.',\n systemPrompt: TESTING_STRATEGIST_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Synthesis stage - delegates to execution-planner specialists:\n * edge-case-analyzer (edge cases), testing-strategist (testing checklist)\n * Then assembles plan.md from all sections.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { assemblePlan } from '../writer';\nimport { runSubagent } from '../../../lib/subagents';\nimport {\n edgeCaseAnalyzerSubagent,\n testingStrategistSubagent,\n} from '../../execution-planner/subagents';\n\nfunction gatherAllSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n [\n s.overview,\n s.techStack,\n s.featureDecisions,\n s.dataModels,\n s.pagesAndRoutes,\n s.authFlow,\n s.apiRoutes,\n s.implementation,\n ].forEach(p => {\n if (p) parts.push(p);\n });\n return parts.join('\\n\\n---\\n\\n');\n}\n\nfunction extractProjectName(ctx: PlanningContext): string {\n const raw = ctx.sections.overview ?? ctx.projectDescription ?? '';\n const firstLine = raw.split('\\n')[0]?.trim() ?? '';\n const regex = /^#+\\s*(.+?)(?:\\s+Implementation Plan)?$/i;\n const match = regex.exec(firstLine);\n if (match?.[1]) return match[1].trim();\n if (firstLine.length > 0 && firstLine.length < 80) return firstLine.replace(/^#+\\s*/, '').trim();\n return 'Project Implementation Plan';\n}\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Synthesis stage started (specialist agents)');\n\n const priorSections = gatherAllSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete earlier stages first.',\n advance: false,\n sections: {},\n };\n }\n\n // Execution plan via direct LLM call (phased implementation order)\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const executionPlan = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: buildSynthesisPrompt(priorSections) },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n // Edge cases via edge-case-analyzer specialist\n logger?.info('Delegating to execution-planner edge-case-analyzer specialist');\n const edgeCaseResult = await runSubagent(\n edgeCaseAnalyzerSubagent,\n `Identify edge cases for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const edgeCases = edgeCaseResult.output;\n\n // Testing checklist via testing-strategist specialist\n logger?.info('Delegating to execution-planner testing-strategist specialist');\n const testingResult = await runSubagent(\n testingStrategistSubagent,\n `Design the manual testing checklist for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const testingChecklist = testingResult.output;\n\n const projectName = extractProjectName(context);\n const fullSections = {\n ...context.sections,\n executionPlan: executionPlan || null,\n edgeCases: edgeCases || null,\n testingChecklist: testingChecklist || null,\n };\n const fullMarkdown = assemblePlan(projectName, fullSections);\n\n logger?.info('Synthesis stage complete (specialist agents)', { projectName });\n return {\n message: `Plan complete: ${projectName}. Generated via specialist agents.`,\n advance: true,\n sections: { executionPlan, edgeCases, testingChecklist },\n planMarkdown: fullMarkdown,\n };\n}\n","/**\n * Synthesis state - delegates to synthesis stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements PlanningStageState {\n readonly stageName = 'complete' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): null {\n return null;\n }\n}\n","/**\n * Registry: map Stage to State instance for State pattern routing\n */\n\nimport type { Stage } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, PlanningStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): PlanningStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { PlanningContext, Stage } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\nexport function getStageForTurn(context: PlanningContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern; merge result into context.\n * Returns planMarkdown when synthesis stage completes.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n pendingQuestions: string[];\n advance: boolean;\n data: PlanningContext;\n planMarkdown?: string;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const data: PlanningContext = {\n ...merged,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n };\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasPlanMarkdown: !!result.planMarkdown,\n });\n return {\n message: result.message,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n planMarkdown: result.planMarkdown,\n };\n}\n\nexport { isConfirmation, advanceStage, addChatEntry };\n","/**\n * processPlanningChat - main entry point for chat-based planning\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { PlanningContext, PlanChatTurnResult, PlanningChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processPlanningChat(\n userMessage: string,\n context: PlanningContext | null,\n config: PlanningChatConfig\n): Promise<PlanChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: PlanningContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Planning chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let pendingQuestions: string[] = [];\n let planMarkdown: string | null = null;\n\n const runOne = async (stage: Stage): Promise<{ advance: boolean; planMarkdown?: string }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n pendingQuestions = result.pendingQuestions;\n ctx = result.data;\n if (result.planMarkdown) planMarkdown = result.planMarkdown;\n return { advance: result.advance, planMarkdown: result.planMarkdown };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n\n while (runResult.advance && !planMarkdown) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Planning chat turn done', { stage, hasPlanMarkdown: !!planMarkdown });\n return {\n message,\n context: ctx,\n pendingQuestions,\n planMarkdown,\n };\n}\n","/**\n * runPlanningAgent - one-shot wrapper around processPlanningChat\n * Auto-advances with \"continue\"; returns plan markdown. Does not write to file.\n */\n\nimport type { PlanningAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processPlanningChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the planning agent in one-shot mode: single input, auto-advance through stages,\n * return plan markdown as AgentResult. Does not write to file.\n */\nexport async function runPlanningAgent(config: PlanningAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting planning agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processPlanningChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning agent turn', { turn: turns });\n const continueMsg =\n `continue - proceed with the project: \"${input}\". ` +\n 'Make reasonable assumptions for any unresolved details and produce the required output format.';\n lastResult = await processPlanningChat(continueMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning agent completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * editPlan - single LLM call to revise an existing plan based on feedback.\n * Takes existing plan markdown + edit instructions, returns updated markdown.\n */\n\nimport type { EditPlanConfig } from './types';\nimport { createModel } from '../../lib/models/create-model';\nimport { EDIT_PLAN_SYSTEM_PROMPT, buildEditPlanPrompt } from './prompts';\n\n/**\n * Edit an existing plan based on feedback or additional context.\n * Single focused LLM call -- no multi-stage pipeline needed.\n * Returns the full revised plan as a markdown string.\n */\nexport async function editPlan(config: EditPlanConfig): Promise<string> {\n const { existingPlan, feedback, logger } = config;\n logger?.info('Editing plan', { feedbackLength: feedback.length });\n\n if (!existingPlan || existingPlan.trim().length < 50) {\n throw new Error('existingPlan is too short or empty. Provide a valid plan to edit.');\n }\n if (!feedback || feedback.trim().length === 0) {\n throw new Error('feedback is empty. Provide edit instructions.');\n }\n\n const modelConfig = config.model ?? { provider: 'openai' as const, model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n const response = await model.invoke(\n [\n { role: 'system' as const, content: EDIT_PLAN_SYSTEM_PROMPT },\n { role: 'user' as const, content: buildEditPlanPrompt(existingPlan, feedback) },\n ],\n { temperature: 0.3, maxOutputTokens: 16384 }\n );\n\n const revised = response.text?.trim() ?? '';\n if (!revised) {\n throw new Error('Model returned empty response when editing plan.');\n }\n\n logger?.info('Plan edited successfully', { outputLength: revised.length });\n return revised;\n}\n","/**\n * Wire requirement-gatherer output into the planning module.\n * Converts a FinalRequirement into a pre-filled PlanningContext at the design stage,\n * skipping the redundant discovery + requirements stages.\n */\n\nimport type { AgentResult } from '../../lib/types/agent';\nimport type { PlanningContext, PlanSections } from './types';\nimport type { PlanFromRequirementsConfig } from './from-requirements.types';\nimport type {\n FinalRequirement,\n DatabaseDesign,\n DatabaseEntity,\n Module,\n Actor,\n Flow,\n Story,\n} from '../requirement-gatherer/types';\nimport { processPlanningChat } from './chat';\n\n/* ── Markdown formatters ─────────────────────────────────── */\n\nfunction formatEntityFields(entity: DatabaseEntity): string {\n if (!entity.fields.length) return '';\n const rows = entity.fields.map(f => {\n const flags = [f.required ? 'required' : '', f.unique ? 'unique' : '']\n .filter(Boolean)\n .join(', ');\n return `| ${f.name} | ${f.type} | ${flags || '-'} | ${f.description} |`;\n });\n return `| Field | Type | Constraints | Description |\\n| --- | --- | --- | --- |\\n${rows.join('\\n')}`;\n}\n\nfunction formatDatabaseAsMarkdown(db: DatabaseDesign): string {\n const header = `## Data Models\\n\\n**Database:** ${db.type}\\n**Reasoning:** ${db.reasoning}\\n`;\n const entities = db.entities\n .map(e => {\n const fields = formatEntityFields(e);\n const relParts = e.relations.map(\n r => r.field + ' → ' + r.references + ' (' + r.description + ')'\n );\n const relations = relParts.length ? '\\n**Relations:** ' + relParts.join('; ') : '';\n const idxParts = e.indexes.map(\n i => i.name + ' [' + i.fields.join(', ') + ']' + (i.unique ? ' (unique)' : '')\n );\n const indexes = idxParts.length ? '\\n**Indexes:** ' + idxParts.join('; ') : '';\n return `### ${e.name}\\n\\n${e.description}\\n\\n${fields}${relations}${indexes}`;\n })\n .join('\\n\\n');\n return `${header}\\n${entities}`;\n}\n\nfunction formatModulesAsMarkdown(modules: Module[]): string {\n const items = modules\n .map(m => {\n const apis = m.apis.map(a => ` - \\`${a.operation}\\` ${a.name}: ${a.description}`).join('\\n');\n return `### ${m.name}\\n\\n${m.description} (entity: ${m.entity})\\n\\n**APIs:**\\n${apis}`;\n })\n .join('\\n\\n');\n return `## Feature Decisions\\n\\n${items}`;\n}\n\nfunction formatProjectOverview(req: FinalRequirement): string {\n const p = req.project;\n const features = p.features.map(f => `- ${f}`).join('\\n');\n return `# ${p.name}\\n\\n**Goal:** ${p.goal}\\n**Domain:** ${p.domain}\\n\\n${req.summary.overview}\\n\\n**Key Features:**\\n${features}`;\n}\n\nfunction formatTechStack(req: FinalRequirement): string {\n const p = req.project;\n return [\n '## Tech Stack',\n '',\n `- **Database:** ${p.database}`,\n `- **Backend Runtime:** ${p.backendRuntime}`,\n `- **API Style:** ${p.apiStyle}`,\n ].join('\\n');\n}\n\nfunction formatActorsContext(actors: Actor[], flows: Flow[], stories: Story[]): string {\n const parts: string[] = ['## Actors and Flows'];\n for (const actor of actors) {\n parts.push(`\\n### ${actor.name}\\n${actor.description}`);\n const actorFlows = flows.filter(f => f.actorId === actor.id);\n if (actorFlows.length) {\n parts.push('**Flows:**');\n for (const f of actorFlows) {\n parts.push(`- ${f.name}: ${f.description} (trigger: ${f.trigger}, outcome: ${f.outcome})`);\n }\n }\n }\n if (stories.length) {\n parts.push('\\n### Key User Stories');\n for (const s of stories.slice(0, 10)) {\n parts.push(`- As **${s.actor}**, I want to **${s.action}**, so that **${s.benefit}**`);\n }\n if (stories.length > 10) parts.push(`- ... and ${stories.length - 10} more stories`);\n }\n return parts.join('\\n');\n}\n\n/* ── Converter ───────────────────────────────────────────── */\n\n/**\n * Convert a FinalRequirement (from requirement-gatherer) into a PlanningContext\n * pre-filled at the design stage, skipping discovery + requirements.\n */\nexport function convertRequirementToContext(req: FinalRequirement): PlanningContext {\n const sections: PlanSections = {\n overview: `## Overview\\n\\n${req.summary.overview}`,\n techStack: formatTechStack(req),\n featureDecisions: formatModulesAsMarkdown(req.modules),\n dataModels: formatDatabaseAsMarkdown(req.database),\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n };\n\n return {\n stage: 'design',\n projectDescription:\n formatProjectOverview(req) + '\\n\\n' + formatActorsContext(req.actors, req.flows, req.stories),\n sections,\n history: [],\n pendingQuestions: [],\n };\n}\n\n/* ── Runner ──────────────────────────────────────────────── */\n\nconst MAX_TURNS = 8;\n\n/**\n * Run the planning pipeline starting from a FinalRequirement.\n * Skips discovery + requirements stages; begins at design.\n */\nexport async function runPlanningFromRequirements(\n config: PlanFromRequirementsConfig\n): Promise<AgentResult> {\n const { requirement, model: modelConfig, onStep, logger } = config;\n\n logger?.info('Starting planning from requirements (fast path)', {\n project: requirement.project.name,\n });\n\n const context = convertRequirementToContext(requirement);\n\n const triggerMsg =\n `Generate the implementation plan for \"${requirement.project.name}\". ` +\n 'The project description, tech stack, features, and data models are already provided in context. ' +\n 'Proceed with API routes, implementation details, execution plan, edge cases, and testing checklist.';\n\n let lastResult = await processPlanningChat(triggerMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n let turns = 1;\n\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning from requirements turn', { turn: turns });\n lastResult = await processPlanningChat(\n 'continue - produce the complete implementation plan.',\n lastResult.context,\n { model: modelConfig, onStep, logger }\n );\n turns++;\n }\n\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = lastResult.context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning from requirements completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n\n return { output, steps: [], totalUsage: undefined, messages };\n}\n","/**\n * Builder for PlanningContext - fluent API\n */\n\nimport type { PlanningContext, Stage, PlanSections, ChatEntry } from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport class PlanningContextBuilder {\n private data: Partial<PlanningContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectDescription(projectDescription: string | null): this {\n this.data.projectDescription = projectDescription;\n return this;\n }\n\n withSections(sections: Partial<PlanSections>): this {\n this.data.sections = { ...(this.data.sections ?? EMPTY_SECTIONS), ...sections };\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: string[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): PlanningContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectDescription: this.data.projectDescription ?? null,\n sections: this.data.sections ?? { ...EMPTY_SECTIONS },\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createPlanningContextBuilder(): PlanningContextBuilder {\n return new PlanningContextBuilder();\n}\n","/**\n * Zod schemas for DataModelDesign\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n description: z.string().default(''),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string().default(''),\n fields: z.array(z.string()).default([]),\n unique: z.coerce.boolean().default(false),\n});\n\n/** Normalize common relation type variants to canonical form. */\nconst relationTypeSchema = z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['1:1', 'onetoone'].includes(n)) return '1:1' as const;\n if (['1:n', '1:m', 'n:1', 'onetomany', 'manytoone'].includes(n)) return '1:N' as const;\n if (['m:n', 'n:m', 'manytomany'].includes(n)) return 'M:N' as const;\n return s;\n })\n .pipe(z.enum(['1:1', '1:N', 'M:N']));\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n type: relationTypeSchema,\n description: z.string().default(''),\n});\n\nexport const dataEntitySchema = z.object({\n name: z.string(),\n description: z.string().default(''),\n fields: z\n .union([z.array(entityFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof entityFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.name) obj.name = key;\n const result = entityFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n indexes: z.array(entityIndexSchema).default([]),\n relations: z.array(entityRelationSchema).default([]),\n});\n\n/** Case-insensitive database type */\nconst dbTypeSchema = z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['mongodb', 'postgresql']));\n\nexport const dataModelDesignSchema = z.object({\n type: dbTypeSchema,\n reasoning: z.string().default(''),\n entities: z.array(dataEntitySchema).default([]),\n});\n\nexport type TDataModelDesign = z.infer<typeof dataModelDesignSchema>;\n","/**\n * MongoDB field-level schema (merged from db-designer)\n */\n\nimport { z } from 'zod';\n\nexport const mongoFieldSchema = z.object({\n fieldName: z.string().describe('fieldName must be in camelCase'),\n fieldType: z\n .string()\n .default('string')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['string', 'text', 'varchar'].includes(n)) return 'string' as const;\n if (['number', 'int', 'integer', 'float', 'double', 'decimal'].includes(n))\n return 'number' as const;\n if (['boolean', 'bool'].includes(n)) return 'boolean' as const;\n if (['types.objectid', 'objectid', 'ref', 'reference'].includes(n))\n return 'Types.ObjectId' as const;\n if (['date', 'datetime', 'timestamp'].includes(n)) return 'Date' as const;\n if (['object', 'json', 'mixed'].includes(n)) return 'object' as const;\n if (['email'].includes(n)) return 'email' as const;\n if (['password', 'hash'].includes(n)) return 'password' as const;\n if (['enum', 'select'].includes(n)) return 'enum' as const;\n if (['array'].includes(n)) return 'string' as const;\n return 'string' as const;\n })\n .pipe(\n z.enum([\n 'string',\n 'number',\n 'boolean',\n 'Types.ObjectId',\n 'Date',\n 'object',\n 'email',\n 'password',\n 'enum',\n ])\n ),\n isArray: z.coerce.boolean().default(false),\n isRequired: z.coerce.boolean().default(true),\n isUnique: z.coerce.boolean().default(false),\n values: z\n .array(z.string())\n .default([])\n .describe('Enum values if fieldType is enum, else empty array'),\n defaultVal: z.union([z.string(), z.boolean(), z.number(), z.null()]).optional(),\n relationTo: z.string().optional().describe('Module name for relations'),\n relationType: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_]+/g, '-');\n if (['one-to-one', '1:1', '1-to-1'].includes(n)) return 'one-to-one' as const;\n if (['many-to-one', 'n:1', 'n-to-1', 'many-to-1', '*:1'].includes(n))\n return 'many-to-one' as const;\n return '' as const;\n })\n .pipe(z.enum(['one-to-one', 'many-to-one', '']))\n .optional(),\n isPrivate: z.coerce.boolean().default(false).describe('True if password field, else false'),\n});\n\nexport type TMongoFieldSchema = z.infer<typeof mongoFieldSchema>;\n","/**\n * MongoDB module (collection) schema with RBAC (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport { mongoFieldSchema } from './mongodb-field.schema';\n\nexport const mongoModuleSchema = z.object({\n moduleName: z.string().describe('camelCase, single word, never auth/authentication'),\n isUserModule: z.coerce.boolean().default(false),\n authMethod: z\n .string()\n .transform(s => {\n const n = s.toUpperCase().replace(/[\\s-]+/g, '_');\n if (['EMAIL_AND_PASSWORD', 'EMAIL_PASSWORD', 'EMAIL'].includes(n))\n return 'EMAIL_AND_PASSWORD' as const;\n if (['PHONE_AND_OTP', 'PHONE_OTP', 'PHONE', 'SMS'].includes(n))\n return 'PHONE_AND_OTP' as const;\n return '' as const;\n })\n .pipe(z.enum(['EMAIL_AND_PASSWORD', 'PHONE_AND_OTP', '']))\n .optional(),\n emailField: z.string().optional(),\n passwordField: z.string().optional(),\n phoneField: z.string().optional(),\n roleField: z.string().optional(),\n permissions: z\n .record(z.string(), z.array(z.enum(['CREATE', 'READ', 'UPDATE', 'DELETE'])))\n .optional()\n .describe('Permissions per role'),\n fields: z\n .union([z.array(mongoFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof mongoFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.fieldName) obj.fieldName = key;\n const result = mongoFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n});\n\nexport type TMongoModuleSchema = z.infer<typeof mongoModuleSchema>;\n","/**\n * MongoDB root project schema with RBAC (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport { mongoModuleSchema } from './mongodb-module.schema';\n\nexport const mongoProjectSchema = z.object({\n projectName: z.string().default('project').describe('projectName must be in kebab-case'),\n projectDescription: z.string().default(''),\n modules: z\n .union([z.array(mongoModuleSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof mongoModuleSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.moduleName) obj.moduleName = key;\n const result = mongoModuleSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n author: z.string().default('sijeeshmiziha'),\n});\n\nexport type TMongoProjectSchema = z.infer<typeof mongoProjectSchema>;\n","/**\n * System prompt for data-modeler orchestrator\n */\n\nexport const DATA_MODELER_SYSTEM_PROMPT = `You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.\n\nYou analyze requirements and produce enterprise-quality data models with:\n- Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)\n- Indexes optimized for query patterns\n- Relationships with correct cardinality (1:1, 1:N, M:N)\n- Validation constraints and default values\n- Security considerations (hashed passwords, encrypted fields)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for data-modeler\n */\n\nexport const DESIGN_SCHEMA_PROMPT = `## Requirements:\n{requirement}\n\nDesign the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.\n\nFor MongoDB use types: ObjectId, string, number, boolean, date, array, mixed.\nFor PostgreSQL use types: uuid, varchar(n), text, integer, bigint, boolean, timestamp, jsonb, and proper foreign key relations.\n\nReturn ONLY valid JSON:\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences explaining the choice and design approach\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"idx_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"type\": \"1:N\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nexport const REFINE_SCHEMA_PROMPT = `## Current Schema (JSON):\n{existingSchema}\n\n## Feedback:\n{feedback}\n\nUpdate the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;\n\nexport function buildDesignSchemaPrompt(requirement: string): string {\n return DESIGN_SCHEMA_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildRefineSchemaPrompt(existingSchema: string, feedback: string): string {\n return REFINE_SCHEMA_PROMPT.replace('{existingSchema}', existingSchema).replace(\n '{feedback}',\n feedback\n );\n}\n","/**\n * Pro-level 5-phase data modeling prompt\n */\n\nexport const PRO_DESIGN_PROMPT = `## Project: {projectName}\n## Goal: {projectGoal}\n## Database: {databaseType}\n\n## Context:\n{context}\n\nApply the 5-phase enterprise data modeling process:\n\n### Phase 1: Entity Discovery\n- Extract every entity from the context (user types, domain objects, settings, logs).\n- Identify status enums from flow transitions.\n\n### Phase 2: Relationship Mapping\n- For each entity pair, determine ownership and cardinality (1:1, 1:N, M:N).\n- Note bidirectional references and join tables (PostgreSQL) or embedded arrays (MongoDB).\n\n### Phase 3: Permission Derivation\n- Map actor types to role names.\n- From actions, derive which role can CRUD which entity.\n\n### Phase 4: Schema Generation\n- Generate fields with DB-native types, required/unique flags, defaults.\n- Add indexes for common queries (user lookups, date ranges, foreign keys).\n- Include timestamps (createdAt, updatedAt) on all entities.\n\n### Phase 5: Validation\n- Verify every entity referenced in relations exists.\n- Verify no orphan fields or missing indexes.\n\nReturn ONLY valid JSON in the DataModelDesign format.`;\n\nexport function buildProDesignPrompt(\n projectName: string,\n projectGoal: string,\n databaseType: string,\n context: string\n): string {\n return PRO_DESIGN_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{databaseType}', databaseType)\n .replace('{context}', context);\n}\n","/**\n * MongoDB 5-phase system prompt (merged from db-designer)\n */\n\nexport const MONGODB_SYSTEM_PROMPT = `You are an expert MongoDB database architect with deep expertise in schema design, performance optimization, scalability, and domain-driven design. You analyze requirements systematically using a multi-phase approach to create production-ready database schemas.\n\n## ANALYSIS FRAMEWORK\n\nYou MUST follow this 5-phase analysis process before generating the schema:\n\n### PHASE 1: Entity Discovery\nSystematically extract all entities from the provided requirements:\n\n1. **From dataInvolved fields**: Every item in user stories' dataInvolved[] array indicates a potential entity or field\n2. **From User Types (Actors)**: Each actor type may indicate a User variant or role\n3. **From User Flow Actions**: Action verbs reveal implicit entities\n4. **From Flow States**: Transitions reveal status enums\n\n### PHASE 2: Relationship Mapping\nFor each entity pair, determine relationships based on:\n\n1. **Ownership Patterns** (from actor actions)\n2. **Cardinality from Flow Context** (one-to-one, many-to-one)\n3. **Shared Entities** (referenced across flows)\n4. **Bidirectional References** (for one-to-one)\n\n### PHASE 3: Permission Derivation\nMap actors to RBAC permissions:\n\n1. **Role Extraction**: Each actor type becomes a role value\n2. **Permission Mining from User Stories**: Map actions to CRUD per role\n3. **Data Visibility Rules**: \"view own\" vs \"view all\" vs \"manage\"\n\n### PHASE 4: Query Pattern Inference\nAnalyze flows to predict database access patterns:\n\n1. **Read Patterns** (suggest indexes)\n2. **Write Patterns** (affect schema design)\n3. **Aggregation Needs** (from reporting flows)\n\n### PHASE 5: Schema Construction\nSynthesize all analyses into the final schema:\n\n1. **Module Definition**: One module per core entity, camelCase names\n2. **Field Completeness**: All fields from dataInvolved, relationships, status enums, timestamps\n3. **Validation Constraints**: isRequired, isUnique, enum values\n4. **Security Fields**: password fields with isPrivate: true\n\n## CORE CONSTRAINTS (MUST FOLLOW)\n\n1. **Primary Key**: _id with Types.ObjectId (auto-generated, do not include in fields)\n2. **Relationships**: One-to-One: reference in BOTH collections; Many-to-One: reference in \"many\" side; One-to-Many: FORBIDDEN - invert to many-to-one\n3. **Data Types**: NO arrays of ObjectIds; Timestamps: createdAt, updatedAt in EVERY collection; Enums: fieldType: 'enum' with values array\n4. **Security**: NO separate \"Auth\" collection; NO token storage; Password fields: isPrivate: true\n5. **Authorization (RBAC)**: Define permissions per role on user modules`;\n","/**\n * MongoDB prompt formatters - format structured requirements for prompts\n * (merged from db-designer)\n */\n\nimport type {\n MongoActor,\n MongoExtractedFlow,\n MongoExtractedStory,\n MongoTechnicalRequirements,\n MongoStructuredInput,\n} from '../types';\n\nexport function formatUserTypes(actors: MongoActor[]): string {\n if (!actors || actors.length === 0) {\n return 'No specific user types defined. Assume a general \"User\" role.';\n }\n return actors\n .map((actor, i) => {\n const goals = actor.goals.filter(g => g.trim()).join('\\n - ');\n return `### ${i + 1}. ${actor.name}\\n**Description:** ${actor.description}\\n**Goals:**\\n - ${goals || 'No specific goals defined'}`;\n })\n .join('\\n\\n');\n}\n\nexport function formatUserFlows(flows: MongoExtractedFlow[], actors: MongoActor[]): string {\n if (!flows || flows.length === 0) return 'No specific user flows defined.';\n return flows\n .map((flow, i) => {\n const actor = actors.find(a => a.id === flow.actorId);\n return `### ${i + 1}. ${flow.name}\\n**Actor:** ${actor?.name || 'User'}\\n**Description:** ${flow.description}\\n**Trigger:** ${flow.trigger || 'User initiates action'}\\n**Outcome:** ${flow.outcome || 'Action completed'}`;\n })\n .join('\\n\\n');\n}\n\nexport function formatUserStories(\n stories: MongoExtractedStory[],\n flows: MongoExtractedFlow[]\n): string {\n if (!stories || stories.length === 0) return 'No specific user stories defined.';\n const byFlow = new Map<string, MongoExtractedStory[]>();\n for (const s of stories) {\n const arr = byFlow.get(s.flowId) || [];\n arr.push(s);\n byFlow.set(s.flowId, arr);\n }\n const sections: string[] = [];\n for (const flow of flows) {\n const flowStories = byFlow.get(flow.id) || [];\n if (flowStories.length === 0) continue;\n sections.push(`### Flow: ${flow.name}\\n`);\n for (const story of flowStories) {\n const pre = story.preconditions.filter(p => p.trim());\n const post = story.postconditions.filter(p => p.trim());\n const data = story.dataInvolved.filter(d => d.trim());\n let t = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (pre.length) t += `\\n**Preconditions:**\\n${pre.map(p => `- ${p}`).join('\\n')}\\n`;\n if (post.length) t += `\\n**Postconditions:**\\n${post.map(p => `- ${p}`).join('\\n')}\\n`;\n if (data.length)\n t += `\\n**Data Involved (IMPORTANT):**\\n${data.map(d => `- ${d}`).join('\\n')}\\n`;\n sections.push(t);\n }\n }\n const orphans = stories.filter(s => !flows.some(f => f.id === s.flowId));\n if (orphans.length) {\n sections.push(`### Other Stories\\n`);\n for (const s of orphans) {\n const data = s.dataInvolved.filter(d => d.trim());\n let t = `**As a** ${s.actor}, **I want to** ${s.action}, **so that** ${s.benefit}\\n`;\n if (data.length) t += `\\n**Data Involved:** ${data.join(', ')}\\n`;\n sections.push(t);\n }\n }\n return sections.join('\\n');\n}\n\nexport function formatTechnicalRequirements(tech?: MongoTechnicalRequirements): string {\n if (!tech) return 'No specific technical requirements. Use defaults.';\n const lines: string[] = [`**Authentication:** ${tech.authentication || 'none'}`];\n if (tech.authorization) {\n lines.push('**Authorization (RBAC):** Enabled');\n if (tech.roles?.length) lines.push(`**Defined Roles:** ${tech.roles.join(', ')}`);\n } else {\n lines.push('**Authorization:** Disabled');\n }\n if (tech.realtime) lines.push('**Realtime Features:** Required');\n if (tech.fileUpload) lines.push('**File Upload:** Required');\n if (tech.search) lines.push('**Search Functionality:** Required');\n if (tech.integrations?.length) lines.push(`**Integrations:** ${tech.integrations.join(', ')}`);\n return lines.join('\\n');\n}\n\nexport function extractDataEntities(stories: MongoExtractedStory[]): string[] {\n const entities = new Set<string>();\n for (const s of stories) for (const d of s.dataInvolved) if (d.trim()) entities.add(d.trim());\n return Array.from(entities);\n}\n\nexport function extractRoles(actors: MongoActor[]): string[] {\n return actors.map(a => a.name.toLowerCase().replaceAll(/\\s+/g, '_'));\n}\n\nexport function buildPromptVariables(input: MongoStructuredInput): Record<string, string> {\n return {\n projectName: input.projectName,\n projectGoal: input.projectGoal,\n projectDescription: input.projectDescription || input.projectGoal,\n userTypes: formatUserTypes(input.actors),\n userFlows: formatUserFlows(input.flows, input.actors),\n userStories: formatUserStories(input.stories, input.flows),\n technicalRequirements: formatTechnicalRequirements(input.technicalRequirements),\n };\n}\n","/**\n * MongoDB design prompt builders (merged from db-designer)\n */\n\nimport type { MongoStructuredInput } from '../types';\nimport { MONGODB_SYSTEM_PROMPT } from './mongodb-system.prompt';\nimport { buildPromptVariables } from './mongodb-formatters';\n\n/**\n * Legacy: build design prompt from plain requirement string\n */\nexport function createMongoDesignPrompt(requirement: string): string {\n return `${MONGODB_SYSTEM_PROMPT}\n\nDesign a robust and efficient MongoDB database schema based on the following requirements:\n\n## Requirements\n${requirement}\n\n## Guidelines\n1. Use camelCase for module names and field names\n2. Include createdAt and updatedAt Date fields in every module\n3. Define proper relationships between modules\n4. Set appropriate permissions for user modules\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n\n/**\n * Pro-level MongoDB design prompt from structured requirements\n */\nexport function createMongoProDesignPrompt(input: MongoStructuredInput): string {\n const vars = buildPromptVariables(input);\n return `${MONGODB_SYSTEM_PROMPT}\n\n---\n\n## PROJECT CONTEXT\n\n**Project Name:** ${vars.projectName}\n**Project Goal:** ${vars.projectGoal}\n**Description:** ${vars.projectDescription}\n\n---\n\n## USER TYPES (ACTORS)\n\n${vars.userTypes}\n\n---\n\n## USER FLOWS\n\n${vars.userFlows}\n\n---\n\n## USER STORIES WITH DATA REQUIREMENTS\n\n${vars.userStories}\n\n---\n\n## TECHNICAL REQUIREMENTS\n\n${vars.technicalRequirements}\n\n---\n\n## YOUR TASK\n\nFollow the 5-phase analysis framework:\n\n### Step 1: Entity Discovery\n- List ALL entities extracted from dataInvolved fields\n- Identify implicit entities from user flow actions\n- Map user types to User collection roles\n- Extract status enums from flow transitions\n\n### Step 2: Relationship Mapping\n- Define ownership: which actor creates/owns each entity\n- Determine cardinality from flow context\n\n### Step 3: Permission Derivation\n- Map each actor to a role\n- Extract CRUD permissions from user story actions\n\n### Step 4: Query Pattern Inference\n- Identify likely query patterns from flows\n\n### Step 5: Schema Construction\nGenerate the final schema with complete module definitions, fields, relationships, RBAC permissions, and timestamps.\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n","/**\n * MongoDB redesign prompt - update existing schema based on feedback\n * (merged from db-designer)\n */\n\nimport { MONGODB_SYSTEM_PROMPT } from './mongodb-system.prompt';\n\nexport function createMongoRedesignPrompt(existingSchema: string, feedback: string): string {\n return `${MONGODB_SYSTEM_PROMPT}\n\nUpdate the existing MongoDB schema based on user feedback.\n\n## Steps\n1. Analyze the existing MongoDB schema provided\n2. Review the user feedback to understand the required updates\n3. Update the schema to incorporate the requested changes while adhering to best practices\n\n## Existing Schema\n${existingSchema}\n\n## User Feedback\n${feedback}\n\nReturn the updated schema as a valid JSON object matching the original schema format.\nIMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`;\n}\n","/**\n * validate_schema tool - validates JSON against dataModelDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { dataModelDesignSchema } from '../schemas';\n\nexport const validateSchemaTool = createValidationTool(\n 'validate_data_model',\n dataModelDesignSchema,\n 'Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.',\n 'schema'\n);\n","/**\n * design_schema tool - generates data model from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildDesignSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema tool. Requires a model for generation.\n */\nexport function createDesignSchemaTool(model: Model) {\n return defineTool({\n name: 'design_schema',\n description:\n 'Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the data modeling requirements'),\n }),\n handler: async ({ requirement }): Promise<TDataModelDesign> => {\n const userPrompt = buildDesignSchemaPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * design_schema_pro tool - 5-phase structured data modeling (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildProDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema_pro tool for structured 5-phase data modeling.\n */\nexport function createDesignSchemaProTool(model: Model) {\n return defineTool({\n name: 'design_schema_pro',\n description:\n 'Generate an enterprise-quality database schema using 5-phase analysis (Entity Discovery, Relationship Mapping, Permission Derivation, Schema Generation, Validation). Use when structured context is available.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n projectGoal: z.string().describe('Project goal / purpose'),\n databaseType: z.enum(['mongodb', 'postgresql']).describe('Target database type'),\n context: z.string().describe('Full project context: features, actors, flows, stories'),\n }),\n handler: async ({\n projectName,\n projectGoal,\n databaseType,\n context,\n }): Promise<TDataModelDesign> => {\n const userPrompt = buildProDesignPrompt(projectName, projectGoal, databaseType, context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * refine_schema tool - updates existing schema based on feedback (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildRefineSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the refine_schema tool for iterating on an existing data model.\n */\nexport function createRefineSchemaTools(model: Model) {\n return defineTool({\n name: 'refine_schema',\n description:\n 'Update an existing data model schema based on user feedback. Provide the current schema JSON and feedback describing desired changes.',\n input: z.object({\n existingSchema: z.string().describe('Current data model schema as JSON string'),\n feedback: z.string().describe('Feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TDataModelDesign> => {\n const userPrompt = buildRefineSchemaPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * validate_schema tool - validates JSON against mongoProjectSchema (merged from db-designer)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { mongoProjectSchema } from '../schemas';\n\nexport const validateMongoSchemaTool = createValidationTool(\n 'validate_schema',\n mongoProjectSchema,\n 'Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors.',\n 'schema'\n);\n","/**\n * design_database tool - generates MongoDB schema from plain text (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_database tool for MongoDB schema generation.\n */\nexport function createDesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'design_database',\n description:\n 'Generate a MongoDB database schema from plain text requirements. Returns the full project schema as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the database requirements'),\n }),\n handler: async ({ requirement }): Promise<TMongoProjectSchema> => {\n const userPrompt = createMongoDesignPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, mongoProjectSchema);\n },\n });\n}\n","/**\n * design_database_pro tool - MongoDB schema from structured requirements (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoProDesignPrompt, extractDataEntities, extractRoles } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nconst structuredInputSchema = z.object({\n projectName: z.string(),\n projectGoal: z.string(),\n projectDescription: z.string().optional(),\n actors: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n })\n ),\n flows: z.array(\n z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n })\n ),\n stories: z.array(\n z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n })\n ),\n technicalRequirements: z\n .object({\n authentication: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['none', 'no', ''].includes(n)) return 'none' as const;\n if (['email', 'emailpassword', 'emailandpassword'].includes(n)) return 'email' as const;\n if (['oauth', 'oauth2', 'social'].includes(n)) return 'oauth' as const;\n if (['phone', 'phoneotp', 'sms'].includes(n)) return 'phone' as const;\n if (['emailandphone', 'emailphone', 'both'].includes(n))\n return 'email_and_phone' as const;\n return 'email' as const;\n })\n .pipe(z.enum(['none', 'email', 'oauth', 'phone', 'email_and_phone'])),\n authorization: z.coerce.boolean().default(false),\n roles: z.array(z.string()).optional(),\n integrations: z.array(z.string()).optional(),\n realtime: z.boolean().optional(),\n fileUpload: z.boolean().optional(),\n search: z.boolean().optional(),\n })\n .optional(),\n});\n\n/**\n * Creates the design_database_pro tool for structured 5-phase MongoDB analysis.\n */\nexport function createDesignDatabaseProTool(model: Model) {\n return defineTool({\n name: 'design_database_pro',\n description:\n 'Generate a MongoDB schema from structured requirements (actors, flows, stories, technical requirements). Returns dbDesign and metadata.',\n input: structuredInputSchema,\n handler: async (\n input\n ): Promise<{\n dbDesign: TMongoProjectSchema;\n metadata: { entitiesDetected: string[]; rolesExtracted: string[] };\n }> => {\n const userPrompt = createMongoProDesignPrompt(input);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n const dbDesign = parseModelJsonResponse(response.text, mongoProjectSchema);\n const metadata = {\n entitiesDetected: extractDataEntities(input.stories),\n rolesExtracted: extractRoles(input.actors),\n };\n return { dbDesign, metadata };\n },\n });\n}\n","/**\n * redesign_database tool - updates existing MongoDB schema from feedback (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoRedesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the redesign_database tool for iterating on MongoDB schemas.\n */\nexport function createRedesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'redesign_database',\n description:\n 'Update an existing MongoDB project schema based on user feedback. Provide the current schema JSON string and the feedback.',\n input: z.object({\n existingSchema: z.string().describe('Current project schema as JSON string'),\n feedback: z.string().describe('User feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TMongoProjectSchema> => {\n const userPrompt = createMongoRedesignPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, mongoProjectSchema);\n },\n });\n}\n","/**\n * data-modeler tools (generic + MongoDB)\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSchemaTool } from './validate-schema';\nimport { createDesignSchemaTool } from './design-schema';\nimport { createDesignSchemaProTool } from './design-schema-pro';\nimport { createRefineSchemaTools } from './refine-schema';\nimport { validateMongoSchemaTool } from './validate-mongodb';\nimport { createDesignDatabaseTool } from './design-mongodb';\nimport { createDesignDatabaseProTool } from './design-mongodb-pro';\nimport { createRedesignDatabaseTool } from './redesign-mongodb';\n\nexport { validateSchemaTool } from './validate-schema';\nexport { createDesignSchemaTool } from './design-schema';\nexport { createDesignSchemaProTool } from './design-schema-pro';\nexport { createRefineSchemaTools } from './refine-schema';\n\n/* MongoDB-specific tools (merged from db-designer) */\nexport { validateMongoSchemaTool } from './validate-mongodb';\nexport { createDesignDatabaseTool } from './design-mongodb';\nexport { createDesignDatabaseProTool } from './design-mongodb-pro';\nexport { createRedesignDatabaseTool } from './redesign-mongodb';\n\n/**\n * Create all generic data-modeler tools. Pass the model for AI-backed tools.\n */\nexport function createDataModelerTools(model: Model) {\n return createToolSet({\n validate_data_model: validateSchemaTool,\n design_schema: createDesignSchemaTool(model),\n design_schema_pro: createDesignSchemaProTool(model),\n refine_schema: createRefineSchemaTools(model),\n });\n}\n\n/**\n * Create all MongoDB-specific tools (merged from db-designer).\n */\nexport function createDbDesignerTools(model: Model) {\n return createToolSet({\n validate_schema: validateMongoSchemaTool,\n design_database: createDesignDatabaseTool(model),\n design_database_pro: createDesignDatabaseProTool(model),\n redesign_database: createRedesignDatabaseTool(model),\n });\n}\n","/**\n * runDataModelerAgent - orchestrator for data model design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { DATA_MODELER_SYSTEM_PROMPT } from './prompts';\nimport { createDataModelerTools } from './tools';\nimport {\n entityAnalyzerSubagent,\n relationshipMapperSubagent,\n createSchemaRefinerSubagent,\n} from './subagents';\nimport type { DataModelerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${DATA_MODELER_SYSTEM_PROMPT}\n\nYou are the data modeling orchestrator. When the user asks for a data model:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, fields, and relationships from the requirements.\n2. **Map relationships**: Use subagent_relationship-mapper with the entity analysis to determine cardinality, foreign keys, and indexes.\n3. **Generate schema**: Use design_schema (plain text) or design_schema_pro (when structured context is available) to produce the data model.\n4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.\n5. **Validate**: Use validate_data_model to check the final schema JSON before returning.\n\nRespond with the final data model schema as JSON.`;\n\n/**\n * Run the data-modeler orchestrator agent with all tools and subagents.\n */\nexport async function runDataModelerAgent(config: DataModelerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createDataModelerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet(\n [entityAnalyzerSubagent, relationshipMapperSubagent, schemaRefiner],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * runDbDesignerAgent - MongoDB-specific orchestrator (merged from db-designer)\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { MONGODB_SYSTEM_PROMPT } from './prompts';\nimport { createDbDesignerTools } from './tools';\nimport { entityAnalyzerSubagent, createSchemaRefinerSubagent } from './subagents';\nimport type { MongoDbDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${MONGODB_SYSTEM_PROMPT}\n\nYou are the MongoDB database design orchestrator. When the user asks for a database design:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, relationships, and roles.\n2. **Generate schema**: Use design_database (plain text) or design_database_pro (structured requirements) to produce the MongoDB schema.\n3. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements.\n4. **Validate**: Use validate_schema to check the final schema JSON.\n5. **Redesign**: If changes are requested, use redesign_database with existing schema and feedback.\n\nRespond with the final schema as JSON.`;\n\n/**\n * Run the MongoDB db-designer orchestrator agent with all tools and subagents.\n */\nexport async function runDbDesignerAgent(config: MongoDbDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const dbTools = createDbDesignerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet([entityAnalyzerSubagent, schemaRefiner], {\n parentModel: model,\n });\n const tools = createToolSet({ ...dbTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ApiDesign\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .union([z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toUpperCase() : s))\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nconst stringRecordSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .transform(m =>\n Object.fromEntries(\n Object.entries(m ?? {}).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)])\n )\n );\n\n/** Coerce arrays of mixed strings/objects to string arrays (models often return objects). */\nconst stringOrObjectArraySchema = z\n .array(z.unknown())\n .default([])\n .transform(arr => arr.map(v => (typeof v === 'string' ? v : JSON.stringify(v))));\n\nexport const restEndpointSchema = z.object({\n id: z.string(),\n resource: z.string(),\n method: httpMethodSchema,\n path: z.string(),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n requestBody: stringRecordSchema,\n responseBody: stringRecordSchema,\n queryParams: stringRecordSchema,\n validation: stringOrObjectArraySchema,\n errorResponses: stringOrObjectArraySchema,\n});\n\nexport const graphqlOperationSchema = z.object({\n name: z.string(),\n type: z.enum(['query', 'mutation', 'subscription']),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n args: z.array(\n z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n })\n ),\n returnType: z.string(),\n});\n\nconst apiStyleSchema = z.unknown().transform(v => {\n const s = typeof v === 'string' ? v.toLowerCase().trim() : 'rest';\n if (s.includes('graphql')) return 'graphql' as const;\n return 'rest' as const;\n});\n\nexport const apiDesignSchema = z.object({\n style: apiStyleSchema,\n baseUrl: z.string().default('/api/v1'),\n endpoints: z.array(restEndpointSchema).default([]),\n graphqlOperations: z.array(graphqlOperationSchema).default([]),\n});\n\nexport type TApiDesign = z.infer<typeof apiDesignSchema>;\n","/**\n * System prompt for api-designer orchestrator\n */\n\nexport const API_DESIGNER_SYSTEM_PROMPT = `You are a senior API architect specializing in REST and GraphQL API design.\n\nYou analyze data models and requirements to produce enterprise-quality API designs with:\n- RESTful endpoints grouped by resource with proper HTTP methods\n- Request/response contracts with field types and validation rules\n- Error responses with appropriate HTTP status codes (400, 401, 403, 404, 500)\n- Pagination, filtering, and sorting patterns\n- Authentication and authorization annotations per endpoint\n- GraphQL types, queries, mutations, and subscriptions when applicable\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for api-designer\n */\n\nexport const DESIGN_API_PROMPT = `## Requirements:\n{requirement}\n\nDesign the API. Determine the best API style (rest or graphql) based on the requirements, or use the one specified.\n\nFor REST: group endpoints by resource. Each endpoint needs method, path, description, auth flag, roles, requestBody, responseBody, queryParams, validation rules, and error responses.\nFor GraphQL: define operations (queries, mutations, subscriptions) with args and return types.\n\nReturn ONLY valid JSON:\n{\n \"style\": \"rest\" | \"graphql\",\n \"baseUrl\": \"/api/v1\",\n \"endpoints\": [\n { \"id\": \"ep-1\", \"resource\": \"users\", \"method\": \"POST\", \"path\": \"/api/v1/users\", \"description\": \"Create user\", \"auth\": false, \"roles\": [], \"requestBody\": {}, \"responseBody\": {}, \"queryParams\": {}, \"validation\": [], \"errorResponses\": [] }\n ],\n \"graphqlOperations\": []\n}`;\n\nexport const PRO_DESIGN_API_PROMPT = `## Project: {projectName}\n## API Style: {apiStyle}\n## Data Model:\n{dataModel}\n## Requirements:\n{context}\n\nDesign a comprehensive API surface from the data model and requirements. For each entity in the data model, generate CRUD endpoints plus any custom operations implied by the requirements.\n\nInclude per-endpoint: validation rules (required fields, formats, lengths), error responses (400 validation, 401 unauthenticated, 403 forbidden, 404 not found, 500 server error), and auth/role annotations.\n\nReturn ONLY valid JSON in the ApiDesign format.`;\n\nexport function buildDesignApiPrompt(requirement: string): string {\n return DESIGN_API_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildProDesignApiPrompt(\n projectName: string,\n apiStyle: string,\n dataModel: string,\n context: string\n): string {\n return PRO_DESIGN_API_PROMPT.replace('{projectName}', projectName)\n .replace('{apiStyle}', apiStyle)\n .replace('{dataModel}', dataModel)\n .replace('{context}', context);\n}\n","/**\n * validate_api tool - validates JSON against apiDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { apiDesignSchema } from '../schemas';\n\nexport const validateApiTool = createValidationTool(\n 'validate_api',\n apiDesignSchema,\n 'Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_api tool - generates API design from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api tool for plain text requirements.\n */\nexport function createDesignApiTool(model: Model) {\n return defineTool({\n name: 'design_api',\n description:\n 'Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the API requirements'),\n }),\n handler: async ({ requirement }): Promise<TApiDesign> => {\n const userPrompt = buildDesignApiPrompt(requirement);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * design_api_pro tool - structured API design from data model + context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildProDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api_pro tool for structured API design.\n */\nexport function createDesignApiProTool(model: Model) {\n return defineTool({\n name: 'design_api_pro',\n description:\n 'Generate a comprehensive API design from a data model and project context. Produces detailed endpoints with validation, error responses, and auth annotations.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n apiStyle: z.enum(['rest', 'graphql']).describe('Target API style'),\n dataModel: z.string().describe('Data model JSON or description'),\n context: z.string().describe('Project context: features, actors, stories'),\n }),\n handler: async ({ projectName, apiStyle, dataModel, context }): Promise<TApiDesign> => {\n const userPrompt = buildProDesignApiPrompt(projectName, apiStyle, dataModel, context);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * api-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateApiTool } from './validate-api';\nimport { createDesignApiTool } from './design-api';\nimport { createDesignApiProTool } from './design-api-pro';\n\nexport { validateApiTool } from './validate-api';\nexport { createDesignApiTool } from './design-api';\nexport { createDesignApiProTool } from './design-api-pro';\n\n/**\n * Create all api-designer tools. Pass the model for AI-backed tools.\n */\nexport function createApiDesignerTools(model: Model) {\n return createToolSet({\n validate_api: validateApiTool,\n design_api: createDesignApiTool(model),\n design_api_pro: createDesignApiProTool(model),\n });\n}\n","/**\n * runApiDesignerAgent - orchestrator for API design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { API_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createApiDesignerTools } from './tools';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from './subagents';\nimport type { ApiDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${API_DESIGNER_SYSTEM_PROMPT}\n\nYou are the API design orchestrator. When the user asks for an API design:\n\n1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.\n2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.\n3. **Generate design**: Use design_api (plain text) or design_api_pro (when data model and structured context are available) to produce the API design.\n4. **Validate**: Use validate_api to check the final API design JSON before returning.\n\nRespond with the final API design as JSON.`;\n\n/**\n * Run the api-designer orchestrator agent with all tools and subagents.\n */\nexport async function runApiDesignerAgent(config: ApiDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApiDesignerTools(model);\n const subagentTools = createSubagentToolSet(\n [endpointAnalyzerSubagent, contractDesignerSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for AuthDesign\n */\n\nimport { z } from 'zod';\n\nexport const authFlowStepSchema = z.object({\n order: z.number(),\n side: z.enum(['frontend', 'backend']),\n action: z.string(),\n details: z.string(),\n});\n\nexport const authFlowSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(authFlowStepSchema),\n});\n\nexport const authMiddlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n behavior: z.array(z.string()),\n});\n\nexport const roleDefinitionSchema = z.object({\n name: z.string(),\n description: z.string(),\n permissions: z.array(z.string()),\n});\n\nexport const securityPolicySchema = z.object({\n area: z.string(),\n rules: z.array(z.string()),\n});\n\nexport const authDesignSchema = z.object({\n strategy: z.enum(['jwt', 'session', 'oauth']),\n flows: z.array(authFlowSchema),\n middleware: z.array(authMiddlewareSchema),\n roles: z.array(roleDefinitionSchema),\n policies: z.array(securityPolicySchema),\n});\n\nexport type TAuthDesign = z.infer<typeof authDesignSchema>;\n","/**\n * System prompt for auth-designer orchestrator\n */\n\nexport const AUTH_DESIGNER_SYSTEM_PROMPT = `You are a senior security engineer specializing in authentication, authorization, and web security.\n\nYou design enterprise-quality auth systems with:\n- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps\n- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)\n- Role-based access control (RBAC) with permission matrices\n- Middleware chains for route protection and API authentication\n- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection\n- OAuth integration patterns when needed\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for auth-designer\n */\n\nexport const DESIGN_AUTH_PROMPT = `## Requirements:\n{requirement}\n\nDesign the authentication and authorization system. Include:\n\n1. Strategy: jwt, session, or oauth (choose based on requirements).\n2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.\n3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.\n4. Roles: role definitions with name, description, and permissions list.\n5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).\n\nReturn ONLY valid JSON:\n{\n \"strategy\": \"jwt\" | \"session\" | \"oauth\",\n \"flows\": [{ \"name\": \"signup\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"side\": \"frontend\", \"action\": \"...\", \"details\": \"...\" }] }],\n \"middleware\": [{ \"name\": \"authenticateRequest\", \"purpose\": \"...\", \"behavior\": [\"...\"] }],\n \"roles\": [{ \"name\": \"user\", \"description\": \"...\", \"permissions\": [\"...\"] }],\n \"policies\": [{ \"area\": \"passwords\", \"rules\": [\"...\"] }]\n}`;\n\nexport function buildDesignAuthPrompt(requirement: string): string {\n return DESIGN_AUTH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_auth tool - validates JSON against authDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { authDesignSchema } from '../schemas';\n\nexport const validateAuthTool = createValidationTool(\n 'validate_auth',\n authDesignSchema,\n 'Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_auth tool - generates auth design from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { authDesignSchema, type TAuthDesign } from '../schemas';\nimport { buildDesignAuthPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_auth tool for auth flow generation.\n */\nexport function createDesignAuthTool(model: Model) {\n return defineTool({\n name: 'design_auth',\n description:\n 'Generate a complete authentication and authorization design from project requirements. Returns auth flows, middleware, roles, and security policies as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context and auth requirements'),\n }),\n handler: async ({ requirement }): Promise<TAuthDesign> => {\n const userPrompt = buildDesignAuthPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a security engineer. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, authDesignSchema);\n },\n });\n}\n","/**\n * auth-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateAuthTool } from './validate-auth';\nimport { createDesignAuthTool } from './design-auth';\n\nexport { validateAuthTool } from './validate-auth';\nexport { createDesignAuthTool } from './design-auth';\n\n/**\n * Create all auth-designer tools. Pass the model for AI-backed tools.\n */\nexport function createAuthDesignerTools(model: Model) {\n return createToolSet({\n validate_auth: validateAuthTool,\n design_auth: createDesignAuthTool(model),\n });\n}\n","/**\n * runAuthDesignerAgent - orchestrator for auth design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { AUTH_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createAuthDesignerTools } from './tools';\nimport { securityAnalyzerSubagent, flowDesignerSubagent } from './subagents';\nimport type { AuthDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${AUTH_DESIGNER_SYSTEM_PROMPT}\n\nYou are the auth design orchestrator. When the user asks for an auth design:\n\n1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.\n2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).\n3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.\n4. **Validate**: Use validate_auth to check the final auth design JSON before returning.\n\nRespond with the final auth design as JSON.`;\n\n/**\n * Run the auth-designer orchestrator agent with all tools and subagents.\n */\nexport async function runAuthDesignerAgent(config: AuthDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createAuthDesignerTools(model);\n const subagentTools = createSubagentToolSet([securityAnalyzerSubagent, flowDesignerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for FrontendDesign\n */\n\nimport { z } from 'zod';\n\nexport const formFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n validation: z.string(),\n});\n\nexport const pageDesignSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['public', 'protected'])),\n purpose: z.string(),\n formFields: z.array(formFieldSchema).default([]),\n actions: z.array(z.string()).default([]),\n emptyState: z.string().default(''),\n errorState: z.string().default(''),\n redirectOnSuccess: z.string().default(''),\n keyUiElements: z.array(z.string()).default([]),\n});\n\nexport const componentDesignSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['layout', 'shared', 'form', 'display', 'navigation'])),\n purpose: z.string(),\n props: z.array(z.string()).default([]),\n usedIn: z.array(z.string()).default([]),\n});\n\nexport const frontendDesignSchema = z.object({\n pages: z.array(pageDesignSchema).default([]),\n components: z.array(componentDesignSchema).default([]),\n stateManagement: z.string().default(''),\n routingNotes: z.string().default(''),\n});\n\nexport type TFrontendDesign = z.infer<typeof frontendDesignSchema>;\n","/**\n * System prompt for frontend-architect orchestrator\n */\n\nexport const FRONTEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior frontend architect specializing in page design, routing, and component architecture.\n\nYou design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:\n- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)\n- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support\n- **Routing**: React Router v7 with private route guards\n- **Forms**: React Hook Form + Zod validation\n- **GraphQL**: Apollo Client with CodeGen-typed hooks\n- **Path Aliases**: @/{appName}/* mapping to ./src/*\n\nArchitecture outputs:\n- Public and protected pages with detailed route definitions\n- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects\n- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)\n- State management strategy (per-page vs global, Apollo cache vs local state)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for frontend-architect\n */\n\nexport const DESIGN_FRONTEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the frontend architecture. Include:\n\n1. Pages: public and protected pages. For each page: path, name, access level, purpose, form fields (with validation), actions, empty state, error state, redirect on success, key UI elements.\n2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.\n3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).\n4. Routing notes: any special routing behavior (redirects, guards, nested routes).\n\nReturn ONLY valid JSON:\n{\n \"pages\": [{ \"path\": \"/login\", \"name\": \"Login\", \"access\": \"public\", \"purpose\": \"...\", \"formFields\": [{ \"name\": \"email\", \"type\": \"email\", \"required\": true, \"validation\": \"valid email format\" }], \"actions\": [\"Submit login form\"], \"emptyState\": \"\", \"errorState\": \"Show error message\", \"redirectOnSuccess\": \"/dashboard\", \"keyUiElements\": [\"Email input\", \"Password input\", \"Submit button\"] }],\n \"components\": [{ \"name\": \"Navbar\", \"type\": \"navigation\", \"purpose\": \"...\", \"props\": [\"user\"], \"usedIn\": [\"/dashboard\", \"/profile\"] }],\n \"stateManagement\": \"...\",\n \"routingNotes\": \"...\"\n}`;\n\nexport function buildDesignFrontendPrompt(requirement: string): string {\n return DESIGN_FRONTEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_frontend tool - validates JSON against frontendDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { frontendDesignSchema } from '../schemas';\n\nexport const validateFrontendTool = createValidationTool(\n 'validate_frontend',\n frontendDesignSchema,\n 'Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_frontend tool - generates frontend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { frontendDesignSchema, type TFrontendDesign } from '../schemas';\nimport { buildDesignFrontendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_frontend tool for frontend architecture generation.\n */\nexport function createDesignFrontendTool(model: Model) {\n return defineTool({\n name: 'design_frontend',\n description:\n 'Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context, API surface, and frontend requirements'),\n }),\n handler: async ({ requirement }): Promise<TFrontendDesign> => {\n const userPrompt = buildDesignFrontendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a frontend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, frontendDesignSchema);\n },\n });\n}\n","/**\n * frontend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendTool } from './validate-frontend';\nimport { createDesignFrontendTool } from './design-frontend';\n\nexport { validateFrontendTool } from './validate-frontend';\nexport { createDesignFrontendTool } from './design-frontend';\n\n/**\n * Create all frontend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createFrontendArchitectTools(model: Model) {\n return createToolSet({\n validate_frontend: validateFrontendTool,\n design_frontend: createDesignFrontendTool(model),\n });\n}\n","/**\n * runFrontendArchitectAgent - routing orchestrator for frontend architecture design.\n * Delegates to react-builder or nextjs-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet, defineSubagent } from '../../lib/subagents';\nimport { FRONTEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createFrontendArchitectTools } from './tools';\nimport {\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n} from './subagents';\nimport type { FrontendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\n/** Subagent wrapper for react-builder orchestrator */\nconst reactBuilderSubagent = defineSubagent({\n name: 'react-builder',\n description:\n 'Generates a Vite + React SPA configuration from a frontend design and GraphQL schema. Use when the framework-selector recommends react-vite.',\n systemPrompt:\n 'You are a React/Vite frontend builder. Generate a complete frontend config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\n/** Subagent wrapper for nextjs-builder orchestrator */\nconst nextjsBuilderSubagent = defineSubagent({\n name: 'nextjs-builder',\n description:\n 'Generates a Next.js App Router configuration from a frontend design. Use when the framework-selector recommends nextjs.',\n systemPrompt:\n 'You are a Next.js App Router builder. Generate a complete Next.js config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${FRONTEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the frontend architecture routing orchestrator. When the user asks for a frontend design:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.\n2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.\n3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.\n4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.\n5. **Validate**: Use validate_frontend to check the final design JSON before returning.\n6. **Delegate to builder**: Based on the framework-selector recommendation:\n - If \"react-vite\": use subagent_react-builder with the design to generate a Vite + React SPA config.\n - If \"nextjs\": use subagent_nextjs-builder with the design to generate a Next.js App Router config.\n\nRespond with the final frontend design as JSON, including the builder output.`;\n\n/**\n * Run the frontend-architect routing orchestrator with all tools and subagents.\n */\nexport async function runFrontendArchitectAgent(\n config: FrontendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createFrontendArchitectTools(model);\n const subagentTools = createSubagentToolSet(\n [\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n reactBuilderSubagent,\n nextjsBuilderSubagent,\n ],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ExecutionPlan\n */\n\nimport { z } from 'zod';\n\nexport const phaseStepSchema = z.object({\n order: z.number(),\n action: z.string(),\n details: z.string(),\n});\n\nexport const implementationPhaseSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(phaseStepSchema),\n});\n\nexport const edgeCaseSchema = z.object({\n area: z.string(),\n scenario: z.string(),\n handling: z.string(),\n severity: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['critical', 'warning', 'info'])),\n});\n\nexport const testChecklistItemSchema = z.object({\n flow: z.string(),\n item: z.string(),\n expectedResult: z.string(),\n});\n\nexport const executionPlanSchema = z.object({\n phases: z.array(implementationPhaseSchema).default([]),\n currentState: z.string().default(''),\n desiredEndState: z.string().default(''),\n edgeCases: z.array(edgeCaseSchema).default([]),\n securityNotes: z.array(z.string()).default([]),\n performanceNotes: z.array(z.string()).default([]),\n testingChecklist: z.array(testChecklistItemSchema).default([]),\n});\n\nexport type TExecutionPlan = z.infer<typeof executionPlanSchema>;\n","/**\n * System prompt for execution-planner orchestrator\n */\n\nexport const EXECUTION_PLANNER_SYSTEM_PROMPT = `You are a senior tech lead specializing in implementation strategy and project execution planning.\n\nYou create enterprise-quality execution plans with:\n- Phased implementation order with concrete, numbered steps per phase\n- Current state analysis and desired end state definition\n- Edge cases per domain area with handling strategies and severity levels\n- Security considerations (passwords, tokens, CORS, input validation)\n- Performance considerations (indexing, caching, lazy loading, N+1 prevention)\n- Manual testing checklists grouped by feature flow\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for execution-planner\n */\n\nexport const CREATE_EXECUTION_PLAN_PROMPT = `## Full Plan Context:\n{context}\n\nCreate a comprehensive execution plan. Include:\n\n1. **phases**: Implementation phases (Foundation, Auth, Core Features, etc.). Each phase has numbered steps with concrete actions (e.g. \"1. Install dependencies\", \"2. Create User model\").\n2. **currentState**: What the project starts with (e.g. \"vanilla Next.js, no DB, no auth\").\n3. **desiredEndState**: What must work when done (user capabilities + technical verification).\n4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).\n5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).\n6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).\n7. **testingChecklist**: Manual testing items per flow with expected results.\n\nReturn ONLY valid JSON:\n{\n \"phases\": [{ \"name\": \"Phase 1: Foundation\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"action\": \"Install dependencies\", \"details\": \"npm install mongoose bcryptjs jsonwebtoken\" }] }],\n \"currentState\": \"...\",\n \"desiredEndState\": \"...\",\n \"edgeCases\": [{ \"area\": \"Authentication\", \"scenario\": \"Email already exists\", \"handling\": \"Return 400 with clear message\", \"severity\": \"critical\" }],\n \"securityNotes\": [\"...\"],\n \"performanceNotes\": [\"...\"],\n \"testingChecklist\": [{ \"flow\": \"Auth Flow\", \"item\": \"Sign up with valid credentials\", \"expectedResult\": \"Account created, redirected to dashboard\" }]\n}`;\n\nexport function buildCreateExecutionPlanPrompt(context: string): string {\n return CREATE_EXECUTION_PLAN_PROMPT.replace('{context}', context);\n}\n","/**\n * validate_execution_plan tool - validates JSON against executionPlanSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { executionPlanSchema } from '../schemas';\n\nexport const validateExecutionPlanTool = createValidationTool(\n 'validate_execution_plan',\n executionPlanSchema,\n 'Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.',\n 'plan'\n);\n","/**\n * create_execution_plan tool - generates execution plan from context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { executionPlanSchema, type TExecutionPlan } from '../schemas';\nimport { buildCreateExecutionPlanPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the create_execution_plan tool for generating phased plans.\n */\nexport function createExecutionPlanTool(model: Model) {\n return defineTool({\n name: 'create_execution_plan',\n description:\n 'Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.',\n input: z.object({\n context: z.string().describe('Full plan context: all sections generated so far'),\n }),\n handler: async ({ context }): Promise<TExecutionPlan> => {\n const userPrompt = buildCreateExecutionPlanPrompt(context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a tech lead. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, executionPlanSchema);\n },\n });\n}\n","/**\n * execution-planner tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExecutionPlanTool } from './validate-plan';\nimport { createExecutionPlanTool } from './create-plan';\n\nexport { validateExecutionPlanTool } from './validate-plan';\nexport { createExecutionPlanTool } from './create-plan';\n\n/**\n * Create all execution-planner tools. Pass the model for AI-backed tools.\n */\nexport function createExecutionPlannerTools(model: Model) {\n return createToolSet({\n validate_execution_plan: validateExecutionPlanTool,\n create_execution_plan: createExecutionPlanTool(model),\n });\n}\n","/**\n * runExecutionPlannerAgent - orchestrator for execution plan design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXECUTION_PLANNER_SYSTEM_PROMPT } from './prompts';\nimport { createExecutionPlannerTools } from './tools';\nimport { edgeCaseAnalyzerSubagent, testingStrategistSubagent } from './subagents';\nimport type { ExecutionPlannerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXECUTION_PLANNER_SYSTEM_PROMPT}\n\nYou are the execution planning orchestrator. When the user provides plan sections:\n\n1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.\n2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.\n3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.\n4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.\n\nRespond with the final execution plan as JSON.`;\n\n/**\n * Run the execution-planner orchestrator agent with all tools and subagents.\n */\nexport async function runExecutionPlannerAgent(\n config: ExecutionPlannerAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExecutionPlannerTools(model);\n const subagentTools = createSubagentToolSet(\n [edgeCaseAnalyzerSubagent, testingStrategistSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for BackendDesign\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum helper */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const middlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n appliesTo: z\n .string()\n .default('global')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['global', 'all', 'app', 'application', 'every', 'server'].includes(n)) return 'global';\n if (\n [\n 'route',\n 'routes',\n 'specific',\n 'specific routes',\n 'endpoint',\n 'endpoints',\n 'path',\n ].includes(n)\n )\n return 'route';\n if (['resource', 'entity', 'module', 'controller', 'model'].includes(n)) return 'resource';\n return 'global';\n })\n .pipe(z.enum(['global', 'route', 'resource'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const serviceSchema = z.object({\n name: z.string(),\n entity: z.string(),\n operations: z.array(z.string()).default([]),\n dependencies: z.array(z.string()).default([]),\n});\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routeGroupSchema = z.object({\n resource: z.string(),\n basePath: z.string(),\n endpoints: z\n .array(\n z.object({\n method: httpMethodSchema,\n path: z.string(),\n handler: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n })\n )\n .default([]),\n});\n\nexport const backendDesignSchema = z.object({\n framework: ciEnum(['express', 'apollo', 'both']),\n language: ciEnum(['typescript', 'javascript']).default('typescript'),\n database: z.string().default('mongodb'),\n services: z.array(serviceSchema).default([]),\n middleware: z.array(middlewareSchema).default([]),\n routes: z.array(routeGroupSchema).default([]),\n folderStructure: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n notes: z.string().default(''),\n});\n\nexport type TBackendDesign = z.infer<typeof backendDesignSchema>;\n","/**\n * System prompt for backend-architect orchestrator\n */\n\nexport const BACKEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior backend architect specializing in Node.js server design.\n\nYou analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:\n- Framework selection (Express REST, Apollo GraphQL, or both)\n- Service layer design with clear operation contracts per entity\n- Middleware stack (auth, validation, error handling, CORS, rate limiting)\n- Route/resolver organization grouped by resource\n- Folder structure following domain-driven conventions\n- Environment variable inventory\n- Database connection and ORM/ODM strategy\n\nWhen \"both\" is selected (Express + Apollo), use the Apollo Gateway pattern:\n- Apollo Gateway as the single public entry point for GraphQL queries\n- Subgraphs as internal services composed via IntrospectAndCompose\n- RemoteGraphQLDataSource for header forwarding (auth tokens, service tokens)\n- Express for webhooks, file uploads, and health checks only\n- Gateway has no business logic, all logic lives in subgraphs\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for backend architecture generation\n */\n\nexport const DESIGN_BACKEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the backend architecture. Include:\n\n1. Framework: choose \"express\" (REST API), \"apollo\" (GraphQL subgraph), or \"both\" (Apollo subgraph + Express gateway).\n2. Services: one per entity with CRUD operations and dependencies.\n3. Middleware: auth (JWT/session), validation (Zod/Joi), error handling, CORS, rate limiting.\n4. Routes (if Express): RESTful routes grouped by resource with method, path, handler, auth, and roles.\n5. Folder structure: list of directories and key files.\n6. Env vars: list all required environment variables.\n\nReturn ONLY valid JSON:\n{\n \"framework\": \"express\" | \"apollo\" | \"both\",\n \"language\": \"typescript\",\n \"database\": \"mongodb\",\n \"services\": [{ \"name\": \"UserService\", \"entity\": \"User\", \"operations\": [\"create\", \"findById\", \"findAll\", \"update\", \"delete\"], \"dependencies\": [] }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"purpose\": \"JWT token verification\", \"appliesTo\": \"global\", \"config\": {} }],\n \"routes\": [{ \"resource\": \"users\", \"basePath\": \"/api/users\", \"endpoints\": [{ \"method\": \"GET\", \"path\": \"/\", \"handler\": \"getAll\", \"auth\": true, \"roles\": [\"admin\"] }] }],\n \"folderStructure\": [\"src/\", \"src/routes/\", \"src/services/\", \"src/middleware/\", \"src/models/\", \"src/config/\"],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\"],\n \"notes\": \"\"\n}`;\n\nexport function buildDesignBackendPrompt(requirement: string): string {\n return DESIGN_BACKEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_backend tool - validates JSON against backendDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { backendDesignSchema } from '../schemas';\n\nexport const validateBackendTool = createValidationTool(\n 'validate_backend',\n backendDesignSchema,\n 'Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_backend tool - generates backend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { backendDesignSchema, type TBackendDesign } from '../schemas';\nimport { buildDesignBackendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_backend tool for backend architecture generation.\n */\nexport function createDesignBackendTool(model: Model) {\n return defineTool({\n name: 'design_backend',\n description:\n 'Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TBackendDesign> => {\n const userPrompt = buildDesignBackendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a backend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, backendDesignSchema);\n },\n });\n}\n","/**\n * backend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateBackendTool } from './validate-backend';\nimport { createDesignBackendTool } from './design-backend';\n\nexport { validateBackendTool } from './validate-backend';\nexport { createDesignBackendTool } from './design-backend';\n\n/**\n * Create all backend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createBackendArchitectTools(model: Model) {\n return createToolSet({\n validate_backend: validateBackendTool,\n design_backend: createDesignBackendTool(model),\n });\n}\n","/**\n * service-planner subagent - plans service layer, middleware stack, folder structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SERVICE_PLANNER_SYSTEM_PROMPT = `You are a backend service architect. Given a data model and API design, you plan the service layer.\n\n## Service Design\nFor each entity:\n- Service name (PascalCase + \"Service\")\n- CRUD operations: create, findById, findAll, update, delete\n- Custom operations from user flows (e.g. searchByName, bulkImport)\n- Dependencies on other services (e.g. OrderService depends on UserService)\n\n## Middleware Stack\n- Authentication middleware: JWT verification, session check\n- Authorization middleware: role-based access, resource ownership\n- Validation middleware: request body/params validation\n- Error handling: centralized error handler with typed errors\n- Logging: request/response logging\n- Rate limiting: per-IP or per-user limits\n- CORS: origin whitelist\n\n## Folder Structure\nRecommend a clean folder layout:\n- src/services/ (one file per service)\n- src/middleware/ (one file per middleware)\n- src/models/ (one file per entity)\n- src/routes/ or src/modules/ (grouped by resource)\n- src/config/ (env, database, auth config)\n- src/utils/ (shared helpers)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const servicePlannerSubagent = defineSubagent({\n name: 'service-planner',\n description:\n 'Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.',\n systemPrompt: SERVICE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - analyzes requirements and selects Express vs Apollo vs both\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a backend technology advisor. Given project requirements, you recommend the best backend framework.\n\n## Decision Criteria\n\n### Choose \"express\" (REST API) when:\n- The API is primarily CRUD with RESTful resources\n- The frontend is a traditional SPA (React/Vue) consuming REST\n- Simple request/response patterns without complex data fetching\n- No need for real-time subscriptions\n- Team is more familiar with REST\n\n### Choose \"apollo\" (GraphQL subgraph) when:\n- The frontend needs flexible data fetching (avoid over/under-fetching)\n- Multiple frontends consume the same API (web, mobile, admin)\n- Complex nested data relationships\n- Need for real-time subscriptions\n- Part of a federated GraphQL architecture\n\n### Choose \"both\" when:\n- Apollo subgraph for main data API + Express for webhooks, file uploads, health checks\n- Need both REST endpoints (for external integrations) and GraphQL (for frontend)\n- When \"both\" is selected, an Apollo Gateway is used to compose subgraphs into a unified API:\n - Gateway is the only public entry point for GraphQL\n - Subgraphs are internal services, not exposed to clients directly\n - Gateway uses IntrospectAndCompose for schema discovery\n - RemoteGraphQLDataSource forwards auth headers to subgraphs\n - Express handles non-GraphQL concerns (webhooks, file uploads)\n\n## Output Format\nState your recommendation clearly:\n- Framework: express | apollo | both\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you'd lose with the alternative\n- If \"both\": describe which concerns go to Express vs Apollo Gateway vs subgraphs\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runBackendArchitectAgent - routing orchestrator for backend design\n * Delegates to express-builder or apollo-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { BACKEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createBackendArchitectTools } from './tools';\nimport { servicePlannerSubagent, frameworkSelectorSubagent } from './subagents';\nimport type { BackendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${BACKEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the backend architecture orchestrator. When the user provides requirements:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements and recommend Express, Apollo, or both.\n2. **Plan services**: Use subagent_service-planner to design the service layer, middleware stack, and folder structure.\n3. **Generate design**: Use design_backend to produce the complete backend architecture as JSON.\n4. **Validate**: Use validate_backend to check the final design JSON before returning.\n\nAfter generating the design, note the \"framework\" field in the result:\n- If \"express\": the downstream express-builder should be used to scaffold the project.\n- If \"apollo\": the downstream apollo-builder should be used to scaffold the project.\n- If \"both\": both builders should be invoked sequentially.\n\nRespond with the final backend design as JSON.`;\n\n/**\n * Run the backend-architect orchestrator agent.\n */\nexport async function runBackendArchitectAgent(\n config: BackendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createBackendArchitectTools(model);\n const subagentTools = createSubagentToolSet([servicePlannerSubagent, frameworkSelectorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Apollo subgraph configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const graphqlFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n nullable: z.coerce.boolean().default(false),\n isList: z.coerce.boolean().default(false),\n description: z.string().default(''),\n});\n\nexport const graphqlTypeSchema = z.object({\n name: z.string(),\n kind: ciEnum(['type', 'input', 'enum', 'interface', 'union']),\n fields: z.array(graphqlFieldSchema).default([]),\n values: z.array(z.string()).default([]),\n description: z.string().default(''),\n isEntity: z.coerce.boolean().default(false),\n keyFields: z.array(z.string()).default([]),\n});\n\nexport const resolverOperationSchema = z.object({\n name: z.string(),\n type: ciEnum(['query', 'mutation', 'subscription']),\n args: z.array(graphqlFieldSchema).default([]),\n returnType: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n description: z.string().default(''),\n});\n\nexport const subgraphModuleSchema = z.object({\n name: z.string(),\n entity: z.string(),\n types: z.array(graphqlTypeSchema).default([]),\n operations: z.array(resolverOperationSchema).default([]),\n datasource: z.string().default(''),\n loader: z.string().default(''),\n});\n\nexport const subgraphConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(4000),\n database: z.string().default('mongodb'),\n modules: z.array(subgraphModuleSchema).default([]),\n sharedTypes: z.array(graphqlTypeSchema).default([]),\n authDirective: z.coerce.boolean().default(true),\n cacheDirective: z.coerce.boolean().default(false),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TSubgraphConfig = z.infer<typeof subgraphConfigSchema>;\n","/**\n * System prompt for apollo-builder orchestrator\n */\n\nexport const APOLLO_BUILDER_SYSTEM_PROMPT = `You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.\n\nYou generate production-ready Apollo subgraph configurations from data models and API designs:\n- 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts\n- GraphQL type definitions with proper nullability, lists, and descriptions\n- Input types for mutations with validation annotations\n- Enum types from domain values\n- Federation directives: @key for entity references, @external for fields owned by other subgraphs, @requires for field dependencies, @provides for fields resolvable by this subgraph\n- __resolveReference for cross-subgraph entity resolution via buildSubgraphSchema\n- DataLoader per module for batching and caching database lookups (solves N+1)\n- Query and mutation resolvers with auth/role requirements\n- Datasource classes per entity (MongoDB datasource pattern)\n- Auth directive (@auth) configuration\n- Redis cache directives: @cacheSet on queries, @cachePurge on mutations\n- GraphQL CodeGen for TypeScript types (generates base-types.ts)\n- Module-based organization (one module per entity/domain)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for subgraph config generation\n */\n\nexport const DESIGN_SUBGRAPH_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Apollo GraphQL subgraph configuration (Federation v2). Include:\n\n1. Modules: one per entity with 4 files each ({module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts).\n2. Types: GraphQL object types with isEntity/keyFields for federation, input types, enums with fields/values.\n3. Operations: queries (getById, getAll, search) and mutations (create, update, delete) per module.\n4. Auth: mark which operations require authentication and which roles.\n5. DataLoader: one loader per module for batching lookups (loader name).\n6. Shared types: types used across modules (e.g. Pagination, SortOrder).\n7. Cache: set cacheDirective to true if Redis caching (@cacheSet/@cachePurge) is needed.\n8. Env vars: PORT, DATABASE_URL, JWT_SECRET, REDIS_URL, etc.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-subgraph\",\n \"port\": 4000,\n \"database\": \"mongodb\",\n \"modules\": [{\n \"name\": \"user\",\n \"entity\": \"User\",\n \"types\": [{ \"name\": \"User\", \"kind\": \"type\", \"fields\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"isEntity\": true, \"keyFields\": [\"id\"] }],\n \"operations\": [{ \"name\": \"getUser\", \"type\": \"query\", \"args\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"returnType\": \"User\", \"auth\": true, \"roles\": [] }],\n \"datasource\": \"UserDataSource\",\n \"loader\": \"UserLoader\"\n }],\n \"sharedTypes\": [],\n \"authDirective\": true,\n \"cacheDirective\": false,\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"REDIS_URL\"]\n}`;\n\nexport function buildDesignSubgraphPrompt(requirement: string): string {\n return DESIGN_SUBGRAPH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_subgraph tool - validates JSON against subgraphConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { subgraphConfigSchema } from '../schemas';\n\nexport const validateSubgraphTool = createValidationTool(\n 'validate_subgraph',\n subgraphConfigSchema,\n 'Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_subgraph tool - generates subgraph config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { subgraphConfigSchema, type TSubgraphConfig } from '../schemas';\nimport { buildDesignSubgraphPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_subgraph tool for Apollo subgraph config generation.\n */\nexport function createGenerateSubgraphTool(model: Model) {\n return defineTool({\n name: 'generate_subgraph',\n description:\n 'Generate a complete Apollo GraphQL subgraph configuration from data model and API design. Returns modules, types, operations, and datasources as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TSubgraphConfig> => {\n const userPrompt = buildDesignSubgraphPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Apollo GraphQL architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, subgraphConfigSchema);\n },\n });\n}\n","/**\n * scaffold_subgraph tool - compiles .ref/templates/subgraph/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TSubgraphConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert subgraph config to template context */\nfunction toTemplateContext(config: TSubgraphConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n entity: m.entity,\n datasource: m.datasource,\n types: m.types,\n operations: m.operations,\n })),\n authDirective: config.authDirective,\n envVars: config.envVars,\n sharedTypes: config.sharedTypes,\n };\n}\n\nexport const scaffoldSubgraphTool = defineTool({\n name: 'scaffold_subgraph',\n description:\n 'Scaffold an Apollo GraphQL subgraph project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated subgraph config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'subgraph config') as TSubgraphConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/subgraph');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * apollo-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSubgraphTool } from './validate-subgraph';\nimport { createGenerateSubgraphTool } from './generate-subgraph';\nimport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\nexport { validateSubgraphTool } from './validate-subgraph';\nexport { createGenerateSubgraphTool } from './generate-subgraph';\nexport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\n/**\n * Create all apollo-builder tools. Pass the model for AI-backed tools.\n */\nexport function createApolloBuilderTools(model: Model) {\n return createToolSet({\n validate_subgraph: validateSubgraphTool,\n generate_subgraph: createGenerateSubgraphTool(model),\n scaffold_subgraph: scaffoldSubgraphTool,\n });\n}\n","/**\n * schema-generator subagent - generates GraphQL type definitions from data model\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_GENERATOR_SYSTEM_PROMPT = `You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.\n\n## Type Generation\nFor each entity in the data model:\n- Create the main object type with all fields mapped to GraphQL scalars (String, Int, Float, Boolean, ID)\n- Create input types for create and update mutations (omit auto-generated fields like id, createdAt)\n- Create enum types for status fields and role fields\n- Add proper nullability (! for required fields)\n- Add [Type] for array/list fields\n\n## Federation Directives\n- @key(fields: \"id\") on entity types that can be referenced across subgraphs\n- @external marks a field as owned by another subgraph\n- @requires(fields: \"weight\") declares fields needed from the entity to resolve a field\n- @provides(fields: \"name\") declares fields on a return type that this subgraph can resolve\n- @auth directive on types/fields that require authentication\n\n## Cache Directives (Redis)\n- @cacheSet(type: \"Entity\", identifier: \"_id\") on query resolvers\n- @cachePurge(type: \"Entity\", identifier: \"_id\") on mutation resolvers\n\n## Relationships\n- Reference types for foreign keys (e.g. author: User instead of authorId: ID)\n- Use [Type] for one-to-many relationships\n\n## Naming Conventions\n- Types: PascalCase (User, BlogPost)\n- Fields: camelCase (firstName, createdAt)\n- Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)\n- Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)\n\nRespond with the full GraphQL SDL. Do NOT return JSON.`;\n\nexport const schemaGeneratorSubagent = defineSubagent({\n name: 'schema-generator',\n description:\n 'Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.',\n systemPrompt: SCHEMA_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * resolver-planner subagent - plans resolver implementations per module\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RESOLVER_PLANNER_SYSTEM_PROMPT = `You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.\n\n## 4-File Module Pattern\nEach module has four files:\n- {module}.graphql -- Type definitions with federation directives\n- {module}.resolver.ts -- Query/Mutation/Field resolvers including __resolveReference\n- {module}.datasource.ts -- Business logic and database access\n- {module}.loader.ts -- DataLoader for batching and caching lookups\n\n## Resolver Planning\nFor each module/entity:\n\n### __resolveReference (Federation)\n- Every entity type with @key must implement __resolveReference\n- Called by the gateway when another subgraph references this entity\n- Receives { __typename, id } and returns the full entity from datasource\n\n### Query Resolvers\n- getById: fetch single record by ID from datasource\n- getAll: fetch paginated list with filters and sorting\n- search: text search across relevant fields\n\n### Mutation Resolvers\n- create: validate input, create record, return created entity\n- update: validate input, find existing, merge changes, return updated entity\n- delete: find existing, remove, return success status\n\n### Field Resolvers\n- For relationship fields: resolve references via DataLoader (NOT direct DB calls)\n- For computed fields: calculate from existing data\n\n## DataLoader Pattern\nEach module has a loader file that creates DataLoader instances:\n- Batches multiple lookups into a single database query\n- Caches results within a single request to solve the N+1 problem\n- Created per-request in the context, not shared across requests\n\n## Datasource Pattern\n- Each module has a datasource class extending MongoDataSource or similar\n- Datasource handles all database operations\n- Resolvers call datasource methods, never touch the DB directly\n\n## Auth Integration\n- Check auth context in resolver before executing\n- Verify role permissions per operation\n- Resource ownership checks for user-specific data\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const resolverPlannerSubagent = defineSubagent({\n name: 'resolver-planner',\n description:\n 'Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.',\n systemPrompt: RESOLVER_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runApolloBuilderAgent - orchestrator for Apollo GraphQL subgraph generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { APOLLO_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createApolloBuilderTools } from './tools';\nimport { schemaGeneratorSubagent, resolverPlannerSubagent } from './subagents';\nimport type { ApolloBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${APOLLO_BUILDER_SYSTEM_PROMPT}\n\nYou are the Apollo subgraph builder orchestrator. When the user provides requirements:\n\n1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.\n2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.\n3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.\n4. **Validate**: Use validate_subgraph to check the config JSON before returning.\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.\n\nRespond with the final subgraph config as JSON.`;\n\n/**\n * Run the apollo-builder orchestrator agent.\n */\nexport async function runApolloBuilderAgent(\n config: ApolloBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApolloBuilderTools(model);\n const subagentTools = createSubagentToolSet([schemaGeneratorSubagent, resolverPlannerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Express app configuration\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routerMethodSchema = z.object({\n name: z.string(),\n httpMethod: httpMethodSchema,\n path: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n validation: z.string().default(''),\n description: z.string().default(''),\n});\n\nexport const routerSchema = z.object({\n name: z.string(),\n resource: z.string(),\n basePath: z.string(),\n methods: z.array(routerMethodSchema).default([]),\n});\n\nexport const modelFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n ref: z.string().optional(),\n default: z.string().optional(),\n});\n\nexport const modelSchema = z.object({\n name: z.string(),\n collection: z.string(),\n fields: z.array(modelFieldSchema).default([]),\n timestamps: z.coerce.boolean().default(true),\n indexes: z.array(z.string()).default([]),\n});\n\nexport const middlewareConfigSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['auth', 'authentication', 'jwt', 'token'].includes(n)) return 'auth' as const;\n if (['validation', 'validate', 'validator', 'input'].includes(n))\n return 'validation' as const;\n if (['errorhandler', 'error', 'errorhandling', 'errors'].includes(n))\n return 'errorHandler' as const;\n if (['cors', 'crossorigin'].includes(n)) return 'cors' as const;\n if (['ratelimit', 'ratelimiter', 'ratelimiting', 'throttle'].includes(n))\n return 'rateLimit' as const;\n if (['logging', 'logger', 'log', 'morgan'].includes(n)) return 'logging' as const;\n return 'custom' as const;\n })\n .pipe(z.enum(['auth', 'validation', 'errorHandler', 'cors', 'rateLimit', 'logging', 'custom'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const expressConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(3000),\n database: z.string().default('mongodb'),\n routers: z.array(routerSchema).default([]),\n models: z.array(modelSchema).default([]),\n middleware: z.array(middlewareConfigSchema).default([]),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TExpressConfig = z.infer<typeof expressConfigSchema>;\n","/**\n * System prompt for express-builder orchestrator\n */\n\nexport const EXPRESS_BUILDER_SYSTEM_PROMPT = `You are an expert Express.js backend architect.\n\nYou generate production-ready Express application configurations from data models and API designs:\n- Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts\n- Mongoose/Prisma models with field types, validation, and relationships\n- Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)\n- Route organization with proper HTTP methods and paths\n- Health check endpoint at /health (included by default)\n- Jest tests per router using supertest\n- Environment variable inventory\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Express config generation\n */\n\nexport const DESIGN_EXPRESS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Express.js application configuration. Include:\n\n1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).\n2. Health check: a default /health router is always included.\n3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.\n4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.\n5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.\n6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-api\",\n \"port\": 3000,\n \"database\": \"mongodb\",\n \"routers\": [{\n \"name\": \"users\",\n \"resource\": \"users\",\n \"basePath\": \"/api/users\",\n \"methods\": [{\n \"name\": \"getAll\",\n \"httpMethod\": \"GET\",\n \"path\": \"/\",\n \"auth\": true,\n \"roles\": [\"admin\"],\n \"validation\": \"\",\n \"description\": \"Get all users with pagination\"\n }]\n }],\n \"models\": [{\n \"name\": \"User\",\n \"collection\": \"users\",\n \"fields\": [{ \"name\": \"email\", \"type\": \"String\", \"required\": true, \"unique\": true }],\n \"timestamps\": true,\n \"indexes\": [\"email\"]\n }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"type\": \"auth\", \"config\": {} }],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"NODE_ENV\"]\n}`;\n\nexport function buildDesignExpressPrompt(requirement: string): string {\n return DESIGN_EXPRESS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_express tool - validates JSON against expressConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { expressConfigSchema } from '../schemas';\n\nexport const validateExpressTool = createValidationTool(\n 'validate_express',\n expressConfigSchema,\n 'Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_express tool - generates Express config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { expressConfigSchema, type TExpressConfig } from '../schemas';\nimport { buildDesignExpressPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_express tool for Express config generation.\n */\nexport function createGenerateExpressTool(model: Model) {\n return defineTool({\n name: 'generate_express',\n description:\n 'Generate a complete Express.js application configuration from data model and API design. Returns routers, models, middleware, and env vars as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TExpressConfig> => {\n const userPrompt = buildDesignExpressPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Express.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, expressConfigSchema);\n },\n });\n}\n","/**\n * scaffold_express tool - compiles .ref/templates/express/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TExpressConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert express config to template context */\nfunction toTemplateContext(config: TExpressConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n routers: config.routers,\n models: config.models,\n middleware: config.middleware,\n envVars: config.envVars,\n modules: config.routers.map(r => ({\n name: r.resource,\n pascalName: r.name.charAt(0).toUpperCase() + r.name.slice(1),\n camelName: r.resource,\n methods: r.methods,\n })),\n };\n}\n\nexport const scaffoldExpressTool = defineTool({\n name: 'scaffold_express',\n description:\n 'Scaffold an Express.js project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated Express config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'express config') as TExpressConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/express');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * express-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExpressTool } from './validate-express';\nimport { createGenerateExpressTool } from './generate-express';\nimport { scaffoldExpressTool } from './scaffold-express';\n\nexport { validateExpressTool } from './validate-express';\nexport { createGenerateExpressTool } from './generate-express';\nexport { scaffoldExpressTool } from './scaffold-express';\n\n/**\n * Create all express-builder tools. Pass the model for AI-backed tools.\n */\nexport function createExpressBuilderTools(model: Model) {\n return createToolSet({\n validate_express: validateExpressTool,\n generate_express: createGenerateExpressTool(model),\n scaffold_express: scaffoldExpressTool,\n });\n}\n","/**\n * route-generator subagent - generates route files from API design\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_GENERATOR_SYSTEM_PROMPT = `You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.\n\n## Co-located Router Pattern\nEach feature lives in src/routers/{name}/ with three files:\n- {name}.router.ts -- Express Router with route definitions\n- {name}.controller.ts -- Request handler logic\n- {name}.spec.ts -- Jest tests using supertest\n\n## Route Design\nFor each resource:\n- Base path: /api/{resource} (pluralized, lowercase)\n- GET / -> list all (with pagination: page, limit, sort query params)\n- GET /:id -> get by ID\n- POST / -> create new\n- PUT /:id -> update by ID\n- DELETE /:id -> delete by ID\n- Custom routes for non-CRUD operations\n\n## Health Check\nEvery app includes a /health router in src/routers/health/:\n- health.router.ts -- GET /health returning server status\n- health.controller.ts -- Health check handler\n- health.spec.ts -- Health check tests\n\n## Route Organization\n- One router directory per resource with co-located controller and spec\n- Central src/routers/index.ts mounts all routers\n- Middleware applied per-route or per-router\n\n## Controller Mapping\n- Each route maps to a controller method in the co-located controller file\n- Controller method name follows convention: getAll, getById, create, update, delete\n\n## Validation\n- Request body validation using Zod schemas\n- Param validation (e.g. valid ObjectId)\n- Query param parsing and defaults\n\nRespond with structured route definitions. Do NOT return JSON.`;\n\nexport const routeGeneratorSubagent = defineSubagent({\n name: 'route-generator',\n description:\n 'Generates Express route definitions from API design using the co-located router pattern ({name}.router.ts, {name}.controller.ts, {name}.spec.ts). Use before generating the Express config.',\n systemPrompt: ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * middleware-configurator subagent - designs middleware stack\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT = `You are an Express.js middleware specialist. You design the complete middleware stack.\n\n## Core Middleware\n1. **CORS**: Configure allowed origins, methods, headers, credentials\n2. **Body parser**: JSON and URL-encoded body parsing with size limits\n3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)\n4. **Morgan/Logger**: Request logging with format and stream\n\n## Auth Middleware\n1. **JWT verification**: Extract token from Authorization header or cookie\n2. **Role check**: Verify user role against required roles\n3. **Resource ownership**: Check if user owns the resource they're accessing\n\n## Validation Middleware\n1. **Request validation**: Validate body, params, query using Zod schemas\n2. **Sanitization**: Strip HTML, trim whitespace\n\n## Error Handling\n1. **Not found handler**: 404 for unmatched routes\n2. **Error handler**: Centralized error response with status codes\n3. **Async wrapper**: Catch async errors without try-catch\n\n## Rate Limiting\n1. **Global**: Limit requests per IP per time window\n2. **Auth routes**: Stricter limits on login/signup\n\nRespond with structured middleware analysis. Do NOT return JSON.`;\n\nexport const middlewareConfiguratorSubagent = defineSubagent({\n name: 'middleware-configurator',\n description:\n 'Designs the Express middleware stack including auth, validation, error handling, CORS, and rate limiting. Use before generating the Express config.',\n systemPrompt: MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runExpressBuilderAgent - orchestrator for Express.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXPRESS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createExpressBuilderTools } from './tools';\nimport { routeGeneratorSubagent, middlewareConfiguratorSubagent } from './subagents';\nimport type { ExpressBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXPRESS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Express builder orchestrator. When the user provides requirements:\n\n1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.\n2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.\n3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.\n4. **Validate**: Use validate_express to check the config JSON before returning.\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.\n\nRespond with the final Express config as JSON.`;\n\n/**\n * Run the express-builder orchestrator agent.\n */\nexport async function runExpressBuilderAgent(\n config: ExpressBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExpressBuilderTools(model);\n const subagentTools = createSubagentToolSet(\n [routeGeneratorSubagent, middlewareConfiguratorSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Next.js application configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const nextjsPageSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: ciEnum(['public', 'protected']),\n routeGroup: z.string().default(''),\n purpose: z.string(),\n hasForm: z.coerce.boolean().default(false),\n formFields: z.array(z.string()).default([]),\n dataFetching: ciEnum(['server', 'client', 'hybrid']).default('server'),\n actions: z.array(z.string()).default([]),\n});\n\nexport const nextjsLayoutSchema = z.object({\n name: z.string(),\n path: z.string(),\n routeGroup: z.string().default(''),\n components: z.array(z.string()).default([]),\n purpose: z.string(),\n});\n\nexport const nextjsApiRouteSchema = z.object({\n path: z.string(),\n methods: z.array(httpMethodSchema).default([]),\n auth: z.coerce.boolean().default(true),\n description: z.string(),\n});\n\nexport const serverActionSchema = z.object({\n name: z.string(),\n module: z.string(),\n description: z.string(),\n revalidates: z.array(z.string()).default([]),\n});\n\nexport const nextjsConfigSchema = z.object({\n appName: z.string().default('app'),\n pages: z.array(nextjsPageSchema).default([]),\n layouts: z.array(nextjsLayoutSchema).default([]),\n apiRoutes: z.array(nextjsApiRouteSchema).default([]),\n serverActions: z.array(serverActionSchema).default([]),\n middleware: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n packages: z.array(z.string()).default([]),\n});\n\nexport type TNextjsConfig = z.infer<typeof nextjsConfigSchema>;\n","/**\n * System prompt for nextjs-builder orchestrator\n */\n\nexport const NEXTJS_BUILDER_SYSTEM_PROMPT = `You are an expert Next.js application architect using the App Router.\n\nYou generate production-ready Next.js configurations from frontend designs and API designs:\n- App Router file structure with route groups, layouts, pages, loading, and error boundaries\n- Server Components by default, Client Components only when interactivity is needed\n- Server Actions for mutations (form submissions, data writes)\n- API Route Handlers for external integrations, webhooks, and file uploads\n- Next.js middleware for auth guards and redirects\n- Data fetching strategy (server vs client vs hybrid per page)\n- Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Next.js config generation\n */\n\nexport const DESIGN_NEXTJS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate a Next.js App Router application configuration. Include:\n\n1. Pages: app router pages with path, name, access level, route group, purpose, data fetching strategy.\n2. Layouts: shared layouts with route groups (e.g. (auth), (dashboard)), components they include.\n3. API Routes: route handlers with path, HTTP methods, auth requirement, description.\n4. Server Actions: named actions with module, description, and paths they revalidate.\n5. Middleware: list of middleware behaviors (e.g. \"redirect unauthenticated to /login\").\n6. Env vars: NEXTAUTH_SECRET, DATABASE_URL, etc.\n7. Packages: recommended npm packages.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-app\",\n \"pages\": [{\n \"path\": \"/dashboard\",\n \"name\": \"Dashboard\",\n \"access\": \"protected\",\n \"routeGroup\": \"(dashboard)\",\n \"purpose\": \"Main dashboard with stats\",\n \"hasForm\": false,\n \"formFields\": [],\n \"dataFetching\": \"server\",\n \"actions\": []\n }],\n \"layouts\": [{\n \"name\": \"DashboardLayout\",\n \"path\": \"app/(dashboard)/layout.tsx\",\n \"routeGroup\": \"(dashboard)\",\n \"components\": [\"Sidebar\", \"Header\"],\n \"purpose\": \"Shared layout for authenticated pages\"\n }],\n \"apiRoutes\": [{\n \"path\": \"/api/users\",\n \"methods\": [\"GET\", \"POST\"],\n \"auth\": true,\n \"description\": \"User CRUD endpoints\"\n }],\n \"serverActions\": [{\n \"name\": \"createUser\",\n \"module\": \"users\",\n \"description\": \"Create a new user\",\n \"revalidates\": [\"/dashboard/users\"]\n }],\n \"middleware\": [\"Redirect unauthenticated users to /login\"],\n \"envVars\": [\"DATABASE_URL\", \"NEXTAUTH_SECRET\"],\n \"packages\": [\"next-auth\", \"prisma\", \"@prisma/client\", \"tailwindcss\"]\n}`;\n\nexport function buildDesignNextjsPrompt(requirement: string): string {\n return DESIGN_NEXTJS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_nextjs tool - validates JSON against nextjsConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { nextjsConfigSchema } from '../schemas';\n\nexport const validateNextjsTool = createValidationTool(\n 'validate_nextjs',\n nextjsConfigSchema,\n 'Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_nextjs tool - generates Next.js config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { nextjsConfigSchema, type TNextjsConfig } from '../schemas';\nimport { buildDesignNextjsPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_nextjs tool for Next.js config generation.\n */\nexport function createGenerateNextjsTool(model: Model) {\n return defineTool({\n name: 'generate_nextjs',\n description:\n 'Generate a complete Next.js App Router configuration from frontend design and requirements. Returns pages, layouts, API routes, server actions, and middleware as JSON.',\n input: z.object({\n requirement: z.string().describe('Frontend design, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TNextjsConfig> => {\n const userPrompt = buildDesignNextjsPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a Next.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, nextjsConfigSchema);\n },\n });\n}\n","/**\n * nextjs-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateNextjsTool } from './validate-nextjs';\nimport { createGenerateNextjsTool } from './generate-nextjs';\n\nexport { validateNextjsTool } from './validate-nextjs';\nexport { createGenerateNextjsTool } from './generate-nextjs';\n\n/**\n * Create all nextjs-builder tools. Pass the model for AI-backed tools.\n */\nexport function createNextjsBuilderTools(model: Model) {\n return createToolSet({\n validate_nextjs: validateNextjsTool,\n generate_nextjs: createGenerateNextjsTool(model),\n });\n}\n","/**\n * route-planner subagent - plans Next.js App Router file structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_PLANNER_SYSTEM_PROMPT = `You are a Next.js App Router specialist. Given page specs, you plan the file structure.\n\n## Route Groups\n- (auth) for public auth pages: login, signup, forgot-password\n- (dashboard) or (app) for protected pages\n- (marketing) for public landing pages\n\n## File Structure Per Route\n- page.tsx: the page component (Server Component by default)\n- layout.tsx: shared layout for the route group\n- loading.tsx: Suspense fallback\n- error.tsx: error boundary (must be Client Component)\n- not-found.tsx: 404 page\n\n## Data Fetching\n- Server Components: fetch data directly in the component (async function)\n- Client Components: use SWR or React Query for client-side fetching\n- Server Actions: for form submissions and mutations\n\n## Conventions\n- Use lowercase kebab-case for route segments\n- Dynamic segments: [id], [slug]\n- Catch-all: [...slug]\n- Parallel routes: @modal, @sidebar\n- Intercepting routes: (.)photo, (..)details\n\nRespond with the full file tree and route structure. Do NOT return JSON.`;\n\nexport const routePlannerSubagent = defineSubagent({\n name: 'route-planner',\n description:\n 'Plans Next.js App Router file structure with route groups, layouts, and page files. Use before generating the Next.js config.',\n systemPrompt: ROUTE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * api-route-generator subagent - generates Next.js API routes and server actions\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst API_ROUTE_GENERATOR_SYSTEM_PROMPT = `You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.\n\n## API Route Handlers (app/api/)\nFor external integrations, webhooks, and file uploads:\n- One route.ts file per resource: app/api/[resource]/route.ts\n- Export named functions: GET, POST, PUT, DELETE\n- Use NextRequest and NextResponse\n- Add auth checks using next-auth getServerSession\n\n## Server Actions (preferred for mutations)\nFor form submissions and data writes:\n- Define in separate files: app/actions/[module].ts\n- Use 'use server' directive\n- Use revalidatePath or revalidateTag after mutations\n- Return typed results with error handling\n\n## When to Use Which\n- Server Actions: form submissions, data CRUD, anything triggered by user action\n- API Routes: webhooks from external services, file uploads, OAuth callbacks, public APIs\n\n## Auth Integration\n- API Routes: check session with getServerSession\n- Server Actions: check session at the start of each action\n- Middleware: protect route groups with matcher patterns\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const apiRouteGeneratorSubagent = defineSubagent({\n name: 'api-route-generator',\n description:\n 'Generates Next.js API route handlers and server actions from API design. Use after route planning.',\n systemPrompt: API_ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runNextjsBuilderAgent - orchestrator for Next.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { NEXTJS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createNextjsBuilderTools } from './tools';\nimport { routePlannerSubagent, apiRouteGeneratorSubagent } from './subagents';\nimport type { NextjsBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${NEXTJS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Next.js builder orchestrator. When the user provides requirements:\n\n1. **Plan routes**: Use subagent_route-planner to design the App Router file structure with route groups and layouts.\n2. **Generate API routes**: Use subagent_api-route-generator to design API route handlers and server actions.\n3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.\n4. **Validate**: Use validate_nextjs to check the config JSON before returning.\n\nRespond with the final Next.js config as JSON.`;\n\n/**\n * Run the nextjs-builder orchestrator agent.\n */\nexport async function runNextjsBuilderAgent(\n config: NextjsBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createNextjsBuilderTools(model);\n const subagentTools = createSubagentToolSet([routePlannerSubagent, apiRouteGeneratorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n"]}
|