clavix 2.3.1 → 2.4.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 (187) hide show
  1. package/README.md +0 -116
  2. package/bin/clavix.js +7 -0
  3. package/dist/cli/commands/implement.js +25 -33
  4. package/dist/cli/commands/plan.js +22 -27
  5. package/dist/cli/commands/prd.js +7 -12
  6. package/dist/cli/commands/start.js +4 -9
  7. package/dist/cli/commands/summarize.js +15 -22
  8. package/dist/core 2/adapters/agents-md-generator.d.ts +26 -0
  9. package/dist/core 2/adapters/agents-md-generator.js +102 -0
  10. package/dist/core 2/adapters/amp-adapter.d.ts +27 -0
  11. package/dist/core 2/adapters/amp-adapter.js +42 -0
  12. package/dist/core 2/adapters/augment-adapter.d.ts +22 -0
  13. package/dist/core 2/adapters/augment-adapter.js +77 -0
  14. package/dist/core 2/adapters/base-adapter.d.ts +45 -0
  15. package/dist/core 2/adapters/base-adapter.js +142 -0
  16. package/dist/core 2/adapters/claude-code-adapter.d.ts +32 -0
  17. package/dist/core 2/adapters/claude-code-adapter.js +116 -0
  18. package/dist/core 2/adapters/cline-adapter.d.ts +34 -0
  19. package/dist/core 2/adapters/cline-adapter.js +52 -0
  20. package/dist/core 2/adapters/codebuddy-adapter.d.ts +24 -0
  21. package/dist/core 2/adapters/codebuddy-adapter.js +82 -0
  22. package/dist/core 2/adapters/codex-adapter.d.ts +24 -0
  23. package/dist/core 2/adapters/codex-adapter.js +79 -0
  24. package/dist/core 2/adapters/copilot-instructions-generator.d.ts +26 -0
  25. package/dist/core 2/adapters/copilot-instructions-generator.js +104 -0
  26. package/dist/core 2/adapters/crush-adapter.d.ts +35 -0
  27. package/dist/core 2/adapters/crush-adapter.js +49 -0
  28. package/dist/core 2/adapters/cursor-adapter.d.ts +25 -0
  29. package/dist/core 2/adapters/cursor-adapter.js +40 -0
  30. package/dist/core 2/adapters/droid-adapter.d.ts +33 -0
  31. package/dist/core 2/adapters/droid-adapter.js +57 -0
  32. package/dist/core 2/adapters/gemini-adapter.d.ts +27 -0
  33. package/dist/core 2/adapters/gemini-adapter.js +90 -0
  34. package/dist/core 2/adapters/kilocode-adapter.d.ts +34 -0
  35. package/dist/core 2/adapters/kilocode-adapter.js +49 -0
  36. package/dist/core 2/adapters/octo-md-generator.d.ts +26 -0
  37. package/dist/core 2/adapters/octo-md-generator.js +102 -0
  38. package/dist/core 2/adapters/opencode-adapter.d.ts +33 -0
  39. package/dist/core 2/adapters/opencode-adapter.js +56 -0
  40. package/dist/core 2/adapters/qwen-adapter.d.ts +27 -0
  41. package/dist/core 2/adapters/qwen-adapter.js +90 -0
  42. package/dist/core 2/adapters/roocode-adapter.d.ts +40 -0
  43. package/dist/core 2/adapters/roocode-adapter.js +68 -0
  44. package/dist/core 2/adapters/warp-md-generator.d.ts +17 -0
  45. package/dist/core 2/adapters/warp-md-generator.js +88 -0
  46. package/dist/core 2/adapters/windsurf-adapter.d.ts +34 -0
  47. package/dist/core 2/adapters/windsurf-adapter.js +49 -0
  48. package/dist/core 2/agent-manager.d.ts +51 -0
  49. package/dist/core 2/agent-manager.js +126 -0
  50. package/dist/core 2/archive-manager.d.ts +100 -0
  51. package/dist/core 2/archive-manager.js +338 -0
  52. package/dist/core 2/conversation-analyzer.d.ts +86 -0
  53. package/dist/core 2/doc-injector.d.ts +51 -0
  54. package/dist/core 2/doc-injector.js +236 -0
  55. package/dist/core 2/git-manager.d.ts +100 -0
  56. package/dist/core 2/git-manager.js +214 -0
  57. package/dist/core 2/prompt-optimizer.d.ts +268 -0
  58. package/dist/core 2/prompt-optimizer.js +963 -0
  59. package/dist/core 2/question-engine.d.ts +167 -0
  60. package/dist/core 2/question-engine.js +395 -0
  61. package/dist/core 2/session-manager.d.ts +139 -0
  62. package/dist/core 2/session-manager.js +403 -0
  63. package/dist/core 2/task-manager.d.ts +155 -0
  64. package/dist/core 2/task-manager.js +689 -0
  65. package/dist/index.js +6 -0
  66. package/dist/utils/template-loader.js +24 -22
  67. package/package.json +1 -1
  68. package/dist/templates/slash-commands/augment/archive.md +0 -291
  69. package/dist/templates/slash-commands/augment/deep.md +0 -207
  70. package/dist/templates/slash-commands/augment/fast.md +0 -183
  71. package/dist/templates/slash-commands/augment/implement.md +0 -267
  72. package/dist/templates/slash-commands/augment/plan.md +0 -173
  73. package/dist/templates/slash-commands/augment/prd.md +0 -178
  74. package/dist/templates/slash-commands/augment/start.md +0 -142
  75. package/dist/templates/slash-commands/augment/summarize.md +0 -179
  76. package/dist/templates/slash-commands/claude-code/archive.md +0 -291
  77. package/dist/templates/slash-commands/claude-code/deep.md +0 -207
  78. package/dist/templates/slash-commands/claude-code/fast.md +0 -183
  79. package/dist/templates/slash-commands/claude-code/implement.md +0 -267
  80. package/dist/templates/slash-commands/claude-code/plan.md +0 -173
  81. package/dist/templates/slash-commands/claude-code/prd.md +0 -178
  82. package/dist/templates/slash-commands/claude-code/start.md +0 -142
  83. package/dist/templates/slash-commands/claude-code/summarize.md +0 -179
  84. package/dist/templates/slash-commands/cline/archive.md +0 -291
  85. package/dist/templates/slash-commands/cline/deep.md +0 -207
  86. package/dist/templates/slash-commands/cline/fast.md +0 -183
  87. package/dist/templates/slash-commands/cline/implement.md +0 -267
  88. package/dist/templates/slash-commands/cline/plan.md +0 -173
  89. package/dist/templates/slash-commands/cline/prd.md +0 -178
  90. package/dist/templates/slash-commands/cline/start.md +0 -142
  91. package/dist/templates/slash-commands/cline/summarize.md +0 -179
  92. package/dist/templates/slash-commands/codebuddy/archive.md +0 -291
  93. package/dist/templates/slash-commands/codebuddy/deep.md +0 -207
  94. package/dist/templates/slash-commands/codebuddy/fast.md +0 -183
  95. package/dist/templates/slash-commands/codebuddy/implement.md +0 -267
  96. package/dist/templates/slash-commands/codebuddy/plan.md +0 -173
  97. package/dist/templates/slash-commands/codebuddy/prd.md +0 -178
  98. package/dist/templates/slash-commands/codebuddy/start.md +0 -142
  99. package/dist/templates/slash-commands/codebuddy/summarize.md +0 -179
  100. package/dist/templates/slash-commands/codex/archive.md +0 -291
  101. package/dist/templates/slash-commands/codex/deep.md +0 -207
  102. package/dist/templates/slash-commands/codex/fast.md +0 -183
  103. package/dist/templates/slash-commands/codex/implement.md +0 -267
  104. package/dist/templates/slash-commands/codex/plan.md +0 -173
  105. package/dist/templates/slash-commands/codex/prd.md +0 -178
  106. package/dist/templates/slash-commands/codex/start.md +0 -142
  107. package/dist/templates/slash-commands/codex/summarize.md +0 -179
  108. package/dist/templates/slash-commands/crush/archive.md +0 -291
  109. package/dist/templates/slash-commands/crush/deep.md +0 -207
  110. package/dist/templates/slash-commands/crush/fast.md +0 -183
  111. package/dist/templates/slash-commands/crush/implement.md +0 -267
  112. package/dist/templates/slash-commands/crush/plan.md +0 -173
  113. package/dist/templates/slash-commands/crush/prd.md +0 -178
  114. package/dist/templates/slash-commands/crush/start.md +0 -142
  115. package/dist/templates/slash-commands/crush/summarize.md +0 -179
  116. package/dist/templates/slash-commands/cursor/archive.md +0 -291
  117. package/dist/templates/slash-commands/cursor/deep.md +0 -207
  118. package/dist/templates/slash-commands/cursor/fast.md +0 -183
  119. package/dist/templates/slash-commands/cursor/implement.md +0 -267
  120. package/dist/templates/slash-commands/cursor/plan.md +0 -173
  121. package/dist/templates/slash-commands/cursor/prd.md +0 -178
  122. package/dist/templates/slash-commands/cursor/start.md +0 -142
  123. package/dist/templates/slash-commands/cursor/summarize.md +0 -179
  124. package/dist/templates/slash-commands/droid/archive.md +0 -291
  125. package/dist/templates/slash-commands/droid/deep.md +0 -207
  126. package/dist/templates/slash-commands/droid/fast.md +0 -183
  127. package/dist/templates/slash-commands/droid/implement.md +0 -267
  128. package/dist/templates/slash-commands/droid/plan.md +0 -173
  129. package/dist/templates/slash-commands/droid/prd.md +0 -178
  130. package/dist/templates/slash-commands/droid/start.md +0 -142
  131. package/dist/templates/slash-commands/droid/summarize.md +0 -179
  132. package/dist/templates/slash-commands/gemini/archive.toml +0 -290
  133. package/dist/templates/slash-commands/gemini/deep.toml +0 -206
  134. package/dist/templates/slash-commands/gemini/fast.toml +0 -182
  135. package/dist/templates/slash-commands/gemini/implement.toml +0 -266
  136. package/dist/templates/slash-commands/gemini/plan.toml +0 -170
  137. package/dist/templates/slash-commands/gemini/prd.toml +0 -177
  138. package/dist/templates/slash-commands/gemini/start.toml +0 -141
  139. package/dist/templates/slash-commands/gemini/summarize.toml +0 -178
  140. package/dist/templates/slash-commands/kilocode/archive.md +0 -291
  141. package/dist/templates/slash-commands/kilocode/deep.md +0 -207
  142. package/dist/templates/slash-commands/kilocode/fast.md +0 -183
  143. package/dist/templates/slash-commands/kilocode/implement.md +0 -267
  144. package/dist/templates/slash-commands/kilocode/plan.md +0 -173
  145. package/dist/templates/slash-commands/kilocode/prd.md +0 -178
  146. package/dist/templates/slash-commands/kilocode/start.md +0 -142
  147. package/dist/templates/slash-commands/kilocode/summarize.md +0 -179
  148. package/dist/templates/slash-commands/opencode/archive.md +0 -291
  149. package/dist/templates/slash-commands/opencode/deep.md +0 -207
  150. package/dist/templates/slash-commands/opencode/fast.md +0 -183
  151. package/dist/templates/slash-commands/opencode/implement.md +0 -267
  152. package/dist/templates/slash-commands/opencode/plan.md +0 -173
  153. package/dist/templates/slash-commands/opencode/prd.md +0 -178
  154. package/dist/templates/slash-commands/opencode/start.md +0 -142
  155. package/dist/templates/slash-commands/opencode/summarize.md +0 -179
  156. package/dist/templates/slash-commands/qwen/archive.toml +0 -290
  157. package/dist/templates/slash-commands/qwen/deep.toml +0 -206
  158. package/dist/templates/slash-commands/qwen/fast.toml +0 -182
  159. package/dist/templates/slash-commands/qwen/implement.toml +0 -266
  160. package/dist/templates/slash-commands/qwen/plan.toml +0 -170
  161. package/dist/templates/slash-commands/qwen/prd.toml +0 -177
  162. package/dist/templates/slash-commands/qwen/start.toml +0 -141
  163. package/dist/templates/slash-commands/qwen/summarize.toml +0 -178
  164. package/dist/templates/slash-commands/roocode/archive.md +0 -291
  165. package/dist/templates/slash-commands/roocode/deep.md +0 -207
  166. package/dist/templates/slash-commands/roocode/fast.md +0 -183
  167. package/dist/templates/slash-commands/roocode/implement.md +0 -267
  168. package/dist/templates/slash-commands/roocode/plan.md +0 -173
  169. package/dist/templates/slash-commands/roocode/prd.md +0 -178
  170. package/dist/templates/slash-commands/roocode/start.md +0 -142
  171. package/dist/templates/slash-commands/roocode/summarize.md +0 -179
  172. package/dist/templates/slash-commands/windsurf/archive.md +0 -291
  173. package/dist/templates/slash-commands/windsurf/deep.md +0 -207
  174. package/dist/templates/slash-commands/windsurf/fast.md +0 -183
  175. package/dist/templates/slash-commands/windsurf/implement.md +0 -267
  176. package/dist/templates/slash-commands/windsurf/plan.md +0 -173
  177. package/dist/templates/slash-commands/windsurf/prd.md +0 -178
  178. package/dist/templates/slash-commands/windsurf/start.md +0 -142
  179. package/dist/templates/slash-commands/windsurf/summarize.md +0 -179
  180. /package/dist/templates/slash-commands/{amp → _canonical}/archive.md +0 -0
  181. /package/dist/templates/slash-commands/{amp → _canonical}/deep.md +0 -0
  182. /package/dist/templates/slash-commands/{amp → _canonical}/fast.md +0 -0
  183. /package/dist/templates/slash-commands/{amp → _canonical}/implement.md +0 -0
  184. /package/dist/templates/slash-commands/{amp → _canonical}/plan.md +0 -0
  185. /package/dist/templates/slash-commands/{amp → _canonical}/prd.md +0 -0
  186. /package/dist/templates/slash-commands/{amp → _canonical}/start.md +0 -0
  187. /package/dist/templates/slash-commands/{amp → _canonical}/summarize.md +0 -0
