-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathci-diagnosis-tool.ts
More file actions
194 lines (176 loc) · 6.13 KB
/
ci-diagnosis-tool.ts
File metadata and controls
194 lines (176 loc) · 6.13 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
import type { FastMCP } from "fastmcp";
import { z } from "zod";
import { gateAuth } from "./github-auth.js";
import { classifyError, getOctokit } from "./github-client.js";
import { errorRespond, jsonRespond, mkError } from "./json.js";
import { FormatSchema, MaxLogLinesSchema, RepoRefSchema } from "./schemas.js";
import { tailTruncate } from "./utils.js";
interface FailedStep {
name: string;
log: string;
}
interface FailedJob {
name: string;
conclusion: string;
failedSteps: FailedStep[];
}
interface DiagnosisResult {
runId: number;
workflow: string;
conclusion: string;
branch: string;
url: string;
triggerCommit: { sha7: string; message: string; author: string };
failedJobs: FailedJob[];
}
export function registerCiDiagnosisTool(server: FastMCP): void {
server.addTool({
name: "ci_diagnosis",
description:
"Diagnose CI failures: fetches the relevant workflow run, extracts failed job logs, shows trigger commit. " +
"Pass runId, prNumber, or ref to target a specific run.",
annotations: { readOnlyHint: true },
parameters: RepoRefSchema.extend({
ref: z.string().optional().describe("Branch or SHA to find the latest run."),
prNumber: z
.number()
.int()
.positive()
.optional()
.describe("PR number; finds runs for its head SHA."),
runId: z.number().int().positive().optional().describe("Exact run ID to fetch."),
maxLogLines: MaxLogLinesSchema.describe("Max lines per job log tail."),
grepLog: z
.string()
.optional()
.describe("Regex applied to each log; only matching lines are returned."),
format: FormatSchema,
}),
execute: async (args) => {
const auth = gateAuth();
if (!auth.ok) return errorRespond(auth.envelope);
const { owner, repo } = args;
try {
const octokit = getOctokit();
type WorkflowRun = Awaited<ReturnType<typeof octokit.actions.getWorkflowRun>>["data"];
let run: WorkflowRun | undefined;
if (args.runId) {
const res = await octokit.actions.getWorkflowRun({
owner,
repo,
run_id: args.runId,
});
run = res.data;
} else if (args.prNumber) {
const pr = await octokit.pulls.get({ owner, repo, pull_number: args.prNumber });
const res = await octokit.actions.listWorkflowRunsForRepo({
owner,
repo,
head_sha: pr.data.head.sha,
per_page: 1,
});
run = res.data.workflow_runs[0];
} else if (args.ref) {
const res = await octokit.actions.listWorkflowRunsForRepo({
owner,
repo,
branch: args.ref,
per_page: 5,
});
run =
res.data.workflow_runs.find((r) => r.conclusion === "failure") ??
res.data.workflow_runs[0];
} else {
const res = await octokit.actions.listWorkflowRunsForRepo({
owner,
repo,
status: "failure" as const,
per_page: 1,
});
run = res.data.workflow_runs[0];
}
if (!run) {
return errorRespond(
mkError("NO_CI_RUNS", `No workflow runs found for ${owner}/${repo}.`, {
suggestedFix:
"Verify the ref/PR has triggered a workflow, or pass an explicit runId.",
}),
);
}
const jobsRes = await octokit.actions.listJobsForWorkflowRun({
owner,
repo,
run_id: run.id,
filter: "latest",
});
const allJobs = jobsRes.data.jobs;
const failed = allJobs.filter((j) => j.conclusion === "failure");
const jobsToAnalyze = failed.length > 0 ? failed : allJobs;
const grepRe = args.grepLog ? new RegExp(args.grepLog, "i") : undefined;
const failedJobs: FailedJob[] = [];
for (const job of jobsToAnalyze) {
let logText = "[logs unavailable]";
try {
const logRes = await octokit.actions.downloadJobLogsForWorkflowRun({
owner,
repo,
job_id: job.id,
});
let raw = String(logRes.data);
if (grepRe) {
raw = raw
.split("\n")
.filter((l) => grepRe.test(l))
.join("\n");
}
logText = tailTruncate(raw, args.maxLogLines);
} catch {
// logs expired or unavailable
}
failedJobs.push({
name: job.name,
conclusion: job.conclusion ?? "unknown",
failedSteps: [{ name: "logs", log: logText }],
});
}
const result: DiagnosisResult = {
runId: run.id,
workflow: run.name ?? "unknown",
conclusion: run.conclusion ?? "unknown",
branch: run.head_branch ?? "unknown",
url: run.html_url,
triggerCommit: {
sha7: run.head_sha.substring(0, 7),
message: run.head_commit?.message ?? "unknown",
author: run.head_commit?.author?.name ?? "unknown",
},
failedJobs,
};
if (args.format === "json") return jsonRespond(result);
const lines: string[] = [
`# CI Diagnosis: ${owner}/${repo}`,
"",
`**Run:** #${result.runId} (${result.workflow}) — ${result.conclusion}`,
`**Branch:** ${result.branch}`,
`**Trigger:** \`${result.triggerCommit.sha7}\` ${result.triggerCommit.message} — ${result.triggerCommit.author}`,
`**URL:** ${result.url}`,
"",
];
if (failedJobs.length === 0) {
lines.push("No failed jobs found.");
} else {
lines.push("## Failed Jobs", "");
for (const job of failedJobs) {
lines.push(`### ${job.name} (${job.conclusion})`, "");
for (const step of job.failedSteps) {
lines.push(`#### ${step.name}`, "", "```", step.log, "```", "");
}
}
}
return lines.join("\n");
} catch (err) {
return errorRespond(classifyError(err));
}
},
});
}