@girardmedia/bootspring 1.2.0 → 2.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.
Files changed (253) hide show
  1. package/README.md +107 -14
  2. package/bin/bootspring.js +166 -27
  3. package/cli/agent.js +189 -17
  4. package/cli/analyze.js +499 -0
  5. package/cli/audit.js +557 -0
  6. package/cli/auth.js +495 -38
  7. package/cli/billing.js +302 -0
  8. package/cli/build.js +695 -0
  9. package/cli/business.js +109 -26
  10. package/cli/checkpoint-utils.js +168 -0
  11. package/cli/checkpoint.js +639 -0
  12. package/cli/cloud-sync.js +447 -0
  13. package/cli/content.js +198 -0
  14. package/cli/context.js +1 -1
  15. package/cli/deploy.js +543 -0
  16. package/cli/fundraise.js +112 -50
  17. package/cli/github-cmd.js +435 -0
  18. package/cli/health.js +477 -0
  19. package/cli/init.js +84 -13
  20. package/cli/legal.js +107 -95
  21. package/cli/log.js +2 -2
  22. package/cli/loop.js +976 -73
  23. package/cli/manager.js +711 -0
  24. package/cli/metrics.js +480 -0
  25. package/cli/monitor.js +812 -0
  26. package/cli/onboard.js +521 -0
  27. package/cli/orchestrator.js +12 -24
  28. package/cli/prd.js +594 -0
  29. package/cli/preseed-start.js +1483 -0
  30. package/cli/preseed.js +2302 -0
  31. package/cli/project.js +436 -0
  32. package/cli/quality.js +233 -0
  33. package/cli/security.js +913 -0
  34. package/cli/seed.js +1441 -5
  35. package/cli/skill.js +273 -211
  36. package/cli/suggest.js +989 -0
  37. package/cli/switch.js +453 -0
  38. package/cli/visualize.js +527 -0
  39. package/cli/watch.js +769 -0
  40. package/cli/workspace.js +607 -0
  41. package/core/analyze-workflow.js +1134 -0
  42. package/core/api-client.js +535 -22
  43. package/core/audit-workflow.js +1350 -0
  44. package/core/build-orchestrator.js +480 -0
  45. package/core/build-state.js +577 -0
  46. package/core/checkpoint-engine.js +408 -0
  47. package/core/config.js +1109 -26
  48. package/core/context-loader.js +21 -1
  49. package/core/deploy-workflow.js +836 -0
  50. package/core/entitlements.js +93 -22
  51. package/core/github-sync.js +610 -0
  52. package/core/index.js +8 -1
  53. package/core/ingest.js +1111 -0
  54. package/core/metrics-engine.js +768 -0
  55. package/core/onboard-workflow.js +1007 -0
  56. package/core/preseed-workflow.js +934 -0
  57. package/core/preseed.js +1617 -0
  58. package/core/project-context.js +325 -0
  59. package/core/project-state.js +694 -0
  60. package/core/r2-sync.js +583 -0
  61. package/core/scaffold.js +525 -7
  62. package/core/session.js +258 -0
  63. package/core/task-extractor.js +758 -0
  64. package/core/telemetry.js +28 -6
  65. package/core/tier-enforcement.js +737 -0
  66. package/core/utils.js +38 -14
  67. package/generators/questionnaire.js +15 -12
  68. package/generators/sections/ai.js +7 -7
  69. package/generators/sections/content.js +300 -0
  70. package/generators/sections/index.js +3 -0
  71. package/generators/sections/plugins.js +7 -6
  72. package/generators/templates/build-planning.template.js +596 -0
  73. package/generators/templates/content.template.js +819 -0
  74. package/generators/templates/index.js +2 -1
  75. package/hooks/git-autopilot.js +1250 -0
  76. package/hooks/index.js +9 -0
  77. package/intelligence/agent-collab.js +2057 -0
  78. package/intelligence/auto-suggest.js +634 -0
  79. package/intelligence/content-gen.js +1589 -0
  80. package/intelligence/cross-project.js +1647 -0
  81. package/intelligence/index.js +184 -0
  82. package/intelligence/learning/insights.json +517 -7
  83. package/intelligence/learning/pattern-learner.js +1008 -14
  84. package/intelligence/memory/decision-tracker.js +1431 -31
  85. package/intelligence/memory/decisions.jsonl +0 -0
  86. package/intelligence/orchestrator.js +2896 -1
  87. package/intelligence/prd.js +92 -1
  88. package/intelligence/recommendation-weights.json +14 -2
  89. package/intelligence/recommendations.js +463 -9
  90. package/intelligence/workflow-composer.js +1451 -0
  91. package/marketplace/index.d.ts +324 -0
  92. package/marketplace/index.js +1921 -0
  93. package/mcp/contracts/mcp-contract.v1.json +342 -4
  94. package/mcp/registry.js +680 -3
  95. package/mcp/response-formatter.js +23 -0
  96. package/mcp/tools/assist-tool.js +78 -4
  97. package/mcp/tools/autopilot-tool.js +408 -0
  98. package/mcp/tools/content-tool.js +571 -0
  99. package/mcp/tools/dashboard-tool.js +251 -5
  100. package/mcp/tools/mvp-tool.js +344 -0
  101. package/mcp/tools/plugin-tool.js +23 -1
  102. package/mcp/tools/prd-tool.js +579 -0
  103. package/mcp/tools/seed-tool.js +447 -0
  104. package/mcp/tools/skill-tool.js +43 -14
  105. package/mcp/tools/suggest-tool.js +147 -0
  106. package/package.json +15 -6
  107. package/agents/README.md +0 -93
  108. package/agents/ai-integration-expert/context.md +0 -386
  109. package/agents/api-expert/context.md +0 -416
  110. package/agents/architecture-expert/context.md +0 -454
  111. package/agents/auth-expert/context.md +0 -399
  112. package/agents/backend-expert/context.md +0 -483
  113. package/agents/business-strategy-expert/context.md +0 -180
  114. package/agents/code-review-expert/context.md +0 -365
  115. package/agents/competitive-analysis-expert/context.md +0 -239
  116. package/agents/data-modeling-expert/context.md +0 -352
  117. package/agents/database-expert/context.md +0 -250
  118. package/agents/devops-expert/context.md +0 -446
  119. package/agents/email-expert/context.md +0 -379
  120. package/agents/financial-expert/context.md +0 -213
  121. package/agents/frontend-expert/context.md +0 -364
  122. package/agents/fundraising-expert/context.md +0 -257
  123. package/agents/growth-expert/context.md +0 -249
  124. package/agents/index.js +0 -140
  125. package/agents/investor-relations-expert/context.md +0 -266
  126. package/agents/legal-expert/context.md +0 -284
  127. package/agents/marketing-expert/context.md +0 -236
  128. package/agents/monitoring-expert/context.md +0 -362
  129. package/agents/operations-expert/context.md +0 -279
  130. package/agents/partnerships-expert/context.md +0 -286
  131. package/agents/payment-expert/context.md +0 -340
  132. package/agents/performance-expert/context.md +0 -377
  133. package/agents/private-equity-expert/context.md +0 -246
  134. package/agents/railway-expert/context.md +0 -284
  135. package/agents/research-expert/context.md +0 -245
  136. package/agents/sales-expert/context.md +0 -241
  137. package/agents/security-expert/context.md +0 -343
  138. package/agents/testing-expert/context.md +0 -414
  139. package/agents/ui-ux-expert/context.md +0 -448
  140. package/agents/vercel-expert/context.md +0 -426
  141. package/skills/index.js +0 -787
  142. package/skills/patterns/README.md +0 -163
  143. package/skills/patterns/ai/agents.md +0 -281
  144. package/skills/patterns/ai/claude.md +0 -138
  145. package/skills/patterns/ai/embeddings.md +0 -150
  146. package/skills/patterns/ai/rag.md +0 -266
  147. package/skills/patterns/ai/streaming.md +0 -170
  148. package/skills/patterns/ai/structured-output.md +0 -162
  149. package/skills/patterns/ai/tools.md +0 -154
  150. package/skills/patterns/analytics/tracking.md +0 -220
  151. package/skills/patterns/api/errors.md +0 -296
  152. package/skills/patterns/api/graphql.md +0 -440
  153. package/skills/patterns/api/middleware.md +0 -279
  154. package/skills/patterns/api/openapi.md +0 -285
  155. package/skills/patterns/api/rate-limiting.md +0 -231
  156. package/skills/patterns/api/route-handler.md +0 -217
  157. package/skills/patterns/api/server-action.md +0 -249
  158. package/skills/patterns/api/versioning.md +0 -443
  159. package/skills/patterns/api/webhooks.md +0 -247
  160. package/skills/patterns/auth/clerk.md +0 -132
  161. package/skills/patterns/auth/mfa.md +0 -313
  162. package/skills/patterns/auth/nextauth.md +0 -140
  163. package/skills/patterns/auth/oauth.md +0 -237
  164. package/skills/patterns/auth/rbac.md +0 -152
  165. package/skills/patterns/auth/session-management.md +0 -367
  166. package/skills/patterns/auth/session.md +0 -120
  167. package/skills/patterns/database/audit.md +0 -177
  168. package/skills/patterns/database/migrations.md +0 -177
  169. package/skills/patterns/database/pagination.md +0 -230
  170. package/skills/patterns/database/pooling.md +0 -357
  171. package/skills/patterns/database/prisma.md +0 -180
  172. package/skills/patterns/database/relations.md +0 -187
  173. package/skills/patterns/database/seeding.md +0 -246
  174. package/skills/patterns/database/soft-delete.md +0 -153
  175. package/skills/patterns/database/transactions.md +0 -162
  176. package/skills/patterns/deployment/ci-cd.md +0 -231
  177. package/skills/patterns/deployment/docker.md +0 -188
  178. package/skills/patterns/deployment/monitoring.md +0 -387
  179. package/skills/patterns/deployment/vercel.md +0 -160
  180. package/skills/patterns/email/resend.md +0 -143
  181. package/skills/patterns/email/templates.md +0 -245
  182. package/skills/patterns/email/transactional.md +0 -503
  183. package/skills/patterns/email/verification.md +0 -176
  184. package/skills/patterns/files/download.md +0 -243
  185. package/skills/patterns/files/upload.md +0 -239
  186. package/skills/patterns/i18n/nextintl.md +0 -188
  187. package/skills/patterns/logging/structured.md +0 -292
  188. package/skills/patterns/notifications/email-queue.md +0 -248
  189. package/skills/patterns/notifications/push.md +0 -279
  190. package/skills/patterns/payments/checkout.md +0 -303
  191. package/skills/patterns/payments/invoices.md +0 -287
  192. package/skills/patterns/payments/portal.md +0 -245
  193. package/skills/patterns/payments/stripe.md +0 -272
  194. package/skills/patterns/payments/subscriptions.md +0 -300
  195. package/skills/patterns/payments/usage.md +0 -279
  196. package/skills/patterns/performance/caching.md +0 -276
  197. package/skills/patterns/performance/code-splitting.md +0 -233
  198. package/skills/patterns/performance/edge.md +0 -254
  199. package/skills/patterns/performance/isr.md +0 -266
  200. package/skills/patterns/performance/lazy-loading.md +0 -281
  201. package/skills/patterns/realtime/sse.md +0 -327
  202. package/skills/patterns/realtime/websockets.md +0 -336
  203. package/skills/patterns/search/filtering.md +0 -329
  204. package/skills/patterns/search/fulltext.md +0 -260
  205. package/skills/patterns/security/audit-logging.md +0 -444
  206. package/skills/patterns/security/csrf.md +0 -234
  207. package/skills/patterns/security/headers.md +0 -252
  208. package/skills/patterns/security/sanitization.md +0 -258
  209. package/skills/patterns/security/secrets.md +0 -261
  210. package/skills/patterns/security/validation.md +0 -268
  211. package/skills/patterns/security/xss.md +0 -229
  212. package/skills/patterns/seo/metadata.md +0 -252
  213. package/skills/patterns/state/context.md +0 -349
  214. package/skills/patterns/state/react-query.md +0 -313
  215. package/skills/patterns/state/url-state.md +0 -482
  216. package/skills/patterns/state/zustand.md +0 -262
  217. package/skills/patterns/testing/api.md +0 -259
  218. package/skills/patterns/testing/component.md +0 -233
  219. package/skills/patterns/testing/coverage.md +0 -207
  220. package/skills/patterns/testing/fixtures.md +0 -225
  221. package/skills/patterns/testing/integration.md +0 -436
  222. package/skills/patterns/testing/mocking.md +0 -177
  223. package/skills/patterns/testing/playwright.md +0 -162
  224. package/skills/patterns/testing/snapshot.md +0 -175
  225. package/skills/patterns/testing/vitest.md +0 -307
  226. package/skills/patterns/ui/accordions.md +0 -395
  227. package/skills/patterns/ui/cards.md +0 -299
  228. package/skills/patterns/ui/dropdowns.md +0 -476
  229. package/skills/patterns/ui/empty-states.md +0 -320
  230. package/skills/patterns/ui/forms.md +0 -405
  231. package/skills/patterns/ui/inputs.md +0 -319
  232. package/skills/patterns/ui/layouts.md +0 -282
  233. package/skills/patterns/ui/loading.md +0 -291
  234. package/skills/patterns/ui/modals.md +0 -338
  235. package/skills/patterns/ui/navigation.md +0 -374
  236. package/skills/patterns/ui/tables.md +0 -407
  237. package/skills/patterns/ui/toasts.md +0 -300
  238. package/skills/patterns/ui/tooltips.md +0 -396
  239. package/skills/patterns/utils/dates.md +0 -435
  240. package/skills/patterns/utils/errors.md +0 -451
  241. package/skills/patterns/utils/formatting.md +0 -345
  242. package/skills/patterns/utils/validation.md +0 -434
  243. package/templates/bootspring.config.js +0 -83
  244. package/templates/business/business-model-canvas.md +0 -246
  245. package/templates/business/business-plan.md +0 -266
  246. package/templates/business/competitive-analysis.md +0 -312
  247. package/templates/fundraising/data-room-checklist.md +0 -300
  248. package/templates/fundraising/investor-research.md +0 -243
  249. package/templates/fundraising/pitch-deck-outline.md +0 -253
  250. package/templates/legal/gdpr-checklist.md +0 -339
  251. package/templates/legal/privacy-policy.md +0 -285
  252. package/templates/legal/terms-of-service.md +0 -222
  253. package/templates/mcp.json +0 -9
