mycontext-cli 4.2.15 → 4.2.17

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 (77) hide show
  1. package/README.md +39 -38
  2. package/dist/cli.js +15 -44
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commands/generate-components.d.ts.map +1 -1
  5. package/dist/commands/generate-components.js +21 -18
  6. package/dist/commands/generate-components.js.map +1 -1
  7. package/dist/commands/generate.d.ts +3 -0
  8. package/dist/commands/generate.d.ts.map +1 -1
  9. package/dist/commands/generate.js +242 -158
  10. package/dist/commands/generate.js.map +1 -1
  11. package/dist/commands/init-interactive.d.ts.map +1 -1
  12. package/dist/commands/init-interactive.js +30 -2
  13. package/dist/commands/init-interactive.js.map +1 -1
  14. package/dist/commands/init.d.ts +1 -0
  15. package/dist/commands/init.d.ts.map +1 -1
  16. package/dist/commands/init.js +194 -38
  17. package/dist/commands/init.js.map +1 -1
  18. package/dist/commands/setup-complete.d.ts.map +1 -1
  19. package/dist/commands/setup-complete.js +4 -6
  20. package/dist/commands/setup-complete.js.map +1 -1
  21. package/dist/commands/workflow.d.ts.map +1 -1
  22. package/dist/commands/workflow.js +10 -58
  23. package/dist/commands/workflow.js.map +1 -1
  24. package/dist/core/ai/AICore.d.ts +4 -0
  25. package/dist/core/ai/AICore.d.ts.map +1 -1
  26. package/dist/core/ai/AICore.js +6 -0
  27. package/dist/core/ai/AICore.js.map +1 -1
  28. package/dist/tui/DashboardMode.d.ts +14 -0
  29. package/dist/tui/DashboardMode.d.ts.map +1 -0
  30. package/dist/tui/DashboardMode.js +75 -0
  31. package/dist/tui/DashboardMode.js.map +1 -0
  32. package/dist/tui/TUIClient.d.ts +9 -0
  33. package/dist/tui/TUIClient.d.ts.map +1 -1
  34. package/dist/tui/TUIClient.js +63 -0
  35. package/dist/tui/TUIClient.js.map +1 -1
  36. package/dist/types/index.d.ts +1 -1
  37. package/dist/types/index.d.ts.map +1 -1
  38. package/dist/types/living-context.d.ts +1 -0
  39. package/dist/types/living-context.d.ts.map +1 -1
  40. package/dist/types/tui.d.ts +3 -1
  41. package/dist/types/tui.d.ts.map +1 -1
  42. package/dist/utils/contextEnricher.d.ts +2 -1
  43. package/dist/utils/contextEnricher.d.ts.map +1 -1
  44. package/dist/utils/contextEnricher.js +138 -1
  45. package/dist/utils/contextEnricher.js.map +1 -1
  46. package/dist/utils/contextRenderer.d.ts +3 -0
  47. package/dist/utils/contextRenderer.d.ts.map +1 -1
  48. package/dist/utils/contextRenderer.js +65 -0
  49. package/dist/utils/contextRenderer.js.map +1 -1
  50. package/dist/utils/fileSystem.d.ts.map +1 -1
  51. package/dist/utils/fileSystem.js +32 -1
  52. package/dist/utils/fileSystem.js.map +1 -1
  53. package/dist/utils/geminiClient.d.ts.map +1 -1
  54. package/dist/utils/geminiClient.js +10 -5
  55. package/dist/utils/geminiClient.js.map +1 -1
  56. package/dist/utils/githubModelsClient.d.ts.map +1 -1
  57. package/dist/utils/githubModelsClient.js +4 -1
  58. package/dist/utils/githubModelsClient.js.map +1 -1
  59. package/dist/utils/openRouterClient.d.ts.map +1 -1
  60. package/dist/utils/openRouterClient.js +1 -0
  61. package/dist/utils/openRouterClient.js.map +1 -1
  62. package/dist/utils/unifiedDesignContextLoader.d.ts.map +1 -1
  63. package/dist/utils/unifiedDesignContextLoader.js +14 -0
  64. package/dist/utils/unifiedDesignContextLoader.js.map +1 -1
  65. package/package.json +4 -2
  66. package/dist/commands/assemble-features.d.ts +0 -40
  67. package/dist/commands/assemble-features.d.ts.map +0 -1
  68. package/dist/commands/assemble-features.js +0 -383
  69. package/dist/commands/assemble-features.js.map +0 -1
  70. package/dist/commands/compile-prd.d.ts +0 -18
  71. package/dist/commands/compile-prd.d.ts.map +0 -1
  72. package/dist/commands/compile-prd.js +0 -253
  73. package/dist/commands/compile-prd.js.map +0 -1
  74. package/dist/commands/generate-context-files.d.ts +0 -44
  75. package/dist/commands/generate-context-files.d.ts.map +0 -1
  76. package/dist/commands/generate-context-files.js +0 -871
  77. package/dist/commands/generate-context-files.js.map +0 -1
