@hailer/mcp 0.1.11 → 0.1.12

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 (62) hide show
  1. package/.claude/settings.json +12 -0
  2. package/CLAUDE.md +37 -1
  3. package/ai-hub/dist/assets/index-8ce6041d.css +1 -0
  4. package/ai-hub/dist/assets/index-930f01ca.js +348 -0
  5. package/ai-hub/dist/index.html +15 -0
  6. package/ai-hub/dist/manifest.json +14 -0
  7. package/ai-hub/dist/vite.svg +1 -0
  8. package/dist/app.js +5 -0
  9. package/dist/client/agents/base.d.ts +5 -0
  10. package/dist/client/agents/base.js +9 -2
  11. package/dist/client/agents/definitions.js +85 -0
  12. package/dist/client/agents/orchestrator.d.ts +21 -0
  13. package/dist/client/agents/orchestrator.js +292 -1
  14. package/dist/client/bot-entrypoint.d.ts +7 -0
  15. package/dist/client/bot-entrypoint.js +103 -0
  16. package/dist/client/bot-runner.d.ts +35 -0
  17. package/dist/client/bot-runner.js +188 -0
  18. package/dist/client/factory.d.ts +4 -0
  19. package/dist/client/factory.js +10 -0
  20. package/dist/client/server.d.ts +8 -0
  21. package/dist/client/server.js +251 -0
  22. package/dist/client/types.d.ts +29 -0
  23. package/dist/client/types.js +4 -1
  24. package/dist/core.d.ts +3 -0
  25. package/dist/core.js +72 -0
  26. package/dist/mcp/hailer-clients.d.ts +4 -0
  27. package/dist/mcp/hailer-clients.js +16 -1
  28. package/dist/mcp/tools/app-scaffold.js +127 -5
  29. package/dist/mcp/tools/bot-config.d.ts +78 -0
  30. package/dist/mcp/tools/bot-config.js +442 -0
  31. package/dist/mcp-server.js +109 -1
  32. package/dist/modules/bug-reports/bug-config.d.ts +25 -0
  33. package/dist/modules/bug-reports/bug-config.js +187 -0
  34. package/dist/modules/bug-reports/bug-monitor.d.ts +108 -0
  35. package/dist/modules/bug-reports/bug-monitor.js +510 -0
  36. package/dist/modules/bug-reports/giuseppe-ai.d.ts +59 -0
  37. package/dist/modules/bug-reports/giuseppe-ai.js +335 -0
  38. package/dist/modules/bug-reports/giuseppe-bot.d.ts +109 -0
  39. package/dist/modules/bug-reports/giuseppe-bot.js +765 -0
  40. package/dist/modules/bug-reports/giuseppe-files.d.ts +52 -0
  41. package/dist/modules/bug-reports/giuseppe-files.js +338 -0
  42. package/dist/modules/bug-reports/giuseppe-git.d.ts +48 -0
  43. package/dist/modules/bug-reports/giuseppe-git.js +298 -0
  44. package/dist/modules/bug-reports/giuseppe-prompt.d.ts +5 -0
  45. package/dist/modules/bug-reports/giuseppe-prompt.js +94 -0
  46. package/dist/modules/bug-reports/index.d.ts +76 -0
  47. package/dist/modules/bug-reports/index.js +213 -0
  48. package/dist/modules/bug-reports/pending-classification-registry.d.ts +28 -0
  49. package/dist/modules/bug-reports/pending-classification-registry.js +50 -0
  50. package/dist/modules/bug-reports/pending-fix-registry.d.ts +30 -0
  51. package/dist/modules/bug-reports/pending-fix-registry.js +42 -0
  52. package/dist/modules/bug-reports/pending-registry.d.ts +27 -0
  53. package/dist/modules/bug-reports/pending-registry.js +49 -0
  54. package/dist/modules/bug-reports/types.d.ts +123 -0
  55. package/dist/modules/bug-reports/types.js +9 -0
  56. package/dist/services/bug-monitor.d.ts +23 -0
  57. package/dist/services/bug-monitor.js +275 -0
  58. package/lineup-manager/dist/assets/index-b30c809f.js +600 -0
  59. package/lineup-manager/dist/index.html +1 -1
  60. package/lineup-manager/dist/manifest.json +5 -5
  61. package/package.json +6 -2
  62. package/lineup-manager/dist/assets/index-e168f265.js +0 -600
