create-universal-ai-context 2.0.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 (136) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -0
  3. package/bin/create-ai-context.js +337 -0
  4. package/lib/adapters/antigravity.js +160 -0
  5. package/lib/adapters/claude.js +122 -0
  6. package/lib/adapters/cline.js +111 -0
  7. package/lib/adapters/copilot.js +117 -0
  8. package/lib/adapters/index.js +69 -0
  9. package/lib/ai-context-generator.js +234 -0
  10. package/lib/ai-orchestrator.js +431 -0
  11. package/lib/call-tracer.js +444 -0
  12. package/lib/detector.js +726 -0
  13. package/lib/environment-detector.js +239 -0
  14. package/lib/index.js +310 -0
  15. package/lib/installer.js +418 -0
  16. package/lib/migrate.js +319 -0
  17. package/lib/placeholder.js +541 -0
  18. package/lib/prompts.js +287 -0
  19. package/lib/spinner.js +60 -0
  20. package/lib/static-analyzer.js +729 -0
  21. package/lib/template-populator.js +843 -0
  22. package/lib/template-renderer.js +382 -0
  23. package/lib/validate.js +155 -0
  24. package/package.json +70 -0
  25. package/templates/AI_CONTEXT.md.template +245 -0
  26. package/templates/base/README.md +257 -0
  27. package/templates/base/RPI_WORKFLOW_PLAN.md +320 -0
  28. package/templates/base/agents/api-developer.md +76 -0
  29. package/templates/base/agents/context-engineer.md +525 -0
  30. package/templates/base/agents/core-architect.md +76 -0
  31. package/templates/base/agents/database-ops.md +76 -0
  32. package/templates/base/agents/deployment-ops.md +76 -0
  33. package/templates/base/agents/integration-hub.md +76 -0
  34. package/templates/base/analytics/README.md +114 -0
  35. package/templates/base/automation/config.json +58 -0
  36. package/templates/base/automation/generators/code-mapper.js +308 -0
  37. package/templates/base/automation/generators/index-builder.js +321 -0
  38. package/templates/base/automation/hooks/post-commit.sh +83 -0
  39. package/templates/base/automation/hooks/pre-commit.sh +103 -0
  40. package/templates/base/ci-templates/README.md +108 -0
  41. package/templates/base/ci-templates/github-actions/context-check.yml +144 -0
  42. package/templates/base/ci-templates/github-actions/validate-docs.yml +105 -0
  43. package/templates/base/commands/analytics.md +238 -0
  44. package/templates/base/commands/auto-sync.md +172 -0
  45. package/templates/base/commands/collab.md +194 -0
  46. package/templates/base/commands/help.md +450 -0
  47. package/templates/base/commands/rpi-implement.md +115 -0
  48. package/templates/base/commands/rpi-plan.md +93 -0
  49. package/templates/base/commands/rpi-research.md +88 -0
  50. package/templates/base/commands/session-resume.md +144 -0
  51. package/templates/base/commands/session-save.md +112 -0
  52. package/templates/base/commands/validate-all.md +77 -0
  53. package/templates/base/commands/verify-docs-current.md +86 -0
  54. package/templates/base/config/base.json +57 -0
  55. package/templates/base/config/environments/development.json +13 -0
  56. package/templates/base/config/environments/production.json +17 -0
  57. package/templates/base/config/environments/staging.json +13 -0
  58. package/templates/base/config/local.json.example +21 -0
  59. package/templates/base/context/.meta/generated-at.json +18 -0
  60. package/templates/base/context/ARCHITECTURE_SNAPSHOT.md +156 -0
  61. package/templates/base/context/CODE_TO_WORKFLOW_MAP.md +94 -0
  62. package/templates/base/context/FILE_OWNERSHIP.md +57 -0
  63. package/templates/base/context/INTEGRATION_POINTS.md +92 -0
  64. package/templates/base/context/KNOWN_GOTCHAS.md +195 -0
  65. package/templates/base/context/TESTING_MAP.md +95 -0
  66. package/templates/base/context/WORKFLOW_INDEX.md +129 -0
  67. package/templates/base/context/workflows/WORKFLOW_TEMPLATE.md +294 -0
  68. package/templates/base/indexes/agents/CAPABILITY_MATRIX.md +255 -0
  69. package/templates/base/indexes/agents/CATEGORY_INDEX.md +44 -0
  70. package/templates/base/indexes/code/CATEGORY_INDEX.md +38 -0
  71. package/templates/base/indexes/routing/CATEGORY_INDEX.md +39 -0
  72. package/templates/base/indexes/search/CATEGORY_INDEX.md +39 -0
  73. package/templates/base/indexes/workflows/CATEGORY_INDEX.md +38 -0
  74. package/templates/base/knowledge/README.md +98 -0
  75. package/templates/base/knowledge/sessions/README.md +88 -0
  76. package/templates/base/knowledge/sessions/TEMPLATE.md +150 -0
  77. package/templates/base/knowledge/shared/decisions/0001-adopt-context-engineering.md +144 -0
  78. package/templates/base/knowledge/shared/decisions/README.md +49 -0
  79. package/templates/base/knowledge/shared/decisions/TEMPLATE.md +123 -0
  80. package/templates/base/knowledge/shared/patterns/README.md +62 -0
  81. package/templates/base/knowledge/shared/patterns/TEMPLATE.md +120 -0
  82. package/templates/base/plans/PLAN_TEMPLATE.md +250 -0
  83. package/templates/base/plans/active/.gitkeep +0 -0
  84. package/templates/base/plans/completed/.gitkeep +0 -0
  85. package/templates/base/research/RESEARCH_TEMPLATE.md +153 -0
  86. package/templates/base/research/active/.gitkeep +0 -0
  87. package/templates/base/research/completed/.gitkeep +0 -0
  88. package/templates/base/schemas/agent.schema.json +141 -0
  89. package/templates/base/schemas/anchors.schema.json +54 -0
  90. package/templates/base/schemas/automation.schema.json +93 -0
  91. package/templates/base/schemas/command.schema.json +134 -0
  92. package/templates/base/schemas/hashes.schema.json +40 -0
  93. package/templates/base/schemas/manifest.schema.json +117 -0
  94. package/templates/base/schemas/plan.schema.json +136 -0
  95. package/templates/base/schemas/research.schema.json +115 -0
  96. package/templates/base/schemas/roles.schema.json +34 -0
  97. package/templates/base/schemas/session.schema.json +77 -0
  98. package/templates/base/schemas/settings.schema.json +244 -0
  99. package/templates/base/schemas/staleness.schema.json +53 -0
  100. package/templates/base/schemas/team-config.schema.json +42 -0
  101. package/templates/base/schemas/workflow.schema.json +126 -0
  102. package/templates/base/session/checkpoints/.gitkeep +2 -0
  103. package/templates/base/session/current/state.json +20 -0
  104. package/templates/base/session/history/.gitkeep +2 -0
  105. package/templates/base/settings.json +3 -0
  106. package/templates/base/standards/COMPATIBILITY.md +219 -0
  107. package/templates/base/standards/EXTENSION_GUIDELINES.md +280 -0
  108. package/templates/base/standards/QUALITY_CHECKLIST.md +211 -0
  109. package/templates/base/standards/README.md +66 -0
  110. package/templates/base/sync/anchors.json +6 -0
  111. package/templates/base/sync/hashes.json +6 -0
  112. package/templates/base/sync/staleness.json +10 -0
  113. package/templates/base/team/README.md +168 -0
  114. package/templates/base/team/config.json +79 -0
  115. package/templates/base/team/roles.json +145 -0
  116. package/templates/base/tools/bin/claude-context.js +151 -0
  117. package/templates/base/tools/lib/anchor-resolver.js +276 -0
  118. package/templates/base/tools/lib/config-loader.js +363 -0
  119. package/templates/base/tools/lib/detector.js +350 -0
  120. package/templates/base/tools/lib/diagnose.js +206 -0
  121. package/templates/base/tools/lib/drift-detector.js +373 -0
  122. package/templates/base/tools/lib/errors.js +199 -0
  123. package/templates/base/tools/lib/index.js +36 -0
  124. package/templates/base/tools/lib/init.js +192 -0
  125. package/templates/base/tools/lib/logger.js +230 -0
  126. package/templates/base/tools/lib/placeholder.js +201 -0
  127. package/templates/base/tools/lib/session-manager.js +354 -0
  128. package/templates/base/tools/lib/validate.js +521 -0
  129. package/templates/base/tools/package.json +49 -0
  130. package/templates/handlebars/antigravity.hbs +337 -0
  131. package/templates/handlebars/claude.hbs +184 -0
  132. package/templates/handlebars/cline.hbs +63 -0
  133. package/templates/handlebars/copilot.hbs +131 -0
  134. package/templates/handlebars/partials/gotcha-list.hbs +11 -0
  135. package/templates/handlebars/partials/header.hbs +3 -0
  136. package/templates/handlebars/partials/workflow-summary.hbs +16 -0