package/core/ingest.js ADDED
@@ -0,0 +1,1111 @@
1
+ /**
2
+ * Bootspring File Ingestion System
3
+ *
4
+ * Processes user-provided files from .bootspring/inputs/ and extracts
5
+ * structured information for document generation.
6
+ *
7
+ * @package bootspring
8
+ * @module core/ingest
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ /**
15
+ * Simple YAML parser for basic key-value pairs
16
+ * @param {string} content - YAML content
17
+ * @returns {object} Parsed object
18
+ */
19
+ function parseYamlSimple(content) {
20
+ const result = {};
21
+ const lines = content.split('\n');
22
+ const currentKey = null;
23
+ const currentIndent = 0;
24
+
25
+ for (const line of lines) {
26
+ const trimmed = line.trim();
27
+ if (!trimmed || trimmed.startsWith('#')) continue;
28
+
29
+ const match = line.match(/^(\s*)(\w+):\s*(.*)/);
30
+ if (match) {
31
+ const indent = match[1].length;
32
+ const key = match[2];
33
+ const value = match[3].trim();
34
+
35
+ if (value) {
36
+ result[key] = value.replace(/^["']|["']$/g, '');
37
+ }
38
+ }
39
+ }
40
+
41
+ return result;
42
+ }
43
+
44
+ /**
45
+ * Ingest all files from .bootspring/inputs
46
+ * @param {string} projectRoot - Project root directory
47
+ * @returns {object} Ingested data
48
+ */
49
+ async function ingestAll(projectRoot) {
50
+ const inputsDir = path.join(projectRoot, '.bootspring', 'inputs');
51
+
52
+ const results = {
53
+ mvp: await ingestMVP(projectRoot),
54
+ business: await ingestBusiness(projectRoot),
55
+ prd: await ingestPRD(projectRoot),
56
+ designs: await ingestDesigns(projectRoot),
57
+ api: await ingestAPI(projectRoot),
58
+ data: await ingestData(projectRoot),
59
+ timestamp: new Date().toISOString()
60
+ };
61
+
62
+ return results;
63
+ }
64
+
65
+ /**
66
+ * Ingest MVP source code
67
+ * @param {string} projectRoot - Project root directory
68
+ * @returns {object} MVP analysis
69
+ */
70
+ async function ingestMVP(projectRoot) {
71
+ const mvpPath = path.join(projectRoot, '.bootspring', 'inputs', 'mvp', 'source');
72
+
73
+ if (!fs.existsSync(mvpPath)) {
74
+ return { files: [], stats: { totalFiles: 0, totalLines: 0 }, patterns: [], components: [], services: [] };
75
+ }
76
+
77
+ const files = [];
78
+ const stats = { totalFiles: 0, totalLines: 0 };
79
+ const patterns = [];
80
+ const components = [];
81
+ const services = [];
82
+ const hooks = [];
83
+ const utilities = [];
84
+
85
+ // Walk the directory
86
+ function walkDir(dir, relativePath = '') {
87
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
88
+
89
+ for (const entry of entries) {
90
+ const fullPath = path.join(dir, entry.name);
91
+ const relPath = path.join(relativePath, entry.name);
92
+
93
+ if (entry.isDirectory()) {
94
+ if (!['node_modules', '.git', '.next', 'dist', 'build'].includes(entry.name)) {
95
+ walkDir(fullPath, relPath);
96
+ }
97
+ } else if (entry.isFile()) {
98
+ const ext = path.extname(entry.name);
99
+ if (['.ts', '.tsx', '.js', '.jsx', '.css', '.scss'].includes(ext)) {
100
+ files.push(relPath);
101
+ stats.totalFiles++;
102
+
103
+ try {
104
+ const content = fs.readFileSync(fullPath, 'utf-8');
105
+ const lines = content.split('\n').length;
106
+ stats.totalLines += lines;
107
+
108
+ // Detect patterns
109
+ if (content.includes("'use client'") || content.includes('"use client"')) {
110
+ if (!patterns.includes('client-components')) patterns.push('client-components');
111
+ }
112
+ if (content.includes("'use server'") || content.includes('"use server"')) {
113
+ if (!patterns.includes('server-actions')) patterns.push('server-actions');
114
+ }
115
+ if (content.includes('useState') || content.includes('useEffect')) {
116
+ if (!patterns.includes('react-hooks')) patterns.push('react-hooks');
117
+ }
118
+ if (content.includes('prisma') || content.includes('PrismaClient')) {
119
+ if (!patterns.includes('prisma-orm')) patterns.push('prisma-orm');
120
+ }
121
+ if (content.includes('zod') || content.includes('.parse(')) {
122
+ if (!patterns.includes('zod-validation')) patterns.push('zod-validation');
123
+ }
124
+ if (content.includes('clerk') || content.includes('Clerk')) {
125
+ if (!patterns.includes('clerk-auth')) patterns.push('clerk-auth');
126
+ }
127
+ if (content.includes('stripe') || content.includes('Stripe')) {
128
+ if (!patterns.includes('stripe-payments')) patterns.push('stripe-payments');
129
+ }
130
+
131
+ // Categorize files
132
+ const lowerPath = relPath.toLowerCase();
133
+ if (lowerPath.includes('component') || entry.name.match(/^[A-Z].*\.(tsx|jsx)$/)) {
134
+ components.push(relPath);
135
+ }
136
+ if (lowerPath.includes('service') || lowerPath.includes('api') || lowerPath.includes('lib')) {
137
+ services.push(relPath);
138
+ }
139
+ if (lowerPath.includes('hook') || entry.name.startsWith('use')) {
140
+ hooks.push(relPath);
141
+ }
142
+ if (lowerPath.includes('util') || lowerPath.includes('helper')) {
143
+ utilities.push(relPath);
144
+ }
145
+ } catch {
146
+ // Skip files that can't be read
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+
153
+ walkDir(mvpPath);
154
+
155
+ return {
156
+ files,
157
+ stats,
158
+ patterns,
159
+ components,
160
+ services,
161
+ hooks,
162
+ utilities
163
+ };
164
+ }
165
+
166
+ /**
167
+ * Ingest business documents
168
+ * @param {string} projectRoot - Project root directory
169
+ * @returns {Array} Business documents
170
+ */
171
+ async function ingestBusiness(projectRoot) {
172
+ const businessPath = path.join(projectRoot, '.bootspring', 'inputs', 'business');
173
+
174
+ if (!fs.existsSync(businessPath)) {
175
+ return [];
176
+ }
177
+
178
+ const documents = [];
179
+
180
+ function walkDir(dir) {
181
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
182
+
183
+ for (const entry of entries) {
184
+ const fullPath = path.join(dir, entry.name);
185
+
186
+ if (entry.isDirectory()) {
187
+ walkDir(fullPath);
188
+ } else if (entry.isFile() && entry.name.endsWith('.md')) {
189
+ try {
190
+ const content = fs.readFileSync(fullPath, 'utf-8');
191
+ const relativePath = path.relative(businessPath, fullPath);
192
+
193
+ documents.push({
194
+ file: relativePath,
195
+ type: detectBusinessDocType(entry.name, content),
196
+ sections: parseMarkdownSections(content),
197
+ summary: extractSummary(content),
198
+ wordCount: content.split(/\s+/).length
199
+ });
200
+ } catch {
201
+ // Skip files that can't be read
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ walkDir(businessPath);
208
+ return documents;
209
+ }
210
+
211
+ /**
212
+ * Detect business document type from filename and content
213
+ * @param {string} filename - File name
214
+ * @param {string} content - File content
215
+ * @returns {string} Document type
216
+ */
217
+ function detectBusinessDocType(filename, content) {
218
+ const lower = filename.toLowerCase();
219
+ const contentLower = content.toLowerCase();
220
+
221
+ if (lower.includes('business-plan') || lower.includes('businessplan')) return 'business-plan';
222
+ if (lower.includes('pitch') || lower.includes('deck')) return 'pitch-deck';
223
+ if (lower.includes('competitive') || lower.includes('competitor')) return 'competitive-analysis';
224
+ if (lower.includes('market') && lower.includes('research')) return 'market-research';
225
+ if (lower.includes('financial') || lower.includes('model')) return 'financial-model';
226
+ if (contentLower.includes('executive summary')) return 'business-plan';
227
+ if (contentLower.includes('tam') && contentLower.includes('sam')) return 'market-research';
228
+ if (contentLower.includes('competitor') || contentLower.includes('competitive advantage')) return 'competitive-analysis';
229
+
230
+ return 'general';
231
+ }
232
+
233
+ /**
234
+ * Parse markdown sections
235
+ * @param {string} content - Markdown content
236
+ * @returns {Array} Section headers
237
+ */
238
+ function parseMarkdownSections(content) {
239
+ const sections = [];
240
+ const lines = content.split('\n');
241
+
242
+ for (const line of lines) {
243
+ const match = line.match(/^(#{1,3})\s+(.+)/);
244
+ if (match) {
245
+ sections.push({
246
+ level: match[1].length,
247
+ title: match[2].trim()
248
+ });
249
+ }
250
+ }
251
+
252
+ return sections;
253
+ }
254
+
255
+ /**
256
+ * Extract summary from document
257
+ * @param {string} content - Document content
258
+ * @returns {string} Summary (first 200 chars of first paragraph)
259
+ */
260
+ function extractSummary(content) {
261
+ // Skip frontmatter
262
+ let text = content;
263
+ if (text.startsWith('---')) {
264
+ const endFrontmatter = text.indexOf('---', 3);
265
+ if (endFrontmatter !== -1) {
266
+ text = text.substring(endFrontmatter + 3);
267
+ }
268
+ }
269
+
270
+ // Find first paragraph
271
+ const lines = text.split('\n').filter(l => l.trim() && !l.startsWith('#'));
272
+ const firstPara = lines.slice(0, 3).join(' ').trim();
273
+
274
+ return firstPara.substring(0, 200) + (firstPara.length > 200 ? '...' : '');
275
+ }
276
+
277
+ /**
278
+ * Ingest PRD documents
279
+ * @param {string} projectRoot - Project root directory
280
+ * @returns {Array} PRD documents
281
+ */
282
+ async function ingestPRD(projectRoot) {
283
+ const prdPath = path.join(projectRoot, '.bootspring', 'inputs', 'prd');
284
+
285
+ if (!fs.existsSync(prdPath)) {
286
+ return [];
287
+ }
288
+
289
+ const prds = [];
290
+
291
+ function walkDir(dir) {
292
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
293
+
294
+ for (const entry of entries) {
295
+ const fullPath = path.join(dir, entry.name);
296
+
297
+ if (entry.isDirectory()) {
298
+ walkDir(fullPath);
299
+ } else if (entry.isFile() && entry.name.endsWith('.md')) {
300
+ try {
301
+ const content = fs.readFileSync(fullPath, 'utf-8');
302
+ const relativePath = path.relative(prdPath, fullPath);
303
+
304
+ prds.push({
305
+ file: relativePath,
306
+ userStories: extractUserStories(content),
307
+ requirements: extractRequirements(content),
308
+ features: extractFeatures(content),
309
+ openQuestions: extractOpenQuestions(content),
310
+ sections: parseMarkdownSections(content)
311
+ });
312
+ } catch {
313
+ // Skip files that can't be read
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ walkDir(prdPath);
320
+ return prds;
321
+ }
322
+
323
+ /**
324
+ * Extract user stories from PRD
325
+ * @param {string} content - PRD content
326
+ * @returns {Array} User stories
327
+ */
328
+ function extractUserStories(content) {
329
+ const stories = [];
330
+
331
+ // Match "As a [user], I want [action] so that [benefit]" pattern
332
+ const storyPattern = /As\s+(?:a|an)\s+(.+?),\s+I\s+want\s+(.+?)\s+so\s+that\s+(.+?)(?:\.|$)/gi;
333
+ let match;
334
+
335
+ while ((match = storyPattern.exec(content)) !== null) {
336
+ stories.push({
337
+ role: match[1].trim(),
338
+ want: match[2].trim(),
339
+ benefit: match[3].trim()
340
+ });
341
+ }
342
+
343
+ // Also look for bullet points starting with "As a"
344
+ const lines = content.split('\n');
345
+ for (const line of lines) {
346
+ if (line.match(/^[-*]\s+As\s+(?:a|an)/i) && !stories.some(s => line.includes(s.want))) {
347
+ const bulletMatch = line.match(/As\s+(?:a|an)\s+(.+?),\s+I\s+want\s+(.+?)(?:\s+so\s+that\s+(.+?))?(?:\.|$)/i);
348
+ if (bulletMatch) {
349
+ stories.push({
350
+ role: bulletMatch[1].trim(),
351
+ want: bulletMatch[2].trim(),
352
+ benefit: bulletMatch[3]?.trim() || ''
353
+ });
354
+ }
355
+ }
356
+ }
357
+
358
+ return stories;
359
+ }
360
+
361
+ /**
362
+ * Extract requirements from PRD
363
+ * @param {string} content - PRD content
364
+ * @returns {object} Requirements by priority
365
+ */
366
+ function extractRequirements(content) {
367
+ const requirements = {
368
+ mustHave: [],
369
+ shouldHave: [],
370
+ niceToHave: []
371
+ };
372
+
373
+ const lines = content.split('\n');
374
+ let currentPriority = null;
375
+
376
+ for (const line of lines) {
377
+ const lowerLine = line.toLowerCase();
378
+
379
+ // Detect priority sections
380
+ if (lowerLine.includes('must have') || lowerLine.includes('p0') || lowerLine.includes('critical')) {
381
+ currentPriority = 'mustHave';
382
+ continue;
383
+ }
384
+ if (lowerLine.includes('should have') || lowerLine.includes('p1') || lowerLine.includes('high')) {
385
+ currentPriority = 'shouldHave';
386
+ continue;
387
+ }
388
+ if (lowerLine.includes('nice to have') || lowerLine.includes('p2') || lowerLine.includes('low')) {
389
+ currentPriority = 'niceToHave';
390
+ continue;
391
+ }
392
+
393
+ // Extract bullet points
394
+ if (currentPriority && line.match(/^[-*]\s+/)) {
395
+ const req = line.replace(/^[-*]\s+/, '').trim();
396
+ if (req && !req.match(/^(must|should|nice|p[012])/i)) {
397
+ requirements[currentPriority].push(req);
398
+ }
399
+ }
400
+ }
401
+
402
+ return requirements;
403
+ }
404
+
405
+ /**
406
+ * Extract features from PRD
407
+ * @param {string} content - PRD content
408
+ * @returns {Array} Features
409
+ */
410
+ function extractFeatures(content) {
411
+ const features = [];
412
+ const lines = content.split('\n');
413
+ let inFeatureSection = false;
414
+
415
+ for (const line of lines) {
416
+ const lowerLine = line.toLowerCase();
417
+
418
+ // Detect feature sections
419
+ if (lowerLine.includes('## feature') || lowerLine.includes('### feature') || lowerLine.includes('## core feature')) {
420
+ inFeatureSection = true;
421
+ continue;
422
+ }
423
+
424
+ // New section ends feature section
425
+ if (inFeatureSection && line.match(/^#{1,3}\s/) && !lowerLine.includes('feature')) {
426
+ inFeatureSection = false;
427
+ }
428
+
429
+ // Extract bullet points
430
+ if (inFeatureSection && line.match(/^[-*]\s+/)) {
431
+ const feature = line.replace(/^[-*]\s+/, '').trim();
432
+ if (feature) {
433
+ features.push(feature);
434
+ }
435
+ }
436
+ }
437
+
438
+ return features;
439
+ }
440
+
441
+ /**
442
+ * Extract open questions from PRD
443
+ * @param {string} content - PRD content
444
+ * @returns {Array} Open questions
445
+ */
446
+ function extractOpenQuestions(content) {
447
+ const questions = [];
448
+ const lines = content.split('\n');
449
+ let inQuestionSection = false;
450
+
451
+ for (const line of lines) {
452
+ const lowerLine = line.toLowerCase();
453
+
454
+ // Detect question sections
455
+ if (lowerLine.includes('open question') || lowerLine.includes('tbd') || lowerLine.includes('to be determined')) {
456
+ inQuestionSection = true;
457
+ continue;
458
+ }
459
+
460
+ // New section ends question section
461
+ if (inQuestionSection && line.match(/^#{1,3}\s/)) {
462
+ inQuestionSection = false;
463
+ }
464
+
465
+ // Extract questions (bullet points or lines ending with ?)
466
+ if (line.match(/\?[\s]*$/) || (inQuestionSection && line.match(/^[-*]\s+/))) {
467
+ const question = line.replace(/^[-*]\s+/, '').trim();
468
+ if (question && question.length > 5) {
469
+ questions.push(question);
470
+ }
471
+ }
472
+ }
473
+
474
+ return questions;
475
+ }
476
+
477
+ /**
478
+ * Ingest design files
479
+ * @param {string} projectRoot - Project root directory
480
+ * @returns {object} Design file information
481
+ */
482
+ async function ingestDesigns(projectRoot) {
483
+ const designsPath = path.join(projectRoot, '.bootspring', 'inputs', 'designs');
484
+
485
+ if (!fs.existsSync(designsPath)) {
486
+ return { files: [], count: 0 };
487
+ }
488
+
489
+ const files = [];
490
+
491
+ function walkDir(dir) {
492
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
493
+
494
+ for (const entry of entries) {
495
+ const fullPath = path.join(dir, entry.name);
496
+
497
+ if (entry.isDirectory()) {
498
+ walkDir(fullPath);
499
+ } else if (entry.isFile()) {
500
+ const ext = path.extname(entry.name).toLowerCase();
501
+ const relativePath = path.relative(designsPath, fullPath);
502
+
503
+ files.push({
504
+ path: relativePath,
505
+ type: ext,
506
+ name: entry.name
507
+ });
508
+ }
509
+ }
510
+ }
511
+
512
+ walkDir(designsPath);
513
+
514
+ return {
515
+ files,
516
+ count: files.length,
517
+ imageCount: files.filter(f => ['.png', '.jpg', '.jpeg', '.svg', '.gif', '.webp'].includes(f.type)).length,
518
+ docCount: files.filter(f => ['.md', '.pdf', '.doc', '.docx'].includes(f.type)).length
519
+ };
520
+ }
521
+
522
+ /**
523
+ * Ingest API specifications
524
+ * @param {string} projectRoot - Project root directory
525
+ * @returns {Array} API specifications
526
+ */
527
+ async function ingestAPI(projectRoot) {
528
+ const apiPath = path.join(projectRoot, '.bootspring', 'inputs', 'api');
529
+
530
+ if (!fs.existsSync(apiPath)) {
531
+ return [];
532
+ }
533
+
534
+ const specs = [];
535
+
536
+ function walkDir(dir) {
537
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
538
+
539
+ for (const entry of entries) {
540
+ const fullPath = path.join(dir, entry.name);
541
+
542
+ if (entry.isDirectory()) {
543
+ walkDir(fullPath);
544
+ } else if (entry.isFile()) {
545
+ const ext = path.extname(entry.name).toLowerCase();
546
+
547
+ if (['.yaml', '.yml', '.json'].includes(ext)) {
548
+ try {
549
+ const content = fs.readFileSync(fullPath, 'utf-8');
550
+ const relativePath = path.relative(apiPath, fullPath);
551
+
552
+ // Check if it's an OpenAPI spec
553
+ if (content.includes('openapi') || content.includes('swagger')) {
554
+ specs.push({
555
+ file: relativePath,
556
+ type: 'openapi',
557
+ endpoints: extractOpenAPIEndpoints(content)
558
+ });
559
+ } else {
560
+ specs.push({
561
+ file: relativePath,
562
+ type: 'unknown',
563
+ endpoints: []
564
+ });
565
+ }
566
+ } catch {
567
+ // Skip files that can't be read
568
+ }
569
+ }
570
+ }
571
+ }
572
+ }
573
+
574
+ walkDir(apiPath);
575
+ return specs;
576
+ }
577
+
578
+ /**
579
+ * Extract endpoints from OpenAPI spec
580
+ * @param {string} content - OpenAPI content
581
+ * @returns {Array} Endpoints
582
+ */
583
+ function extractOpenAPIEndpoints(content) {
584
+ const endpoints = [];
585
+
586
+ // Simple regex-based extraction (not full YAML parsing)
587
+ const pathPattern = /["']?(\/[^"'\s:]+)["']?\s*:/g;
588
+ const methodPattern = /(get|post|put|delete|patch):/gi;
589
+
590
+ let match;
591
+ const paths = new Set();
592
+
593
+ while ((match = pathPattern.exec(content)) !== null) {
594
+ const pathStr = match[1];
595
+ if (pathStr && !pathStr.includes('$') && pathStr.length < 100) {
596
+ paths.add(pathStr);
597
+ }
598
+ }
599
+
600
+ for (const pathStr of paths) {
601
+ endpoints.push({ path: pathStr });
602
+ }
603
+
604
+ return endpoints;
605
+ }
606
+
607
+ /**
608
+ * Ingest data files
609
+ * @param {string} projectRoot - Project root directory
610
+ * @returns {Array} Data files
611
+ */
612
+ async function ingestData(projectRoot) {
613
+ const dataPath = path.join(projectRoot, '.bootspring', 'inputs', 'data');
614
+
615
+ if (!fs.existsSync(dataPath)) {
616
+ return [];
617
+ }
618
+
619
+ const dataFiles = [];
620
+
621
+ function walkDir(dir) {
622
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
623
+
624
+ for (const entry of entries) {
625
+ const fullPath = path.join(dir, entry.name);
626
+
627
+ if (entry.isDirectory()) {
628
+ walkDir(fullPath);
629
+ } else if (entry.isFile()) {
630
+ const ext = path.extname(entry.name).toLowerCase();
631
+ const relativePath = path.relative(dataPath, fullPath);
632
+
633
+ try {
634
+ const content = fs.readFileSync(fullPath, 'utf-8');
635
+
636
+ if (ext === '.sql') {
637
+ dataFiles.push({
638
+ file: relativePath,
639
+ type: 'sql',
640
+ tables: extractSQLTables(content)
641
+ });
642
+ } else if (ext === '.json') {
643
+ const parsed = JSON.parse(content);
644
+ dataFiles.push({
645
+ file: relativePath,
646
+ type: 'json',
647
+ structure: inferJSONStructure(parsed)
648
+ });
649
+ } else if (ext === '.csv') {
650
+ const headers = content.split('\n')[0]?.split(',').map(h => h.trim());
651
+ dataFiles.push({
652
+ file: relativePath,
653
+ type: 'csv',
654
+ headers: headers || []
655
+ });
656
+ }
657
+ } catch {
658
+ // Skip files that can't be parsed
659
+ }
660
+ }
661
+ }
662
+ }
663
+
664
+ walkDir(dataPath);
665
+ return dataFiles;
666
+ }
667
+
668
+ /**
669
+ * Extract table definitions from SQL
670
+ * @param {string} content - SQL content
671
+ * @returns {Array} Tables
672
+ */
673
+ function extractSQLTables(content) {
674
+ const tables = [];
675
+ const tablePattern = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["'`]?(\w+)["'`]?\s*\(/gi;
676
+
677
+ let match;
678
+ while ((match = tablePattern.exec(content)) !== null) {
679
+ tables.push(match[1]);
680
+ }
681
+
682
+ return tables;
683
+ }
684
+
685
+ /**
686
+ * Infer structure from JSON
687
+ * @param {*} data - JSON data
688
+ * @returns {object} Structure description
689
+ */
690
+ function inferJSONStructure(data) {
691
+ if (Array.isArray(data)) {
692
+ return {
693
+ type: 'array',
694
+ length: data.length,
695
+ itemType: data.length > 0 ? inferJSONStructure(data[0]) : 'unknown'
696
+ };
697
+ }
698
+
699
+ if (data === null) return { type: 'null' };
700
+ if (typeof data !== 'object') return { type: typeof data };
701
+
702
+ const fields = {};
703
+ for (const [key, value] of Object.entries(data)) {
704
+ fields[key] = typeof value === 'object' && value !== null
705
+ ? (Array.isArray(value) ? 'array' : 'object')
706
+ : typeof value;
707
+ }
708
+
709
+ return { type: 'object', fields };
710
+ }
711
+
712
+ /**
713
+ * Generate documents from ingested data
714
+ * @param {object} ingested - Ingested data
715
+ * @param {object} seedConfig - SEED.md configuration
716
+ * @param {string} projectRoot - Project root directory
717
+ * @returns {object} Generated documents
718
+ */
719
+ async function generateDocuments(ingested, seedConfig, projectRoot) {
720
+ const outputs = {};
721
+ const generatedDir = path.join(projectRoot, '.bootspring', 'generated');
722
+
723
+ // Generate context summary
724
+ outputs['context-summary.md'] = generateContextSummary(ingested, seedConfig);
725
+ fs.writeFileSync(
726
+ path.join(generatedDir, 'context-summary.md'),
727
+ outputs['context-summary.md']
728
+ );
729
+
730
+ // Generate MVP analysis if MVP exists
731
+ if (ingested.mvp && ingested.mvp.files && ingested.mvp.files.length > 0) {
732
+ outputs['mvp-analysis.md'] = generateMVPAnalysis(ingested.mvp);
733
+ fs.mkdirSync(path.join(generatedDir, 'architecture'), { recursive: true });
734
+ fs.writeFileSync(
735
+ path.join(generatedDir, 'architecture', 'mvp-analysis.md'),
736
+ outputs['mvp-analysis.md']
737
+ );
738
+ }
739
+
740
+ // Generate PRD consolidation if PRDs exist
741
+ if (ingested.prd && ingested.prd.length > 0) {
742
+ outputs['consolidated-prd.md'] = generateConsolidatedPRD(ingested.prd, seedConfig);
743
+ fs.mkdirSync(path.join(generatedDir, 'prd'), { recursive: true });
744
+ fs.writeFileSync(
745
+ path.join(generatedDir, 'prd', 'consolidated-prd.md'),
746
+ outputs['consolidated-prd.md']
747
+ );
748
+ }
749
+
750
+ // Generate business summary if business docs exist
751
+ if (ingested.business && ingested.business.length > 0) {
752
+ outputs['business-summary.md'] = generateBusinessSummary(ingested.business, seedConfig);
753
+ fs.mkdirSync(path.join(generatedDir, 'business'), { recursive: true });
754
+ fs.writeFileSync(
755
+ path.join(generatedDir, 'business', 'business-summary.md'),
756
+ outputs['business-summary.md']
757
+ );
758
+ }
759
+
760
+ // Generate API summary if API specs exist
761
+ if (ingested.api && ingested.api.length > 0) {
762
+ outputs['api-summary.md'] = generateAPISummary(ingested.api);
763
+ fs.mkdirSync(path.join(generatedDir, 'architecture'), { recursive: true });
764
+ fs.writeFileSync(
765
+ path.join(generatedDir, 'architecture', 'api-summary.md'),
766
+ outputs['api-summary.md']
767
+ );
768
+ }
769
+
770
+ // Generate data model if data files exist
771
+ if (ingested.data && ingested.data.length > 0) {
772
+ outputs['data-model.md'] = generateDataModel(ingested.data);
773
+ fs.mkdirSync(path.join(generatedDir, 'architecture'), { recursive: true });
774
+ fs.writeFileSync(
775
+ path.join(generatedDir, 'architecture', 'data-model.md'),
776
+ outputs['data-model.md']
777
+ );
778
+ }
779
+
780
+ return outputs;
781
+ }
782
+
783
+ /**
784
+ * Generate context summary document
785
+ */
786
+ function generateContextSummary(ingested, seedConfig) {
787
+ const projectName = seedConfig.project?.name || 'Project';
788
+
789
+ return `# ${projectName} - Context Summary
790
+
791
+ > Auto-generated by Bootspring on ${new Date().toISOString().split('T')[0]}
792
+
793
+ ## Input Files Summary
794
+
795
+ | Category | Count | Status |
796
+ |----------|-------|--------|
797
+ | MVP Code | ${ingested.mvp?.files?.length || 0} files | ${ingested.mvp?.files?.length > 0 ? 'Analyzed' : 'Not provided'} |
798
+ | Business Docs | ${ingested.business?.length || 0} files | ${ingested.business?.length > 0 ? 'Analyzed' : 'Not provided'} |
799
+ | PRD Docs | ${ingested.prd?.length || 0} files | ${ingested.prd?.length > 0 ? 'Analyzed' : 'Not provided'} |
800
+ | Design Files | ${ingested.designs?.count || 0} files | ${ingested.designs?.count > 0 ? 'Indexed' : 'Not provided'} |
801
+ | API Specs | ${ingested.api?.length || 0} files | ${ingested.api?.length > 0 ? 'Analyzed' : 'Not provided'} |
802
+ | Data Files | ${ingested.data?.length || 0} files | ${ingested.data?.length > 0 ? 'Analyzed' : 'Not provided'} |
803
+
804
+ ## Detected Patterns
805
+
806
+ ${ingested.mvp?.patterns?.length > 0 ? ingested.mvp.patterns.map(p => `- ${p}`).join('\n') : '- No patterns detected'}
807
+
808
+ ## Key Statistics
809
+
810
+ ${ingested.mvp?.stats ? `
811
+ - **Total MVP Files**: ${ingested.mvp.stats.totalFiles}
812
+ - **Total Lines of Code**: ${ingested.mvp.stats.totalLines.toLocaleString()}
813
+ - **Components**: ${ingested.mvp.components?.length || 0}
814
+ - **Services**: ${ingested.mvp.services?.length || 0}
815
+ - **Hooks**: ${ingested.mvp.hooks?.length || 0}
816
+ ` : '- No MVP code provided'}
817
+
818
+ ${ingested.prd?.length > 0 ? `
819
+ ## User Stories Found
820
+
821
+ ${ingested.prd.flatMap(p => p.userStories || []).slice(0, 10).map(s =>
822
+ `- As a **${s.role}**, I want **${s.want}**${s.benefit ? ` so that ${s.benefit}` : ''}`
823
+ ).join('\n') || '- No user stories found'}
824
+ ` : ''}
825
+
826
+ ---
827
+
828
+ *Generated by Bootspring*
829
+ `;
830
+ }
831
+
832
+ /**
833
+ * Generate MVP analysis document
834
+ */
835
+ function generateMVPAnalysis(mvp) {
836
+ return `# MVP Code Analysis
837
+
838
+ > Auto-generated by Bootspring
839
+
840
+ ## Overview
841
+
842
+ | Metric | Value |
843
+ |--------|-------|
844
+ | Total Files | ${mvp.stats.totalFiles} |
845
+ | Total Lines | ${mvp.stats.totalLines.toLocaleString()} |
846
+ | Components | ${mvp.components.length} |
847
+ | Services | ${mvp.services.length} |
848
+ | Hooks | ${mvp.hooks.length} |
849
+ | Utilities | ${mvp.utilities.length} |
850
+
851
+ ## Detected Patterns
852
+
853
+ ${mvp.patterns.map(p => `- ${p}`).join('\n') || '- None detected'}
854
+
855
+ ## Components
856
+
857
+ ${mvp.components.slice(0, 20).map(c => `- \`${c}\``).join('\n') || '- None found'}
858
+ ${mvp.components.length > 20 ? `\n*... and ${mvp.components.length - 20} more*` : ''}
859
+
860
+ ## Services
861
+
862
+ ${mvp.services.slice(0, 10).map(s => `- \`${s}\``).join('\n') || '- None found'}
863
+ ${mvp.services.length > 10 ? `\n*... and ${mvp.services.length - 10} more*` : ''}
864
+
865
+ ## Hooks
866
+
867
+ ${mvp.hooks.slice(0, 10).map(h => `- \`${h}\``).join('\n') || '- None found'}
868
+
869
+ ## Recommendations
870
+
871
+ Based on the detected patterns:
872
+
873
+ ${mvp.patterns.includes('client-components') ? '- Consider reviewing client components for server-side rendering opportunities' : ''}
874
+ ${mvp.patterns.includes('prisma-orm') ? '- Prisma ORM detected - ensure schema is optimized for production' : ''}
875
+ ${mvp.patterns.includes('clerk-auth') ? '- Clerk authentication detected - verify middleware configuration' : ''}
876
+ ${mvp.patterns.includes('stripe-payments') ? '- Stripe integration detected - ensure webhook handlers are secure' : ''}
877
+
878
+ ---
879
+
880
+ *Generated by Bootspring*
881
+ `;
882
+ }
883
+
884
+ /**
885
+ * Generate consolidated PRD document
886
+ */
887
+ function generateConsolidatedPRD(prds, seedConfig) {
888
+ const allStories = prds.flatMap(p => p.userStories || []);
889
+ const allRequirements = {
890
+ mustHave: prds.flatMap(p => p.requirements?.mustHave || []),
891
+ shouldHave: prds.flatMap(p => p.requirements?.shouldHave || []),
892
+ niceToHave: prds.flatMap(p => p.requirements?.niceToHave || [])
893
+ };
894
+ const allFeatures = prds.flatMap(p => p.features || []);
895
+ const allQuestions = prds.flatMap(p => p.openQuestions || []);
896
+
897
+ return `# Consolidated Product Requirements
898
+
899
+ > Auto-generated from ${prds.length} PRD file(s)
900
+
901
+ ## User Stories
902
+
903
+ ${allStories.map((s, i) => `${i + 1}. As a **${s.role}**, I want **${s.want}**${s.benefit ? ` so that ${s.benefit}` : ''}`).join('\n') || '- No user stories extracted'}
904
+
905
+ ## Requirements
906
+
907
+ ### Must Have (P0)
908
+
909
+ ${allRequirements.mustHave.map(r => `- [ ] ${r}`).join('\n') || '- None specified'}
910
+
911
+ ### Should Have (P1)
912
+
913
+ ${allRequirements.shouldHave.map(r => `- [ ] ${r}`).join('\n') || '- None specified'}
914
+
915
+ ### Nice to Have (P2)
916
+
917
+ ${allRequirements.niceToHave.map(r => `- [ ] ${r}`).join('\n') || '- None specified'}
918
+
919
+ ## Features
920
+
921
+ ${allFeatures.map(f => `- ${f}`).join('\n') || '- No features extracted'}
922
+
923
+ ## Open Questions
924
+
925
+ ${allQuestions.map(q => `- ${q}`).join('\n') || '- No open questions found'}
926
+
927
+ ## Source Files
928
+
929
+ ${prds.map(p => `- \`${p.file}\``).join('\n')}
930
+
931
+ ---
932
+
933
+ *Generated by Bootspring*
934
+ `;
935
+ }
936
+
937
+ /**
938
+ * Generate business summary document
939
+ */
940
+ function generateBusinessSummary(businessDocs, seedConfig) {
941
+ const byType = {};
942
+ for (const doc of businessDocs) {
943
+ if (!byType[doc.type]) byType[doc.type] = [];
944
+ byType[doc.type].push(doc);
945
+ }
946
+
947
+ return `# Business Context Summary
948
+
949
+ > Auto-generated from ${businessDocs.length} business document(s)
950
+
951
+ ## Documents Analyzed
952
+
953
+ | Document | Type | Word Count |
954
+ |----------|------|------------|
955
+ ${businessDocs.map(d => `| ${d.file} | ${d.type} | ${d.wordCount} |`).join('\n')}
956
+
957
+ ## Key Sections Found
958
+
959
+ ${businessDocs.map(d => `
960
+ ### ${d.file}
961
+
962
+ ${d.sections.filter(s => s.level <= 2).map(s => `${' '.repeat(s.level - 1)}- ${s.title}`).join('\n')}
963
+ `).join('\n')}
964
+
965
+ ## Summaries
966
+
967
+ ${businessDocs.map(d => `
968
+ ### ${d.file}
969
+
970
+ ${d.summary}
971
+ `).join('\n')}
972
+
973
+ ---
974
+
975
+ *Generated by Bootspring*
976
+ `;
977
+ }
978
+
979
+ /**
980
+ * Generate API summary document
981
+ */
982
+ function generateAPISummary(apiSpecs) {
983
+ return `# API Specification Summary
984
+
985
+ > Auto-generated from ${apiSpecs.length} API spec file(s)
986
+
987
+ ## Specifications
988
+
989
+ ${apiSpecs.map(spec => `
990
+ ### ${spec.file}
991
+
992
+ **Type**: ${spec.type}
993
+
994
+ **Endpoints** (${spec.endpoints.length}):
995
+
996
+ ${spec.endpoints.slice(0, 20).map(e => `- \`${e.path}\``).join('\n') || '- None extracted'}
997
+ ${spec.endpoints.length > 20 ? `\n*... and ${spec.endpoints.length - 20} more*` : ''}
998
+ `).join('\n')}
999
+
1000
+ ---
1001
+
1002
+ *Generated by Bootspring*
1003
+ `;
1004
+ }
1005
+
1006
+ /**
1007
+ * Generate data model document
1008
+ */
1009
+ function generateDataModel(dataFiles) {
1010
+ const sqlFiles = dataFiles.filter(f => f.type === 'sql');
1011
+ const jsonFiles = dataFiles.filter(f => f.type === 'json');
1012
+ const csvFiles = dataFiles.filter(f => f.type === 'csv');
1013
+
1014
+ return `# Data Model Summary
1015
+
1016
+ > Auto-generated from ${dataFiles.length} data file(s)
1017
+
1018
+ ## Database Tables
1019
+
1020
+ ${sqlFiles.length > 0 ? sqlFiles.map(f => `
1021
+ ### ${f.file}
1022
+
1023
+ Tables: ${f.tables.join(', ') || 'None found'}
1024
+ `).join('\n') : '- No SQL files provided'}
1025
+
1026
+ ## JSON Structures
1027
+
1028
+ ${jsonFiles.length > 0 ? jsonFiles.map(f => `
1029
+ ### ${f.file}
1030
+
1031
+ Type: ${f.structure.type}
1032
+ ${f.structure.fields ? `Fields: ${Object.keys(f.structure.fields).join(', ')}` : ''}
1033
+ `).join('\n') : '- No JSON files provided'}
1034
+
1035
+ ## CSV Files
1036
+
1037
+ ${csvFiles.length > 0 ? csvFiles.map(f => `
1038
+ ### ${f.file}
1039
+
1040
+ Headers: ${f.headers.join(', ')}
1041
+ `).join('\n') : '- No CSV files provided'}
1042
+
1043
+ ---
1044
+
1045
+ *Generated by Bootspring*
1046
+ `;
1047
+ }
1048
+
1049
+ /**
1050
+ * Update context index
1051
+ * @param {string} projectRoot - Project root directory
1052
+ * @param {object} ingested - Ingested data
1053
+ */
1054
+ async function updateContextIndex(projectRoot, ingested) {
1055
+ const contextDir = path.join(projectRoot, '.bootspring', 'context');
1056
+ const indexPath = path.join(contextDir, 'context-index.json');
1057
+
1058
+ if (!fs.existsSync(contextDir)) {
1059
+ fs.mkdirSync(contextDir, { recursive: true });
1060
+ }
1061
+
1062
+ const index = {
1063
+ lastUpdated: new Date().toISOString(),
1064
+ inputsAnalyzed: {
1065
+ mvp: {
1066
+ fileCount: ingested.mvp?.files?.length || 0,
1067
+ patterns: ingested.mvp?.patterns || []
1068
+ },
1069
+ business: {
1070
+ fileCount: ingested.business?.length || 0,
1071
+ types: ingested.business?.map(d => d.type) || []
1072
+ },
1073
+ prd: {
1074
+ fileCount: ingested.prd?.length || 0,
1075
+ userStoryCount: ingested.prd?.reduce((sum, p) => sum + (p.userStories?.length || 0), 0) || 0
1076
+ },
1077
+ designs: {
1078
+ fileCount: ingested.designs?.count || 0
1079
+ },
1080
+ api: {
1081
+ fileCount: ingested.api?.length || 0,
1082
+ endpointCount: ingested.api?.reduce((sum, s) => sum + (s.endpoints?.length || 0), 0) || 0
1083
+ },
1084
+ data: {
1085
+ fileCount: ingested.data?.length || 0
1086
+ }
1087
+ },
1088
+ generatedFiles: [
1089
+ 'context-summary.md',
1090
+ ...(ingested.mvp?.files?.length > 0 ? ['architecture/mvp-analysis.md'] : []),
1091
+ ...(ingested.prd?.length > 0 ? ['prd/consolidated-prd.md'] : []),
1092
+ ...(ingested.business?.length > 0 ? ['business/business-summary.md'] : []),
1093
+ ...(ingested.api?.length > 0 ? ['architecture/api-summary.md'] : []),
1094
+ ...(ingested.data?.length > 0 ? ['architecture/data-model.md'] : [])
1095
+ ]
1096
+ };
1097
+
1098
+ fs.writeFileSync(indexPath, JSON.stringify(index, null, 2));
1099
+ }
1100
+
1101
+ module.exports = {
1102
+ ingestAll,
1103
+ ingestMVP,
1104
+ ingestBusiness,
1105
+ ingestPRD,
1106
+ ingestDesigns,
1107
+ ingestAPI,
1108
+ ingestData,
1109
+ generateDocuments,
1110
+ updateContextIndex
1111
+ };