@@ -0,0 +1,765 @@
1
+ "use strict";
2
+ /**
3
+ * Bug Reports Module - Giuseppe Bot
4
+ *
5
+ * Autonomous app fixer that:
6
+ * 1. Analyzes bug reports
7
+ * 2. Finds app project code
8
+ * 3. Generates fixes using Claude
9
+ * 4. Tests locally
10
+ * 5. Publishes to production
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.GiuseppeBot = void 0;
14
+ const child_process_1 = require("child_process");
15
+ const logger_1 = require("../../lib/logger");
16
+ const pending_fix_registry_1 = require("./pending-fix-registry");
17
+ const pending_classification_registry_1 = require("./pending-classification-registry");
18
+ const app_scaffold_1 = require("../../mcp/tools/app-scaffold");
19
+ // Import extracted modules
20
+ const giuseppe_ai_1 = require("./giuseppe-ai");
21
+ const giuseppe_git_1 = require("./giuseppe-git");
22
+ const giuseppe_files_1 = require("./giuseppe-files");
23
+ const logger = (0, logger_1.createLogger)({ component: 'giuseppe-bot' });
24
+ // Magic words for approval flow
25
+ const MAGIC_WORD_APPROVED = 'approved';
26
+ const MAGIC_WORD_DENIED = 'denied';
27
+ const MAGIC_WORD_FIX_IT = 'fix it';
28
+ const MAGIC_WORD_NOT_A_BUG = 'not a bug';
29
+ // Session Log (Context Log) field IDs for logging
30
+ const SESSION_LOG_CONFIG = {
31
+ workflowId: '695784898d347a6c707ee397',
32
+ phaseId: '695784898d347a6c707ee3c3', // Active phase
33
+ teamId: '6901c67b4e80fecb6fd7b38b', // Required team
34
+ fields: {
35
+ contextSummary: '695784898d347a6c707ee3be',
36
+ linkedWork: '695784898d347a6c707ee3c0', // Link to bug report
37
+ madeBy: '695784898d347a6c707ee3c2' // Link to agent
38
+ }
39
+ };
40
+ class GiuseppeBot {
41
+ userContext;
42
+ config;
43
+ monitor;
44
+ ai;
45
+ git;
46
+ files;
47
+ appsRegistry = new Map();
48
+ constructor(userContext, config, monitor) {
49
+ this.userContext = userContext;
50
+ this.config = config;
51
+ this.monitor = monitor;
52
+ // Initialize extracted modules
53
+ const apiKey = config.anthropicApiKey || process.env.ANTHROPIC_API_KEY;
54
+ this.ai = new giuseppe_ai_1.GiuseppeAI(apiKey);
55
+ this.git = new giuseppe_git_1.GiuseppeGit();
56
+ this.files = new giuseppe_files_1.GiuseppeFiles(process.env.DEV_APPS_PATH);
57
+ // Load apps registry from config
58
+ if (config.appsRegistry) {
59
+ for (const [appId, entry] of Object.entries(config.appsRegistry)) {
60
+ this.appsRegistry.set(appId, entry);
61
+ }
62
+ }
63
+ }
64
+ /**
65
+ * Create a session log entry in Context Log workflow
66
+ * Links to the bug report for traceability
67
+ */
68
+ async createSessionLogEntry(title, summary, bugActivityId) {
69
+ try {
70
+ const { hailer } = this.userContext;
71
+ // createActivities expects array of activity objects with 'fields' (not 'fieldsAndValues')
72
+ const activities = [{
73
+ name: title,
74
+ phaseId: SESSION_LOG_CONFIG.phaseId,
75
+ teamId: SESSION_LOG_CONFIG.teamId,
76
+ fields: {
77
+ [SESSION_LOG_CONFIG.fields.contextSummary]: summary,
78
+ [SESSION_LOG_CONFIG.fields.linkedWork]: bugActivityId
79
+ }
80
+ }];
81
+ const result = await hailer.createActivities(SESSION_LOG_CONFIG.workflowId, activities);
82
+ // Result is array of created activity IDs
83
+ const createdId = result?.[0];
84
+ if (createdId) {
85
+ logger.info('Created session log entry', {
86
+ logId: createdId,
87
+ title,
88
+ linkedBugId: bugActivityId
89
+ });
90
+ return createdId;
91
+ }
92
+ return null;
93
+ }
94
+ catch (error) {
95
+ logger.warn('Failed to create session log entry', {
96
+ title,
97
+ bugActivityId,
98
+ error: error instanceof Error ? error.message : String(error)
99
+ });
100
+ return null;
101
+ }
102
+ }
103
+ /**
104
+ * Check if this bug was already classified by looking for classification message in discussion
105
+ */
106
+ async wasAlreadyClassified(bug) {
107
+ if (!bug.discussionId)
108
+ return false;
109
+ try {
110
+ const { hailer } = this.userContext;
111
+ const result = await hailer.fetchDiscussionMessages(bug.discussionId, 20);
112
+ const messages = result?.messages || [];
113
+ // Check if any message contains our classification pattern
114
+ return messages.some((msg) => {
115
+ const content = msg.content || msg.msg || msg.message || '';
116
+ return content.includes('**Classification:') && content.includes('Reply **"fix it"**');
117
+ });
118
+ }
119
+ catch (error) {
120
+ logger.debug('Failed to check classification history', { bugId: bug.id, error });
121
+ return false;
122
+ }
123
+ }
124
+ /**
125
+ * Handle a new bug - main entry point
126
+ */
127
+ async handleBug(bug) {
128
+ logger.info('Giuseppe analyzing report', {
129
+ bugId: bug.id,
130
+ bugName: bug.name,
131
+ appId: bug.appId
132
+ });
133
+ const result = {
134
+ success: false,
135
+ summary: '',
136
+ log: []
137
+ };
138
+ // Check if already classified (e.g., after server restart)
139
+ const alreadyClassified = await this.wasAlreadyClassified(bug);
140
+ if (alreadyClassified) {
141
+ logger.info('Bug already classified, skipping re-classification', { bugId: bug.id });
142
+ // Re-register in pending registry for message watching (in case server restarted)
143
+ if (bug.discussionId) {
144
+ // Just register with unknown classification - we're waiting for user response
145
+ pending_classification_registry_1.pendingClassificationRegistry.register({
146
+ discussionId: bug.discussionId,
147
+ bugId: bug.id,
148
+ bugName: bug.name,
149
+ appId: bug.appId,
150
+ appName: bug.appName,
151
+ classification: 'unclear', // Unknown at this point
152
+ reason: 'Previously classified',
153
+ timestamp: Date.now(),
154
+ bug
155
+ });
156
+ this.monitor.watchDiscussion(bug.discussionId);
157
+ }
158
+ return {
159
+ success: false,
160
+ summary: 'Already classified - awaiting confirmation'
161
+ };
162
+ }
163
+ try {
164
+ // 0. Join the bug's discussion so we can post updates
165
+ await this.joinBugDiscussion(bug.id);
166
+ // 1. Classify the report first
167
+ const { classification, reason } = await this.ai.classifyReport(bug);
168
+ result.log?.push(`Classification: ${classification} - ${reason}`);
169
+ // 2. Post classification and ask for confirmation
170
+ const classificationEmoji = classification === 'bug' ? '🐛' : classification === 'feature_request' ? '✨' : '❓';
171
+ const classificationLabel = classification === 'bug' ? 'Bug' : classification === 'feature_request' ? 'Feature Request' : 'Unclear';
172
+ const confirmMessage = [
173
+ `${classificationEmoji} **Classification: ${classificationLabel}**`,
174
+ '',
175
+ `**Reason:** ${reason}`,
176
+ '',
177
+ classification === 'bug'
178
+ ? `This looks like a bug I can try to fix.\n\n👉 Reply **"fix it"** to proceed with auto-fix.\n👉 Reply **"not a bug"** if this is actually a feature request.`
179
+ : `This looks like a feature request, not a bug.\n\n👉 Reply **"fix it"** if you still want me to try.\n👉 Reply **"not a bug"** to confirm and close.`
180
+ ].join('\n');
181
+ await this.reportProgress(bug, confirmMessage);
182
+ // 3. Store pending classification and wait for user response
183
+ if (bug.discussionId) {
184
+ pending_classification_registry_1.pendingClassificationRegistry.register({
185
+ discussionId: bug.discussionId,
186
+ bugId: bug.id,
187
+ bugName: bug.name,
188
+ appId: bug.appId,
189
+ appName: bug.appName,
190
+ classification,
191
+ reason,
192
+ timestamp: Date.now(),
193
+ bug
194
+ });
195
+ logger.info('Stored pending classification', {
196
+ discussionId: bug.discussionId,
197
+ bugId: bug.id,
198
+ classification,
199
+ pendingClassificationsSize: pending_classification_registry_1.pendingClassificationRegistry.size
200
+ });
201
+ this.monitor.watchDiscussion(bug.discussionId);
202
+ }
203
+ result.summary = `Classified as ${classificationLabel} - awaiting confirmation`;
204
+ result.log?.push('Waiting for user to confirm with "fix it"');
205
+ return result;
206
+ }
207
+ catch (error) {
208
+ const errorMessage = error instanceof Error ? error.message : String(error);
209
+ logger.error('Classification failed', { bugId: bug.id, error: errorMessage });
210
+ result.summary = `Classification error: ${errorMessage}`;
211
+ return result;
212
+ }
213
+ }
214
+ /**
215
+ * Continue with bug fix after user confirms
216
+ */
217
+ async proceedWithFix(bug) {
218
+ logger.info('Giuseppe proceeding with fix', {
219
+ bugId: bug.id,
220
+ bugName: bug.name,
221
+ appId: bug.appId
222
+ });
223
+ const result = {
224
+ success: false,
225
+ summary: '',
226
+ log: []
227
+ };
228
+ try {
229
+ // 1. Find app project
230
+ const app = await this.files.findAppProject(bug, this.appsRegistry);
231
+ if (!app) {
232
+ result.summary = `Could not find app project for appId: ${bug.appId}`;
233
+ result.log?.push('App project not found');
234
+ await this.reportProgress(bug, `❌ ${result.summary}`);
235
+ return result;
236
+ }
237
+ result.log?.push(`Found app project: ${app.projectPath}`);
238
+ await this.reportProgress(bug, `📁 Found app project: ${app.name}`);
239
+ // 2. Analyze and generate fix
240
+ const allFiles = await this.files.scanSourceFiles(app.projectPath);
241
+ const fixPlan = await this.ai.analyzeAndPlanFix(bug, app, allFiles, (paths) => this.files.readSelectedFiles(app.projectPath, paths));
242
+ if (!fixPlan) {
243
+ result.summary = 'Could not generate fix plan';
244
+ result.log?.push('Fix plan generation failed');
245
+ await this.reportProgress(bug, '❌ Could not analyze bug - manual review needed');
246
+ return result;
247
+ }
248
+ result.log?.push(`Fix plan: ${fixPlan.analysis}`);
249
+ await this.reportProgress(bug, `🔍 Analysis: ${fixPlan.analysis}\n🔧 Root cause: ${fixPlan.rootCause}`);
250
+ // 3. Move to "In Progress"
251
+ await this.monitor.moveBugToPhase(bug.id, 'inProgress');
252
+ // 4. Apply fixes and build (with retry on any failure)
253
+ const MAX_RETRIES = 3;
254
+ let currentFixPlan = fixPlan;
255
+ let fixSuccess = false;
256
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
257
+ // Try to apply the fix
258
+ const applyResult = await this.files.applyFixes(app, currentFixPlan.fix.files);
259
+ if (!applyResult.success) {
260
+ // Apply failed - likely search string not found
261
+ result.log?.push(`Apply failed (attempt ${attempt}): ${applyResult.error}`);
262
+ await this.reportProgress(bug, `❌ Apply failed (attempt ${attempt}/${MAX_RETRIES}): ${applyResult.error}`);
263
+ if (attempt < MAX_RETRIES) {
264
+ await this.reportProgress(bug, `🔄 Re-reading file and generating new fix...`);
265
+ // Re-read the current state of files that need to be modified
266
+ const filePaths = currentFixPlan.fix.files.map(f => f.path);
267
+ const currentFiles = await this.files.readSelectedFiles(app.projectPath, filePaths);
268
+ // Re-generate fix with current file state
269
+ const retryFix = await this.ai.retryFixFromApplyError(bug, currentFixPlan, applyResult.error || 'Unknown error', currentFiles, attempt);
270
+ if (!retryFix) {
271
+ result.log?.push('Could not generate retry fix');
272
+ await this.reportProgress(bug, `❌ Could not generate corrected fix`);
273
+ break;
274
+ }
275
+ currentFixPlan = retryFix;
276
+ continue; // Try applying again
277
+ }
278
+ break;
279
+ }
280
+ // Apply succeeded - now build
281
+ result.filesModified = [...new Set([...(result.filesModified || []), ...applyResult.files])];
282
+ result.log?.push(`Modified ${applyResult.files.length} file(s)`);
283
+ await this.reportProgress(bug, `✏️ Applied fixes to ${applyResult.files.length} file(s)`);
284
+ const buildResult = await this.buildAndTest(app);
285
+ if (buildResult.success) {
286
+ fixSuccess = true;
287
+ result.log?.push(`Build successful (attempt ${attempt})`);
288
+ await this.reportProgress(bug, '✅ Build successful');
289
+ break;
290
+ }
291
+ // Build failed
292
+ result.log?.push(`Build failed (attempt ${attempt}): ${buildResult.error}`);
293
+ await this.reportProgress(bug, `❌ Build failed (attempt ${attempt}/${MAX_RETRIES}):\n\`\`\`\n${buildResult.error}\n\`\`\``);
294
+ if (attempt < MAX_RETRIES) {
295
+ await this.reportProgress(bug, `🔄 Analyzing error and retrying...`);
296
+ // Read the current state of files that were modified
297
+ const currentFiles = await this.files.readSelectedFiles(app.projectPath, currentFixPlan.fix.files.map(f => f.path));
298
+ const retryFix = await this.ai.retryFixFromError(bug, currentFixPlan, buildResult.error || 'Unknown error', currentFiles, attempt);
299
+ if (!retryFix) {
300
+ result.log?.push('Could not generate retry fix');
301
+ await this.reportProgress(bug, `❌ Could not generate corrected fix`);
302
+ break;
303
+ }
304
+ currentFixPlan = retryFix;
305
+ // Continue to next attempt - will apply the new fix
306
+ }
307
+ }
308
+ if (!fixSuccess) {
309
+ result.summary = `Fix failed after ${MAX_RETRIES} attempts`;
310
+ // Revert all changes
311
+ if (result.filesModified && result.filesModified.length > 0) {
312
+ await this.git.revertChanges(app, result.filesModified);
313
+ }
314
+ await this.reportProgress(bug, `❌ Could not fix bug after ${MAX_RETRIES} attempts. Changes reverted.`);
315
+ return result;
316
+ }
317
+ // 6. Commit changes
318
+ const commitResult = await this.git.commitChanges(app, bug);
319
+ if (commitResult.hash) {
320
+ result.commitHash = commitResult.hash;
321
+ result.log?.push(`Committed: ${commitResult.hash}`);
322
+ }
323
+ // 7. Stay in "In Progress" - will move to "Fixed" only after approval
324
+ // (already moved to inProgress in step 3)
325
+ // 8. Store pending fix and ask owner to test
326
+ if (bug.discussionId) {
327
+ pending_fix_registry_1.pendingFixRegistry.register({
328
+ discussionId: bug.discussionId,
329
+ bugId: bug.id,
330
+ appId: bug.appId || app.name,
331
+ state: 'awaiting_test',
332
+ fixSummary: currentFixPlan.explanation,
333
+ timestamp: Date.now(),
334
+ bug,
335
+ app,
336
+ fixPlan: currentFixPlan,
337
+ filesModified: result.filesModified || [],
338
+ commitHash: result.commitHash
339
+ });
340
+ logger.info('Stored pending fix awaiting approval', { bugId: bug.id, discussionId: bug.discussionId });
341
+ // Start watching this discussion for approval messages
342
+ this.monitor.watchDiscussion(bug.discussionId);
343
+ }
344
+ result.success = true;
345
+ result.summary = `Fixed: ${currentFixPlan.explanation} (awaiting approval)`;
346
+ // Ask owner to test with clear magic words
347
+ await this.reportProgress(bug, `✅ **Bug Fixed!**
348
+
349
+ ${currentFixPlan.explanation}
350
+
351
+ **Files changed:** ${result.filesModified?.join(', ') || 'none'}
352
+
353
+ ---
354
+
355
+ 🧪 **Please test the fix locally**, then reply with:
356
+ - **\`approved\`** - to publish to production
357
+ - **\`denied\`** - if the fix doesn't work (I'll ask what's wrong)`);
358
+ return result;
359
+ }
360
+ catch (error) {
361
+ result.summary = `Error: ${error instanceof Error ? error.message : String(error)}`;
362
+ result.log?.push(`Exception: ${result.summary}`);
363
+ logger.error('Giuseppe failed', { bugId: bug.id, error });
364
+ await this.reportProgress(bug, `❌ Giuseppe encountered an error: ${result.summary}`);
365
+ return result;
366
+ }
367
+ }
368
+ /**
369
+ * Handle a message in a bug discussion - state machine for approval flow
370
+ */
371
+ async handleDiscussionMessage(discussionId, message, senderId) {
372
+ // Normalize: replace non-breaking spaces (0xA0) with regular spaces (0x20)
373
+ // Hailer chat may send NBSP instead of regular spaces
374
+ const messageLower = message.toLowerCase().replace(/\u00A0/g, ' ').trim();
375
+ logger.debug('handleDiscussionMessage called', {
376
+ discussionId,
377
+ message: message.substring(0, 50),
378
+ pendingClassificationsSize: pending_classification_registry_1.pendingClassificationRegistry.size,
379
+ hasPendingForDiscussion: pending_classification_registry_1.pendingClassificationRegistry.has(discussionId)
380
+ });
381
+ // Check for pending classification first (waiting for "fix it" or "not a bug")
382
+ const pendingClassification = pending_classification_registry_1.pendingClassificationRegistry.get(discussionId);
383
+ if (pendingClassification) {
384
+ // Hex dump for debugging character encoding issues
385
+ const hexDump = (str) => Array.from(str).map(c => c.charCodeAt(0).toString(16).padStart(2, '0')).join(' ');
386
+ logger.debug('Checking message against magic words', {
387
+ discussionId,
388
+ messageLower,
389
+ messageLowerHex: hexDump(messageLower),
390
+ MAGIC_WORD_NOT_A_BUG,
391
+ magicWordHex: hexDump(MAGIC_WORD_NOT_A_BUG),
392
+ isFixIt: messageLower === MAGIC_WORD_FIX_IT || messageLower === 'fix',
393
+ isNotABug: messageLower === MAGIC_WORD_NOT_A_BUG,
394
+ includesNotABug: messageLower.includes('not a bug'),
395
+ includesFeature: messageLower.includes('feature')
396
+ });
397
+ if (messageLower === MAGIC_WORD_FIX_IT || messageLower === 'fix') {
398
+ logger.debug('Matched fix it - calling handleFixItConfirmation');
399
+ return await this.handleFixItConfirmation(discussionId, pendingClassification);
400
+ }
401
+ if (messageLower === MAGIC_WORD_NOT_A_BUG || messageLower.includes('not a bug') || messageLower.includes('feature')) {
402
+ logger.debug('Matched not a bug - calling handleNotABugConfirmation');
403
+ return await this.handleNotABugConfirmation(discussionId, pendingClassification);
404
+ }
405
+ logger.debug('No magic word match - ignoring message');
406
+ // Other messages while waiting for classification - ignore
407
+ return { approved: false, published: false };
408
+ }
409
+ // Check for pending fix (waiting for "approved" or "denied")
410
+ const pendingFix = pending_fix_registry_1.pendingFixRegistry.get(discussionId);
411
+ if (!pendingFix) {
412
+ return { approved: false, published: false };
413
+ }
414
+ // Giuseppe ONLY handles "approved" - HAL handles everything else (denial, explanations)
415
+ if (messageLower === MAGIC_WORD_APPROVED) {
416
+ return await this.handleApproval(discussionId, pendingFix);
417
+ }
418
+ // All other messages: return false, let HAL handle
419
+ return { approved: false, published: false };
420
+ }
421
+ /**
422
+ * Handle "fix it" confirmation - proceed with bug fix
423
+ */
424
+ async handleFixItConfirmation(discussionId, pending) {
425
+ logger.info('User confirmed fix', { discussionId, bugId: pending.bugId });
426
+ // Remove from pending classifications
427
+ pending_classification_registry_1.pendingClassificationRegistry.unregister(discussionId);
428
+ await this.sendDiscussionMessage(discussionId, `✅ Got it! Starting bug fix...`);
429
+ // Proceed with the actual fix
430
+ const result = await this.proceedWithFix(pending.bug);
431
+ return {
432
+ approved: true,
433
+ published: result.success,
434
+ error: result.success ? undefined : result.summary
435
+ };
436
+ }
437
+ /**
438
+ * Handle "not a bug" confirmation - close without fixing
439
+ */
440
+ async handleNotABugConfirmation(discussionId, pending) {
441
+ logger.info('User confirmed not a bug', { discussionId, bugId: pending.bugId });
442
+ // Remove from pending classifications
443
+ pending_classification_registry_1.pendingClassificationRegistry.unregister(discussionId);
444
+ this.monitor.unwatchDiscussion(discussionId);
445
+ await this.sendDiscussionMessage(discussionId, `✅ Understood. This has been marked as a feature request and moved to Declined.\n\nPlease create a feature request if you'd like this change implemented.`);
446
+ // Move to declined phase (not a bug)
447
+ await this.monitor.moveBugToPhase(pending.bugId, 'declined');
448
+ return { approved: false, published: false };
449
+ }
450
+ /**
451
+ * Handle "approved" - publish to production
452
+ */
453
+ async handleApproval(discussionId, pending) {
454
+ logger.info('Fix approved', { discussionId, bugId: pending.bugId });
455
+ await this.sendDiscussionMessage(discussionId, `🚀 Publishing to production...`);
456
+ const publishResult = await this.publishApp(pending.app, pending.bug);
457
+ if (publishResult.success) {
458
+ // Move to Fixed phase (published successfully)
459
+ await this.monitor.moveBugToPhase(pending.bugId, 'fixed');
460
+ // Remove from pending and stop watching
461
+ pending_fix_registry_1.pendingFixRegistry.unregister(discussionId);
462
+ this.monitor.unwatchDiscussion(discussionId);
463
+ // Log to Session Log - fix published
464
+ await this.createSessionLogEntry(`Giuseppe: Published fix for ${pending.bug.name}`, [
465
+ `**Bug Report:** ${pending.bug.name}`,
466
+ `**App:** ${pending.app.name}`,
467
+ `**Version:** ${publishResult.version || 'latest'}`,
468
+ `**Files changed:** ${pending.filesModified.join(', ') || 'none'}`,
469
+ '',
470
+ `**Fix summary:** ${pending.fixPlan.explanation}`,
471
+ '',
472
+ `Fix has been tested, approved, and published to production.`
473
+ ].join('\n'), pending.bugId);
474
+ await this.sendDiscussionMessage(discussionId, `✅ **Published to production!** v${publishResult.version || 'latest'}\n\nBug marked as Fixed. Thank you for testing!`);
475
+ logger.info('Fix published', { bugId: pending.bugId, version: publishResult.version });
476
+ return { approved: true, published: true };
477
+ }
478
+ else {
479
+ await this.sendDiscussionMessage(discussionId, `❌ Publish failed: ${publishResult.error}\n\nPlease try publishing manually or contact support.`);
480
+ return { approved: true, published: false, error: publishResult.error };
481
+ }
482
+ }
483
+ /**
484
+ * Handle "denied" - ask for explanation
485
+ */
486
+ async handleDenial(discussionId, pending) {
487
+ logger.info('Fix denied, asking for explanation', { discussionId, bugId: pending.bugId });
488
+ // Change state to awaiting_explanation
489
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_explanation');
490
+ await this.sendDiscussionMessage(discussionId, `📝 **What's not working?**\n\nPlease describe what's still broken or what the fix didn't address. I'll analyze your feedback and try again.`);
491
+ return { approved: false, published: false };
492
+ }
493
+ /**
494
+ * Handle explanation after denial - retry the fix
495
+ */
496
+ async handleExplanationAndRetry(discussionId, pending, explanation) {
497
+ logger.info('Received explanation, retrying fix', {
498
+ discussionId,
499
+ bugId: pending.bugId,
500
+ explanation: explanation.substring(0, 100)
501
+ });
502
+ await this.sendDiscussionMessage(discussionId, `🔄 Got it. Analyzing your feedback and generating a new fix...`);
503
+ // Revert previous changes first
504
+ if (pending.filesModified.length > 0) {
505
+ await this.git.revertChanges(pending.app, pending.filesModified);
506
+ await this.sendDiscussionMessage(discussionId, `↩️ Reverted previous changes`);
507
+ }
508
+ // Get file list from git (fast, accurate)
509
+ let allSourceFiles = await this.git.getSourceFilesFromGit(pending.app.projectPath);
510
+ if (allSourceFiles.length === 0) {
511
+ // Fallback to directory scan if git fails
512
+ allSourceFiles = await this.files.scanSourceFiles(pending.app.projectPath);
513
+ }
514
+ // Search for relevant files based on feedback keywords
515
+ const relevantFiles = await this.files.findRelevantFiles(pending.app.projectPath, explanation, pending.bug);
516
+ // Always include files from previous fix
517
+ const previousFixFiles = pending.fixPlan.fix.files.map(f => f.path);
518
+ // Combine all relevant files (deduplicated)
519
+ const filesToRead = [...new Set([
520
+ ...previousFixFiles,
521
+ ...relevantFiles,
522
+ 'src/App.tsx' // Always include main app file
523
+ ])].filter(f => allSourceFiles.includes(f));
524
+ const currentFiles = await this.files.readSelectedFiles(pending.app.projectPath, filesToRead);
525
+ // Generate new fix based on feedback
526
+ const retryFix = await this.ai.retryFixWithFeedback(pending.bug, pending.fixPlan, explanation, allSourceFiles, currentFiles);
527
+ if (!retryFix) {
528
+ await this.sendDiscussionMessage(discussionId, `❌ Could not generate a new fix based on your feedback. Please provide more details or contact support.`);
529
+ // Reset state to allow another try
530
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_explanation');
531
+ return { approved: false, published: false, error: 'Could not generate retry fix' };
532
+ }
533
+ // Apply the new fix
534
+ const applyResult = await this.files.applyFixes(pending.app, retryFix.fix.files);
535
+ if (!applyResult.success) {
536
+ await this.sendDiscussionMessage(discussionId, `❌ Failed to apply new fix: ${applyResult.error}\n\nPlease provide more details about the issue.`);
537
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_explanation');
538
+ return { approved: false, published: false, error: applyResult.error };
539
+ }
540
+ // Build and test
541
+ const buildResult = await this.buildAndTest(pending.app);
542
+ if (!buildResult.success) {
543
+ await this.sendDiscussionMessage(discussionId, `❌ Build failed:\n\`\`\`\n${buildResult.error}\n\`\`\`\n\nI'll need to try a different approach. What exactly is broken?`);
544
+ // Revert and ask again
545
+ await this.git.revertChanges(pending.app, applyResult.files);
546
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_explanation');
547
+ return { approved: false, published: false, error: buildResult.error };
548
+ }
549
+ // Success! Update pending fix and ask for approval again
550
+ pending.fixPlan = retryFix;
551
+ pending.filesModified = applyResult.files;
552
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_test');
553
+ await this.sendDiscussionMessage(discussionId, `✅ **New fix applied!**
554
+
555
+ ${retryFix.explanation}
556
+
557
+ **Files changed:** ${applyResult.files.join(', ')}
558
+
559
+ ---
560
+
561
+ 🧪 **Please test again**, then reply with:
562
+ - **\`approved\`** - to publish to production
563
+ - **\`denied\`** - if still not working`);
564
+ return { approved: false, published: false, retrying: true };
565
+ }
566
+ /**
567
+ * Check if there's a pending fix for a discussion
568
+ */
569
+ hasPendingFix(discussionId) {
570
+ return pending_fix_registry_1.pendingFixRegistry.has(discussionId);
571
+ }
572
+ /**
573
+ * Retry a pending fix with explanation from HAL
574
+ * Called by HAL after gathering info through conversation
575
+ */
576
+ async retryWithExplanation(discussionId, explanation) {
577
+ const pending = pending_fix_registry_1.pendingFixRegistry.get(discussionId);
578
+ if (!pending) {
579
+ logger.warn('No pending fix found for retry', { discussionId });
580
+ return false;
581
+ }
582
+ logger.info('HAL triggered retry with explanation', {
583
+ discussionId,
584
+ bugId: pending.bugId,
585
+ explanationLength: explanation.length
586
+ });
587
+ // Update registry state
588
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_explanation');
589
+ // Trigger the retry
590
+ const result = await this.handleExplanationAndRetry(discussionId, pending, explanation);
591
+ // Update registry state based on result
592
+ if (result.retrying) {
593
+ pending_fix_registry_1.pendingFixRegistry.updateState(discussionId, 'awaiting_test');
594
+ }
595
+ return result.retrying || false;
596
+ }
597
+ /**
598
+ * Initialize registry callback (call this after construction)
599
+ */
600
+ initializeRegistryCallback() {
601
+ pending_fix_registry_1.pendingFixRegistry.setRetryCallback(async (discussionId, explanation) => {
602
+ await this.retryWithExplanation(discussionId, explanation);
603
+ });
604
+ logger.info('Registry retry callback initialized');
605
+ }
606
+ /**
607
+ * Initialize classification registry callbacks for HAL coordination
608
+ * This allows HAL to trigger "fix it" or "not a bug" via natural conversation
609
+ */
610
+ initializeClassificationCallbacks() {
611
+ pending_classification_registry_1.pendingClassificationRegistry.setCallbacks(
612
+ // fixIt callback
613
+ async (discussionId) => {
614
+ const pending = pending_classification_registry_1.pendingClassificationRegistry.get(discussionId);
615
+ if (pending) {
616
+ await this.handleFixItConfirmation(discussionId, pending);
617
+ }
618
+ },
619
+ // notABug callback
620
+ async (discussionId) => {
621
+ const pending = pending_classification_registry_1.pendingClassificationRegistry.get(discussionId);
622
+ if (pending) {
623
+ await this.handleNotABugConfirmation(discussionId, pending);
624
+ }
625
+ });
626
+ logger.info('Classification callbacks initialized');
627
+ }
628
+ /**
629
+ * Helper to send a message to a discussion
630
+ */
631
+ async sendDiscussionMessage(discussionId, message) {
632
+ try {
633
+ const { hailer } = this.userContext;
634
+ await hailer.sendDiscussionMessage(discussionId, message);
635
+ }
636
+ catch (error) {
637
+ logger.warn('Failed to send discussion message', { discussionId, error });
638
+ }
639
+ }
640
+ /**
641
+ * Build and test the app
642
+ */
643
+ async buildAndTest(app) {
644
+ return new Promise((resolve) => {
645
+ const child = (0, child_process_1.spawn)('npm', ['run', 'build'], {
646
+ cwd: app.projectPath,
647
+ shell: true
648
+ });
649
+ let stdout = '';
650
+ let stderr = '';
651
+ child.stdout.on('data', (data) => {
652
+ stdout += data.toString();
653
+ });
654
+ child.stderr.on('data', (data) => {
655
+ stderr += data.toString();
656
+ });
657
+ child.on('close', (code) => {
658
+ if (code === 0) {
659
+ resolve({ success: true });
660
+ }
661
+ else {
662
+ // TypeScript errors often go to stdout, combine both
663
+ const allOutput = stdout + '\n' + stderr;
664
+ // Extract just the error lines (look for .tsx/.ts errors)
665
+ const errorLines = allOutput.split('\n')
666
+ .filter(line => line.includes('error TS') || line.includes('Error:') || line.includes('error:'))
667
+ .slice(0, 10)
668
+ .join('\n');
669
+ resolve({ success: false, error: errorLines || allOutput.slice(-1000) });
670
+ }
671
+ });
672
+ child.on('error', (error) => {
673
+ resolve({ success: false, error: error.message });
674
+ });
675
+ // Timeout after 2 minutes
676
+ setTimeout(() => {
677
+ child.kill();
678
+ resolve({ success: false, error: 'Build timeout' });
679
+ }, 120000);
680
+ });
681
+ }
682
+ /**
683
+ * Join a bug's discussion using the activity ID (not discussion ID)
684
+ * For activity discussions, we must use joinActivityDiscussion
685
+ */
686
+ async joinBugDiscussion(activityId) {
687
+ try {
688
+ const { hailer } = this.userContext;
689
+ await hailer.joinActivityDiscussion(activityId);
690
+ logger.info('Joined bug discussion', { activityId });
691
+ }
692
+ catch (error) {
693
+ // Might already be a member, that's OK
694
+ logger.debug('Could not join bug discussion (may already be member)', { activityId, error });
695
+ }
696
+ }
697
+ /**
698
+ * Publish app to production using expect script (same as MCP tool)
699
+ */
700
+ async publishApp(app, bug) {
701
+ try {
702
+ // Bump patch version before publishing (bug fix = patch)
703
+ const versionBump = await this.git.bumpPatchVersion(app.projectPath);
704
+ const version = versionBump?.newVersion || '1.0.0';
705
+ if (versionBump) {
706
+ logger.info('Version bumped for bug fix', {
707
+ oldVersion: versionBump.oldVersion,
708
+ newVersion: versionBump.newVersion,
709
+ bugId: bug.id
710
+ });
711
+ // Stage and commit the version bump
712
+ await this.git.commitVersionBump(app.projectPath, version);
713
+ }
714
+ logger.info('Publishing app via MCP tool', {
715
+ projectPath: app.projectPath,
716
+ version
717
+ });
718
+ // Use the MCP publish_hailer_app tool directly
719
+ const result = await app_scaffold_1.publishHailerAppTool.execute({
720
+ projectDirectory: app.projectPath,
721
+ publishToMarket: false
722
+ }, this.userContext);
723
+ // Parse the result
724
+ const text = result.content?.[0]?.type === 'text' ? result.content[0].text : '';
725
+ if (text.includes('✅') || text.includes('Successfully') || text.includes('Published')) {
726
+ logger.info('App published successfully', { version });
727
+ // Push to git after successful publish
728
+ await this.git.push(app.projectPath);
729
+ // Create and push version tag (persists version history across code resets)
730
+ this.git.createVersionTag(app.projectPath, version);
731
+ return { success: true, version };
732
+ }
733
+ else {
734
+ // Extract error message from response
735
+ const errorMatch = text.match(/❌.*?(?:\n|$)/)?.[0] || text.substring(0, 200);
736
+ logger.error('Publish failed', { error: errorMatch });
737
+ return { success: false, error: errorMatch };
738
+ }
739
+ }
740
+ catch (error) {
741
+ const errorMessage = error instanceof Error ? error.message : String(error);
742
+ logger.error('Publish exception', { error: errorMessage });
743
+ return {
744
+ success: false,
745
+ error: errorMessage
746
+ };
747
+ }
748
+ }
749
+ /**
750
+ * Report progress to bug discussion
751
+ */
752
+ async reportProgress(bug, message) {
753
+ if (!bug.discussionId)
754
+ return;
755
+ try {
756
+ const { hailer } = this.userContext;
757
+ await hailer.sendDiscussionMessage(bug.discussionId, message);
758
+ }
759
+ catch (error) {
760
+ logger.warn('Failed to report progress', { bugId: bug.id, error });
761
+ }
762
+ }
763
+ }
764
+ exports.GiuseppeBot = GiuseppeBot;
765
+ //# sourceMappingURL=giuseppe-bot.js.map