@@ -0,0 +1,541 @@
1
+ /**
2
+ * AI Context Engineering - Placeholder Replacement Engine
3
+ *
4
+ * Finds and replaces {{PLACEHOLDER}} patterns in template files.
5
+ */
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { glob } = require('glob');
10
+
11
+ /**
12
+ * Context directory and file names
13
+ */
14
+ const AI_CONTEXT_DIR = '.ai-context';
15
+ const AI_CONTEXT_FILE = 'AI_CONTEXT.md';
16
+
17
+ /**
18
+ * Known placeholders with their descriptions
19
+ */
20
+ const KNOWN_PLACEHOLDERS = {
21
+ // Project identity
22
+ PROJECT_NAME: { description: 'Project name', example: 'my-awesome-app' },
23
+ PROJECT_DESCRIPTION: { description: 'Brief project description', example: 'A web application for...' },
24
+ TECH_STACK: { description: 'Technologies used', example: 'Python 3.11, FastAPI, PostgreSQL' },
25
+ PRODUCTION_URL: { description: 'Production URL', example: 'https://api.example.com' },
26
+ PROJECT_STATUS: { description: 'Project status', example: 'Production' },
27
+
28
+ // URLs
29
+ API_URL: { description: 'API base URL', example: 'https://api.example.com/v1' },
30
+ REPO_URL: { description: 'Repository URL', example: 'https://github.com/user/repo' },
31
+ DEPLOYMENT_PLATFORM: { description: 'Where deployed', example: 'AWS ECS' },
32
+
33
+ // Commands
34
+ INSTALL_COMMAND: { description: 'Install dependencies command', example: 'npm install' },
35
+ DEV_START_COMMAND: { description: 'Start dev server command', example: 'npm run dev' },
36
+ TEST_COMMAND: { description: 'Run tests command', example: 'npm test' },
37
+ TEST_E2E_COMMAND: { description: 'Run E2E tests command', example: 'npm run test:e2e' },
38
+ TEST_COVERAGE_COMMAND: { description: 'Run coverage command', example: 'npm run coverage' },
39
+ MIGRATION_CREATE_COMMAND: { description: 'Create migration command', example: 'npm run db:migrate:create' },
40
+ MIGRATION_RUN_COMMAND: { description: 'Run migrations command', example: 'npm run db:migrate' },
41
+ DEPLOY_COMMAND: { description: 'Deploy command', example: 'npm run deploy' },
42
+
43
+ // Paths
44
+ MODELS_PATH: { description: 'Models directory path', example: 'src/models/' },
45
+ MIGRATIONS_PATH: { description: 'Migrations directory path', example: 'src/migrations/' },
46
+ CORE_FILES_LIST: { description: 'List of core files', example: '- src/services/\n- src/models/' },
47
+
48
+ // Counts
49
+ WORKFLOWS_COUNT: { description: 'Number of workflows', example: '12' },
50
+ AGENTS_COUNT: { description: 'Number of agents', example: '6' },
51
+ COMMANDS_COUNT: { description: 'Number of commands', example: '8' },
52
+
53
+ // Meta
54
+ DATE: { description: 'Current date', example: '2025-01-24' },
55
+ AGENT_TABLE_ROWS: { description: 'Agent table rows', example: '| core-architect | System design |' },
56
+ };
57
+
58
+ /**
59
+ * Get default placeholder values based on config, tech stack, and analysis
60
+ */
61
+ function getDefaultValues(config = {}, techStack = {}, analysis = {}) {
62
+ const today = new Date().toISOString().split('T')[0];
63
+ const projectName = config.projectName || 'my-project';
64
+ const projectSlug = projectName.toLowerCase().replace(/[^a-z0-9]+/g, '-');
65
+
66
+ // Get LOC information from tech stack or analysis
67
+ const loc = techStack.loc || analysis.linesOfCode || { total: 0, code: 0, files: 0 };
68
+
69
+ // Get file purposes from tech stack
70
+ const filePurposes = techStack.filePurposes || {};
71
+
72
+ // Determine commands based on tech stack
73
+ let commands = {
74
+ install: 'npm install',
75
+ dev: 'npm run dev',
76
+ test: 'npm test',
77
+ testE2e: 'npm run test:e2e',
78
+ testCoverage: 'npm run test:coverage',
79
+ migrateCreate: 'npm run migration:create',
80
+ migrateRun: 'npm run migration:run',
81
+ deploy: 'npm run deploy'
82
+ };
83
+
84
+ if (techStack.commands) {
85
+ commands = { ...commands, ...techStack.commands };
86
+ } else if (techStack.languages?.includes('python')) {
87
+ commands = {
88
+ install: 'pip install -r requirements.txt',
89
+ dev: 'python main.py',
90
+ test: 'pytest',
91
+ testE2e: 'pytest tests/e2e/',
92
+ testCoverage: 'pytest --cov',
93
+ migrateCreate: 'alembic revision --autogenerate',
94
+ migrateRun: 'alembic upgrade head',
95
+ deploy: 'docker-compose up -d'
96
+ };
97
+ } else if (techStack.languages?.includes('go')) {
98
+ commands = {
99
+ install: 'go mod download',
100
+ dev: 'go run .',
101
+ test: 'go test ./...',
102
+ testE2e: 'go test ./e2e/...',
103
+ testCoverage: 'go test -cover ./...',
104
+ migrateCreate: 'migrate create -ext sql',
105
+ migrateRun: 'migrate -path migrations up',
106
+ deploy: 'docker-compose up -d'
107
+ };
108
+ } else if (techStack.languages?.includes('rust')) {
109
+ commands = {
110
+ install: 'cargo build',
111
+ dev: 'cargo run',
112
+ test: 'cargo test',
113
+ testE2e: 'cargo test --test e2e',
114
+ testCoverage: 'cargo tarpaulin',
115
+ migrateCreate: 'sqlx migrate add',
116
+ migrateRun: 'sqlx migrate run',
117
+ deploy: 'cargo build --release'
118
+ };
119
+ }
120
+
121
+ // Build core files list from analysis
122
+ let coreFilesList = '- src/\n- config/';
123
+ if (analysis.entryPoints && analysis.entryPoints.length > 0) {
124
+ const uniqueFiles = [...new Set(analysis.entryPoints.map(e => e.file))];
125
+ coreFilesList = uniqueFiles.slice(0, 10).map(f => `- \`${f}\``).join('\n');
126
+ }
127
+
128
+ // Get workflow count from analysis
129
+ const workflowCount = analysis.workflows?.length || 0;
130
+
131
+ // Detect deployment platform from project files
132
+ const deploymentPlatform = detectDeploymentPlatform(config.targetDir);
133
+
134
+ // Build models and migrations paths from file purposes
135
+ const modelsPath = buildPathFromPurpose(filePurposes, 'model', 'models/');
136
+ const migrationsPath = buildPathFromPurpose(filePurposes, 'migration', 'migrations/');
137
+
138
+ // Build external integrations list from dependencies
139
+ const externalIntegrations = buildExternalIntegrations(techStack.databases || [], analysis.dependencies || []);
140
+
141
+ // Build architecture diagram from analysis
142
+ const architectureDiagram = buildArchitectureDiagram(analysis.architecture || {}, filePurposes);
143
+
144
+ // Determine search patterns based on language
145
+ const searchPatterns = getSearchPatterns(techStack.languages || []);
146
+
147
+ // Entry point count
148
+ const entryPointCount = analysis.entryPoints?.length || techStack.entryPoints?.length || 0;
149
+
150
+ return {
151
+ // Project identity
152
+ PROJECT_NAME: projectName,
153
+ PROJECT_SLUG: projectSlug,
154
+ PROJECT_DESCRIPTION: `${projectName} application`,
155
+ TECH_STACK: techStack.summary || techStack.stack || 'Not detected',
156
+ PRODUCTION_URL: `https://${projectSlug}.example.com`,
157
+ PROJECT_STATUS: 'Development',
158
+
159
+ // URLs
160
+ API_URL: `https://api.${projectSlug}.example.com`,
161
+ REPO_URL: `https://github.com/user/${projectSlug}`,
162
+ DEPLOYMENT_PLATFORM: deploymentPlatform,
163
+
164
+ // Commands
165
+ INSTALL_COMMAND: commands.install,
166
+ DEV_START_COMMAND: commands.dev,
167
+ TEST_COMMAND: commands.test,
168
+ TEST_E2E_COMMAND: commands.testE2e,
169
+ TEST_COVERAGE_COMMAND: commands.testCoverage,
170
+ MIGRATION_CREATE_COMMAND: commands.migrateCreate,
171
+ MIGRATION_RUN_COMMAND: commands.migrateRun,
172
+ DEPLOY_COMMAND: commands.deploy,
173
+
174
+ // Paths (from analysis)
175
+ MODELS_PATH: modelsPath,
176
+ MIGRATIONS_PATH: migrationsPath,
177
+ CORE_FILES_LIST: coreFilesList,
178
+
179
+ // Counts (from analysis)
180
+ WORKFLOWS_COUNT: String(workflowCount),
181
+ WORKFLOW_DOMAINS_COUNT: String(workflowCount > 0 ? Math.min(workflowCount, 5) : 0),
182
+ CODE_DOMAINS_COUNT: String(Object.keys(filePurposes.counts || {}).length),
183
+ ENTRY_POINTS_COUNT: String(entryPointCount),
184
+ SOURCE_FILES_COUNT: String(loc.files || 0),
185
+ LINES_OF_CODE: String(loc.code || loc.total || 0),
186
+ AGENTS_COUNT: '6',
187
+ COMMANDS_COUNT: '11',
188
+ INDEX_FILES_COUNT: '15',
189
+
190
+ // Meta
191
+ DATE: today,
192
+ AGENT_TABLE_ROWS: '',
193
+ AGENT_ROUTING_TABLE: '@context-engineer for setup, @core-architect for design',
194
+ DEBUGGING_QUICK_REFS: 'KNOWN_GOTCHAS.md, logs/',
195
+
196
+ // Examples (based on detected stack)
197
+ EXAMPLE_REFACTOR_TASK: buildExampleTask('refactor', techStack),
198
+ EXAMPLE_LOWLEVEL_TASK: buildExampleTask('lowlevel', techStack),
199
+ EXAMPLE_FEATURE_TASK: buildExampleTask('feature', techStack),
200
+
201
+ // Search patterns (language-aware)
202
+ CONFIG_SEARCH_PATTERN: searchPatterns.config,
203
+ URL_SEARCH_PATTERN: searchPatterns.url,
204
+
205
+ // External integrations (from dependencies)
206
+ EXTERNAL_INTEGRATIONS_LIST: externalIntegrations,
207
+
208
+ // Architecture (from analysis)
209
+ ARCHITECTURE_DIAGRAM: architectureDiagram,
210
+
211
+ // URLs
212
+ CRITICAL_URLS: `- Production: https://${projectSlug}.example.com`,
213
+ BUSINESS_CONSTANTS: '- TBD (document key business constants)',
214
+
215
+ // Gotchas
216
+ GOTCHA_CATEGORY_1: 'Database',
217
+ GOTCHA_1_ITEMS: '- TBD (document database gotchas)',
218
+ GOTCHA_CATEGORY_2: 'API',
219
+ GOTCHA_2_ITEMS: '- TBD (document API gotchas)',
220
+
221
+ // Production
222
+ PRODUCTION_PLATFORM: deploymentPlatform,
223
+ PRODUCTION_SERVICES: buildProductionServices(techStack),
224
+ MONITORING_COMMANDS: 'Check logs, health endpoints',
225
+
226
+ // Constraints
227
+ MIGRATION_CONSTRAINTS: 'Always backup before migrations',
228
+ TESTING_CONSTRAINTS: 'Run tests before merging',
229
+ SECURITY_CONSTRAINTS: 'Never commit secrets',
230
+ CONTACT_INFO: 'TBD (add contact info)',
231
+
232
+ // Languages and frameworks (for templates)
233
+ PRIMARY_LANGUAGE: techStack.languages?.[0] || 'javascript',
234
+ PRIMARY_FRAMEWORK: techStack.frameworks?.[0] || '',
235
+ DATABASE_TYPE: techStack.databases?.[0] || '',
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Detect deployment platform from project files
241
+ */
242
+ function detectDeploymentPlatform(projectRoot) {
243
+ if (!projectRoot) return 'TBD';
244
+
245
+ const platforms = [
246
+ { file: 'vercel.json', name: 'Vercel' },
247
+ { file: 'netlify.toml', name: 'Netlify' },
248
+ { file: 'fly.toml', name: 'Fly.io' },
249
+ { file: 'render.yaml', name: 'Render' },
250
+ { file: 'railway.json', name: 'Railway' },
251
+ { file: 'Dockerfile', name: 'Docker' },
252
+ { file: 'docker-compose.yml', name: 'Docker Compose' },
253
+ { file: 'docker-compose.yaml', name: 'Docker Compose' },
254
+ { file: 'heroku.yml', name: 'Heroku' },
255
+ { file: 'Procfile', name: 'Heroku' },
256
+ { file: 'app.yaml', name: 'Google Cloud' },
257
+ { file: 'serverless.yml', name: 'Serverless' },
258
+ { file: 'terraform', name: 'Terraform' },
259
+ ];
260
+
261
+ for (const platform of platforms) {
262
+ try {
263
+ if (fs.existsSync(path.join(projectRoot, platform.file))) {
264
+ return platform.name;
265
+ }
266
+ } catch {
267
+ // Ignore errors
268
+ }
269
+ }
270
+
271
+ return 'TBD';
272
+ }
273
+
274
+ /**
275
+ * Build path from file purposes
276
+ */
277
+ function buildPathFromPurpose(filePurposes, purpose, defaultPath) {
278
+ const files = filePurposes?.files?.[purpose];
279
+ if (files && files.length > 0) {
280
+ const dir = path.dirname(files[0]);
281
+ return dir === '.' ? defaultPath : dir + '/';
282
+ }
283
+ return defaultPath;
284
+ }
285
+
286
+ /**
287
+ * Build external integrations list from dependencies
288
+ */
289
+ function buildExternalIntegrations(databases, dependencies) {
290
+ const integrations = [];
291
+
292
+ // Add databases
293
+ for (const db of databases) {
294
+ integrations.push(`- **${capitalize(db)}**: Database`);
295
+ }
296
+
297
+ // Check dependencies for known integrations
298
+ const knownIntegrations = {
299
+ stripe: 'Payment processing',
300
+ 'aws-sdk': 'AWS services',
301
+ '@aws-sdk': 'AWS services',
302
+ firebase: 'Firebase services',
303
+ twilio: 'SMS/Voice',
304
+ sendgrid: 'Email delivery',
305
+ '@sendgrid': 'Email delivery',
306
+ nodemailer: 'Email',
307
+ redis: 'Caching',
308
+ ioredis: 'Caching',
309
+ elasticsearch: 'Search',
310
+ '@elastic': 'Search',
311
+ 'socket.io': 'Real-time',
312
+ pusher: 'Real-time',
313
+ cloudinary: 'Media storage',
314
+ 's3': 'File storage',
315
+ };
316
+
317
+ for (const dep of dependencies) {
318
+ const depName = dep.name || dep;
319
+ for (const [key, desc] of Object.entries(knownIntegrations)) {
320
+ if (depName.toLowerCase().includes(key)) {
321
+ integrations.push(`- **${depName}**: ${desc}`);
322
+ break;
323
+ }
324
+ }
325
+ }
326
+
327
+ if (integrations.length === 0) {
328
+ return '*No external integrations detected. Document manually if present.*';
329
+ }
330
+
331
+ return integrations.slice(0, 10).join('\n');
332
+ }
333
+
334
+ /**
335
+ * Build architecture diagram from analysis
336
+ */
337
+ function buildArchitectureDiagram(architecture, filePurposes) {
338
+ const layers = architecture?.layers || [];
339
+ const purposeCounts = filePurposes?.counts || {};
340
+
341
+ // Build diagram based on discovered layers or file purposes
342
+ if (layers.length > 0) {
343
+ let diagram = '┌─────────────────────────────────────┐\n';
344
+ for (const layer of layers.slice(0, 4)) {
345
+ diagram += `│ [${(layer.name || 'Layer').padEnd(30)}] │\n`;
346
+ }
347
+ diagram += '└─────────────────────────────────────┘';
348
+ return diagram;
349
+ }
350
+
351
+ // Build from file purposes
352
+ const hasControllers = purposeCounts.controller > 0 || purposeCounts.route > 0;
353
+ const hasServices = purposeCounts.service > 0;
354
+ const hasModels = purposeCounts.model > 0;
355
+ const hasRepos = purposeCounts.repository > 0;
356
+
357
+ return `┌─────────────────────────────────────┐
358
+ │ [Application] │
359
+ │ │
360
+ ${hasControllers ? '│ ┌───────────┐ ┌───────────┐ │\n│ │ API │ │ Routes │ │\n│ └───────────┘ └───────────┘ │\n' : ''}${hasServices ? '│ ┌───────────────────────────┐ │\n│ │ Services │ │\n│ └───────────────────────────┘ │\n' : ''}${hasModels || hasRepos ? '│ ┌───────────┐ ┌───────────┐ │\n│ │ Models │ │ Database │ │\n│ └───────────┘ └───────────┘ │\n' : ''}└─────────────────────────────────────┘`;
361
+ }
362
+
363
+ /**
364
+ * Get search patterns based on languages
365
+ */
366
+ function getSearchPatterns(languages) {
367
+ if (languages.includes('python')) {
368
+ return {
369
+ config: 'grep -r "os.environ" --include="*.py"',
370
+ url: 'grep -rE "https?://" --include="*.py" --include="*.json"'
371
+ };
372
+ }
373
+ if (languages.includes('go')) {
374
+ return {
375
+ config: 'grep -r "os.Getenv" --include="*.go"',
376
+ url: 'grep -rE "https?://" --include="*.go" --include="*.json"'
377
+ };
378
+ }
379
+ if (languages.includes('rust')) {
380
+ return {
381
+ config: 'grep -r "env::var" --include="*.rs"',
382
+ url: 'grep -rE "https?://" --include="*.rs" --include="*.toml"'
383
+ };
384
+ }
385
+ // Default: JavaScript/TypeScript
386
+ return {
387
+ config: 'grep -r "process.env" --include="*.js" --include="*.ts"',
388
+ url: 'grep -rE "https?://" --include="*.js" --include="*.ts" --include="*.json"'
389
+ };
390
+ }
391
+
392
+ /**
393
+ * Build example task based on tech stack
394
+ */
395
+ function buildExampleTask(type, techStack) {
396
+ const framework = techStack.frameworks?.[0] || '';
397
+ const language = techStack.languages?.[0] || 'javascript';
398
+
399
+ const examples = {
400
+ refactor: {
401
+ express: 'Refactor the authentication middleware',
402
+ fastapi: 'Refactor the dependency injection system',
403
+ django: 'Refactor the view decorators',
404
+ nextjs: 'Refactor the API routes to app router',
405
+ default: 'Refactor the authentication flow'
406
+ },
407
+ lowlevel: {
408
+ express: 'Fix hardcoded timeout in request handler',
409
+ fastapi: 'Fix hardcoded API URL in config',
410
+ django: 'Fix hardcoded secret key in settings',
411
+ default: 'Fix hardcoded API URL in config'
412
+ },
413
+ feature: {
414
+ express: 'Add rate limiting middleware',
415
+ fastapi: 'Add WebSocket support for real-time updates',
416
+ django: 'Add user notifications feature',
417
+ nextjs: 'Add server-side caching',
418
+ default: 'Add user notifications feature'
419
+ }
420
+ };
421
+
422
+ return examples[type][framework] || examples[type].default;
423
+ }
424
+
425
+ /**
426
+ * Build production services list
427
+ */
428
+ function buildProductionServices(techStack) {
429
+ const services = ['Web'];
430
+
431
+ if (techStack.frameworks?.some(f => ['express', 'fastapi', 'django', 'rails'].includes(f))) {
432
+ services.push('API');
433
+ }
434
+
435
+ if (techStack.databases?.length > 0) {
436
+ services.push('Database');
437
+ }
438
+
439
+ if (techStack.databases?.includes('redis')) {
440
+ services.push('Cache');
441
+ }
442
+
443
+ return services.join(', ');
444
+ }
445
+
446
+ /**
447
+ * Capitalize first letter
448
+ */
449
+ function capitalize(str) {
450
+ return str.charAt(0).toUpperCase() + str.slice(1);
451
+ }
452
+
453
+ /**
454
+ * Replace placeholders in all files in a directory
455
+ */
456
+ async function replacePlaceholders(targetDir, config = {}) {
457
+ const contextDir = path.join(targetDir, AI_CONTEXT_DIR);
458
+ const values = getDefaultValues(config, config.techStack || {}, config.analysis || {});
459
+
460
+ // Find all markdown and JSON files
461
+ const files = await glob('**/*.{md,json}', {
462
+ cwd: contextDir,
463
+ ignore: ['node_modules/**', '.git/**'],
464
+ nodir: true,
465
+ absolute: true
466
+ });
467
+
468
+ let totalReplaced = 0;
469
+
470
+ for (const filePath of files) {
471
+ try {
472
+ let content = fs.readFileSync(filePath, 'utf8');
473
+ const originalContent = content;
474
+
475
+ // Replace all placeholders
476
+ for (const [key, value] of Object.entries(values)) {
477
+ const pattern = new RegExp(`\\{\\{${key}\\}\\}`, 'g');
478
+ content = content.replace(pattern, String(value));
479
+ }
480
+
481
+ if (content !== originalContent) {
482
+ fs.writeFileSync(filePath, content, 'utf8');
483
+ totalReplaced++;
484
+ }
485
+ } catch (error) {
486
+ // Skip files that can't be read
487
+ }
488
+ }
489
+
490
+ // Also replace in AI_CONTEXT.md at root
491
+ const aiContextPath = path.join(targetDir, AI_CONTEXT_FILE);
492
+ if (fs.existsSync(aiContextPath)) {
493
+ try {
494
+ let content = fs.readFileSync(aiContextPath, 'utf8');
495
+ const originalContent = content;
496
+
497
+ for (const [key, value] of Object.entries(values)) {
498
+ const pattern = new RegExp(`\\{\\{${key}\\}\\}`, 'g');
499
+ content = content.replace(pattern, String(value));
500
+ }
501
+
502
+ if (content !== originalContent) {
503
+ fs.writeFileSync(aiContextPath, content, 'utf8');
504
+ totalReplaced++;
505
+ }
506
+ } catch (error) {
507
+ // Skip if can't read
508
+ }
509
+ }
510
+
511
+ return totalReplaced;
512
+ }
513
+
514
+ /**
515
+ * Find all placeholders in a file
516
+ */
517
+ function findPlaceholders(filePath) {
518
+ const content = fs.readFileSync(filePath, 'utf8');
519
+ const placeholderPattern = /\{\{([A-Z_]+)\}\}/g;
520
+
521
+ const found = [];
522
+ let match;
523
+
524
+ while ((match = placeholderPattern.exec(content)) !== null) {
525
+ found.push({
526
+ placeholder: match[0],
527
+ name: match[1],
528
+ index: match.index,
529
+ known: KNOWN_PLACEHOLDERS.hasOwnProperty(match[1]),
530
+ });
531
+ }
532
+
533
+ return found;
534
+ }
535
+
536
+ module.exports = {
537
+ replacePlaceholders,
538
+ findPlaceholders,
539
+ getDefaultValues,
540
+ KNOWN_PLACEHOLDERS,
541
+ };