@@ -1,871 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.GenerateContextFilesCommand = void 0;
40
- const chalk_1 = __importDefault(require("chalk"));
41
- const fs = __importStar(require("fs-extra"));
42
- const path_1 = __importDefault(require("path"));
43
- const hybridAIClient_1 = require("../utils/hybridAIClient");
44
- const spinner_1 = require("../utils/spinner");
45
- const logger_1 = require("../utils/logger");
46
- const errorHandler_1 = require("../utils/errorHandler");
47
- const nextStepsSuggester_1 = require("../utils/nextStepsSuggester");
48
- const ContextValidator_1 = require("../services/ContextValidator");
49
- class GenerateContextFilesCommand {
50
- constructor() {
51
- this.aiClient = new hybridAIClient_1.HybridAIClient();
52
- this.spinner = new spinner_1.EnhancedSpinner("Generating context files...");
53
- this.contextValidator = new ContextValidator_1.ContextValidator();
54
- }
55
- async execute(options) {
56
- const projectPath = options.projectPath || process.cwd();
57
- const contextDir = path_1.default.join(projectPath, ".mycontext");
58
- logger_1.logger.info("Generating Context Files (A/B/C/D)");
59
- logger_1.logger.verbose("Creating comprehensive project context from PRD or description");
60
- // Ensure .mycontext directory exists
61
- await fs.ensureDir(contextDir);
62
- // Check if context files already exist
63
- const existingFiles = await this.checkExistingFiles(contextDir);
64
- if (existingFiles.length > 0 && !options.force) {
65
- logger_1.logger.warn("Context files already exist:");
66
- existingFiles.forEach((file) => logger_1.logger.verbose(` • ${file}`));
67
- logger_1.logger.info("Use --force to overwrite existing files");
68
- return;
69
- }
70
- // Get context from PRD if it exists, otherwise use description
71
- const contextContent = await this.getContextForGeneration(contextDir, options.description);
72
- // Validate context and detect gaps
73
- this.spinner.updateText("🔍 Validating context completeness...");
74
- const validationResult = await this.validateContext(contextContent, options.description);
75
- // Save auto-generated features for review
76
- await this.saveAutoGeneratedFeatures(contextDir, validationResult);
77
- // Check for critical gaps
78
- if (validationResult.hasCriticalGaps) {
79
- this.spinner.fail("Critical information missing");
80
- console.log(chalk_1.default.red("\n❌ Critical information missing:"));
81
- const criticalGaps = validationResult.gaps.filter((gap) => gap.category === "critical");
82
- criticalGaps.forEach((gap, index) => {
83
- console.log(chalk_1.default.yellow(`\n${index + 1}. ${gap.question}`));
84
- console.log(chalk_1.default.gray(` ${gap.reasoning}`));
85
- if (gap.suggestedAnswers) {
86
- gap.suggestedAnswers.forEach((answer, i) => {
87
- console.log(chalk_1.default.gray(` - ${String.fromCharCode(97 + i)}) ${answer}`));
88
- });
89
- }
90
- });
91
- console.log(chalk_1.default.blue("\n💡 Please provide the missing information and run the command again."));
92
- console.log(chalk_1.default.blue(" Or run 'mycontext review:context' to address these gaps interactively."));
93
- return;
94
- }
95
- // Show auto-generated features for review
96
- if (validationResult.autoGeneratedFeatures.length > 0) {
97
- console.log(chalk_1.default.yellow("\n⚠️ Auto-generated features detected:"));
98
- validationResult.autoGeneratedFeatures.forEach((feature, index) => {
99
- console.log(chalk_1.default.gray(` ${index + 1}. ${feature.feature}`));
100
- console.log(chalk_1.default.gray(` Reasoning: ${feature.reasoning}`));
101
- console.log(chalk_1.default.gray(` Confidence: ${feature.confidence}`));
102
- });
103
- console.log(chalk_1.default.blue("\n💡 Run 'mycontext review:context' to approve/reject these features."));
104
- }
105
- this.spinner.start();
106
- try {
107
- // Generate each context file using the PRD content as context
108
- const results = await Promise.allSettled([
109
- this.generateFeaturesFile(contextDir, contextContent),
110
- this.generateUserFlowsFile(contextDir, contextContent),
111
- this.generateEdgeCasesFile(contextDir, contextContent),
112
- this.generateTechnicalSpecsFile(contextDir, contextContent),
113
- ]);
114
- // Check if any files were generated successfully
115
- const successCount = results.filter((result) => result.status === "fulfilled").length;
116
- const failureCount = results.filter((result) => result.status === "rejected").length;
117
- if (successCount === 0) {
118
- const error = errorHandler_1.ErrorHandler.createError(errorHandler_1.ErrorType.AI_PROVIDER_ERROR, "All context file generation failed - no AI providers available", undefined, { successCount, failureCount });
119
- errorHandler_1.ErrorHandler.handleErrorGracefully(error);
120
- throw new Error("All context file generation failed - configure API keys and retry");
121
- }
122
- else if (failureCount > 0) {
123
- logger_1.logger.warn(`⚠️ ${failureCount} of 4 context files failed to generate`);
124
- logger_1.logger.info(`✅ ${successCount} context files generated successfully`);
125
- }
126
- else {
127
- logger_1.logger.success("✅ Context files generated successfully!");
128
- }
129
- this.spinner.succeed("User-centric context documentation generated successfully!");
130
- // Show next steps
131
- const workflowContext = await nextStepsSuggester_1.NextStepsSuggester.getWorkflowContext();
132
- workflowContext.lastCommand = "generate-context-files";
133
- workflowContext.hasContextFiles = true;
134
- const nextSteps = nextStepsSuggester_1.NextStepsSuggester.getNextSteps(workflowContext);
135
- nextStepsSuggester_1.NextStepsSuggester.displayNextSteps(nextSteps);
136
- }
137
- catch (error) {
138
- this.spinner.fail("Context file generation failed");
139
- // Don't log the error again - it's already been logged by the individual methods
140
- throw error;
141
- }
142
- }
143
- /**
144
- * Validate context and detect gaps
145
- */
146
- async validateContext(contextContent, description) {
147
- const contextFiles = {
148
- prd: contextContent,
149
- description: description,
150
- };
151
- return await this.contextValidator.validateContext(contextFiles);
152
- }
153
- /**
154
- * Save auto-generated features for review
155
- */
156
- async saveAutoGeneratedFeatures(contextDir, validationResult) {
157
- const autoGeneratedData = {
158
- features: validationResult.autoGeneratedFeatures,
159
- gaps: validationResult.gaps,
160
- timestamp: new Date().toISOString(),
161
- version: "1.0",
162
- };
163
- await fs.writeFile(path_1.default.join(contextDir, "auto-generated.json"), JSON.stringify(autoGeneratedData, null, 2));
164
- }
165
- async checkExistingFiles(contextDir) {
166
- const files = [
167
- "01a-features.md",
168
- "01b-user-flows.md",
169
- "01c-edge-cases.md",
170
- "01d-technical-specs.md",
171
- ];
172
- const existingFiles = [];
173
- for (const file of files) {
174
- if (await fs.pathExists(path_1.default.join(contextDir, file))) {
175
- existingFiles.push(file);
176
- }
177
- }
178
- return existingFiles;
179
- }
180
- async generateFeaturesFile(contextDir, contextContent) {
181
- // Generate features file
182
- try {
183
- const prompt = this.buildFeaturesPrompt(contextContent);
184
- const response = await this.aiClient.generateText(prompt, {
185
- temperature: 0.7,
186
- maxTokens: 2000,
187
- spinnerCallback: (text, resetTimer = false) => {
188
- this.spinner.updateText(text);
189
- if (resetTimer) {
190
- this.spinner.reset();
191
- }
192
- },
193
- });
194
- const content = this.formatFeaturesContent(response.text);
195
- await fs.writeFile(path_1.default.join(contextDir, "01a-features.md"), content);
196
- console.log(chalk_1.default.green(" ✅ Features documented"));
197
- }
198
- catch (error) {
199
- console.log(chalk_1.default.red(" ❌ Features failed"));
200
- // Re-throw the error so Promise.allSettled can catch it
201
- throw error;
202
- }
203
- }
204
- async generateUserFlowsFile(contextDir, contextContent) {
205
- // Generate user flows file
206
- try {
207
- const prompt = this.buildUserFlowsPrompt(contextContent);
208
- const response = await this.aiClient.generateText(prompt, {
209
- temperature: 0.7,
210
- maxTokens: 2000,
211
- spinnerCallback: (text, resetTimer = false) => {
212
- this.spinner.updateText(text);
213
- if (resetTimer) {
214
- this.spinner.reset();
215
- }
216
- },
217
- });
218
- const content = this.formatUserFlowsContent(response.text);
219
- await fs.writeFile(path_1.default.join(contextDir, "01b-user-flows.md"), content);
220
- console.log(chalk_1.default.green(" ✅ User flows documented"));
221
- }
222
- catch (error) {
223
- console.log(chalk_1.default.red(" ❌ User flows failed"));
224
- // Re-throw the error so Promise.allSettled can catch it
225
- throw error;
226
- }
227
- }
228
- async generateEdgeCasesFile(contextDir, contextContent) {
229
- // Generate edge cases file
230
- try {
231
- const prompt = this.buildEdgeCasesPrompt(contextContent);
232
- const response = await this.aiClient.generateText(prompt, {
233
- temperature: 0.7,
234
- maxTokens: 2000,
235
- spinnerCallback: (text, resetTimer = false) => {
236
- this.spinner.updateText(text);
237
- if (resetTimer) {
238
- this.spinner.reset();
239
- }
240
- },
241
- });
242
- const content = this.formatEdgeCasesContent(response.text);
243
- await fs.writeFile(path_1.default.join(contextDir, "01c-edge-cases.md"), content);
244
- console.log(chalk_1.default.green(" ✅ Edge cases documented"));
245
- }
246
- catch (error) {
247
- console.log(chalk_1.default.red(" ❌ Edge cases failed"));
248
- // Re-throw the error so Promise.allSettled can catch it
249
- throw error;
250
- }
251
- }
252
- async generateTechnicalSpecsFile(contextDir, contextContent) {
253
- // Generate technical specs file
254
- try {
255
- const prompt = this.buildTechnicalSpecsPrompt(contextContent);
256
- const response = await this.aiClient.generateText(prompt, {
257
- temperature: 0.7,
258
- maxTokens: 2000,
259
- spinnerCallback: (text, resetTimer = false) => {
260
- this.spinner.updateText(text);
261
- if (resetTimer) {
262
- this.spinner.reset();
263
- }
264
- },
265
- });
266
- const content = this.formatTechnicalSpecsContent(response.text);
267
- await fs.writeFile(path_1.default.join(contextDir, "01d-technical-specs.md"), content);
268
- console.log(chalk_1.default.green(" ✅ Technical specs documented"));
269
- }
270
- catch (error) {
271
- console.log(chalk_1.default.red(" ❌ Technical specs failed"));
272
- // Re-throw the error so Promise.allSettled can catch it
273
- throw error;
274
- }
275
- }
276
- buildFeaturesPrompt(contextContent) {
277
- return `You are a user experience researcher documenting every user interaction for a web application.
278
-
279
- ${contextContent
280
- ? `Project Context: ${contextContent}`
281
- : "Generate user interaction documentation for a modern web application."}
282
-
283
- Create a comprehensive user-centric features document that documents every user interaction:
284
-
285
- ## 🎯 **User-Centric Features Documentation**
286
-
287
- ### **What Users Can Do (User Actions)**
288
- Document every action users can take in the application:
289
-
290
- **❌ Don't write technical specs:**
291
- - User authentication system
292
- - Shopping cart functionality
293
- - Payment processing
294
-
295
- **✅ Write user interactions:**
296
- - User can click "Sign Up" to create an account
297
- - User can browse products by category and search
298
- - User can add items to cart with quantity selection
299
- - User can complete checkout with multiple payment options
300
- - User can view order history and track deliveries
301
-
302
- ### **What Users See (System Responses)**
303
- Document what users see after each action:
304
-
305
- **❌ Don't write:**
306
- - Dashboard displays user profile
307
- - Products show in grid layout
308
-
309
- **✅ Write:**
310
- - After login, user sees personalized dashboard with recent orders
311
- - Product catalog shows items with images, prices, and "Add to Cart" buttons
312
- - Shopping cart displays items with quantity controls and remove options
313
- - Checkout form shows shipping address, payment method, and order summary
314
- - Order confirmation page displays order number, estimated delivery, and tracking info
315
-
316
- ### **User Journey Documentation**
317
- Document complete user journeys from start to finish:
318
-
319
- 1. **New User Onboarding**
320
- - User visits homepage → sees hero section with "Get Started" button
321
- - User clicks "Get Started" → registration form appears
322
- - User fills out form → email verification sent
323
- - User verifies email → redirected to dashboard
324
-
325
- 2. **Product Purchase Flow**
326
- - User browses catalog → sees product grid with filters
327
- - User selects product → product detail page with reviews
328
- - User adds to cart → cart shows item count in header
329
- - User checks out → payment form with saved addresses
330
-
331
- ### **User Feedback and States**
332
- Document what users see in different states:
333
-
334
- **Success States:**
335
- - Registration successful → welcome message with next steps
336
- - Order placed → confirmation with order number and tracking
337
- - Payment processed → receipt with download option
338
-
339
- **Error States:**
340
- - Login failed → error message with "Forgot password?" link
341
- - Out of stock → "Notify when available" option
342
- - Payment declined → retry form with error explanation
343
-
344
- **Loading States:**
345
- - Page loading → skeleton screens matching final layout
346
- - Form submitting → disabled inputs with progress indicator
347
- - Image loading → placeholder with smooth transition
348
-
349
- ### **User Interactions by Role**
350
- Document interactions for different user types:
351
-
352
- **Guest Users:**
353
- - Can browse products and read reviews
354
- - Can add items to cart (requires registration to checkout)
355
- - Can view help documentation and contact support
356
-
357
- **Registered Users:**
358
- - Can save payment methods and addresses
359
- - Can view order history and reorder items
360
- - Can update profile and preferences
361
- - Can leave reviews and ratings
362
-
363
- **Admin Users:**
364
- - Can manage products and inventory
365
- - Can view user analytics and reports
366
- - Can process refunds and handle support
367
- - Can update site content and settings
368
- 6. **Security Features** - Authentication, authorization, and data protection
369
- 7. **Performance Features** - Optimization and scalability features
370
- 8. **Accessibility Features** - WCAG compliance and inclusive design
371
-
372
- For each feature, include:
373
- - Feature name and description
374
- - User value proposition
375
- - Acceptance criteria
376
- - Priority level (High/Medium/Low)
377
- - Dependencies on other features
378
-
379
- Format the output as a well-structured markdown document with clear sections and bullet points.`;
380
- }
381
- buildUserFlowsPrompt(contextContent) {
382
- return `You are a user experience researcher documenting every user interaction and system response for a web application.
383
-
384
- ${contextContent
385
- ? `Project Context: ${contextContent}`
386
- : "Generate user interaction flows for a modern web application."}
387
-
388
- Create comprehensive user-centric flow documentation that captures every user interaction:
389
-
390
- ## 🎯 **User Interaction Flow Documentation**
391
-
392
- ### **Document Every User Action → System Response**
393
-
394
- **❌ Don't write technical flows:**
395
- - User navigates to login page
396
- - System validates credentials
397
- - User is redirected
398
-
399
- **✅ Write complete user interactions:**
400
- - User clicks "Login" button in navigation → login form appears with email and password fields
401
- - User enters email and clicks "Continue" → password field appears with "Show/Hide" toggle
402
- - User enters password and clicks "Sign In" → loading spinner shows for 2 seconds
403
- - User sees error message "Invalid credentials" with "Forgot password?" link → can click link to reset password
404
- - User clicks "Forgot password?" → reset form appears with email field and "Send reset link" button
405
- - User enters email and clicks "Send reset link" → success message "Check your email for reset instructions"
406
-
407
- ### **Complete User Journey Documentation**
408
- Document every step users take and what they see:
409
-
410
- 1. **Homepage Interaction Flow**
411
- - User visits homepage → sees hero section with "Get Started" button
412
- - User clicks "Get Started" → registration form slides in from right
413
- - User sees form with name, email, password fields → each field has validation
414
- - User fills out form with valid data → "Create Account" button becomes enabled
415
- - User clicks "Create Account" → loading state with "Creating your account..."
416
- - User sees success message "Account created! Please check your email to verify"
417
-
418
- 2. **Product Browsing Flow**
419
- - User visits products page → sees filter sidebar and product grid
420
- - User clicks category filter → products update instantly with smooth animation
421
- - User searches for "wireless headphones" → search results appear with suggestions
422
- - User clicks on product image → product detail page loads with image gallery
423
- - User clicks "Add to Cart" → cart icon in header shows "1" and success toast appears
424
- - User clicks cart icon → cart dropdown opens showing added item with quantity controls
425
-
426
- 3. **Checkout Process Flow**
427
- - User clicks "Checkout" → shipping address form appears with saved addresses
428
- - User selects address or fills new one → payment method selection appears
429
- - User chooses payment method → payment form loads with security indicators
430
- - User enters payment details → order summary updates with totals and fees
431
- - User clicks "Complete Order" → processing animation with progress steps
432
- - User sees order confirmation → with order number, tracking info, and "Download receipt" button
433
-
434
- ### **User Feedback Documentation**
435
- Document what users see in every state:
436
-
437
- **Success Feedback:**
438
- - Form submitted successfully → green checkmark with "Success!" message
439
- - Item added to cart → toast notification "Added to cart" with item name
440
- - Order completed → confetti animation with "Order confirmed!" message
441
- - Email sent → blue info banner "Check your email for next steps"
442
-
443
- **Error Feedback:**
444
- - Invalid email format → red error under field "Please enter a valid email"
445
- - Network error → retry banner "Connection lost. Please check your internet"
446
- - Payment failed → error card "Payment declined. Please try another card"
447
- - Session expired → redirect to login with "Please log in again" message
448
-
449
- **Loading Feedback:**
450
- - Page loading → skeleton screens matching the final layout
451
- - Form submitting → disabled inputs with pulsing "Processing..." button
452
- - Image loading → blur placeholder that sharpens when loaded
453
- - Search loading → "Searching..." with animated dots
454
-
455
- ### **User Decision Points**
456
- Document where users make choices and what happens:
457
-
458
- **Navigation Choices:**
459
- - User clicks "Products" → product catalog loads with filters visible
460
- - User clicks "Categories" → category page with subcategories and breadcrumbs
461
- - User clicks "Profile" → account settings with tabs for different sections
462
- - User clicks "Help" → help center with search and popular topics
463
-
464
- **Feature Choices:**
465
- - User can choose "Express checkout" → skips shipping form and uses defaults
466
- - User can select "Guest checkout" → creates account automatically after purchase
467
- - User can choose "Save for later" → item moves to wishlist instead of cart
468
- - User can select "Notify me" → gets alerts when out-of-stock items return
469
-
470
- **Preference Choices:**
471
- - User can toggle "Dark mode" → entire interface switches theme instantly
472
- - User can select "Language" → content translates with loading indicator
473
- - User can choose "Notifications" → settings panel with granular options
474
- - User can set "Privacy" → different levels affect what data is collected
475
-
476
- ### **User Error Recovery**
477
- Document how users recover from mistakes:
478
-
479
- **Input Errors:**
480
- - User enters invalid email → field highlights red with helpful message
481
- - User leaves required field empty → "This field is required" appears on blur
482
- - User enters weak password → strength meter shows with improvement tips
483
- - User selects invalid date → calendar widget shows available dates
484
-
485
- **System Errors:**
486
- - Server error during save → retry button with "Try again" and exponential backoff
487
- - Network timeout → offline banner with "Reconnecting..." and auto-retry
488
- - File upload fails → drag-and-drop area shows "Upload failed. Try again?"
489
- - Payment processing error → clear error message with support contact info
490
-
491
- **User Actions:**
492
- - User can click "Cancel" at any time → confirmation dialog "Discard changes?"
493
- - User can use "Back" button → returns to previous state without data loss
494
- - User can click "Help" icons → contextual help appears without leaving flow
495
- - User can contact support → chat widget opens with conversation context
496
-
497
- Format the output as a well-structured markdown document with clear sections and numbered steps.`;
498
- }
499
- buildEdgeCasesPrompt(contextContent) {
500
- return `You are a user experience researcher documenting error scenarios and edge cases from the user's perspective.
501
-
502
- ${contextContent
503
- ? `Project Context: ${contextContent}`
504
- : "Generate user error scenarios for a modern web application."}
505
-
506
- Create comprehensive user-centric error documentation that captures what users experience when things go wrong:
507
-
508
- ## 🎯 **User-Centric Error Scenarios Documentation**
509
-
510
- ### **Document What Users See When Errors Happen**
511
-
512
- **❌ Don't write technical edge cases:**
513
- - Network timeout after 30 seconds
514
- - Invalid input validation failure
515
- - Database connection error
516
-
517
- **✅ Write user experiences:**
518
- - User clicks "Save" → sees "Saving..." for 5 seconds → gets "Connection lost. Please check your internet" message
519
- - User enters email without @ → field turns red → "Please enter a valid email address" appears below field
520
- - User tries to login with wrong password → "Invalid credentials" message appears → "Forgot password?" link becomes clickable
521
-
522
- ### **User Error Recovery Documentation**
523
- Document how users recover from different error scenarios:
524
-
525
- 1. **Network Issues**
526
- - User clicks "Submit form" → sees loading spinner → connection drops
527
- - User sees "Connection lost" banner with "Reconnecting..." message
528
- - After 10 seconds, user sees "Connection restored" with auto-retry
529
- - User can click "Retry now" to manually retry or "Try again later" to save draft
530
-
531
- 2. **Input Validation Errors**
532
- - User enters phone number "123" → field highlights red → "Phone number must be at least 10 digits"
533
- - User leaves required field empty → clicks "Next" → form scrolls to empty field with red border
534
- - User enters password "123" → strength meter shows red → "Password must be at least 8 characters"
535
- - User enters mismatched passwords → confirmation field shows "Passwords don't match"
536
-
537
- 3. **Authentication Errors**
538
- - User clicks "Sign In" → loading spinner appears → "Invalid email or password" message shows
539
- - User sees "Forgot password?" link → clicks it → reset form loads with email field
540
- - User enters unregistered email for password reset → "No account found with that email" appears
541
- - User enters registered email → "Reset instructions sent" with "Check your email" message
542
-
543
- 4. **Payment Errors**
544
- - User clicks "Complete payment" → processing animation starts → "Payment declined" message appears
545
- - User sees "Please try another payment method" with card form → can select saved cards or add new
546
- - User enters expired card → "Card expired. Please use a different card" with date validation
547
- - User enters insufficient funds → "Insufficient funds" with suggestion to use different payment method
548
-
549
- 5. **Data Loading Errors**
550
- - User opens product page → sees skeleton loading → "Failed to load product information" message
551
- - User clicks "Load more" → loading spinner appears → "Connection timeout. Try again?" message
552
- - User searches for products → search bar shows "Searching..." → "No results found" with suggestions
553
- - User opens cart → sees "Loading cart..." → "Your cart is empty" or "Failed to load cart items"
554
-
555
- 6. **File Upload Errors**
556
- - User drags file to upload area → sees "Uploading..." → "File too large (max 10MB)" message
557
- - User selects unsupported file type → "Unsupported file type. Please use JPG, PNG, or PDF"
558
- - User tries to upload during network issue → "Upload failed due to connection issues" with retry
559
- - User uploads corrupted file → "File appears to be corrupted. Please try again"
560
-
561
- 7. **Session Management Errors**
562
- - User tries to access protected page → sees "Session expired. Please log in again" modal
563
- - User clicks "Stay logged in" → redirected to login form with "Re-login required" message
564
- - User logs in from new device → sees "Login from unrecognized device" with security options
565
- - User has multiple tabs open → one tab shows "Account accessed from another location"
566
-
567
- 8. **Browser/Device Compatibility**
568
- - User on old browser → sees "Your browser is not supported. Please update to latest version"
569
- - User on mobile device → sees "This feature works best on desktop" with mobile-optimized version
570
- - User with JavaScript disabled → sees "JavaScript required for this feature to work"
571
- - User with slow connection → sees "Loading slowly? Try our mobile app for better performance"
572
-
573
- 9. **Business Logic Errors**
574
- - User tries to buy out-of-stock item → sees "Out of stock" with "Notify when available" option
575
- - User applies expired coupon → sees "Coupon expired" with suggestion to use current offers
576
- - User tries to access admin area without permission → sees "Access denied" with contact info
577
- - User reaches usage limits → sees "You've reached your monthly limit" with upgrade options
578
-
579
- 10. **Third-Party Integration Errors**
580
- - User tries to login with Google → sees "Google login temporarily unavailable" with email option
581
- - User pays with PayPal → sees "PayPal service unavailable" with alternative payment methods
582
- - User shares on social media → sees "Unable to connect to [platform]" with manual share option
583
- - User gets email notifications → sees "Notification service issue" with settings to check preferences
584
-
585
- ### **User Feedback and Recovery Patterns**
586
- Document consistent patterns for error handling:
587
-
588
- **Error Message Guidelines:**
589
- - Always explain what went wrong in user-friendly language
590
- - Suggest next steps or alternatives when possible
591
- - Provide contact information for complex issues
592
- - Use consistent visual styling (red borders, warning icons)
593
-
594
- **Recovery Action Guidelines:**
595
- - Offer retry options with clear labels ("Try again", "Retry", "Refresh")
596
- - Provide alternative paths when primary action fails
597
- - Save user progress when possible (drafts, partial forms)
598
- - Allow users to go back without losing data
599
-
600
- **Loading State Guidelines:**
601
- - Show progress indicators for long operations
602
- - Disable inputs during processing to prevent double-submission
603
- - Provide cancel options for non-critical operations
604
- - Use skeleton screens that match final layout
605
-
606
- **Help and Support Guidelines:**
607
- - Contextual help available without leaving current flow
608
- - Clear escalation paths for complex issues
609
- - Self-service options before contacting support
610
- - Preserve context when transferring to support
611
-
612
- Format the output as a well-structured markdown document with clear sections and detailed scenarios.`;
613
- }
614
- buildTechnicalSpecsPrompt(contextContent) {
615
- return `You are a user experience researcher documenting technical implementation details from the user's perspective.
616
-
617
- ${contextContent
618
- ? `Project Context: ${contextContent}`
619
- : "Generate technical implementation details for a modern web application."}
620
-
621
- Create user-centric technical documentation that explains how the system works behind the scenes to support user interactions:
622
-
623
- ## 🎯 **User-Centric Technical Implementation Documentation**
624
-
625
- ### **Document Technical Details That Support User Experiences**
626
-
627
- **❌ Don't write abstract technical specs:**
628
- - React 18 with Next.js 14
629
- - PostgreSQL database with Prisma ORM
630
- - JWT authentication with refresh tokens
631
-
632
- **✅ Write user-focused technical details:**
633
- - Pages load instantly with React Server Components → users see content immediately without loading delays
634
- - Database queries optimized for product catalog → users can browse thousands of products with instant search
635
- - Authentication tokens automatically refreshed → users stay logged in even after browser restart
636
- - Images served via CDN → users see product photos instantly even on slow connections
637
-
638
- ### **User Performance Documentation**
639
- Document how technical choices affect user experience:
640
-
641
- 1. **Loading Performance**
642
- - Homepage loads in <2 seconds → users see hero content immediately
643
- - Product images load progressively → users see low-res preview first, then full quality
644
- - Search results appear in <100ms → users get instant feedback as they type
645
- - Page transitions use client-side routing → users navigate without full page reloads
646
-
647
- 2. **Responsive Design Implementation**
648
- - CSS Grid and Flexbox for flexible layouts → users see properly aligned content on any screen size
649
- - Mobile-first responsive breakpoints → users get optimized experience on phones and tablets
650
- - Touch-friendly interaction targets → users can easily tap buttons and links on mobile
651
- - Keyboard navigation support → users can navigate entirely with keyboard if needed
652
-
653
- 3. **Accessibility Implementation**
654
- - ARIA labels and semantic HTML → screen readers announce content correctly to users
655
- - High contrast color schemes → users with visual impairments can read all text
656
- - Keyboard shortcuts for common actions → power users can navigate efficiently
657
- - Focus management for complex interactions → users never lose their place in forms
658
-
659
- 4. **Error Handling Implementation**
660
- - Graceful degradation for failed requests → users see helpful messages instead of blank pages
661
- - Retry mechanisms with exponential backoff → users get automatic recovery from temporary issues
662
- - Offline detection and messaging → users understand when connection issues occur
663
- - Fallback content for missing data → users see alternative content when primary data fails to load
664
-
665
- 5. **Security Implementation**
666
- - HTTPS encryption for all data → users' personal information is protected in transit
667
- - CSRF protection on forms → users' actions are protected from cross-site attacks
668
- - XSS prevention measures → users' data is safe from script injection attacks
669
- - Secure password hashing → users' credentials are protected even if database is compromised
670
-
671
- 6. **Data Management Implementation**
672
- - Real-time data synchronization → users see live updates without refreshing
673
- - Optimistic UI updates → users see immediate feedback while server processes requests
674
- - Conflict resolution for concurrent edits → users' changes are preserved when multiple people edit
675
- - Data validation on client and server → users get immediate feedback on invalid input
676
-
677
- 7. **Integration Implementation**
678
- - Payment processor integration → users can complete purchases securely
679
- - Email service integration → users receive order confirmations and notifications
680
- - Analytics tracking → user behavior is measured to improve experience
681
- - Social media integration → users can share products with their networks
682
-
683
- 8. **Performance Optimization**
684
- - Code splitting for faster loading → users only download code they need for current page
685
- - Image optimization and lazy loading → users see optimized images without waiting
686
- - Caching strategies for repeat visits → returning users get even faster experience
687
- - Bundle optimization → users download minimal JavaScript for fast execution
688
-
689
- 9. **Monitoring and Analytics**
690
- - User interaction tracking → understand how users navigate and where they get stuck
691
- - Performance monitoring → identify slow pages and optimize user experience
692
- - Error tracking → quickly identify and fix issues affecting users
693
- - A/B testing framework → test different approaches to improve user experience
694
-
695
- 10. **Scalability Considerations**
696
- - Horizontal scaling capabilities → handle traffic spikes without user impact
697
- - Database optimization → maintain performance as user base grows
698
- - CDN integration → serve content quickly to users worldwide
699
- - Rate limiting protection → prevent abuse while maintaining service for legitimate users
700
-
701
- ### **Technical Implementation Guidelines**
702
- Document how technical choices support user needs:
703
-
704
- **User Experience Priority:**
705
- - Always prioritize user experience over technical complexity
706
- - Choose technologies that enable smooth, fast user interactions
707
- - Implement graceful fallbacks for when things go wrong
708
- - Monitor real user impact of technical changes
709
-
710
- **Performance First:**
711
- - Optimize for perceived performance (what users actually experience)
712
- - Use loading states and progress indicators
713
- - Implement skeleton screens that match final layouts
714
- - Cache intelligently to improve repeat visit performance
715
-
716
- **Accessibility by Design:**
717
- - Build accessibility into components from the start
718
- - Test with screen readers and keyboard navigation
719
- - Follow WCAG guidelines for color contrast and interaction
720
- - Consider users with different abilities and devices
721
-
722
- **Error Resilience:**
723
- - Implement comprehensive error handling
724
- - Provide clear recovery paths for users
725
- - Use retry mechanisms with user-friendly messaging
726
- - Log errors for developers while showing helpful messages to users
727
-
728
- **Security User-Focused:**
729
- - Protect user data without compromising usability
730
- - Use security measures that are invisible to users
731
- - Provide clear security status indicators
732
- - Balance security with user convenience
733
-
734
- Format the output as a well-structured markdown document with clear sections and detailed scenarios.`;
735
- }
736
- formatFeaturesContent(response) {
737
- return `# User-Centric Features Documentation
738
-
739
- ${response}
740
-
741
- ---
742
- *Generated by MyContext CLI - AI-powered component generation platform*
743
- *Last updated: ${new Date().toISOString()}*
744
- `;
745
- }
746
- formatUserFlowsContent(response) {
747
- return `# User Interaction Flows Documentation
748
-
749
- ${response}
750
-
751
- ---
752
- *Generated by MyContext CLI - AI-powered component generation platform*
753
- *Last updated: ${new Date().toISOString()}*
754
- `;
755
- }
756
- formatEdgeCasesContent(response) {
757
- return `# User Error Scenarios and Recovery Documentation
758
-
759
- ${response}
760
-
761
- ---
762
- *Generated by MyContext CLI - AI-powered component generation platform*
763
- *Last updated: ${new Date().toISOString()}*
764
- `;
765
- }
766
- formatTechnicalSpecsContent(response) {
767
- return `# User-Centric Technical Implementation Documentation
768
-
769
- ${response}
770
-
771
- ---
772
- *Generated by MyContext CLI - AI-powered component generation platform*
773
- *Last updated: ${new Date().toISOString()}*
774
- `;
775
- }
776
- /**
777
- * Get context content for generation - prefer PRD over description
778
- */
779
- async getContextForGeneration(contextDir, fallbackDescription) {
780
- // First, try to read from 01-prd.md
781
- const prdPath = path_1.default.join(contextDir, "01-prd.md");
782
- if (await fs.pathExists(prdPath)) {
783
- try {
784
- const prdContent = await fs.readFile(prdPath, "utf8");
785
- // Check if PRD is just a template/starter sample
786
- if (this.isTemplatePRD(prdContent)) {
787
- // If we have a fallback description, check if it's substantial
788
- if (fallbackDescription) {
789
- const isSubstantial = fallbackDescription.trim().length > 100 &&
790
- fallbackDescription.split(/\s+/).length > 15;
791
- if (isSubstantial) {
792
- console.log(chalk_1.default.blue("📝 PRD is a template, but provided description is substantial. Using it as context."));
793
- return fallbackDescription;
794
- }
795
- else {
796
- console.log(chalk_1.default.yellow("⚠️ Description provided is too brief to seed a high-quality PRD."));
797
- console.log(chalk_1.default.gray(" Please provide more detail (e.g., features, user flows, tech stack)."));
798
- }
799
- }
800
- console.log(chalk_1.default.yellow("⚠️ PRD is a template - please update with your project details first"));
801
- console.log(chalk_1.default.gray(` Edit: ${prdPath.replace(process.cwd(), ".")}`));
802
- console.log(chalk_1.default.gray(" Then run: mycontext generate-context-files"));
803
- // Exit gracefully instead of throwing error
804
- process.exit(0);
805
- }
806
- else {
807
- console.log(chalk_1.default.blue("📖 Using existing PRD as context for context files generation"));
808
- return prdContent;
809
- }
810
- }
811
- catch (error) {
812
- if (error instanceof Error && error.message.includes("template")) {
813
- throw error; // Re-throw template error
814
- }
815
- console.log(chalk_1.default.yellow("⚠️ Could not read PRD file, falling back to description"));
816
- }
817
- }
818
- // Fallback to description if no PRD exists
819
- if (fallbackDescription) {
820
- console.log(chalk_1.default.blue("📝 Using project description as context"));
821
- return fallbackDescription;
822
- }
823
- // No context available - tell user to create PRD first
824
- console.log(chalk_1.default.red("❌ No PRD found!"));
825
- console.log(chalk_1.default.yellow("Please create a PRD first:"));
826
- console.log(chalk_1.default.gray(" 1. Edit .mycontext/01-prd.md with your project details"));
827
- console.log(chalk_1.default.gray(" 2. Or run 'mycontext generate context --full' to create PRD + context files"));
828
- console.log(chalk_1.default.gray(" 3. Or use --description flag: mycontext generate-context-files --description 'Your project'"));
829
- throw new Error("No PRD found. Please create a PRD file first or use --description flag.");
830
- }
831
- /**
832
- * Check if PRD content is just a template/starter sample
833
- */
834
- isTemplatePRD(content) {
835
- const templateIndicators = [
836
- "MyContext project",
837
- "Replace this with your actual project description",
838
- "TODO: Add your project details",
839
- "This is a template",
840
- "Sample project",
841
- "Example project",
842
- "Your project description here",
843
- "Project Name: [Your Project Name]",
844
- "Description: [Your project description]",
845
- "## Project Overview\n\n[Add your project overview here]",
846
- "## Requirements\n\n[Add your requirements here]",
847
- "## Features\n\n[Add your features here]",
848
- "## Technical Specifications\n\n[Add your technical specs here]",
849
- ];
850
- // Check if content contains multiple template indicators
851
- const templateMatches = templateIndicators.filter((indicator) => content.toLowerCase().includes(indicator.toLowerCase()));
852
- // If more than 2 template indicators are found, it's likely a template
853
- if (templateMatches.length >= 2) {
854
- return true;
855
- }
856
- // Check if content is very short (likely a template)
857
- if (content.trim().length < 200) {
858
- return true;
859
- }
860
- // Check if content is mostly placeholder text
861
- const placeholderRatio = (content.match(/\[.*?\]/g) || []).length /
862
- (content.split(" ").length || 1);
863
- if (placeholderRatio > 0.1) {
864
- // More than 10% placeholders
865
- return true;
866
- }
867
- return false;
868
- }
869
- }
870
- exports.GenerateContextFilesCommand = GenerateContextFilesCommand;
871
- //# sourceMappingURL=generate-context-files.js.map