@@ -0,0 +1,963 @@
1
+ "use strict";
2
+ /**
3
+ * PromptOptimizer - Analyzes and improves prompts using the CLEAR Framework
4
+ * CLEAR Framework: Concise, Logical, Explicit, Adaptive, Reflective
5
+ * Developed by Dr. Leo Lo, University of New Mexico
6
+ * Reference: https://guides.library.tamucc.edu/prompt-engineering/clear
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.PromptOptimizer = void 0;
10
+ class PromptOptimizer {
11
+ /**
12
+ * Analyze a prompt and identify issues
13
+ */
14
+ analyze(prompt) {
15
+ return {
16
+ gaps: this.findGaps(prompt),
17
+ ambiguities: this.findAmbiguities(prompt),
18
+ strengths: this.findStrengths(prompt),
19
+ suggestions: this.generateSuggestions(prompt),
20
+ };
21
+ }
22
+ /**
23
+ * Perform smart triage to determine if deep analysis is recommended
24
+ */
25
+ performTriage(prompt) {
26
+ const reasons = [];
27
+ // Check 1: Short prompts (< 20 characters)
28
+ if (prompt.trim().length < 20) {
29
+ reasons.push('Prompt is very short (< 20 characters)');
30
+ }
31
+ // Check 2: Missing critical elements
32
+ const criticalElements = this.countMissingCriticalElements(prompt);
33
+ if (criticalElements >= 3) {
34
+ reasons.push(`Missing ${criticalElements} critical elements (context, tech stack, success criteria, user needs, expected output)`);
35
+ }
36
+ // Check 3: Vague scope words without context
37
+ if (this.hasVagueScopeWithoutContext(prompt)) {
38
+ reasons.push('Contains vague scope words ("app", "system", "project") without sufficient context');
39
+ }
40
+ return {
41
+ needsDeepAnalysis: reasons.length > 0,
42
+ reasons,
43
+ };
44
+ }
45
+ /**
46
+ * Assess prompt quality
47
+ */
48
+ assessQuality(prompt) {
49
+ const criteria = {
50
+ clearGoal: this.hasClearGoal(prompt),
51
+ sufficientContext: this.hasContext(prompt),
52
+ actionableLanguage: this.hasActionableLanguage(prompt),
53
+ reasonableScope: this.hasReasonableScope(prompt),
54
+ };
55
+ const metCount = Object.values(criteria).filter(Boolean).length;
56
+ const total = Object.keys(criteria).length;
57
+ return {
58
+ isAlreadyGood: metCount >= 3,
59
+ criteriaMetCount: metCount,
60
+ totalCriteria: total,
61
+ criteriaResults: criteria,
62
+ };
63
+ }
64
+ /**
65
+ * Generate an improved version of the prompt
66
+ */
67
+ improve(prompt, mode = 'fast') {
68
+ const analysis = this.analyze(prompt);
69
+ const improved = this.generateImprovedPrompt(prompt, analysis);
70
+ const changesSummary = this.generateChangesSummary(prompt, improved);
71
+ const triageResult = mode === 'fast' ? this.performTriage(prompt) : undefined;
72
+ const qualityAssessment = this.assessQuality(prompt);
73
+ const result = {
74
+ original: prompt,
75
+ analysis,
76
+ improved,
77
+ changesSummary,
78
+ triageResult,
79
+ qualityAssessment,
80
+ };
81
+ // Add deep mode features
82
+ if (mode === 'deep') {
83
+ result.alternativePhrasings = this.generateAlternativePhrasings(prompt);
84
+ result.edgeCases = this.identifyEdgeCases(prompt);
85
+ result.implementationExamples = this.generateImplementationExamples(prompt);
86
+ result.alternativeStructures = this.suggestAlternativeStructures(prompt);
87
+ result.potentialIssues = this.identifyPotentialIssues(prompt);
88
+ }
89
+ return result;
90
+ }
91
+ /**
92
+ * Apply CLEAR Framework analysis to a prompt
93
+ * C = Concise, L = Logical, E = Explicit, A = Adaptive (deep only), R = Reflective (deep only)
94
+ */
95
+ applyCLEARFramework(prompt, mode = 'fast') {
96
+ // Analyze all components
97
+ const conciseness = this.analyzeConciseness(prompt);
98
+ const logic = this.analyzeLogic(prompt);
99
+ const explicitness = this.analyzeExplicitness(prompt);
100
+ let adaptiveness;
101
+ let reflectiveness;
102
+ if (mode === 'deep') {
103
+ adaptiveness = this.analyzeAdaptiveness(prompt);
104
+ reflectiveness = this.analyzeReflectiveness(prompt);
105
+ }
106
+ // Generate improved prompt based on CLEAR analysis
107
+ const improvedPrompt = this.generateCLEARImprovedPrompt(prompt, {
108
+ conciseness,
109
+ logic,
110
+ explicitness,
111
+ adaptiveness,
112
+ reflectiveness,
113
+ });
114
+ // Generate changes summary with CLEAR labels
115
+ const changesSummary = this.generateCLEARChangesSummary(prompt, improvedPrompt, {
116
+ conciseness,
117
+ logic,
118
+ explicitness,
119
+ adaptiveness,
120
+ reflectiveness,
121
+ });
122
+ // Calculate overall score
123
+ const overallScore = this.calculateCLEARScore({
124
+ conciseness,
125
+ logic,
126
+ explicitness,
127
+ adaptiveness,
128
+ reflectiveness,
129
+ }).overall;
130
+ return {
131
+ conciseness,
132
+ logic,
133
+ explicitness,
134
+ adaptiveness,
135
+ reflectiveness,
136
+ overallScore,
137
+ improvedPrompt,
138
+ changesSummary,
139
+ };
140
+ }
141
+ /**
142
+ * Analyze Conciseness (C): Brevity and clarity
143
+ */
144
+ analyzeConciseness(prompt) {
145
+ const issues = [];
146
+ const suggestions = [];
147
+ // Count pleasantries
148
+ const pleasantries = [
149
+ 'please',
150
+ 'could you',
151
+ 'would you',
152
+ 'if possible',
153
+ 'maybe',
154
+ 'perhaps',
155
+ 'kindly',
156
+ 'thank you',
157
+ ];
158
+ let pleasantriesCount = 0;
159
+ pleasantries.forEach((word) => {
160
+ const regex = new RegExp(`\\b${word}\\b`, 'gi');
161
+ const matches = prompt.match(regex);
162
+ if (matches) {
163
+ pleasantriesCount += matches.length;
164
+ }
165
+ });
166
+ if (pleasantriesCount > 0) {
167
+ issues.push(`Contains ${pleasantriesCount} unnecessary pleasantries`);
168
+ suggestions.push('[C] Remove pleasantries - be direct and concise');
169
+ }
170
+ // Count verbose language
171
+ const verbosePatterns = [
172
+ /in order to/gi,
173
+ /due to the fact that/gi,
174
+ /at this point in time/gi,
175
+ /for the purpose of/gi,
176
+ /in the event that/gi,
177
+ ];
178
+ let verbosityCount = 0;
179
+ verbosePatterns.forEach((pattern) => {
180
+ const matches = prompt.match(pattern);
181
+ if (matches) {
182
+ verbosityCount += matches.length;
183
+ }
184
+ });
185
+ if (verbosityCount > 0) {
186
+ issues.push(`Contains ${verbosityCount} verbose phrases`);
187
+ suggestions.push('[C] Replace verbose phrases with concise alternatives');
188
+ }
189
+ // Calculate signal-to-noise ratio
190
+ const wordCount = prompt.split(/\s+/).length;
191
+ const noiseWords = pleasantriesCount + verbosityCount;
192
+ const signalToNoiseRatio = wordCount > 0 ? (wordCount - noiseWords) / wordCount : 0;
193
+ // Calculate score
194
+ let score = 100;
195
+ score -= pleasantriesCount * 5; // -5 points per pleasantry
196
+ score -= verbosityCount * 10; // -10 points per verbose phrase
197
+ if (wordCount > 200 && !this.hasContext(prompt)) {
198
+ issues.push('Long prompt without clear structure');
199
+ suggestions.push('[C] Break into sections for clarity');
200
+ score -= 10;
201
+ }
202
+ score = Math.max(0, Math.min(100, score));
203
+ return {
204
+ score,
205
+ verbosityCount,
206
+ pleasantriesCount,
207
+ signalToNoiseRatio,
208
+ issues,
209
+ suggestions,
210
+ };
211
+ }
212
+ /**
213
+ * Analyze Logic (L): Structured and coherent prompts
214
+ */
215
+ analyzeLogic(prompt) {
216
+ const issues = [];
217
+ const suggestions = [];
218
+ const sequencingIssues = [];
219
+ // Check for coherent flow - ideal sequence: context → requirements → constraints → output
220
+ const hasContextFirst = this.hasContext(prompt.substring(0, prompt.length / 2));
221
+ const hasOutputLast = this.hasExpectedOutput(prompt.substring(prompt.length / 2));
222
+ let hasCoherentFlow = true;
223
+ // Check if success criteria comes before requirements
224
+ const successMatch = prompt.match(/\b(success|complete|done|measure)/i);
225
+ const requirementMatch = prompt.match(/\b(require|need|must|should have)/i);
226
+ if (successMatch && requirementMatch) {
227
+ const successIndex = successMatch.index || 0;
228
+ const requirementIndex = requirementMatch.index || 0;
229
+ if (successIndex < requirementIndex && successIndex < prompt.length / 3) {
230
+ sequencingIssues.push('Success criteria appears before requirements');
231
+ hasCoherentFlow = false;
232
+ }
233
+ }
234
+ if (!hasContextFirst && this.hasContext(prompt)) {
235
+ sequencingIssues.push('Context appears late in prompt - should be at the beginning');
236
+ hasCoherentFlow = false;
237
+ }
238
+ if (!hasOutputLast && this.hasExpectedOutput(prompt)) {
239
+ sequencingIssues.push('Expected output appears early - should be near the end');
240
+ hasCoherentFlow = false;
241
+ }
242
+ // Suggest optimal order
243
+ const suggestedOrder = [
244
+ '1. Context/Background (what exists now)',
245
+ '2. Objective (what you want to achieve)',
246
+ '3. Requirements (specific needs)',
247
+ '4. Technical Constraints',
248
+ '5. Expected Output',
249
+ '6. Success Criteria',
250
+ ];
251
+ if (!hasCoherentFlow) {
252
+ issues.push('Logical flow could be improved');
253
+ suggestions.push('[L] Restructure prompt following optimal sequence');
254
+ }
255
+ // Check for scattered information
256
+ const lines = prompt.split(/\n/).filter((l) => l.trim());
257
+ if (lines.length > 5 && lines.length < 3) {
258
+ issues.push('Information appears scattered');
259
+ suggestions.push('[L] Group related concepts together');
260
+ }
261
+ // Calculate score
262
+ let score = 100;
263
+ score -= sequencingIssues.length * 15; // -15 points per sequencing issue
264
+ if (!hasCoherentFlow)
265
+ score -= 20;
266
+ score = Math.max(0, Math.min(100, score));
267
+ return {
268
+ score,
269
+ hasCoherentFlow,
270
+ sequencingIssues,
271
+ suggestedOrder,
272
+ issues,
273
+ suggestions,
274
+ };
275
+ }
276
+ /**
277
+ * Analyze Explicitness (E): Clear output specifications
278
+ */
279
+ analyzeExplicitness(prompt) {
280
+ const issues = [];
281
+ const suggestions = [];
282
+ // Check for persona/role
283
+ const hasPersona = /\b(as a|role|persona|you are|act as|expert|developer|designer|engineer)\b/i.test(prompt);
284
+ if (!hasPersona) {
285
+ issues.push('No persona or role specified');
286
+ suggestions.push('[E] Specify who should respond (e.g., "As a senior developer...")');
287
+ }
288
+ // Check for output format
289
+ const hasOutputFormat = /\b(format|structure|markdown|json|code|list|table|bullet|numbered)\b/i.test(prompt) ||
290
+ this.hasExpectedOutput(prompt);
291
+ if (!hasOutputFormat) {
292
+ issues.push('Output format not specified');
293
+ suggestions.push('[E] Define expected format (e.g., "Provide as a numbered list...")');
294
+ }
295
+ // Check for tone/style
296
+ const hasToneStyle = /\b(tone|style|formal|casual|professional|concise|detailed|technical)\b/i.test(prompt);
297
+ if (!hasToneStyle) {
298
+ issues.push('Tone or style not specified');
299
+ suggestions.push('[E] Specify desired tone (e.g., "Use professional tone...")');
300
+ }
301
+ // Check for success criteria
302
+ const hasSuccessCriteria = this.hasSuccessCriteria(prompt);
303
+ if (!hasSuccessCriteria) {
304
+ issues.push('Success criteria not defined');
305
+ suggestions.push('[E] Add measurable success criteria');
306
+ }
307
+ // Check for examples
308
+ const hasExamples = /\b(example|such as|like|e\.g\.|for instance)\b/i.test(prompt);
309
+ if (!hasExamples && prompt.length < 100) {
310
+ suggestions.push('[E] Consider adding examples for clarity');
311
+ }
312
+ // Calculate score based on what's present
313
+ let score = 0;
314
+ if (hasPersona)
315
+ score += 20;
316
+ if (hasOutputFormat)
317
+ score += 30;
318
+ if (hasToneStyle)
319
+ score += 20;
320
+ if (hasSuccessCriteria)
321
+ score += 20;
322
+ if (hasExamples)
323
+ score += 10;
324
+ return {
325
+ score,
326
+ hasPersona,
327
+ hasOutputFormat,
328
+ hasToneStyle,
329
+ hasSuccessCriteria,
330
+ hasExamples,
331
+ issues,
332
+ suggestions,
333
+ };
334
+ }
335
+ /**
336
+ * Analyze Adaptiveness (A): Flexibility and customization
337
+ */
338
+ analyzeAdaptiveness(prompt) {
339
+ const issues = [];
340
+ const suggestions = [];
341
+ // Generate alternative phrasings
342
+ const alternativePhrasings = this.generateAlternativePhrasings(prompt);
343
+ // Generate alternative structures
344
+ const alternativeStructures = this.suggestAlternativeStructures(prompt).map((s) => ({
345
+ name: s.structure.split(':')[0],
346
+ structure: s.structure,
347
+ benefits: s.benefits,
348
+ }));
349
+ // Recommend temperature based on prompt type
350
+ let temperatureRecommendation = 0.7; // default
351
+ if (/creative|brainstorm|ideas|innovate/i.test(prompt)) {
352
+ temperatureRecommendation = 0.9;
353
+ suggestions.push('[A] Use higher temperature (0.8-0.9) for creative tasks');
354
+ }
355
+ else if (/code|technical|precise|exact/i.test(prompt)) {
356
+ temperatureRecommendation = 0.3;
357
+ suggestions.push('[A] Use lower temperature (0.2-0.4) for precise technical tasks');
358
+ }
359
+ // Check if prompt is too rigid
360
+ if (/\b(must|only|exactly|precisely|never|always)\b/gi.test(prompt) &&
361
+ prompt.match(/\b(must|only|exactly|precisely|never|always)\b/gi).length > 3) {
362
+ issues.push('Prompt may be too rigid - limits creative solutions');
363
+ suggestions.push('[A] Consider allowing alternative approaches where appropriate');
364
+ }
365
+ // Calculate score based on flexibility
366
+ let score = 60; // base score
367
+ if (alternativePhrasings.length >= 3)
368
+ score += 20;
369
+ if (/\b(or|alternative|option|variation)\b/i.test(prompt))
370
+ score += 10;
371
+ if (temperatureRecommendation > 0.5 && temperatureRecommendation < 0.9)
372
+ score += 10;
373
+ score = Math.max(0, Math.min(100, score));
374
+ return {
375
+ score,
376
+ alternativePhrasings,
377
+ alternativeStructures,
378
+ temperatureRecommendation,
379
+ issues,
380
+ suggestions,
381
+ };
382
+ }
383
+ /**
384
+ * Analyze Reflectiveness (R): Continuous evaluation and improvement
385
+ */
386
+ analyzeReflectiveness(prompt) {
387
+ const issues = [];
388
+ const suggestions = [];
389
+ // Create validation checklist
390
+ const validationChecklist = [
391
+ 'Verify all requirements are clearly stated',
392
+ 'Check that success criteria are measurable',
393
+ 'Ensure technical constraints are realistic',
394
+ 'Validate that the scope is achievable',
395
+ ];
396
+ // Identify edge cases
397
+ const edgeCases = this.identifyEdgeCases(prompt);
398
+ // Identify potential issues
399
+ const potentialIssues = this.identifyPotentialIssues(prompt);
400
+ // Fact-checking steps
401
+ const factCheckingSteps = [
402
+ 'Verify AI output matches specified requirements',
403
+ 'Cross-reference technical details with documentation',
404
+ 'Validate examples and code snippets for accuracy',
405
+ 'Check for logical consistency in the response',
406
+ ];
407
+ // Quality criteria
408
+ const qualityCriteria = [
409
+ 'Response addresses all stated requirements',
410
+ 'Output follows specified format and structure',
411
+ 'Technical details are accurate and current',
412
+ 'Edge cases are properly handled',
413
+ ];
414
+ if (edgeCases.length === 0) {
415
+ suggestions.push('[R] Add specific edge cases to consider');
416
+ }
417
+ if (!this.hasSuccessCriteria(prompt)) {
418
+ issues.push('No validation criteria provided');
419
+ suggestions.push('[R] Define how to validate the AI output');
420
+ }
421
+ // Calculate score
422
+ let score = 70; // base score
423
+ if (edgeCases.length > 2)
424
+ score += 10;
425
+ if (this.hasSuccessCriteria(prompt))
426
+ score += 20;
427
+ if (potentialIssues.length < 3)
428
+ score += 10; // fewer issues = better quality
429
+ score = Math.max(0, Math.min(100, score));
430
+ return {
431
+ score,
432
+ validationChecklist,
433
+ edgeCases,
434
+ potentialIssues,
435
+ factCheckingSteps,
436
+ qualityCriteria,
437
+ issues,
438
+ suggestions,
439
+ };
440
+ }
441
+ /**
442
+ * Calculate overall CLEAR score with weighted components
443
+ */
444
+ calculateCLEARScore(analysis) {
445
+ const { conciseness, logic, explicitness, adaptiveness, reflectiveness } = analysis;
446
+ let overall;
447
+ let rating;
448
+ if (adaptiveness && reflectiveness) {
449
+ // Deep mode: weight all 5 components
450
+ overall =
451
+ conciseness.score * 0.2 +
452
+ logic.score * 0.2 +
453
+ explicitness.score * 0.3 +
454
+ adaptiveness.score * 0.15 +
455
+ reflectiveness.score * 0.15;
456
+ }
457
+ else {
458
+ // Fast mode: weight only C, L, E
459
+ overall = conciseness.score * 0.25 + logic.score * 0.25 + explicitness.score * 0.5;
460
+ }
461
+ // Determine rating
462
+ if (overall >= 80)
463
+ rating = 'excellent';
464
+ else if (overall >= 60)
465
+ rating = 'good';
466
+ else if (overall >= 40)
467
+ rating = 'needs-improvement';
468
+ else
469
+ rating = 'poor';
470
+ return {
471
+ overall: Math.round(overall),
472
+ conciseness: conciseness.score,
473
+ logic: logic.score,
474
+ explicitness: explicitness.score,
475
+ adaptiveness: adaptiveness?.score,
476
+ reflectiveness: reflectiveness?.score,
477
+ rating,
478
+ };
479
+ }
480
+ /**
481
+ * Generate improved prompt using CLEAR framework insights
482
+ */
483
+ generateCLEARImprovedPrompt(original, analysis) {
484
+ let improved = '';
485
+ // Apply Conciseness: Remove fluff
486
+ let cleaned = original;
487
+ const pleasantries = ['please', 'could you', 'would you', 'if possible', 'maybe', 'perhaps', 'kindly'];
488
+ pleasantries.forEach((word) => {
489
+ const regex = new RegExp(`\\b${word}\\b\\s*`, 'gi');
490
+ cleaned = cleaned.replace(regex, '');
491
+ });
492
+ // Apply Explicitness: Add missing elements
493
+ if (!analysis.explicitness.hasPersona) {
494
+ improved += '**Role:** Act as an expert developer.\n\n';
495
+ }
496
+ // Apply Logic: Structure the prompt
497
+ improved += '# Objective\n\n';
498
+ improved += this.extractOrInferObjective(cleaned) + '\n\n';
499
+ improved += '# Requirements\n\n';
500
+ improved += this.extractOrInferRequirements(cleaned) + '\n\n';
501
+ improved += '# Technical Constraints\n\n';
502
+ improved += this.extractOrInferTechnical(cleaned) + '\n\n';
503
+ improved += '# Expected Output\n\n';
504
+ improved += this.extractOrInferOutput(cleaned) + '\n\n';
505
+ // Apply Explicitness: Add format specification
506
+ if (!analysis.explicitness.hasOutputFormat) {
507
+ improved += '**Format:** Provide response as a structured, well-organized output.\n\n';
508
+ }
509
+ improved += '# Success Criteria\n\n';
510
+ improved += this.extractOrInferSuccess(cleaned) + '\n';
511
+ return improved.trim();
512
+ }
513
+ /**
514
+ * Generate CLEAR-labeled changes summary
515
+ */
516
+ generateCLEARChangesSummary(original, improved, analysis) {
517
+ const changes = [];
518
+ // Conciseness changes
519
+ if (analysis.conciseness.pleasantriesCount > 0) {
520
+ changes.push({
521
+ component: 'C',
522
+ change: `Removed ${analysis.conciseness.pleasantriesCount} unnecessary pleasantries`,
523
+ });
524
+ }
525
+ if (analysis.conciseness.verbosityCount > 0) {
526
+ changes.push({
527
+ component: 'C',
528
+ change: `Eliminated ${analysis.conciseness.verbosityCount} verbose phrases`,
529
+ });
530
+ }
531
+ // Logic changes
532
+ if (!analysis.logic.hasCoherentFlow) {
533
+ changes.push({
534
+ component: 'L',
535
+ change: 'Restructured for logical flow: Context → Requirements → Constraints → Output',
536
+ });
537
+ }
538
+ // Explicitness changes
539
+ if (!analysis.explicitness.hasPersona) {
540
+ changes.push({
541
+ component: 'E',
542
+ change: 'Added explicit persona/role specification',
543
+ });
544
+ }
545
+ if (!analysis.explicitness.hasOutputFormat) {
546
+ changes.push({
547
+ component: 'E',
548
+ change: 'Defined output format and structure',
549
+ });
550
+ }
551
+ if (!analysis.explicitness.hasSuccessCriteria && !this.hasSuccessCriteria(original)) {
552
+ changes.push({
553
+ component: 'E',
554
+ change: 'Added measurable success criteria',
555
+ });
556
+ }
557
+ // Adaptive changes (deep mode only)
558
+ if (analysis.adaptiveness && analysis.adaptiveness.alternativePhrasings.length > 0) {
559
+ changes.push({
560
+ component: 'A',
561
+ change: `Generated ${analysis.adaptiveness.alternativePhrasings.length} alternative approaches (see Adaptive Variations)`,
562
+ });
563
+ }
564
+ // Reflective changes (deep mode only)
565
+ if (analysis.reflectiveness) {
566
+ changes.push({
567
+ component: 'R',
568
+ change: `Created validation checklist with ${analysis.reflectiveness.edgeCases.length} edge cases (see Reflection Checklist)`,
569
+ });
570
+ }
571
+ // Fallback if no changes detected
572
+ if (changes.length === 0) {
573
+ changes.push({
574
+ component: 'E',
575
+ change: 'Structured the prompt with clear sections',
576
+ });
577
+ }
578
+ return changes;
579
+ }
580
+ /**
581
+ * Map CLEAR result to legacy PromptAnalysis format for backward compatibility
582
+ */
583
+ mapCLEARToLegacy(clearResult) {
584
+ return {
585
+ gaps: clearResult.explicitness.issues,
586
+ ambiguities: clearResult.conciseness.issues,
587
+ strengths: this.extractCLEARStrengths(clearResult),
588
+ suggestions: [
589
+ ...clearResult.conciseness.suggestions,
590
+ ...clearResult.logic.suggestions,
591
+ ...clearResult.explicitness.suggestions,
592
+ ],
593
+ };
594
+ }
595
+ /**
596
+ * Extract strengths from CLEAR analysis
597
+ */
598
+ extractCLEARStrengths(clearResult) {
599
+ const strengths = [];
600
+ if (clearResult.conciseness.score >= 80) {
601
+ strengths.push('[C] Concise and focused language');
602
+ }
603
+ if (clearResult.logic.score >= 80) {
604
+ strengths.push('[L] Well-structured logical flow');
605
+ }
606
+ if (clearResult.explicitness.score >= 80) {
607
+ strengths.push('[E] Clear and explicit specifications');
608
+ }
609
+ if (clearResult.adaptiveness && clearResult.adaptiveness.score >= 80) {
610
+ strengths.push('[A] Flexible and adaptable approach');
611
+ }
612
+ if (clearResult.reflectiveness && clearResult.reflectiveness.score >= 80) {
613
+ strengths.push('[R] Strong validation and reflection criteria');
614
+ }
615
+ if (strengths.length === 0) {
616
+ strengths.push('Prompt has been structured for improvement');
617
+ }
618
+ return strengths;
619
+ }
620
+ /**
621
+ * Find gaps in the prompt
622
+ */
623
+ findGaps(prompt) {
624
+ const gaps = [];
625
+ if (!this.hasContext(prompt)) {
626
+ gaps.push('Missing context: What is the background or current situation?');
627
+ }
628
+ if (!this.hasSuccessCriteria(prompt)) {
629
+ gaps.push('No success criteria: How will you know when this is complete?');
630
+ }
631
+ if (!this.hasTechnicalDetails(prompt)) {
632
+ gaps.push('Missing technical details: What technologies or constraints apply?');
633
+ }
634
+ if (!this.hasUserNeeds(prompt)) {
635
+ gaps.push('No user perspective: Who will use this and what do they need?');
636
+ }
637
+ if (!this.hasExpectedOutput(prompt)) {
638
+ gaps.push('Unclear expected output: What should the final deliverable look like?');
639
+ }
640
+ return gaps;
641
+ }
642
+ /**
643
+ * Find ambiguities in the prompt
644
+ */
645
+ findAmbiguities(prompt) {
646
+ const ambiguities = [];
647
+ // Check for vague terms
648
+ const vagueTerms = ['some', 'maybe', 'probably', 'should', 'could', 'nice to have'];
649
+ for (const term of vagueTerms) {
650
+ if (new RegExp(`\\b${term}\\b`, 'i').test(prompt)) {
651
+ ambiguities.push(`Vague term: "${term}" - be more specific`);
652
+ }
653
+ }
654
+ // Check for undefined pronouns
655
+ if (/(this|that|these|those|it)\s+/gi.test(prompt) && prompt.length < 100) {
656
+ ambiguities.push('Undefined references: What does "this" or "it" refer to?');
657
+ }
658
+ // Check for unspecified quantities
659
+ if (/\b(many|several|few|some)\b/i.test(prompt)) {
660
+ ambiguities.push('Unspecified quantities: How many exactly?');
661
+ }
662
+ return ambiguities;
663
+ }
664
+ /**
665
+ * Find strengths in the prompt
666
+ */
667
+ findStrengths(prompt) {
668
+ const strengths = [];
669
+ if (this.hasContext(prompt)) {
670
+ strengths.push('Clear context provided');
671
+ }
672
+ if (this.hasTechnicalDetails(prompt)) {
673
+ strengths.push('Technical constraints specified');
674
+ }
675
+ if (this.hasSuccessCriteria(prompt)) {
676
+ strengths.push('Success criteria defined');
677
+ }
678
+ if (prompt.length > 200) {
679
+ strengths.push('Comprehensive detail provided');
680
+ }
681
+ if (/example|such as|like|e\.g\./i.test(prompt)) {
682
+ strengths.push('Includes examples for clarity');
683
+ }
684
+ return strengths;
685
+ }
686
+ /**
687
+ * Generate improvement suggestions
688
+ */
689
+ generateSuggestions(prompt) {
690
+ const suggestions = [];
691
+ if (!this.hasContext(prompt)) {
692
+ suggestions.push('Add background: Explain the current situation or problem');
693
+ }
694
+ if (!this.hasSuccessCriteria(prompt)) {
695
+ suggestions.push('Define success: Specify measurable criteria for completion');
696
+ }
697
+ if (!this.hasTechnicalDetails(prompt)) {
698
+ suggestions.push('Add constraints: Specify technologies, integrations, or performance needs');
699
+ }
700
+ if (prompt.length < 50) {
701
+ suggestions.push('Expand detail: Add more specific requirements and context');
702
+ }
703
+ if (!this.hasUserNeeds(prompt)) {
704
+ suggestions.push('Consider users: Who will use this and what do they need?');
705
+ }
706
+ return suggestions;
707
+ }
708
+ /**
709
+ * Generate improved prompt with structure
710
+ */
711
+ generateImprovedPrompt(original, _analysis) {
712
+ let improved = '# Objective\n\n';
713
+ improved += this.extractOrInferObjective(original) + '\n\n';
714
+ improved += '# Requirements\n\n';
715
+ improved += this.extractOrInferRequirements(original) + '\n\n';
716
+ improved += '# Technical Constraints\n\n';
717
+ improved += this.extractOrInferTechnical(original) + '\n\n';
718
+ improved += '# Expected Output\n\n';
719
+ improved += this.extractOrInferOutput(original) + '\n\n';
720
+ improved += '# Success Criteria\n\n';
721
+ improved += this.extractOrInferSuccess(original) + '\n';
722
+ return improved;
723
+ }
724
+ // Helper methods for analysis
725
+ hasContext(prompt) {
726
+ return /\b(background|context|currently|existing|problem|issue|because)\b/i.test(prompt);
727
+ }
728
+ hasSuccessCriteria(prompt) {
729
+ return /\b(success|complete|done|measure|metric|goal|should be able to)\b/i.test(prompt);
730
+ }
731
+ hasTechnicalDetails(prompt) {
732
+ const techTerms = /\b(react|vue|angular|node|python|java|typescript|api|database|sql|nosql|aws|docker|kubernetes)\b/i;
733
+ return techTerms.test(prompt) || /\b(integrate|performance|scale|security)\b/i.test(prompt);
734
+ }
735
+ hasUserNeeds(prompt) {
736
+ return /\b(user|customer|client|team|developer|admin|visitor)\b/i.test(prompt);
737
+ }
738
+ hasExpectedOutput(prompt) {
739
+ return /\b(output|result|deliverable|should|look like|include|contain)\b/i.test(prompt);
740
+ }
741
+ extractOrInferObjective(prompt) {
742
+ // Try to find action verbs at the start
743
+ const actionMatch = prompt.match(/^(create|build|develop|implement|add|update|fix|refactor|design)\s+(.+)/i);
744
+ if (actionMatch) {
745
+ return `${actionMatch[1]} ${actionMatch[2]}`;
746
+ }
747
+ return prompt.split('\n')[0] || prompt.substring(0, 100);
748
+ }
749
+ extractOrInferRequirements(prompt) {
750
+ const lines = prompt.split('\n').filter((line) => line.trim());
751
+ if (lines.length > 1) {
752
+ return lines.slice(1).map((line) => `- ${line}`).join('\n');
753
+ }
754
+ return '- ' + prompt + '\n- [Add specific requirements based on objective]';
755
+ }
756
+ extractOrInferTechnical(original) {
757
+ const techStack = [];
758
+ if (/react/i.test(original))
759
+ techStack.push('React');
760
+ if (/typescript/i.test(original))
761
+ techStack.push('TypeScript');
762
+ if (/node/i.test(original))
763
+ techStack.push('Node.js');
764
+ if (/python/i.test(original))
765
+ techStack.push('Python');
766
+ if (techStack.length > 0) {
767
+ return '- Technology stack: ' + techStack.join(', ') + '\n- [Add other constraints]';
768
+ }
769
+ return '- [Specify technologies, integrations, performance requirements]';
770
+ }
771
+ extractOrInferOutput(original) {
772
+ if (/component|page|ui/i.test(original)) {
773
+ return '- Functional, tested component\n- Responsive design\n- Accessible implementation';
774
+ }
775
+ if (/api|endpoint|service/i.test(original)) {
776
+ return '- Working API endpoint(s)\n- Error handling\n- Documentation';
777
+ }
778
+ return '- [Describe what the final deliverable should look like]';
779
+ }
780
+ extractOrInferSuccess(_original) {
781
+ return '- Implementation matches requirements\n- All edge cases handled\n- Code is tested and documented\n- [Add specific success metrics]';
782
+ }
783
+ // New helper methods for mode support
784
+ /**
785
+ * Count missing critical elements
786
+ */
787
+ countMissingCriticalElements(prompt) {
788
+ let missing = 0;
789
+ if (!this.hasContext(prompt))
790
+ missing++;
791
+ if (!this.hasTechnicalDetails(prompt))
792
+ missing++;
793
+ if (!this.hasSuccessCriteria(prompt))
794
+ missing++;
795
+ if (!this.hasUserNeeds(prompt))
796
+ missing++;
797
+ if (!this.hasExpectedOutput(prompt))
798
+ missing++;
799
+ return missing;
800
+ }
801
+ /**
802
+ * Check for vague scope words without sufficient context
803
+ */
804
+ hasVagueScopeWithoutContext(prompt) {
805
+ const vagueScopeWords = /\b(app|system|repository|project|platform|solution|tool|service)\b/i;
806
+ if (!vagueScopeWords.test(prompt)) {
807
+ return false;
808
+ }
809
+ // Check if there's sufficient context
810
+ const hasSpecificPurpose = /\b(for|to|that|which|enables|allows|helps)\b.{10,}/i.test(prompt);
811
+ const hasTechStack = this.hasTechnicalDetails(prompt);
812
+ const hasDetailedRequirements = prompt.length > 100;
813
+ return !(hasSpecificPurpose && (hasTechStack || hasDetailedRequirements));
814
+ }
815
+ /**
816
+ * Check if prompt has a clear goal
817
+ */
818
+ hasClearGoal(prompt) {
819
+ const actionVerbs = /^(create|build|develop|implement|add|update|fix|refactor|design|make|write)\b/i;
820
+ return actionVerbs.test(prompt.trim()) || /objective|goal|purpose/i.test(prompt);
821
+ }
822
+ /**
823
+ * Check if prompt uses actionable language
824
+ */
825
+ hasActionableLanguage(prompt) {
826
+ const actionWords = /\b(create|build|implement|add|update|remove|fix|test|deploy|configure|setup)\b/i;
827
+ return actionWords.test(prompt);
828
+ }
829
+ /**
830
+ * Check if prompt has reasonable scope
831
+ */
832
+ hasReasonableScope(prompt) {
833
+ // Too vague (unreasonably broad)
834
+ const tooVague = /^(build an app|create a system|make a platform)$/i.test(prompt.trim());
835
+ // Too specific (unreasonably narrow)
836
+ const tooSpecific = prompt.length > 1000;
837
+ return !tooVague && !tooSpecific;
838
+ }
839
+ /**
840
+ * Generate changes summary
841
+ */
842
+ generateChangesSummary(original, improved) {
843
+ const changes = [];
844
+ if (!this.hasContext(original) && /# Objective/.test(improved)) {
845
+ changes.push('Added clear objective and context');
846
+ }
847
+ if (!this.hasTechnicalDetails(original) && /# Technical Constraints/.test(improved)) {
848
+ changes.push('Added technical constraints and requirements');
849
+ }
850
+ if (!this.hasSuccessCriteria(original) && /# Success Criteria/.test(improved)) {
851
+ changes.push('Defined measurable success criteria');
852
+ }
853
+ if (!this.hasExpectedOutput(original) && /# Expected Output/.test(improved)) {
854
+ changes.push('Specified expected deliverables');
855
+ }
856
+ if (original.length < 100 && improved.length > 100) {
857
+ changes.push('Expanded prompt with structured sections');
858
+ }
859
+ if (changes.length === 0) {
860
+ changes.push('Refined and structured the existing prompt');
861
+ }
862
+ return { changes };
863
+ }
864
+ /**
865
+ * Generate alternative phrasings (deep mode)
866
+ */
867
+ generateAlternativePhrasings(prompt) {
868
+ const phrasings = [];
869
+ const mainAction = prompt.match(/^(create|build|develop|implement|add)/i)?.[0] || 'Implement';
870
+ phrasings.push(`${mainAction} a solution that ${this.extractCoreRequirement(prompt)}`);
871
+ phrasings.push(`Design and implement ${this.extractCoreRequirement(prompt)}`);
872
+ phrasings.push(`Build a system to ${this.extractCoreRequirement(prompt)}`);
873
+ return phrasings.slice(0, 3);
874
+ }
875
+ /**
876
+ * Identify edge cases in requirements (deep mode)
877
+ */
878
+ identifyEdgeCases(prompt) {
879
+ const edgeCases = [];
880
+ if (/user|login|auth/i.test(prompt)) {
881
+ edgeCases.push('What happens when user is not authenticated?');
882
+ edgeCases.push('How to handle expired sessions?');
883
+ }
884
+ if (/api|endpoint|request/i.test(prompt)) {
885
+ edgeCases.push('How to handle network failures or timeouts?');
886
+ edgeCases.push('What validation is needed for input data?');
887
+ }
888
+ if (/form|input|data/i.test(prompt)) {
889
+ edgeCases.push('How to handle invalid or malformed input?');
890
+ edgeCases.push('What happens with empty or missing fields?');
891
+ }
892
+ if (edgeCases.length === 0) {
893
+ edgeCases.push('Consider error states and failure scenarios');
894
+ edgeCases.push('Think about boundary conditions and limits');
895
+ }
896
+ return edgeCases;
897
+ }
898
+ /**
899
+ * Generate implementation examples (deep mode)
900
+ */
901
+ generateImplementationExamples(_prompt) {
902
+ return {
903
+ good: [
904
+ 'Clear, specific requirements with measurable outcomes',
905
+ 'Includes context about why this is needed',
906
+ 'Specifies technical constraints and success criteria',
907
+ ],
908
+ bad: [
909
+ 'Vague requirements without context',
910
+ 'No success criteria or expected output',
911
+ 'Missing technical constraints and user perspective',
912
+ ],
913
+ };
914
+ }
915
+ /**
916
+ * Suggest alternative prompt structures (deep mode)
917
+ */
918
+ suggestAlternativeStructures(_prompt) {
919
+ return [
920
+ {
921
+ structure: 'User Story Format: As a [user], I want [goal] so that [benefit]',
922
+ benefits: 'Focuses on user needs and value delivery',
923
+ },
924
+ {
925
+ structure: 'Job Story Format: When [situation], I want to [motivation], so I can [expected outcome]',
926
+ benefits: 'Emphasizes context and outcomes over personas',
927
+ },
928
+ {
929
+ structure: 'Structured Sections: Objective, Requirements, Constraints, Success Criteria',
930
+ benefits: 'Provides clear organization and comprehensive coverage',
931
+ },
932
+ ];
933
+ }
934
+ /**
935
+ * Identify potential issues with the prompt (deep mode)
936
+ */
937
+ identifyPotentialIssues(prompt) {
938
+ const issues = [];
939
+ if (prompt.length < 30) {
940
+ issues.push('Prompt may be too vague - could be interpreted in multiple ways');
941
+ }
942
+ if (!this.hasSuccessCriteria(prompt)) {
943
+ issues.push('Without success criteria, it will be hard to know when the task is complete');
944
+ }
945
+ if (!this.hasTechnicalDetails(prompt)) {
946
+ issues.push('Missing technical details may lead to incorrect technology choices');
947
+ }
948
+ if (!this.hasUserNeeds(prompt)) {
949
+ issues.push('Without user perspective, solution may not meet actual needs');
950
+ }
951
+ return issues;
952
+ }
953
+ /**
954
+ * Extract core requirement from prompt
955
+ */
956
+ extractCoreRequirement(prompt) {
957
+ // Remove action verbs and extract the core requirement
958
+ const cleaned = prompt.replace(/^(create|build|develop|implement|add|update|fix)\s+/i, '');
959
+ return cleaned.split('.')[0] || cleaned.substring(0, 100);
960
+ }
961
+ }
962
+ exports.PromptOptimizer = PromptOptimizer;
963
+ //# sourceMappingURL=prompt-optimizer.js.map