fraim-framework 2.0.44 → 2.0.45

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 (72) hide show
  1. package/bin/fraim.js +1 -1
  2. package/dist/registry/ai-manager-rules/design-phases/design-completeness-review.md +73 -0
  3. package/dist/registry/ai-manager-rules/design-phases/design-design.md +145 -0
  4. package/dist/registry/ai-manager-rules/design-phases/design.md +108 -0
  5. package/dist/registry/ai-manager-rules/design-phases/finalize.md +60 -0
  6. package/dist/registry/ai-manager-rules/design-phases/validate.md +125 -0
  7. package/dist/registry/ai-manager-rules/implement-phases/code.md +323 -0
  8. package/dist/registry/ai-manager-rules/implement-phases/completeness-review.md +94 -0
  9. package/dist/registry/ai-manager-rules/implement-phases/finalize.md +177 -0
  10. package/dist/registry/ai-manager-rules/implement-phases/implement-code.md +286 -0
  11. package/dist/registry/ai-manager-rules/implement-phases/implement-completeness-review.md +120 -0
  12. package/dist/registry/ai-manager-rules/implement-phases/implement-regression.md +173 -0
  13. package/dist/registry/ai-manager-rules/implement-phases/implement-repro.md +104 -0
  14. package/dist/registry/ai-manager-rules/implement-phases/implement-scoping.md +100 -0
  15. package/dist/registry/ai-manager-rules/implement-phases/implement-smoke.md +230 -0
  16. package/dist/registry/ai-manager-rules/implement-phases/implement-spike.md +121 -0
  17. package/dist/registry/ai-manager-rules/implement-phases/implement-validate.md +371 -0
  18. package/dist/registry/ai-manager-rules/implement-phases/quality-review.md +304 -0
  19. package/dist/registry/ai-manager-rules/implement-phases/regression.md +159 -0
  20. package/dist/registry/ai-manager-rules/implement-phases/repro.md +101 -0
  21. package/dist/registry/ai-manager-rules/implement-phases/scoping.md +93 -0
  22. package/dist/registry/ai-manager-rules/implement-phases/smoke.md +225 -0
  23. package/dist/registry/ai-manager-rules/implement-phases/spike.md +118 -0
  24. package/dist/registry/ai-manager-rules/implement-phases/validate.md +347 -0
  25. package/dist/registry/ai-manager-rules/shared-phases/finalize.md +169 -0
  26. package/dist/registry/ai-manager-rules/shared-phases/submit-pr.md +202 -0
  27. package/dist/registry/ai-manager-rules/shared-phases/wait-for-pr-review.md +170 -0
  28. package/dist/registry/ai-manager-rules/spec-phases/finalize.md +60 -0
  29. package/dist/registry/ai-manager-rules/spec-phases/spec-completeness-review.md +66 -0
  30. package/dist/registry/ai-manager-rules/spec-phases/spec-spec.md +139 -0
  31. package/dist/registry/ai-manager-rules/spec-phases/spec.md +102 -0
  32. package/dist/registry/ai-manager-rules/spec-phases/validate.md +118 -0
  33. package/dist/src/ai-manager/ai-manager.js +380 -119
  34. package/dist/src/ai-manager/evidence-validator.js +309 -0
  35. package/dist/src/ai-manager/phase-flow.js +244 -0
  36. package/dist/src/ai-manager/types.js +5 -0
  37. package/dist/src/fraim-mcp-server.js +45 -153
  38. package/dist/src/static-website-middleware.js +75 -0
  39. package/dist/tests/test-ai-coach-edge-cases.js +415 -0
  40. package/dist/tests/test-ai-coach-mcp-integration.js +432 -0
  41. package/dist/tests/test-ai-coach-performance.js +328 -0
  42. package/dist/tests/test-ai-coach-phase-content.js +264 -0
  43. package/dist/tests/test-ai-coach-workflows.js +487 -0
  44. package/dist/tests/test-ai-manager-phase-protocol.js +147 -0
  45. package/dist/tests/test-ai-manager.js +60 -71
  46. package/dist/tests/test-evidence-validation.js +221 -0
  47. package/dist/tests/test-mcp-lifecycle-methods.js +18 -23
  48. package/dist/tests/test-pr-review-integration.js +1 -0
  49. package/dist/tests/test-pr-review-workflow.js +299 -0
  50. package/dist/website/.nojekyll +0 -0
  51. package/dist/website/404.html +101 -0
  52. package/dist/website/CNAME +1 -0
  53. package/dist/website/README.md +22 -0
  54. package/dist/website/demo.html +604 -0
  55. package/dist/website/images/.gitkeep +1 -0
  56. package/dist/website/images/fraim-logo.png +0 -0
  57. package/dist/website/index.html +290 -0
  58. package/dist/website/pricing.html +414 -0
  59. package/dist/website/script.js +55 -0
  60. package/dist/website/styles.css +2647 -0
  61. package/package.json +2 -1
  62. package/registry/agent-guardrails.md +1 -1
  63. package/registry/stubs/workflows/brainstorming/blue-sky-brainstorming.md +11 -0
  64. package/registry/stubs/workflows/brainstorming/codebase-brainstorming.md +11 -0
  65. package/registry/stubs/workflows/compliance/detect-compliance-requirements.md +11 -0
  66. package/registry/stubs/workflows/compliance/generate-audit-evidence.md +11 -0
  67. package/registry/stubs/workflows/learning/synthesize-learnings.md +11 -0
  68. package/registry/stubs/workflows/legal/nda.md +11 -0
  69. package/registry/stubs/workflows/legal/patent-filing.md +11 -0
  70. package/registry/stubs/workflows/legal/trademark-filing.md +11 -0
  71. package/registry/stubs/workflows/product-building/design.md +1 -1
  72. package/registry/stubs/workflows/product-building/implement.md +1 -2
