-
Notifications
You must be signed in to change notification settings - Fork 31.9k
Expand file tree
/
Copy pathpr-status.js
More file actions
1747 lines (1552 loc) · 50.1 KB
/
Copy pathpr-status.js
File metadata and controls
1747 lines (1552 loc) · 50.1 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 { execSync, execFileSync, spawn } = require('child_process')
const fs = require('fs/promises')
const path = require('path')
const OUTPUT_ROOT = path.join(__dirname, 'pr-status')
const RESULTS_DIR = path.join(OUTPUT_ROOT, 'results')
const INTERMEDIATE_DIR = path.join(OUTPUT_ROOT, 'intermediate')
const ANSI_RE = new RegExp(String.raw`\u001B\[[0-9;]*[A-Za-z]`, 'g')
const JOBS_PAGE_SIZE = 30
// ============================================================================
// Helper Functions
// ============================================================================
function exec(cmd) {
try {
return execSync(cmd, {
encoding: 'utf8',
maxBuffer: 50 * 1024 * 1024, // 50MB for large logs
}).trim()
} catch (error) {
console.error(`Command failed: ${cmd}`)
console.error(error.stderr || error.message)
throw error
}
}
function execAsync(prog, args) {
return new Promise((resolve, reject) => {
const child = spawn(prog, args, {
stdio: ['ignore', 'pipe', 'pipe'],
})
const chunks = []
let stderr = ''
child.stdout.on('data', (chunk) => chunks.push(chunk))
child.stderr.on('data', (chunk) => {
stderr += chunk
})
child.on('close', (code) => {
if (code !== 0) {
const error = new Error(`Command failed: ${prog} ${args.join(' ')}`)
error.stderr = stderr
reject(error)
} else {
resolve(Buffer.concat(chunks).toString('utf8').trim())
}
})
child.on('error', reject)
})
}
function execJson(cmd) {
const output = exec(cmd)
return JSON.parse(output)
}
function formatDuration(startedAt, completedAt) {
if (!startedAt || !completedAt) return 'N/A'
const start = new Date(startedAt)
const end = new Date(completedAt)
// Validate that both dates are valid (not Invalid Date objects)
if (isNaN(start.getTime()) || isNaN(end.getTime())) return 'N/A'
const seconds = Math.floor((end - start) / 1000)
if (seconds < 60) return `${seconds}s`
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}m ${remainingSeconds}s`
}
function formatElapsedTime(startedAt) {
if (!startedAt) return 'N/A'
const start = new Date(startedAt)
if (isNaN(start.getTime())) return 'N/A'
const now = new Date()
const seconds = Math.floor((now - start) / 1000)
if (seconds < 60) return `${seconds}s`
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}m ${remainingSeconds}s`
}
function sanitizeFilename(name) {
return name
.replace(/[^a-zA-Z0-9._-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.substring(0, 100)
}
function resultPath(...segments) {
return path.join(RESULTS_DIR, ...segments)
}
function intermediatePath(...segments) {
return path.join(INTERMEDIATE_DIR, ...segments)
}
function escapeMarkdownTableCell(text) {
if (!text) return ''
// Escape pipe characters and newlines for markdown table cells
return String(text)
.replace(/\|/g, '\\|')
.replace(/\n/g, ' ')
.replace(/\r/g, '')
}
function stripTimestamps(logContent) {
// Remove GitHub Actions timestamp prefixes like "2026-01-23T10:11:12.8077557Z "
return logContent.replace(/^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s/gm, '')
}
function stripAnsi(text) {
return String(text || '').replace(ANSI_RE, '')
}
function truncate(text, maxLength) {
const value = String(text || '')
if (value.length <= maxLength) return value
return `${value.substring(0, maxLength)}...`
}
function normalizeTestPath(testName) {
const normalized = String(testName || '').replace(/\\/g, '/')
const match = normalized.match(/(?:^|\/)(test\/.*)$/)
return match ? match[1] : normalized
}
function formatFailedAssertionName(assertion) {
const ancestors = assertion?.ancestorTitles || []
const title = assertion?.title || assertion?.fullName || 'Unknown test'
return [...ancestors, title].filter(Boolean).join(' > ')
}
function collectFailureMessages(testResult) {
return (testResult?.assertionResults || [])
.flatMap((assertion) => assertion.failureMessages || [])
.join('\n\n')
}
function isBot(username) {
if (!username) return false
return username.endsWith('-bot') || username.endsWith('[bot]')
}
/**
* Parses the build_and_test.yml workflow to extract env vars from afterBuild
* sections. Returns a map of job display name prefix → env var list.
*/
function getJobEnvVarsFromWorkflow() {
const workflowPath = path.join(
__dirname,
'..',
'.github',
'workflows',
'build_and_test.yml'
)
try {
const content = require('fs').readFileSync(workflowPath, 'utf8')
const envMap = {}
// Match job blocks: " job-id:\n name: display name\n" ... "afterBuild: |"
const jobRegex =
/^ {2}([\w-]+):\s*\n\s+name:\s*(.+)\n[\s\S]*?afterBuild:\s*\|\n([\s\S]*?)(?=\n\s+stepName:)/gm
let match
while ((match = jobRegex.exec(content)) !== null) {
const displayName = match[2].trim()
const afterBuild = match[3]
const exports = []
for (const line of afterBuild.split('\n')) {
const exportMatch = line.match(/^\s*export\s+([\w]+)=(.*)$/)
if (exportMatch) {
let value = exportMatch[2].trim()
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.substring(1, value.length - 1)
}
if (value) {
exports.push(`${exportMatch[1]}=${value}`)
}
}
}
if (exports.length > 0) {
envMap[displayName] = exports
}
}
return envMap
} catch {
return {}
}
}
/**
* Given a job name like "test node streams prod (4/7) / build" and the env map,
* returns the relevant env vars or null.
*/
function getEnvVarsForJob(jobName, envMap) {
for (const [prefix, vars] of Object.entries(envMap)) {
if (jobName.startsWith(prefix)) {
return vars
}
}
return null
}
// ============================================================================
// Data Fetching Functions
// ============================================================================
function getBranchInfo(prNumberArg) {
// If PR number provided as argument, fetch branch from that PR
if (prNumberArg) {
try {
const output = exec(`gh pr view ${prNumberArg} --json number,headRefName`)
const data = JSON.parse(output)
if (data.number && data.headRefName) {
return { prNumber: String(data.number), branchName: data.headRefName }
}
} catch {
console.error(`Failed to fetch PR #${prNumberArg}`)
process.exit(1)
}
}
// Auto-detect from current branch/PR context
try {
const output = exec(`gh pr view --json number,headRefName`)
const data = JSON.parse(output)
if (data.number && data.headRefName) {
return { prNumber: String(data.number), branchName: data.headRefName }
}
} catch {
// Fallback to git if not in PR context
}
const branchName = exec('git rev-parse --abbrev-ref HEAD')
return { prNumber: null, branchName }
}
function getWorkflowRuns(branch) {
const encodedBranch = encodeURIComponent(branch)
const jqQuery =
'.workflow_runs[] | select(.name == "build-and-test") | {id, run_attempt, status, conclusion}'
const output = exec(
`gh api "repos/vercel/next.js/actions/runs?branch=${encodedBranch}&per_page=10" --jq '${jqQuery}'`
)
if (!output.trim()) return []
return output
.split('\n')
.filter((line) => line.trim())
.map((line) => JSON.parse(line))
}
function getRunMetadata(runId) {
return execJson(
`gh api "repos/vercel/next.js/actions/runs/${runId}" --jq '{id, name, status, conclusion, run_attempt, html_url, head_sha, created_at, updated_at}'`
)
}
const FAILED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure'])
function getFailedJobs(runId) {
// Fetch all jobs first, then filter for failures in JS.
// We can't use jq filtering during pagination because a page full of
// non-failure jobs produces empty jq output, which would incorrectly
// stop pagination before reaching later pages that contain failures.
const allJobs = getAllJobs(runId)
return allJobs
.filter((j) => FAILED_CONCLUSIONS.has(j.conclusion))
.map((j) => ({ id: j.id, name: j.name, conclusion: j.conclusion }))
}
function getAllJobs(runId) {
const allJobs = []
let page = 1
while (true) {
const jqQuery =
'.jobs[] | {id, name, status, conclusion, started_at, completed_at}'
let output
let lastError
// Retry up to 3 times for transient API errors (e.g. HTTP 502)
for (let attempt = 1; attempt <= 3; attempt++) {
try {
output = exec(
`gh api "repos/vercel/next.js/actions/runs/${runId}/jobs?per_page=${JOBS_PAGE_SIZE}&page=${page}" --jq '${jqQuery}'`
)
lastError = null
break
} catch (error) {
lastError = error
if (attempt < 3) {
const delay = attempt * 2000
console.error(
`API request failed (attempt ${attempt}/3), retrying in ${delay / 1000}s...`
)
execSync(`sleep ${delay / 1000}`)
}
}
}
if (lastError) {
// If all retries failed on the first page, we have no data at all — throw
// so callers know the fetch failed instead of silently returning [].
if (page === 1) {
throw new Error(
`Failed to fetch jobs for run ${runId} after 3 attempts: ${lastError.message}`
)
}
// For later pages we already have partial data; warn and return what we have
console.error(
`Warning: Failed to fetch page ${page} of jobs after 3 attempts. Returning ${allJobs.length} jobs from previous pages.`
)
break
}
if (!output.trim()) break
const jobs = output
.split('\n')
.filter((line) => line.trim())
.map((line) => JSON.parse(line))
allJobs.push(...jobs)
if (jobs.length < JOBS_PAGE_SIZE) break
page++
}
return allJobs
}
function categorizeJobs(jobs) {
return {
failed: jobs.filter((j) => FAILED_CONCLUSIONS.has(j.conclusion)),
inProgress: jobs.filter((j) => j.status === 'in_progress'),
queued: jobs.filter((j) => j.status === 'queued'),
succeeded: jobs.filter((j) => j.conclusion === 'success'),
cancelled: jobs.filter((j) => j.conclusion === 'cancelled'),
skipped: jobs.filter((j) => j.conclusion === 'skipped'),
}
}
function getJobMetadata(jobId) {
return execJson(
`gh api "repos/vercel/next.js/actions/jobs/${jobId}" --jq '{id, name, status, conclusion, started_at, completed_at, html_url}'`
)
}
async function getJobLogs(jobId) {
try {
return await execAsync('gh', [
'api',
`repos/vercel/next.js/actions/jobs/${jobId}/logs`,
])
} catch {
return 'Logs not available'
}
}
function getPRReviews(prNumber) {
try {
const reviews = execJson(
`gh api "repos/vercel/next.js/pulls/${prNumber}/reviews" --jq '[.[] | {id, user: .user.login, state: .state, body: .body, submitted_at: .submitted_at, html_url: .html_url}]'`
)
return reviews.filter((r) => !isBot(r.user))
} catch {
return []
}
}
function getPRReviewThreads(prNumber) {
const query = `
query {
repository(owner:"vercel", name:"next.js") {
pullRequest(number:${prNumber}) {
reviewThreads(first:100) {
nodes {
id
isResolved
path
line
startLine
diffSide
comments(first:50) {
nodes {
id
author { login }
body
createdAt
url
diffHunk
}
}
}
}
}
}
}
`
try {
const output = exec(`gh api graphql -f query='${query}'`)
const data = JSON.parse(output)
return data.data.repository.pullRequest.reviewThreads.nodes
} catch {
return []
}
}
function getPRComments(prNumber) {
try {
const comments = execJson(
`gh api "repos/vercel/next.js/issues/${prNumber}/comments" --jq '[.[] | {id, user: .user.login, body: .body, created_at: .created_at, html_url: .html_url}]'`
)
return comments.filter((c) => !isBot(c.user))
} catch {
return []
}
}
// ============================================================================
// Thread Interaction Functions
// ============================================================================
function replyToThread(threadId, body) {
body = ':robot: ' + body
// Step 1: Look up the PR number and first comment's databaseId from the
// thread's GraphQL node ID. The REST reply endpoint requires both.
const lookupQuery = `
query($id: ID!) {
node(id: $id) {
... on PullRequestReviewThread {
pullRequest {
number
}
comments(first: 1) {
nodes {
databaseId
}
}
}
}
}
`
let prNumber, commentDatabaseId
try {
const lookupOutput = execFileSync(
'gh',
['api', 'graphql', '-f', `query=${lookupQuery}`, '-f', `id=${threadId}`],
{ encoding: 'utf8' }
).trim()
const lookupData = JSON.parse(lookupOutput)
const thread = lookupData.data.node
if (!thread || !thread.pullRequest || !thread.comments?.nodes?.[0]) {
console.error(`Could not resolve thread node ID: ${threadId}`)
process.exit(1)
}
prNumber = thread.pullRequest.number
commentDatabaseId = thread.comments.nodes[0].databaseId
} catch (error) {
console.error(
'Failed to look up thread info:',
error.stderr || error.message
)
process.exit(1)
}
// Step 2: Post the reply via REST. Unlike the GraphQL mutation
// addPullRequestReviewThreadReply, this endpoint always publishes the reply
// immediately — it is never attached to a pending/draft review.
try {
const output = execFileSync(
'gh',
[
'api',
'--method',
'POST',
`/repos/vercel/next.js/pulls/${prNumber}/comments/${commentDatabaseId}/replies`,
'-f',
`body=${body}`,
],
{ encoding: 'utf8' }
).trim()
const data = JSON.parse(output)
console.log(`Reply posted: ${data.html_url}`)
} catch (error) {
console.error('Failed to reply to thread:', error.stderr || error.message)
process.exit(1)
}
}
function resolveThread(threadId) {
const mutation = `
mutation($threadId: ID!) {
resolveReviewThread(input: {
threadId: $threadId
}) {
thread {
id
isResolved
}
}
}
`
try {
const output = execFileSync(
'gh',
[
'api',
'graphql',
'-f',
`query=${mutation}`,
'-f',
`threadId=${threadId}`,
],
{ encoding: 'utf8' }
).trim()
const data = JSON.parse(output)
const thread = data.data.resolveReviewThread.thread
if (thread.isResolved) {
console.log(`Thread ${threadId} resolved successfully.`)
} else {
console.log('Warning: Thread may not have been resolved.')
}
} catch (error) {
console.error('Failed to resolve thread:', error.stderr || error.message)
process.exit(1)
}
}
// ============================================================================
// Log Parsing Functions
// ============================================================================
function extractTestOutputJson(logContent) {
// Extract all --test output start-- {JSON} --test output end-- blocks
const results = []
const regex = /--test output start--\s*(\{[\s\S]*?\})\s*--test output end--/g
let match = regex.exec(logContent)
while (match !== null) {
try {
const json = JSON.parse(match[1])
results.push(json)
} catch {
// Skip invalid JSON
}
match = regex.exec(logContent)
}
return results
}
function extractTestCaseGroups(logContent) {
// Extract ##[group]❌ test/... ##[endgroup] blocks
// Combine multiple retries of the same test into one entry
const groupsByPath = new Map()
const regex =
/##\[group\]❌\s*(test\/[^\s]+)\s+output([\s\S]*?)##\[endgroup\]/g
let match = regex.exec(logContent)
while (match !== null) {
const testPath = match[1]
const content = stripTimestamps(match[2].trim())
if (groupsByPath.has(testPath)) {
// Append retry content with a separator
const existing = groupsByPath.get(testPath)
groupsByPath.set(testPath, `${existing}\n\n--- RETRY ---\n\n${content}`)
} else {
groupsByPath.set(testPath, content)
}
match = regex.exec(logContent)
}
const groups = []
for (const [testPath, content] of groupsByPath) {
groups.push({ testPath, content })
}
return groups
}
function extractStructuredTestFiles(testResults) {
const testsByPath = new Map()
for (const result of testResults) {
const resultTestFiles = result.testResults || []
for (const testResult of resultTestFiles) {
const failedAssertions = (testResult.assertionResults || [])
.filter((assertion) => assertion.status === 'failed')
.map((assertion) => ({
name: formatFailedAssertionName(assertion),
message: stripAnsi(
(assertion.failureMessages || []).join('\n\n') || testResult.message
).trim(),
}))
const failed =
testResult.status === 'failed' ||
failedAssertions.length > 0 ||
(resultTestFiles.length === 1 && (result.numFailedTests || 0) > 0)
if (!failed) continue
const testPath = normalizeTestPath(testResult.name)
if (!testsByPath.has(testPath)) {
testsByPath.set(testPath, {
testPath,
attempts: [],
rawOutput: null,
})
}
testsByPath.get(testPath).attempts.push({
status: testResult.status || 'unknown',
processEnv: result.processEnv || {},
summary: {
failed: result.numFailedTests || failedAssertions.length,
passed: result.numPassedTests || 0,
total: result.numTotalTests || 0,
},
message: stripAnsi(
testResult.message || collectFailureMessages(testResult)
).trim(),
failedAssertions,
})
}
}
return [...testsByPath.values()].sort((a, b) =>
a.testPath.localeCompare(b.testPath)
)
}
function mergeRawTestOutputs(structuredTestFiles, rawTestGroups) {
const testsByPath = new Map(
structuredTestFiles.map((testFile) => [testFile.testPath, testFile])
)
for (const rawGroup of rawTestGroups) {
const existing = testsByPath.get(rawGroup.testPath)
if (existing) {
existing.rawOutput = rawGroup.content
} else {
testsByPath.set(rawGroup.testPath, {
testPath: rawGroup.testPath,
attempts: [],
rawOutput: rawGroup.content,
})
}
}
return [...testsByPath.values()].sort((a, b) =>
a.testPath.localeCompare(b.testPath)
)
}
function extractSections(logContent) {
// Split the log into sections at ##[group] and ##[endgroup] boundaries
const sections = []
const lines = logContent.split('\n')
let currentSection = { name: null, startLine: 0 }
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
// Check for group start
const groupMatch = line.match(/##\[group\](.*)/)
if (groupMatch) {
// End current section
const lineCount = i - currentSection.startLine
if (lineCount > 0 || sections.length === 0) {
const rawContent = lines.slice(currentSection.startLine, i).join('\n')
const hasError = rawContent.includes('##[error]')
const content = stripTimestamps(rawContent.trim())
sections.push({
name: currentSection.name,
lineCount: lineCount,
content: content,
hasError: hasError,
})
}
// Start new section with group name
currentSection = { name: groupMatch[1].trim() || null, startLine: i + 1 }
continue
}
// Check for group end
if (line.includes('##[endgroup]')) {
// End current section
const lineCount = i - currentSection.startLine
const rawContent = lines.slice(currentSection.startLine, i).join('\n')
const hasError = rawContent.includes('##[error]')
const content = stripTimestamps(rawContent.trim())
sections.push({
name: currentSection.name,
lineCount: lineCount,
content: content,
hasError: hasError,
})
// Start new section with no name
currentSection = { name: null, startLine: i + 1 }
continue
}
}
// Add final section if there are remaining lines
const finalLineCount = lines.length - currentSection.startLine
if (finalLineCount > 0) {
const rawContent = lines.slice(currentSection.startLine).join('\n')
const hasError = rawContent.includes('##[error]')
const content = stripTimestamps(rawContent.trim())
sections.push({
name: currentSection.name,
lineCount: finalLineCount,
content: content,
hasError: hasError,
})
}
return sections
}
// ============================================================================
// Markdown Generation Functions
// ============================================================================
function generateIndexMd(
branchInfo,
runMetadata,
categorizedJobs,
jobTestCounts,
reviewData,
jobEnvMap,
flakyTests
) {
const { failed, inProgress, queued, succeeded, cancelled, skipped } =
categorizedJobs
const totalJobs =
failed.length +
inProgress.length +
queued.length +
succeeded.length +
cancelled.length +
skipped.length
const completedJobs =
failed.length + succeeded.length + cancelled.length + skipped.length
const isRunComplete = runMetadata.status === 'completed'
const reportTitle = isRunComplete
? '# CI Failures Report'
: '# CI Status Report'
const lines = [reportTitle, '', `Branch: ${branchInfo.branchName}`]
if (branchInfo.prNumber) {
lines.push(`PR: #${branchInfo.prNumber}`)
}
const statusStr = runMetadata.conclusion
? `${runMetadata.status}/${runMetadata.conclusion}`
: runMetadata.status
lines.push(
`Run: ${runMetadata.id} (attempt ${runMetadata.run_attempt})`,
`Status: ${statusStr}`,
`Time: ${runMetadata.created_at} - ${runMetadata.updated_at || 'ongoing'}`,
`URL: ${runMetadata.html_url}`,
''
)
// Progress summary for in-progress runs
if (!isRunComplete) {
lines.push(
'## CI Progress',
'',
`**${completedJobs}/${totalJobs}** jobs completed`,
'',
'| Status | Count |',
'|--------|-------|',
`| Failed | ${failed.length} |`,
`| In Progress | ${inProgress.length} |`,
`| Queued | ${queued.length} |`,
`| Succeeded | ${succeeded.length} |`
)
if (cancelled.length > 0) lines.push(`| Cancelled | ${cancelled.length} |`)
if (skipped.length > 0) lines.push(`| Skipped | ${skipped.length} |`)
lines.push(
'',
'> **Note:** CI is still running. Re-run this script later for updated results.',
''
)
}
// Failed jobs section
if (failed.length > 0) {
lines.push(
`## Failed Jobs (${failed.length})`,
'',
'| Job | Name | Duration | Tests | File |',
'|-----|------|----------|-------|------|'
)
for (const job of failed) {
const duration = formatDuration(job.started_at, job.completed_at)
const testCount = jobTestCounts[job.id]
const testsStr = testCount
? `${testCount.failed}/${testCount.total}`
: 'N/A'
const nameStr = escapeMarkdownTableCell(job.name)
const conclusionTag =
job.conclusion && job.conclusion !== 'failure'
? ` (${job.conclusion})`
: ''
lines.push(
`| ${job.id} | ${nameStr}${conclusionTag} | ${duration} | ${testsStr} | [Details](job-${job.id}.md) |`
)
}
lines.push('')
// Show env vars for failed jobs if they differ from defaults
if (jobEnvMap && Object.keys(jobEnvMap).length > 0) {
const jobEnvGroups = new Map()
for (const job of failed) {
const envVars = getEnvVarsForJob(job.name, jobEnvMap)
if (envVars) {
const key = envVars.join(', ')
if (!jobEnvGroups.has(key)) {
jobEnvGroups.set(key, [])
}
jobEnvGroups.get(key).push(job.name)
}
}
if (jobEnvGroups.size > 0) {
lines.push('### Job Environment Variables', '')
for (const [envStr, jobNames] of jobEnvGroups) {
const prefix = jobNames[0].replace(/ \(.*/, '')
lines.push(`**${prefix}**: \`${envStr}\``, '')
}
}
}
// Known flaky tests section
if (flakyTests && flakyTests.size > 0) {
lines.push('### Known Flaky Tests (failing on 2+ branches)', '')
lines.push(
'These tests also failed in recent CI runs across multiple different branches and are likely pre-existing flakes, not caused by this PR:',
''
)
for (const testPath of [...flakyTests].sort()) {
lines.push(`- \`${testPath}\``)
}
lines.push('')
}
}
// In-progress jobs section (only when CI is running)
if (inProgress.length > 0) {
lines.push(
`## In Progress Jobs (${inProgress.length})`,
'',
'| Job | Name | Running For |',
'|-----|------|-------------|'
)
for (const job of inProgress) {
const elapsed = formatElapsedTime(job.started_at)
lines.push(
`| ${job.id} | ${escapeMarkdownTableCell(job.name)} | ${elapsed} |`
)
}
lines.push('')
}
// Queued jobs section (only when CI is running)
if (queued.length > 0) {
lines.push(
`## Queued Jobs (${queued.length})`,
'',
'| Job | Name |',
'|-----|------|'
)
for (const job of queued) {
lines.push(`| ${job.id} | ${escapeMarkdownTableCell(job.name)} |`)
}
lines.push('')
}
// Add PR reviews section if we have review data
if (reviewData) {
const { reviews, reviewThreads, prComments } = reviewData
// Filter reviews to only include meaningful ones
const meaningfulReviews = reviews.filter(
(r) =>
r.state === 'APPROVED' ||
r.state === 'CHANGES_REQUESTED' ||
r.body?.trim()
)
if (meaningfulReviews.length > 0 || prComments.length > 0) {
lines.push('', `## PR Reviews (${meaningfulReviews.length})`, '')
if (meaningfulReviews.length > 0) {
lines.push(
'| Reviewer | State | Date/Time | Comment |',
'|----------|-------|-----------|---------|'
)
// Sort reviews by date, oldest first
const sortedReviews = [...meaningfulReviews].sort(
(a, b) => new Date(a.submitted_at) - new Date(b.submitted_at)
)
for (const review of sortedReviews) {
const time = review.submitted_at
? new Date(review.submitted_at)
.toISOString()
.replace('T', ' ')
.substring(0, 19)
: 'N/A'
const hasComment = review.body?.trim()
const commentLink = hasComment ? `[View](review-${review.id}.md)` : ''
lines.push(
`| ${escapeMarkdownTableCell(review.user)} | ${review.state} | ${time} | ${commentLink} |`
)
}
}
}
if (reviewThreads.length > 0) {
lines.push(
'',
`## Inline Review Comments (${reviewThreads.length} threads)`,
'',
'| File | Line | Participants | Replies | Status | Details |',
'|------|------|--------------|---------|--------|---------|'
)
for (let i = 0; i < reviewThreads.length; i++) {
const thread = reviewThreads[i]
const line = thread.line || thread.startLine || 'N/A'
const participants = new Set()
for (const comment of thread.comments.nodes) {
if (comment.author?.login) participants.add(comment.author.login)
}
const participantsStr =
participants.size > 0 ? [...participants].join(', ') : 'Unknown'
const replyCount = Math.max(0, thread.comments.nodes.length - 1)
const status = thread.isResolved ? 'Resolved' : 'Open'
lines.push(
`| ${escapeMarkdownTableCell(thread.path)} | ${line} | ${participantsStr} | ${replyCount} | ${status} | [View](thread-${i + 1}.md) |`
)
}
}
// General comments section
if (prComments.length > 0) {
lines.push(
'',
`## General Comments (${prComments.length})`,
'',
'| Author | Date/Time | Details |',
'|--------|-----------|---------|'
)
const sortedComments = [...prComments].sort(
(a, b) => new Date(a.created_at) - new Date(b.created_at)
)
for (const comment of sortedComments) {
const time = comment.created_at
? new Date(comment.created_at)
.toISOString()
.replace('T', ' ')
.substring(0, 19)
: 'N/A'
lines.push(
`| ${escapeMarkdownTableCell(comment.user)} | ${time} | [View](comment-${comment.id}.md) |`
)
}
}
}
return lines.join('\n')
}
function generateJobMd(jobMetadata, testResults, testFiles, sections) {
const duration = formatDuration(
jobMetadata.started_at,
jobMetadata.completed_at