@nerviq/cli 1.20.1 → 1.22.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 (186) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +20 -2
  3. package/bin/cli.js +3 -3
  4. package/package.json +1 -1
  5. package/src/activity.js +1039 -1039
  6. package/src/adoption-advisor.js +299 -299
  7. package/src/aider/config-parser.js +166 -166
  8. package/src/aider/context.js +4 -1
  9. package/src/aider/deep-review.js +316 -316
  10. package/src/aider/domain-packs.js +303 -303
  11. package/src/aider/freshness.js +93 -93
  12. package/src/aider/governance.js +253 -253
  13. package/src/aider/interactive.js +334 -334
  14. package/src/aider/mcp-packs.js +329 -329
  15. package/src/aider/patch.js +214 -214
  16. package/src/aider/plans.js +186 -186
  17. package/src/aider/premium.js +360 -360
  18. package/src/aider/setup.js +404 -404
  19. package/src/aider/techniques.js +312 -67
  20. package/src/analyze.js +951 -951
  21. package/src/anti-patterns.js +485 -485
  22. package/src/audit/instruction-files.js +180 -180
  23. package/src/audit/recommendations.js +577 -577
  24. package/src/audit.js +20 -0
  25. package/src/auto-suggest.js +154 -154
  26. package/src/badge.js +13 -13
  27. package/src/behavioral-drift.js +801 -801
  28. package/src/benchmark.js +67 -67
  29. package/src/catalog.js +103 -103
  30. package/src/certification.js +128 -128
  31. package/src/codex/config-parser.js +183 -183
  32. package/src/codex/context.js +223 -223
  33. package/src/codex/deep-review.js +493 -493
  34. package/src/codex/domain-packs.js +394 -394
  35. package/src/codex/freshness.js +84 -84
  36. package/src/codex/governance.js +192 -192
  37. package/src/codex/interactive.js +618 -618
  38. package/src/codex/mcp-packs.js +914 -914
  39. package/src/codex/patch.js +209 -209
  40. package/src/codex/plans.js +251 -251
  41. package/src/codex/premium.js +614 -614
  42. package/src/codex/setup.js +591 -591
  43. package/src/continuous-ops.js +681 -681
  44. package/src/copilot/activity.js +309 -309
  45. package/src/copilot/deep-review.js +346 -346
  46. package/src/copilot/domain-packs.js +372 -372
  47. package/src/copilot/freshness.js +57 -57
  48. package/src/copilot/governance.js +222 -222
  49. package/src/copilot/interactive.js +406 -406
  50. package/src/copilot/mcp-packs.js +826 -826
  51. package/src/copilot/plans.js +253 -253
  52. package/src/copilot/premium.js +451 -451
  53. package/src/copilot/setup.js +488 -488
  54. package/src/cost-tracking.js +61 -61
  55. package/src/cursor/activity.js +301 -301
  56. package/src/cursor/config-parser.js +265 -265
  57. package/src/cursor/context.js +256 -256
  58. package/src/cursor/deep-review.js +334 -334
  59. package/src/cursor/domain-packs.js +368 -368
  60. package/src/cursor/freshness.js +65 -65
  61. package/src/cursor/governance.js +229 -229
  62. package/src/cursor/interactive.js +391 -391
  63. package/src/cursor/mcp-packs.js +828 -828
  64. package/src/cursor/plans.js +254 -254
  65. package/src/cursor/premium.js +469 -469
  66. package/src/cursor/setup.js +488 -488
  67. package/src/dashboard.js +493 -493
  68. package/src/deep-review.js +428 -428
  69. package/src/deprecation.js +98 -98
  70. package/src/diff-only.js +280 -280
  71. package/src/doctor.js +119 -119
  72. package/src/domain-pack-expansion.js +1033 -1033
  73. package/src/domain-packs.js +387 -387
  74. package/src/feedback.js +178 -178
  75. package/src/fix-engine.js +783 -783
  76. package/src/fix-prompts.js +122 -122
  77. package/src/formatters/csv.js +69 -0
  78. package/src/formatters/junit.js +99 -0
  79. package/src/formatters/markdown.js +118 -0
  80. package/src/formatters/sarif.js +115 -115
  81. package/src/freshness.js +74 -74
  82. package/src/gemini/config-parser.js +275 -275
  83. package/src/gemini/deep-review.js +559 -559
  84. package/src/gemini/domain-packs.js +393 -393
  85. package/src/gemini/freshness.js +66 -66
  86. package/src/gemini/governance.js +201 -201
  87. package/src/gemini/interactive.js +860 -860
  88. package/src/gemini/mcp-packs.js +915 -915
  89. package/src/gemini/plans.js +269 -269
  90. package/src/gemini/premium.js +760 -760
  91. package/src/gemini/setup.js +692 -692
  92. package/src/governance.js +72 -72
  93. package/src/harmony/add.js +68 -68
  94. package/src/harmony/advisor.js +333 -333
  95. package/src/harmony/canon.js +565 -565
  96. package/src/harmony/cli.js +591 -591
  97. package/src/harmony/drift.js +401 -401
  98. package/src/harmony/governance.js +313 -313
  99. package/src/harmony/memory.js +239 -239
  100. package/src/harmony/sync.js +475 -475
  101. package/src/harmony/watch.js +370 -370
  102. package/src/hook-validation.js +342 -342
  103. package/src/index.js +271 -271
  104. package/src/init.js +184 -184
  105. package/src/instruction-surfaces.js +185 -185
  106. package/src/integrations.js +144 -144
  107. package/src/interactive.js +118 -118
  108. package/src/locales/en.json +1 -1
  109. package/src/locales/es.json +1 -1
  110. package/src/mcp-packs.js +830 -830
  111. package/src/mcp-server.js +726 -726
  112. package/src/mcp-validation.js +337 -337
  113. package/src/nerviq-sync.json +7 -7
  114. package/src/opencode/config-parser.js +109 -109
  115. package/src/opencode/context.js +247 -247
  116. package/src/opencode/deep-review.js +313 -313
  117. package/src/opencode/domain-packs.js +262 -262
  118. package/src/opencode/freshness.js +66 -66
  119. package/src/opencode/governance.js +159 -159
  120. package/src/opencode/interactive.js +392 -392
  121. package/src/opencode/mcp-packs.js +705 -705
  122. package/src/opencode/patch.js +184 -184
  123. package/src/opencode/plans.js +231 -231
  124. package/src/opencode/premium.js +413 -413
  125. package/src/opencode/setup.js +449 -449
  126. package/src/opencode/techniques.js +27 -27
  127. package/src/operating-profile.js +574 -574
  128. package/src/org.js +152 -152
  129. package/src/permission-rules.js +218 -218
  130. package/src/plans.js +839 -839
  131. package/src/platform-change-manifest.js +86 -86
  132. package/src/plugins.js +110 -110
  133. package/src/policy-layers.js +210 -210
  134. package/src/profiles.js +124 -124
  135. package/src/prompt-injection.js +74 -74
  136. package/src/public-api.js +173 -173
  137. package/src/recommendation-rules.js +84 -84
  138. package/src/repo-archetype.js +386 -386
  139. package/src/secret-patterns.js +39 -39
  140. package/src/server.js +527 -527
  141. package/src/setup/analysis.js +607 -607
  142. package/src/setup/runtime.js +172 -172
  143. package/src/setup.js +677 -677
  144. package/src/shared/capabilities.js +194 -194
  145. package/src/source-urls.js +132 -132
  146. package/src/stack-checks.js +565 -565
  147. package/src/supplemental-checks.js +13 -13
  148. package/src/synergy/adaptive.js +261 -261
  149. package/src/synergy/compensation.js +137 -137
  150. package/src/synergy/evidence.js +193 -193
  151. package/src/synergy/learning.js +199 -199
  152. package/src/synergy/patterns.js +227 -227
  153. package/src/synergy/ranking.js +83 -83
  154. package/src/synergy/report.js +165 -165
  155. package/src/synergy/routing.js +146 -146
  156. package/src/techniques/api.js +407 -407
  157. package/src/techniques/automation.js +316 -316
  158. package/src/techniques/compliance.js +257 -257
  159. package/src/techniques/hygiene.js +294 -294
  160. package/src/techniques/instructions.js +243 -243
  161. package/src/techniques/observability.js +226 -226
  162. package/src/techniques/optimization.js +142 -142
  163. package/src/techniques/quality.js +318 -318
  164. package/src/techniques/security.js +237 -237
  165. package/src/techniques/shared.js +443 -443
  166. package/src/techniques/stacks.js +2294 -2294
  167. package/src/techniques/tools.js +106 -106
  168. package/src/techniques/workflow.js +413 -413
  169. package/src/techniques.js +81 -81
  170. package/src/terminology.js +73 -73
  171. package/src/token-estimate.js +35 -35
  172. package/src/usage-patterns.js +99 -99
  173. package/src/verification-metadata.js +145 -145
  174. package/src/watch.js +247 -247
  175. package/src/windsurf/activity.js +302 -302
  176. package/src/windsurf/config-parser.js +267 -267
  177. package/src/windsurf/deep-review.js +337 -337
  178. package/src/windsurf/domain-packs.js +370 -370
  179. package/src/windsurf/freshness.js +36 -36
  180. package/src/windsurf/governance.js +231 -231
  181. package/src/windsurf/interactive.js +388 -388
  182. package/src/windsurf/mcp-packs.js +792 -792
  183. package/src/windsurf/plans.js +247 -247
  184. package/src/windsurf/premium.js +468 -468
  185. package/src/windsurf/setup.js +471 -471
  186. package/src/workspace.js +375 -375