@@ -1,162 +1,423 @@
1
1
  "use strict";
2
2
  /**
3
- * Simplified AI Manager
3
+ * AI Coach - Provides guidance and coaching for implementation phases
4
4
  *
5
- * Single AI manager integrated into fraim-mcp-server that reads validation rules
6
- * from pre-defined JSON files and provides structured review instructions.
5
+ * Handles coaching requests from agents, provides phase instructions,
6
+ * completion messages, and help when agents encounter challenges.
7
7
  */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
8
41
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.AIManager = void 0;
42
+ exports.AICoach = void 0;
10
43
  const fs_1 = require("fs");
11
- const path_1 = require("path");
12
- class AIManager {
13
- constructor(rulesPath) {
14
- // Default to rules directory - server-side only, not sent to client
15
- this.rulesPath = rulesPath || (0, path_1.join)(__dirname, '..', '..', 'registry', 'ai-manager-rules');
44
+ const phase_flow_js_1 = require("./phase-flow.js");
45
+ class AICoach {
46
+ constructor(fileIndex) {
47
+ this.fileIndex = fileIndex;
16
48
  }
17
49
  /**
18
- * Generate review instructions for a workflow phase
50
+ * Handle coaching request from agent
19
51
  */
20
- generateReviewInstructions(context) {
21
- console.log(`🤖 AI Manager: Generating review instructions for ${context.workflowType} phase`);
22
- const rules = this.loadWorkflowRules(context.workflowType);
23
- if (!rules) {
24
- throw new Error(`No rules found for workflow type: ${context.workflowType}`);
52
+ async handleCoachingRequest(args) {
53
+ // console.log(`🤖 AI Coach: Providing guidance for ${args.workflowType} workflow, phase: ${args.currentPhase}, status: ${args.status}`);
54
+ // Validate required parameters
55
+ const requiredParams = ['workflowType', 'currentPhase', 'status'];
56
+ const missingParams = requiredParams.filter(param => !args[param]);
57
+ if (missingParams.length > 0) {
58
+ throw new Error(`Missing required parameters: ${missingParams.join(', ')}`);
59
+ }
60
+ // Handle missing or empty issue number gracefully
61
+ if (!args.issueNumber || args.issueNumber.trim() === '') {
62
+ return `⚠️ **Issue Number Missing**
63
+
64
+ Please provide a valid issue number to get specific guidance for your workflow.
65
+
66
+ **Current Request:**
67
+ - Workflow: ${args.workflowType}
68
+ - Phase: ${args.currentPhase}
69
+ - Status: ${args.status}
70
+
71
+ **Next Steps:**
72
+ 1. Identify the GitHub issue number you're working on
73
+ 2. Include the issue number in your coaching request
74
+ 3. Re-request guidance with complete information
75
+
76
+ Example: \`seekCoachingOnNextStep({ workflowType: "${args.workflowType}", issueNumber: "123", currentPhase: "${args.currentPhase}", status: "${args.status}" })\``;
77
+ }
78
+ // Validate workflow type
79
+ const validWorkflowTypes = ['implement', 'spec', 'design', 'test'];
80
+ if (!validWorkflowTypes.includes(args.workflowType)) {
81
+ throw new Error(`Invalid workflow type: ${args.workflowType}. Valid types: ${validWorkflowTypes.join(', ')}`);
82
+ }
83
+ // Validate phase for workflow type
84
+ const issueType = this.extractIssueType(args.findings, args.evidence);
85
+ if (!(0, phase_flow_js_1.isPhaseValidForWorkflow)(args.currentPhase, args.workflowType, issueType)) {
86
+ // Special handling for implement workflow to provide better error messages
87
+ if (args.workflowType === 'implement') {
88
+ const hasIssueType = args.findings?.issueType || args.evidence?.issueType;
89
+ if (!hasIssueType) {
90
+ throw new Error(`❌ Missing Required Field: issueType
91
+
92
+ For implement workflow, you MUST specify issueType in your findings object:
93
+
94
+ **Correct format:**
95
+ \`\`\`javascript
96
+ seekCoachingOnNextStep({
97
+ workflowType: "implement",
98
+ issueNumber: "${args.issueNumber}",
99
+ currentPhase: "${args.currentPhase}",
100
+ status: "${args.status}",
101
+ findings: {
102
+ issueType: "bug" // or "feature" - REQUIRED!
103
+ },
104
+ evidence: {
105
+ // your evidence here
106
+ }
107
+ })
108
+ \`\`\`
109
+
110
+ **Valid phases by issue type:**
111
+ - **Bugs**: implement-scoping → implement-repro → implement-code → implement-validate → implement-smoke → implement-regression → implement-completeness-review → submit-pr → wait-for-pr-review
112
+ - **Features**: implement-scoping → implement-spike → implement-code → implement-validate → implement-smoke → implement-regression → implement-completeness-review → submit-pr → wait-for-pr-review`);
113
+ }
114
+ else {
115
+ throw new Error(`❌ Invalid Phase for Issue Type
116
+
117
+ Phase "${args.currentPhase}" is not valid for ${issueType} issues.
118
+
119
+ **Valid phases for ${issueType}s:**
120
+ ${this.getValidPhasesForIssueType(issueType).join(' → ')}
121
+
122
+ **Your current request:**
123
+ - Workflow: ${args.workflowType}
124
+ - Issue Type: ${issueType}
125
+ - Phase: ${args.currentPhase} ❌
126
+
127
+ **Suggestion:** Use the correct phase name from the valid flow above.`);
128
+ }
129
+ }
130
+ else {
131
+ throw new Error(`Invalid phase "${args.currentPhase}" for workflow type "${args.workflowType}"`);
132
+ }
133
+ }
134
+ if (args.status === 'complete') {
135
+ return await this.generateCompletionMessage(args);
136
+ }
137
+ else if (args.status === 'incomplete') {
138
+ return await this.generateHelpMessage(args);
139
+ }
140
+ else if (args.status === 'failure') {
141
+ return await this.generateFailureMessage(args);
142
+ }
143
+ else {
144
+ return await this.getPhaseInstructions(args.currentPhase, args.workflowType);
25
145
  }
26
- return this.formatReviewInstructions(rules, context);
27
146
  }
28
147
  /**
29
- * Evaluate agent's review report and provide decision
148
+ * Generate completion message for completed phases
30
149
  */
31
- evaluateReport(report, context) {
32
- console.log(`🤖 AI Manager: Evaluating review report for ${context.workflowType} phase`);
33
- const iterationCount = report.iterationCount || 1;
34
- const maxIterations = 3;
35
- if (report.pass) {
36
- return {
37
- action: 'PROCEED',
38
- message: 'Review passed. Ready to submit PR to human for review.',
39
- nextSteps: [
40
- 'Update issue status to "status:needs-review"',
41
- 'Remove "status:wip" label',
42
- 'Include complete review results in evidence document',
43
- 'Submit PR for human review with evidence'
44
- ],
45
- iterationCount
46
- };
150
+ async generateCompletionMessage(args) {
151
+ // Handle workflow completion for wait-for-pr-review phase when PR is approved
152
+ if (args.currentPhase === 'wait-for-pr-review') {
153
+ return `# 🎉 ${args.workflowType.charAt(0).toUpperCase() + args.workflowType.slice(1)} Complete!
154
+
155
+ **Congratulations!** You have successfully completed all ${args.workflowType} phases for issue #${args.issueNumber}.
156
+
157
+ ## 🏆 What You've Accomplished
158
+ ${this.getAccomplishmentsForWorkflow(args.workflowType)}
159
+
160
+ ## 📋 Final Evidence Summary
161
+ ${JSON.stringify(args.evidence || {}, null, 2)}
162
+
163
+ `;
47
164
  }
48
165
  else {
49
- // Check if max iterations reached
50
- if (iterationCount >= maxIterations) {
51
- return {
52
- action: 'ESCALATE',
53
- message: `Maximum iterations (${maxIterations}) reached. Escalating to human review despite failing validation.`,
54
- nextSteps: [
55
- 'Update issue status to "status:needs-review"',
56
- 'Add "ai-manager:max-iterations" label to indicate escalation reason',
57
- 'Include all iteration attempts and failure reasons in evidence document',
58
- 'Submit PR for human review with detailed iteration history',
59
- 'Human reviewer should focus on the recurring validation failures'
60
- ],
61
- iterationCount,
62
- maxIterationsReached: true
63
- };
64
- }
65
- else {
66
- return {
67
- action: 'ITERATE',
68
- message: `Review failed. Address the identified issues before proceeding. (Iteration ${iterationCount}/${maxIterations})`,
69
- nextSteps: [
70
- 'Fix all issues identified in the failure reasons',
71
- 'Re-run validation steps to verify fixes',
72
- `Request new review instructions with iterationCount: ${iterationCount + 1}`,
73
- 'Do not submit PR until review passes or max iterations reached'
74
- ],
75
- iterationCount
76
- };
166
+ // Determine next phase and provide its instructions
167
+ const issueType = this.extractIssueType(args.findings, args.evidence);
168
+ const nextPhase = (0, phase_flow_js_1.getNextPhase)(args.currentPhase, args.workflowType, issueType);
169
+ if (!nextPhase) {
170
+ return `# 🎉 Phase Complete!
171
+
172
+ **Phase:** ${args.currentPhase}
173
+ **Status:** Complete
174
+
175
+ Great work! You've completed the ${args.currentPhase} phase.
176
+
177
+ ## Evidence Summary
178
+ ${JSON.stringify(args.evidence || args.findings || {}, null, 2)}
179
+
180
+ ## 🚨 Error: No Next Phase Found
181
+ Unable to determine the next phase. This might indicate an issue with the phase flow logic.
182
+ Please check your workflow type and current phase.
183
+ `;
77
184
  }
185
+ // Get instructions for the next phase
186
+ const nextPhaseInstructions = await this.getPhaseInstructions(nextPhase, args.workflowType);
187
+ return `# 🎉 Phase Complete!
188
+
189
+ **Phase:** ${args.currentPhase}
190
+ **Status:** Complete
191
+
192
+ Great work! You've completed the ${args.currentPhase} phase.
193
+
194
+ ## Evidence Summary
195
+ ${JSON.stringify(args.evidence || args.findings || {}, null, 2)}
196
+
197
+ ## 🚀 Next Phase: ${nextPhase}
198
+
199
+ Here are the instructions for your next phase:
200
+
201
+ ---
202
+
203
+ ${nextPhaseInstructions}
204
+ `;
78
205
  }
79
206
  }
80
207
  /**
81
- * Load workflow rules from JSON file (server-side only)
208
+ * Get accomplishments list for a workflow type
82
209
  */
83
- loadWorkflowRules(workflowType) {
84
- const rulesFile = (0, path_1.join)(this.rulesPath, `${workflowType}.json`);
85
- if (!(0, fs_1.existsSync)(rulesFile)) {
86
- console.warn(`⚠️ No rules file found for workflow: ${workflowType} at ${rulesFile}`);
87
- return null;
210
+ getAccomplishmentsForWorkflow(workflowType) {
211
+ switch (workflowType) {
212
+ case 'implement':
213
+ return `- **Scoping**: Understood requirements and issue type
214
+ - ✅ **Repro/Spike**: Created reproduction test or validated technical approach
215
+ - ✅ **Implementation**: Built working solution with comprehensive tests
216
+ - ✅ **Validation**: Verified functionality through manual and automated testing
217
+ - ✅ **Smoke Tests**: Confirmed technical health (build, tests, git status)
218
+ - ✅ **Regression Tests**: Ensured bug fixes work or features have proper test coverage
219
+ - ✅ **Completeness Review**: Verified all design aspects implemented
220
+ - ✅ **Submit PR**: Prepared work for human review
221
+ - ✅ **PR Review**: Successfully completed code review process`;
222
+ case 'spec':
223
+ return `- ✅ **Specification**: Created comprehensive feature specification
224
+ - ✅ **Validation**: Verified spec completeness and quality
225
+ - ✅ **Submit PR**: Prepared specification for review
226
+ - ✅ **PR Review**: Successfully completed specification review process`;
227
+ case 'design':
228
+ return `- ✅ **Design**: Created technical design and architecture
229
+ - ✅ **Validation**: Verified design completeness and feasibility
230
+ - ✅ **Submit PR**: Prepared design for implementation phase
231
+ - ✅ **PR Review**: Successfully completed design review process`;
232
+ case 'test':
233
+ return `- ✅ **Testing**: Created comprehensive test suite
234
+ - ✅ **Validation**: Verified test coverage and quality
235
+ - ✅ **Submit PR**: Prepared tests for integration
236
+ - ✅ **PR Review**: Successfully completed test review process`;
237
+ default:
238
+ return `- ✅ **${workflowType}**: Completed all phases successfully
239
+ - ✅ **Validation**: Verified work quality and completeness
240
+ - ✅ **Submit PR**: Prepared work for review
241
+ - ✅ **PR Review**: Successfully completed review process`;
88
242
  }
89
- try {
90
- const content = (0, fs_1.readFileSync)(rulesFile, 'utf8');
91
- return JSON.parse(content);
243
+ }
244
+ /**
245
+ * Get valid phases for a specific issue type
246
+ */
247
+ getValidPhasesForIssueType(issueType) {
248
+ if (issueType === 'bug') {
249
+ return ['implement-scoping', 'implement-repro', 'implement-code', 'implement-validate', 'implement-smoke', 'implement-regression', 'implement-completeness-review', 'submit-pr', 'wait-for-pr-review'];
92
250
  }
93
- catch (error) {
94
- console.error(`❌ Error loading rules for ${workflowType}:`, error);
95
- return null;
251
+ else {
252
+ return ['implement-scoping', 'implement-spike', 'implement-code', 'implement-validate', 'implement-smoke', 'implement-regression', 'implement-completeness-review', 'submit-pr', 'wait-for-pr-review'];
253
+ }
254
+ }
255
+ /**
256
+ * Extract issue type from findings or evidence
257
+ */
258
+ extractIssueType(findings, evidence) {
259
+ // Try to get issue type from findings first
260
+ if (findings?.issueType) {
261
+ return findings.issueType;
262
+ }
263
+ // Try to get from evidence
264
+ if (evidence?.issueType) {
265
+ return evidence.issueType;
96
266
  }
267
+ // Default to feature if not specified
268
+ return 'feature';
97
269
  }
98
270
  /**
99
- * Format review instructions with proper template structure
271
+ * Generate failure message for failed phases
100
272
  */
101
- formatReviewInstructions(rules, context) {
102
- const instructions = `# AI Manager Review Instructions
273
+ async generateFailureMessage(args) {
274
+ // Standard failure handling for all phases
275
+ const issueType = this.extractIssueType(args.findings);
276
+ const { getPhaseOnFailure } = await Promise.resolve().then(() => __importStar(require('./phase-flow.js')));
277
+ const nextPhase = getPhaseOnFailure(args.currentPhase, args.workflowType, issueType);
278
+ const nextPhaseInstructions = await this.getPhaseInstructions(nextPhase, args.workflowType);
279
+ return `# ❌ Phase Failed
103
280
 
104
- ## Workflow: ${rules.workflowType.toUpperCase()}
105
- **Issue:** #${context.issueNumber}
106
- **Phase:** ${context.phase}
281
+ **Workflow:** ${args.workflowType}
282
+ **Failed Phase:** ${args.currentPhase}
283
+ **Issue:** ${args.issueNumber}
107
284
 
108
- ## Description
109
- ${rules.description}
285
+ ## Failure Details
286
+ ${args.findings ? JSON.stringify(args.findings, null, 2) : 'No specific failure details provided'}
110
287
 
111
- ## Iteration Tracking
112
- **IMPORTANT**: You must track your iteration count for this phase. This is your attempt number for this specific workflow phase (spec, implement, test, etc.).
288
+ ## 🚀 Next Phase: ${nextPhase}
113
289
 
114
- - **First attempt**: Use iterationCount: 1
115
- - **After first failure**: Use iterationCount: 2
116
- - **After second failure**: Use iterationCount: 3
117
- - **Maximum iterations**: 3 (after 3rd failure, work will be escalated to human review)
290
+ You'll now return to the **${nextPhase}** phase to address the issues.
118
291
 
119
- ## Validation Steps
120
- Complete each step below and evaluate whether you meet the pass criteria:
292
+ ---
121
293
 
122
- ${rules.validationRules.map(rule => `
123
- ### Step ${rule.step}: ${rule.description}
124
- ${rule.command ? `**Command:** \`${rule.command.replace('{issue_number}', context.issueNumber)}\`` : ''}
125
- **Pass Criteria:** ${rule.passCriteria}
126
- **Weight:** ${rule.weight.toUpperCase()}${rule.weight === 'blocking' ? ' (Must pass to proceed)' : ' (Should pass for quality)'}
127
- **Category:** ${rule.category}
128
- `).join('')}
294
+ ${nextPhaseInstructions}
129
295
 
130
- ## Grading Criteria
296
+ ---
131
297
 
132
- ### Pass Requirements
133
- ${rules.gradingCriteria.passRequirements.map(req => `- ${req}`).join('\n')}
298
+ ## Action Plan
299
+ 1. **Review the failure details above**
300
+ 2. **Follow the ${nextPhase} phase instructions**
301
+ 3. **Address the root cause of the failure**
302
+ 4. **Continue through the workflow**
303
+ `;
304
+ }
305
+ /**
306
+ * Generate help message for incomplete phases
307
+ */
308
+ async generateHelpMessage(args) {
309
+ // Standard help message for all phases
310
+ const phaseInstructions = await this.getPhaseInstructions(args.currentPhase, args.workflowType);
311
+ return `# 🤝 AI Coach Assistance
134
312
 
135
- ### Fail Requirements
136
- ${rules.gradingCriteria.failRequirements.map(req => `- ${req}`).join('\n')}
313
+ **Workflow:** ${args.workflowType}
314
+ **Phase:** ${args.currentPhase}
315
+ **Status:** Incomplete - Need Help
137
316
 
138
- ## Reporting Format
139
- ${rules.reportingFormat.instructions}
317
+ I understand you're encountering challenges with the ${args.currentPhase} phase. Let me provide you with the complete guidance for this phase.
140
318
 
141
- **Required Response Format:**
142
- \`\`\`json
143
- {
144
- "pass": true/false,
145
- "reasons": ["reason1", "reason2"], // Only required if pass=false
146
- "iterationCount": 1 // REQUIRED: Your current iteration number for this phase
147
- }
148
- \`\`\`
319
+ ## Issues You Mentioned
320
+ ${args.findings?.uncertainties && Array.isArray(args.findings.uncertainties) ?
321
+ args.findings.uncertainties.map((issue) => `- ${issue}`).join('\n') :
322
+ 'No specific issues mentioned'}
323
+
324
+ ## Complete Phase Guidance
325
+ Here are the complete instructions for the ${args.currentPhase} phase:
149
326
 
150
- ## Iteration Limits
151
- - **Maximum 3 iterations** per workflow phase
152
- - After 3 failed attempts, work will be **automatically escalated** to human review
153
- - Track your attempts carefully - include iterationCount in every report
154
- - Each workflow phase (spec, implement, test) has its own iteration counter
327
+ ---
328
+
329
+ ${phaseInstructions}
330
+
331
+ ---
155
332
 
156
333
  ## Next Steps
157
- After completing your review, report back with the JSON response above including your iteration count. The AI Manager will evaluate your report and provide next steps based on your progress and iteration count.
334
+ 1. Review the complete phase guidance above
335
+ 2. Address the specific issues you mentioned
336
+ 3. Follow the phase workflow step by step
337
+ 4. When ready, call seekCoachingOnNextStep again with status "complete"
338
+
339
+ Remember: Take your time and follow each step carefully. The phase guidance contains everything you need to succeed.
340
+ `;
341
+ }
342
+ /**
343
+ * Get phase instructions from .md files
344
+ */
345
+ async getPhaseInstructions(phase, workflowType) {
346
+ try {
347
+ // Read phase instructions from .md files based on workflow type
348
+ let phasePath;
349
+ if (workflowType === 'implement') {
350
+ phasePath = `ai-manager-rules/implement-phases/${phase}.md`;
351
+ }
352
+ else {
353
+ phasePath = `ai-manager-rules/${workflowType}-phases/${phase}.md`;
354
+ }
355
+ // Try to get from file index first
356
+ let phaseFile = this.fileIndex.get(phasePath);
357
+ if (phaseFile && (0, fs_1.existsSync)(phaseFile.fullPath)) {
358
+ return (0, fs_1.readFileSync)(phaseFile.fullPath, 'utf8');
359
+ }
360
+ // If not found in workflow-specific directory, try shared-phases
361
+ const sharedPhasePath = `ai-manager-rules/shared-phases/${phase}.md`;
362
+ phaseFile = this.fileIndex.get(sharedPhasePath);
363
+ if (phaseFile && (0, fs_1.existsSync)(phaseFile.fullPath)) {
364
+ return (0, fs_1.readFileSync)(phaseFile.fullPath, 'utf8');
365
+ }
366
+ // Fallback: try to read directly from filesystem
367
+ const { join } = require('path');
368
+ const possiblePaths = [
369
+ // Try workflow-specific paths first
370
+ join(process.cwd(), 'dist', 'registry', phasePath),
371
+ join(process.cwd(), 'registry', phasePath),
372
+ join(__dirname, '..', '..', 'registry', phasePath),
373
+ join(__dirname, '..', 'registry', phasePath),
374
+ // Try shared-phases paths
375
+ join(process.cwd(), 'dist', 'registry', sharedPhasePath),
376
+ join(process.cwd(), 'registry', sharedPhasePath),
377
+ join(__dirname, '..', '..', 'registry', sharedPhasePath),
378
+ join(__dirname, '..', 'registry', sharedPhasePath)
379
+ ];
380
+ for (const fullPath of possiblePaths) {
381
+ if ((0, fs_1.existsSync)(fullPath)) {
382
+ console.log(`📖 AI Coach: Reading phase file from ${fullPath}`);
383
+ return (0, fs_1.readFileSync)(fullPath, 'utf8');
384
+ }
385
+ }
386
+ return `# Phase: ${phase}
387
+
388
+ **Error**: Phase instructions not found at ${phasePath} or ${sharedPhasePath}
389
+
390
+ Tried paths:
391
+ ${possiblePaths.map(p => `- ${p}`).join('\n')}
392
+
393
+ Please check that the phase name is correct and the phase file exists.
394
+
395
+ Available phases for ${workflowType} workflow: ${this.getAvailablePhasesForWorkflow(workflowType)}
396
+ `;
397
+ }
398
+ catch (error) {
399
+ return `# Phase: ${phase}
400
+
401
+ **Error**: Failed to load phase instructions: ${error instanceof Error ? error.message : 'Unknown error'}
158
402
  `;
159
- return instructions;
403
+ }
404
+ }
405
+ /**
406
+ * Get available phases for a workflow type
407
+ */
408
+ getAvailablePhasesForWorkflow(workflowType) {
409
+ switch (workflowType) {
410
+ case 'implement':
411
+ return 'implement-scoping, implement-repro, implement-spike, implement-code, implement-validate, implement-smoke, implement-regression, implement-completeness-review, submit-pr, wait-for-pr-review';
412
+ case 'spec':
413
+ return 'spec-spec, spec-completeness-review, submit-pr, wait-for-pr-review';
414
+ case 'design':
415
+ return 'design-design, design-completeness-review, submit-pr, wait-for-pr-review';
416
+ case 'test':
417
+ return 'test-test, test-validate, submit-pr, wait-for-pr-review';
418
+ default:
419
+ return 'unknown';
420
+ }
160
421
  }
161
422
  }
162
- exports.AIManager = AIManager;
423
+ exports.AICoach = AICoach;