@brainst0rm/cli 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/{App-SSKWB7CT.js → App-HGJSYIVS.js} +133 -62
  2. package/dist/App-HGJSYIVS.js.map +1 -0
  3. package/dist/{App-DPXJYXKH.js → App-XCJW3A4I.js} +133 -62
  4. package/dist/App-XCJW3A4I.js.map +1 -0
  5. package/dist/brainstorm.js +1428 -150
  6. package/dist/brainstorm.js.map +1 -1
  7. package/dist/{chunk-7D4SUZUM.js → chunk-PR4QN5HX.js} +6 -1
  8. package/dist/{chunk-ZWE3DS7E.js → chunk-SEGVTWSK.js} +6 -1
  9. package/dist/{chunk-5NA3GH6X.js → chunk-WYQU3HAB.js} +175 -10
  10. package/dist/chunk-WYQU3HAB.js.map +1 -0
  11. package/dist/{chunk-55ITCWZZ.js → chunk-Z2QIGVYT.js} +175 -10
  12. package/dist/chunk-Z2QIGVYT.js.map +1 -0
  13. package/dist/{dist-GNHTH2DH.js → dist-3BC75XHW.js} +2 -2
  14. package/dist/dist-42TQFHMB.js +1640 -0
  15. package/dist/dist-42TQFHMB.js.map +1 -0
  16. package/dist/dist-BULARAL3.js +7308 -0
  17. package/dist/dist-BULARAL3.js.map +1 -0
  18. package/dist/{dist-JUDVPE7G.js → dist-ET6CSS7O.js} +2 -2
  19. package/dist/{dist-DUDO3RDM.js → dist-GVK5Q4YK.js} +62 -16
  20. package/dist/{dist-V5DTSTKJ.js.map → dist-GVK5Q4YK.js.map} +1 -1
  21. package/dist/{dist-V5DTSTKJ.js → dist-K7BDAMTO.js} +62 -16
  22. package/dist/{dist-DUDO3RDM.js.map → dist-K7BDAMTO.js.map} +1 -1
  23. package/dist/{dist-WLTQTLFO.js → dist-OYQTULIU.js} +2 -2
  24. package/dist/dist-S5JYXFUW.js +7307 -0
  25. package/dist/dist-S5JYXFUW.js.map +1 -0
  26. package/dist/{dist-YIGU37Q2.js → dist-Y25MC2VO.js} +2 -2
  27. package/dist/dist-Z4SBSK4Q.js +1639 -0
  28. package/dist/dist-Z4SBSK4Q.js.map +1 -0
  29. package/dist/index.js +1428 -150
  30. package/dist/index.js.map +1 -1
  31. package/dist/mcp-server-CROPNYHI.js +4252 -0
  32. package/dist/mcp-server-CROPNYHI.js.map +1 -0
  33. package/dist/mcp-server-IJVEG6CS.js +4251 -0
  34. package/dist/mcp-server-IJVEG6CS.js.map +1 -0
  35. package/dist/{recorder-D6ILEOZP.js → recorder-33N4U6TO.js} +2 -2
  36. package/dist/{recorder-SPYYF4DL.js → recorder-APOOXJYA.js} +2 -2
  37. package/dist/{roles-2DGF4PZU.js → roles-GKDCLP5G.js} +2 -2
  38. package/dist/{roles-UIPX7GBC.js → roles-UUIISXEW.js} +2 -2
  39. package/dist/{slash-PDWKCZOQ.js → slash-4XSR3SJD.js} +3 -3
  40. package/dist/{slash-ZDC4DKL4.js → slash-CVWH3LTR.js} +3 -3
  41. package/package.json +4 -2
  42. package/dist/App-DPXJYXKH.js.map +0 -1
  43. package/dist/App-SSKWB7CT.js.map +0 -1
  44. package/dist/chunk-55ITCWZZ.js.map +0 -1
  45. package/dist/chunk-5NA3GH6X.js.map +0 -1
  46. /package/dist/{chunk-7D4SUZUM.js.map → chunk-PR4QN5HX.js.map} +0 -0
  47. /package/dist/{chunk-ZWE3DS7E.js.map → chunk-SEGVTWSK.js.map} +0 -0
  48. /package/dist/{dist-GNHTH2DH.js.map → dist-3BC75XHW.js.map} +0 -0
  49. /package/dist/{dist-JUDVPE7G.js.map → dist-ET6CSS7O.js.map} +0 -0
  50. /package/dist/{dist-WLTQTLFO.js.map → dist-OYQTULIU.js.map} +0 -0
  51. /package/dist/{dist-YIGU37Q2.js.map → dist-Y25MC2VO.js.map} +0 -0
  52. /package/dist/{recorder-D6ILEOZP.js.map → recorder-33N4U6TO.js.map} +0 -0
  53. /package/dist/{recorder-SPYYF4DL.js.map → recorder-APOOXJYA.js.map} +0 -0
  54. /package/dist/{roles-2DGF4PZU.js.map → roles-GKDCLP5G.js.map} +0 -0
  55. /package/dist/{roles-UIPX7GBC.js.map → roles-UUIISXEW.js.map} +0 -0
  56. /package/dist/{slash-PDWKCZOQ.js.map → slash-4XSR3SJD.js.map} +0 -0
  57. /package/dist/{slash-ZDC4DKL4.js.map → slash-CVWH3LTR.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../onboard/src/pipeline.ts","../../onboard/src/types.ts","../../onboard/src/budget.ts","../../onboard/src/phases/static-analysis.ts","../../onboard/src/phases/verification.ts","../../onboard/src/phases/deep-exploration.ts","../../onboard/src/prompts/exploration.ts","../../onboard/src/phases/team-assembly.ts","../../onboard/src/prompts/assembly.ts","../../onboard/src/phases/routing-rules.ts","../../onboard/src/prompts/routing.ts","../../onboard/src/phases/workflow-gen.ts","../../onboard/src/prompts/workflow.ts","../../onboard/src/phases/brainstorm-md.ts","../../onboard/src/prompts/enrichment.ts"],"sourcesContent":["/**\n * Onboard Pipeline — async generator that orchestrates all phases.\n *\n * Same pattern as DaemonController and runOrchestrationPipeline:\n * yields OnboardEvents for real-time CLI rendering.\n *\n * Each phase enriches the OnboardContext. LLM phases check the\n * budget tracker before running and skip if over budget.\n * Phase 0 (static) and Phase 6 (verification) always run.\n */\n\nimport { createLogger } from \"@brainst0rm/shared\";\nimport {\n type OnboardOptions,\n type OnboardEvent,\n type OnboardContext,\n type OnboardResult,\n type OnboardPhase,\n type OnboardDispatcher,\n ALL_PHASES,\n PHASE_LABELS,\n} from \"./types.js\";\nimport {\n inferBudget,\n createBudgetTracker,\n PHASE_COST_ESTIMATES,\n type BudgetTracker,\n} from \"./budget.js\";\nimport { runStaticAnalysis } from \"./phases/static-analysis.js\";\nimport { runVerification } from \"./phases/verification.js\";\nimport { runDeepExploration } from \"./phases/deep-exploration.js\";\nimport { runTeamAssembly } from \"./phases/team-assembly.js\";\nimport { runRoutingRules } from \"./phases/routing-rules.js\";\nimport { runWorkflowGen } from \"./phases/workflow-gen.js\";\nimport { runBrainstormMd } from \"./phases/brainstorm-md.js\";\n\nconst log = createLogger(\"onboard\");\n\n/** Phases that require LLM calls (and therefore budget). */\nconst LLM_PHASES: OnboardPhase[] = [\n \"deep-exploration\",\n \"team-assembly\",\n \"routing-rules\",\n \"workflow-gen\",\n \"brainstorm-md\",\n];\n\n/**\n * Run the full onboard pipeline.\n *\n * Yields OnboardEvents as phases progress. The caller (CLI)\n * iterates this generator and renders each event.\n */\nexport async function* runOnboardPipeline(\n options: OnboardOptions,\n dispatcher?: OnboardDispatcher,\n): AsyncGenerator<OnboardEvent> {\n const startTime = Date.now();\n const phases = options.phases ?? ALL_PHASES;\n const filesWritten: string[] = [];\n const phasesRun: OnboardPhase[] = [];\n const phasesSkipped: OnboardPhase[] = [];\n\n // ── Phase 0: Static Analysis (always runs) ─────────────────────\n\n let context: OnboardContext | null = null;\n let budget: BudgetTracker | null = null;\n\n if (phases.includes(\"static-analysis\")) {\n const phaseStart = Date.now();\n yield {\n type: \"phase-started\",\n phase: \"static-analysis\",\n description: \"Analyzing codebase structure\",\n };\n\n try {\n const { analysis, gitSummary } = runStaticAnalysis(options.projectPath);\n context = { analysis };\n\n // Store gitSummary on context for Phase 1 to use\n (context as any)._gitSummary = gitSummary;\n\n // Infer budget from analysis\n const totalBudget = options.budget ?? inferBudget(analysis);\n budget = createBudgetTracker(totalBudget);\n\n const summary = [\n `${analysis.summary.totalFiles} files`,\n `${analysis.summary.totalLines.toLocaleString()} lines`,\n `${analysis.summary.moduleCount} modules`,\n analysis.summary.primaryLanguage,\n ...analysis.summary.frameworkList.slice(0, 3),\n ].join(\", \");\n\n phasesRun.push(\"static-analysis\");\n yield {\n type: \"phase-completed\",\n phase: \"static-analysis\",\n cost: 0,\n durationMs: Date.now() - phaseStart,\n summary,\n };\n } catch (error) {\n yield {\n type: \"phase-failed\",\n phase: \"static-analysis\",\n error: error instanceof Error ? error.message : String(error),\n };\n return;\n }\n }\n\n if (!context) {\n yield {\n type: \"phase-failed\",\n phase: \"static-analysis\",\n error: \"Static analysis is required but was not included in phases\",\n };\n return;\n }\n\n if (!budget) {\n budget = createBudgetTracker(options.budget ?? 5.0);\n }\n\n // Emit pipeline start with estimated budget\n const estimatedTotal = phases\n .filter((p) => LLM_PHASES.includes(p))\n .reduce((sum, p) => sum + (PHASE_COST_ESTIMATES[p] ?? 0), 0);\n\n yield {\n type: \"onboard-started\",\n options,\n estimatedBudget: Math.round(estimatedTotal * 100) / 100,\n };\n\n // ── LLM Phases (1-5) — skip if staticOnly or no dispatcher ────\n\n if (!options.staticOnly && dispatcher) {\n for (const phase of LLM_PHASES) {\n if (!phases.includes(phase)) continue;\n\n const estimate = PHASE_COST_ESTIMATES[phase] ?? 0;\n\n // Budget check\n if (estimate > 0 && !budget.canAfford(estimate)) {\n yield {\n type: \"budget-warning\",\n spent: budget.spent,\n remaining: budget.remaining,\n };\n yield {\n type: \"phase-skipped\",\n phase,\n reason: `Budget insufficient (need ~$${estimate.toFixed(2)}, have $${budget.remaining.toFixed(2)})`,\n };\n phasesSkipped.push(phase);\n continue;\n }\n\n // Dry run: show what would happen\n if (options.dryRun) {\n yield {\n type: \"phase-skipped\",\n phase,\n reason: `Dry run — would cost ~$${estimate.toFixed(2)}`,\n };\n phasesSkipped.push(phase);\n continue;\n }\n\n const phaseStart = Date.now();\n yield {\n type: \"phase-started\",\n phase,\n description: getPhaseDescription(phase),\n };\n\n try {\n const result = await runLLMPhase(phase, context, dispatcher);\n const cost = result.cost;\n budget.record(cost);\n\n // Merge result into context\n Object.assign(context, result.contextPatch);\n\n // Track written files\n if (result.filesWritten) {\n filesWritten.push(...result.filesWritten);\n for (const f of result.filesWritten) {\n yield { type: \"file-written\", path: f, description: phase };\n }\n }\n\n phasesRun.push(phase);\n yield {\n type: \"phase-completed\",\n phase,\n cost,\n durationMs: Date.now() - phaseStart,\n summary: result.summary,\n };\n } catch (error) {\n yield {\n type: \"phase-failed\",\n phase,\n error: error instanceof Error ? error.message : String(error),\n };\n // Continue to verification even if an LLM phase fails\n phasesSkipped.push(phase);\n }\n }\n } else {\n // Static-only mode or no dispatcher: skip all LLM phases\n for (const phase of LLM_PHASES) {\n if (!phases.includes(phase)) continue;\n yield {\n type: \"phase-skipped\",\n phase,\n reason: options.staticOnly\n ? \"Static-only mode\"\n : \"No LLM dispatcher provided\",\n };\n phasesSkipped.push(phase);\n }\n }\n\n // ── Phase 6: Verification (always runs) ────────────────────────\n\n if (phases.includes(\"verification\")) {\n const phaseStart = Date.now();\n yield {\n type: \"phase-started\",\n phase: \"verification\",\n description: \"Validating generated artifacts\",\n };\n\n const verification = runVerification(context);\n context.verification = verification;\n phasesRun.push(\"verification\");\n\n const counts: string[] = [];\n if (context.agents) {\n counts.push(\n `${context.agents.length} agents ${verification.agentsValid ? \"valid\" : \"INVALID\"}`,\n );\n }\n if (context.routingRules) {\n counts.push(\n `${context.routingRules.length} rules ${verification.routingValid ? \"valid\" : \"INVALID\"}`,\n );\n }\n if (context.recipes) {\n counts.push(\n `${context.recipes.length} recipes ${verification.recipesValid ? \"valid\" : \"INVALID\"}`,\n );\n }\n if (context.brainstormMd) {\n counts.push(\n `BRAINSTORM.md ${verification.brainstormMdValid ? \"valid\" : \"INVALID\"}`,\n );\n }\n\n yield {\n type: \"phase-completed\",\n phase: \"verification\",\n cost: 0,\n durationMs: Date.now() - phaseStart,\n summary: counts.join(\", \") || \"No artifacts to verify\",\n };\n }\n\n // ── Result ─────────────────────────────────────────────────────\n\n yield {\n type: \"onboard-completed\",\n result: {\n context,\n filesWritten,\n totalCost: budget.spent,\n totalDurationMs: Date.now() - startTime,\n phasesRun,\n phasesSkipped,\n },\n };\n}\n\n// ── Phase Dispatch ─────────────────────────────────────────────────\n\ninterface PhaseRunResult {\n contextPatch: Partial<OnboardContext>;\n cost: number;\n summary: string;\n filesWritten?: string[];\n}\n\n/**\n * Dispatch to the appropriate LLM phase implementation.\n */\nasync function runLLMPhase(\n phase: OnboardPhase,\n context: OnboardContext,\n dispatcher: OnboardDispatcher,\n): Promise<PhaseRunResult> {\n switch (phase) {\n case \"deep-exploration\":\n return runDeepExploration(context, dispatcher);\n case \"team-assembly\":\n return runTeamAssembly(context, dispatcher);\n case \"routing-rules\":\n return runRoutingRules(context, dispatcher);\n case \"workflow-gen\":\n return runWorkflowGen(context, dispatcher);\n case \"brainstorm-md\":\n return runBrainstormMd(context, dispatcher);\n default:\n throw new Error(`Unknown LLM phase: ${phase}`);\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction getPhaseDescription(phase: OnboardPhase): string {\n switch (phase) {\n case \"deep-exploration\":\n return \"Reading key files, discovering conventions and domain concepts\";\n case \"team-assembly\":\n return \"Generating specialized agents with project-specific knowledge\";\n case \"routing-rules\":\n return \"Creating task-to-agent routing rules\";\n case \"workflow-gen\":\n return \"Building project-specific workflow recipes\";\n case \"brainstorm-md\":\n return \"Generating enhanced BRAINSTORM.md with real conventions\";\n default:\n return PHASE_LABELS[phase] ?? phase;\n }\n}\n","/**\n * Onboard Types — LLM-driven autonomous project ingestion.\n *\n * The pipeline enriches an OnboardContext through 7 phases:\n * Phase 0 (static) → Phase 1 (explore) → Phase 2 (agents) →\n * Phase 3 (routing) → Phase 4 (workflows) → Phase 5 (BRAINSTORM.md) →\n * Phase 6 (verify)\n *\n * Each phase receives the accumulated context and returns its contribution.\n * OnboardEvents stream progress for real-time CLI rendering.\n */\n\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport type { AgentRole } from \"@brainst0rm/shared\";\n\n// ── Pipeline Options ─────────────────────────────────────────────\n\nexport interface OnboardOptions {\n /** Absolute path to the project root. */\n projectPath: string;\n /** Total budget cap in USD. Default auto-inferred from project size. */\n budget?: number;\n /** Skip LLM phases — equivalent to old setup-infra. */\n staticOnly?: boolean;\n /** Ask user for confirmation between phases. */\n interactive?: boolean;\n /** Show what would happen without writing files or calling LLMs. */\n dryRun?: boolean;\n /** Specific phases to run (default: all). */\n phases?: OnboardPhase[];\n}\n\nexport type OnboardPhase =\n | \"static-analysis\"\n | \"deep-exploration\"\n | \"team-assembly\"\n | \"routing-rules\"\n | \"workflow-gen\"\n | \"brainstorm-md\"\n | \"verification\";\n\nexport const ALL_PHASES: OnboardPhase[] = [\n \"static-analysis\",\n \"deep-exploration\",\n \"team-assembly\",\n \"routing-rules\",\n \"workflow-gen\",\n \"brainstorm-md\",\n \"verification\",\n];\n\nexport const PHASE_LABELS: Record<OnboardPhase, string> = {\n \"static-analysis\": \"Static Analysis\",\n \"deep-exploration\": \"Deep Exploration\",\n \"team-assembly\": \"Team Assembly\",\n \"routing-rules\": \"Routing Rules\",\n \"workflow-gen\": \"Workflow Generation\",\n \"brainstorm-md\": \"BRAINSTORM.md\",\n verification: \"Verification\",\n};\n\n// ── Dispatcher (LLM interface) ───────────────────────────────────\n\nexport interface OnboardDispatcher {\n /** Read-heavy analysis — sends file contents for the LLM to analyze. */\n explore(\n prompt: string,\n budget: number,\n ): Promise<{ text: string; cost: number }>;\n\n /** Structured output — returns parsed JSON matching the prompt's schema. */\n generate(\n prompt: string,\n budget: number,\n ): Promise<{ text: string; cost: number }>;\n}\n\n// ── Accumulating Context ─────────────────────────────────────────\n\nexport interface OnboardContext {\n analysis: ProjectAnalysis;\n exploration?: ExplorationResult;\n agents?: GeneratedAgent[];\n routingRules?: GeneratedRoutingRule[];\n recipes?: GeneratedRecipe[];\n brainstormMd?: string;\n verification?: VerificationResult;\n}\n\n// ── Phase 1: Deep Exploration ────────────────────────────────────\n\nexport interface ExplorationResult {\n conventions: ConventionSet;\n domainConcepts: DomainConcept[];\n gitWorkflow: GitWorkflowProfile;\n cicdSetup: CICDProfile;\n keyFiles: KeyFileDigest[];\n projectPurpose: string;\n}\n\nexport interface ConventionSet {\n /** Variable/function naming: camelCase, snake_case, PascalCase, etc. */\n naming: NamingConvention;\n /** Error handling approach: try/catch, Result type, error boundaries, etc. */\n errorHandling: string;\n /** Test patterns: colocated __tests__, test/ dir, naming convention, etc. */\n testingPatterns: string;\n /** Import style: barrel exports, direct imports, path aliases, etc. */\n importStyle: string;\n /** State management (frontend): zustand, redux, context, signals, etc. */\n stateManagement?: string;\n /** API patterns: REST, tRPC, GraphQL, route handlers, etc. */\n apiPatterns?: string;\n /** Any other conventions discovered. */\n customRules: string[];\n}\n\nexport interface NamingConvention {\n variables: string;\n files: string;\n components?: string;\n exports: string;\n}\n\nexport interface DomainConcept {\n name: string;\n definition: string;\n relatedFiles: string[];\n}\n\nexport interface GitWorkflowProfile {\n commitStyle: string;\n branchStrategy: string;\n prPatterns: string;\n typicalPRSize: string;\n activeContributors: number;\n}\n\nexport interface CICDProfile {\n provider: string;\n stages: string[];\n deployTarget: string;\n hasPreCommitHooks: boolean;\n}\n\nexport interface KeyFileDigest {\n path: string;\n purpose: string;\n summary: string;\n}\n\n// ── Phase 2: Team Assembly ───────────────────────────────────────\n\nexport interface GeneratedAgent {\n id: string;\n role: AgentRole;\n /** Where the .agent.md will be written. */\n filePath: string;\n /** Full .agent.md content (frontmatter + body). */\n content: string;\n /** Why this agent was created. */\n rationale: string;\n}\n\n// ── Phase 3: Routing Rules ───────────────────────────────────────\n\nexport interface GeneratedRoutingRule {\n /** Task type or keyword pattern this rule matches. */\n match: string;\n /** Agent to route matching tasks to. */\n agentId: string;\n /** Model tier hint: quality, capable, cheap. */\n modelHint?: string;\n /** Why this rule exists. */\n rationale: string;\n}\n\n// ── Phase 4: Workflow Recipes ────────────────────────────────────\n\nexport interface GeneratedRecipe {\n /** Recipe filename (e.g., \"pr-ready.yaml\"). */\n filename: string;\n /** Full YAML content. */\n content: string;\n /** What this recipe does. */\n description: string;\n}\n\n// ── Phase 6: Verification ────────────────────────────────────────\n\nexport interface VerificationResult {\n agentsValid: boolean;\n agentErrors: string[];\n routingValid: boolean;\n routingErrors: string[];\n recipesValid: boolean;\n recipeErrors: string[];\n brainstormMdValid: boolean;\n brainstormMdErrors: string[];\n}\n\n// ── Pipeline Events (streaming) ──────────────────────────────────\n\nexport type OnboardEvent =\n | {\n type: \"onboard-started\";\n options: OnboardOptions;\n estimatedBudget: number;\n }\n | { type: \"phase-started\"; phase: OnboardPhase; description: string }\n | {\n type: \"phase-progress\";\n phase: OnboardPhase;\n message: string;\n percent?: number;\n }\n | {\n type: \"phase-completed\";\n phase: OnboardPhase;\n cost: number;\n durationMs: number;\n summary: string;\n }\n | { type: \"phase-failed\"; phase: OnboardPhase; error: string }\n | { type: \"phase-skipped\"; phase: OnboardPhase; reason: string }\n | { type: \"file-written\"; path: string; description: string }\n | { type: \"budget-warning\"; spent: number; remaining: number }\n | { type: \"onboard-completed\"; result: OnboardResult };\n\nexport interface OnboardResult {\n context: OnboardContext;\n filesWritten: string[];\n totalCost: number;\n totalDurationMs: number;\n phasesRun: OnboardPhase[];\n phasesSkipped: OnboardPhase[];\n}\n","/**\n * Budget inference and tracking for the onboard pipeline.\n *\n * Auto-infers a budget cap from project size (file count + complexity),\n * then tracks spend per-phase to prevent cost overruns.\n */\n\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\n\nexport interface BudgetTracker {\n /** Total budget in USD. */\n total: number;\n /** Amount spent so far. */\n spent: number;\n /** Remaining budget. */\n remaining: number;\n /** Whether there's enough budget for an estimated cost. */\n canAfford(estimatedCost: number): boolean;\n /** Record a spend. Returns false if budget exceeded. */\n record(cost: number): boolean;\n}\n\n/**\n * Infer a reasonable budget from project analysis.\n *\n * Small projects (<50 files): $2.00\n * Medium projects (<500 files): $5.00\n * Large projects (500+): $10.00\n *\n * Complexity multiplier: high-complexity projects get 1.5x.\n */\nexport function inferBudget(analysis: ProjectAnalysis): number {\n const files = analysis.summary.totalFiles;\n const complexity = analysis.summary.avgComplexity;\n\n let base: number;\n if (files < 50) base = 2.0;\n else if (files < 500) base = 5.0;\n else base = 10.0;\n\n // High-complexity projects (avg > 15) get a bump\n const multiplier = complexity > 15 ? 1.5 : 1.0;\n\n return Math.round(base * multiplier * 100) / 100;\n}\n\n/**\n * Create a budget tracker for the pipeline.\n */\nexport function createBudgetTracker(totalBudget: number): BudgetTracker {\n let spent = 0;\n\n return {\n get total() {\n return totalBudget;\n },\n get spent() {\n return Math.round(spent * 1000) / 1000;\n },\n get remaining() {\n return Math.round((totalBudget - spent) * 1000) / 1000;\n },\n canAfford(estimatedCost: number): boolean {\n return spent + estimatedCost <= totalBudget;\n },\n record(cost: number): boolean {\n spent += cost;\n return spent <= totalBudget;\n },\n };\n}\n\n/** Per-phase cost estimates (USD) for budget planning. */\nexport const PHASE_COST_ESTIMATES: Record<string, number> = {\n \"static-analysis\": 0,\n \"deep-exploration\": 0.25,\n \"team-assembly\": 0.4,\n \"routing-rules\": 0.06,\n \"workflow-gen\": 0.08,\n \"brainstorm-md\": 0.15,\n verification: 0,\n};\n","/**\n * Phase 0: Static Analysis — deterministic codebase analysis.\n *\n * Wraps analyzeProject() from @brainst0rm/ingest. Zero cost.\n * Also collects git history for Phase 1 to consume.\n *\n * This is the foundation — every subsequent phase builds on\n * the ProjectAnalysis it returns.\n */\n\nimport { analyzeProject, type ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport { existsSync } from \"node:fs\";\nimport { execFileSync } from \"node:child_process\";\n\nexport interface StaticAnalysisResult {\n analysis: ProjectAnalysis;\n gitSummary: string;\n}\n\n/**\n * Run static analysis on a project directory.\n *\n * Returns the structured ProjectAnalysis plus a git log summary\n * string for the exploration phase to include in its prompt.\n */\nexport function runStaticAnalysis(projectPath: string): StaticAnalysisResult {\n const analysis = analyzeProject(projectPath);\n const gitSummary = collectGitSummary(projectPath);\n\n return { analysis, gitSummary };\n}\n\n/**\n * Collect a git log summary for context.\n * Returns a formatted string of recent commits, or empty if not a git repo.\n */\nfunction collectGitSummary(projectPath: string): string {\n const gitDir = `${projectPath}/.git`;\n if (!existsSync(gitDir)) return \"\";\n\n try {\n const log = execFileSync(\n \"git\",\n [\"log\", \"--oneline\", \"--stat\", \"--no-color\", \"-30\"],\n {\n cwd: projectPath,\n encoding: \"utf-8\",\n timeout: 10_000,\n },\n );\n return log.trim();\n } catch {\n return \"\";\n }\n}\n","/**\n * Phase 6: Verification — validates all generated artifacts.\n *\n * Pure deterministic validation — no LLM calls, zero cost.\n * Parses .agent.md files, BRAINSTORM.md frontmatter, recipe YAMLs,\n * and routing rules to catch generation errors before the user\n * starts working with a broken setup.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { OnboardContext, VerificationResult } from \"../types.js\";\n\n/**\n * Validate all generated artifacts in the onboard context.\n */\nexport function runVerification(context: OnboardContext): VerificationResult {\n const result: VerificationResult = {\n agentsValid: true,\n agentErrors: [],\n routingValid: true,\n routingErrors: [],\n recipesValid: true,\n recipeErrors: [],\n brainstormMdValid: true,\n brainstormMdErrors: [],\n };\n\n // Validate agents\n if (context.agents) {\n for (const agent of context.agents) {\n const errors = validateAgentContent(agent.id, agent.content);\n if (errors.length > 0) {\n result.agentsValid = false;\n result.agentErrors.push(...errors);\n }\n }\n }\n\n // Validate routing rules\n if (context.routingRules) {\n for (const rule of context.routingRules) {\n if (!rule.match || !rule.agentId) {\n result.routingValid = false;\n result.routingErrors.push(\n `Rule missing required fields: match=\"${rule.match}\", agentId=\"${rule.agentId}\"`,\n );\n }\n // Check that agentId references a generated agent\n if (\n context.agents &&\n !context.agents.some((a) => a.id === rule.agentId)\n ) {\n result.routingValid = false;\n result.routingErrors.push(\n `Rule references unknown agent \"${rule.agentId}\"`,\n );\n }\n }\n }\n\n // Validate recipes\n if (context.recipes) {\n for (const recipe of context.recipes) {\n const errors = validateRecipeContent(recipe.filename, recipe.content);\n if (errors.length > 0) {\n result.recipesValid = false;\n result.recipeErrors.push(...errors);\n }\n }\n }\n\n // Validate BRAINSTORM.md\n if (context.brainstormMd) {\n const errors = validateBrainstormMd(context.brainstormMd);\n if (errors.length > 0) {\n result.brainstormMdValid = false;\n result.brainstormMdErrors.push(...errors);\n }\n }\n\n return result;\n}\n\n/**\n * Validate .agent.md content has valid frontmatter structure.\n */\nfunction validateAgentContent(id: string, content: string): string[] {\n const errors: string[] = [];\n\n // Must have frontmatter delimiters\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) {\n errors.push(`Agent \"${id}\": missing YAML frontmatter (---)`);\n return errors;\n }\n\n const frontmatter = fmMatch[1];\n const body = fmMatch[2].trim();\n\n // Must have a name field\n if (!/^name:\\s*.+$/m.test(frontmatter)) {\n errors.push(`Agent \"${id}\": missing \"name\" field in frontmatter`);\n }\n\n // Must have a role field\n if (!/^role:\\s*.+$/m.test(frontmatter)) {\n errors.push(`Agent \"${id}\": missing \"role\" field in frontmatter`);\n }\n\n // Should have a system prompt body\n if (!body) {\n errors.push(`Agent \"${id}\": empty system prompt body`);\n }\n\n return errors;\n}\n\n/**\n * Validate recipe YAML has required fields.\n */\nfunction validateRecipeContent(filename: string, content: string): string[] {\n const errors: string[] = [];\n\n // Basic YAML structure checks (we don't pull in a YAML parser for verification)\n if (!content.includes(\"name:\")) {\n errors.push(`Recipe \"${filename}\": missing \"name\" field`);\n }\n if (!content.includes(\"steps:\")) {\n errors.push(`Recipe \"${filename}\": missing \"steps\" field`);\n }\n\n return errors;\n}\n\n/**\n * Validate BRAINSTORM.md has frontmatter with version field.\n */\nfunction validateBrainstormMd(content: string): string[] {\n const errors: string[] = [];\n\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!fmMatch) {\n // Body-only is acceptable — frontmatter is optional\n return errors;\n }\n\n const frontmatter = fmMatch[1];\n if (!/version:\\s*1/.test(frontmatter)) {\n errors.push(\"BRAINSTORM.md: frontmatter missing version: 1\");\n }\n\n return errors;\n}\n","/**\n * Phase 1: Deep Exploration — LLM reads key files and discovers conventions.\n *\n * This is the core innovation of storm onboard. Instead of generic analysis,\n * the LLM actually reads representative source files, test files, configs,\n * and git history to discover real conventions and domain concepts.\n *\n * File selection is deterministic (no LLM needed):\n * - Entry points (up to 5, first 100 lines each)\n * - Config files (tsconfig, package.json, CI, linter)\n * - README.md\n * - One test file (to discover testing patterns)\n * - One source file per module cluster (highest complexity)\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport type {\n OnboardContext,\n OnboardDispatcher,\n ExplorationResult,\n} from \"../types.js\";\nimport { buildExplorationPrompt } from \"../prompts/exploration.js\";\n\n/** Max lines to read from any single file. */\nconst MAX_LINES_PER_FILE = 100;\n/** Max files to include in the prompt. */\nconst MAX_FILES = 20;\n/** Max total characters for all file contents. */\nconst MAX_TOTAL_CHARS = 50_000;\n\ninterface PhaseResult {\n contextPatch: Partial<OnboardContext>;\n cost: number;\n summary: string;\n}\n\n/**\n * Run deep exploration: select key files, build prompt, call LLM.\n */\nexport async function runDeepExploration(\n context: OnboardContext,\n dispatcher: OnboardDispatcher,\n): Promise<PhaseResult> {\n const { analysis } = context;\n const gitSummary = (context as any)._gitSummary ?? \"\";\n\n // Select key files to include in the prompt\n const selectedFiles = selectKeyFiles(analysis);\n\n // Read file contents (truncated)\n const fileContents = readSelectedFiles(analysis.projectPath, selectedFiles);\n\n // Build the exploration prompt\n const prompt = buildExplorationPrompt(analysis, fileContents, gitSummary);\n\n // Call LLM\n const response = await dispatcher.generate(prompt, 0.3);\n\n // Parse the response as JSON\n let exploration: ExplorationResult;\n try {\n exploration = parseExplorationResponse(response.text);\n } catch (error) {\n // If JSON parse fails, return a minimal result\n exploration = createFallbackResult(analysis);\n }\n\n const conceptCount = exploration.domainConcepts.length;\n const conventionCount = countConventions(exploration.conventions);\n const workflowDesc = exploration.gitWorkflow.branchStrategy;\n\n return {\n contextPatch: { exploration },\n cost: response.cost,\n summary: `${conventionCount} conventions, ${conceptCount} domain concepts, ${workflowDesc} workflow`,\n };\n}\n\n/**\n * Select key files to include in the exploration prompt.\n * Deterministic selection — no LLM needed.\n */\nfunction selectKeyFiles(analysis: ProjectAnalysis): string[] {\n const files: string[] = [];\n const seen = new Set<string>();\n\n const add = (path: string) => {\n if (seen.has(path) || files.length >= MAX_FILES) return;\n seen.add(path);\n files.push(path);\n };\n\n // 1. Entry points (up to 5)\n for (const ep of analysis.dependencies.entryPoints.slice(0, 5)) {\n add(ep);\n }\n\n // 2. Config files\n const configFiles = [\n \"package.json\",\n \"tsconfig.json\",\n \"tsconfig.base.json\",\n \".eslintrc.json\",\n \".eslintrc.js\",\n \".eslintrc.cjs\",\n \"eslint.config.js\",\n \"eslint.config.mjs\",\n \".prettierrc\",\n \".prettierrc.json\",\n \"prettier.config.js\",\n \"turbo.json\",\n \"vercel.json\",\n \"next.config.js\",\n \"next.config.mjs\",\n \"next.config.ts\",\n \"vite.config.ts\",\n \"vitest.config.ts\",\n \"jest.config.ts\",\n \"jest.config.js\",\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n \".github/workflows/ci.yml\",\n \".github/workflows/ci.yaml\",\n \".github/workflows/test.yml\",\n \".github/workflows/deploy.yml\",\n ];\n\n for (const cf of configFiles) {\n const fullPath = join(analysis.projectPath, cf);\n if (existsSync(fullPath)) {\n add(cf);\n }\n }\n\n // 3. README\n for (const readme of [\"README.md\", \"readme.md\", \"Readme.md\"]) {\n const fullPath = join(analysis.projectPath, readme);\n if (existsSync(fullPath)) {\n add(readme);\n break;\n }\n }\n\n // 4. One test file (find first .test. or .spec. file)\n const testFile = findTestFile(analysis);\n if (testFile) add(testFile);\n\n // 5. Highest-complexity source file per module cluster (up to 5)\n for (const cluster of analysis.dependencies.clusters.slice(0, 5)) {\n const hottest = findHottestFile(analysis, cluster.files);\n if (hottest) add(hottest);\n }\n\n return files;\n}\n\n/**\n * Find a representative test file from the project.\n */\nfunction findTestFile(analysis: ProjectAnalysis): string | null {\n for (const node of analysis.dependencies.nodes) {\n if (\n node.path.includes(\".test.\") ||\n node.path.includes(\".spec.\") ||\n node.path.includes(\"__tests__/\")\n ) {\n return node.path;\n }\n }\n return null;\n}\n\n/**\n * Find the highest-complexity file in a set of file paths.\n */\nfunction findHottestFile(\n analysis: ProjectAnalysis,\n files: string[],\n): string | null {\n let best: { path: string; score: number } | null = null;\n for (const f of files) {\n const fc = analysis.complexity.files.find((c) => c.path === f);\n if (fc && (!best || fc.score > best.score)) {\n best = { path: fc.path, score: fc.score };\n }\n }\n return best?.path ?? files[0] ?? null;\n}\n\n/**\n * Read selected files, truncating each to MAX_LINES_PER_FILE.\n * Stops adding files if total characters would exceed MAX_TOTAL_CHARS.\n */\nfunction readSelectedFiles(\n projectPath: string,\n files: string[],\n): Map<string, string> {\n const contents = new Map<string, string>();\n let totalChars = 0;\n\n for (const file of files) {\n const fullPath = join(projectPath, file);\n if (!existsSync(fullPath)) continue;\n\n try {\n const raw = readFileSync(fullPath, \"utf-8\");\n const lines = raw.split(\"\\n\").slice(0, MAX_LINES_PER_FILE);\n const truncated = lines.join(\"\\n\");\n\n if (totalChars + truncated.length > MAX_TOTAL_CHARS) break;\n\n contents.set(file, truncated);\n totalChars += truncated.length;\n } catch {\n // Skip unreadable files (binary, permissions, etc.)\n }\n }\n\n return contents;\n}\n\n/**\n * Parse the LLM response as an ExplorationResult.\n * Handles JSON wrapped in markdown code fences.\n */\nfunction parseExplorationResponse(text: string): ExplorationResult {\n // Strip markdown code fences if present\n let json = text.trim();\n if (json.startsWith(\"```\")) {\n json = json.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n\n const parsed = JSON.parse(json);\n\n // Validate required fields exist (minimal check)\n if (!parsed.conventions || !parsed.domainConcepts || !parsed.gitWorkflow) {\n throw new Error(\"Missing required fields in exploration response\");\n }\n\n return parsed as ExplorationResult;\n}\n\n/**\n * Create a fallback ExplorationResult from static analysis\n * when the LLM response fails to parse.\n */\nfunction createFallbackResult(analysis: ProjectAnalysis): ExplorationResult {\n return {\n conventions: {\n naming: {\n variables: \"unknown\",\n files: \"unknown\",\n exports: \"unknown\",\n },\n errorHandling: \"unknown\",\n testingPatterns:\n analysis.frameworks.testing.length > 0\n ? `Uses ${analysis.frameworks.testing.join(\", \")}`\n : \"No testing framework detected\",\n importStyle: \"unknown\",\n customRules: [],\n },\n domainConcepts: [],\n gitWorkflow: {\n commitStyle: \"unknown\",\n branchStrategy: \"unknown\",\n prPatterns: \"unknown\",\n typicalPRSize: \"unknown\",\n activeContributors: 1,\n },\n cicdSetup: {\n provider: analysis.frameworks.ci?.[0] ?? \"none\",\n stages: [],\n deployTarget: analysis.frameworks.deployment?.[0] ?? \"none\",\n hasPreCommitHooks: false,\n },\n keyFiles: [],\n projectPurpose: `A ${analysis.summary.primaryLanguage} project using ${analysis.summary.frameworkList.join(\", \") || \"no detected frameworks\"}.`,\n };\n}\n\n/**\n * Count non-empty convention fields.\n */\nfunction countConventions(\n conventions: ExplorationResult[\"conventions\"],\n): number {\n let count = 0;\n if (conventions.naming.variables !== \"unknown\") count++;\n if (conventions.naming.files !== \"unknown\") count++;\n if (conventions.naming.components) count++;\n if (conventions.naming.exports !== \"unknown\") count++;\n if (conventions.errorHandling !== \"unknown\") count++;\n if (\n conventions.testingPatterns &&\n !conventions.testingPatterns.startsWith(\"No\")\n )\n count++;\n if (conventions.importStyle !== \"unknown\") count++;\n if (conventions.stateManagement) count++;\n if (conventions.apiPatterns) count++;\n count += conventions.customRules.length;\n return count;\n}\n","/**\n * Exploration Prompt — the heart of deep-exploration.\n *\n * Constructs a structured prompt that includes actual file contents\n * and asks the LLM to discover conventions, domain concepts, and\n * workflow patterns. Returns JSON matching ExplorationResult.\n */\n\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\n\n/**\n * Build the exploration prompt with file contents and git history.\n */\nexport function buildExplorationPrompt(\n analysis: ProjectAnalysis,\n fileContents: Map<string, string>,\n gitSummary: string,\n): string {\n const sections: string[] = [];\n\n // Header\n sections.push(`You are analyzing a codebase to understand its conventions, domain concepts, and development workflow.\nYour goal: produce a JSON object that captures everything a new AI agent would need to know before writing code in this project.\n\n## Project Overview\n- Path: ${analysis.projectPath}\n- Primary language: ${analysis.summary.primaryLanguage}\n- Frameworks: ${analysis.summary.frameworkList.join(\", \") || \"none detected\"}\n- Files: ${analysis.summary.totalFiles}, Lines: ${analysis.summary.totalLines.toLocaleString()}\n- Modules: ${analysis.summary.moduleCount}\n- Entry points: ${analysis.summary.entryPointCount}\n- API routes: ${analysis.summary.apiRouteCount}\n- Avg complexity: ${analysis.summary.avgComplexity.toFixed(1)}\n- Hotspots: ${analysis.summary.hotspotCount}`);\n\n // File contents\n if (fileContents.size > 0) {\n sections.push(\"\\n## Key Files\\n\");\n for (const [path, content] of fileContents) {\n sections.push(`### ${path}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\`\\n`);\n }\n }\n\n // Git history\n if (gitSummary) {\n sections.push(\n `## Recent Git History (last 30 commits)\\n\\`\\`\\`\\n${gitSummary}\\n\\`\\`\\``,\n );\n }\n\n // Detected frameworks detail\n if (analysis.frameworks.frameworks.length > 0) {\n sections.push(`## Detected Stack\n- Frameworks: ${analysis.frameworks.frameworks.join(\", \")}\n- Build tools: ${analysis.frameworks.buildTools.join(\", \") || \"none\"}\n- Databases: ${analysis.frameworks.databases.join(\", \") || \"none\"}\n- Testing: ${analysis.frameworks.testing.join(\", \") || \"none\"}\n- CI/CD: ${analysis.frameworks.ci?.join(\", \") || \"none\"}\n- Deployment: ${analysis.frameworks.deployment?.join(\", \") || \"none\"}`);\n }\n\n // Entry points\n if (analysis.dependencies.entryPoints.length > 0) {\n sections.push(\n `## Entry Points\\n${analysis.dependencies.entryPoints\n .slice(0, 10)\n .map((e) => `- ${e}`)\n .join(\"\\n\")}`,\n );\n }\n\n // Complexity hotspots\n if (analysis.complexity.summary.hotspots.length > 0) {\n sections.push(\n `## Complexity Hotspots\\n${analysis.complexity.summary.hotspots\n .slice(0, 10)\n .map((h) => `- ${h}`)\n .join(\"\\n\")}`,\n );\n }\n\n // Instructions\n sections.push(`\n## Instructions\n\nAnalyze all the information above and respond with a JSON object matching this exact schema:\n\n\\`\\`\\`json\n{\n \"conventions\": {\n \"naming\": {\n \"variables\": \"camelCase | snake_case | PascalCase\",\n \"files\": \"kebab-case | camelCase | PascalCase | snake_case\",\n \"components\": \"PascalCase (if applicable)\",\n \"exports\": \"named | default | barrel\"\n },\n \"errorHandling\": \"description of error handling patterns\",\n \"testingPatterns\": \"description of testing approach and file organization\",\n \"importStyle\": \"description of import patterns\",\n \"stateManagement\": \"description if frontend (null if not applicable)\",\n \"apiPatterns\": \"description of API design patterns (null if not applicable)\",\n \"customRules\": [\"any other conventions discovered\"]\n },\n \"domainConcepts\": [\n {\n \"name\": \"concept name\",\n \"definition\": \"what this concept means in the project\",\n \"relatedFiles\": [\"path/to/relevant/files\"]\n }\n ],\n \"gitWorkflow\": {\n \"commitStyle\": \"conventional commits | freeform | prefixed | etc.\",\n \"branchStrategy\": \"trunk-based | gitflow | github flow | unknown\",\n \"prPatterns\": \"squash merge | merge commits | rebase | unknown\",\n \"typicalPRSize\": \"small (<100 lines) | medium (100-500) | large (500+)\",\n \"activeContributors\": 1\n },\n \"cicdSetup\": {\n \"provider\": \"github-actions | vercel | circleci | none | etc.\",\n \"stages\": [\"lint\", \"test\", \"build\", \"deploy\"],\n \"deployTarget\": \"vercel | aws | docker | do-app-platform | none | etc.\",\n \"hasPreCommitHooks\": false\n },\n \"keyFiles\": [\n {\n \"path\": \"relative/path\",\n \"purpose\": \"what this file does\",\n \"summary\": \"2-3 sentence summary\"\n }\n ],\n \"projectPurpose\": \"One paragraph describing what this project does, its target users, and its primary value proposition.\"\n}\n\\`\\`\\`\n\nImportant:\n- Base ALL answers on the actual file contents and git history provided above\n- For conventions, look at actual patterns in the code — don't guess\n- For domain concepts, identify the core business/technical abstractions unique to this project\n- For git workflow, analyze the commit messages and file change patterns\n- Include 3-10 domain concepts and 5-15 key files\n- Respond ONLY with the JSON object, no markdown fencing or explanation`);\n\n return sections.join(\"\\n\\n\");\n}\n","/**\n * Phase 2: Team Assembly — generate specialized agents.\n *\n * Two-step process:\n * 1. Heuristic pre-filter: detect baseline agents from analysis signals (free)\n * 2. LLM enrichment: write rich system prompts with real conventions\n *\n * The heuristics decide WHICH agents to create. The LLM decides\n * WHAT they know (system prompt content).\n */\n\nimport { writeFileSync, mkdirSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ProjectAnalysis, ModuleCluster } from \"@brainst0rm/ingest\";\nimport type {\n OnboardContext,\n OnboardDispatcher,\n GeneratedAgent,\n} from \"../types.js\";\nimport {\n buildAssemblyPrompt,\n type AgentCandidate,\n} from \"../prompts/assembly.js\";\n\ninterface PhaseResult {\n contextPatch: Partial<OnboardContext>;\n cost: number;\n summary: string;\n filesWritten?: string[];\n}\n\nexport async function runTeamAssembly(\n context: OnboardContext,\n dispatcher: OnboardDispatcher,\n): Promise<PhaseResult> {\n const { analysis, exploration } = context;\n\n // Step 1: Heuristic candidate detection (free)\n const candidates = detectCandidates(analysis);\n\n // Step 2: LLM enrichment — generate rich system prompts\n const prompt = buildAssemblyPrompt(analysis, exploration, candidates);\n const response = await dispatcher.generate(prompt, 0.5);\n\n // Parse LLM response\n let enrichedAgents: Array<{\n id: string;\n role: string;\n modelHint?: string;\n tools?: string[] | \"all\";\n maxSteps?: number;\n budget?: number;\n systemPrompt: string;\n }>;\n\n try {\n let json = response.text.trim();\n if (json.startsWith(\"```\")) {\n json = json.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n enrichedAgents = JSON.parse(json);\n } catch {\n // Fallback: create agents with generic prompts\n enrichedAgents = candidates.map((c) => ({\n id: c.id,\n role: c.role,\n modelHint: c.modelHint,\n tools: c.tools,\n systemPrompt: buildFallbackPrompt(c, analysis),\n }));\n }\n\n // Generate .agent.md files\n const agentsDir = join(analysis.projectPath, \".brainstorm\", \"agents\");\n if (!existsSync(agentsDir)) mkdirSync(agentsDir, { recursive: true });\n\n const agents: GeneratedAgent[] = [];\n const filesWritten: string[] = [];\n\n for (const enriched of enrichedAgents) {\n const candidate = candidates.find((c) => c.id === enriched.id);\n const filePath = join(agentsDir, `${enriched.id}.agent.md`);\n\n const content = formatAgentMd(enriched);\n writeFileSync(filePath, content, \"utf-8\");\n\n agents.push({\n id: enriched.id,\n role: enriched.role as any,\n filePath,\n content,\n rationale: candidate?.rationale ?? \"LLM-generated\",\n });\n filesWritten.push(filePath);\n }\n\n const roleList = agents.map((a) => a.id).join(\", \");\n\n return {\n contextPatch: { agents },\n cost: response.cost,\n summary: `${agents.length} agents: ${roleList}`,\n filesWritten,\n };\n}\n\n/**\n * Detect agent candidates from static analysis signals.\n * No LLM needed — pure heuristic.\n */\nfunction detectCandidates(analysis: ProjectAnalysis): AgentCandidate[] {\n const candidates: AgentCandidate[] = [];\n\n // Always: architect\n candidates.push({\n id: \"architect\",\n role: \"architect\",\n rationale: \"Every project needs high-level design guidance\",\n modelHint: \"quality\",\n });\n\n // Always: code-reviewer\n candidates.push({\n id: \"code-reviewer\",\n role: \"code-reviewer\",\n rationale: \"Code review is critical for quality\",\n tools: [\"file_read\", \"grep\", \"glob\", \"git_diff\", \"git_log\"],\n modelHint: \"capable\",\n });\n\n // Frontend framework detected → frontend-expert\n const frontendFrameworks = [\n \"react\",\n \"nextjs\",\n \"next.js\",\n \"vue\",\n \"angular\",\n \"svelte\",\n ];\n if (\n analysis.frameworks.frameworks.some((f) =>\n frontendFrameworks.includes(f.toLowerCase()),\n )\n ) {\n candidates.push({\n id: \"frontend-expert\",\n role: \"coder\",\n rationale: `Frontend framework detected: ${analysis.frameworks.frameworks.filter((f) => frontendFrameworks.includes(f.toLowerCase())).join(\", \")}`,\n modelHint: \"capable\",\n });\n }\n\n // API routes detected → api-expert\n if (analysis.summary.apiRouteCount > 0) {\n candidates.push({\n id: \"api-expert\",\n role: \"coder\",\n rationale: `${analysis.summary.apiRouteCount} API routes detected`,\n modelHint: \"capable\",\n });\n }\n\n // Testing frameworks detected → qa\n if (analysis.frameworks.testing.length > 0) {\n candidates.push({\n id: \"qa\",\n role: \"qa\",\n rationale: `Testing with ${analysis.frameworks.testing.join(\", \")}`,\n modelHint: \"capable\",\n });\n }\n\n // CI/CD detected → devops\n if (analysis.frameworks.ci && analysis.frameworks.ci.length > 0) {\n candidates.push({\n id: \"devops\",\n role: \"devops\",\n rationale: `CI/CD detected: ${analysis.frameworks.ci.join(\", \")}`,\n tools: [\"file_read\", \"file_write\", \"grep\", \"glob\", \"shell\"],\n modelHint: \"capable\",\n });\n }\n\n // High complexity → security-reviewer\n if (\n analysis.summary.avgComplexity > 10 ||\n analysis.summary.hotspotCount > 5\n ) {\n candidates.push({\n id: \"security-reviewer\",\n role: \"security-reviewer\",\n rationale: `High complexity (avg ${analysis.summary.avgComplexity.toFixed(1)}) warrants security review`,\n tools: [\"file_read\", \"grep\", \"glob\"],\n modelHint: \"quality\",\n });\n }\n\n // Module-specific experts for top 3 complex clusters\n const topClusters = analysis.dependencies.clusters\n .filter((c) => c.files.length >= 3)\n .sort((a, b) => b.files.length - a.files.length)\n .slice(0, 3);\n\n for (const cluster of topClusters) {\n const safeName = cluster.directory\n .replace(/[/\\\\]/g, \"-\")\n .replace(/^-/, \"\")\n .replace(/-$/, \"\");\n\n if (!safeName || candidates.some((c) => c.id === `${safeName}-expert`))\n continue;\n\n candidates.push({\n id: `${safeName}-expert`,\n role: \"coder\",\n rationale: `Module \"${cluster.directory}\" has ${cluster.files.length} files`,\n moduleScope: cluster,\n modelHint: \"capable\",\n });\n }\n\n return candidates;\n}\n\n/**\n * Format an enriched agent into .agent.md content.\n */\nfunction formatAgentMd(agent: {\n id: string;\n role: string;\n modelHint?: string;\n tools?: string[] | \"all\";\n maxSteps?: number;\n budget?: number;\n systemPrompt: string;\n}): string {\n const lines: string[] = [\"---\"];\n lines.push(`name: ${agent.id}`);\n lines.push(`role: ${agent.role}`);\n lines.push(`model: ${agent.modelHint ?? \"capable\"}`);\n if (agent.tools && agent.tools !== \"all\") {\n lines.push(`tools: [${agent.tools.map((t) => `\"${t}\"`).join(\", \")}]`);\n }\n if (agent.maxSteps) lines.push(`max_steps: ${agent.maxSteps}`);\n if (agent.budget) lines.push(`budget: ${agent.budget}`);\n lines.push(\"---\");\n lines.push(\"\");\n lines.push(agent.systemPrompt);\n return lines.join(\"\\n\");\n}\n\n/**\n * Build a fallback system prompt when LLM fails.\n */\nfunction buildFallbackPrompt(\n candidate: AgentCandidate,\n analysis: ProjectAnalysis,\n): string {\n const lines: string[] = [\n `# ${candidate.id}`,\n \"\",\n `You are a ${candidate.role} for a ${analysis.summary.primaryLanguage} project.`,\n \"\",\n `## Context`,\n `- Language: ${analysis.summary.primaryLanguage}`,\n `- Frameworks: ${analysis.summary.frameworkList.join(\", \") || \"none\"}`,\n `- ${analysis.summary.totalFiles} files, ${analysis.summary.totalLines.toLocaleString()} lines`,\n ];\n\n if (candidate.moduleScope) {\n lines.push(\n \"\",\n `## Module Scope: ${candidate.moduleScope.directory}`,\n `- Files: ${candidate.moduleScope.files.length}`,\n `- Cohesion: ${candidate.moduleScope.cohesion > 0.5 ? \"high\" : candidate.moduleScope.cohesion > 0.2 ? \"medium\" : \"low\"}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Assembly Prompt — generates enriched agent system prompts.\n *\n * Takes heuristic agent candidates + exploration results and asks\n * the LLM to write rich system prompts that embed actual conventions,\n * domain knowledge, and module-specific context.\n */\n\nimport type { ExplorationResult, GeneratedAgent } from \"../types.js\";\nimport type { ProjectAnalysis, ModuleCluster } from \"@brainst0rm/ingest\";\n\nexport interface AgentCandidate {\n id: string;\n role: string;\n rationale: string;\n moduleScope?: ModuleCluster;\n tools?: string[];\n modelHint?: string;\n}\n\nexport function buildAssemblyPrompt(\n analysis: ProjectAnalysis,\n exploration: ExplorationResult | undefined,\n candidates: AgentCandidate[],\n): string {\n const sections: string[] = [];\n\n sections.push(`You are designing a team of specialized AI agents for a codebase. Each agent needs a rich system prompt that embeds the project's actual conventions, domain knowledge, and module context.\n\n## Project\n${exploration?.projectPurpose ?? `A ${analysis.summary.primaryLanguage} project with ${analysis.summary.totalFiles} files.`}\n\n## Stack\n- Language: ${analysis.summary.primaryLanguage}\n- Frameworks: ${analysis.summary.frameworkList.join(\", \") || \"none\"}\n- Testing: ${analysis.frameworks.testing.join(\", \") || \"none\"}\n- Modules: ${analysis.summary.moduleCount}\n- Complexity: avg ${analysis.summary.avgComplexity.toFixed(1)}`);\n\n if (exploration) {\n sections.push(`## Conventions\n- Naming: variables=${exploration.conventions.naming.variables}, files=${exploration.conventions.naming.files}\n- Error handling: ${exploration.conventions.errorHandling}\n- Testing: ${exploration.conventions.testingPatterns}\n- Imports: ${exploration.conventions.importStyle}${exploration.conventions.stateManagement ? `\\n- State: ${exploration.conventions.stateManagement}` : \"\"}${exploration.conventions.apiPatterns ? `\\n- API: ${exploration.conventions.apiPatterns}` : \"\"}\n- Rules: ${exploration.conventions.customRules.join(\"; \") || \"none\"}`);\n\n if (exploration.domainConcepts.length > 0) {\n sections.push(`## Domain Concepts\n${exploration.domainConcepts.map((c) => `- **${c.name}**: ${c.definition}`).join(\"\\n\")}`);\n }\n }\n\n // Agent candidates\n sections.push(`## Agent Candidates\n\nGenerate a .agent.md system prompt for EACH of the following agents. The system prompt should be 10-30 lines of markdown that a code-writing AI reads before starting work.\n\n${candidates\n .map((c, i) => {\n let desc = `### Agent ${i + 1}: ${c.id} (${c.role})\n- Rationale: ${c.rationale}`;\n if (c.tools) desc += `\\n- Allowed tools: ${c.tools.join(\", \")}`;\n if (c.moduleScope) {\n desc += `\\n- Module scope: ${c.moduleScope.directory} (${c.moduleScope.files.length} files, cohesion: ${c.moduleScope.cohesion.toFixed(2)})`;\n }\n return desc;\n })\n .join(\"\\n\\n\")}`);\n\n sections.push(`## Instructions\n\nFor each agent candidate, generate a complete .agent.md file. Respond with a JSON array of objects:\n\n\\`\\`\\`json\n[\n {\n \"id\": \"agent-id\",\n \"role\": \"role\",\n \"modelHint\": \"quality | capable | cheap\",\n \"tools\": [\"tool1\", \"tool2\"] or \"all\",\n \"maxSteps\": 10,\n \"budget\": 5.0,\n \"systemPrompt\": \"The full markdown system prompt content...\"\n }\n]\n\\`\\`\\`\n\nEach systemPrompt MUST include:\n1. A clear role definition (what this agent does)\n2. Project-specific conventions (from the conventions section above)\n3. Domain concepts relevant to this agent's scope\n4. Specific do's and don'ts for this codebase\n5. Module context if the agent has a module scope\n\nKeep prompts actionable and specific. Avoid generic advice like \"write clean code.\"\nRespond ONLY with the JSON array, no markdown fencing or explanation.`);\n\n return sections.join(\"\\n\\n\");\n}\n","/**\n * Phase 3: Routing Rules — wire agents to task types.\n *\n * Two-step:\n * 1. Heuristic rules from analysis signals + agent list (free)\n * 2. LLM review to adjust and add project-specific rules\n *\n * Output: routing.yaml in .brainstorm/ directory.\n */\n\nimport { writeFileSync, mkdirSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport type {\n OnboardContext,\n OnboardDispatcher,\n GeneratedRoutingRule,\n GeneratedAgent,\n} from \"../types.js\";\nimport { buildRoutingPrompt } from \"../prompts/routing.js\";\n\ninterface PhaseResult {\n contextPatch: Partial<OnboardContext>;\n cost: number;\n summary: string;\n filesWritten?: string[];\n}\n\nexport async function runRoutingRules(\n context: OnboardContext,\n dispatcher: OnboardDispatcher,\n): Promise<PhaseResult> {\n const { analysis, agents } = context;\n\n if (!agents || agents.length === 0) {\n return {\n contextPatch: { routingRules: [] },\n cost: 0,\n summary: \"No agents to route to (skipped)\",\n };\n }\n\n // Step 1: Heuristic rules (free)\n const heuristicRules = generateHeuristicRules(analysis, agents);\n\n // Step 2: LLM review\n const prompt = buildRoutingPrompt(analysis, agents, heuristicRules);\n const response = await dispatcher.generate(prompt, 0.08);\n\n let rules: GeneratedRoutingRule[];\n try {\n let json = response.text.trim();\n if (json.startsWith(\"```\")) {\n json = json.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n rules = JSON.parse(json);\n } catch {\n // Fall back to heuristic rules\n rules = heuristicRules;\n }\n\n // Write routing.yaml\n const brainstormDir = join(analysis.projectPath, \".brainstorm\");\n if (!existsSync(brainstormDir)) mkdirSync(brainstormDir, { recursive: true });\n\n const routingPath = join(brainstormDir, \"routing.yaml\");\n const yamlContent = formatRoutingYaml(rules);\n writeFileSync(routingPath, yamlContent, \"utf-8\");\n\n return {\n contextPatch: { routingRules: rules },\n cost: response.cost,\n summary: `${rules.length} routing rules`,\n filesWritten: [routingPath],\n };\n}\n\n/**\n * Generate heuristic routing rules from analysis + agents.\n */\nfunction generateHeuristicRules(\n analysis: ProjectAnalysis,\n agents: GeneratedAgent[],\n): GeneratedRoutingRule[] {\n const rules: GeneratedRoutingRule[] = [];\n const agentIds = new Set(agents.map((a) => a.id));\n\n // Code review → code-reviewer\n if (agentIds.has(\"code-reviewer\")) {\n rules.push({\n match: \"code-review\",\n agentId: \"code-reviewer\",\n modelHint: \"capable\",\n rationale: \"Route review tasks to dedicated reviewer\",\n });\n }\n\n // Architecture/design → architect\n if (agentIds.has(\"architect\")) {\n rules.push({\n match: \"architecture\",\n agentId: \"architect\",\n modelHint: \"quality\",\n rationale: \"Design tasks need quality-tier reasoning\",\n });\n rules.push({\n match: \"refactoring\",\n agentId: \"architect\",\n modelHint: \"quality\",\n rationale: \"Refactoring needs architectural awareness\",\n });\n }\n\n // Frontend tasks → frontend-expert\n if (agentIds.has(\"frontend-expert\")) {\n rules.push({\n match: \"frontend\",\n agentId: \"frontend-expert\",\n modelHint: \"capable\",\n rationale: \"Frontend-specific tasks\",\n });\n rules.push({\n match: \"component\",\n agentId: \"frontend-expert\",\n modelHint: \"capable\",\n rationale: \"Component creation/modification\",\n });\n }\n\n // API tasks → api-expert\n if (agentIds.has(\"api-expert\")) {\n rules.push({\n match: \"api\",\n agentId: \"api-expert\",\n modelHint: \"capable\",\n rationale: `${analysis.summary.apiRouteCount} API routes in project`,\n });\n rules.push({\n match: \"endpoint\",\n agentId: \"api-expert\",\n modelHint: \"capable\",\n rationale: \"Endpoint creation/modification\",\n });\n }\n\n // Testing → qa\n if (agentIds.has(\"qa\")) {\n rules.push({\n match: \"test\",\n agentId: \"qa\",\n modelHint: \"capable\",\n rationale: \"Test writing and debugging\",\n });\n }\n\n // Security → security-reviewer\n if (agentIds.has(\"security-reviewer\")) {\n rules.push({\n match: \"security\",\n agentId: \"security-reviewer\",\n modelHint: \"quality\",\n rationale: \"Security tasks need thorough analysis\",\n });\n rules.push({\n match: \"audit\",\n agentId: \"security-reviewer\",\n modelHint: \"quality\",\n rationale: \"Code audits are security-adjacent\",\n });\n }\n\n // CI/CD → devops\n if (agentIds.has(\"devops\")) {\n rules.push({\n match: \"deploy\",\n agentId: \"devops\",\n modelHint: \"capable\",\n rationale: \"Deployment and infrastructure tasks\",\n });\n rules.push({\n match: \"ci\",\n agentId: \"devops\",\n modelHint: \"capable\",\n rationale: \"CI/CD pipeline tasks\",\n });\n }\n\n // General code generation → first coder agent\n const coderAgent = agents.find(\n (a) => a.role === \"coder\" && !a.id.includes(\"-expert\"),\n );\n if (coderAgent) {\n rules.push({\n match: \"code-generation\",\n agentId: coderAgent.id,\n modelHint: \"capable\",\n rationale: \"General code generation\",\n });\n }\n\n // Debugging → first available coder or debugger\n const debugAgent = agents.find((a) => a.role === \"debugger\") ?? coderAgent;\n if (debugAgent) {\n rules.push({\n match: \"debugging\",\n agentId: debugAgent.id,\n modelHint: \"capable\",\n rationale: \"Bug investigation and fixing\",\n });\n }\n\n return rules;\n}\n\n/**\n * Format routing rules as YAML.\n */\nfunction formatRoutingYaml(rules: GeneratedRoutingRule[]): string {\n const lines: string[] = [\n \"# Brainstorm Routing Rules\",\n \"# Generated by `storm onboard` — maps task patterns to specialized agents.\",\n \"#\",\n \"# Format: match pattern → agent ID, model tier, rationale\",\n \"# Edit freely — these rules override heuristic routing.\",\n \"\",\n \"rules:\",\n ];\n\n for (const rule of rules) {\n lines.push(` - match: \"${rule.match}\"`);\n lines.push(` agent: ${rule.agentId}`);\n if (rule.modelHint) lines.push(` model: ${rule.modelHint}`);\n lines.push(` # ${rule.rationale}`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Routing Prompt — generates task-to-agent routing rules.\n *\n * Takes heuristic rule candidates + agent list and asks the LLM\n * to review, adjust, and add project-specific rules.\n */\n\nimport type { GeneratedAgent, GeneratedRoutingRule } from \"../types.js\";\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\n\nexport function buildRoutingPrompt(\n analysis: ProjectAnalysis,\n agents: GeneratedAgent[],\n heuristicRules: GeneratedRoutingRule[],\n): string {\n return `You are configuring task routing for an AI coding assistant. Each task should be routed to the most appropriate specialized agent.\n\n## Available Agents\n${agents.map((a) => `- **${a.id}** (${a.role}): ${a.rationale}`).join(\"\\n\")}\n\n## Project Context\n- Language: ${analysis.summary.primaryLanguage}\n- Frameworks: ${analysis.summary.frameworkList.join(\", \") || \"none\"}\n- ${analysis.summary.apiRouteCount} API routes, ${analysis.summary.moduleCount} modules\n\n## Heuristic Rules (auto-generated)\nThese rules were generated from static analysis. Review them and add any project-specific rules.\n\n${heuristicRules.map((r) => `- match: \"${r.match}\" → agent: ${r.agentId} (${r.modelHint ?? \"auto\"}) — ${r.rationale}`).join(\"\\n\")}\n\n## Instructions\n\nReturn a JSON array of routing rules. Include the heuristic rules (adjusted if needed) plus any additional project-specific rules.\n\n\\`\\`\\`json\n[\n {\n \"match\": \"task type or keyword pattern\",\n \"agentId\": \"agent-id\",\n \"modelHint\": \"quality | capable | cheap\",\n \"rationale\": \"why this rule exists\"\n }\n]\n\\`\\`\\`\n\nGuidelines:\n- \"match\" should be a task type (code-generation, debugging, refactoring, etc.) or keyword pattern\n- Every agent should have at least one routing rule\n- Security-sensitive tasks should route to quality-tier models\n- Simple fixes can use cheap-tier models\n- Respond ONLY with the JSON array`;\n}\n","/**\n * Phase 4: Workflow Generation — create project-specific recipes.\n *\n * Two-step:\n * 1. Heuristic recipe detection from analysis (free)\n * 2. LLM customization of step descriptions\n *\n * Output: YAML recipe files in .brainstorm/recipes/\n */\n\nimport { writeFileSync, mkdirSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport type {\n OnboardContext,\n OnboardDispatcher,\n GeneratedRecipe,\n} from \"../types.js\";\nimport { buildWorkflowPrompt } from \"../prompts/workflow.js\";\n\ninterface PhaseResult {\n contextPatch: Partial<OnboardContext>;\n cost: number;\n summary: string;\n filesWritten?: string[];\n}\n\nexport async function runWorkflowGen(\n context: OnboardContext,\n dispatcher: OnboardDispatcher,\n): Promise<PhaseResult> {\n const { analysis, exploration } = context;\n\n // Step 1: Heuristic recipe generation (free)\n const heuristicRecipes = generateHeuristicRecipes(analysis);\n\n if (heuristicRecipes.length === 0) {\n return {\n contextPatch: { recipes: [] },\n cost: 0,\n summary: \"No recipes generated (project too simple)\",\n };\n }\n\n // Step 2: LLM customization\n const prompt = buildWorkflowPrompt(analysis, exploration, heuristicRecipes);\n const response = await dispatcher.generate(prompt, 0.1);\n\n let recipes: GeneratedRecipe[];\n try {\n let json = response.text.trim();\n if (json.startsWith(\"```\")) {\n json = json.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n recipes = JSON.parse(json);\n } catch {\n // Fall back to heuristic recipes\n recipes = heuristicRecipes;\n }\n\n // Write recipe files\n const recipesDir = join(analysis.projectPath, \".brainstorm\", \"recipes\");\n if (!existsSync(recipesDir)) mkdirSync(recipesDir, { recursive: true });\n\n const filesWritten: string[] = [];\n for (const recipe of recipes) {\n const recipePath = join(recipesDir, recipe.filename);\n writeFileSync(recipePath, recipe.content, \"utf-8\");\n filesWritten.push(recipePath);\n }\n\n const recipeNames = recipes\n .map((r) => r.filename.replace(\".yaml\", \"\"))\n .join(\", \");\n\n return {\n contextPatch: { recipes },\n cost: response.cost,\n summary: `${recipes.length} recipes: ${recipeNames}`,\n filesWritten,\n };\n}\n\n/**\n * Generate heuristic recipes based on detected project patterns.\n */\nfunction generateHeuristicRecipes(\n analysis: ProjectAnalysis,\n): GeneratedRecipe[] {\n const recipes: GeneratedRecipe[] = [];\n const frameworks = analysis.frameworks.frameworks.map((f) => f.toLowerCase());\n const hasTests = analysis.frameworks.testing.length > 0;\n const hasCI = analysis.frameworks.ci && analysis.frameworks.ci.length > 0;\n const isMonorepo =\n frameworks.includes(\"turborepo\") || frameworks.includes(\"lerna\");\n\n // PR-ready recipe: implement → test → review\n if (hasTests) {\n const testTool = analysis.frameworks.testing[0] ?? \"test runner\";\n recipes.push({\n filename: \"pr-ready.yaml\",\n content: buildPrReadyRecipe(analysis, testTool),\n description: \"Full PR workflow: plan → implement → test → review\",\n });\n }\n\n // Multi-package change recipe for monorepos\n if (isMonorepo) {\n recipes.push({\n filename: \"multi-package-change.yaml\",\n content: buildMultiPackageRecipe(analysis),\n description: \"Coordinate changes across multiple packages\",\n });\n }\n\n // Deploy flow recipe\n if (hasCI) {\n recipes.push({\n filename: \"deploy-flow.yaml\",\n content: buildDeployRecipe(analysis),\n description: \"Implement → verify → deploy pipeline\",\n });\n }\n\n return recipes;\n}\n\nfunction buildPrReadyRecipe(\n analysis: ProjectAnalysis,\n testTool: string,\n): string {\n const buildCmd = inferBuildCmd(analysis);\n const testCmd = inferTestCmd(analysis, testTool);\n\n return `name: PR Ready\ndescription: Full workflow from plan to review-ready PR\ncommunication: handoff\nmaxIterations: 2\nsteps:\n - id: plan\n role: architect\n description: \"Analyze the task and create an implementation plan with file changes needed\"\n output: spec\n outputSchema: implementation-spec\n\n - id: implement\n role: coder\n description: \"Implement the changes according to the plan\"\n input: [spec]\n output: code\n\n - id: test\n role: qa\n description: \"Run ${testTool} tests and verify the changes work correctly (${testCmd})\"\n input: [spec, code]\n output: test-result\n\n - id: review\n role: code-reviewer\n description: \"Review for correctness, conventions, and potential issues\"\n input: [spec, code, test-result]\n output: review\n review: true\n loopBack: implement\n`;\n}\n\nfunction buildMultiPackageRecipe(analysis: ProjectAnalysis): string {\n return `name: Multi-Package Change\ndescription: Coordinate changes across multiple monorepo packages\ncommunication: handoff\nmaxIterations: 2\nsteps:\n - id: plan\n role: architect\n description: \"Map which packages need changes and their dependency order\"\n output: spec\n outputSchema: implementation-spec\n\n - id: implement\n role: coder\n description: \"Implement changes in dependency order — leaf packages first, dependents after\"\n input: [spec]\n output: code\n\n - id: verify\n role: qa\n description: \"Run full monorepo build (npx turbo run build) and tests to verify cross-package compatibility\"\n input: [spec, code]\n output: test-result\n\n - id: review\n role: code-reviewer\n description: \"Review for cross-package consistency and interface contracts\"\n input: [spec, code, test-result]\n output: review\n review: true\n loopBack: implement\n`;\n}\n\nfunction buildDeployRecipe(analysis: ProjectAnalysis): string {\n return `name: Deploy Flow\ndescription: Implement, verify, and prepare for deployment\ncommunication: handoff\nmaxIterations: 2\nsteps:\n - id: implement\n role: coder\n description: \"Implement the changes\"\n output: code\n\n - id: verify\n role: qa\n description: \"Run build and tests to verify deployment readiness\"\n input: [code]\n output: test-result\n\n - id: deploy-prep\n role: devops\n description: \"Review deployment configuration and prepare deployment steps\"\n input: [code, test-result]\n output: deploy-plan\n\n - id: review\n role: code-reviewer\n description: \"Final review before deployment\"\n input: [code, test-result, deploy-plan]\n output: review\n review: true\n loopBack: implement\n`;\n}\n\nfunction inferBuildCmd(analysis: ProjectAnalysis): string {\n const frameworks = analysis.frameworks.frameworks.map((f) => f.toLowerCase());\n if (frameworks.includes(\"turborepo\")) return \"npx turbo run build\";\n return \"npm run build\";\n}\n\nfunction inferTestCmd(analysis: ProjectAnalysis, testTool: string): string {\n const lower = testTool.toLowerCase();\n if (lower.includes(\"vitest\")) return \"npx vitest run\";\n if (lower.includes(\"jest\")) return \"npx jest\";\n if (lower.includes(\"pytest\")) return \"pytest\";\n return \"npm test\";\n}\n","/**\n * Workflow Prompt — customizes recipe step descriptions.\n *\n * Takes heuristic recipe templates and asks the LLM to customize\n * step descriptions with project-specific conventions.\n */\n\nimport type { ExplorationResult, GeneratedRecipe } from \"../types.js\";\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\n\nexport function buildWorkflowPrompt(\n analysis: ProjectAnalysis,\n exploration: ExplorationResult | undefined,\n heuristicRecipes: GeneratedRecipe[],\n): string {\n return `You are customizing workflow recipes for a project. Each recipe defines a multi-step workflow where AI agents collaborate.\n\n## Project\n- Language: ${analysis.summary.primaryLanguage}\n- Frameworks: ${analysis.summary.frameworkList.join(\", \") || \"none\"}\n- Testing: ${analysis.frameworks.testing.join(\", \") || \"none\"}\n${\n exploration\n ? `- Conventions: ${exploration.conventions.testingPatterns}\n- Error handling: ${exploration.conventions.errorHandling}\n- Commit style: ${exploration.gitWorkflow.commitStyle}\n- CI stages: ${exploration.cicdSetup.stages.join(\" → \") || \"unknown\"}`\n : \"\"\n}\n\n## Heuristic Recipes\nThese recipes were auto-generated. Customize the step descriptions to match this project's conventions.\n\n${heuristicRecipes.map((r) => `### ${r.filename}\\n\\`\\`\\`yaml\\n${r.content}\\n\\`\\`\\``).join(\"\\n\\n\")}\n\n## Instructions\n\nReturn a JSON array of customized recipes. Keep the same structure but improve the step descriptions to be project-specific.\n\n\\`\\`\\`json\n[\n {\n \"filename\": \"recipe-name.yaml\",\n \"content\": \"full YAML content\",\n \"description\": \"what this recipe does\"\n }\n]\n\\`\\`\\`\n\nGuidelines:\n- Reference actual testing frameworks (${analysis.frameworks.testing.join(\", \") || \"none\"})\n- Reference actual build tools (${analysis.frameworks.buildTools.join(\", \") || \"none\"})\n- Step descriptions should be actionable and project-specific\n- Keep YAML syntax valid\n- Respond ONLY with the JSON array`;\n}\n","/**\n * Phase 5: BRAINSTORM.md Enhancement — generates rich project context.\n *\n * Combines deterministic frontmatter (from analysis) with LLM-generated\n * prose sections (architecture, gotchas, anti-patterns). The result is\n * a BRAINSTORM.md that gives agents real context before their first task.\n *\n * Frontmatter uses StormFrontmatter schema from @brainst0rm/config.\n */\n\nimport { writeFileSync, existsSync } from \"node:fs\";\nimport { join, basename } from \"node:path\";\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport type {\n OnboardContext,\n OnboardDispatcher,\n ExplorationResult,\n} from \"../types.js\";\nimport { buildEnrichmentPrompt } from \"../prompts/enrichment.js\";\n\ninterface PhaseResult {\n contextPatch: Partial<OnboardContext>;\n cost: number;\n summary: string;\n filesWritten?: string[];\n}\n\nexport async function runBrainstormMd(\n context: OnboardContext,\n dispatcher: OnboardDispatcher,\n): Promise<PhaseResult> {\n const { analysis, exploration, agents } = context;\n const projectName = basename(analysis.projectPath);\n\n // Build frontmatter deterministically\n const frontmatter = buildFrontmatter(analysis, exploration);\n\n // Build deterministic body sections\n const staticSections = buildStaticSections(\n analysis,\n exploration,\n agents?.map((a) => ({ id: a.id, role: a.role })),\n );\n\n // Get LLM-generated prose\n let proseSections = \"\";\n let cost = 0;\n\n const prompt = buildEnrichmentPrompt(analysis, exploration, agents);\n const response = await dispatcher.explore(prompt, 0.2);\n proseSections = response.text;\n cost = response.cost;\n\n // Assemble the full BRAINSTORM.md\n const content = assembleBrainstormMd(\n frontmatter,\n projectName,\n staticSections,\n proseSections,\n );\n\n // Write to disk\n const outputPath = join(analysis.projectPath, \"BRAINSTORM.md\");\n const isUpdate = existsSync(outputPath);\n writeFileSync(outputPath, content, \"utf-8\");\n\n return {\n contextPatch: { brainstormMd: content },\n cost,\n summary: `${isUpdate ? \"Updated\" : \"Generated\"} with conventions, domain glossary, architecture`,\n filesWritten: [outputPath],\n };\n}\n\n/**\n * Build StormFrontmatter YAML from analysis.\n */\nfunction buildFrontmatter(\n analysis: ProjectAnalysis,\n exploration?: ExplorationResult,\n): string {\n const lines: string[] = [\"---\", \"version: 1\"];\n\n // Project identity\n lines.push(`name: ${basename(analysis.projectPath)}`);\n\n // Type inference\n const type = inferProjectType(analysis);\n if (type) lines.push(`type: ${type}`);\n\n // Language\n const lang = mapLanguage(analysis.summary.primaryLanguage);\n if (lang) lines.push(`language: ${lang}`);\n\n // Framework\n const framework = mapFramework(analysis.frameworks.frameworks);\n lines.push(`framework: ${framework}`);\n\n // Runtime\n const runtime = inferRuntime(analysis);\n lines.push(`runtime: ${runtime}`);\n\n // Deploy target\n const deploy = inferDeployTarget(analysis, exploration);\n lines.push(`deploy: ${deploy}`);\n\n // Commands\n const buildCmd = inferBuildCommand(analysis);\n if (buildCmd) lines.push(`build_command: \"${buildCmd}\"`);\n\n const testCmd = inferTestCommand(analysis);\n if (testCmd) lines.push(`test_command: \"${testCmd}\"`);\n\n // Entry points\n if (analysis.dependencies.entryPoints.length > 0) {\n const eps = analysis.dependencies.entryPoints\n .slice(0, 5)\n .map((e) => `\"${e}\"`)\n .join(\", \");\n lines.push(`entry_points: [${eps}]`);\n }\n\n // Routing hints\n lines.push(\"routing:\");\n lines.push(` typical_complexity: ${inferComplexity(analysis)}`);\n lines.push(` budget_tier: ${inferBudgetTier(analysis)}`);\n\n lines.push(\"---\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Build deterministic body sections from analysis + exploration.\n */\nfunction buildStaticSections(\n analysis: ProjectAnalysis,\n exploration?: ExplorationResult,\n agents?: Array<{ id: string; role: string }>,\n): string {\n const sections: string[] = [];\n\n // Stack\n sections.push(\"## Stack\\n\");\n if (analysis.summary.primaryLanguage)\n sections.push(`- **Language:** ${analysis.summary.primaryLanguage}`);\n if (analysis.summary.frameworkList.length > 0)\n sections.push(\n `- **Frameworks:** ${analysis.summary.frameworkList.join(\", \")}`,\n );\n if (analysis.frameworks.databases.length > 0)\n sections.push(\n `- **Databases:** ${analysis.frameworks.databases.join(\", \")}`,\n );\n if (analysis.frameworks.testing.length > 0)\n sections.push(`- **Testing:** ${analysis.frameworks.testing.join(\", \")}`);\n if (analysis.frameworks.buildTools.length > 0)\n sections.push(`- **Build:** ${analysis.frameworks.buildTools.join(\", \")}`);\n sections.push(\n `- **Size:** ${analysis.summary.totalFiles} files, ${analysis.summary.totalLines.toLocaleString()} lines, ${analysis.summary.moduleCount} modules`,\n );\n\n // Conventions (from exploration)\n if (exploration) {\n sections.push(\"\\n## Conventions\\n\");\n const c = exploration.conventions;\n sections.push(\n `- **Naming:** variables=${c.naming.variables}, files=${c.naming.files}, exports=${c.naming.exports}`,\n );\n sections.push(`- **Error handling:** ${c.errorHandling}`);\n sections.push(`- **Testing:** ${c.testingPatterns}`);\n sections.push(`- **Imports:** ${c.importStyle}`);\n if (c.stateManagement)\n sections.push(`- **State management:** ${c.stateManagement}`);\n if (c.apiPatterns) sections.push(`- **API patterns:** ${c.apiPatterns}`);\n if (c.customRules.length > 0) {\n for (const rule of c.customRules) {\n sections.push(`- ${rule}`);\n }\n }\n }\n\n // Domain glossary\n if (exploration && exploration.domainConcepts.length > 0) {\n sections.push(\"\\n## Domain Glossary\\n\");\n for (const concept of exploration.domainConcepts) {\n sections.push(`- **${concept.name}:** ${concept.definition}`);\n }\n }\n\n // Key files\n if (exploration && exploration.keyFiles.length > 0) {\n sections.push(\"\\n## Key Files\\n\");\n for (const kf of exploration.keyFiles) {\n sections.push(`- \\`${kf.path}\\` — ${kf.purpose}`);\n }\n }\n\n // Team (agents)\n if (agents && agents.length > 0) {\n sections.push(\"\\n## AI Team\\n\");\n for (const a of agents) {\n sections.push(`- **${a.id}** (${a.role})`);\n }\n }\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Assemble the full BRAINSTORM.md from parts.\n */\nfunction assembleBrainstormMd(\n frontmatter: string,\n projectName: string,\n staticSections: string,\n proseSections: string,\n): string {\n const parts = [frontmatter, \"\", `# ${projectName}`, \"\", staticSections];\n\n if (proseSections) {\n parts.push(\"\", proseSections.trim());\n }\n\n return parts.join(\"\\n\") + \"\\n\";\n}\n\n// ── Inference Helpers ──────────────────────────────────────────────\n\nfunction inferProjectType(analysis: ProjectAnalysis): string | null {\n const frameworks = analysis.frameworks.frameworks.map((f) => f.toLowerCase());\n if (frameworks.includes(\"turborepo\") || frameworks.includes(\"lerna\"))\n return \"monorepo\";\n if (\n frameworks.some((f) =>\n [\"nextjs\", \"react\", \"vue\", \"angular\", \"svelte\"].includes(f),\n )\n )\n return \"app\";\n if (\n analysis.dependencies.entryPoints.some(\n (e) => e.includes(\"cli\") || e.includes(\"bin\"),\n )\n )\n return \"cli\";\n if (analysis.summary.apiRouteCount > 0) return \"api\";\n return null;\n}\n\nfunction mapLanguage(primary: string): string | null {\n const map: Record<string, string> = {\n TypeScript: \"typescript\",\n JavaScript: \"typescript\",\n Python: \"python\",\n Rust: \"rust\",\n Go: \"go\",\n Java: \"java\",\n };\n return map[primary] ?? null;\n}\n\nfunction mapFramework(frameworks: string[]): string {\n const lower = frameworks.map((f) => f.toLowerCase());\n if (lower.includes(\"nextjs\") || lower.includes(\"next.js\")) return \"nextjs\";\n if (lower.includes(\"hono\")) return \"hono\";\n if (lower.includes(\"fastapi\")) return \"fastapi\";\n if (lower.includes(\"express\")) return \"express\";\n return \"none\";\n}\n\nfunction inferRuntime(analysis: ProjectAnalysis): string {\n const lang = analysis.summary.primaryLanguage.toLowerCase();\n if (lang === \"python\") return \"python\";\n if (lang === \"go\") return \"go\";\n return \"node\";\n}\n\nfunction inferDeployTarget(\n analysis: ProjectAnalysis,\n exploration?: ExplorationResult,\n): string {\n if (\n exploration?.cicdSetup.deployTarget &&\n exploration.cicdSetup.deployTarget !== \"none\"\n ) {\n return exploration.cicdSetup.deployTarget;\n }\n const deploy = analysis.frameworks.deployment ?? [];\n if (deploy.some((d) => d.toLowerCase().includes(\"vercel\"))) return \"vercel\";\n if (deploy.some((d) => d.toLowerCase().includes(\"docker\"))) return \"docker\";\n return \"none\";\n}\n\nfunction inferBuildCommand(analysis: ProjectAnalysis): string | null {\n const frameworks = analysis.frameworks.frameworks.map((f) => f.toLowerCase());\n if (frameworks.includes(\"turborepo\")) return \"npx turbo run build\";\n if (\n analysis.summary.primaryLanguage === \"TypeScript\" ||\n analysis.summary.primaryLanguage === \"JavaScript\"\n )\n return \"npm run build\";\n if (analysis.summary.primaryLanguage === \"Python\") return null;\n if (analysis.summary.primaryLanguage === \"Go\") return \"go build ./...\";\n return null;\n}\n\nfunction inferTestCommand(analysis: ProjectAnalysis): string | null {\n if (analysis.frameworks.testing.length === 0) return null;\n const frameworks = analysis.frameworks.frameworks.map((f) => f.toLowerCase());\n if (frameworks.includes(\"turborepo\")) return \"npx turbo run test\";\n if (\n analysis.frameworks.testing.some((t) => t.toLowerCase().includes(\"vitest\"))\n )\n return \"npx vitest run\";\n if (analysis.frameworks.testing.some((t) => t.toLowerCase().includes(\"jest\")))\n return \"npx jest\";\n if (\n analysis.frameworks.testing.some((t) => t.toLowerCase().includes(\"pytest\"))\n )\n return \"pytest\";\n return \"npm test\";\n}\n\nfunction inferComplexity(analysis: ProjectAnalysis): string {\n const avg = analysis.summary.avgComplexity;\n if (avg < 5) return \"simple\";\n if (avg < 10) return \"moderate\";\n if (avg < 20) return \"complex\";\n return \"expert\";\n}\n\nfunction inferBudgetTier(analysis: ProjectAnalysis): string {\n const files = analysis.summary.totalFiles;\n if (files < 50) return \"low\";\n if (files < 500) return \"standard\";\n return \"premium\";\n}\n","/**\n * Enrichment Prompt — generates prose sections for BRAINSTORM.md.\n *\n * Takes the accumulated context (analysis + exploration) and asks\n * the LLM to write architecture description, gotchas, and anti-patterns.\n * The frontmatter and structured sections are built deterministically;\n * only the prose needs LLM generation.\n */\n\nimport type { ProjectAnalysis } from \"@brainst0rm/ingest\";\nimport type { ExplorationResult, GeneratedAgent } from \"../types.js\";\n\nexport function buildEnrichmentPrompt(\n analysis: ProjectAnalysis,\n exploration: ExplorationResult | undefined,\n agents: GeneratedAgent[] | undefined,\n): string {\n const sections: string[] = [];\n\n sections.push(`You are writing the prose sections of a BRAINSTORM.md file — a context document that AI agents read before working on this project. Write concise, actionable content.\n\n## Project\n${exploration?.projectPurpose ?? `A ${analysis.summary.primaryLanguage} project with ${analysis.summary.totalFiles} files.`}\n\n## Stack\n- Language: ${analysis.summary.primaryLanguage}\n- Frameworks: ${analysis.summary.frameworkList.join(\", \") || \"none\"}\n- ${analysis.summary.totalFiles} files, ${analysis.summary.totalLines.toLocaleString()} lines, ${analysis.summary.moduleCount} modules`);\n\n if (exploration) {\n sections.push(`## Discovered Conventions\n- Naming: variables=${exploration.conventions.naming.variables}, files=${exploration.conventions.naming.files}, exports=${exploration.conventions.naming.exports}\n- Error handling: ${exploration.conventions.errorHandling}\n- Testing: ${exploration.conventions.testingPatterns}\n- Imports: ${exploration.conventions.importStyle}${exploration.conventions.stateManagement ? `\\n- State management: ${exploration.conventions.stateManagement}` : \"\"}${exploration.conventions.apiPatterns ? `\\n- API patterns: ${exploration.conventions.apiPatterns}` : \"\"}\n- Custom rules: ${exploration.conventions.customRules.join(\"; \") || \"none\"}`);\n\n if (exploration.domainConcepts.length > 0) {\n sections.push(`## Domain Concepts\n${exploration.domainConcepts.map((c) => `- **${c.name}**: ${c.definition}`).join(\"\\n\")}`);\n }\n\n sections.push(`## Development Workflow\n- Commits: ${exploration.gitWorkflow.commitStyle}\n- Branching: ${exploration.gitWorkflow.branchStrategy}\n- PRs: ${exploration.gitWorkflow.prPatterns}\n- CI/CD: ${exploration.cicdSetup.provider}, stages: ${exploration.cicdSetup.stages.join(\" → \") || \"unknown\"}\n- Deploy target: ${exploration.cicdSetup.deployTarget}`);\n }\n\n if (agents && agents.length > 0) {\n sections.push(`## Generated Agents\n${agents.map((a) => `- **${a.id}** (${a.role}): ${a.rationale}`).join(\"\\n\")}`);\n }\n\n sections.push(`## Instructions\n\nWrite THREE sections as markdown. Each section should be 2-5 paragraphs of actionable content.\n\n**Section 1: Architecture**\nDescribe the project's architecture: how modules relate, data flow, key abstractions, and the overall design philosophy. Reference specific directories and files.\n\n**Section 2: Gotchas**\nList 3-8 things a new developer (or AI agent) would trip over. Include non-obvious conventions, surprising behaviors, common mistakes, and \"don't do X, do Y instead\" guidance.\n\n**Section 3: Anti-Patterns**\nList 2-5 patterns to avoid in this codebase, with brief explanations of why.\n\nRespond with ONLY the three markdown sections (with ## headers), no JSON, no code fences around the whole response.`);\n\n return sections.join(\"\\n\\n\");\n}\n"],"mappings":";;;AAWA,SAAS,oBAAoB;AGD7B,SAAS,sBAA4C;AACrD,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AEG7B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