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,192 @@
1
+ /**
2
+ * Claude Context Engineering - Initialization Module
3
+ *
4
+ * Handles initialization of context engineering for a repository.
5
+ * Includes tech stack detection, workflow discovery, and template population.
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const chalk = require('chalk');
11
+ const { configLoader, findClaudeDir } = require('./config-loader');
12
+ const { logger } = require('./logger');
13
+ const { InitializationError, FileSystemError } = require('./errors');
14
+ const { detectTechStack } = require('./detector');
15
+ const { replacePlaceholders } = require('./placeholder');
16
+
17
+ /**
18
+ * Initialize context engineering for a repository
19
+ */
20
+ async function init(options = {}) {
21
+ const {
22
+ config: configPath,
23
+ interactive = true,
24
+ resume = false,
25
+ validateOnly = false,
26
+ techStack = null,
27
+ projectName = null,
28
+ } = options;
29
+
30
+ const op = logger.startOperation('init');
31
+
32
+ try {
33
+ console.log(chalk.cyan('\n📦 Initializing Claude Context Engineering...\n'));
34
+
35
+ // Find or create .claude directory
36
+ const claudeDir = findClaudeDir();
37
+ const projectRoot = path.dirname(claudeDir);
38
+
39
+ // Check for existing initialization
40
+ const progressFile = path.join(claudeDir, 'INIT_PROGRESS.json');
41
+ let progress = null;
42
+
43
+ if (fs.existsSync(progressFile)) {
44
+ progress = JSON.parse(fs.readFileSync(progressFile, 'utf8'));
45
+
46
+ if (!resume && progress.status !== 'COMPLETED') {
47
+ console.log(chalk.yellow('⚠️ Previous initialization found. Use --resume to continue.'));
48
+ console.log(chalk.gray(` Status: ${progress.status}`));
49
+ console.log(chalk.gray(` Last phase: ${progress.current_phase}`));
50
+ return;
51
+ }
52
+ }
53
+
54
+ // Validate-only mode
55
+ if (validateOnly) {
56
+ console.log(chalk.cyan('🔍 Validating existing initialization...\n'));
57
+ return await validateInitialization(claudeDir);
58
+ }
59
+
60
+ // Resume mode
61
+ if (resume && progress) {
62
+ console.log(chalk.cyan(`🔄 Resuming from phase: ${progress.current_phase}\n`));
63
+ return await resumeInitialization(claudeDir, progress, options);
64
+ }
65
+
66
+ // Start fresh initialization
67
+ console.log(chalk.white('Phase 1: Repository Analysis'));
68
+ console.log(chalk.gray('─'.repeat(50)));
69
+
70
+ // Detect tech stack
71
+ console.log(' Detecting technology stack...');
72
+ const detected = await detectTechStack(projectRoot, { hint: techStack });
73
+
74
+ console.log(chalk.green(` ✓ Tech stack: ${detected.stack}`));
75
+ console.log(chalk.gray(` Languages: ${detected.languages.join(', ')}`));
76
+ console.log(chalk.gray(` Frameworks: ${detected.frameworks.join(', ')}`));
77
+ console.log(chalk.gray(` Files: ${detected.fileCount}`));
78
+
79
+ // Create progress file
80
+ progress = {
81
+ version: '1.0.0',
82
+ started_at: new Date().toISOString(),
83
+ last_updated: new Date().toISOString(),
84
+ status: 'IN_PROGRESS',
85
+ current_phase: 'analysis',
86
+ phases: {
87
+ analysis: { status: 'COMPLETE', duration_ms: 0 },
88
+ discovery: { status: 'PENDING' },
89
+ population: { status: 'PENDING' },
90
+ validation: { status: 'PENDING' },
91
+ finalization: { status: 'PENDING' },
92
+ },
93
+ detected: {
94
+ tech_stack: detected.stack,
95
+ languages: detected.languages,
96
+ frameworks: detected.frameworks,
97
+ file_count: detected.fileCount,
98
+ loc: detected.loc || 0,
99
+ },
100
+ project_name: projectName || detected.projectName || path.basename(projectRoot),
101
+ errors: [],
102
+ };
103
+
104
+ saveProgress(progressFile, progress);
105
+
106
+ // Phase 2: Workflow Discovery
107
+ console.log(chalk.white('\nPhase 2: Workflow Discovery'));
108
+ console.log(chalk.gray('─'.repeat(50)));
109
+ console.log(chalk.yellow(' ⚠️ Full workflow discovery requires Claude Code agent.'));
110
+ console.log(chalk.gray(' Run: @context-engineer "Initialize context engineering"'));
111
+ console.log(chalk.gray(' The agent will discover 8-15 workflows automatically.\n'));
112
+
113
+ progress.current_phase = 'discovery';
114
+ progress.phases.discovery.status = 'PENDING_AGENT';
115
+ saveProgress(progressFile, progress);
116
+
117
+ // Phase 3: Template Population (partial - placeholders only)
118
+ console.log(chalk.white('Phase 3: Template Population (Partial)'));
119
+ console.log(chalk.gray('─'.repeat(50)));
120
+
121
+ const placeholderValues = {
122
+ PROJECT_NAME: progress.project_name,
123
+ TECH_STACK: detected.stack,
124
+ DATE: new Date().toISOString().split('T')[0],
125
+ WORKFLOWS_COUNT: '{{WORKFLOWS_COUNT}}', // To be filled by agent
126
+ // Add more known values
127
+ };
128
+
129
+ const claudeMdPath = path.join(projectRoot, 'AI_CONTEXT.md');
130
+ if (fs.existsSync(claudeMdPath)) {
131
+ const result = await replacePlaceholders(claudeMdPath, placeholderValues, { dryRun: false });
132
+ console.log(chalk.green(` ✓ Replaced ${result.replaced} placeholders in AI_CONTEXT.md`));
133
+ console.log(chalk.gray(` Remaining: ${result.remaining} placeholders`));
134
+ }
135
+
136
+ progress.current_phase = 'population';
137
+ progress.phases.population.status = 'PARTIAL';
138
+ saveProgress(progressFile, progress);
139
+
140
+ // Summary
141
+ console.log(chalk.white('\n📋 Initialization Summary'));
142
+ console.log(chalk.gray('─'.repeat(50)));
143
+ console.log(chalk.green(' ✓ Repository analyzed'));
144
+ console.log(chalk.green(' ✓ Tech stack detected'));
145
+ console.log(chalk.yellow(' ⏳ Workflow discovery pending (run agent)'));
146
+ console.log(chalk.yellow(' ⏳ Template population partial'));
147
+
148
+ console.log(chalk.white('\n📌 Next Steps:'));
149
+ console.log(chalk.cyan(' 1. Run: @context-engineer "Initialize context engineering"'));
150
+ console.log(chalk.gray(' This will discover workflows and complete the setup.'));
151
+ console.log(chalk.cyan(' 2. Review generated workflow documentation'));
152
+ console.log(chalk.cyan(' 3. Run: npx claude-context validate'));
153
+
154
+ op.success();
155
+
156
+ } catch (error) {
157
+ op.fail(error);
158
+ throw error;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Save initialization progress
164
+ */
165
+ function saveProgress(filePath, progress) {
166
+ progress.last_updated = new Date().toISOString();
167
+ fs.writeFileSync(filePath, JSON.stringify(progress, null, 2));
168
+ }
169
+
170
+ /**
171
+ * Resume an interrupted initialization
172
+ */
173
+ async function resumeInitialization(claudeDir, progress, options) {
174
+ console.log(chalk.cyan(`Resuming from phase: ${progress.current_phase}`));
175
+ // Implementation would continue from the last phase
176
+ console.log(chalk.yellow('⚠️ Resume functionality requires full agent support.'));
177
+ console.log(chalk.gray(' Run: @context-engineer "resume initialization"'));
178
+ }
179
+
180
+ /**
181
+ * Validate an existing initialization
182
+ */
183
+ async function validateInitialization(claudeDir) {
184
+ const { validate } = require('./validate');
185
+ return await validate({ all: true, claudeDir });
186
+ }
187
+
188
+ module.exports = {
189
+ init,
190
+ resumeInitialization,
191
+ validateInitialization,
192
+ };
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Claude Context Engineering - Logger
3
+ *
4
+ * Structured logging with levels, file output, and operation tracking.
5
+ */
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const chalk = require('chalk');
10
+
11
+ const LOG_LEVELS = {
12
+ debug: 0,
13
+ info: 1,
14
+ warn: 2,
15
+ error: 3,
16
+ };
17
+
18
+ const LEVEL_COLORS = {
19
+ debug: chalk.gray,
20
+ info: chalk.blue,
21
+ warn: chalk.yellow,
22
+ error: chalk.red,
23
+ };
24
+
25
+ const LEVEL_ICONS = {
26
+ debug: '🔍',
27
+ info: 'ℹ️ ',
28
+ warn: '⚠️ ',
29
+ error: '❌',
30
+ };
31
+
32
+ /**
33
+ * Create a logger instance
34
+ */
35
+ function createLogger(options = {}) {
36
+ const config = {
37
+ level: options.level || 'info',
38
+ file: options.file || null,
39
+ maxSizeMb: options.maxSizeMb || 10,
40
+ console: options.console !== false,
41
+ timestamps: options.timestamps !== false,
42
+ colors: options.colors !== false,
43
+ };
44
+
45
+ // Ensure log directory exists if file logging enabled
46
+ if (config.file) {
47
+ const logDir = path.dirname(config.file);
48
+ if (!fs.existsSync(logDir)) {
49
+ fs.mkdirSync(logDir, { recursive: true });
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Check if we should log at this level
55
+ */
56
+ function shouldLog(level) {
57
+ return LOG_LEVELS[level] >= LOG_LEVELS[config.level];
58
+ }
59
+
60
+ /**
61
+ * Format a log message
62
+ */
63
+ function formatMessage(level, message, meta = {}) {
64
+ const timestamp = new Date().toISOString();
65
+ const parts = [];
66
+
67
+ if (config.timestamps) {
68
+ parts.push(`[${timestamp}]`);
69
+ }
70
+ parts.push(`[${level.toUpperCase()}]`);
71
+ parts.push(message);
72
+
73
+ if (Object.keys(meta).length > 0) {
74
+ parts.push(JSON.stringify(meta));
75
+ }
76
+
77
+ return parts.join(' ');
78
+ }
79
+
80
+ /**
81
+ * Write to console with colors
82
+ */
83
+ function writeConsole(level, message, meta) {
84
+ if (!config.console) return;
85
+
86
+ const colorFn = config.colors ? LEVEL_COLORS[level] : (s) => s;
87
+ const icon = LEVEL_ICONS[level];
88
+ const timestamp = config.timestamps
89
+ ? chalk.gray(`[${new Date().toISOString()}] `)
90
+ : '';
91
+
92
+ let output = `${timestamp}${icon} ${colorFn(message)}`;
93
+
94
+ if (Object.keys(meta).length > 0) {
95
+ output += '\n' + chalk.gray(JSON.stringify(meta, null, 2));
96
+ }
97
+
98
+ if (level === 'error') {
99
+ console.error(output);
100
+ } else {
101
+ console.log(output);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Write to file
107
+ */
108
+ function writeFile(level, message, meta) {
109
+ if (!config.file) return;
110
+
111
+ try {
112
+ const formatted = formatMessage(level, message, meta) + '\n';
113
+ fs.appendFileSync(config.file, formatted);
114
+
115
+ // Check file size and rotate if needed
116
+ const stats = fs.statSync(config.file);
117
+ const sizeMb = stats.size / (1024 * 1024);
118
+ if (sizeMb > config.maxSizeMb) {
119
+ rotateLog();
120
+ }
121
+ } catch (error) {
122
+ // Silently fail file logging
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Rotate log file
128
+ */
129
+ function rotateLog() {
130
+ if (!config.file || !fs.existsSync(config.file)) return;
131
+
132
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
133
+ const rotatedPath = config.file.replace('.log', `-${timestamp}.log`);
134
+
135
+ try {
136
+ fs.renameSync(config.file, rotatedPath);
137
+ } catch (error) {
138
+ // Silently fail rotation
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Core log function
144
+ */
145
+ function log(level, message, meta = {}) {
146
+ if (!shouldLog(level)) return;
147
+
148
+ writeConsole(level, message, meta);
149
+ writeFile(level, message, meta);
150
+ }
151
+
152
+ /**
153
+ * Start an operation and return tracking object
154
+ */
155
+ function startOperation(name) {
156
+ const operationId = generateId();
157
+ const startTime = Date.now();
158
+
159
+ log('info', `Operation started: ${name}`, { operation_id: operationId });
160
+
161
+ return {
162
+ id: operationId,
163
+
164
+ /**
165
+ * Log progress
166
+ */
167
+ progress: (message, meta = {}) => {
168
+ log('debug', `[${name}] ${message}`, { operation_id: operationId, ...meta });
169
+ },
170
+
171
+ /**
172
+ * Mark operation as successful
173
+ */
174
+ success: (message = 'completed', meta = {}) => {
175
+ const duration = Date.now() - startTime;
176
+ log('info', `Operation completed: ${name} - ${message}`, {
177
+ operation_id: operationId,
178
+ duration_ms: duration,
179
+ ...meta,
180
+ });
181
+ return { success: true, duration };
182
+ },
183
+
184
+ /**
185
+ * Mark operation as failed
186
+ */
187
+ fail: (error, meta = {}) => {
188
+ const duration = Date.now() - startTime;
189
+ const errorMessage = error instanceof Error ? error.message : error;
190
+ log('error', `Operation failed: ${name} - ${errorMessage}`, {
191
+ operation_id: operationId,
192
+ duration_ms: duration,
193
+ error: error instanceof Error ? { name: error.name, stack: error.stack } : error,
194
+ ...meta,
195
+ });
196
+ return { success: false, duration, error };
197
+ },
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Generate a short unique ID
203
+ */
204
+ function generateId() {
205
+ return Math.random().toString(36).substring(2, 10);
206
+ }
207
+
208
+ // Return logger interface
209
+ return {
210
+ debug: (message, meta) => log('debug', message, meta),
211
+ info: (message, meta) => log('info', message, meta),
212
+ warn: (message, meta) => log('warn', message, meta),
213
+ error: (message, meta) => log('error', message, meta),
214
+ startOperation,
215
+ setLevel: (level) => { config.level = level; },
216
+ getLevel: () => config.level,
217
+ };
218
+ }
219
+
220
+ // Default logger instance
221
+ const logger = createLogger({
222
+ level: process.env.CLAUDE_LOG_LEVEL || 'info',
223
+ file: process.env.CLAUDE_LOG_FILE || null,
224
+ });
225
+
226
+ module.exports = {
227
+ createLogger,
228
+ logger,
229
+ LOG_LEVELS,
230
+ };
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Claude 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 { logger } = require('./logger');
10
+
11
+ /**
12
+ * Known placeholders with their descriptions
13
+ */
14
+ const KNOWN_PLACEHOLDERS = {
15
+ // Project identity
16
+ PROJECT_NAME: { description: 'Project name', example: 'my-awesome-app' },
17
+ PROJECT_DESCRIPTION: { description: 'Brief project description', example: 'A web application for...' },
18
+ TECH_STACK: { description: 'Technologies used', example: 'Python 3.11, FastAPI, PostgreSQL' },
19
+ PRODUCTION_URL: { description: 'Production URL', example: 'https://api.example.com' },
20
+ PROJECT_STATUS: { description: 'Project status', example: 'Production' },
21
+
22
+ // URLs
23
+ API_URL: { description: 'API base URL', example: 'https://api.example.com/v1' },
24
+ REPO_URL: { description: 'Repository URL', example: 'https://github.com/user/repo' },
25
+ DEPLOYMENT_PLATFORM: { description: 'Where deployed', example: 'AWS ECS' },
26
+
27
+ // Commands
28
+ INSTALL_COMMAND: { description: 'Install dependencies command', example: 'npm install' },
29
+ DEV_START_COMMAND: { description: 'Start dev server command', example: 'npm run dev' },
30
+ TEST_COMMAND: { description: 'Run tests command', example: 'npm test' },
31
+ TEST_E2E_COMMAND: { description: 'Run E2E tests command', example: 'npm run test:e2e' },
32
+ TEST_COVERAGE_COMMAND: { description: 'Run coverage command', example: 'npm run coverage' },
33
+ MIGRATION_CREATE_COMMAND: { description: 'Create migration command', example: 'npm run db:migrate:create' },
34
+ MIGRATION_RUN_COMMAND: { description: 'Run migrations command', example: 'npm run db:migrate' },
35
+ DEPLOY_COMMAND: { description: 'Deploy command', example: 'npm run deploy' },
36
+
37
+ // Paths
38
+ MODELS_PATH: { description: 'Models directory path', example: 'src/models/' },
39
+ MIGRATIONS_PATH: { description: 'Migrations directory path', example: 'src/migrations/' },
40
+ CORE_FILES_LIST: { description: 'List of core files', example: '- src/services/\n- src/models/' },
41
+
42
+ // Patterns
43
+ CONFIG_SEARCH_PATTERN: { description: 'Config search grep pattern', example: 'grep -r "process.env" src/' },
44
+ URL_SEARCH_PATTERN: { description: 'URL search grep pattern', example: 'grep -rE "https?://" src/' },
45
+
46
+ // Architecture
47
+ ARCHITECTURE_DIAGRAM: { description: 'ASCII architecture diagram', example: '```\nClient → API → DB\n```' },
48
+ EXTERNAL_INTEGRATIONS_LIST: { description: 'List of external integrations', example: '- Stripe: payments\n- SendGrid: email' },
49
+
50
+ // Counts
51
+ WORKFLOWS_COUNT: { description: 'Number of workflows', example: '12' },
52
+ WORKFLOW_DOMAINS_COUNT: { description: 'Number of workflow domains', example: '5' },
53
+ CODE_DOMAINS_COUNT: { description: 'Number of code domains', example: '4' },
54
+ AGENTS_COUNT: { description: 'Number of agents', example: '6' },
55
+ COMMANDS_COUNT: { description: 'Number of commands', example: '5' },
56
+ INDEX_FILES_COUNT: { description: 'Number of index files', example: '25' },
57
+
58
+ // Meta
59
+ DATE: { description: 'Current date', example: '2025-12-06' },
60
+
61
+ // Quick references
62
+ DEBUGGING_QUICK_REFS: { description: 'Quick debug references', example: '[logs.md], [errors.md]' },
63
+ CRITICAL_URLS: { description: 'Critical URLs list', example: '- API: https://...\n- Admin: https://...' },
64
+ BUSINESS_CONSTANTS: { description: 'Business constants', example: '- MAX_USERS: 1000' },
65
+
66
+ // Gotchas
67
+ GOTCHA_CATEGORY_1: { description: 'First gotcha category', example: 'Authentication' },
68
+ GOTCHA_1_ITEMS: { description: 'First gotcha items', example: '- Token expiry: 24h' },
69
+ GOTCHA_CATEGORY_2: { description: 'Second gotcha category', example: 'Database' },
70
+ GOTCHA_2_ITEMS: { description: 'Second gotcha items', example: '- Connection pooling required' },
71
+
72
+ // Agent/command routing
73
+ AGENT_ROUTING_TABLE: { description: 'Agent routing reference', example: '| Task | Agent |\n|---|---|' },
74
+ COMMAND_LIST: { description: 'Command list', example: '/rpi-research, /rpi-plan' },
75
+
76
+ // Tasks
77
+ EXAMPLE_REFACTOR_TASK: { description: 'Example refactor task', example: 'Refactor authentication flow' },
78
+ EXAMPLE_LOWLEVEL_TASK: { description: 'Example low-level task', example: 'Fix hardcoded API URL' },
79
+ EXAMPLE_FEATURE_TASK: { description: 'Example feature task', example: 'Add user profile page' },
80
+
81
+ // Production
82
+ PRODUCTION_PLATFORM: { description: 'Production platform', example: 'AWS' },
83
+ PRODUCTION_SERVICES: { description: 'Production services', example: 'ECS, RDS, ElastiCache' },
84
+ MONITORING_COMMANDS: { description: 'Monitoring commands', example: 'kubectl logs, aws logs' },
85
+
86
+ // Constraints
87
+ MIGRATION_CONSTRAINTS: { description: 'Migration constraints', example: 'Always backup first' },
88
+ TESTING_CONSTRAINTS: { description: 'Testing constraints', example: 'Must pass CI before merge' },
89
+ SECURITY_CONSTRAINTS: { description: 'Security constraints', example: 'No secrets in code' },
90
+
91
+ // Contact
92
+ CONTACT_INFO: { description: 'Contact information', example: 'team@example.com' },
93
+ };
94
+
95
+ /**
96
+ * Replace placeholders in a file
97
+ */
98
+ async function replacePlaceholders(filePath, values, options = {}) {
99
+ const { dryRun = false, backup = true } = options;
100
+
101
+ const result = {
102
+ file: filePath,
103
+ replaced: 0,
104
+ remaining: 0,
105
+ replacements: [],
106
+ };
107
+
108
+ if (!fs.existsSync(filePath)) {
109
+ throw new Error(`File not found: ${filePath}`);
110
+ }
111
+
112
+ let content = fs.readFileSync(filePath, 'utf8');
113
+ const placeholderPattern = /\{\{([A-Z_]+)\}\}/g;
114
+
115
+ // Find all placeholders
116
+ const found = new Set();
117
+ let match;
118
+ while ((match = placeholderPattern.exec(content)) !== null) {
119
+ found.add(match[1]);
120
+ }
121
+
122
+ // Replace placeholders with provided values
123
+ for (const placeholder of found) {
124
+ const value = values[placeholder];
125
+
126
+ if (value !== undefined && value !== `{{${placeholder}}}`) {
127
+ const pattern = new RegExp(`\\{\\{${placeholder}\\}\\}`, 'g');
128
+ const before = content;
129
+ content = content.replace(pattern, value);
130
+
131
+ if (content !== before) {
132
+ result.replaced++;
133
+ result.replacements.push({
134
+ placeholder,
135
+ value: value.substring(0, 50) + (value.length > 50 ? '...' : ''),
136
+ });
137
+ }
138
+ } else {
139
+ result.remaining++;
140
+ }
141
+ }
142
+
143
+ // Write changes
144
+ if (!dryRun && result.replaced > 0) {
145
+ if (backup) {
146
+ const backupPath = filePath + '.bak';
147
+ fs.copyFileSync(filePath, backupPath);
148
+ }
149
+ fs.writeFileSync(filePath, content, 'utf8');
150
+ }
151
+
152
+ return result;
153
+ }
154
+
155
+ /**
156
+ * Find all placeholders in a file
157
+ */
158
+ function findPlaceholders(filePath) {
159
+ const content = fs.readFileSync(filePath, 'utf8');
160
+ const placeholderPattern = /\{\{([A-Z_]+)\}\}/g;
161
+
162
+ const found = [];
163
+ let match;
164
+
165
+ while ((match = placeholderPattern.exec(content)) !== null) {
166
+ found.push({
167
+ placeholder: match[0],
168
+ name: match[1],
169
+ index: match.index,
170
+ known: KNOWN_PLACEHOLDERS.hasOwnProperty(match[1]),
171
+ });
172
+ }
173
+
174
+ return found;
175
+ }
176
+
177
+ /**
178
+ * Get placeholder information
179
+ */
180
+ function getPlaceholderInfo(name) {
181
+ return KNOWN_PLACEHOLDERS[name] || null;
182
+ }
183
+
184
+ /**
185
+ * List all known placeholders
186
+ */
187
+ function listKnownPlaceholders() {
188
+ return Object.entries(KNOWN_PLACEHOLDERS).map(([name, info]) => ({
189
+ name,
190
+ placeholder: `{{${name}}}`,
191
+ ...info,
192
+ }));
193
+ }
194
+
195
+ module.exports = {
196
+ replacePlaceholders,
197
+ findPlaceholders,
198
+ getPlaceholderInfo,
199
+ listKnownPlaceholders,
200
+ KNOWN_PLACEHOLDERS,
201
+ };