-
Notifications
You must be signed in to change notification settings - Fork 501
Expand file tree
/
Copy pathhandle_agent_failure.cjs
More file actions
3139 lines (2788 loc) · 135 KB
/
Copy pathhandle_agent_failure.cjs
File metadata and controls
3139 lines (2788 loc) · 135 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
// @ts-check
/// <reference types="@actions/github-script" />
const { getErrorMessage } = require("./error_helpers.cjs");
const { sanitizeContent } = require("./sanitize_content.cjs");
const { getDetectionCautionAlert, getFooterAgentFailureIssueMessage, getFooterAgentFailureCommentMessage, generateXMLMarker } = require("./messages.cjs");
const { renderTemplate, renderTemplateFromFile, getPromptPath } = require("./messages_core.cjs");
const { getCurrentBranch } = require("./get_current_branch.cjs");
const { createExpirationLine, extractExpirationDate, generateFooterWithExpiration } = require("./ephemerals.cjs");
const { MAX_SUB_ISSUES, getSubIssueCount } = require("./sub_issue_helpers.cjs");
const { formatMissingData, formatMissingTools } = require("./missing_info_formatter.cjs");
const { generateHistoryUrl } = require("./generate_history_link.cjs");
const { AWF_INFRA_LINE_RE } = require("./log_parser_shared.cjs");
const { resolveFirewallAuditLogPath, resolveAICreditsFailureState, parseMaxAICreditsFromAuditLog, parseAICreditsErrorInfoFromAuditLog } = require("./ai_credits_context.cjs");
const { formatAICCredits } = require("./daily_aic_workflow_helpers.cjs");
const { formatAIC } = require("./model_costs.cjs");
const { parseTokenUsageJsonl, generateTokenUsageSummary } = require("./parse_mcp_gateway_log.cjs");
const { readDedupedTokenUsage, TOKEN_USAGE_PATHS } = require("./parse_token_usage.cjs");
const fs = require("fs");
const os = require("os");
const path = require("path");
const DEFAULT_ACTION_FAILURE_ISSUE_EXPIRES_HOURS = 24 * 7;
const FAILURE_ISSUE_DEDUP_WINDOW_HOURS = 24;
const FAILURE_ISSUE_CATEGORY_DAILY_CAP = 50;
const FAILURE_ISSUE_WINDOW_MS = FAILURE_ISSUE_DEDUP_WINDOW_HOURS * 60 * 60 * 1000;
const DEFAULT_OTEL_JSONL_PATH = "/tmp/gh-aw/otel.jsonl";
const GITHUB_API_VERSION = "2022-11-28";
const COPILOT_SESSION_STATE_DIR = path.join(os.tmpdir(), "gh-aw", "sandbox", "agent", "logs", "copilot-session-state");
// Engine-side 429/rate-limit signatures:
// - HTTP 429 accompanied by "too many requests"/"rate limit" phrasing
// - provider error codes like rate_limit_error / rate_limit_exceeded
// - Copilot/CAPI "CAPIError: 429" and utility-model quota text
// - retry wrapper text that includes the canonical "Failed to get response..." phrase
const ENGINE_RATE_LIMIT_429_RE =
/(?:\b429\b[\s\S]{0,120}(?:too many requests|rate[\s-]*limit)|rate_limit_(?:error|exceeded)|capierror:\s*429|failed to get response from the ai model[\s\S]{0,120}\b429\b|exceeded your rate limit for utility models)/i;
/**
* Parse action failure issue expiration from environment.
* @returns {number} Expiration in hours (defaults to 168 when unset/invalid)
*/
function getActionFailureIssueExpiresHours() {
const raw = process.env.GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS || "";
const parsed = Number.parseInt(raw, 10);
if (Number.isInteger(parsed) && parsed > 0) {
return parsed;
}
return DEFAULT_ACTION_FAILURE_ISSUE_EXPIRES_HOURS;
}
/**
* Build a GitHub markdown warning alert line.
* @param {string} title
* @param {string} message
* @returns {string}
*/
function buildWarningAlertLine(title, message) {
return `\n> [!WARNING]\n> **${title}**: ${message}\n`;
}
/**
* Render a prompt template from runtime prompts.
* @param {string} templateName
* @param {Record<string, string|number|boolean|undefined>} [context]
* @returns {string}
*/
function renderPromptTemplate(templateName, context = {}) {
return renderTemplateFromFile(getPromptPath(templateName), context);
}
/**
* Attempt to find a pull request for the current branch
* @returns {Promise<{number: number, html_url: string, head_sha: string, mergeable: boolean | null, mergeable_state: string, updated_at: string} | null>} PR info or null if not found
*/
async function findPullRequestForCurrentBranch() {
try {
const { owner, repo } = context.repo;
const currentBranch = getCurrentBranch();
core.info(`Searching for pull request from branch: ${currentBranch}`);
// Search for open PRs with the current branch as head
const searchQuery = `repo:${owner}/${repo} is:pr is:open head:${currentBranch}`;
const searchResult = await github.rest.search.issuesAndPullRequests({
q: searchQuery,
per_page: 1,
});
if (searchResult.data.total_count > 0) {
const pr = searchResult.data.items[0];
core.info(`Found pull request #${pr.number}: ${pr.html_url}`);
// Fetch detailed PR info to get mergeable state and head SHA
try {
const detailedPR = await github.rest.pulls.get({
owner,
repo,
pull_number: pr.number,
});
core.info(`PR #${pr.number} details - head_sha: ${detailedPR.data.head.sha}, mergeable: ${detailedPR.data.mergeable}, mergeable_state: ${detailedPR.data.mergeable_state}`);
return {
number: pr.number,
html_url: pr.html_url,
head_sha: detailedPR.data.head.sha,
mergeable: detailedPR.data.mergeable,
mergeable_state: detailedPR.data.mergeable_state || "unknown",
updated_at: detailedPR.data.updated_at,
};
} catch (detailsError) {
core.warning(`Failed to fetch detailed PR info: ${getErrorMessage(detailsError)}`);
// Fall back to basic info
return {
number: pr.number,
html_url: pr.html_url,
head_sha: "",
mergeable: null,
mergeable_state: "unknown",
updated_at: "",
};
}
}
core.info(`No pull request found for branch: ${currentBranch}`);
return null;
} catch (error) {
core.warning(`Failed to find pull request for current branch: ${getErrorMessage(error)}`);
return null;
}
}
/**
* Parse HTML comment metadata into key/value pairs.
* @param {string} body - Body text to inspect
* @param {string} markerKey - Marker key that must be present in the comment
* @returns {Record<string, string>|null} Parsed metadata or null when not found
*/
function parseHTMLCommentMetadata(body, markerKey) {
if (!body) {
return null;
}
for (const match of body.matchAll(/<!--\s*([\s\S]*?)\s*-->/g)) {
const content = match[1].trim();
if (!content.includes(`${markerKey}:`)) {
continue;
}
/** @type {Record<string, string>} */
const metadata = {};
const pairMatches = [...content.matchAll(/(?:^|,\s*)([a-zA-Z0-9_-]+):\s*/g)];
for (let index = 0; index < pairMatches.length; index += 1) {
const pairMatch = pairMatches[index];
const nextPairMatch = pairMatches[index + 1];
const valueStart = (pairMatch.index || 0) + pairMatch[0].length;
const valueEnd = nextPairMatch ? nextPairMatch.index || content.length : content.length;
metadata[pairMatch[1]] = content.slice(valueStart, valueEnd).trim();
}
if (metadata[markerKey]) {
return metadata;
}
}
return null;
}
/**
* Build the stable category set used to match failure issues precisely.
* @param {Object} options - Active failure signals
* @returns {string[]} Sorted failure categories
*/
function buildFailureMatchCategories(options) {
const categories = [];
if (options.isTimedOut) categories.push("timed_out");
if (options.hasAssignmentErrors) categories.push("assignment_errors");
if (options.hasAssignCopilotFailures) categories.push("assign_copilot_failures");
if (options.hasCreateDiscussionErrors) categories.push("create_discussion_errors");
if (options.hasCodePushFailures) categories.push("code_push_failures");
if (options.hasRepoMemoryValidationErrors) categories.push("repo_memory_validation_errors");
if (options.hasPushRepoMemoryFailure) categories.push("push_repo_memory_failure");
if (options.hasMissingSafeOutputs) categories.push("missing_safe_outputs");
if (options.hasReportIncomplete) categories.push("report_incomplete");
if (options.hasMissingTool) categories.push("missing_tool");
if (options.hasToolDenialsExceeded) categories.push("tool_denials_exceeded");
if (options.hasMissingData) categories.push("missing_data");
if (options.hasCacheMissMisconfiguration) categories.push("cache_miss_misconfiguration");
if (options.secretVerificationFailed) categories.push("secret_verification_failed");
if (options.inferenceAccessError) categories.push("inference_access_error");
if (options.mcpPolicyError) categories.push("mcp_policy_error");
if (options.modelNotSupportedError) categories.push("model_not_supported_error");
if (options.aiCreditsRateLimitError) categories.push("ai_credits_rate_limit_error");
if (options.maxAICreditsExceeded) categories.push("max_ai_credits_exceeded");
if (options.hasAppTokenMintingFailed) categories.push("app_token_minting_failed");
if (options.hasLockdownCheckFailed) categories.push("lockdown_check_failed");
if (options.hasStaleLockFileFailed) categories.push("stale_lock_file_failed");
if (options.hasDailyAICExceeded) categories.push("daily_effective_workflow_exceeded");
if (options.agentConclusion === "failure" && !options.isTimedOut) {
categories.push("agent_failure");
}
return categories.sort();
}
/**
* Generate a precise failure-match marker for failure issue bodies.
* @param {Object} options - Marker options
* @param {string} options.workflowId - Workflow identifier
* @param {string} options.branch - Triggering branch
* @param {number|undefined} options.pullRequestNumber - Triggering pull request number
* @param {string[]} options.failureCategories - Sorted failure categories
* @returns {string} HTML comment marker
*/
function generateFailureMatchMarker(options) {
const { workflowId, branch, pullRequestNumber, failureCategories } = options;
const parts = ["gh-aw-failure-issue: true", `workflow_id: ${workflowId}`, `branch: ${branch || ""}`, `failure_categories: ${failureCategories.join("|")}`];
if (pullRequestNumber) {
parts.push(`pull_request: ${pullRequestNumber}`);
}
return `<!-- ${parts.join(", ")} -->`;
}
/**
* Determine whether an existing issue body matches the current failure precisely.
* @param {string} body - Existing issue body
* @param {Object} options - Match criteria
* @param {string} options.workflowId - Workflow identifier
* @param {string[]} options.failureCategories - Sorted failure categories
* @returns {boolean} True when the issue body matches and is not expired
*/
function isReusableFailureIssue(body, options) {
if (!body) {
return false;
}
const expirationDate = extractExpirationDate(body);
if (expirationDate && expirationDate.getTime() <= Date.now()) {
return false;
}
const workflowMarker = parseHTMLCommentMetadata(body, "gh-aw-agentic-workflow");
if (!workflowMarker || workflowMarker.workflow_id !== options.workflowId) {
return false;
}
const failureMarker = parseHTMLCommentMetadata(body, "gh-aw-failure-issue");
if (!failureMarker) {
return false;
}
if ((failureMarker.workflow_id || "") !== options.workflowId) {
return false;
}
return (failureMarker.failure_categories || "") === options.failureCategories.join("|");
}
/**
* Determine whether an issue timestamp falls within the active dedup/throttle window.
* @param {string|undefined} createdAt - Issue created_at timestamp
* @param {number} windowStartMs - Inclusive lower bound as Unix ms
* @returns {boolean} True when timestamp is missing or within the window
*/
function isIssueWithinWindow(createdAt, windowStartMs) {
if (!createdAt) {
return true;
}
const createdMs = Date.parse(createdAt);
return Number.isFinite(createdMs) && createdMs >= windowStartMs;
}
/**
* Escape a GitHub search phrase for safe inclusion inside double quotes.
* GitHub search phrases are wrapped in double quotes, so embedded backslashes and
* quotes must be escaped, and newlines are normalized to spaces to keep the query
* on a single line.
* @param {string} value - Raw phrase value
* @returns {string} Escaped phrase
*/
function escapeGitHubSearchPhrase(value) {
return value
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/\r?\n|\r/g, " ");
}
/**
* Find an existing open failure issue that exactly matches the current failure metadata.
* @param {Object} options - Search options
* @param {string} options.owner - Repository owner
* @param {string} options.repo - Repository name
* @param {string} options.workflowId - Workflow identifier
* @param {string[]} options.failureCategories - Sorted failure categories
* @returns {Promise<{number: number, html_url: string} | null>} Matching issue or null
*/
async function findExistingFailureIssue(options) {
const { owner, repo, workflowId, failureCategories } = options;
const windowStartMs = Date.now() - FAILURE_ISSUE_WINDOW_MS;
const since = new Date(windowStartMs).toISOString().slice(0, 19) + "Z";
const escapedWorkflowId = escapeGitHubSearchPhrase(workflowId);
const searchQuery = `repo:${owner}/${repo} is:issue is:open label:agentic-workflows created:>=${since} ` + `"gh-aw-agentic-workflow:" "workflow_id: ${escapedWorkflowId}" in:body`;
const perPage = 100;
for (let page = 1; ; page += 1) {
const searchResult = await github.rest.search.issuesAndPullRequests({
q: searchQuery,
per_page: perPage,
page,
});
for (const item of searchResult.data.items) {
if (!isIssueWithinWindow(item.created_at, windowStartMs)) {
continue;
}
let body = typeof item.body === "string" ? item.body : "";
if (!body) {
const issueResult = await github.rest.issues.get({
owner,
repo,
issue_number: item.number,
});
body = issueResult.data.body || "";
}
if (
isReusableFailureIssue(body, {
workflowId,
failureCategories,
})
) {
return {
number: item.number,
html_url: item.html_url,
};
}
}
if (searchResult.data.items.length < perPage) {
break;
}
}
return null;
}
/**
* Count recently created failure issues that include the specified failure category.
* @param {Object} options - Query options
* @param {string} options.owner - Repository owner
* @param {string} options.repo - Repository name
* @param {string} options.category - Failure category name
* @returns {Promise<number>} Number of matching issues created within the dedup window
*/
async function countRecentFailureIssuesByCategory(options) {
const { owner, repo, category } = options;
const windowStartMs = Date.now() - FAILURE_ISSUE_WINDOW_MS;
const since = new Date(windowStartMs).toISOString().slice(0, 19) + "Z";
const escapedCategory = escapeGitHubSearchPhrase(category);
const searchQuery = `repo:${owner}/${repo} is:issue is:open label:agentic-workflows created:>=${since} ` + `"gh-aw-failure-issue:" "failure_categories:" "${escapedCategory}" in:body`;
const perPage = 100;
let count = 0;
for (let page = 1; ; page += 1) {
const searchResult = await github.rest.search.issuesAndPullRequests({
q: searchQuery,
per_page: perPage,
page,
});
for (const item of searchResult.data.items) {
if (!isIssueWithinWindow(item.created_at, windowStartMs)) {
continue;
}
let body = typeof item.body === "string" ? item.body : "";
if (!body) {
const issueResult = await github.rest.issues.get({
owner,
repo,
issue_number: item.number,
});
body = issueResult.data.body || "";
}
const marker = parseHTMLCommentMetadata(body, "gh-aw-failure-issue");
if (!marker) {
continue;
}
const categories = (marker.failure_categories || "")
.split("|")
.map(part => part.trim())
.filter(Boolean);
if (categories.includes(category)) {
count += 1;
}
}
if (searchResult.data.items.length < perPage) {
break;
}
}
return count;
}
/**
* Find categories that hit the daily new-issue cap.
* @param {Object} options - Query options
* @param {string} options.owner - Repository owner
* @param {string} options.repo - Repository name
* @param {string[]} options.failureCategories - Categories for the current failure
* @returns {Promise<Array<{category: string, count: number}>>}
*/
async function getCappedFailureCategories(options) {
const { owner, repo, failureCategories } = options;
const uniqueCategories = [...new Set(failureCategories)];
/** @type {Array<{category: string, count: number}>} */
const capped = [];
for (const category of uniqueCategories) {
const count = await countRecentFailureIssuesByCategory({ owner, repo, category });
if (count >= FAILURE_ISSUE_CATEGORY_DAILY_CAP) {
capped.push({ category, count });
}
}
return capped;
}
/**
* Search for or create the parent issue for all agentic workflow failures
* @param {number|null} previousParentNumber - Previous parent issue number if creating due to limit
* @param {string} [ownerOverride] - Repository owner override (from failure-issue-repo config)
* @param {string} [repoOverride] - Repository name override (from failure-issue-repo config)
* @param {number} [expiresHours] - Expiration in hours for created parent issue
* @returns {Promise<{number: number, node_id: string}>} Parent issue number and node ID
*/
async function ensureParentIssue(previousParentNumber = null, ownerOverride, repoOverride, expiresHours = DEFAULT_ACTION_FAILURE_ISSUE_EXPIRES_HOURS) {
const { owner: contextOwner, repo: contextRepo } = context.repo;
const owner = ownerOverride || contextOwner;
const repo = repoOverride || contextRepo;
const parentTitle = "[aw] Failed runs";
const parentLabel = "agentic-workflows";
core.info(`Searching for parent issue: "${parentTitle}"`);
// Search for existing parent issue
const searchQuery = `repo:${owner}/${repo} is:issue is:open label:${parentLabel} in:title "${parentTitle}"`;
try {
const searchResult = await github.rest.search.issuesAndPullRequests({
q: searchQuery,
per_page: 1,
});
if (searchResult.data.total_count > 0) {
const existingIssue = searchResult.data.items[0];
core.info(`Found existing parent issue #${existingIssue.number}: ${existingIssue.html_url}`);
// Check the sub-issue count
const subIssueCount = await getSubIssueCount(owner, repo, existingIssue.number);
if (subIssueCount !== null && subIssueCount >= MAX_SUB_ISSUES) {
core.warning(`Parent issue #${existingIssue.number} has ${subIssueCount} sub-issues (max: ${MAX_SUB_ISSUES})`);
core.info(`Creating a new parent issue (previous parent #${existingIssue.number} is full)`);
// Fall through to create a new parent issue, passing the previous parent number
previousParentNumber = existingIssue.number;
} else {
// Parent issue is within limits, return it
if (subIssueCount !== null) {
core.info(`Parent issue has ${subIssueCount} sub-issues (within limit of ${MAX_SUB_ISSUES})`);
}
return {
number: existingIssue.number,
node_id: existingIssue.node_id,
};
}
}
} catch (error) {
core.warning(`Error searching for parent issue: ${getErrorMessage(error)}`);
}
// Create parent issue if it doesn't exist or if previous one is full
const creationReason = previousParentNumber ? `creating new parent (previous #${previousParentNumber} reached limit)` : "creating first parent";
core.info(`No suitable parent issue found, ${creationReason}`);
let parentBodyContent = `This issue tracks all failures from agentic workflows in this repository. Each failed workflow run creates a sub-issue linked here for organization and easy filtering.`;
// Add reference to previous parent if this is a continuation
if (previousParentNumber) {
parentBodyContent += `
> **Note:** This is a continuation parent issue. The previous parent issue #${previousParentNumber} reached the maximum of ${MAX_SUB_ISSUES} sub-issues.`;
}
parentBodyContent += `
### Purpose
This parent issue helps you:
- View all workflow failures in one place by checking the sub-issues below
- Filter out failure issues from your main issue list using \`no:parent-issue\`
- Track the health of your agentic workflows over time
### Sub-Issues
All individual workflow failure issues are linked as sub-issues below. Click on any sub-issue to see details about a specific failure.
### Troubleshooting Failed Workflows
#### Using agentic-workflows Agent (Recommended)
**Agent:** \`agentic-workflows\`
**Purpose:** Debug and fix workflow failures
**Instructions:**
1. Invoke the agent: Type \`/agent\` in GitHub Copilot Chat and select **agentic-workflows**
2. Provide context: Tell the agent to **debug** the workflow failure
3. Supply the workflow run URL for analysis
4. The agent will:
- Analyze failure logs
- Identify root causes
- Propose specific fixes
- Validate solutions
#### Using gh aw CLI
You can also debug failures using the \`gh aw\` CLI:
\`\`\`bash
# Download and analyze workflow logs
gh aw logs <workflow-run-url>
# Audit a specific workflow run
gh aw audit <run-id>
\`\`\`
#### Manual Investigation
1. Click on a sub-issue to see the failed workflow details
2. Follow the workflow run link in the issue
3. Review the agent job logs for error messages
4. Check the workflow configuration in your repository
### Resources
- [GitHub Agentic Workflows Documentation](https://github.com/github/gh-aw)
- [Troubleshooting Guide](https://github.github.com/gh-aw/troubleshooting/common-issues/)
---
> This issue is automatically managed by GitHub Agentic Workflows. Do not close this issue manually.`;
// Add expiration marker inside the quoted section using helper
const footer = generateFooterWithExpiration({
footerText: parentBodyContent,
expiresHours,
});
const parentBody = footer;
try {
const newIssue = await github.rest.issues.create({
owner,
repo,
title: parentTitle,
body: parentBody,
labels: [parentLabel],
headers: { "X-GitHub-Api-Version": GITHUB_API_VERSION },
});
core.info(`✓ Created parent issue #${newIssue.data.number}: ${newIssue.data.html_url}`);
return {
number: newIssue.data.number,
node_id: newIssue.data.node_id,
};
} catch (error) {
core.error(`Failed to create parent issue: ${getErrorMessage(error)}`);
throw error;
}
}
/**
* Link an issue as a sub-issue to a parent issue
* @param {string} parentNodeId - GraphQL node ID of the parent issue
* @param {string} subIssueNodeId - GraphQL node ID of the sub-issue
* @param {number} parentNumber - Parent issue number (for logging)
* @param {number} subIssueNumber - Sub-issue number (for logging)
*/
async function linkSubIssue(parentNodeId, subIssueNodeId, parentNumber, subIssueNumber) {
core.info(`Linking issue #${subIssueNumber} as sub-issue of #${parentNumber}`);
try {
// Use GraphQL to link the sub-issue
await github.graphql(
`mutation($parentId: ID!, $subIssueId: ID!) {
addSubIssue(input: {issueId: $parentId, subIssueId: $subIssueId}) {
issue {
id
number
}
subIssue {
id
number
}
}
}`,
{
parentId: parentNodeId,
subIssueId: subIssueNodeId,
}
);
core.info(`✓ Successfully linked #${subIssueNumber} as sub-issue of #${parentNumber}`);
} catch (error) {
const errorMessage = getErrorMessage(error);
if (errorMessage.includes("Field 'addSubIssue' doesn't exist") || errorMessage.includes("not yet available")) {
core.warning(`Sub-issue API not available. Issue #${subIssueNumber} created but not linked to parent.`);
} else {
core.warning(`Failed to link sub-issue: ${errorMessage}`);
}
}
}
/**
* Build create_discussion errors context string from error environment variable
* @param {string} createDiscussionErrors - Newline-separated error strings
* @returns {string} Formatted error context for display
*/
function buildCreateDiscussionErrorsContext(createDiscussionErrors) {
if (!createDiscussionErrors) {
return "";
}
let context = buildWarningAlertLine("Create Discussion Failed", "Failed to create one or more discussions.") + "\n**Discussion Errors:**\n";
const errorLines = createDiscussionErrors.split("\n").filter(line => line.trim());
for (const errorLine of errorLines) {
const parts = errorLine.split(":");
if (parts.length >= 4) {
// parts[0] is "discussion", parts[1] is index - both unused
const repo = parts[2];
const title = parts[3];
const error = parts.slice(4).join(":"); // Rest is the error message
context += `- Discussion "${title}" in ${repo}: ${error}\n`;
}
}
context += "\n";
return context;
}
/**
* Build a fork context hint string when the repository is a fork.
* @returns {string} Fork hint string, or empty string if not a fork
*/
function buildForkContextHint() {
if (context.payload?.repository?.fork) {
return "\n💡 **This repository is a fork.** If this failure is due to missing API keys or tokens, note that secrets from the parent repository are not inherited. Configure the required secrets directly in your fork's Settings → Secrets and variables → Actions.\n";
}
return "";
}
/**
* Build a context string describing code-push failures for inclusion in failure issue/comment bodies.
* Manifest file protection refusals are separated from other push failures to give them a dedicated
* section with clearer remediation instructions.
* @param {string} codePushFailureErrors - Newline-separated list of "type:error" entries
* @param {{number: number, html_url: string, head_sha?: string, mergeable?: boolean | null, mergeable_state?: string, updated_at?: string} | null} pullRequest - PR info if available
* @param {string} [runUrl] - URL of the current workflow run, used to provide patch download instructions
* @returns {string} Formatted context string, or empty string if no failures
*/
function buildCodePushFailureContext(codePushFailureErrors, pullRequest = null, runUrl = "") {
if (!codePushFailureErrors) {
return "";
}
// Split errors into protected-file protection refusals, patch size errors, patch apply failures, and other push failures
const manifestErrors = [];
const patchSizeErrors = [];
const patchApplyErrors = [];
const otherErrors = [];
const errorLines = codePushFailureErrors.split("\n").filter(line => line.trim());
for (const errorLine of errorLines) {
const colonIndex = errorLine.indexOf(":");
if (colonIndex !== -1) {
const type = errorLine.substring(0, colonIndex);
const error = errorLine.substring(colonIndex + 1);
if (error.includes("manifest files") || error.includes("protected files")) {
manifestErrors.push({ type, error });
} else if (error.includes("Patch size") && error.includes("exceeds")) {
patchSizeErrors.push({ type, error });
} else if (error.includes("Failed to apply patch")) {
patchApplyErrors.push({ type, error });
} else {
otherErrors.push({ type, error });
}
}
}
let context = "";
// Protected file protection section — shown before generic failures
if (manifestErrors.length > 0) {
context +=
"\n**🛡️ Protected Files**: The code push was refused because the patch modifies protected files (package manifests, agent instruction files, or repository security configuration). " +
"This protection guards against unintended supply chain changes.\n";
if (pullRequest) {
context += `\n**Target Pull Request:** [#${pullRequest.number}](${pullRequest.html_url})\n`;
}
context += "\n**Blocked Operations:**\n";
for (const { type, error } of manifestErrors) {
context += `- \`${type}\`: ${error}\n`;
}
// Build a dynamic YAML snippet listing only the safe output types that were actually blocked
const typeToYamlKey = {
create_pull_request: "create-pull-request",
push_to_pull_request_branch: "push-to-pull-request-branch",
};
const blockedTypes = [...new Set(manifestErrors.map(e => e.type))];
let yamlSnippet = "```yaml\nsafe-outputs:\n";
for (const type of blockedTypes) {
const yamlKey = typeToYamlKey[type] || type.replace(/_/g, "-");
yamlSnippet += ` ${yamlKey}:\n protected-files: fallback-to-issue\n`;
}
yamlSnippet += "```\n";
context += "\n<details>\n<summary>⚙️ Configure <code>protected-files: fallback-to-issue</code></summary>\n\n";
context += yamlSnippet;
context += "</details>\n";
}
// Patch size exceeded section
if (patchSizeErrors.length > 0) {
context += "\n**📦 Patch Size Exceeded**: The code push was rejected because the generated patch is too large.\n";
if (pullRequest) {
context += `\n**Target Pull Request:** [#${pullRequest.number}](${pullRequest.html_url})\n`;
}
context += "\n**Errors:**\n";
for (const { type, error } of patchSizeErrors) {
context += `- \`${type}\`: ${error}\n`;
}
// Build a dynamic YAML snippet listing only the safe output types that had patch size errors
const typeToYamlKey = {
create_pull_request: "create-pull-request",
push_to_pull_request_branch: "push-to-pull-request-branch",
};
const affectedTypes = [...new Set(patchSizeErrors.map(e => e.type))];
let yamlSnippet = "```yaml\nsafe-outputs:\n";
for (const type of affectedTypes) {
const yamlKey = typeToYamlKey[type] || type.replace(/_/g, "-");
yamlSnippet += ` ${yamlKey}:\n max-patch-size: 2048 # Example: double the default limit (in KB, default: 1024)\n`;
}
yamlSnippet += "```\n";
context += "\nTo allow larger patches, increase `max-patch-size` in your workflow's front matter (value in KB):\n";
context += yamlSnippet;
}
// Patch apply failure section — shown when the patch could not be applied (e.g. merge conflict)
if (patchApplyErrors.length > 0) {
context += "\n**🔀 Patch Apply Failed**: The patch could not be applied to the current state of the repository. " + "This is typically caused by a merge conflict between the agent's changes and recent commits on the target branch.\n";
if (pullRequest) {
context += `\n**Target Pull Request:** [#${pullRequest.number}](${pullRequest.html_url})\n`;
}
context += "\n**Failed Operations:**\n";
for (const { type, error } of patchApplyErrors) {
context += `- \`${type}\`: ${error}\n`;
}
// Extract run ID from runUrl for use in the download command
let runId = "";
if (runUrl) {
const runIdMatch = runUrl.match(/\/actions\/runs\/(\d+)/);
if (runIdMatch) {
runId = runIdMatch[1];
}
}
context += "\n<details>\n<summary>📋 Apply the patch manually</summary>\n\n";
if (runId) {
context += `\`\`\`sh
# Download the patch artifact from the workflow run
gh run download ${runId} -n agent -D /tmp/agent-${runId}
# List available patches
ls /tmp/agent-${runId}/*.patch
# Create a new branch (adjust as needed)
git checkout -b aw/manual-apply
# Apply the patch (--3way handles cross-repo patches)
git am --3way /tmp/agent-${runId}/YOUR_PATCH_FILE.patch
# If there are conflicts, resolve them and continue (or abort):
# git am --continue
# git am --abort
# Push and create a pull request
git push origin aw/manual-apply
gh pr create --head aw/manual-apply
\`\`\`
${runUrl ? `\nThe patch artifact is available at: [View run and download artifacts](${runUrl})\n` : ""}`;
} else {
context += "Download the patch artifact from the workflow run, then apply it with `git am --3way <patch-file>`.\n";
}
context += "\n</details>\n";
}
// Generic code-push failure section
if (otherErrors.length > 0) {
context += buildWarningAlertLine("Code Push Failed", "A code push safe output failed, and subsequent safe outputs were cancelled.");
if (pullRequest) {
context += `\n**Target Pull Request:** [#${pullRequest.number}](${pullRequest.html_url})`;
// Add PR state diagnostics
const workflowSha = process.env.GITHUB_SHA || "";
const prDetails = [];
// Check for merge conflicts
if (pullRequest.mergeable === false) {
prDetails.push("❌ **Merge conflicts detected** - the PR has conflicts that need resolution");
} else if (pullRequest.mergeable_state === "dirty") {
prDetails.push("❌ **PR is in dirty state** - likely has merge conflicts");
} else if (pullRequest.mergeable_state === "blocked") {
prDetails.push("**PR is blocked** - required status checks or reviews may be missing");
} else if (pullRequest.mergeable_state === "behind") {
prDetails.push("**PR is behind base branch** - may need to be updated");
}
// Check if branch was updated since workflow started
if (workflowSha && pullRequest.head_sha && workflowSha !== pullRequest.head_sha) {
prDetails.push(`**Branch was updated** - workflow started at \`${workflowSha.substring(0, 7)}\`, PR head is now \`${pullRequest.head_sha.substring(0, 7)}\``);
}
// Add SHA info for debugging
if (pullRequest.head_sha) {
prDetails.push(`**PR head SHA:** \`${pullRequest.head_sha.substring(0, 7)}\``);
}
if (workflowSha) {
prDetails.push(`**Workflow SHA:** \`${workflowSha.substring(0, 7)}\``);
}
if (pullRequest.mergeable_state && pullRequest.mergeable_state !== "unknown") {
prDetails.push(`**Mergeable state:** ${pullRequest.mergeable_state}`);
}
if (prDetails.length > 0) {
context += "\n\n**PR State at Push Time:**\n";
for (const detail of prDetails) {
context += `- ${detail}\n`;
}
}
}
context += "\n**Code Push Errors:**\n";
for (const { type, error } of otherErrors) {
context += `- \`${type}\`: ${error}\n`;
}
context += "\n";
} else if (manifestErrors.length > 0 || patchSizeErrors.length > 0 || patchApplyErrors.length > 0) {
// Only manifest, patch size, or patch apply errors — ensure trailing newline
context += "\n";
}
return context;
}
/**
* Build a context string for push_repo_memory job failures, with a dedicated section for patch size errors.
* @param {boolean} hasPushRepoMemoryFailure - Whether the push_repo_memory job failed
* @param {string[]} repoMemoryPatchSizeExceededIDs - Memory IDs that exceeded the patch size limit
* @param {string} runUrl - URL of the current workflow run
* @returns {string} Formatted context string, or empty string if no failure
*/
function buildPushRepoMemoryFailureContext(hasPushRepoMemoryFailure, repoMemoryPatchSizeExceededIDs, runUrl) {
if (!hasPushRepoMemoryFailure) {
return "";
}
if (repoMemoryPatchSizeExceededIDs.length > 0) {
let context = "\n**📦 Repo-Memory Patch Size Exceeded**: The repo-memory push failed because the memory data is too large.\n";
context += "\n**Affected memories:** " + repoMemoryPatchSizeExceededIDs.map(id => `\`${id}\``).join(", ") + "\n";
context += "\nTo allow larger memory snapshots, increase `max-patch-size` in your workflow's `repo-memory` front matter (value in bytes):\n";
context += "```yaml\nrepo-memory:\n";
for (const memoryID of repoMemoryPatchSizeExceededIDs) {
context += ` - id: ${memoryID}\n max-patch-size: 51200 # Example: 5x the default limit (in bytes, default: 10240, max: 102400)\n`;
}
context += "```\n\n";
return context;
}
return (
buildWarningAlertLine(
"Repo-Memory Push Failed",
"The push-repo-memory job failed to write memory back to the repository. This may indicate a permission issue, a configuration error, or a network problem. Check the [workflow run](" + runUrl + ") for details."
) + "\n"
);
}
/**
* Load missing_data messages from agent output
* @param {Array<any>} [items] - Optional pre-loaded agent output items. When provided, avoids re-reading the output file.
* @returns {Array<{data_type: string, reason: string, context?: string, alternatives?: string}>} Array of missing data messages
*/
function loadMissingDataMessages(items) {
try {
let resolvedItems = items;
if (!resolvedItems) {
const { loadAgentOutput } = require("./load_agent_output.cjs");
const agentOutputResult = loadAgentOutput();
if (!agentOutputResult.success || !agentOutputResult.items) {
return [];
}
resolvedItems = agentOutputResult.items;
}
// Extract missing_data messages from agent output
const missingDataMessages = [];
for (const item of resolvedItems) {
if (item.type === "missing_data") {
// Accept items with at least a reason; data_type may be absent for cache-miss signals
if (item.reason) {
missingDataMessages.push({
data_type: item.data_type || "",
reason: item.reason,
context: item.context || null,
alternatives: item.alternatives || null,
});
}
}
}
return missingDataMessages;
} catch (error) {
core.warning(`Failed to load missing_data messages: ${getErrorMessage(error)}`);
return [];
}
}
/**
* Build missing_data context string for display in failure issues/comments.
* When cache-memory is enabled and a cache_miss is detected, appends a
* configuration-problem warning to the context.
* @param {boolean} cacheMemoryEnabled - Whether cache-memory is configured for this workflow
* @param {Array<any>} [items] - Optional pre-loaded agent output items. When provided, avoids re-reading the output file.
* @returns {string} Formatted missing data context
*/
function buildMissingDataContext(cacheMemoryEnabled, items) {
const missingDataMessages = loadMissingDataMessages(items);
if (missingDataMessages.length === 0) {
return "";
}
core.info(`Found ${missingDataMessages.length} missing_data message(s)`);
// Detect cache_miss: if cache-memory is available and the agent reported a cache miss,
// this indicates the prompt is referencing an incorrect file path within the cache directory.
const hasCacheMiss = missingDataMessages.some(m => m.reason === "cache_memory_miss");
// When cache-memory is configured and cache_miss is present, avoid repeating the same
// signal in the generic "Missing Data" section. Keep the specialised cache warning below.
const displayableMissingData = cacheMemoryEnabled && hasCacheMiss ? missingDataMessages.filter(m => m.reason !== "cache_memory_miss") : missingDataMessages;
let context = "";
if (displayableMissingData.length > 0) {
const formattedList = formatMissingData(displayableMissingData);
context += buildWarningAlertLine("Missing Data Reported", "The agent reported missing data during execution.") + "\n**Missing Data:**\n";
context += formattedList;
context += "\n\n";
}
if (cacheMemoryEnabled && hasCacheMiss) {
core.info("Cache-miss detected despite cache-memory being available — likely a configuration problem");
const templatePath = getPromptPath("cache_memory_miss.md");
context += "\n" + renderTemplateFromFile(templatePath, {}) + "\n";
}
return context;
}
/**
* Extract denied command entries from a missing_tool alternatives string.
* Handles batched command text in the form:
* ".... Denied commands: cmd1 | cmd2 | cmd3"
* while preserving internal pipes inside tool call parentheses.
* @param {string | null | undefined} alternatives
* @returns {string[]}
*/
function extractDeniedCommandsFromAlternatives(alternatives) {
if (!alternatives || typeof alternatives !== "string") {
return [];
}
const marker = "Denied commands:";
const markerIndex = alternatives.indexOf(marker);
if (markerIndex < 0) {
return [];
}
const deniedSection = alternatives.slice(markerIndex + marker.length).trim();