-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2371 lines (1936 loc) · 74.5 KB
/
server.js
File metadata and controls
2371 lines (1936 loc) · 74.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const { execSync, exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
const azdev = require('azure-devops-node-api');
const { WorkItemExpand } = require('azure-devops-node-api/interfaces/WorkItemTrackingInterfaces');
const { BedrockRuntimeClient, InvokeModelCommand } = require('@aws-sdk/client-bedrock-runtime');
const { fromIni } = require('@aws-sdk/credential-provider-ini');
const PBIQualityAssessor = require('./pbi-quality-assessor');
const app = express();
const PORT = 3000;
// Check if Angular build exists
const distPath = path.join(__dirname, 'dist/pbi-pr-analyzer/browser/index.html');
if (!fs.existsSync(distPath)) {
console.error('');
console.error('============================================');
console.error(' ERROR: Angular build not found!');
console.error('============================================');
console.error('');
console.error('The Angular application has not been built yet.');
console.error('');
console.error('Please run: npm run build');
console.error('');
process.exit(1);
}
// Middleware
app.use(cors());
app.use(express.json());
// Configuration
const DEFAULT_ORG = 'https://dev.azure.com/gl-development';
const DEFAULT_PROJECT = 'Testwise';
const AZURE_DEVOPS_RESOURCE_ID = '499b84ac-1321-427f-aa17-267ca6975798';
const AWS_REGION = process.env.AWS_REGION || 'us-east-1';
const AWS_PROFILE = process.env.AWS_PROFILE || 'ai-tools-prod';
const BEDROCK_MODEL_ID = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'us.anthropic.claude-opus-4-6-v1';
// Azure token cache with TTL
let azureTokenCache = {
token: null,
expiresAt: 0
};
// Helper function to get Azure CLI access token with caching
async function getAzureToken() {
const now = Date.now();
// Return cached token if still valid (with 5min buffer before expiry)
if (azureTokenCache.token && azureTokenCache.expiresAt > now + 300000) {
console.log('✓ Using cached Azure token');
return azureTokenCache.token;
}
// Refresh token
try {
console.log('🔄 Fetching new Azure token...');
const { stdout } = await execAsync(
`az account get-access-token --resource ${AZURE_DEVOPS_RESOURCE_ID}`,
{
encoding: 'utf-8',
timeout: 10000
}
);
const tokenData = JSON.parse(stdout);
azureTokenCache.token = tokenData.accessToken;
azureTokenCache.expiresAt = now + 3600000; // 1 hour TTL
console.log('✓ Azure token cached');
return azureTokenCache.token;
} catch (error) {
throw new Error('Azure CLI not logged in. Please run "az login" first.');
}
}
// Synchronous version for backward compatibility (uses cache if available)
function getAzureTokenSync() {
if (azureTokenCache.token && azureTokenCache.expiresAt > Date.now() + 300000) {
return azureTokenCache.token;
}
// Fallback to sync call if no cache
try {
const result = execSync(`az account get-access-token --resource ${AZURE_DEVOPS_RESOURCE_ID}`, {
encoding: 'utf-8',
timeout: 10000
});
const tokenData = JSON.parse(result);
azureTokenCache.token = tokenData.accessToken;
azureTokenCache.expiresAt = Date.now() + 3600000;
return tokenData.accessToken;
} catch (error) {
throw new Error('Azure CLI not logged in. Please run "az login" first.');
}
}
// Helper function to get Bedrock client
function getBedrockClient() {
try {
const client = new BedrockRuntimeClient({
region: AWS_REGION,
credentials: fromIni({ profile: AWS_PROFILE })
});
return client;
} catch (error) {
throw new Error('Failed to create Bedrock client. Ensure AWS credentials are configured.');
}
}
// Helper function to call Claude via Bedrock
async function invokeClaudeOnBedrock(prompt) {
const client = getBedrockClient();
const payload = {
anthropic_version: 'bedrock-2023-05-31',
max_tokens: 16384, // Increased from 4096 to allow for comprehensive test plans
messages: [
{
role: 'user',
content: prompt
}
]
};
const command = new InvokeModelCommand({
modelId: BEDROCK_MODEL_ID,
contentType: 'application/json',
accept: 'application/json',
body: JSON.stringify(payload)
});
const response = await client.send(command);
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
return responseBody.content[0].text;
}
// Check Azure CLI authentication status
function checkAzureCliAuth() {
try {
execSync('az account show', { encoding: 'utf-8', timeout: 5000 });
return true;
} catch (error) {
return false;
}
}
// ============================================================================
// HELPER FUNCTIONS FOR TEST CASE EXPORT
// ============================================================================
/**
* Escape XML special characters for DevOps test steps
*/
function escapeXml(text) {
if (!text) return '';
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\n/g, ' ') // Replace newlines with spaces
.replace(/\s+/g, ' ') // Collapse multiple spaces
.trim();
}
/**
* Generate DevOps test steps XML format
*/
function generateDevOpsStepsXml(steps) {
if (!steps || steps.length === 0) {
return '<steps id="0" last="0"></steps>';
}
const stepElements = steps.map((step, index) => {
const stepId = index + 1;
const action = escapeXml(step.action || 'No action specified');
const expected = escapeXml(step.expected || 'No expected result specified');
return ` <step id="${stepId}" type="ActionStep">
<parameterizedString isformatted="true"><DIV><P>${action}</P></DIV></parameterizedString>
<parameterizedString isformatted="true"><DIV><P>${expected}</P></DIV></parameterizedString>
<description/>
</step>`;
}).join('\n');
return `<steps id="0" last="${steps.length}">
${stepElements}
</steps>`;
}
/**
* Parse Given/When/Then format
*/
function parseGivenWhenThen(content) {
const steps = [];
let description = '';
// Extract Given (preconditions)
const givenMatch = content.match(/\*\*Given:\*\*\s*(.+?)(?=\n\*\*When:|\n\*\*Then:|$)/s);
const given = givenMatch ? givenMatch[1].trim() : '';
// Extract When (action)
const whenMatch = content.match(/\*\*When:\*\*\s*(.+?)(?=\n\*\*Then:|\n\*\*Given:|$)/s);
const when = whenMatch ? whenMatch[1].trim() : '';
// Extract Then (expected result)
const thenMatch = content.match(/\*\*Then:\*\*\s*(.+?)(?=\n\*\*When:|\n\*\*Given:|\n##|$)/s);
const then = thenMatch ? thenMatch[1].trim() : '';
// Extract any content before Given/When/Then as description
const descMatch = content.match(/^([\s\S]+?)(?=\*\*Given:|\*\*When:|\*\*Then:)/);
if (descMatch) {
description = descMatch[1].trim();
}
// Create steps
if (given) {
steps.push({
action: `Precondition: ${given}`,
expected: 'Setup complete'
});
}
if (when && then) {
steps.push({
action: when,
expected: then
});
} else if (when) {
steps.push({
action: when,
expected: 'See description'
});
}
return { steps, description };
}
/**
* Parse numbered or bulleted list format
*/
function parseListSteps(content) {
const steps = [];
let description = '';
// Extract any content before first list item as description
const descMatch = content.match(/^([\s\S]+?)(?=^\d+\.\s+|^[-*]\s+)/m);
if (descMatch) {
description = descMatch[1].trim();
}
// Match list items (numbered or bulleted)
const listItemRegex = /^(?:\d+\.|\-|\*)\s+(.+?)$/gm;
let match;
while ((match = listItemRegex.exec(content)) !== null) {
const itemText = match[1].trim();
// Try to split into action/expected if there's an indicator
const expectedIndicators = ['Expected:', 'Result:', 'Verify:', 'Should:', 'Then:'];
let action = itemText;
let expected = 'Verify step completes successfully';
for (const indicator of expectedIndicators) {
if (itemText.includes(indicator)) {
const parts = itemText.split(indicator);
action = parts[0].trim();
expected = parts[1].trim();
break;
}
}
steps.push({ action, expected });
}
return { steps, description };
}
/**
* Parse test case content into structured format
* Handles multiple content structures
*/
function parseTestCaseContent(content, testCaseId) {
// Try to detect format
const hasGivenWhenThen = content.includes('**Given:**') || content.includes('**When:**') || content.includes('**Then:**');
const hasNumberedSteps = /^\d+\.\s+/m.test(content);
const hasBulletSteps = /^[-*]\s+/m.test(content);
let steps = [];
let description = '';
if (hasGivenWhenThen) {
// Parse Given/When/Then format
const result = parseGivenWhenThen(content);
steps = result.steps;
description = result.description;
} else if (hasNumberedSteps || hasBulletSteps) {
// Parse list-based format
const result = parseListSteps(content);
steps = result.steps;
description = result.description;
} else {
// Freeform text - treat entire content as description with single step
description = content;
steps = [{
action: 'Execute test case as described',
expected: 'See description for expected results'
}];
}
// Convert to DevOps XML format
const stepsXml = generateDevOpsStepsXml(steps);
return {
description: description || `Test case ${testCaseId}`,
stepsXml: stepsXml
};
}
/**
* Parse test cases from markdown - FORMAT AGNOSTIC
*
* Works with:
* - Given/When/Then format
* - Numbered steps
* - Bulleted lists
* - Freeform text
* - Mixed formats
*/
function parseTestCasesFromMarkdown(markdown) {
const testCases = [];
// Match test case headers - flexible patterns
// Matches: "## TC-001: Title", "### TC-001: Title", "## Test Case 1: Title", etc.
const headerRegex = /^(#{2,3})\s+(TC-\d+|Test Case \d+):\s*(.+?)$/gm;
let matches = [];
let match;
// Find all test case headers and their positions
while ((match = headerRegex.exec(markdown)) !== null) {
matches.push({
fullMatch: match[0],
headerLevel: match[1],
id: match[2],
title: match[3].trim(),
startIndex: match.index,
endIndex: match.index + match[0].length
});
}
if (matches.length === 0) {
console.warn('No test case headers found. Expected format: ## TC-001: Title');
return [];
}
// Extract content between headers
for (let i = 0; i < matches.length; i++) {
const current = matches[i];
const next = matches[i + 1];
// Content is from end of current header to start of next header (or end of string)
const contentStart = current.endIndex;
const contentEnd = next ? next.startIndex : markdown.length;
const rawContent = markdown.substring(contentStart, contentEnd).trim();
if (!rawContent) {
console.warn(`Test case ${current.id} has no content, skipping`);
continue;
}
// Parse content into structured format
const parsedContent = parseTestCaseContent(rawContent, current.id);
testCases.push({
id: current.id,
title: `${current.id}: ${current.title}`,
description: parsedContent.description,
steps: parsedContent.stepsXml,
rawContent: rawContent // Preserve for debugging
});
}
console.log(`Parsed ${testCases.length} test case(s) from markdown`);
return testCases;
}
/**
* Helper to flatten classification node tree (area paths, iterations)
*/
function flattenClassificationTree(node, prefix = '') {
const currentPath = prefix ? `${prefix}\\${node.name}` : node.name;
let paths = [currentPath];
if (node.children && node.children.length > 0) {
node.children.forEach(child => {
paths = paths.concat(flattenClassificationTree(child, currentPath));
});
}
return paths;
}
// API Routes
// Get settings/status
app.get('/api/settings', (req, res) => {
res.json({
azureDevOpsOrg: DEFAULT_ORG,
defaultProject: DEFAULT_PROJECT,
defaultRepository: '',
azureCliAuthenticated: checkAzureCliAuth(),
claudeApiKeySource: 'bedrock',
awsRegion: AWS_REGION,
awsProfile: AWS_PROFILE,
bedrockModelId: BEDROCK_MODEL_ID
});
});
// Get Work Item
app.get('/api/workitem/:id', async (req, res) => {
try {
const workItemId = parseInt(req.params.id);
const project = req.query.project || DEFAULT_PROJECT;
console.log(`Fetching work item ${workItemId} from project ${project}...`);
// Sanity check: Azure DevOps work item IDs must fit in Int32 (max 2147483647)
// Also check for obviously invalid values
if (workItemId > 2147483647 || workItemId < 1 || isNaN(workItemId)) {
console.error(`✗ Invalid work item ID: ${req.params.id} (parsed as ${workItemId})`);
return res.status(404).json({
success: false,
error: `Work item ${req.params.id} is not a valid work item ID. Work item IDs must be positive integers less than 2,147,483,647.`,
validationError: true
});
}
const token = await getAzureToken();
const authHandler = azdev.getBearerHandler(token);
const connection = new azdev.WebApi(DEFAULT_ORG, authHandler);
const witApi = await connection.getWorkItemTrackingApi(project);
// getWorkItem(id, fields, asOf, expand)
// Only fetch fields we actually use (performance optimization)
const workItem = await witApi.getWorkItem(
workItemId,
[
'System.Title',
'System.Description',
'Microsoft.VSTS.Common.AcceptanceCriteria',
'System.State',
'System.WorkItemType',
'System.AssignedTo'
],
undefined, // asOf
WorkItemExpand.None // Don't expand relations/links (performance optimization)
);
// Validate the work item response
if (!workItem) {
console.error(`Work item ${workItemId} returned null/undefined`);
return res.status(404).json({
success: false,
error: `Work item ${workItemId} not found. This could mean: (1) The ticket doesn't exist, (2) You don't have permission to view it, or (3) It's in a different project than '${project}'.`,
validationError: true
});
}
// Check for permissions/access issues - empty fields object is a telltale sign
if (!workItem.fields || Object.keys(workItem.fields).length === 0) {
console.error(`Work item ${workItemId} has no fields - likely a permissions issue`);
return res.status(403).json({
success: false,
error: `Unable to access work item ${workItemId}. You may not have permission to view this item or it may not exist in the specified project.`,
validationError: true
});
}
// Validate essential fields exist
const hasTitle = workItem.fields['System.Title'];
const hasWorkItemType = workItem.fields['System.WorkItemType'];
if (!hasTitle || !hasWorkItemType) {
console.error(`Work item ${workItemId} missing essential fields (Title: ${!!hasTitle}, Type: ${!!hasWorkItemType})`);
return res.status(403).json({
success: false,
error: `Work item ${workItemId} appears incomplete. This usually indicates insufficient permissions or the item doesn't exist.`,
validationError: true
});
}
console.log(`✓ Successfully fetched work item ${workItemId}: "${workItem.fields['System.Title']}"`);
res.json({ success: true, data: workItem });
} catch (error) {
console.error(`Error fetching work item ${req.params.id}:`, error);
console.error('Error type:', typeof error);
console.error('Error properties:', Object.keys(error));
// Log more details about the error structure for debugging
if (error.statusCode) console.error('Error statusCode:', error.statusCode);
if (error.status) console.error('Error status:', error.status);
if (error.code) console.error('Error code:', error.code);
console.error('Error stack:', error.stack);
// Check if this is a 404 error from Azure DevOps (multiple ways to detect)
const is404 =
error.statusCode === 404 ||
error.status === 404 ||
error.code === 404 ||
(error.message && (
error.message.includes('404') ||
error.message.includes('does not exist') ||
error.message.toLowerCase().includes('not found') ||
error.message.includes('Work item') && error.message.includes('does not exist')
));
if (is404) {
console.error('✗ Detected 404: Work item not found');
return res.status(404).json({
success: false,
error: `Work item ${req.params.id} not found. This could mean: (1) The ticket doesn't exist, (2) You don't have permission to view it, or (3) It's in a different project than '${req.query.project || DEFAULT_PROJECT}'.`,
validationError: true
});
}
// Check if this is an authentication/authorization error
const isAuthError =
error.statusCode === 401 ||
error.statusCode === 403 ||
error.status === 401 ||
error.status === 403 ||
(error.message && (
error.message.includes('unauthorized') ||
error.message.includes('forbidden') ||
error.message.includes('Access denied') ||
error.message.includes('authentication')
));
if (isAuthError) {
console.error('✗ Detected auth error: Access denied');
return res.status(403).json({
success: false,
error: `Access denied for work item ${req.params.id}. Please check your Azure DevOps permissions and PAT token.`,
validationError: true
});
}
// Check if this is a 400 Bad Request (invalid work item ID format)
const is400BadRequest =
error.statusCode === 400 ||
error.status === 400 ||
(error.message && (
error.message.includes('parameter conversion') ||
error.message.includes('System.Int32') ||
error.message.includes('BadRequest')
)) ||
(error.result && error.result.value && error.result.value.Message && (
error.result.value.Message.includes('parameter conversion') ||
error.result.value.Message.includes('System.Int32')
));
if (is400BadRequest) {
console.error('✗ Detected 400 Bad Request: Invalid work item ID format');
return res.status(404).json({
success: false,
error: `Work item ${req.params.id} is not a valid work item ID. Please check the ID and try again.`,
validationError: true
});
}
// Generic error
console.error('✗ Unhandled error type, returning 500');
res.status(500).json({
success: false,
error: error.message || 'An error occurred while fetching the work item',
details: `Error type: ${typeof error}, Status: ${error.statusCode || error.status || 'unknown'}`,
stack: error.stack
});
}
});
// Analyze with Claude
app.post('/api/analyze', async (req, res) => {
try {
const { data, analysisType, userFeedback, previousTestCases, additionalContext, generateAll } = req.body;
// Set up SSE headers for streaming progress
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no'); // Disable buffering in nginx
// Helper function to send SSE messages
const sendProgress = (message) => {
res.write(`data: ${JSON.stringify({ type: 'progress', message })}\n\n`);
console.log(` 📤 Sent progress: ${message}`);
};
console.log('');
console.log('============================================');
console.log(` Starting Analysis: ${analysisType}`);
console.log('============================================');
// Build request context once to avoid duplicate loading
console.time('⏱️ Request Context Load');
const requestContext = buildRequestContext();
console.timeEnd('⏱️ Request Context Load');
if (analysisType === 'testCases') {
// Log generation mode
if (generateAll) {
console.log('📋 Generating ALL test cases (comprehensive mode)');
} else {
console.log('📋 Generating Happy Path + Top 5 Critical tests (focused mode)');
}
// Log additional context if provided
if (additionalContext) {
console.log('📝 Additional Context from PBI Quality Assessment:');
console.log(` ${additionalContext.substring(0, 150).replace(/\n/g, '\n ')}${additionalContext.length > 150 ? '...' : ''}`);
} else {
console.log('ℹ No additional context provided from PBI Quality Assessment');
}
// If user provided feedback, use direct improvement flow
if (userFeedback && previousTestCases) {
console.log('🔄 User Feedback Mode - Improving existing test cases...');
console.log(` Feedback: "${userFeedback.substring(0, 100)}${userFeedback.length > 100 ? '...' : ''}"`);
sendProgress('Regenerating with feedback');
const result = await improveTestCasesWithFeedback(data, previousTestCases, userFeedback, additionalContext, sendProgress, requestContext, generateAll);
res.write(`data: ${JSON.stringify({
type: 'complete',
success: true,
data: result.testCases,
qualityScore: result.qualityScore,
iterations: 1
})}\n\n`);
res.end();
} else {
// Use iterative quality generation for initial test cases
const result = await generateTestCasesWithQuality(data, additionalContext, sendProgress, requestContext, generateAll);
res.write(`data: ${JSON.stringify({
type: 'complete',
success: true,
data: result.testCases,
qualityScore: result.qualityScore,
iterations: result.iterations
})}\n\n`);
res.end();
}
} else if (analysisType === 'pbiQualityAssessment') {
// PBI Quality Assessment using specialized assessor
console.log('📊 Using PBI Quality Assessor with rich system prompt and examples...');
sendProgress('Analyzing PBI quality');
const assessor = new PBIQualityAssessor(requestContext);
const payload = assessor.buildBedrockPayload(data);
const client = getBedrockClient();
const command = new InvokeModelCommand({
modelId: BEDROCK_MODEL_ID,
contentType: 'application/json',
accept: 'application/json',
body: JSON.stringify(payload)
});
console.log(`🤖 Calling Claude via AWS Bedrock (${BEDROCK_MODEL_ID})...`);
const response = await client.send(command);
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
const result = responseBody.content[0].text;
console.log('✓ Claude response received from Bedrock');
console.log('============================================');
console.log('');
res.write(`data: ${JSON.stringify({
type: 'complete',
success: true,
data: result
})}\n\n`);
res.end();
} else {
// Other analysis types use simple generation
let prompt = '';
let progressMsg = '';
switch (analysisType) {
case 'impactAnalysis':
prompt = buildImpactAnalysisPrompt(data);
progressMsg = 'Analyzing impact';
break;
case 'documentation':
prompt = buildDocumentationPrompt(data);
progressMsg = 'Generating documentation';
break;
default:
throw new Error(`Unknown analysis type: ${analysisType}`);
}
console.log(`🤖 Calling Claude via AWS Bedrock (${BEDROCK_MODEL_ID})...`);
sendProgress(progressMsg);
const result = await invokeClaudeOnBedrock(prompt);
console.log('✓ Claude response received from Bedrock');
console.log('============================================');
console.log('');
res.write(`data: ${JSON.stringify({
type: 'complete',
success: true,
data: result
})}\n\n`);
res.end();
}
} catch (error) {
console.error('Error in Claude analysis:', error);
console.error('Error stack:', error.stack);
res.write(`data: ${JSON.stringify({
type: 'error',
success: false,
error: error.message,
details: error.toString()
})}\n\n`);
res.end();
}
});
// ============================================================================
// AZURE DEVOPS TEST PLANS API ENDPOINTS
// ============================================================================
/**
* GET /api/project-info - Get project structure (area paths, iterations)
* Used to populate dropdowns for creating new test plans
*/
app.get('/api/project-info', async (req, res) => {
try {
const { project } = req.query;
const projectName = project || DEFAULT_PROJECT;
const token = await getAzureToken();
const authHandler = azdev.getBearerHandler(token);
const connection = new azdev.WebApi(DEFAULT_ORG, authHandler);
const witApi = await connection.getWorkItemTrackingApi();
const coreApi = await connection.getCoreApi();
// Get project details
const projectDetails = await coreApi.getProject(projectName);
// Get area paths - with fallback
let areaPaths = [projectName];
try {
const areaTree = await witApi.getClassificationNode(
projectName,
'Areas',
undefined,
10 // depth
);
areaPaths = flattenClassificationTree(areaTree);
} catch (areaError) {
console.warn('Could not fetch area paths, using default:', areaError.message);
}
// Get iteration paths - with fallback
let iterationPaths = [projectName];
try {
const iterationTree = await witApi.getClassificationNode(
projectName,
'Iterations',
undefined,
10 // depth
);
iterationPaths = flattenClassificationTree(iterationTree);
} catch (iterationError) {
console.warn('Could not fetch iteration paths, using default:', iterationError.message);
}
res.json({
success: true,
data: {
projectName: projectDetails.name,
areaPaths: areaPaths,
iterationPaths: iterationPaths,
defaultAreaPath: projectName,
defaultIteration: projectName
}
});
} catch (error) {
console.error('Error fetching project info:', error);
res.status(500).json({
success: false,
error: error.message
});
}
});
/**
* GET /api/test-plans - Get all test plans for a project
*/
app.get('/api/test-plans', async (req, res) => {
try {
const { project } = req.query;
const projectName = project || DEFAULT_PROJECT;
const token = await getAzureToken();
const authHandler = azdev.getBearerHandler(token);
const connection = new azdev.WebApi(DEFAULT_ORG, authHandler);
const testPlanApi = await connection.getTestPlanApi();
const testPlans = await testPlanApi.getTestPlans(projectName);
res.json({
success: true,
data: testPlans.map(plan => ({
id: plan.id,
name: plan.name,
state: plan.state,
iteration: plan.iteration,
areaPath: plan.areaPath,
rootSuite: plan.rootSuite ? {
id: plan.rootSuite.id,
name: plan.rootSuite.name
} : null
}))
});
} catch (error) {
console.error('Error fetching test plans:', error);
res.status(500).json({
success: false,
error: error.message
});
}
});
/**
* GET /api/test-suites - Get test suites for a test plan
*/
app.get('/api/test-suites', async (req, res) => {
try {
const { project, planId } = req.query;
const projectName = project || DEFAULT_PROJECT;
if (!planId) {
return res.status(400).json({
success: false,
error: 'planId is required'
});
}
const token = await getAzureToken();
const authHandler = azdev.getBearerHandler(token);
const connection = new azdev.WebApi(DEFAULT_ORG, authHandler);
const testPlanApi = await connection.getTestPlanApi();
// Get test plan to find root suite
const plan = await testPlanApi.getTestPlanById(projectName, parseInt(planId));
// Get all suites for the plan
const suites = await testPlanApi.getTestSuitesForPlan(projectName, parseInt(planId));
res.json({
success: true,
data: {
rootSuiteId: plan.rootSuite?.id,
suites: suites.map(suite => ({
id: suite.id,
name: suite.name,
suiteType: suite.suiteType,
parentSuiteId: suite.parentSuite?.id,
isRoot: suite.id === plan.rootSuite?.id
}))
}
});
} catch (error) {
console.error('Error fetching test suites:', error);
res.status(500).json({
success: false,
error: error.message
});
}
});
/**
* POST /api/test-plans - Create a new test plan
*/
app.post('/api/test-plans', async (req, res) => {
try {
const { project, name, areaPath, iteration } = req.body;
const projectName = project || DEFAULT_PROJECT;
if (!name) {
return res.status(400).json({
success: false,
error: 'Test plan name is required'
});
}
const token = await getAzureToken();
const authHandler = azdev.getBearerHandler(token);
const connection = new azdev.WebApi(DEFAULT_ORG, authHandler);
const testPlanApi = await connection.getTestPlanApi();
// Use provided paths or fallback to project name
const testPlanParams = {
name: name,
areaPath: areaPath || projectName,
iteration: iteration || projectName
};
console.log('Creating test plan:', testPlanParams);
const newPlan = await testPlanApi.createTestPlan(testPlanParams, projectName);
res.json({
success: true,
data: {
id: newPlan.id,
name: newPlan.name,
rootSuite: {
id: newPlan.rootSuite.id,
name: newPlan.rootSuite.name
}
}
});
} catch (error) {
console.error('Error creating test plan:', error);
// Better error messages
let errorMessage = error.message;
if (error.message.includes('area path')) {
errorMessage = 'Invalid area path. Please select a valid area path from the dropdown.';
} else if (error.message.includes('iteration')) {
errorMessage = 'Invalid iteration path. Please select a valid iteration from the dropdown.';
}
res.status(500).json({
success: false,
error: errorMessage
});
}
});
/**
* POST /api/test-suites - Create a new test suite
*/
app.post('/api/test-suites', async (req, res) => {
try {
const { project, planId, name, suiteType, parentSuiteId, requirementId } = req.body;
const projectName = project || DEFAULT_PROJECT;
if (!planId || !name) {
return res.status(400).json({
success: false,
error: 'planId and name are required'
});
}
const token = await getAzureToken();
const authHandler = azdev.getBearerHandler(token);
const connection = new azdev.WebApi(DEFAULT_ORG, authHandler);
const testPlanApi = await connection.getTestPlanApi();
// If no parent suite provided, get the root suite of the plan
let actualParentSuiteId = parentSuiteId;
if (!actualParentSuiteId) {
const plan = await testPlanApi.getTestPlanById(projectName, parseInt(planId));
if (!plan.rootSuite || !plan.rootSuite.id) {
throw new Error('Could not determine root suite for test plan');
}
actualParentSuiteId = plan.rootSuite.id;
console.log(`Using root suite ${actualParentSuiteId} as parent for new suite`);
}
const suiteParams = {
name: name,
suiteType: suiteType || 'StaticTestSuite',
parentSuite: { id: actualParentSuiteId }
};
// For requirement-based suites
if (suiteType === 'RequirementTestSuite') {
if (!requirementId) {
return res.status(400).json({
success: false,
error: 'requirementId is required for requirement-based test suites'
});
}
suiteParams.requirementId = requirementId;
}
console.log('Creating test suite:', suiteParams);