@@ -1,612 +1,612 @@
1
1
  const path = require('path');
2
2
 
3
- // ============================================================
4
- // Helper: detect project scripts from package.json
5
- // ============================================================
6
- function detectScripts(ctx) {
7
- const pkg = ctx.jsonFile('package.json');
8
- if (!pkg || !pkg.scripts) return {};
9
- const relevant = ['test', 'build', 'lint', 'dev', 'start', 'format', 'typecheck', 'check'];
10
- const found = {};
11
- for (const key of relevant) {
12
- if (pkg.scripts[key]) {
13
- found[key] = pkg.scripts[key];
14
- }
15
- }
16
- return found;
17
- }
18
-
19
- // ============================================================
20
- // Helper: detect key dependencies and generate guidelines
21
- // ============================================================
22
- function detectDependencies(ctx) {
23
- const pkg = ctx.jsonFile('package.json') || {};
24
- const allDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
25
- const guidelines = [];
26
-
27
- // Data fetching
28
- if (allDeps['@tanstack/react-query']) {
29
- guidelines.push('- Use React Query (TanStack Query) for all server data fetching — never raw useEffect + fetch');
30
- guidelines.push('- Define query keys as constants. Invalidate related queries after mutations');
31
- }
32
- if (allDeps['swr']) {
33
- guidelines.push('- Use SWR for data fetching with automatic revalidation');
34
- }
35
-
36
- // Validation
37
- if (allDeps['zod']) {
38
- guidelines.push('- Use Zod for all input validation and type inference (z.infer<typeof schema>)');
39
- guidelines.push('- Define schemas in a shared location. Use .parse() at API boundaries');
40
- }
41
-
42
- // ORM / Database
43
- if (allDeps['prisma'] || allDeps['@prisma/client']) {
44
- guidelines.push('- Use Prisma for all database operations. Run `npx prisma generate` after schema changes');
45
- guidelines.push('- Never write raw SQL unless Prisma cannot express the query');
46
- }
47
- if (allDeps['drizzle-orm']) {
48
- guidelines.push('- Use Drizzle ORM for database operations. Schema-first approach');
49
- }
50
- if (allDeps['mongoose']) {
51
- guidelines.push('- Use Mongoose for MongoDB operations. Define schemas with validation');
52
- }
53
-
54
- // Auth
55
- if (allDeps['next-auth'] || allDeps['@auth/core']) {
56
- guidelines.push('- Use NextAuth.js for authentication. Access session via auth() in Server Components');
57
- }
58
- if (allDeps['clerk'] || allDeps['@clerk/nextjs']) {
59
- guidelines.push('- Use Clerk for authentication. Protect routes with middleware');
60
- }
61
-
62
- // State management
63
- if (allDeps['zustand']) {
64
- guidelines.push('- Use Zustand for client state. Keep stores small and focused');
65
- }
66
- if (allDeps['@reduxjs/toolkit']) {
67
- guidelines.push('- Use Redux Toolkit for state management. Use createSlice and RTK Query');
68
- }
69
-
70
- // Styling
71
- if (allDeps['tailwindcss']) {
72
- guidelines.push('- Use Tailwind CSS for all styling. Avoid inline styles and CSS modules');
73
- }
74
- if (allDeps['styled-components'] || allDeps['@emotion/react']) {
75
- guidelines.push('- Use CSS-in-JS for component styling. Colocate styles with components');
76
- }
77
-
78
- // Testing
79
- if (allDeps['vitest']) {
80
- guidelines.push('- Use Vitest for testing. Colocate test files with source (*.test.ts)');
81
- }
82
- if (allDeps['jest']) {
83
- guidelines.push('- Use Jest for testing. Follow existing test patterns in the codebase');
84
- }
85
- if (allDeps['playwright'] || allDeps['@playwright/test']) {
86
- guidelines.push('- Use Playwright for E2E tests. Keep tests in tests/ or e2e/');
87
- }
88
-
89
- // Testing tools
90
- if (allDeps['msw']) {
91
- guidelines.push('- Use MSW (Mock Service Worker) for API mocking in tests. Define handlers in __mocks__/');
92
- }
93
- if (allDeps['@testing-library/react']) {
94
- guidelines.push('- Use Testing Library for component tests. Prefer userEvent over fireEvent, query by role/label');
95
- }
96
- if (allDeps['@vitest/coverage-v8'] || allDeps['@vitest/coverage-istanbul']) {
97
- guidelines.push('- Coverage configured. Maintain coverage thresholds. Check reports before merging');
98
- }
99
-
100
- // tRPC
101
- if (allDeps['@trpc/server'] || allDeps['@trpc/client']) {
102
- guidelines.push('- Use tRPC for type-safe API calls. Define routers in server, use client hooks in components');
103
- }
104
-
105
- // Stripe
106
- if (allDeps['stripe']) {
107
- guidelines.push('- Use Stripe SDK for payments. Always verify webhooks with stripe.webhooks.constructEvent()');
108
- }
109
-
110
- // Resend
111
- if (allDeps['resend']) {
112
- guidelines.push('- Use Resend for transactional email. Define templates as React components');
113
- }
114
-
115
- // Express security
116
- if (allDeps['helmet']) {
117
- guidelines.push('- Helmet is configured — ensure all middleware is applied before routes');
118
- }
119
- if (allDeps['jsonwebtoken']) {
120
- guidelines.push('- Use JWT for authentication. Always verify tokens with the correct secret/algorithm');
121
- }
122
- if (allDeps['bcrypt']) {
123
- guidelines.push('- Use bcrypt for password hashing. Never store plaintext passwords');
124
- }
125
- if (allDeps['cors']) {
126
- guidelines.push('- CORS is configured — restrict origins to known domains in production');
127
- }
128
-
129
- // Monorepo
130
- if (allDeps['turbo'] || allDeps['turborepo']) {
131
- guidelines.push('- Turborepo monorepo — use `turbo run` for all tasks. Respect package boundaries');
132
- }
133
- if (allDeps['nx']) {
134
- guidelines.push('- Nx monorepo — use `nx affected` for incremental builds and tests');
135
- }
136
-
137
- // Python
138
- const reqTxt = ctx.fileContent('requirements.txt') || '';
139
- if (reqTxt.includes('sqlalchemy')) {
140
- guidelines.push('- Use SQLAlchemy for database operations. Define models in models/');
141
- }
142
- if (reqTxt.includes('pydantic')) {
143
- guidelines.push('- Use Pydantic for data validation and serialization');
144
- }
145
- if (reqTxt.includes('pytest')) {
146
- guidelines.push('- Use pytest for testing. Run with `python -m pytest`');
147
- }
148
- if (reqTxt.includes('alembic')) {
149
- guidelines.push('- Use Alembic for database migrations. Run `alembic upgrade head` after model changes');
150
- }
151
- if (reqTxt.includes('celery')) {
152
- guidelines.push('- Use Celery for background tasks. Define tasks in tasks/ or services/');
153
- }
154
- if (reqTxt.includes('redis')) {
155
- guidelines.push('- Redis is available for caching and task queues');
156
- }
157
- if (reqTxt.includes('langchain')) {
158
- guidelines.push('- Use LangChain for chain/agent orchestration. Define chains in chains/ directory');
159
- }
160
- if (reqTxt.includes('openai')) {
161
- guidelines.push('- OpenAI SDK available. Use structured outputs where possible');
162
- }
163
- if (reqTxt.includes('anthropic')) {
164
- guidelines.push('- Anthropic SDK available. Prefer Claude for complex reasoning tasks');
165
- }
166
- if (reqTxt.includes('chromadb')) {
167
- guidelines.push('- Use ChromaDB for local vector storage. Persist collections to disk');
168
- }
169
- if (reqTxt.includes('pinecone')) {
170
- guidelines.push('- Use Pinecone for production vector search. Define index schemas upfront');
171
- }
172
- if (reqTxt.includes('mlflow')) {
173
- guidelines.push('- Use MLflow for experiment tracking. Log all model parameters and metrics');
174
- }
175
- if (reqTxt.includes('wandb')) {
176
- guidelines.push('- Use Weights & Biases for experiment tracking and visualization');
177
- }
178
- if (reqTxt.includes('transformers')) {
179
- guidelines.push('- HuggingFace Transformers available. Use AutoModel/AutoTokenizer for loading');
180
- }
181
-
182
- // JS AI/ML/Cloud deps
183
- if (allDeps['@anthropic-ai/sdk']) {
184
- guidelines.push('- Anthropic SDK configured. Use Messages API with structured tool_use for agents');
185
- }
186
- if (allDeps['openai']) {
187
- guidelines.push('- OpenAI SDK available. Use structured outputs and function calling');
188
- }
189
- if (allDeps['@modelcontextprotocol/sdk']) {
190
- guidelines.push('- MCP SDK available. Build MCP servers with stdio transport');
191
- }
192
- if (allDeps['langchain'] || allDeps['@langchain/core']) {
193
- guidelines.push('- LangChain available. Use LCEL for chain composition');
194
- }
195
- if (allDeps['@aws-sdk/client-s3'] || allDeps['@aws-sdk/client-dynamodb']) {
196
- guidelines.push('- AWS SDK v3 configured. Use modular imports, not aws-sdk v2');
197
- }
198
- if (allDeps['@aws-cdk/aws-lambda'] || allDeps['aws-cdk-lib']) {
199
- guidelines.push('- AWS CDK available. Define stacks in lib/, constructs as separate classes');
200
- }
201
-
202
- // Security middleware
203
- if (allDeps['express-rate-limit']) {
204
- guidelines.push('- Rate limiting configured. Apply to auth endpoints. Set appropriate windowMs and max values');
205
- }
206
- if (allDeps['hpp']) {
207
- guidelines.push('- HPP (HTTP Parameter Pollution) protection enabled');
208
- }
209
- if (allDeps['csurf']) {
210
- guidelines.push('- CSRF protection enabled. Ensure tokens are included in all state-changing requests');
211
- }
212
-
213
- // AWS Lambda
214
- if (allDeps['@aws-sdk/client-lambda'] || allDeps['@aws-cdk/aws-lambda'] || allDeps['aws-cdk-lib']) {
215
- guidelines.push('- Lambda handlers: keep cold start fast, use layers for deps, set appropriate memory/timeout');
216
- }
217
-
218
- // Deprecated dependency warnings
219
- if (allDeps['moment']) {
220
- guidelines.push('- ⚠️ moment.js is deprecated and heavy (330KB). Migrate to date-fns or dayjs');
221
- }
222
- if (allDeps['request']) {
223
- guidelines.push('- ⚠️ request is deprecated. Use fetch (native) or axios instead');
224
- }
225
- if (allDeps['lodash'] && !allDeps['lodash-es']) {
226
- guidelines.push('- Consider replacing lodash with native JS methods or lodash-es for tree-shaking');
227
- }
228
- if (allDeps['node-sass']) {
229
- guidelines.push('- ⚠️ node-sass is deprecated. Migrate to sass (dart-sass)');
230
- }
231
- if (allDeps['tslint']) {
232
- guidelines.push('- ⚠️ TSLint is deprecated. Migrate to ESLint with @typescript-eslint');
233
- }
234
-
235
- return guidelines;
236
- }
237
-
238
- // ============================================================
239
- // Helper: detect main directories
240
- // ============================================================
241
- function detectMainDirs(ctx) {
242
- const candidates = ['src', 'lib', 'app', 'pages', 'components', 'api', 'routes', 'utils', 'helpers', 'services', 'models', 'controllers', 'views', 'public', 'assets', 'config', 'tests', 'test', '__tests__', 'spec', 'scripts', 'prisma', 'db', 'middleware', 'hooks', 'agents', 'chains', 'workers', 'jobs', 'dags', 'macros', 'migrations'];
243
- // Also check inside src/ for nested structure (common in Next.js, React)
244
- const srcNested = ['src/components', 'src/app', 'src/pages', 'src/api', 'src/lib', 'src/hooks', 'src/utils', 'src/services', 'src/models', 'src/middleware', 'src/app/api', 'app/api', 'src/agents', 'src/chains', 'src/workers', 'src/jobs', 'models/staging', 'models/marts'];
245
- const found = [];
246
- const seenNames = new Set();
247
-
248
- for (const dir of [...candidates, ...srcNested]) {
249
- if (ctx.hasDir(dir)) {
250
- const files = ctx.dirFiles(dir);
251
- const displayName = dir.includes('/') ? dir : dir;
252
- if (!seenNames.has(displayName)) {
253
- found.push({ name: displayName, fileCount: files.length, files: files.slice(0, 10) });
254
- seenNames.add(displayName);
255
- }
256
- }
257
- }
258
- return found;
259
- }
260
-
261
- function escapeRegex(value) {
262
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
263
- }
264
-
265
- function extractTomlSection(content, sectionName) {
266
- const pattern = new RegExp(`\\[${escapeRegex(sectionName)}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`);
267
- const match = content.match(pattern);
268
- return match ? match[1] : null;
269
- }
270
-
271
- function extractTomlValue(sectionContent, key) {
272
- if (!sectionContent) return null;
273
- const pattern = new RegExp(`^\\s*${escapeRegex(key)}\\s*=\\s*["']([^"']+)["']`, 'm');
274
- const match = sectionContent.match(pattern);
275
- return match ? match[1].trim() : null;
276
- }
277
-
278
- function detectProjectMetadata(ctx) {
279
- const pkg = ctx.jsonFile('package.json');
280
- if (pkg && (pkg.name || pkg.description)) {
281
- return {
282
- name: pkg.name || path.basename(ctx.dir),
283
- description: pkg.description || '',
284
- };
285
- }
286
-
287
- const pyproject = ctx.fileContent('pyproject.toml') || '';
288
- if (pyproject) {
289
- const projectSection = extractTomlSection(pyproject, 'project');
290
- const poetrySection = extractTomlSection(pyproject, 'tool.poetry');
291
- const name = extractTomlValue(projectSection, 'name') ||
292
- extractTomlValue(poetrySection, 'name');
293
- const description = extractTomlValue(projectSection, 'description') ||
294
- extractTomlValue(poetrySection, 'description');
295
-
296
- if (name || description) {
297
- return {
298
- name: name || path.basename(ctx.dir),
299
- description: description || '',
300
- };
301
- }
302
- }
303
-
304
- return {
305
- name: path.basename(ctx.dir),
306
- description: '',
307
- };
308
- }
309
-
310
- // ============================================================
311
- // Helper: generate Mermaid diagram from directory structure
312
- // ============================================================
313
- function generateMermaid(dirs, stacks) {
314
- const stackKeys = stacks.map(s => s.key);
315
- const dirNames = dirs.map(d => d.name);
316
-
317
- // Build nodes based on what exists
318
- const nodes = [];
319
- const edges = [];
320
- let nodeId = 0;
321
- const ids = {};
322
-
323
- function addNode(label, shape) {
324
- const id = String.fromCharCode(65 + nodeId++); // A, B, C...
325
- ids[label] = id;
326
- if (shape === 'db') return ` ${id}[(${label})]`;
327
- if (shape === 'round') return ` ${id}(${label})`;
328
- return ` ${id}[${label}]`;
329
- }
330
-
331
- // Detect Next.js App Router specifically
332
- const hasAppRouter = dirNames.includes('app') || dirNames.includes('src/app');
333
- const hasPages = dirNames.includes('pages') || dirNames.includes('src/pages');
334
- const hasAppApi = dirNames.includes('app/api') || dirNames.includes('src/app/api');
335
- const hasSrcComponents = dirNames.includes('src/components') || dirNames.includes('components');
336
- const hasSrcHooks = dirNames.includes('src/hooks') || dirNames.includes('hooks');
337
- const hasSrcLib = dirNames.includes('src/lib') || dirNames.includes('lib');
338
- const hasSrcNode = dirNames.includes('src');
339
- const hasAgents = dirNames.includes('src/agents') || dirNames.includes('agents');
340
- const hasChains = dirNames.includes('src/chains') || dirNames.includes('chains');
341
- const hasWorkers = dirNames.includes('src/workers') || dirNames.includes('workers') || dirNames.includes('jobs');
342
- const hasPipelines = dirNames.includes('dags') || dirNames.includes('macros');
343
-
344
- // Smart entry point based on framework
345
- const isNextJs = stackKeys.includes('nextjs');
346
- const isDjango = stackKeys.includes('django');
347
- const isFastApi = stackKeys.includes('fastapi');
348
-
349
- if (isNextJs) {
350
- nodes.push(addNode('Next.js', 'round'));
351
- } else if (isDjango) {
352
- nodes.push(addNode('Django', 'round'));
353
- } else if (isFastApi) {
354
- nodes.push(addNode('FastAPI', 'round'));
355
- } else {
356
- nodes.push(addNode('Entry Point', 'round'));
357
- }
358
-
359
- const root = ids['Next.js'] || ids['Django'] || ids['FastAPI'] || ids['Entry Point'] || 'A';
360
- const pickNodeId = (...labels) => labels.map(label => ids[label]).find(Boolean) || root;
361
-
362
- // Detect layers
363
- if (hasAppRouter || hasPages) {
364
- const label = hasAppRouter ? 'App Router' : 'Pages';
365
- nodes.push(addNode(label, 'default'));
366
- edges.push(` ${root} --> ${ids[label]}`);
367
- }
368
-
369
- if (hasAppApi) {
370
- nodes.push(addNode('API Routes', 'default'));
371
- const parent = ids['App Router'] || ids['Pages'] || root;
372
- edges.push(` ${parent} --> ${ids['API Routes']}`);
373
- }
374
-
375
- if (hasSrcComponents) {
376
- nodes.push(addNode('Components', 'default'));
377
- const parent = ids['App Router'] || ids['Pages'] || root;
378
- edges.push(` ${parent} --> ${ids['Components']}`);
379
- }
380
-
381
- if (hasSrcHooks) {
382
- nodes.push(addNode('Hooks', 'default'));
383
- const parent = ids['Components'] || root;
384
- edges.push(` ${parent} --> ${ids['Hooks']}`);
385
- }
386
-
387
- if (hasSrcLib) {
388
- nodes.push(addNode('lib/', 'default'));
389
- const parent = pickNodeId('API Routes', 'Hooks', 'Components');
390
- edges.push(` ${parent} --> ${ids['lib/']}`);
391
- } else if (hasSrcNode && !hasAppRouter && !hasPages) {
392
- nodes.push(addNode('src/', 'default'));
393
- edges.push(` ${root} --> ${ids['src/']}`);
394
- }
395
-
396
- if (dirNames.includes('api') || dirNames.includes('routes') || dirNames.includes('controllers')) {
397
- const label = dirNames.includes('api') ? 'API Layer' : 'Routes';
398
- nodes.push(addNode(label, 'default'));
399
- const parent = pickNodeId('src/', 'App Router', 'Pages');
400
- edges.push(` ${parent} --> ${ids[label]}`);
401
- }
402
-
403
- if (dirNames.includes('services')) {
404
- nodes.push(addNode('Services', 'default'));
405
- const parent = pickNodeId('API Layer', 'Routes', 'src/', 'App Router', 'Pages');
406
- edges.push(` ${parent} --> ${ids['Services']}`);
407
- }
408
-
409
- if (dirNames.includes('models') || dirNames.includes('prisma') || dirNames.includes('db')) {
410
- nodes.push(addNode('Data Layer', 'default'));
411
- const parent = pickNodeId('Services', 'API Layer', 'Routes', 'src/', 'App Router', 'Pages');
412
- edges.push(` ${parent} --> ${ids['Data Layer']}`);
413
- nodes.push(addNode('Database', 'db'));
414
- edges.push(` ${ids['Data Layer']} --> ${ids['Database']}`);
415
- }
416
-
417
- if (dirNames.includes('utils') || dirNames.includes('helpers')) {
418
- nodes.push(addNode('Utils', 'default'));
419
- const parent = pickNodeId('src/', 'Services', 'lib/', 'Components');
420
- edges.push(` ${parent} --> ${ids['Utils']}`);
421
- }
422
-
423
- if (dirNames.includes('middleware')) {
424
- nodes.push(addNode('Middleware', 'default'));
425
- const parent = pickNodeId('API Layer', 'Routes', 'App Router', 'Pages');
426
- edges.push(` ${parent} --> ${ids['Middleware']}`);
427
- }
428
-
429
- if (hasChains) {
430
- nodes.push(addNode('Chains', 'default'));
431
- const parent = pickNodeId('Services', 'src/', 'lib/', 'API Layer');
432
- edges.push(` ${parent} --> ${ids['Chains']}`);
433
- }
434
-
435
- if (hasAgents) {
436
- nodes.push(addNode('Agents', 'default'));
437
- const parent = pickNodeId('Chains', 'Services', 'src/', 'lib/');
438
- edges.push(` ${parent} --> ${ids['Agents']}`);
439
- }
440
-
441
- if (hasWorkers) {
442
- nodes.push(addNode('Workers', 'default'));
443
- const parent = pickNodeId('Services', 'API Layer', 'src/');
444
- edges.push(` ${parent} --> ${ids['Workers']}`);
445
- }
446
-
447
- if (hasPipelines) {
448
- nodes.push(addNode('Pipelines', 'default'));
449
- const parent = pickNodeId('Services', 'Data Layer', 'src/');
450
- edges.push(` ${parent} --> ${ids['Pipelines']}`);
451
- }
452
-
453
- if (dirNames.includes('tests') || dirNames.includes('test') || dirNames.includes('__tests__') || dirNames.includes('spec')) {
454
- nodes.push(addNode('Tests', 'round'));
455
- const parent = pickNodeId('src/', 'App Router', 'Pages', 'Services', 'Components');
456
- edges.push(` ${ids['Tests']} -.-> ${parent}`);
457
- }
458
-
459
- // Fallback: if we only have Entry Point, make a generic diagram
460
- if (nodes.length <= 1) {
461
- return `\`\`\`mermaid
462
- graph TD
463
- A[Entry Point] --> B[Core Logic]
464
- B --> C[Data Layer]
465
- B --> D[API / Routes]
466
- C --> E[(Database)]
467
- D --> F[External Services]
468
- \`\`\`
469
- <!-- Update this diagram to match your actual architecture -->`;
470
- }
471
-
472
- return '```mermaid\ngraph TD\n' + nodes.join('\n') + '\n' + edges.join('\n') + '\n```';
473
- }
474
-
475
- // ============================================================
476
- // Helper: framework-specific instructions
477
- // ============================================================
478
- function getFrameworkInstructions(stacks) {
479
- const stackKeys = stacks.map(s => s.key);
480
- const sections = [];
481
-
482
- if (stackKeys.includes('nextjs')) {
483
- sections.push(`### Next.js
484
- - Use App Router conventions (app/ directory) when applicable
485
- - Prefer Server Components by default; add 'use client' only when needed
486
- - Use next/image for images, next/link for navigation
487
- - API routes go in app/api/ (App Router) or pages/api/ (Pages Router)
488
- - Use loading.tsx, error.tsx, and not-found.tsx for route-level UX
489
- - If app/ exists, use Server Actions for mutations, validate with Zod, and call revalidatePath after writes
490
- - Route handlers in app/api/ should export named functions: GET, POST, PUT, DELETE
491
- - Middleware in middleware.ts should handle auth checks, redirects, and headers`);
492
- } else if (stackKeys.includes('react')) {
493
- sections.push(`### React
494
- - Use functional components with hooks exclusively
495
- - Prefer named exports over default exports
496
- - Keep components under 150 lines; extract sub-components
497
- - Use custom hooks to share stateful logic
498
- - Colocate styles, tests, and types with components`);
499
- }
500
-
501
- if (stackKeys.includes('vue')) {
502
- sections.push(`### Vue
503
- - Use Composition API with \`<script setup>\` syntax
504
- - Prefer defineProps/defineEmits macros
505
- - Keep components under 200 lines
506
- - Use composables for shared logic`);
507
- }
508
-
509
- if (stackKeys.includes('angular')) {
510
- sections.push(`### Angular
511
- - Use standalone components when possible
512
- - Follow Angular style guide naming conventions
513
- - Use reactive forms over template-driven forms
514
- - Keep services focused on a single responsibility`);
515
- }
516
-
517
- if (stackKeys.includes('typescript')) {
518
- sections.push(`### TypeScript
519
- - Use \`interface\` for object shapes, \`type\` for unions/intersections
520
- - Enable strict mode in tsconfig.json
521
- - Avoid \`any\` — use \`unknown\` and narrow with type guards
522
- - Prefer \`as const\` assertions over enum when practical
523
- - Export types alongside their implementations`);
524
- }
525
-
526
- if (stackKeys.includes('django')) {
527
- sections.push(`### Django
528
- - Follow fat models, thin views pattern
529
- - Use class-based views for complex logic, function views for simple
530
- - Always use Django ORM; avoid raw SQL unless necessary
531
- - Keep business logic in models or services, not views`);
532
- } else if (stackKeys.includes('fastapi')) {
533
- sections.push(`### FastAPI
534
- - Use Pydantic models for request/response validation
535
- - Use dependency injection for shared logic
536
- - Keep route handlers thin; delegate to service functions
537
- - Use async def for I/O-bound endpoints`);
538
- }
539
-
540
- if (stackKeys.includes('python') || stackKeys.includes('django') || stackKeys.includes('fastapi')) {
541
- sections.push(`### Python
542
- - Use type hints on all function signatures and return types
543
- - Follow PEP 8; use f-strings for formatting
544
- - Prefer pathlib over os.path
545
- - Use dataclasses or pydantic for structured data
546
- - Raise specific exceptions; never bare \`except:\``);
547
- }
548
-
549
- if (stackKeys.includes('rust')) {
550
- sections.push(`### Rust
551
- - Use Result<T, E> for error handling, avoid unwrap() in production code
552
- - Prefer &str over String for function parameters
553
- - Use clippy: \`cargo clippy -- -D warnings\`
554
- - Structure: src/lib.rs for library, src/main.rs for binary`);
555
- }
556
-
557
- if (stackKeys.includes('go')) {
558
- sections.push(`### Go
559
- - Follow standard Go project layout (cmd/, internal/, pkg/)
560
- - Use interfaces for dependency injection and testability
561
- - Handle all errors explicitly — never ignore err returns
562
- - Use context.Context for cancellation and timeouts
563
- - Prefer table-driven tests
564
- - Run \`go vet\` and \`golangci-lint\` before committing
565
- - If using gRPC: define .proto files in proto/ or pkg/proto, generate with protoc
566
- - If Makefile exists: use make targets for build/test/lint
567
- - Organize: cmd/ for entry points, internal/ for private packages, pkg/ for public`);
568
- }
569
-
570
- if (stackKeys.includes('cpp')) {
571
- sections.push(`### C++
572
- - Follow project coding standards (check .clang-format if present)
573
- - Use smart pointers (unique_ptr, shared_ptr) over raw pointers
574
- - Run clang-tidy for static analysis
575
- - Prefer const references for function parameters
576
- - Use CMake targets, not raw compiler flags`);
577
- }
578
-
579
- if (stackKeys.includes('bazel')) {
580
- sections.push(`### Bazel
581
- - Define BUILD files per package. Keep targets focused
582
- - Use visibility carefully — prefer package-private
583
- - Run buildifier for formatting`);
584
- }
585
-
586
- if (stackKeys.includes('terraform')) {
587
- sections.push(`### Terraform
588
- - Use modules for reusable infrastructure components
589
- - Always run \`terraform plan\` before \`terraform apply\`
590
- - Store state remotely (S3 + DynamoDB, or Terraform Cloud)
591
- - Use variables.tf for all configurable values
592
- - Tag all resources consistently
593
- - If using Helm: define charts in charts/ or helm/, use values.yaml for config
594
- - Lock providers: always commit .terraform.lock.hcl
595
- - Use terraform fmt before committing`);
596
- }
597
-
598
- const hasJS = stackKeys.some(k => ['react', 'vue', 'angular', 'nextjs', 'node', 'svelte'].includes(k));
599
- if (hasJS && !stackKeys.includes('typescript')) {
600
- sections.push(`### JavaScript
601
- - Use \`const\` by default, \`let\` when reassignment needed; never \`var\`
602
- - Use \`async/await\` over raw Promises
603
- - Use named exports over default exports
604
- - Import order: stdlib > external > internal > relative`);
605
- }
606
-
607
- return sections.join('\n\n');
608
- }
609
-
3
+ // ============================================================
4
+ // Helper: detect project scripts from package.json
5
+ // ============================================================
6
+ function detectScripts(ctx) {
7
+ const pkg = ctx.jsonFile('package.json');
8
+ if (!pkg || !pkg.scripts) return {};
9
+ const relevant = ['test', 'build', 'lint', 'dev', 'start', 'format', 'typecheck', 'check'];
10
+ const found = {};
11
+ for (const key of relevant) {
12
+ if (pkg.scripts[key]) {
13
+ found[key] = pkg.scripts[key];
14
+ }
15
+ }
16
+ return found;
17
+ }
18
+
19
+ // ============================================================
20
+ // Helper: detect key dependencies and generate guidelines
21
+ // ============================================================
22
+ function detectDependencies(ctx) {
23
+ const pkg = ctx.jsonFile('package.json') || {};
24
+ const allDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
25
+ const guidelines = [];
26
+
27
+ // Data fetching
28
+ if (allDeps['@tanstack/react-query']) {
29
+ guidelines.push('- Use React Query (TanStack Query) for all server data fetching — never raw useEffect + fetch');
30
+ guidelines.push('- Define query keys as constants. Invalidate related queries after mutations');
31
+ }
32
+ if (allDeps['swr']) {
33
+ guidelines.push('- Use SWR for data fetching with automatic revalidation');
34
+ }
35
+
36
+ // Validation
37
+ if (allDeps['zod']) {
38
+ guidelines.push('- Use Zod for all input validation and type inference (z.infer<typeof schema>)');
39
+ guidelines.push('- Define schemas in a shared location. Use .parse() at API boundaries');
40
+ }
41
+
42
+ // ORM / Database
43
+ if (allDeps['prisma'] || allDeps['@prisma/client']) {
44
+ guidelines.push('- Use Prisma for all database operations. Run `npx prisma generate` after schema changes');
45
+ guidelines.push('- Never write raw SQL unless Prisma cannot express the query');
46
+ }
47
+ if (allDeps['drizzle-orm']) {
48
+ guidelines.push('- Use Drizzle ORM for database operations. Schema-first approach');
49
+ }
50
+ if (allDeps['mongoose']) {
51
+ guidelines.push('- Use Mongoose for MongoDB operations. Define schemas with validation');
52
+ }
53
+
54
+ // Auth
55
+ if (allDeps['next-auth'] || allDeps['@auth/core']) {
56
+ guidelines.push('- Use NextAuth.js for authentication. Access session via auth() in Server Components');
57
+ }
58
+ if (allDeps['clerk'] || allDeps['@clerk/nextjs']) {
59
+ guidelines.push('- Use Clerk for authentication. Protect routes with middleware');
60
+ }
61
+
62
+ // State management
63
+ if (allDeps['zustand']) {
64
+ guidelines.push('- Use Zustand for client state. Keep stores small and focused');
65
+ }
66
+ if (allDeps['@reduxjs/toolkit']) {
67
+ guidelines.push('- Use Redux Toolkit for state management. Use createSlice and RTK Query');
68
+ }
69
+
70
+ // Styling
71
+ if (allDeps['tailwindcss']) {
72
+ guidelines.push('- Use Tailwind CSS for all styling. Avoid inline styles and CSS modules');
73
+ }
74
+ if (allDeps['styled-components'] || allDeps['@emotion/react']) {
75
+ guidelines.push('- Use CSS-in-JS for component styling. Colocate styles with components');
76
+ }
77
+
78
+ // Testing
79
+ if (allDeps['vitest']) {
80
+ guidelines.push('- Use Vitest for testing. Colocate test files with source (*.test.ts)');
81
+ }
82
+ if (allDeps['jest']) {
83
+ guidelines.push('- Use Jest for testing. Follow existing test patterns in the codebase');
84
+ }
85
+ if (allDeps['playwright'] || allDeps['@playwright/test']) {
86
+ guidelines.push('- Use Playwright for E2E tests. Keep tests in tests/ or e2e/');
87
+ }
88
+
89
+ // Testing tools
90
+ if (allDeps['msw']) {
91
+ guidelines.push('- Use MSW (Mock Service Worker) for API mocking in tests. Define handlers in __mocks__/');
92
+ }
93
+ if (allDeps['@testing-library/react']) {
94
+ guidelines.push('- Use Testing Library for component tests. Prefer userEvent over fireEvent, query by role/label');
95
+ }
96
+ if (allDeps['@vitest/coverage-v8'] || allDeps['@vitest/coverage-istanbul']) {
97
+ guidelines.push('- Coverage configured. Maintain coverage thresholds. Check reports before merging');
98
+ }
99
+
100
+ // tRPC
101
+ if (allDeps['@trpc/server'] || allDeps['@trpc/client']) {
102
+ guidelines.push('- Use tRPC for type-safe API calls. Define routers in server, use client hooks in components');
103
+ }
104
+
105
+ // Stripe
106
+ if (allDeps['stripe']) {
107
+ guidelines.push('- Use Stripe SDK for payments. Always verify webhooks with stripe.webhooks.constructEvent()');
108
+ }
109
+
110
+ // Resend
111
+ if (allDeps['resend']) {
112
+ guidelines.push('- Use Resend for transactional email. Define templates as React components');
113
+ }
114
+
115
+ // Express security
116
+ if (allDeps['helmet']) {
117
+ guidelines.push('- Helmet is configured — ensure all middleware is applied before routes');
118
+ }
119
+ if (allDeps['jsonwebtoken']) {
120
+ guidelines.push('- Use JWT for authentication. Always verify tokens with the correct secret/algorithm');
121
+ }
122
+ if (allDeps['bcrypt']) {
123
+ guidelines.push('- Use bcrypt for password hashing. Never store plaintext passwords');
124
+ }
125
+ if (allDeps['cors']) {
126
+ guidelines.push('- CORS is configured — restrict origins to known domains in production');
127
+ }
128
+
129
+ // Monorepo
130
+ if (allDeps['turbo'] || allDeps['turborepo']) {
131
+ guidelines.push('- Turborepo monorepo — use `turbo run` for all tasks. Respect package boundaries');
132
+ }
133
+ if (allDeps['nx']) {
134
+ guidelines.push('- Nx monorepo — use `nx affected` for incremental builds and tests');
135
+ }
136
+
137
+ // Python
138
+ const reqTxt = ctx.fileContent('requirements.txt') || '';
139
+ if (reqTxt.includes('sqlalchemy')) {
140
+ guidelines.push('- Use SQLAlchemy for database operations. Define models in models/');
141
+ }
142
+ if (reqTxt.includes('pydantic')) {
143
+ guidelines.push('- Use Pydantic for data validation and serialization');
144
+ }
145
+ if (reqTxt.includes('pytest')) {
146
+ guidelines.push('- Use pytest for testing. Run with `python -m pytest`');
147
+ }
148
+ if (reqTxt.includes('alembic')) {
149
+ guidelines.push('- Use Alembic for database migrations. Run `alembic upgrade head` after model changes');
150
+ }
151
+ if (reqTxt.includes('celery')) {
152
+ guidelines.push('- Use Celery for background tasks. Define tasks in tasks/ or services/');
153
+ }
154
+ if (reqTxt.includes('redis')) {
155
+ guidelines.push('- Redis is available for caching and task queues');
156
+ }
157
+ if (reqTxt.includes('langchain')) {
158
+ guidelines.push('- Use LangChain for chain/agent orchestration. Define chains in chains/ directory');
159
+ }
160
+ if (reqTxt.includes('openai')) {
161
+ guidelines.push('- OpenAI SDK available. Use structured outputs where possible');
162
+ }
163
+ if (reqTxt.includes('anthropic')) {
164
+ guidelines.push('- Anthropic SDK available. Prefer Claude for complex reasoning tasks');
165
+ }
166
+ if (reqTxt.includes('chromadb')) {
167
+ guidelines.push('- Use ChromaDB for local vector storage. Persist collections to disk');
168
+ }
169
+ if (reqTxt.includes('pinecone')) {
170
+ guidelines.push('- Use Pinecone for production vector search. Define index schemas upfront');
171
+ }
172
+ if (reqTxt.includes('mlflow')) {
173
+ guidelines.push('- Use MLflow for experiment tracking. Log all model parameters and metrics');
174
+ }
175
+ if (reqTxt.includes('wandb')) {
176
+ guidelines.push('- Use Weights & Biases for experiment tracking and visualization');
177
+ }
178
+ if (reqTxt.includes('transformers')) {
179
+ guidelines.push('- HuggingFace Transformers available. Use AutoModel/AutoTokenizer for loading');
180
+ }
181
+
182
+ // JS AI/ML/Cloud deps
183
+ if (allDeps['@anthropic-ai/sdk']) {
184
+ guidelines.push('- Anthropic SDK configured. Use Messages API with structured tool_use for agents');
185
+ }
186
+ if (allDeps['openai']) {
187
+ guidelines.push('- OpenAI SDK available. Use structured outputs and function calling');
188
+ }
189
+ if (allDeps['@modelcontextprotocol/sdk']) {
190
+ guidelines.push('- MCP SDK available. Build MCP servers with stdio transport');
191
+ }
192
+ if (allDeps['langchain'] || allDeps['@langchain/core']) {
193
+ guidelines.push('- LangChain available. Use LCEL for chain composition');
194
+ }
195
+ if (allDeps['@aws-sdk/client-s3'] || allDeps['@aws-sdk/client-dynamodb']) {
196
+ guidelines.push('- AWS SDK v3 configured. Use modular imports, not aws-sdk v2');
197
+ }
198
+ if (allDeps['@aws-cdk/aws-lambda'] || allDeps['aws-cdk-lib']) {
199
+ guidelines.push('- AWS CDK available. Define stacks in lib/, constructs as separate classes');
200
+ }
201
+
202
+ // Security middleware
203
+ if (allDeps['express-rate-limit']) {
204
+ guidelines.push('- Rate limiting configured. Apply to auth endpoints. Set appropriate windowMs and max values');
205
+ }
206
+ if (allDeps['hpp']) {
207
+ guidelines.push('- HPP (HTTP Parameter Pollution) protection enabled');
208
+ }
209
+ if (allDeps['csurf']) {
210
+ guidelines.push('- CSRF protection enabled. Ensure tokens are included in all state-changing requests');
211
+ }
212
+
213
+ // AWS Lambda
214
+ if (allDeps['@aws-sdk/client-lambda'] || allDeps['@aws-cdk/aws-lambda'] || allDeps['aws-cdk-lib']) {
215
+ guidelines.push('- Lambda handlers: keep cold start fast, use layers for deps, set appropriate memory/timeout');
216
+ }
217
+
218
+ // Deprecated dependency warnings
219
+ if (allDeps['moment']) {
220
+ guidelines.push('- ⚠️ moment.js is deprecated and heavy (330KB). Migrate to date-fns or dayjs');
221
+ }
222
+ if (allDeps['request']) {
223
+ guidelines.push('- ⚠️ request is deprecated. Use fetch (native) or axios instead');
224
+ }
225
+ if (allDeps['lodash'] && !allDeps['lodash-es']) {
226
+ guidelines.push('- Consider replacing lodash with native JS methods or lodash-es for tree-shaking');
227
+ }
228
+ if (allDeps['node-sass']) {
229
+ guidelines.push('- ⚠️ node-sass is deprecated. Migrate to sass (dart-sass)');
230
+ }
231
+ if (allDeps['tslint']) {
232
+ guidelines.push('- ⚠️ TSLint is deprecated. Migrate to ESLint with @typescript-eslint');
233
+ }
234
+
235
+ return guidelines;
236
+ }
237
+
238
+ // ============================================================
239
+ // Helper: detect main directories
240
+ // ============================================================
241
+ function detectMainDirs(ctx) {
242
+ const candidates = ['src', 'lib', 'app', 'pages', 'components', 'api', 'routes', 'utils', 'helpers', 'services', 'models', 'controllers', 'views', 'public', 'assets', 'config', 'tests', 'test', '__tests__', 'spec', 'scripts', 'prisma', 'db', 'middleware', 'hooks', 'agents', 'chains', 'workers', 'jobs', 'dags', 'macros', 'migrations'];
243
+ // Also check inside src/ for nested structure (common in Next.js, React)
244
+ const srcNested = ['src/components', 'src/app', 'src/pages', 'src/api', 'src/lib', 'src/hooks', 'src/utils', 'src/services', 'src/models', 'src/middleware', 'src/app/api', 'app/api', 'src/agents', 'src/chains', 'src/workers', 'src/jobs', 'models/staging', 'models/marts'];
245
+ const found = [];
246
+ const seenNames = new Set();
247
+
248
+ for (const dir of [...candidates, ...srcNested]) {
249
+ if (ctx.hasDir(dir)) {
250
+ const files = ctx.dirFiles(dir);
251
+ const displayName = dir.includes('/') ? dir : dir;
252
+ if (!seenNames.has(displayName)) {
253
+ found.push({ name: displayName, fileCount: files.length, files: files.slice(0, 10) });
254
+ seenNames.add(displayName);
255
+ }
256
+ }
257
+ }
258
+ return found;
259
+ }
260
+
261
+ function escapeRegex(value) {
262
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
263
+ }
264
+
265
+ function extractTomlSection(content, sectionName) {
266
+ const pattern = new RegExp(`\\[${escapeRegex(sectionName)}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`);
267
+ const match = content.match(pattern);
268
+ return match ? match[1] : null;
269
+ }
270
+
271
+ function extractTomlValue(sectionContent, key) {
272
+ if (!sectionContent) return null;
273
+ const pattern = new RegExp(`^\\s*${escapeRegex(key)}\\s*=\\s*["']([^"']+)["']`, 'm');
274
+ const match = sectionContent.match(pattern);
275
+ return match ? match[1].trim() : null;
276
+ }
277
+
278
+ function detectProjectMetadata(ctx) {
279
+ const pkg = ctx.jsonFile('package.json');
280
+ if (pkg && (pkg.name || pkg.description)) {
281
+ return {
282
+ name: pkg.name || path.basename(ctx.dir),
283
+ description: pkg.description || '',
284
+ };
285
+ }
286
+
287
+ const pyproject = ctx.fileContent('pyproject.toml') || '';
288
+ if (pyproject) {
289
+ const projectSection = extractTomlSection(pyproject, 'project');
290
+ const poetrySection = extractTomlSection(pyproject, 'tool.poetry');
291
+ const name = extractTomlValue(projectSection, 'name') ||
292
+ extractTomlValue(poetrySection, 'name');
293
+ const description = extractTomlValue(projectSection, 'description') ||
294
+ extractTomlValue(poetrySection, 'description');
295
+
296
+ if (name || description) {
297
+ return {
298
+ name: name || path.basename(ctx.dir),
299
+ description: description || '',
300
+ };
301
+ }
302
+ }
303
+
304
+ return {
305
+ name: path.basename(ctx.dir),
306
+ description: '',
307
+ };
308
+ }
309
+
310
+ // ============================================================
311
+ // Helper: generate Mermaid diagram from directory structure
312
+ // ============================================================
313
+ function generateMermaid(dirs, stacks) {
314
+ const stackKeys = stacks.map(s => s.key);
315
+ const dirNames = dirs.map(d => d.name);
316
+
317
+ // Build nodes based on what exists
318
+ const nodes = [];
319
+ const edges = [];
320
+ let nodeId = 0;
321
+ const ids = {};
322
+
323
+ function addNode(label, shape) {
324
+ const id = String.fromCharCode(65 + nodeId++); // A, B, C...
325
+ ids[label] = id;
326
+ if (shape === 'db') return ` ${id}[(${label})]`;
327
+ if (shape === 'round') return ` ${id}(${label})`;
328
+ return ` ${id}[${label}]`;
329
+ }
330
+
331
+ // Detect Next.js App Router specifically
332
+ const hasAppRouter = dirNames.includes('app') || dirNames.includes('src/app');
333
+ const hasPages = dirNames.includes('pages') || dirNames.includes('src/pages');
334
+ const hasAppApi = dirNames.includes('app/api') || dirNames.includes('src/app/api');
335
+ const hasSrcComponents = dirNames.includes('src/components') || dirNames.includes('components');
336
+ const hasSrcHooks = dirNames.includes('src/hooks') || dirNames.includes('hooks');
337
+ const hasSrcLib = dirNames.includes('src/lib') || dirNames.includes('lib');
338
+ const hasSrcNode = dirNames.includes('src');
339
+ const hasAgents = dirNames.includes('src/agents') || dirNames.includes('agents');
340
+ const hasChains = dirNames.includes('src/chains') || dirNames.includes('chains');
341
+ const hasWorkers = dirNames.includes('src/workers') || dirNames.includes('workers') || dirNames.includes('jobs');
342
+ const hasPipelines = dirNames.includes('dags') || dirNames.includes('macros');
343
+
344
+ // Smart entry point based on framework
345
+ const isNextJs = stackKeys.includes('nextjs');
346
+ const isDjango = stackKeys.includes('django');
347
+ const isFastApi = stackKeys.includes('fastapi');
348
+
349
+ if (isNextJs) {
350
+ nodes.push(addNode('Next.js', 'round'));
351
+ } else if (isDjango) {
352
+ nodes.push(addNode('Django', 'round'));
353
+ } else if (isFastApi) {
354
+ nodes.push(addNode('FastAPI', 'round'));
355
+ } else {
356
+ nodes.push(addNode('Entry Point', 'round'));
357
+ }
358
+
359
+ const root = ids['Next.js'] || ids['Django'] || ids['FastAPI'] || ids['Entry Point'] || 'A';
360
+ const pickNodeId = (...labels) => labels.map(label => ids[label]).find(Boolean) || root;
361
+
362
+ // Detect layers
363
+ if (hasAppRouter || hasPages) {
364
+ const label = hasAppRouter ? 'App Router' : 'Pages';
365
+ nodes.push(addNode(label, 'default'));
366
+ edges.push(` ${root} --> ${ids[label]}`);
367
+ }
368
+
369
+ if (hasAppApi) {
370
+ nodes.push(addNode('API Routes', 'default'));
371
+ const parent = ids['App Router'] || ids['Pages'] || root;
372
+ edges.push(` ${parent} --> ${ids['API Routes']}`);
373
+ }
374
+
375
+ if (hasSrcComponents) {
376
+ nodes.push(addNode('Components', 'default'));
377
+ const parent = ids['App Router'] || ids['Pages'] || root;
378
+ edges.push(` ${parent} --> ${ids['Components']}`);
379
+ }
380
+
381
+ if (hasSrcHooks) {
382
+ nodes.push(addNode('Hooks', 'default'));
383
+ const parent = ids['Components'] || root;
384
+ edges.push(` ${parent} --> ${ids['Hooks']}`);
385
+ }
386
+
387
+ if (hasSrcLib) {
388
+ nodes.push(addNode('lib/', 'default'));
389
+ const parent = pickNodeId('API Routes', 'Hooks', 'Components');
390
+ edges.push(` ${parent} --> ${ids['lib/']}`);
391
+ } else if (hasSrcNode && !hasAppRouter && !hasPages) {
392
+ nodes.push(addNode('src/', 'default'));
393
+ edges.push(` ${root} --> ${ids['src/']}`);
394
+ }
395
+
396
+ if (dirNames.includes('api') || dirNames.includes('routes') || dirNames.includes('controllers')) {
397
+ const label = dirNames.includes('api') ? 'API Layer' : 'Routes';
398
+ nodes.push(addNode(label, 'default'));
399
+ const parent = pickNodeId('src/', 'App Router', 'Pages');
400
+ edges.push(` ${parent} --> ${ids[label]}`);
401
+ }
402
+
403
+ if (dirNames.includes('services')) {
404
+ nodes.push(addNode('Services', 'default'));
405
+ const parent = pickNodeId('API Layer', 'Routes', 'src/', 'App Router', 'Pages');
406
+ edges.push(` ${parent} --> ${ids['Services']}`);
407
+ }
408
+
409
+ if (dirNames.includes('models') || dirNames.includes('prisma') || dirNames.includes('db')) {
410
+ nodes.push(addNode('Data Layer', 'default'));
411
+ const parent = pickNodeId('Services', 'API Layer', 'Routes', 'src/', 'App Router', 'Pages');
412
+ edges.push(` ${parent} --> ${ids['Data Layer']}`);
413
+ nodes.push(addNode('Database', 'db'));
414
+ edges.push(` ${ids['Data Layer']} --> ${ids['Database']}`);
415
+ }
416
+
417
+ if (dirNames.includes('utils') || dirNames.includes('helpers')) {
418
+ nodes.push(addNode('Utils', 'default'));
419
+ const parent = pickNodeId('src/', 'Services', 'lib/', 'Components');
420
+ edges.push(` ${parent} --> ${ids['Utils']}`);
421
+ }
422
+
423
+ if (dirNames.includes('middleware')) {
424
+ nodes.push(addNode('Middleware', 'default'));
425
+ const parent = pickNodeId('API Layer', 'Routes', 'App Router', 'Pages');
426
+ edges.push(` ${parent} --> ${ids['Middleware']}`);
427
+ }
428
+
429
+ if (hasChains) {
430
+ nodes.push(addNode('Chains', 'default'));
431
+ const parent = pickNodeId('Services', 'src/', 'lib/', 'API Layer');
432
+ edges.push(` ${parent} --> ${ids['Chains']}`);
433
+ }
434
+
435
+ if (hasAgents) {
436
+ nodes.push(addNode('Agents', 'default'));
437
+ const parent = pickNodeId('Chains', 'Services', 'src/', 'lib/');
438
+ edges.push(` ${parent} --> ${ids['Agents']}`);
439
+ }
440
+
441
+ if (hasWorkers) {
442
+ nodes.push(addNode('Workers', 'default'));
443
+ const parent = pickNodeId('Services', 'API Layer', 'src/');
444
+ edges.push(` ${parent} --> ${ids['Workers']}`);
445
+ }
446
+
447
+ if (hasPipelines) {
448
+ nodes.push(addNode('Pipelines', 'default'));
449
+ const parent = pickNodeId('Services', 'Data Layer', 'src/');
450
+ edges.push(` ${parent} --> ${ids['Pipelines']}`);
451
+ }
452
+
453
+ if (dirNames.includes('tests') || dirNames.includes('test') || dirNames.includes('__tests__') || dirNames.includes('spec')) {
454
+ nodes.push(addNode('Tests', 'round'));
455
+ const parent = pickNodeId('src/', 'App Router', 'Pages', 'Services', 'Components');
456
+ edges.push(` ${ids['Tests']} -.-> ${parent}`);
457
+ }
458
+
459
+ // Fallback: if we only have Entry Point, make a generic diagram
460
+ if (nodes.length <= 1) {
461
+ return `\`\`\`mermaid
462
+ graph TD
463
+ A[Entry Point] --> B[Core Logic]
464
+ B --> C[Data Layer]
465
+ B --> D[API / Routes]
466
+ C --> E[(Database)]
467
+ D --> F[External Services]
468
+ \`\`\`
469
+ <!-- Update this diagram to match your actual architecture -->`;
470
+ }
471
+
472
+ return '```mermaid\ngraph TD\n' + nodes.join('\n') + '\n' + edges.join('\n') + '\n```';
473
+ }
474
+
475
+ // ============================================================
476
+ // Helper: framework-specific instructions
477
+ // ============================================================
478
+ function getFrameworkInstructions(stacks) {
479
+ const stackKeys = stacks.map(s => s.key);
480
+ const sections = [];
481
+
482
+ if (stackKeys.includes('nextjs')) {
483
+ sections.push(`### Next.js
484
+ - Use App Router conventions (app/ directory) when applicable
485
+ - Prefer Server Components by default; add 'use client' only when needed
486
+ - Use next/image for images, next/link for navigation
487
+ - API routes go in app/api/ (App Router) or pages/api/ (Pages Router)
488
+ - Use loading.tsx, error.tsx, and not-found.tsx for route-level UX
489
+ - If app/ exists, use Server Actions for mutations, validate with Zod, and call revalidatePath after writes
490
+ - Route handlers in app/api/ should export named functions: GET, POST, PUT, DELETE
491
+ - Middleware in middleware.ts should handle auth checks, redirects, and headers`);
492
+ } else if (stackKeys.includes('react')) {
493
+ sections.push(`### React
494
+ - Use functional components with hooks exclusively
495
+ - Prefer named exports over default exports
496
+ - Keep components under 150 lines; extract sub-components
497
+ - Use custom hooks to share stateful logic
498
+ - Colocate styles, tests, and types with components`);
499
+ }
500
+
501
+ if (stackKeys.includes('vue')) {
502
+ sections.push(`### Vue
503
+ - Use Composition API with \`<script setup>\` syntax
504
+ - Prefer defineProps/defineEmits macros
505
+ - Keep components under 200 lines
506
+ - Use composables for shared logic`);
507
+ }
508
+
509
+ if (stackKeys.includes('angular')) {
510
+ sections.push(`### Angular
511
+ - Use standalone components when possible
512
+ - Follow Angular style guide naming conventions
513
+ - Use reactive forms over template-driven forms
514
+ - Keep services focused on a single responsibility`);
515
+ }
516
+
517
+ if (stackKeys.includes('typescript')) {
518
+ sections.push(`### TypeScript
519
+ - Use \`interface\` for object shapes, \`type\` for unions/intersections
520
+ - Enable strict mode in tsconfig.json
521
+ - Avoid \`any\` — use \`unknown\` and narrow with type guards
522
+ - Prefer \`as const\` assertions over enum when practical
523
+ - Export types alongside their implementations`);
524
+ }
525
+
526
+ if (stackKeys.includes('django')) {
527
+ sections.push(`### Django
528
+ - Follow fat models, thin views pattern
529
+ - Use class-based views for complex logic, function views for simple
530
+ - Always use Django ORM; avoid raw SQL unless necessary
531
+ - Keep business logic in models or services, not views`);
532
+ } else if (stackKeys.includes('fastapi')) {
533
+ sections.push(`### FastAPI
534
+ - Use Pydantic models for request/response validation
535
+ - Use dependency injection for shared logic
536
+ - Keep route handlers thin; delegate to service functions
537
+ - Use async def for I/O-bound endpoints`);
538
+ }
539
+
540
+ if (stackKeys.includes('python') || stackKeys.includes('django') || stackKeys.includes('fastapi')) {
541
+ sections.push(`### Python
542
+ - Use type hints on all function signatures and return types
543
+ - Follow PEP 8; use f-strings for formatting
544
+ - Prefer pathlib over os.path
545
+ - Use dataclasses or pydantic for structured data
546
+ - Raise specific exceptions; never bare \`except:\``);
547
+ }
548
+
549
+ if (stackKeys.includes('rust')) {
550
+ sections.push(`### Rust
551
+ - Use Result<T, E> for error handling, avoid unwrap() in production code
552
+ - Prefer &str over String for function parameters
553
+ - Use clippy: \`cargo clippy -- -D warnings\`
554
+ - Structure: src/lib.rs for library, src/main.rs for binary`);
555
+ }
556
+
557
+ if (stackKeys.includes('go')) {
558
+ sections.push(`### Go
559
+ - Follow standard Go project layout (cmd/, internal/, pkg/)
560
+ - Use interfaces for dependency injection and testability
561
+ - Handle all errors explicitly — never ignore err returns
562
+ - Use context.Context for cancellation and timeouts
563
+ - Prefer table-driven tests
564
+ - Run \`go vet\` and \`golangci-lint\` before committing
565
+ - If using gRPC: define .proto files in proto/ or pkg/proto, generate with protoc
566
+ - If Makefile exists: use make targets for build/test/lint
567
+ - Organize: cmd/ for entry points, internal/ for private packages, pkg/ for public`);
568
+ }
569
+
570
+ if (stackKeys.includes('cpp')) {
571
+ sections.push(`### C++
572
+ - Follow project coding standards (check .clang-format if present)
573
+ - Use smart pointers (unique_ptr, shared_ptr) over raw pointers
574
+ - Run clang-tidy for static analysis
575
+ - Prefer const references for function parameters
576
+ - Use CMake targets, not raw compiler flags`);
577
+ }
578
+
579
+ if (stackKeys.includes('bazel')) {
580
+ sections.push(`### Bazel
581
+ - Define BUILD files per package. Keep targets focused
582
+ - Use visibility carefully — prefer package-private
583
+ - Run buildifier for formatting`);
584
+ }
585
+
586
+ if (stackKeys.includes('terraform')) {
587
+ sections.push(`### Terraform
588
+ - Use modules for reusable infrastructure components
589
+ - Always run \`terraform plan\` before \`terraform apply\`
590
+ - Store state remotely (S3 + DynamoDB, or Terraform Cloud)
591
+ - Use variables.tf for all configurable values
592
+ - Tag all resources consistently
593
+ - If using Helm: define charts in charts/ or helm/, use values.yaml for config
594
+ - Lock providers: always commit .terraform.lock.hcl
595
+ - Use terraform fmt before committing`);
596
+ }
597
+
598
+ const hasJS = stackKeys.some(k => ['react', 'vue', 'angular', 'nextjs', 'node', 'svelte'].includes(k));
599
+ if (hasJS && !stackKeys.includes('typescript')) {
600
+ sections.push(`### JavaScript
601
+ - Use \`const\` by default, \`let\` when reassignment needed; never \`var\`
602
+ - Use \`async/await\` over raw Promises
603
+ - Use named exports over default exports
604
+ - Import order: stdlib > external > internal > relative`);
605
+ }
606
+
607
+ return sections.join('\n\n');
608
+ }
609
+
610
610
 
611
611
  module.exports = {
612
612
  detectDependencies,