@nerviq/cli 0.0.1 → 0.9.0-beta.1

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 (148) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +21 -0
  3. package/README.md +447 -0
  4. package/bin/cli.js +749 -0
  5. package/content/case-study-template.md +91 -0
  6. package/content/claims-governance.md +37 -0
  7. package/content/claude-code/audit-repo/SKILL.md +20 -0
  8. package/content/claude-native-integration.md +60 -0
  9. package/content/devto-article.json +9 -0
  10. package/content/launch-posts.md +226 -0
  11. package/content/pilot-rollout-kit.md +30 -0
  12. package/content/release-checklist.md +31 -0
  13. package/package.json +53 -4
  14. package/src/activity.js +529 -0
  15. package/src/aider/activity.js +226 -0
  16. package/src/aider/config-parser.js +166 -0
  17. package/src/aider/context.js +158 -0
  18. package/src/aider/deep-review.js +316 -0
  19. package/src/aider/domain-packs.js +278 -0
  20. package/src/aider/freshness.js +168 -0
  21. package/src/aider/governance.js +253 -0
  22. package/src/aider/interactive.js +334 -0
  23. package/src/aider/mcp-packs.js +98 -0
  24. package/src/aider/patch.js +214 -0
  25. package/src/aider/plans.js +186 -0
  26. package/src/aider/premium.js +360 -0
  27. package/src/aider/setup.js +404 -0
  28. package/src/aider/techniques.js +1323 -0
  29. package/src/analyze.js +821 -0
  30. package/src/audit.js +1003 -0
  31. package/src/badge.js +13 -0
  32. package/src/benchmark.js +339 -0
  33. package/src/claudex-sync.json +7 -0
  34. package/src/codex/activity.js +324 -0
  35. package/src/codex/config-parser.js +183 -0
  36. package/src/codex/context.js +221 -0
  37. package/src/codex/deep-review.js +493 -0
  38. package/src/codex/domain-packs.js +372 -0
  39. package/src/codex/freshness.js +167 -0
  40. package/src/codex/governance.js +192 -0
  41. package/src/codex/interactive.js +618 -0
  42. package/src/codex/mcp-packs.js +660 -0
  43. package/src/codex/patch.js +209 -0
  44. package/src/codex/plans.js +251 -0
  45. package/src/codex/premium.js +614 -0
  46. package/src/codex/setup.js +603 -0
  47. package/src/codex/techniques.js +2649 -0
  48. package/src/context.js +272 -0
  49. package/src/copilot/activity.js +309 -0
  50. package/src/copilot/config-parser.js +226 -0
  51. package/src/copilot/context.js +197 -0
  52. package/src/copilot/deep-review.js +346 -0
  53. package/src/copilot/domain-packs.js +350 -0
  54. package/src/copilot/freshness.js +197 -0
  55. package/src/copilot/governance.js +222 -0
  56. package/src/copilot/interactive.js +406 -0
  57. package/src/copilot/mcp-packs.js +572 -0
  58. package/src/copilot/patch.js +238 -0
  59. package/src/copilot/plans.js +253 -0
  60. package/src/copilot/premium.js +450 -0
  61. package/src/copilot/setup.js +488 -0
  62. package/src/copilot/techniques.js +1822 -0
  63. package/src/cursor/activity.js +301 -0
  64. package/src/cursor/config-parser.js +265 -0
  65. package/src/cursor/context.js +236 -0
  66. package/src/cursor/deep-review.js +334 -0
  67. package/src/cursor/domain-packs.js +346 -0
  68. package/src/cursor/freshness.js +214 -0
  69. package/src/cursor/governance.js +229 -0
  70. package/src/cursor/interactive.js +391 -0
  71. package/src/cursor/mcp-packs.js +571 -0
  72. package/src/cursor/patch.js +243 -0
  73. package/src/cursor/plans.js +254 -0
  74. package/src/cursor/premium.js +468 -0
  75. package/src/cursor/setup.js +488 -0
  76. package/src/cursor/techniques.js +1786 -0
  77. package/src/deep-review.js +345 -0
  78. package/src/domain-packs.js +364 -0
  79. package/src/formatters/sarif.js +115 -0
  80. package/src/gemini/activity.js +402 -0
  81. package/src/gemini/config-parser.js +275 -0
  82. package/src/gemini/context.js +221 -0
  83. package/src/gemini/deep-review.js +559 -0
  84. package/src/gemini/domain-packs.js +371 -0
  85. package/src/gemini/freshness.js +204 -0
  86. package/src/gemini/governance.js +201 -0
  87. package/src/gemini/interactive.js +860 -0
  88. package/src/gemini/mcp-packs.js +658 -0
  89. package/src/gemini/patch.js +229 -0
  90. package/src/gemini/plans.js +269 -0
  91. package/src/gemini/premium.js +759 -0
  92. package/src/gemini/setup.js +692 -0
  93. package/src/gemini/techniques.js +2084 -0
  94. package/src/governance.js +523 -0
  95. package/src/harmony/advisor.js +383 -0
  96. package/src/harmony/audit.js +303 -0
  97. package/src/harmony/canon.js +444 -0
  98. package/src/harmony/cli.js +331 -0
  99. package/src/harmony/drift.js +401 -0
  100. package/src/harmony/governance.js +313 -0
  101. package/src/harmony/memory.js +238 -0
  102. package/src/harmony/sync.js +458 -0
  103. package/src/harmony/watch.js +336 -0
  104. package/src/index.js +256 -0
  105. package/src/insights.js +119 -0
  106. package/src/interactive.js +118 -0
  107. package/src/mcp-packs.js +597 -0
  108. package/src/opencode/activity.js +286 -0
  109. package/src/opencode/config-parser.js +109 -0
  110. package/src/opencode/context.js +247 -0
  111. package/src/opencode/deep-review.js +313 -0
  112. package/src/opencode/domain-packs.js +240 -0
  113. package/src/opencode/freshness.js +158 -0
  114. package/src/opencode/governance.js +159 -0
  115. package/src/opencode/interactive.js +392 -0
  116. package/src/opencode/mcp-packs.js +474 -0
  117. package/src/opencode/patch.js +184 -0
  118. package/src/opencode/plans.js +231 -0
  119. package/src/opencode/premium.js +413 -0
  120. package/src/opencode/setup.js +449 -0
  121. package/src/opencode/techniques.js +1713 -0
  122. package/src/plans.js +655 -0
  123. package/src/secret-patterns.js +30 -0
  124. package/src/setup.js +1274 -0
  125. package/src/synergy/adaptive.js +261 -0
  126. package/src/synergy/compensation.js +156 -0
  127. package/src/synergy/evidence.js +193 -0
  128. package/src/synergy/learning.js +184 -0
  129. package/src/synergy/patterns.js +227 -0
  130. package/src/synergy/ranking.js +83 -0
  131. package/src/synergy/report.js +163 -0
  132. package/src/synergy/routing.js +152 -0
  133. package/src/techniques.js +1354 -0
  134. package/src/watch.js +229 -0
  135. package/src/windsurf/activity.js +302 -0
  136. package/src/windsurf/config-parser.js +267 -0
  137. package/src/windsurf/context.js +249 -0
  138. package/src/windsurf/deep-review.js +337 -0
  139. package/src/windsurf/domain-packs.js +348 -0
  140. package/src/windsurf/freshness.js +215 -0
  141. package/src/windsurf/governance.js +231 -0
  142. package/src/windsurf/interactive.js +388 -0
  143. package/src/windsurf/mcp-packs.js +535 -0
  144. package/src/windsurf/patch.js +231 -0
  145. package/src/windsurf/plans.js +247 -0
  146. package/src/windsurf/premium.js +467 -0
  147. package/src/windsurf/setup.js +471 -0
  148. package/src/windsurf/techniques.js +1758 -0
package/src/setup.js ADDED
@@ -0,0 +1,1274 @@
1
+ /**
2
+ * Setup engine - applies recommended Claude Code configuration to a project.
3
+ * v1.8.0 - Starter-safe setup engine with reusable planning primitives.
4
+ */
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { TECHNIQUES, STACKS } = require('./techniques');
9
+ const { ProjectContext } = require('./context');
10
+ const { audit } = require('./audit');
11
+ const { buildSettingsForProfile } = require('./governance');
12
+ const { getMcpPackPreflight } = require('./mcp-packs');
13
+ const { setupCodex } = require('./codex/setup');
14
+
15
+ // ============================================================
16
+ // Helper: detect project scripts from package.json
17
+ // ============================================================
18
+ function detectScripts(ctx) {
19
+ const pkg = ctx.jsonFile('package.json');
20
+ if (!pkg || !pkg.scripts) return {};
21
+ const relevant = ['test', 'build', 'lint', 'dev', 'start', 'format', 'typecheck', 'check'];
22
+ const found = {};
23
+ for (const key of relevant) {
24
+ if (pkg.scripts[key]) {
25
+ found[key] = pkg.scripts[key];
26
+ }
27
+ }
28
+ return found;
29
+ }
30
+
31
+ // ============================================================
32
+ // Helper: detect key dependencies and generate guidelines
33
+ // ============================================================
34
+ function detectDependencies(ctx) {
35
+ const pkg = ctx.jsonFile('package.json') || {};
36
+ const allDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
37
+ const guidelines = [];
38
+
39
+ // Data fetching
40
+ if (allDeps['@tanstack/react-query']) {
41
+ guidelines.push('- Use React Query (TanStack Query) for all server data fetching — never raw useEffect + fetch');
42
+ guidelines.push('- Define query keys as constants. Invalidate related queries after mutations');
43
+ }
44
+ if (allDeps['swr']) {
45
+ guidelines.push('- Use SWR for data fetching with automatic revalidation');
46
+ }
47
+
48
+ // Validation
49
+ if (allDeps['zod']) {
50
+ guidelines.push('- Use Zod for all input validation and type inference (z.infer<typeof schema>)');
51
+ guidelines.push('- Define schemas in a shared location. Use .parse() at API boundaries');
52
+ }
53
+
54
+ // ORM / Database
55
+ if (allDeps['prisma'] || allDeps['@prisma/client']) {
56
+ guidelines.push('- Use Prisma for all database operations. Run `npx prisma generate` after schema changes');
57
+ guidelines.push('- Never write raw SQL unless Prisma cannot express the query');
58
+ }
59
+ if (allDeps['drizzle-orm']) {
60
+ guidelines.push('- Use Drizzle ORM for database operations. Schema-first approach');
61
+ }
62
+ if (allDeps['mongoose']) {
63
+ guidelines.push('- Use Mongoose for MongoDB operations. Define schemas with validation');
64
+ }
65
+
66
+ // Auth
67
+ if (allDeps['next-auth'] || allDeps['@auth/core']) {
68
+ guidelines.push('- Use NextAuth.js for authentication. Access session via auth() in Server Components');
69
+ }
70
+ if (allDeps['clerk'] || allDeps['@clerk/nextjs']) {
71
+ guidelines.push('- Use Clerk for authentication. Protect routes with middleware');
72
+ }
73
+
74
+ // State management
75
+ if (allDeps['zustand']) {
76
+ guidelines.push('- Use Zustand for client state. Keep stores small and focused');
77
+ }
78
+ if (allDeps['@reduxjs/toolkit']) {
79
+ guidelines.push('- Use Redux Toolkit for state management. Use createSlice and RTK Query');
80
+ }
81
+
82
+ // Styling
83
+ if (allDeps['tailwindcss']) {
84
+ guidelines.push('- Use Tailwind CSS for all styling. Avoid inline styles and CSS modules');
85
+ }
86
+ if (allDeps['styled-components'] || allDeps['@emotion/react']) {
87
+ guidelines.push('- Use CSS-in-JS for component styling. Colocate styles with components');
88
+ }
89
+
90
+ // Testing
91
+ if (allDeps['vitest']) {
92
+ guidelines.push('- Use Vitest for testing. Colocate test files with source (*.test.ts)');
93
+ }
94
+ if (allDeps['jest']) {
95
+ guidelines.push('- Use Jest for testing. Follow existing test patterns in the codebase');
96
+ }
97
+ if (allDeps['playwright'] || allDeps['@playwright/test']) {
98
+ guidelines.push('- Use Playwright for E2E tests. Keep tests in tests/ or e2e/');
99
+ }
100
+
101
+ // Testing tools
102
+ if (allDeps['msw']) {
103
+ guidelines.push('- Use MSW (Mock Service Worker) for API mocking in tests. Define handlers in __mocks__/');
104
+ }
105
+ if (allDeps['@testing-library/react']) {
106
+ guidelines.push('- Use Testing Library for component tests. Prefer userEvent over fireEvent, query by role/label');
107
+ }
108
+ if (allDeps['@vitest/coverage-v8'] || allDeps['@vitest/coverage-istanbul']) {
109
+ guidelines.push('- Coverage configured. Maintain coverage thresholds. Check reports before merging');
110
+ }
111
+
112
+ // tRPC
113
+ if (allDeps['@trpc/server'] || allDeps['@trpc/client']) {
114
+ guidelines.push('- Use tRPC for type-safe API calls. Define routers in server, use client hooks in components');
115
+ }
116
+
117
+ // Stripe
118
+ if (allDeps['stripe']) {
119
+ guidelines.push('- Use Stripe SDK for payments. Always verify webhooks with stripe.webhooks.constructEvent()');
120
+ }
121
+
122
+ // Resend
123
+ if (allDeps['resend']) {
124
+ guidelines.push('- Use Resend for transactional email. Define templates as React components');
125
+ }
126
+
127
+ // Express security
128
+ if (allDeps['helmet']) {
129
+ guidelines.push('- Helmet is configured — ensure all middleware is applied before routes');
130
+ }
131
+ if (allDeps['jsonwebtoken']) {
132
+ guidelines.push('- Use JWT for authentication. Always verify tokens with the correct secret/algorithm');
133
+ }
134
+ if (allDeps['bcrypt']) {
135
+ guidelines.push('- Use bcrypt for password hashing. Never store plaintext passwords');
136
+ }
137
+ if (allDeps['cors']) {
138
+ guidelines.push('- CORS is configured — restrict origins to known domains in production');
139
+ }
140
+
141
+ // Monorepo
142
+ if (allDeps['turbo'] || allDeps['turborepo']) {
143
+ guidelines.push('- Turborepo monorepo — use `turbo run` for all tasks. Respect package boundaries');
144
+ }
145
+ if (allDeps['nx']) {
146
+ guidelines.push('- Nx monorepo — use `nx affected` for incremental builds and tests');
147
+ }
148
+
149
+ // Python
150
+ const reqTxt = ctx.fileContent('requirements.txt') || '';
151
+ if (reqTxt.includes('sqlalchemy')) {
152
+ guidelines.push('- Use SQLAlchemy for database operations. Define models in models/');
153
+ }
154
+ if (reqTxt.includes('pydantic')) {
155
+ guidelines.push('- Use Pydantic for data validation and serialization');
156
+ }
157
+ if (reqTxt.includes('pytest')) {
158
+ guidelines.push('- Use pytest for testing. Run with `python -m pytest`');
159
+ }
160
+ if (reqTxt.includes('alembic')) {
161
+ guidelines.push('- Use Alembic for database migrations. Run `alembic upgrade head` after model changes');
162
+ }
163
+ if (reqTxt.includes('celery')) {
164
+ guidelines.push('- Use Celery for background tasks. Define tasks in tasks/ or services/');
165
+ }
166
+ if (reqTxt.includes('redis')) {
167
+ guidelines.push('- Redis is available for caching and task queues');
168
+ }
169
+ if (reqTxt.includes('langchain')) {
170
+ guidelines.push('- Use LangChain for chain/agent orchestration. Define chains in chains/ directory');
171
+ }
172
+ if (reqTxt.includes('openai')) {
173
+ guidelines.push('- OpenAI SDK available. Use structured outputs where possible');
174
+ }
175
+ if (reqTxt.includes('anthropic')) {
176
+ guidelines.push('- Anthropic SDK available. Prefer Claude for complex reasoning tasks');
177
+ }
178
+ if (reqTxt.includes('chromadb')) {
179
+ guidelines.push('- Use ChromaDB for local vector storage. Persist collections to disk');
180
+ }
181
+ if (reqTxt.includes('pinecone')) {
182
+ guidelines.push('- Use Pinecone for production vector search. Define index schemas upfront');
183
+ }
184
+ if (reqTxt.includes('mlflow')) {
185
+ guidelines.push('- Use MLflow for experiment tracking. Log all model parameters and metrics');
186
+ }
187
+ if (reqTxt.includes('wandb')) {
188
+ guidelines.push('- Use Weights & Biases for experiment tracking and visualization');
189
+ }
190
+ if (reqTxt.includes('transformers')) {
191
+ guidelines.push('- HuggingFace Transformers available. Use AutoModel/AutoTokenizer for loading');
192
+ }
193
+
194
+ // JS AI/ML/Cloud deps
195
+ if (allDeps['@anthropic-ai/sdk']) {
196
+ guidelines.push('- Anthropic SDK configured. Use Messages API with structured tool_use for agents');
197
+ }
198
+ if (allDeps['openai']) {
199
+ guidelines.push('- OpenAI SDK available. Use structured outputs and function calling');
200
+ }
201
+ if (allDeps['@modelcontextprotocol/sdk']) {
202
+ guidelines.push('- MCP SDK available. Build MCP servers with stdio transport');
203
+ }
204
+ if (allDeps['langchain'] || allDeps['@langchain/core']) {
205
+ guidelines.push('- LangChain available. Use LCEL for chain composition');
206
+ }
207
+ if (allDeps['@aws-sdk/client-s3'] || allDeps['@aws-sdk/client-dynamodb']) {
208
+ guidelines.push('- AWS SDK v3 configured. Use modular imports, not aws-sdk v2');
209
+ }
210
+ if (allDeps['@aws-cdk/aws-lambda'] || allDeps['aws-cdk-lib']) {
211
+ guidelines.push('- AWS CDK available. Define stacks in lib/, constructs as separate classes');
212
+ }
213
+
214
+ // Security middleware
215
+ if (allDeps['express-rate-limit']) {
216
+ guidelines.push('- Rate limiting configured. Apply to auth endpoints. Set appropriate windowMs and max values');
217
+ }
218
+ if (allDeps['hpp']) {
219
+ guidelines.push('- HPP (HTTP Parameter Pollution) protection enabled');
220
+ }
221
+ if (allDeps['csurf']) {
222
+ guidelines.push('- CSRF protection enabled. Ensure tokens are included in all state-changing requests');
223
+ }
224
+
225
+ // AWS Lambda
226
+ if (allDeps['@aws-sdk/client-lambda'] || allDeps['@aws-cdk/aws-lambda'] || allDeps['aws-cdk-lib']) {
227
+ guidelines.push('- Lambda handlers: keep cold start fast, use layers for deps, set appropriate memory/timeout');
228
+ }
229
+
230
+ // Deprecated dependency warnings
231
+ if (allDeps['moment']) {
232
+ guidelines.push('- ⚠️ moment.js is deprecated and heavy (330KB). Migrate to date-fns or dayjs');
233
+ }
234
+ if (allDeps['request']) {
235
+ guidelines.push('- ⚠️ request is deprecated. Use fetch (native) or axios instead');
236
+ }
237
+ if (allDeps['lodash'] && !allDeps['lodash-es']) {
238
+ guidelines.push('- Consider replacing lodash with native JS methods or lodash-es for tree-shaking');
239
+ }
240
+ if (allDeps['node-sass']) {
241
+ guidelines.push('- ⚠️ node-sass is deprecated. Migrate to sass (dart-sass)');
242
+ }
243
+ if (allDeps['tslint']) {
244
+ guidelines.push('- ⚠️ TSLint is deprecated. Migrate to ESLint with @typescript-eslint');
245
+ }
246
+
247
+ return guidelines;
248
+ }
249
+
250
+ // ============================================================
251
+ // Helper: detect main directories
252
+ // ============================================================
253
+ function detectMainDirs(ctx) {
254
+ 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'];
255
+ // Also check inside src/ for nested structure (common in Next.js, React)
256
+ 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'];
257
+ const found = [];
258
+ const seenNames = new Set();
259
+
260
+ for (const dir of [...candidates, ...srcNested]) {
261
+ if (ctx.hasDir(dir)) {
262
+ const files = ctx.dirFiles(dir);
263
+ const displayName = dir.includes('/') ? dir : dir;
264
+ if (!seenNames.has(displayName)) {
265
+ found.push({ name: displayName, fileCount: files.length, files: files.slice(0, 10) });
266
+ seenNames.add(displayName);
267
+ }
268
+ }
269
+ }
270
+ return found;
271
+ }
272
+
273
+ function escapeRegex(value) {
274
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
275
+ }
276
+
277
+ function extractTomlSection(content, sectionName) {
278
+ const pattern = new RegExp(`\\[${escapeRegex(sectionName)}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`);
279
+ const match = content.match(pattern);
280
+ return match ? match[1] : null;
281
+ }
282
+
283
+ function extractTomlValue(sectionContent, key) {
284
+ if (!sectionContent) return null;
285
+ const pattern = new RegExp(`^\\s*${escapeRegex(key)}\\s*=\\s*["']([^"']+)["']`, 'm');
286
+ const match = sectionContent.match(pattern);
287
+ return match ? match[1].trim() : null;
288
+ }
289
+
290
+ function detectProjectMetadata(ctx) {
291
+ const pkg = ctx.jsonFile('package.json');
292
+ if (pkg && (pkg.name || pkg.description)) {
293
+ return {
294
+ name: pkg.name || path.basename(ctx.dir),
295
+ description: pkg.description || '',
296
+ };
297
+ }
298
+
299
+ const pyproject = ctx.fileContent('pyproject.toml') || '';
300
+ if (pyproject) {
301
+ const projectSection = extractTomlSection(pyproject, 'project');
302
+ const poetrySection = extractTomlSection(pyproject, 'tool.poetry');
303
+ const name = extractTomlValue(projectSection, 'name') ||
304
+ extractTomlValue(poetrySection, 'name');
305
+ const description = extractTomlValue(projectSection, 'description') ||
306
+ extractTomlValue(poetrySection, 'description');
307
+
308
+ if (name || description) {
309
+ return {
310
+ name: name || path.basename(ctx.dir),
311
+ description: description || '',
312
+ };
313
+ }
314
+ }
315
+
316
+ return {
317
+ name: path.basename(ctx.dir),
318
+ description: '',
319
+ };
320
+ }
321
+
322
+ // ============================================================
323
+ // Helper: generate Mermaid diagram from directory structure
324
+ // ============================================================
325
+ function generateMermaid(dirs, stacks) {
326
+ const stackKeys = stacks.map(s => s.key);
327
+ const dirNames = dirs.map(d => d.name);
328
+
329
+ // Build nodes based on what exists
330
+ const nodes = [];
331
+ const edges = [];
332
+ let nodeId = 0;
333
+ const ids = {};
334
+
335
+ function addNode(label, shape) {
336
+ const id = String.fromCharCode(65 + nodeId++); // A, B, C...
337
+ ids[label] = id;
338
+ if (shape === 'db') return ` ${id}[(${label})]`;
339
+ if (shape === 'round') return ` ${id}(${label})`;
340
+ return ` ${id}[${label}]`;
341
+ }
342
+
343
+ // Detect Next.js App Router specifically
344
+ const hasAppRouter = dirNames.includes('app') || dirNames.includes('src/app');
345
+ const hasPages = dirNames.includes('pages') || dirNames.includes('src/pages');
346
+ const hasAppApi = dirNames.includes('app/api') || dirNames.includes('src/app/api');
347
+ const hasSrcComponents = dirNames.includes('src/components') || dirNames.includes('components');
348
+ const hasSrcHooks = dirNames.includes('src/hooks') || dirNames.includes('hooks');
349
+ const hasSrcLib = dirNames.includes('src/lib') || dirNames.includes('lib');
350
+ const hasSrcNode = dirNames.includes('src');
351
+ const hasAgents = dirNames.includes('src/agents') || dirNames.includes('agents');
352
+ const hasChains = dirNames.includes('src/chains') || dirNames.includes('chains');
353
+ const hasWorkers = dirNames.includes('src/workers') || dirNames.includes('workers') || dirNames.includes('jobs');
354
+ const hasPipelines = dirNames.includes('dags') || dirNames.includes('macros');
355
+
356
+ // Smart entry point based on framework
357
+ const isNextJs = stackKeys.includes('nextjs');
358
+ const isDjango = stackKeys.includes('django');
359
+ const isFastApi = stackKeys.includes('fastapi');
360
+
361
+ if (isNextJs) {
362
+ nodes.push(addNode('Next.js', 'round'));
363
+ } else if (isDjango) {
364
+ nodes.push(addNode('Django', 'round'));
365
+ } else if (isFastApi) {
366
+ nodes.push(addNode('FastAPI', 'round'));
367
+ } else {
368
+ nodes.push(addNode('Entry Point', 'round'));
369
+ }
370
+
371
+ const root = ids['Next.js'] || ids['Django'] || ids['FastAPI'] || ids['Entry Point'] || 'A';
372
+ const pickNodeId = (...labels) => labels.map(label => ids[label]).find(Boolean) || root;
373
+
374
+ // Detect layers
375
+ if (hasAppRouter || hasPages) {
376
+ const label = hasAppRouter ? 'App Router' : 'Pages';
377
+ nodes.push(addNode(label, 'default'));
378
+ edges.push(` ${root} --> ${ids[label]}`);
379
+ }
380
+
381
+ if (hasAppApi) {
382
+ nodes.push(addNode('API Routes', 'default'));
383
+ const parent = ids['App Router'] || ids['Pages'] || root;
384
+ edges.push(` ${parent} --> ${ids['API Routes']}`);
385
+ }
386
+
387
+ if (hasSrcComponents) {
388
+ nodes.push(addNode('Components', 'default'));
389
+ const parent = ids['App Router'] || ids['Pages'] || root;
390
+ edges.push(` ${parent} --> ${ids['Components']}`);
391
+ }
392
+
393
+ if (hasSrcHooks) {
394
+ nodes.push(addNode('Hooks', 'default'));
395
+ const parent = ids['Components'] || root;
396
+ edges.push(` ${parent} --> ${ids['Hooks']}`);
397
+ }
398
+
399
+ if (hasSrcLib) {
400
+ nodes.push(addNode('lib/', 'default'));
401
+ const parent = pickNodeId('API Routes', 'Hooks', 'Components');
402
+ edges.push(` ${parent} --> ${ids['lib/']}`);
403
+ } else if (hasSrcNode && !hasAppRouter && !hasPages) {
404
+ nodes.push(addNode('src/', 'default'));
405
+ edges.push(` ${root} --> ${ids['src/']}`);
406
+ }
407
+
408
+ if (dirNames.includes('api') || dirNames.includes('routes') || dirNames.includes('controllers')) {
409
+ const label = dirNames.includes('api') ? 'API Layer' : 'Routes';
410
+ nodes.push(addNode(label, 'default'));
411
+ const parent = pickNodeId('src/', 'App Router', 'Pages');
412
+ edges.push(` ${parent} --> ${ids[label]}`);
413
+ }
414
+
415
+ if (dirNames.includes('services')) {
416
+ nodes.push(addNode('Services', 'default'));
417
+ const parent = pickNodeId('API Layer', 'Routes', 'src/', 'App Router', 'Pages');
418
+ edges.push(` ${parent} --> ${ids['Services']}`);
419
+ }
420
+
421
+ if (dirNames.includes('models') || dirNames.includes('prisma') || dirNames.includes('db')) {
422
+ nodes.push(addNode('Data Layer', 'default'));
423
+ const parent = pickNodeId('Services', 'API Layer', 'Routes', 'src/', 'App Router', 'Pages');
424
+ edges.push(` ${parent} --> ${ids['Data Layer']}`);
425
+ nodes.push(addNode('Database', 'db'));
426
+ edges.push(` ${ids['Data Layer']} --> ${ids['Database']}`);
427
+ }
428
+
429
+ if (dirNames.includes('utils') || dirNames.includes('helpers')) {
430
+ nodes.push(addNode('Utils', 'default'));
431
+ const parent = pickNodeId('src/', 'Services', 'lib/', 'Components');
432
+ edges.push(` ${parent} --> ${ids['Utils']}`);
433
+ }
434
+
435
+ if (dirNames.includes('middleware')) {
436
+ nodes.push(addNode('Middleware', 'default'));
437
+ const parent = pickNodeId('API Layer', 'Routes', 'App Router', 'Pages');
438
+ edges.push(` ${parent} --> ${ids['Middleware']}`);
439
+ }
440
+
441
+ if (hasChains) {
442
+ nodes.push(addNode('Chains', 'default'));
443
+ const parent = pickNodeId('Services', 'src/', 'lib/', 'API Layer');
444
+ edges.push(` ${parent} --> ${ids['Chains']}`);
445
+ }
446
+
447
+ if (hasAgents) {
448
+ nodes.push(addNode('Agents', 'default'));
449
+ const parent = pickNodeId('Chains', 'Services', 'src/', 'lib/');
450
+ edges.push(` ${parent} --> ${ids['Agents']}`);
451
+ }
452
+
453
+ if (hasWorkers) {
454
+ nodes.push(addNode('Workers', 'default'));
455
+ const parent = pickNodeId('Services', 'API Layer', 'src/');
456
+ edges.push(` ${parent} --> ${ids['Workers']}`);
457
+ }
458
+
459
+ if (hasPipelines) {
460
+ nodes.push(addNode('Pipelines', 'default'));
461
+ const parent = pickNodeId('Services', 'Data Layer', 'src/');
462
+ edges.push(` ${parent} --> ${ids['Pipelines']}`);
463
+ }
464
+
465
+ if (dirNames.includes('tests') || dirNames.includes('test') || dirNames.includes('__tests__') || dirNames.includes('spec')) {
466
+ nodes.push(addNode('Tests', 'round'));
467
+ const parent = pickNodeId('src/', 'App Router', 'Pages', 'Services', 'Components');
468
+ edges.push(` ${ids['Tests']} -.-> ${parent}`);
469
+ }
470
+
471
+ // Fallback: if we only have Entry Point, make a generic diagram
472
+ if (nodes.length <= 1) {
473
+ return `\`\`\`mermaid
474
+ graph TD
475
+ A[Entry Point] --> B[Core Logic]
476
+ B --> C[Data Layer]
477
+ B --> D[API / Routes]
478
+ C --> E[(Database)]
479
+ D --> F[External Services]
480
+ \`\`\`
481
+ <!-- Update this diagram to match your actual architecture -->`;
482
+ }
483
+
484
+ return '```mermaid\ngraph TD\n' + nodes.join('\n') + '\n' + edges.join('\n') + '\n```';
485
+ }
486
+
487
+ // ============================================================
488
+ // Helper: framework-specific instructions
489
+ // ============================================================
490
+ function getFrameworkInstructions(stacks) {
491
+ const stackKeys = stacks.map(s => s.key);
492
+ const sections = [];
493
+
494
+ if (stackKeys.includes('nextjs')) {
495
+ sections.push(`### Next.js
496
+ - Use App Router conventions (app/ directory) when applicable
497
+ - Prefer Server Components by default; add 'use client' only when needed
498
+ - Use next/image for images, next/link for navigation
499
+ - API routes go in app/api/ (App Router) or pages/api/ (Pages Router)
500
+ - Use loading.tsx, error.tsx, and not-found.tsx for route-level UX
501
+ - If app/ exists, use Server Actions for mutations, validate with Zod, and call revalidatePath after writes
502
+ - Route handlers in app/api/ should export named functions: GET, POST, PUT, DELETE
503
+ - Middleware in middleware.ts should handle auth checks, redirects, and headers`);
504
+ } else if (stackKeys.includes('react')) {
505
+ sections.push(`### React
506
+ - Use functional components with hooks exclusively
507
+ - Prefer named exports over default exports
508
+ - Keep components under 150 lines; extract sub-components
509
+ - Use custom hooks to share stateful logic
510
+ - Colocate styles, tests, and types with components`);
511
+ }
512
+
513
+ if (stackKeys.includes('vue')) {
514
+ sections.push(`### Vue
515
+ - Use Composition API with \`<script setup>\` syntax
516
+ - Prefer defineProps/defineEmits macros
517
+ - Keep components under 200 lines
518
+ - Use composables for shared logic`);
519
+ }
520
+
521
+ if (stackKeys.includes('angular')) {
522
+ sections.push(`### Angular
523
+ - Use standalone components when possible
524
+ - Follow Angular style guide naming conventions
525
+ - Use reactive forms over template-driven forms
526
+ - Keep services focused on a single responsibility`);
527
+ }
528
+
529
+ if (stackKeys.includes('typescript')) {
530
+ sections.push(`### TypeScript
531
+ - Use \`interface\` for object shapes, \`type\` for unions/intersections
532
+ - Enable strict mode in tsconfig.json
533
+ - Avoid \`any\` — use \`unknown\` and narrow with type guards
534
+ - Prefer \`as const\` assertions over enum when practical
535
+ - Export types alongside their implementations`);
536
+ }
537
+
538
+ if (stackKeys.includes('django')) {
539
+ sections.push(`### Django
540
+ - Follow fat models, thin views pattern
541
+ - Use class-based views for complex logic, function views for simple
542
+ - Always use Django ORM; avoid raw SQL unless necessary
543
+ - Keep business logic in models or services, not views`);
544
+ } else if (stackKeys.includes('fastapi')) {
545
+ sections.push(`### FastAPI
546
+ - Use Pydantic models for request/response validation
547
+ - Use dependency injection for shared logic
548
+ - Keep route handlers thin; delegate to service functions
549
+ - Use async def for I/O-bound endpoints`);
550
+ }
551
+
552
+ if (stackKeys.includes('python') || stackKeys.includes('django') || stackKeys.includes('fastapi')) {
553
+ sections.push(`### Python
554
+ - Use type hints on all function signatures and return types
555
+ - Follow PEP 8; use f-strings for formatting
556
+ - Prefer pathlib over os.path
557
+ - Use dataclasses or pydantic for structured data
558
+ - Raise specific exceptions; never bare \`except:\``);
559
+ }
560
+
561
+ if (stackKeys.includes('rust')) {
562
+ sections.push(`### Rust
563
+ - Use Result<T, E> for error handling, avoid unwrap() in production code
564
+ - Prefer &str over String for function parameters
565
+ - Use clippy: \`cargo clippy -- -D warnings\`
566
+ - Structure: src/lib.rs for library, src/main.rs for binary`);
567
+ }
568
+
569
+ if (stackKeys.includes('go')) {
570
+ sections.push(`### Go
571
+ - Follow standard Go project layout (cmd/, internal/, pkg/)
572
+ - Use interfaces for dependency injection and testability
573
+ - Handle all errors explicitly — never ignore err returns
574
+ - Use context.Context for cancellation and timeouts
575
+ - Prefer table-driven tests
576
+ - Run \`go vet\` and \`golangci-lint\` before committing
577
+ - If using gRPC: define .proto files in proto/ or pkg/proto, generate with protoc
578
+ - If Makefile exists: use make targets for build/test/lint
579
+ - Organize: cmd/ for entry points, internal/ for private packages, pkg/ for public`);
580
+ }
581
+
582
+ if (stackKeys.includes('cpp')) {
583
+ sections.push(`### C++
584
+ - Follow project coding standards (check .clang-format if present)
585
+ - Use smart pointers (unique_ptr, shared_ptr) over raw pointers
586
+ - Run clang-tidy for static analysis
587
+ - Prefer const references for function parameters
588
+ - Use CMake targets, not raw compiler flags`);
589
+ }
590
+
591
+ if (stackKeys.includes('bazel')) {
592
+ sections.push(`### Bazel
593
+ - Define BUILD files per package. Keep targets focused
594
+ - Use visibility carefully — prefer package-private
595
+ - Run buildifier for formatting`);
596
+ }
597
+
598
+ if (stackKeys.includes('terraform')) {
599
+ sections.push(`### Terraform
600
+ - Use modules for reusable infrastructure components
601
+ - Always run \`terraform plan\` before \`terraform apply\`
602
+ - Store state remotely (S3 + DynamoDB, or Terraform Cloud)
603
+ - Use variables.tf for all configurable values
604
+ - Tag all resources consistently
605
+ - If using Helm: define charts in charts/ or helm/, use values.yaml for config
606
+ - Lock providers: always commit .terraform.lock.hcl
607
+ - Use terraform fmt before committing`);
608
+ }
609
+
610
+ const hasJS = stackKeys.some(k => ['react', 'vue', 'angular', 'nextjs', 'node', 'svelte'].includes(k));
611
+ if (hasJS && !stackKeys.includes('typescript')) {
612
+ sections.push(`### JavaScript
613
+ - Use \`const\` by default, \`let\` when reassignment needed; never \`var\`
614
+ - Use \`async/await\` over raw Promises
615
+ - Use named exports over default exports
616
+ - Import order: stdlib > external > internal > relative`);
617
+ }
618
+
619
+ return sections.join('\n\n');
620
+ }
621
+
622
+ // ============================================================
623
+ // TEMPLATES
624
+ // ============================================================
625
+
626
+ const TEMPLATES = {
627
+ 'claude-md': (stacks, ctx) => {
628
+ const stackNames = stacks.map(s => s.label).join(', ') || 'General';
629
+ const stackKeys = stacks.map(s => s.key);
630
+
631
+ // --- Detect project details ---
632
+ const scripts = detectScripts(ctx);
633
+ const mainDirs = detectMainDirs(ctx);
634
+ const hasTS = stackKeys.includes('typescript') || ctx.files.includes('tsconfig.json');
635
+ const hasPython = stackKeys.includes('python') || stackKeys.includes('django') || stackKeys.includes('fastapi');
636
+ const hasJS = stackKeys.some(k => ['react', 'vue', 'angular', 'nextjs', 'node', 'svelte'].includes(k));
637
+
638
+ // --- Build commands section ---
639
+ let buildSection = '';
640
+ if (Object.keys(scripts).length > 0) {
641
+ const lines = [];
642
+ if (scripts.dev) lines.push(`npm run dev # ${scripts.dev}`);
643
+ if (scripts.start) lines.push(`npm start # ${scripts.start}`);
644
+ if (scripts.build) lines.push(`npm run build # ${scripts.build}`);
645
+ if (scripts.test) lines.push(`npm test # ${scripts.test}`);
646
+ if (scripts.lint) lines.push(`npm run lint # ${scripts.lint}`);
647
+ if (scripts.format) lines.push(`npm run format # ${scripts.format}`);
648
+ if (scripts.typecheck) lines.push(`npm run typecheck # ${scripts.typecheck}`);
649
+ if (scripts.check) lines.push(`npm run check # ${scripts.check}`);
650
+ buildSection = lines.join('\n');
651
+ } else if (hasPython) {
652
+ buildSection = `python -m pytest # run tests
653
+ python -m mypy . # type checking
654
+ ruff check . # lint`;
655
+ } else if (hasJS) {
656
+ buildSection = `npm run build # or: npx tsc --noEmit
657
+ npm test # or: npx jest / npx vitest
658
+ npm run lint # or: npx eslint .`;
659
+ } else {
660
+ buildSection = '# Add your build command\n# Add your test command\n# Add your lint command';
661
+ }
662
+
663
+ // --- Architecture description ---
664
+ const mermaid = generateMermaid(mainDirs, stacks);
665
+
666
+ let dirDescription = '';
667
+ if (mainDirs.length > 0) {
668
+ dirDescription = '\n### Directory Structure\n';
669
+ for (const dir of mainDirs) {
670
+ const suffix = dir.fileCount > 0 ? ` (${dir.fileCount} files)` : '';
671
+ dirDescription += `- \`${dir.name}/\`${suffix}\n`;
672
+ }
673
+ }
674
+
675
+ // --- Framework-specific instructions ---
676
+ const frameworkInstructions = getFrameworkInstructions(stacks);
677
+ let stackSection = frameworkInstructions
678
+ ? `\n## Stack-Specific Guidelines\n\n${frameworkInstructions}\n`
679
+ : '';
680
+
681
+ // Check for security-focused project
682
+ const pkg2 = ctx.jsonFile('package.json') || {};
683
+ const allDeps2 = { ...(pkg2.dependencies || {}), ...(pkg2.devDependencies || {}) };
684
+ const hasSecurityDeps = allDeps2['helmet'] || allDeps2['jsonwebtoken'] || allDeps2['bcrypt'] || allDeps2['passport'];
685
+ if (hasSecurityDeps) {
686
+ stackSection += '\n### Security Best Practices\n';
687
+ stackSection += '- Follow OWASP Top 10 — run /security-review regularly\n';
688
+ stackSection += '- Never log sensitive data (passwords, tokens, PII)\n';
689
+ stackSection += '- Use parameterized queries — never string concatenation for SQL\n';
690
+ stackSection += '- Set security headers via Helmet. Review CSP policy for your frontend\n';
691
+ stackSection += '- Rate limit all authentication endpoints\n';
692
+ stackSection += '- Validate and sanitize all user input at API boundaries\n';
693
+ }
694
+
695
+ // --- TypeScript-specific additions ---
696
+ let tsSection = '';
697
+ if (hasTS) {
698
+ const tsconfig = ctx.jsonFile('tsconfig.json');
699
+ if (tsconfig) {
700
+ const strict = tsconfig.compilerOptions && tsconfig.compilerOptions.strict;
701
+ tsSection = `
702
+ ## TypeScript Configuration
703
+ - Strict mode: ${strict ? '**enabled**' : '**disabled** (consider enabling)'}
704
+ - Always fix type errors before committing — do not use \`@ts-ignore\`
705
+ - Run type checking: \`${scripts.typecheck ? 'npm run typecheck' : 'npx tsc --noEmit'}\`
706
+ `;
707
+ }
708
+ }
709
+
710
+ // --- Dependency-specific guidelines ---
711
+ const depGuidelines = detectDependencies(ctx);
712
+ const depSection = depGuidelines.length > 0 ? `
713
+ ## Key Dependencies
714
+ ${depGuidelines.join('\n')}
715
+ ` : '';
716
+
717
+ // --- Verification criteria based on detected commands ---
718
+ const verificationSteps = [];
719
+ verificationSteps.push('1. All existing tests still pass');
720
+ verificationSteps.push('2. New code has test coverage');
721
+ if (scripts.lint || hasPython) {
722
+ verificationSteps.push(`3. No linting errors (\`${scripts.lint ? 'npm run lint' : 'ruff check .'}\`)`);
723
+ } else if (hasJS) {
724
+ verificationSteps.push('3. No linting errors (`npx eslint .`)');
725
+ } else {
726
+ verificationSteps.push('3. No linting errors introduced');
727
+ }
728
+ if (scripts.build) {
729
+ verificationSteps.push(`4. Build succeeds (\`npm run build\`)`);
730
+ }
731
+ if (hasTS) {
732
+ verificationSteps.push(`${verificationSteps.length + 1}. No TypeScript errors (\`${scripts.typecheck ? 'npm run typecheck' : 'npx tsc --noEmit'}\`)`);
733
+ }
734
+ verificationSteps.push(`${verificationSteps.length + 1}. Changes match the requested scope (no gold-plating)`);
735
+
736
+ // --- Read project metadata from package.json or pyproject.toml ---
737
+ const projectMeta = detectProjectMetadata(ctx);
738
+ const projectName = projectMeta.name;
739
+ const projectDesc = projectMeta.description ? ` — ${projectMeta.description}` : '';
740
+
741
+ // --- Assemble the final CLAUDE.md ---
742
+ return `# ${projectName}${projectDesc}
743
+
744
+ ## Architecture
745
+ ${mermaid}
746
+ ${dirDescription}
747
+ ## Stack
748
+ ${stackNames}
749
+ ${stackSection}${tsSection}${depSection}
750
+ ## Build & Test
751
+ \`\`\`bash
752
+ ${buildSection}
753
+ \`\`\`
754
+
755
+ ## Working Notes
756
+ - You are a careful engineer working inside this repository. Preserve its existing architecture and naming patterns unless the task requires a change
757
+ - Prefer extending existing modules over creating parallel abstractions
758
+ - Keep changes scoped to the requested task and verify them before marking work complete
759
+
760
+ <constraints>
761
+ - Never commit secrets, API keys, or .env files
762
+ - Always run tests before marking work complete
763
+ - Prefer editing existing files over creating new ones
764
+ - When uncertain about architecture, ask before implementing
765
+ ${hasTS ? '- Do not use @ts-ignore or @ts-expect-error without a tracking issue\n' : ''}\
766
+ ${hasJS ? '- Use const by default; never use var\n' : ''}\
767
+ </constraints>
768
+
769
+ <verification>
770
+ Before completing any task, confirm:
771
+ ${verificationSteps.join('\n')}
772
+ </verification>
773
+
774
+ ## Context Management
775
+ - Use /compact when context gets large (above 50% capacity)
776
+ - Prefer focused sessions — one task per conversation
777
+ - If a session gets too long, start fresh with /clear
778
+ - Use subagents for research tasks to keep main context clean
779
+
780
+ ---
781
+ *Generated by [nerviq](https://github.com/nerviq/nerviq) v${require('../package.json').version} on ${new Date().toISOString().split('T')[0]}. Customize this file for your project — a hand-crafted CLAUDE.md will always be better than a generated one.*
782
+ `;
783
+ },
784
+
785
+ 'hooks': () => ({
786
+ 'on-edit-lint.js': `#!/usr/bin/env node
787
+ // PostToolUse hook - runs linter after file edits
788
+ const { execSync } = require('child_process');
789
+ const fs = require('fs');
790
+ try {
791
+ if (fs.existsSync('package.json')) {
792
+ const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
793
+ if (pkg.scripts && pkg.scripts.lint) {
794
+ execSync('npm run lint --silent', { stdio: 'ignore', timeout: 30000 });
795
+ }
796
+ }
797
+ } catch (e) { /* linter not available or failed - non-blocking */ }
798
+ `,
799
+ 'protect-secrets.js': `#!/usr/bin/env node
800
+ // PreToolUse hook - blocks reads of secret files
801
+ let input = '';
802
+ process.stdin.on('data', d => input += d);
803
+ process.stdin.on('end', () => {
804
+ try {
805
+ const data = JSON.parse(input);
806
+ const fp = (data.tool_input && data.tool_input.file_path) || '';
807
+ if (/\\.env$|\\.env\\.|secrets[\\/\\\\]|credentials|\\.pem$|\\.key$/i.test(fp)) {
808
+ console.log(JSON.stringify({ decision: 'block', reason: 'Blocked: accessing secret/credential files is not allowed.' }));
809
+ } else {
810
+ console.log(JSON.stringify({ decision: 'allow' }));
811
+ }
812
+ } catch (e) {
813
+ console.log(JSON.stringify({ decision: 'allow' }));
814
+ }
815
+ });
816
+ `,
817
+ 'log-changes.js': `#!/usr/bin/env node
818
+ // PostToolUse hook - logs all file changes with timestamps
819
+ const fs = require('fs');
820
+ const path = require('path');
821
+ let input = '';
822
+ process.stdin.on('data', d => input += d);
823
+ process.stdin.on('end', () => {
824
+ try {
825
+ const data = JSON.parse(input);
826
+ const fp = (data.tool_input && data.tool_input.file_path) || '';
827
+ if (!fp) process.exit(0);
828
+ const toolName = data.tool_name || 'unknown';
829
+ const logDir = path.join('.claude', 'logs');
830
+ fs.mkdirSync(logDir, { recursive: true });
831
+ const ts = new Date().toISOString().replace('T', ' ').split('.')[0];
832
+ fs.appendFileSync(path.join(logDir, 'file-changes.log'), \`[\${ts}] \${toolName}: \${fp}\\n\`);
833
+ } catch (e) { /* non-blocking */ }
834
+ });
835
+ `,
836
+ 'session-start.js': `#!/usr/bin/env node
837
+ // SessionStart hook - prepares logs and records session entry
838
+ const fs = require('fs');
839
+ const path = require('path');
840
+ const logDir = path.join('.claude', 'logs');
841
+ fs.mkdirSync(logDir, { recursive: true });
842
+ const ts = new Date().toISOString().replace('T', ' ').split('.')[0];
843
+ fs.appendFileSync(path.join(logDir, 'sessions.log'), \`[\${ts}] session started\\n\`);
844
+ `,
845
+ }),
846
+
847
+ 'commands': (stacks) => {
848
+ const stackKeys = stacks.map(s => s.key);
849
+ const isNext = stackKeys.includes('nextjs');
850
+ const isDjango = stackKeys.includes('django');
851
+ const isFastApi = stackKeys.includes('fastapi');
852
+ const isPython = stackKeys.includes('python') || isDjango || isFastApi;
853
+ const hasDocker = stackKeys.includes('docker');
854
+
855
+ const cmds = {};
856
+
857
+ // Test command - stack-specific
858
+ if (isNext) {
859
+ cmds['test.md'] = `Run the test suite for this Next.js project.
860
+
861
+ ## Steps:
862
+ 1. Run \`npm test\` (or \`npx vitest run\`)
863
+ 2. If tests fail, check for missing mocks or async issues
864
+ 3. For component tests, ensure React Testing Library patterns are used
865
+ 4. For API route tests, check request/response handling
866
+ 5. Report: total, passed, failed, coverage if available
867
+ `;
868
+ } else if (isPython) {
869
+ cmds['test.md'] = `Run the test suite for this Python project.
870
+
871
+ ## Steps:
872
+ 1. Run \`python -m pytest -v\` (or the project's test command)
873
+ 2. Check for fixture issues, missing test database, or import errors
874
+ 3. If using Django: \`python manage.py test\`
875
+ 4. Report: total, passed, failed, and any tracebacks
876
+ `;
877
+ } else {
878
+ cmds['test.md'] = `Run the test suite and report results.
879
+
880
+ ## Steps:
881
+ 1. Run the project's test command
882
+ 2. If tests fail, analyze the failures
883
+ 3. Report: total, passed, failed, and any error details
884
+ `;
885
+ }
886
+
887
+ // Review - always generic (works well as-is)
888
+ cmds['review.md'] = `Review the current changes for quality and correctness.
889
+
890
+ ## Steps:
891
+ 1. Run \`git diff\` to see all changes
892
+ 2. Check for: bugs, security issues, missing tests, code style
893
+ 3. Provide actionable feedback
894
+ `;
895
+
896
+ cmds['security-review.md'] = `Run a focused security review using Claude Code's built-in security workflow.
897
+
898
+ ## Steps:
899
+ 1. Review auth, permissions, secrets handling, and data access paths
900
+ 2. Run \`/security-review\` for OWASP-focused analysis
901
+ 3. Check for unsafe shell commands, token leakage, and risky file access
902
+ 4. Report findings ordered by severity with concrete fixes
903
+ `;
904
+
905
+ // Deploy - stack-specific
906
+ if (isNext) {
907
+ cmds['deploy.md'] = `Pre-deployment checklist for Next.js.
908
+
909
+ ## Pre-deploy:
910
+ 1. Run \`git status\` — working tree must be clean
911
+ 2. Run \`npm run build\` — must succeed with no errors
912
+ 3. Run \`npm test\` — all tests pass
913
+ 4. Run \`npm run lint\` — no lint errors
914
+ 5. Check for \`console.log\` in production code
915
+ 6. Verify environment variables are set in deployment platform
916
+
917
+ ## Deploy:
918
+ 1. If Vercel: \`git push\` triggers auto-deploy
919
+ 2. If self-hosted: \`npm run build && npm start\`
920
+ 3. Verify: check /api/health or main page loads
921
+ 4. Tag: \`git tag -a vX.Y.Z -m "Release vX.Y.Z"\`
922
+ `;
923
+ } else if (hasDocker) {
924
+ cmds['deploy.md'] = `Pre-deployment checklist with Docker.
925
+
926
+ ## Pre-deploy:
927
+ 1. Run \`git status\` — working tree must be clean
928
+ 2. Run full test suite — all tests pass
929
+ 3. Run \`docker build -t app .\` — must succeed
930
+ 4. Run \`docker run app\` locally — smoke test
931
+
932
+ ## Deploy:
933
+ 1. Build: \`docker build -t registry/app:latest .\`
934
+ 2. Push: \`docker push registry/app:latest\`
935
+ 3. Deploy to target environment
936
+ 4. Verify health endpoint responds
937
+ 5. Tag: \`git tag -a vX.Y.Z -m "Release vX.Y.Z"\`
938
+ `;
939
+ } else {
940
+ cmds['deploy.md'] = `Pre-deployment checklist.
941
+
942
+ ## Pre-deploy:
943
+ 1. Run \`git status\` — working tree must be clean
944
+ 2. Run full test suite — all tests must pass
945
+ 3. Run linter — no errors
946
+ 4. Verify no secrets in staged changes
947
+ 5. Review diff since last deploy
948
+
949
+ ## Deploy:
950
+ 1. Confirm target environment
951
+ 2. Run deployment command
952
+ 3. Verify deployment (health check)
953
+ 4. Tag: \`git tag -a vX.Y.Z -m "Release vX.Y.Z"\`
954
+ `;
955
+ }
956
+
957
+ // Fix - always generic with $ARGUMENTS
958
+ cmds['fix.md'] = `Fix the issue described: $ARGUMENTS
959
+
960
+ ## Steps:
961
+ 1. Understand the issue — read relevant code and error messages
962
+ 2. Identify the root cause (not just the symptom)
963
+ 3. Implement the minimal fix
964
+ 4. Write or update tests to cover the fix
965
+ 5. Run the full test suite to verify no regressions
966
+ 6. Summarize what was wrong and how the fix addresses it
967
+ `;
968
+
969
+ // Stack-specific bonus commands
970
+ if (isNext) {
971
+ cmds['check-build.md'] = `Run Next.js build check without deploying.
972
+
973
+ 1. Run \`npx next build\`
974
+ 2. Check for: TypeScript errors, missing pages, broken imports
975
+ 3. Verify no "Dynamic server usage" errors in static pages
976
+ 4. Report build output size and any warnings
977
+ `;
978
+ }
979
+
980
+ if (isPython && (isDjango || isFastApi)) {
981
+ cmds['migrate.md'] = `Run database migrations safely.
982
+
983
+ 1. Check current migration status${isDjango ? ': `python manage.py showmigrations`' : ''}
984
+ 2. Create new migration if schema changed${isDjango ? ': `python manage.py makemigrations`' : ''}
985
+ 3. Review the generated migration file
986
+ 4. Apply: ${isDjango ? '`python manage.py migrate`' : '`alembic upgrade head`'}
987
+ 5. Verify: check that the app starts and queries work
988
+ `;
989
+ }
990
+
991
+ return cmds;
992
+ },
993
+
994
+ 'skills': () => ({
995
+ 'fix-issue/SKILL.md': `---
996
+ name: fix-issue
997
+ description: Fix a GitHub issue by number
998
+ ---
999
+ Fix the GitHub issue: $ARGUMENTS
1000
+
1001
+ 1. Read the issue details
1002
+ 2. Search the codebase for relevant files
1003
+ 3. Implement the fix
1004
+ 4. Write tests
1005
+ 5. Create a descriptive commit
1006
+ `,
1007
+ 'release-check/SKILL.md': `---
1008
+ name: release-check
1009
+ description: Prepare a release candidate and verify publish readiness
1010
+ ---
1011
+ Prepare a release candidate for: $ARGUMENTS
1012
+
1013
+ 1. Read CHANGELOG.md and package.json version
1014
+ 2. Run the test suite and packaging checks
1015
+ 3. Verify docs, tags, and release notes are aligned
1016
+ 4. Flag anything that would make the release unsafe or misleading
1017
+ `,
1018
+ }),
1019
+
1020
+ 'rules': (stacks) => {
1021
+ const rules = {};
1022
+ const hasTS = stacks.some(s => s.key === 'typescript');
1023
+ const hasPython = stacks.some(s => s.key === 'python');
1024
+ const hasFrontend = stacks.some(s => ['react', 'vue', 'angular', 'svelte', 'nextjs'].includes(s.key));
1025
+ const hasBackend = stacks.some(s => ['go', 'python', 'django', 'fastapi', 'rust', 'java'].includes(s.key));
1026
+
1027
+ if (hasFrontend || (hasTS && !hasBackend)) {
1028
+ rules['frontend.md'] = `When editing JavaScript/TypeScript files (*.ts, *.tsx, *.js, *.jsx, *.vue):
1029
+ - Use functional components with hooks (React/Vue 3)
1030
+ - Add TypeScript interfaces for all props and function params
1031
+ - Prefer \`const\` over \`let\`; never use \`var\`
1032
+ - Use named exports over default exports
1033
+ - Handle errors explicitly — no empty catch blocks
1034
+ - Keep component files under 200 lines; extract sub-components
1035
+ `;
1036
+ }
1037
+ if (hasBackend) {
1038
+ rules['backend.md'] = `When editing backend code:
1039
+ - Handle all errors explicitly — never swallow exceptions silently
1040
+ - Validate all external input at API boundaries
1041
+ - Use dependency injection for testability
1042
+ - Keep route handlers thin — delegate to service/business logic layers
1043
+ - Log errors with sufficient context for debugging
1044
+ - Never hardcode secrets or credentials
1045
+ `;
1046
+ }
1047
+ if (hasPython) {
1048
+ rules['python.md'] = `When editing Python files (*.py):
1049
+ - Use type hints for all function signatures and return types
1050
+ - Follow PEP 8 conventions; max line length 88 (black default)
1051
+ - Use f-strings for string formatting
1052
+ - Prefer pathlib.Path over os.path
1053
+ - Use \`if __name__ == "__main__":\` guard in scripts
1054
+ - Raise specific exceptions, never bare \`except:\`
1055
+ `;
1056
+ }
1057
+ rules['tests.md'] = `When writing or editing test files:
1058
+ - Each test must have a clear, descriptive name (test_should_X_when_Y)
1059
+ - Follow Arrange-Act-Assert (AAA) pattern
1060
+ - One assertion per test when practical
1061
+ - Never skip or disable tests without a tracking issue
1062
+ - Mock external dependencies, not internal logic
1063
+ - Include both happy path and edge case tests
1064
+ `;
1065
+ rules['repository.md'] = `When changing release, packaging, or workflow files:
1066
+ - Keep package.json, CHANGELOG.md, README.md, and docs in sync
1067
+ - Prefer tagged release references over floating branch references in public docs
1068
+ - Preserve backward compatibility in CLI flags where practical
1069
+ - Any automation that writes files must document rollback expectations
1070
+ `;
1071
+ return rules;
1072
+ },
1073
+
1074
+ 'agents': () => ({
1075
+ 'security-reviewer.md': `---
1076
+ name: security-reviewer
1077
+ description: Reviews code for security vulnerabilities
1078
+ tools: [Read, Grep, Glob]
1079
+ model: sonnet
1080
+ maxTurns: 50
1081
+ ---
1082
+ Review code for security issues:
1083
+ - Injection vulnerabilities (SQL, XSS, command injection)
1084
+ - Authentication and authorization flaws
1085
+ - Secrets or credentials in code
1086
+ - Insecure data handling
1087
+ `,
1088
+ 'release-manager.md': `---
1089
+ name: release-manager
1090
+ description: Checks release readiness and packaging consistency
1091
+ tools: [Read, Grep, Glob]
1092
+ model: sonnet
1093
+ maxTurns: 50
1094
+ ---
1095
+ Review release readiness:
1096
+ - version alignment across package.json, changelog, and docs
1097
+ - publish safety and packaging scope
1098
+ - missing rollback or migration notes
1099
+ - documentation drift that would confuse adopters
1100
+ `,
1101
+ }),
1102
+
1103
+ 'mermaid': () => `\`\`\`mermaid
1104
+ graph TD
1105
+ A[Entry Point] --> B[Core Logic]
1106
+ B --> C[Data Layer]
1107
+ B --> D[API / Routes]
1108
+ C --> E[(Database)]
1109
+ D --> F[External Services]
1110
+ \`\`\`
1111
+ `,
1112
+ };
1113
+
1114
+ async function setup(options) {
1115
+ if (options.platform === 'codex') {
1116
+ return setupCodex(options);
1117
+ }
1118
+
1119
+ const ctx = new ProjectContext(options.dir);
1120
+ const stacks = ctx.detectStacks(STACKS);
1121
+ const silent = options.silent === true;
1122
+ const writtenFiles = [];
1123
+ const preservedFiles = [];
1124
+ const mcpPreflightWarnings = getMcpPackPreflight(options.mcpPacks || [])
1125
+ .filter(item => item.missingEnvVars.length > 0);
1126
+
1127
+ function log(message = '') {
1128
+ if (!silent) {
1129
+ console.log(message);
1130
+ }
1131
+ }
1132
+
1133
+ log('');
1134
+ log('\x1b[1m nerviq\x1b[0m');
1135
+ log('\x1b[2m ═══════════════════════════════════════\x1b[0m');
1136
+
1137
+ if (stacks.length > 0) {
1138
+ log(`\x1b[36m Detected: ${stacks.map(s => s.label).join(', ')}\x1b[0m`);
1139
+ }
1140
+ log('');
1141
+
1142
+ let created = 0;
1143
+ let skipped = 0;
1144
+
1145
+ let failedWithTemplates = [];
1146
+ for (const [key, technique] of Object.entries(TECHNIQUES)) {
1147
+ if (technique.passed || technique.check(ctx)) continue;
1148
+ if (!technique.template) continue;
1149
+ failedWithTemplates.push({ key, technique });
1150
+ }
1151
+
1152
+ // Filter by 'only' list if provided (interactive wizard selections)
1153
+ if (options.only && options.only.length > 0) {
1154
+ failedWithTemplates = failedWithTemplates.filter(r => options.only.includes(r.key));
1155
+ }
1156
+
1157
+ for (const { key, technique } of failedWithTemplates) {
1158
+
1159
+ const template = TEMPLATES[technique.template];
1160
+ if (!template) continue;
1161
+
1162
+ // Pass ctx as second argument — only claude-md uses it
1163
+ const result = template(stacks, ctx);
1164
+
1165
+ if (typeof result === 'string') {
1166
+ // Single file template (like CLAUDE.md)
1167
+ // Map technique keys to actual file paths
1168
+ const filePathMap = {
1169
+ 'claudeMd': 'CLAUDE.md',
1170
+ 'mermaidArchitecture': 'CLAUDE.md', // mermaid is part of CLAUDE.md, skip separate file
1171
+ };
1172
+ if (key === 'mermaidArchitecture') continue; // Mermaid is generated inside CLAUDE.md template
1173
+ const filePath = filePathMap[key] || key;
1174
+ const fullPath = path.join(options.dir, filePath);
1175
+
1176
+ if (!fs.existsSync(fullPath)) {
1177
+ fs.writeFileSync(fullPath, result, 'utf8');
1178
+ writtenFiles.push(filePath);
1179
+ log(` \x1b[32m✅\x1b[0m Created ${filePath}`);
1180
+ created++;
1181
+ } else {
1182
+ preservedFiles.push(filePath);
1183
+ log(` \x1b[2m⏭️ Skipped ${filePath} (already exists — your version is kept)\x1b[0m`);
1184
+ skipped++;
1185
+ }
1186
+ } else if (typeof result === 'object') {
1187
+ // Multiple files template (hooks, commands, etc)
1188
+ const dirMap = {
1189
+ 'hooks': '.claude/hooks',
1190
+ 'commands': '.claude/commands',
1191
+ 'skills': '.claude/skills',
1192
+ 'rules': '.claude/rules',
1193
+ 'agents': '.claude/agents',
1194
+ };
1195
+ const targetDir = dirMap[technique.template] || `.claude/${technique.template}`;
1196
+ const fullDir = path.join(options.dir, targetDir);
1197
+
1198
+ if (!fs.existsSync(fullDir)) {
1199
+ fs.mkdirSync(fullDir, { recursive: true });
1200
+ }
1201
+
1202
+ for (const [fileName, content] of Object.entries(result)) {
1203
+ const filePath = path.join(fullDir, fileName);
1204
+ const fileDir = path.dirname(filePath);
1205
+ if (!fs.existsSync(fileDir)) {
1206
+ fs.mkdirSync(fileDir, { recursive: true });
1207
+ }
1208
+ if (!fs.existsSync(filePath)) {
1209
+ fs.writeFileSync(filePath, content, 'utf8');
1210
+ writtenFiles.push(path.relative(options.dir, filePath));
1211
+ log(` \x1b[32m✅\x1b[0m Created ${path.relative(options.dir, filePath)}`);
1212
+ created++;
1213
+ } else {
1214
+ preservedFiles.push(path.relative(options.dir, filePath));
1215
+ skipped++;
1216
+ }
1217
+ }
1218
+ }
1219
+ }
1220
+
1221
+ // Auto-register hooks in settings if hooks were created but no settings exist
1222
+ const hooksDir = path.join(options.dir, '.claude/hooks');
1223
+ const settingsPath = path.join(options.dir, '.claude/settings.json');
1224
+ if (fs.existsSync(hooksDir) && !fs.existsSync(settingsPath)) {
1225
+ const hookFiles = fs.readdirSync(hooksDir).filter(f => f.endsWith('.sh') || f.endsWith('.js'));
1226
+ if (hookFiles.length > 0) {
1227
+ const settings = buildSettingsForProfile({
1228
+ profileKey: options.profile || 'safe-write',
1229
+ hookFiles,
1230
+ mcpPackKeys: options.mcpPacks || [],
1231
+ });
1232
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
1233
+ writtenFiles.push('.claude/settings.json');
1234
+ log(` \x1b[32m✅\x1b[0m Created .claude/settings.json (hooks registered)`);
1235
+ created++;
1236
+ }
1237
+ }
1238
+
1239
+ log('');
1240
+ if (created === 0 && skipped > 0) {
1241
+ log(' \x1b[32m✅\x1b[0m Your project is already well configured!');
1242
+ log(` \x1b[2m ${skipped} files already exist and were preserved.\x1b[0m`);
1243
+ log(' \x1b[2m We never overwrite your existing config — your setup is kept.\x1b[0m');
1244
+ } else if (created > 0) {
1245
+ log(` \x1b[1m${created} files created.\x1b[0m`);
1246
+ if (skipped > 0) {
1247
+ log(` \x1b[2m${skipped} existing files preserved (not overwritten).\x1b[0m`);
1248
+ }
1249
+ }
1250
+
1251
+ log('');
1252
+ if (mcpPreflightWarnings.length > 0) {
1253
+ log('\x1b[33m MCP Preflight Warnings\x1b[0m');
1254
+ for (const warning of mcpPreflightWarnings) {
1255
+ log(` - ${warning.label}: missing ${warning.missingEnvVars.join(', ')}`);
1256
+ log(' \x1b[2m Settings were generated with placeholders, but this MCP server will not start until those env vars are set.\x1b[0m');
1257
+ }
1258
+ log('');
1259
+ }
1260
+
1261
+ log(' Run \x1b[1mnpx nerviq audit\x1b[0m to check your score.');
1262
+ log('');
1263
+
1264
+ return {
1265
+ created,
1266
+ skipped,
1267
+ writtenFiles,
1268
+ preservedFiles,
1269
+ stacks,
1270
+ mcpPreflightWarnings,
1271
+ };
1272
+ }
1273
+
1274
+ module.exports = { setup, TEMPLATES };