ticket-runner 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.ko.md +97 -0
- package/README.md +98 -0
- package/bin/ticket-runner.js +6 -0
- package/docs/templates/operator-skill.md +87 -0
- package/package.json +42 -0
- package/src/acceptance-criteria.ts +44 -0
- package/src/adapters/claude-agent-runner.ts +389 -0
- package/src/adapters/exec.ts +169 -0
- package/src/adapters/gh-tracker.ts +955 -0
- package/src/adapters/git-workspace.ts +951 -0
- package/src/adapters/repo-root.ts +20 -0
- package/src/adapters/version.ts +118 -0
- package/src/base-branch.ts +21 -0
- package/src/branch.ts +33 -0
- package/src/cli.ts +135 -0
- package/src/command-line.ts +190 -0
- package/src/config.ts +277 -0
- package/src/conventions.ts +118 -0
- package/src/criteria.ts +106 -0
- package/src/frontier.ts +36 -0
- package/src/guards.ts +143 -0
- package/src/handoff.ts +82 -0
- package/src/host.ts +116 -0
- package/src/init.ts +405 -0
- package/src/labels.ts +42 -0
- package/src/landing.ts +75 -0
- package/src/lifecycle.ts +34 -0
- package/src/lock.ts +215 -0
- package/src/note-schema.ts +58 -0
- package/src/notes.ts +433 -0
- package/src/operator-skill.ts +24 -0
- package/src/orchestrator.ts +1816 -0
- package/src/ports/agent-runner.ts +105 -0
- package/src/ports/tracker.ts +334 -0
- package/src/ports/workspace.ts +422 -0
- package/src/progress.ts +231 -0
- package/src/prompts.ts +288 -0
- package/src/readiness.ts +256 -0
- package/src/remove.ts +732 -0
- package/src/resume.ts +145 -0
- package/src/run-log.ts +85 -0
- package/src/run.ts +331 -0
- package/src/self-hosting.ts +33 -0
- package/src/stage-guard.ts +32 -0
- package/src/staleness.ts +101 -0
- package/src/start.ts +284 -0
- package/src/startup.ts +34 -0
- package/src/stop.ts +178 -0
- package/src/stranded.ts +136 -0
- package/src/templates.ts +596 -0
- package/src/title.ts +97 -0
- package/src/verdict.ts +88 -0
- package/src/version-number.ts +67 -0
- package/src/version-pr.ts +103 -0
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Authentication,
|
|
3
|
+
Candidate,
|
|
4
|
+
CiOutcome,
|
|
5
|
+
CreateIssue,
|
|
6
|
+
CreatePullRequest,
|
|
7
|
+
Issue,
|
|
8
|
+
IssueComment,
|
|
9
|
+
IssueRef,
|
|
10
|
+
LabelSpec,
|
|
11
|
+
NumberKind,
|
|
12
|
+
OpenPullRequest,
|
|
13
|
+
PullRequestRef,
|
|
14
|
+
SquashCommit,
|
|
15
|
+
Tracker,
|
|
16
|
+
} from "../ports/tracker.js";
|
|
17
|
+
import { DEFAULT_CI_GRACE_MINUTES } from "../config.js";
|
|
18
|
+
import { type HostKind, hostKind } from "../host.js";
|
|
19
|
+
import { highestVersion } from "../version-number.js";
|
|
20
|
+
import { type Execution, type RunProcess, exec, throwOnFailure } from "./exec.js";
|
|
21
|
+
|
|
22
|
+
export interface GhTrackerOptions {
|
|
23
|
+
run?: RunProcess;
|
|
24
|
+
cwd?: string;
|
|
25
|
+
pollIntervalMs?: number;
|
|
26
|
+
/**
|
|
27
|
+
* How long "no checks yet" counts as pending after the wait starts. The
|
|
28
|
+
* Target's `ciGraceMinutes`, in the unit the poll works in.
|
|
29
|
+
*/
|
|
30
|
+
checksGraceMs?: number;
|
|
31
|
+
sleep?: (ms: number) => Promise<void>;
|
|
32
|
+
now?: () => number;
|
|
33
|
+
/**
|
|
34
|
+
* The Host the Run is on, which only draft and ready depend on. Whatever the
|
|
35
|
+
* environment says unless a test says otherwise.
|
|
36
|
+
*/
|
|
37
|
+
host?: HostKind;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* One issue as the REST API reports it, in the fields the pipeline reads. The
|
|
42
|
+
* issue list, the dependency list and a single issue all answer in this shape.
|
|
43
|
+
*/
|
|
44
|
+
interface RawIssue {
|
|
45
|
+
number: number;
|
|
46
|
+
title: string;
|
|
47
|
+
html_url: string;
|
|
48
|
+
body: string | null;
|
|
49
|
+
/** `open` or `closed`. */
|
|
50
|
+
state?: string;
|
|
51
|
+
labels: { name: string }[];
|
|
52
|
+
assignees: { login: string }[] | null;
|
|
53
|
+
/** Present on pull requests only; GitHub lists them as issues too. */
|
|
54
|
+
pull_request?: unknown;
|
|
55
|
+
sub_issues_summary?: { total?: number };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One entry of an issue's REST comment list. */
|
|
59
|
+
interface RawComment {
|
|
60
|
+
id?: number;
|
|
61
|
+
body: string | null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** One issue GitHub records as blocking another, and whether it still does. */
|
|
65
|
+
interface Blocker {
|
|
66
|
+
number: number;
|
|
67
|
+
open: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One entry of the REST release list, in the three fields a Version needs. */
|
|
71
|
+
interface RawRelease {
|
|
72
|
+
tag_name: string;
|
|
73
|
+
draft: boolean;
|
|
74
|
+
prerelease: boolean;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A pull request as REST reports it, in the fields the pipeline reads. */
|
|
78
|
+
interface RawPullRequest {
|
|
79
|
+
number: number;
|
|
80
|
+
html_url: string;
|
|
81
|
+
/** The GraphQL id, which a workstation's draft and ready mutations take. */
|
|
82
|
+
node_id: string;
|
|
83
|
+
draft: boolean;
|
|
84
|
+
head: { sha: string };
|
|
85
|
+
/**
|
|
86
|
+
* Whether GitHub can merge the pull request into its base: `false` when the
|
|
87
|
+
* two conflict. GitHub works it out lazily and answers `null` until it has.
|
|
88
|
+
*/
|
|
89
|
+
mergeable?: boolean | null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** One check run on a commit, as the REST check-runs list reports it. */
|
|
93
|
+
interface RawCheckRun {
|
|
94
|
+
name: string;
|
|
95
|
+
/** `queued`, `in_progress`, `completed` and the like; only `completed` has a conclusion. */
|
|
96
|
+
status: string;
|
|
97
|
+
conclusion: string | null;
|
|
98
|
+
/** Where the check reports; for an Actions job, the job's own page. */
|
|
99
|
+
details_url?: string | null;
|
|
100
|
+
html_url?: string | null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One commit status, as the REST combined status reports it: the latest per context. */
|
|
104
|
+
interface RawStatus {
|
|
105
|
+
context: string;
|
|
106
|
+
/** `success`, `failure`, `error` or `pending`. */
|
|
107
|
+
state: string;
|
|
108
|
+
target_url?: string | null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The bucket `gh pr checks` sorted a check into, which is still the vocabulary
|
|
113
|
+
* a reading is made of now that the checks come from REST.
|
|
114
|
+
*/
|
|
115
|
+
type Bucket = "pass" | "fail" | "cancel" | "skipping" | "pending";
|
|
116
|
+
|
|
117
|
+
/** One check on a pull request's head commit, a check run or a commit status alike. */
|
|
118
|
+
interface CiCheck {
|
|
119
|
+
name: string;
|
|
120
|
+
bucket: Bucket;
|
|
121
|
+
/** Where the check reports; an Actions job's is the only one a log is behind. */
|
|
122
|
+
link?: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* One look at a pull request: its head commit's checks, or nothing when GitHub
|
|
127
|
+
* would not report them, and whether GitHub has found it conflicting with its
|
|
128
|
+
* base.
|
|
129
|
+
*/
|
|
130
|
+
interface CiSnapshot {
|
|
131
|
+
checks: CiCheck[] | undefined;
|
|
132
|
+
conflicting: boolean;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* What one reading of the head commit's checks settled on, before any log is
|
|
137
|
+
* fetched.
|
|
138
|
+
*
|
|
139
|
+
* A failed reading keeps the checks themselves rather than only their names,
|
|
140
|
+
* because the log fetch happens once, after the polling loop is over, and it
|
|
141
|
+
* needs the links.
|
|
142
|
+
*/
|
|
143
|
+
type CiReading =
|
|
144
|
+
| { state: "passed" }
|
|
145
|
+
| { state: "none" }
|
|
146
|
+
| { state: "conflicting" }
|
|
147
|
+
| { state: "failed"; summary: string; failed: CiCheck[] };
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The GitHub-backed {@link Tracker}, spoken through the `gh` CLI so it reuses
|
|
151
|
+
* the repo's own auth and conventions.
|
|
152
|
+
*
|
|
153
|
+
* Argument building and output parsing, plus the one piece of waiting the port
|
|
154
|
+
* owns: polling a pull request's CI until it settles or the caller's timeout
|
|
155
|
+
* runs out. What that outcome means is the orchestrator's decision.
|
|
156
|
+
*/
|
|
157
|
+
export class GhTracker implements Tracker {
|
|
158
|
+
private readonly runProcess: RunProcess;
|
|
159
|
+
private readonly cwd: string | undefined;
|
|
160
|
+
private readonly pollIntervalMs: number;
|
|
161
|
+
private readonly checksGraceMs: number;
|
|
162
|
+
private readonly sleep: (ms: number) => Promise<void>;
|
|
163
|
+
private readonly now: () => number;
|
|
164
|
+
private readonly host: HostKind;
|
|
165
|
+
|
|
166
|
+
constructor(options: GhTrackerOptions = {}) {
|
|
167
|
+
this.runProcess = options.run ?? exec;
|
|
168
|
+
this.cwd = options.cwd;
|
|
169
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 15_000;
|
|
170
|
+
this.checksGraceMs = options.checksGraceMs ?? DEFAULT_CI_GRACE_MINUTES * 60_000;
|
|
171
|
+
this.sleep =
|
|
172
|
+
options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
173
|
+
this.now = options.now ?? Date.now;
|
|
174
|
+
this.host = options.host ?? hostKind(process.env);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Whether `gh` can reach GitHub as somebody, which is whether REST will say
|
|
179
|
+
* who the current user is.
|
|
180
|
+
*
|
|
181
|
+
* Not `gh auth status`: on a cloud Host it calls the proxy's placeholder
|
|
182
|
+
* token invalid while every REST call a Run makes works (ADR-0008).
|
|
183
|
+
*
|
|
184
|
+
* The failure is the answer here, so this is the one call that does not
|
|
185
|
+
* throw on one: `init` reports it as a line rather than as a crash.
|
|
186
|
+
*/
|
|
187
|
+
async authentication(): Promise<Authentication> {
|
|
188
|
+
let exitCode: number;
|
|
189
|
+
try {
|
|
190
|
+
({ exitCode } = await this.gh(["api", "user", "--jq", ".login"], {
|
|
191
|
+
allowFailure: true,
|
|
192
|
+
}));
|
|
193
|
+
} catch {
|
|
194
|
+
// A failed exit comes back as an exit code, so a throw is the spawn
|
|
195
|
+
// itself failing: `gh` is not on the PATH, and no login would help.
|
|
196
|
+
return "not-installed";
|
|
197
|
+
}
|
|
198
|
+
return exitCode === 0 ? "authenticated" : "unauthenticated";
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async currentUser(): Promise<string> {
|
|
202
|
+
const { stdout } = await this.gh(["api", "user", "--jq", ".login"]);
|
|
203
|
+
return stdout.trim();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Whatever the Target's `HEAD` points at, read off the repository through
|
|
208
|
+
* REST: `gh repo view` asks GraphQL, which a cloud Host refuses (ADR-0008).
|
|
209
|
+
*/
|
|
210
|
+
async defaultBranch(): Promise<string> {
|
|
211
|
+
const { stdout } = await this.gh(["api", "repos/{owner}/{repo}", "--jq", ".default_branch"]);
|
|
212
|
+
const branch = stdout.trim();
|
|
213
|
+
if (branch === "") throw new Error("gh reported no default branch for this repository");
|
|
214
|
+
return branch;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The Target's `owner/name`, read through REST like {@link defaultBranch}.
|
|
219
|
+
* Every failure is no answer, because a Target this cannot name is only a
|
|
220
|
+
* Target that is not the pipeline's own.
|
|
221
|
+
*/
|
|
222
|
+
async repository(): Promise<string | undefined> {
|
|
223
|
+
try {
|
|
224
|
+
const { exitCode, stdout } = await this.gh(
|
|
225
|
+
["api", "repos/{owner}/{repo}", "--jq", ".full_name"],
|
|
226
|
+
{ allowFailure: true },
|
|
227
|
+
);
|
|
228
|
+
const name = stdout.trim();
|
|
229
|
+
return exitCode === 0 && name !== "" ? name : undefined;
|
|
230
|
+
} catch {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The tag of the highest Version published on `repository` as a Release.
|
|
237
|
+
*
|
|
238
|
+
* Every failure is the same answer — no answer — because nothing the caller
|
|
239
|
+
* does with it may stop a Run: a rate limit, a repository nobody can see, a
|
|
240
|
+
* `gh` that is not installed. The list is asked for rather than GitHub's own
|
|
241
|
+
* `latest`, which is the newest by date: a patch cut on an old branch after a
|
|
242
|
+
* minor would otherwise be reported as the Version to upgrade to. A hundred
|
|
243
|
+
* of them is every Version this tool is likely to have, and they arrive
|
|
244
|
+
* newest first, so the highest is among them wherever the count lands: one
|
|
245
|
+
* page, never every page.
|
|
246
|
+
*/
|
|
247
|
+
async latestVersionTag(repository: string): Promise<string | undefined> {
|
|
248
|
+
try {
|
|
249
|
+
const { exitCode, stdout } = await this.gh(
|
|
250
|
+
["api", "--method", "GET", `repos/${repository}/releases`, "-F", "per_page=100"],
|
|
251
|
+
{ allowFailure: true },
|
|
252
|
+
);
|
|
253
|
+
if (exitCode !== 0) return undefined;
|
|
254
|
+
const releases = JSON.parse(stdout) as RawRelease[];
|
|
255
|
+
return highestVersion(
|
|
256
|
+
releases
|
|
257
|
+
.filter((release) => !release.draft && !release.prerelease)
|
|
258
|
+
.map((release) => release.tag_name),
|
|
259
|
+
)?.tag;
|
|
260
|
+
} catch {
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async listLabels(): Promise<string[]> {
|
|
266
|
+
const labels = await this.list<{ name: string }>("repos/{owner}/{repo}/labels");
|
|
267
|
+
return labels.map((label) => label.name);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* GitHub refuses a name it already has with a 422 whose error code is
|
|
272
|
+
* `already_exists`. Every other failure, another 422 included, still throws.
|
|
273
|
+
*/
|
|
274
|
+
async createLabel(label: LabelSpec): Promise<boolean> {
|
|
275
|
+
const result = await this.rest(
|
|
276
|
+
"POST",
|
|
277
|
+
"repos/{owner}/{repo}/labels",
|
|
278
|
+
[`name=${label.name}`, `color=${label.color}`, `description=${label.description}`],
|
|
279
|
+
{ tolerate: /"code"\s*:\s*"already_exists"/ },
|
|
280
|
+
);
|
|
281
|
+
return result.exitCode === 0;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* GitHub answers a label it does not have with a 404, which is the one
|
|
286
|
+
* failure taken as an answer: whatever the reason, the label is not there.
|
|
287
|
+
*/
|
|
288
|
+
async deleteLabel(name: string): Promise<boolean> {
|
|
289
|
+
const result = await this.rest(
|
|
290
|
+
"DELETE",
|
|
291
|
+
`repos/{owner}/{repo}/labels/${encodeURIComponent(name)}`,
|
|
292
|
+
[],
|
|
293
|
+
{ tolerate: /HTTP 404/ },
|
|
294
|
+
);
|
|
295
|
+
return result.exitCode === 0;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Turn squash merging on, naming that one field and no other.
|
|
300
|
+
*
|
|
301
|
+
* The repository's own PATCH endpoint takes each merge method separately, so
|
|
302
|
+
* a repository that also allows merge commits keeps allowing them.
|
|
303
|
+
*/
|
|
304
|
+
async enableSquashMerge(): Promise<void> {
|
|
305
|
+
await this.rest("PATCH", "repos/{owner}/{repo}", [], { typed: ["allow_squash_merge=true"] });
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Read off the repository itself. GitHub leaves the field out for a caller
|
|
310
|
+
* who may not change it, which is read as off: a Run cannot count on it.
|
|
311
|
+
*/
|
|
312
|
+
async deletesBranchOnMerge(): Promise<boolean> {
|
|
313
|
+
const { stdout } = await this.gh(["api", "repos/{owner}/{repo}", "--jq", ".delete_branch_on_merge"]);
|
|
314
|
+
return stdout.trim() === "true";
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async enableDeleteBranchOnMerge(): Promise<void> {
|
|
318
|
+
await this.rest("PATCH", "repos/{owner}/{repo}", [], { typed: ["delete_branch_on_merge=true"] });
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* One issue, with its comments and the two native relations the guards read:
|
|
323
|
+
* how many sub-issues it has, and what GitHub says blocks it.
|
|
324
|
+
*
|
|
325
|
+
* Three REST calls, because the issue itself carries neither its comments nor
|
|
326
|
+
* its blockers, only a count of each.
|
|
327
|
+
*/
|
|
328
|
+
async getIssue(number: number): Promise<Issue> {
|
|
329
|
+
const { stdout } = await this.gh(["api", `repos/{owner}/{repo}/issues/${number}`]);
|
|
330
|
+
const raw = JSON.parse(stdout) as RawIssue;
|
|
331
|
+
const comments = await this.list<RawComment>(`repos/{owner}/{repo}/issues/${number}/comments`);
|
|
332
|
+
const blockers = await this.blockers(number);
|
|
333
|
+
return {
|
|
334
|
+
number: raw.number,
|
|
335
|
+
title: raw.title,
|
|
336
|
+
url: raw.html_url,
|
|
337
|
+
body: raw.body ?? "",
|
|
338
|
+
closed: raw.state === "closed",
|
|
339
|
+
labels: raw.labels.map((label) => label.name),
|
|
340
|
+
assignees: (raw.assignees ?? []).map((assignee) => assignee.login),
|
|
341
|
+
comments: comments.map((comment) => ({ ...withCommentId(comment), body: comment.body ?? "" })),
|
|
342
|
+
subIssues: subIssues(raw),
|
|
343
|
+
blockedBy: blockers.map((blocker) => blocker.number),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* GitHub serves a pull request at its issue URL too, marked by the field
|
|
349
|
+
* only a pull request has. A 404 is a number it never gave out, and a 410 one
|
|
350
|
+
* whose issue was deleted: neither has anything behind it to take.
|
|
351
|
+
*/
|
|
352
|
+
async numberKind(number: number): Promise<NumberKind> {
|
|
353
|
+
const args = ["api", `repos/{owner}/{repo}/issues/${number}`, "--jq", ".pull_request != null"];
|
|
354
|
+
const result = await this.gh(args, { allowFailure: true });
|
|
355
|
+
if (result.exitCode !== 0 && /HTTP 4(04|10)\b/.test(result.output)) return "nothing";
|
|
356
|
+
const { stdout } = throwOnFailure("gh", args, result);
|
|
357
|
+
return stdout.trim() === "true" ? "pull-request" : "issue";
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Open an issue, and read its number back out of what REST answers with.
|
|
362
|
+
*
|
|
363
|
+
* GitHub creates a label the Target does not have rather than refusing the
|
|
364
|
+
* issue, so a missing label is `init`'s to catch, not this call's.
|
|
365
|
+
*/
|
|
366
|
+
async createIssue(issue: CreateIssue): Promise<IssueRef> {
|
|
367
|
+
const { stdout } = await this.rest("POST", "repos/{owner}/{repo}/issues", [
|
|
368
|
+
`title=${issue.title}`,
|
|
369
|
+
`body=${issue.body}`,
|
|
370
|
+
...issue.labels.map((label) => `labels[]=${label}`),
|
|
371
|
+
]);
|
|
372
|
+
const created = JSON.parse(stdout) as Partial<RawIssue>;
|
|
373
|
+
if (typeof created.number !== "number" || typeof created.html_url !== "string") {
|
|
374
|
+
throw new Error(`could not read an issue number from gh output: ${stdout}`);
|
|
375
|
+
}
|
|
376
|
+
return { number: created.number, url: created.html_url };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* The open issues carrying `label`, straight from the REST issue list, each
|
|
381
|
+
* with its open blockers counted off its own dependency list.
|
|
382
|
+
*
|
|
383
|
+
* Not off the list's `issue_dependencies_summary`: the summary lags the list,
|
|
384
|
+
* so a blocker added a moment ago would be missed and its Ticket merged ahead
|
|
385
|
+
* of it. That costs a call per candidate, and native dependencies are the
|
|
386
|
+
* only blocker source the pipeline trusts (ADR-0003).
|
|
387
|
+
*/
|
|
388
|
+
async listCandidates(label: string): Promise<Candidate[]> {
|
|
389
|
+
const issues = await this.list<RawIssue>("repos/{owner}/{repo}/issues", [
|
|
390
|
+
"-f",
|
|
391
|
+
"state=open",
|
|
392
|
+
"-f",
|
|
393
|
+
`labels=${label}`,
|
|
394
|
+
]);
|
|
395
|
+
|
|
396
|
+
const candidates: Candidate[] = [];
|
|
397
|
+
for (const issue of issues.filter((issue) => issue.pull_request === undefined)) {
|
|
398
|
+
const blockers = await this.blockers(issue.number);
|
|
399
|
+
candidates.push({
|
|
400
|
+
number: issue.number,
|
|
401
|
+
title: issue.title,
|
|
402
|
+
assignees: (issue.assignees ?? []).map((assignee) => assignee.login),
|
|
403
|
+
openBlockers: blockers.filter((blocker) => blocker.open).length,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
return candidates;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Assign `user`, and refuse an assignment GitHub did not make.
|
|
411
|
+
*
|
|
412
|
+
* REST answers a user it cannot assign with the issue as it was and a
|
|
413
|
+
* success, where `gh issue edit --add-assignee` failed. A Claim nobody can
|
|
414
|
+
* see is worse than one that fails, so the answer is read back.
|
|
415
|
+
*/
|
|
416
|
+
async assign(number: number, user: string): Promise<void> {
|
|
417
|
+
const { stdout } = await this.rest(
|
|
418
|
+
"POST",
|
|
419
|
+
`repos/{owner}/{repo}/issues/${number}/assignees`,
|
|
420
|
+
[`assignees[]=${user}`],
|
|
421
|
+
);
|
|
422
|
+
const assignees = (JSON.parse(stdout) as Partial<RawIssue>).assignees ?? [];
|
|
423
|
+
if (!assignees.some((assignee) => assignee.login.toLowerCase() === user.toLowerCase())) {
|
|
424
|
+
throw new Error(`GitHub did not assign ${user} to #${number}`);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async unassign(number: number, user: string): Promise<void> {
|
|
429
|
+
await this.rest("DELETE", `repos/{owner}/{repo}/issues/${number}/assignees`, [
|
|
430
|
+
`assignees[]=${user}`,
|
|
431
|
+
]);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async addLabel(number: number, label: string): Promise<void> {
|
|
435
|
+
await this.rest("POST", `repos/{owner}/{repo}/issues/${number}/labels`, [
|
|
436
|
+
`labels[]=${label}`,
|
|
437
|
+
]);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Take a label off an issue, and take one it does not wear as already off.
|
|
442
|
+
*
|
|
443
|
+
* REST answers that with a 404 where `gh issue edit --remove-label` did
|
|
444
|
+
* nothing, and a Ticket must not fail over a label somebody removed first.
|
|
445
|
+
* Every other failure, a missing issue's 404 included, still throws.
|
|
446
|
+
*/
|
|
447
|
+
async removeLabel(number: number, label: string): Promise<void> {
|
|
448
|
+
const path = `repos/{owner}/{repo}/issues/${number}/labels/${encodeURIComponent(label)}`;
|
|
449
|
+
await this.rest("DELETE", path, [], { tolerate: /Label does not exist/ });
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** REST answers with the new comment, whose id is what it is edited by later. */
|
|
453
|
+
async comment(number: number, body: string): Promise<IssueComment> {
|
|
454
|
+
const { stdout } = await this.rest("POST", `repos/{owner}/{repo}/issues/${number}/comments`, [
|
|
455
|
+
`body=${body}`,
|
|
456
|
+
]);
|
|
457
|
+
return { ...withCommentId(JSON.parse(stdout) as RawComment), body };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Edit a comment in place, by the numeric id REST reported it with. */
|
|
461
|
+
async updateComment(id: string, body: string): Promise<void> {
|
|
462
|
+
await this.rest("PATCH", `repos/{owner}/{repo}/issues/comments/${id}`, [`body=${body}`]);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async updateIssueBody(number: number, body: string): Promise<void> {
|
|
466
|
+
await this.rest("PATCH", `repos/{owner}/{repo}/issues/${number}`, [`body=${body}`]);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Open a pull request through REST, and read its number back out of the
|
|
471
|
+
* answer rather than off anything printed.
|
|
472
|
+
*/
|
|
473
|
+
async createPullRequest(pr: CreatePullRequest): Promise<PullRequestRef> {
|
|
474
|
+
const { stdout } = await this.rest(
|
|
475
|
+
"POST",
|
|
476
|
+
"repos/{owner}/{repo}/pulls",
|
|
477
|
+
[`base=${pr.base}`, `head=${pr.head}`, `title=${pr.title}`, `body=${pr.body}`],
|
|
478
|
+
{ typed: [`draft=${pr.draft}`] },
|
|
479
|
+
);
|
|
480
|
+
const created = JSON.parse(stdout) as Partial<RawPullRequest>;
|
|
481
|
+
if (typeof created.number !== "number" || typeof created.html_url !== "string") {
|
|
482
|
+
throw new Error(`could not read a pull request number from gh output: ${stdout}`);
|
|
483
|
+
}
|
|
484
|
+
return { number: created.number, url: created.html_url };
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
async openPullRequests(): Promise<OpenPullRequest[]> {
|
|
488
|
+
const pulls = await this.list<{ number: number; head: { ref: string } }>(
|
|
489
|
+
"repos/{owner}/{repo}/pulls",
|
|
490
|
+
["-f", "state=open"],
|
|
491
|
+
);
|
|
492
|
+
return pulls.map((pull) => ({ number: pull.number, head: pull.head.ref }));
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async convertPullRequestToDraft(number: number): Promise<void> {
|
|
496
|
+
await this.setDraft(number, true);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* The draft direction reversed.
|
|
501
|
+
*
|
|
502
|
+
* A pull request already out of draft is left as it is, as `gh pr ready` left
|
|
503
|
+
* it, so the second pass a fix Stage buys asks this of a ready pull request
|
|
504
|
+
* for nothing rather than failing the Ticket at `pr`.
|
|
505
|
+
*/
|
|
506
|
+
async markPullRequestReady(number: number): Promise<void> {
|
|
507
|
+
await this.setDraft(number, false);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async updatePullRequestBody(number: number, body: string): Promise<void> {
|
|
511
|
+
await this.rest("PATCH", `repos/{owner}/{repo}/pulls/${number}`, [`body=${body}`]);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async updatePullRequestTitle(number: number, title: string): Promise<void> {
|
|
515
|
+
await this.rest("PATCH", `repos/{owner}/{repo}/pulls/${number}`, [`title=${title}`]);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Poll the PR's CI until it settles or the timeout runs out. A PR with no
|
|
520
|
+
* checks is reported as such, never as a pass.
|
|
521
|
+
*
|
|
522
|
+
* The checks are the head commit's check runs and commit statuses, which is
|
|
523
|
+
* everything `gh pr checks` read through GraphQL.
|
|
524
|
+
*
|
|
525
|
+
* Right after a PR opens, GitHub answers "no checks" for a while before the
|
|
526
|
+
* workflow's check run exists, so "no checks" only counts once the grace
|
|
527
|
+
* period has passed. A PR GitHub finds conflicting with its base is the
|
|
528
|
+
* exception: GitHub runs no `pull_request` workflow for it, so no check is
|
|
529
|
+
* coming and the wait ends as soon as the conflict is seen.
|
|
530
|
+
*/
|
|
531
|
+
async waitForCi(number: number, timeoutMs: number): Promise<CiOutcome> {
|
|
532
|
+
const startedAt = this.now();
|
|
533
|
+
const deadline = startedAt + timeoutMs;
|
|
534
|
+
const graceUntil = startedAt + Math.min(this.checksGraceMs, timeoutMs);
|
|
535
|
+
|
|
536
|
+
for (;;) {
|
|
537
|
+
const reading = readCi(await this.ciSnapshot(number));
|
|
538
|
+
const stillRegistering = reading !== "pending" && reading.state === "none" && this.now() < graceUntil;
|
|
539
|
+
if (reading !== "pending" && !stillRegistering) return this.withEvidence(reading);
|
|
540
|
+
// Checks that never appeared are "none", not a timeout: nothing was ever pending.
|
|
541
|
+
if (this.now() >= deadline) {
|
|
542
|
+
return reading === "pending" ? { state: "timed-out" } : this.withEvidence(reading);
|
|
543
|
+
}
|
|
544
|
+
await this.sleep(this.pollIntervalMs);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* The reading the poll stopped on, turned into the outcome the caller gets.
|
|
550
|
+
*
|
|
551
|
+
* The one place a job log is fetched, so it happens once per wait and never
|
|
552
|
+
* while a check is still pending.
|
|
553
|
+
*/
|
|
554
|
+
private async withEvidence(reading: CiReading): Promise<CiOutcome> {
|
|
555
|
+
if (reading.state !== "failed") return reading;
|
|
556
|
+
return {
|
|
557
|
+
state: "failed",
|
|
558
|
+
summary: reading.summary,
|
|
559
|
+
excerpt: await this.failedJobLogs(reading.failed),
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* The tail of each failing Actions job's log, or a line saying it could not
|
|
565
|
+
* be had and where the job is.
|
|
566
|
+
*
|
|
567
|
+
* Evidence is worth a few extra calls and nothing more: a Ticket whose CI
|
|
568
|
+
* really is red has a failure to report whether or not a log came back, so
|
|
569
|
+
* every way the fetch can go wrong — a `gh` that fails or is not there, a
|
|
570
|
+
* proxy that will not follow the log's redirect, an empty log — is reported
|
|
571
|
+
* to the fix Stage as a log it has to go and look at rather than as an error.
|
|
572
|
+
* A check that is not an Actions job has no log to fetch and yields nothing.
|
|
573
|
+
*
|
|
574
|
+
* The cap counts the jobs a log could be fetched for, not the red checks: a
|
|
575
|
+
* PR whose external checks went red alongside one Actions job still gets the
|
|
576
|
+
* one log there is. What it keeps out of a prompt is a whole matrix failing
|
|
577
|
+
* a leg at a time, each leg with the same log.
|
|
578
|
+
*/
|
|
579
|
+
private async failedJobLogs(failed: CiCheck[]): Promise<string> {
|
|
580
|
+
const jobs = failed.flatMap((check) => {
|
|
581
|
+
const job = actionsJobId(check.link);
|
|
582
|
+
return job === undefined || check.link === undefined
|
|
583
|
+
? []
|
|
584
|
+
: [{ name: check.name, job, link: check.link }];
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
const logs: string[] = [];
|
|
588
|
+
for (const { name, job, link } of jobs.slice(0, MAX_LOG_JOBS)) {
|
|
589
|
+
const log = await this.jobLog(job);
|
|
590
|
+
logs.push(
|
|
591
|
+
log === undefined
|
|
592
|
+
? `${name}\n(the log was unavailable; the job is at ${link})`
|
|
593
|
+
: `${name}\n${tail(log)}`,
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
return logs.join("\n\n");
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* One Actions job's log through REST, up to the last line the runner marked
|
|
601
|
+
* as an error, or nothing when there is no log to be had.
|
|
602
|
+
*
|
|
603
|
+
* REST gives the whole job where `gh run view --log-failed` gave the failed
|
|
604
|
+
* steps, so what the post-job cleanup printed after the failure is cut off:
|
|
605
|
+
* otherwise it would be the tail that is kept.
|
|
606
|
+
*/
|
|
607
|
+
private async jobLog(job: string): Promise<string | undefined> {
|
|
608
|
+
try {
|
|
609
|
+
const result = await this.gh(["api", `repos/{owner}/{repo}/actions/jobs/${job}/logs`], {
|
|
610
|
+
allowFailure: true,
|
|
611
|
+
});
|
|
612
|
+
if (result.exitCode !== 0) return undefined;
|
|
613
|
+
const log = throughLastError(result.stdout).trim();
|
|
614
|
+
return log === "" ? undefined : log;
|
|
615
|
+
} catch {
|
|
616
|
+
// `gh` itself could not be run. The failure still stands; the log does not.
|
|
617
|
+
return undefined;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Squash-merge through REST, with the subject and body the pipeline composed
|
|
623
|
+
* as the commit's title and message.
|
|
624
|
+
*/
|
|
625
|
+
async squashMerge(number: number, commit: SquashCommit): Promise<void> {
|
|
626
|
+
await this.rest("PUT", `repos/{owner}/{repo}/pulls/${number}/merge`, [
|
|
627
|
+
"merge_method=squash",
|
|
628
|
+
`commit_title=${commit.subject}`,
|
|
629
|
+
`commit_message=${commit.body}`,
|
|
630
|
+
]);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** One pull request, read through REST. */
|
|
634
|
+
private async pullRequest(number: number): Promise<RawPullRequest> {
|
|
635
|
+
const { stdout } = await this.gh(["api", `repos/{owner}/{repo}/pulls/${number}`]);
|
|
636
|
+
return JSON.parse(stdout) as RawPullRequest;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Put a pull request into draft or take it out, and leave one already there
|
|
641
|
+
* as it is.
|
|
642
|
+
*
|
|
643
|
+
* The one call that depends on the Host: GitHub's REST API has no form of it,
|
|
644
|
+
* so a workstation uses the GraphQL mutation `gh pr ready` used, and a cloud
|
|
645
|
+
* Host, where GraphQL is refused, the proxy's own routes (ADR-0008). The
|
|
646
|
+
* state is read first on either, which is also where GraphQL's id comes from.
|
|
647
|
+
*/
|
|
648
|
+
private async setDraft(number: number, draft: boolean): Promise<void> {
|
|
649
|
+
const pr = await this.pullRequest(number);
|
|
650
|
+
if (pr.draft === draft) return;
|
|
651
|
+
|
|
652
|
+
if (this.host === "cloud") {
|
|
653
|
+
const route = draft ? "convert_to_draft" : "ready_for_review";
|
|
654
|
+
await this.rest("POST", `repos/{owner}/{repo}/pulls/${number}/ccr/${route}`, []);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
const mutation = draft ? "convertPullRequestToDraft" : "markPullRequestReadyForReview";
|
|
659
|
+
await this.gh([
|
|
660
|
+
"api",
|
|
661
|
+
"graphql",
|
|
662
|
+
"-f",
|
|
663
|
+
`query=mutation($id: ID!) { ${mutation}(input: {pullRequestId: $id}) { pullRequest { isDraft } } }`,
|
|
664
|
+
"-f",
|
|
665
|
+
`id=${pr.node_id}`,
|
|
666
|
+
]);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Every check on a pull request's head commit — its check runs and its
|
|
671
|
+
* commit statuses — or nothing when GitHub would not say, which reads as no
|
|
672
|
+
* checks; and whether GitHub has found the pull request conflicting.
|
|
673
|
+
*
|
|
674
|
+
* The head is read afresh each time, as `gh pr checks` read it, so a failed
|
|
675
|
+
* read costs one reading rather than the wait. Check runs come from the
|
|
676
|
+
* `latest` filter REST applies by default, so a job re-run after failing
|
|
677
|
+
* counts as its re-run, as `gh pr checks` counted it.
|
|
678
|
+
*/
|
|
679
|
+
private async ciSnapshot(number: number): Promise<CiSnapshot> {
|
|
680
|
+
const pr = await this.gh(["api", `repos/{owner}/{repo}/pulls/${number}`], {
|
|
681
|
+
allowFailure: true,
|
|
682
|
+
});
|
|
683
|
+
if (pr.exitCode !== 0) return { checks: undefined, conflicting: false };
|
|
684
|
+
const { head, mergeable } = JSON.parse(pr.stdout) as RawPullRequest;
|
|
685
|
+
// `null` is GitHub still working it out, which is no conflict yet.
|
|
686
|
+
const conflicting = mergeable === false;
|
|
687
|
+
const commit = `repos/{owner}/{repo}/commits/${head.sha}`;
|
|
688
|
+
const runs = await this.wrappedList(`${commit}/check-runs`, "check_runs");
|
|
689
|
+
const statuses = await this.wrappedList(`${commit}/status`, "statuses");
|
|
690
|
+
if (runs === undefined || statuses === undefined) return { checks: undefined, conflicting };
|
|
691
|
+
const checks = [
|
|
692
|
+
...(runs as RawCheckRun[]).map((run) => ({
|
|
693
|
+
name: run.name,
|
|
694
|
+
bucket: checkRunBucket(run),
|
|
695
|
+
...linked(run.details_url ?? run.html_url),
|
|
696
|
+
})),
|
|
697
|
+
...(statuses as RawStatus[]).map((status) => ({
|
|
698
|
+
name: status.context,
|
|
699
|
+
bucket: statusBucket(status.state),
|
|
700
|
+
...linked(status.target_url),
|
|
701
|
+
})),
|
|
702
|
+
];
|
|
703
|
+
return { checks, conflicting };
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Every page of a list REST wraps in an object under `key`, one entry per
|
|
708
|
+
* line as `--jq` prints them, or nothing when the call failed: `--paginate`
|
|
709
|
+
* joins arrays, not the objects around them.
|
|
710
|
+
*/
|
|
711
|
+
private async wrappedList(path: string, key: string): Promise<unknown[] | undefined> {
|
|
712
|
+
const result = await this.gh([...pagedGet(path), "--jq", `.${key}[]`], {
|
|
713
|
+
allowFailure: true,
|
|
714
|
+
});
|
|
715
|
+
if (result.exitCode !== 0) return undefined;
|
|
716
|
+
try {
|
|
717
|
+
return result.stdout
|
|
718
|
+
.split("\n")
|
|
719
|
+
.filter((line) => line.trim() !== "")
|
|
720
|
+
.map((line) => JSON.parse(line) as unknown);
|
|
721
|
+
} catch {
|
|
722
|
+
throw new Error(`could not read the ${key} gh listed: ${result.output.trim()}`);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* The issues GitHub records as blocking `number`, open or closed, from the
|
|
728
|
+
* issue's own dependency list.
|
|
729
|
+
*
|
|
730
|
+
* A blocker whose state did not come back counts as open: reading it as
|
|
731
|
+
* closed would put a blocked Ticket on the Frontier (ADR-0003). A GitHub that
|
|
732
|
+
* cannot list dependencies at all fails the call, which is no answer rather
|
|
733
|
+
* than an empty one.
|
|
734
|
+
*/
|
|
735
|
+
private async blockers(number: number): Promise<Blocker[]> {
|
|
736
|
+
const blockers = await this.list<RawIssue>(
|
|
737
|
+
`repos/{owner}/{repo}/issues/${number}/dependencies/blocked_by`,
|
|
738
|
+
);
|
|
739
|
+
return blockers.map((blocker) => ({
|
|
740
|
+
number: blocker.number,
|
|
741
|
+
open: blocker.state !== "closed",
|
|
742
|
+
}));
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* One REST write, every field raw with `-f`, so a body is never read as a
|
|
747
|
+
* file or a number whatever it starts with. The `typed` ones are the few
|
|
748
|
+
* that must reach GitHub as a boolean, and go with `-F`.
|
|
749
|
+
*
|
|
750
|
+
* `tolerate` names the one failure a caller takes as an answer rather than
|
|
751
|
+
* an error: a run that failed with output matching it comes back instead of
|
|
752
|
+
* throwing, and every other failure still throws.
|
|
753
|
+
*/
|
|
754
|
+
private async rest(
|
|
755
|
+
method: "POST" | "PATCH" | "PUT" | "DELETE",
|
|
756
|
+
path: string,
|
|
757
|
+
fields: string[],
|
|
758
|
+
options: { allowFailure?: boolean; typed?: string[]; tolerate?: RegExp } = {},
|
|
759
|
+
): Promise<Execution> {
|
|
760
|
+
const args = [
|
|
761
|
+
"api",
|
|
762
|
+
"--method",
|
|
763
|
+
method,
|
|
764
|
+
path,
|
|
765
|
+
...fields.flatMap((field) => ["-f", field]),
|
|
766
|
+
...(options.typed ?? []).flatMap((field) => ["-F", field]),
|
|
767
|
+
];
|
|
768
|
+
const result = await this.gh(args, { allowFailure: true });
|
|
769
|
+
if (options.allowFailure || options.tolerate?.test(result.output)) return result;
|
|
770
|
+
return throwOnFailure("gh", args, result);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* Every page of a REST list, as one array: `gh --paginate` joins the pages.
|
|
775
|
+
* `--method GET` is spelled out because fields would otherwise make it a POST.
|
|
776
|
+
*/
|
|
777
|
+
private async list<T>(path: string, fields: string[] = []): Promise<T[]> {
|
|
778
|
+
const { stdout } = await this.gh([...pagedGet(path), ...fields]);
|
|
779
|
+
return JSON.parse(stdout) as T[];
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
private async gh(
|
|
783
|
+
args: string[],
|
|
784
|
+
options: { allowFailure?: boolean } = {},
|
|
785
|
+
): Promise<Execution> {
|
|
786
|
+
const result = await this.runProcess("gh", args, {
|
|
787
|
+
...(this.cwd === undefined ? {} : { cwd: this.cwd }),
|
|
788
|
+
});
|
|
789
|
+
return options.allowFailure ? result : throwOnFailure("gh", args, result);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Every page of a REST list, a hundred at a time. `--method GET` is spelled
|
|
795
|
+
* out because fields would otherwise make it a POST.
|
|
796
|
+
*/
|
|
797
|
+
function pagedGet(path: string): string[] {
|
|
798
|
+
return ["api", "--paginate", "--method", "GET", path, "-F", "per_page=100"];
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** The Actions job a check's link points at: `.../actions/runs/<run>/job/<job>`. */
|
|
802
|
+
const ACTIONS_JOB_URL = /\/actions\/runs\/\d+\/job\/(\d+)(?:[?#]|$)/;
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* How many failing Actions jobs a single wait fetches a log for.
|
|
806
|
+
*
|
|
807
|
+
* A matrix build fails a leg at a time with the same log each time, and the
|
|
808
|
+
* prompt and the hand-off comment both have to stay readable, so the excerpt
|
|
809
|
+
* is bounded by this times {@link MAX_LOG_LINES} rather than by the build.
|
|
810
|
+
*/
|
|
811
|
+
const MAX_LOG_JOBS = 3;
|
|
812
|
+
|
|
813
|
+
/** Lines kept from the tail of one job's log. */
|
|
814
|
+
const MAX_LOG_LINES = 40;
|
|
815
|
+
|
|
816
|
+
/** Characters kept from the tail of one job's log, for lines long enough to need it. */
|
|
817
|
+
const MAX_LOG_CHARS = 4_000;
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* A comment's id, as the string {@link Tracker.updateComment} takes, or nothing
|
|
821
|
+
* when REST reported none.
|
|
822
|
+
*
|
|
823
|
+
* Unlike the native relations this adapter refuses to guess, a missing id
|
|
824
|
+
* decides nothing: it costs an edit, never a Ticket. So it is reported as
|
|
825
|
+
* missing rather than thrown, and the one caller that needs to edit posts a
|
|
826
|
+
* fresh comment instead.
|
|
827
|
+
*/
|
|
828
|
+
function withCommentId(comment: RawComment): { id?: string } {
|
|
829
|
+
return typeof comment.id === "number" ? { id: String(comment.id) } : {};
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* How many native sub-issues an issue has, and it may not be guessed.
|
|
834
|
+
*
|
|
835
|
+
* Reading a missing summary as zero would hand every Spec to an implement
|
|
836
|
+
* Stage (ADR-0003), so no answer is an error.
|
|
837
|
+
*/
|
|
838
|
+
function subIssues(issue: RawIssue): number {
|
|
839
|
+
const total = issue.sub_issues_summary?.total;
|
|
840
|
+
if (typeof total !== "number") {
|
|
841
|
+
throw new Error(
|
|
842
|
+
`#${issue.number} came back without sub_issues_summary.total, so whether ` +
|
|
843
|
+
"it is a Spec cannot be read; ticket-runner trusts GitHub's native " +
|
|
844
|
+
"relations only (ADR-0003)",
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
return total;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* `pending` means "ask again"; everything else is an answer. Checks GitHub
|
|
852
|
+
* would not report read as none, as a failing `gh pr checks` did, so the grace
|
|
853
|
+
* period still covers a wait that starts before the checks exist. No checks on
|
|
854
|
+
* a PR GitHub finds conflicting is the conflict, since that is why there are
|
|
855
|
+
* none; checks it does have are read as they are.
|
|
856
|
+
*/
|
|
857
|
+
function readCi({ checks, conflicting }: CiSnapshot): CiReading | "pending" {
|
|
858
|
+
if (checks === undefined || checks.length === 0) {
|
|
859
|
+
return conflicting ? { state: "conflicting" } : { state: "none" };
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const failed = checks.filter((check) => check.bucket === "fail" || check.bucket === "cancel");
|
|
863
|
+
if (failed.length > 0) {
|
|
864
|
+
return {
|
|
865
|
+
state: "failed",
|
|
866
|
+
summary: failed
|
|
867
|
+
.map((check) => `${check.name} ${check.bucket === "cancel" ? "cancelled" : "failed"}`)
|
|
868
|
+
.join(", "),
|
|
869
|
+
failed,
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
if (checks.some((check) => check.bucket === "pending")) return "pending";
|
|
873
|
+
return { state: "passed" };
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* A check run's bucket, as `gh pr checks` sorted it: by conclusion once it has
|
|
878
|
+
* completed, and pending until then. A conclusion GitHub adds later is pending
|
|
879
|
+
* too, which the timeout bounds, rather than a pass nobody saw.
|
|
880
|
+
*
|
|
881
|
+
* One departure: `startup_failure`, which `gh` left pending, is a failure. A
|
|
882
|
+
* workflow that could not start never will, and waiting it out only turns a
|
|
883
|
+
* red check into a timeout.
|
|
884
|
+
*/
|
|
885
|
+
function checkRunBucket(run: RawCheckRun): Bucket {
|
|
886
|
+
if (run.status !== "completed") return "pending";
|
|
887
|
+
switch (run.conclusion) {
|
|
888
|
+
case "success":
|
|
889
|
+
return "pass";
|
|
890
|
+
case "skipped":
|
|
891
|
+
case "neutral":
|
|
892
|
+
return "skipping";
|
|
893
|
+
case "cancelled":
|
|
894
|
+
return "cancel";
|
|
895
|
+
case "failure":
|
|
896
|
+
case "timed_out":
|
|
897
|
+
case "action_required":
|
|
898
|
+
case "startup_failure":
|
|
899
|
+
return "fail";
|
|
900
|
+
default:
|
|
901
|
+
return "pending";
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** A commit status's bucket: `error` and `failure` are red, and `pending` is pending. */
|
|
906
|
+
function statusBucket(state: string): Bucket {
|
|
907
|
+
if (state === "success") return "pass";
|
|
908
|
+
if (state === "failure" || state === "error") return "fail";
|
|
909
|
+
return "pending";
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** A check's link, left out rather than empty when GitHub reported none. */
|
|
913
|
+
function linked(url: string | null | undefined): { link?: string } {
|
|
914
|
+
return url ? { link: url } : {};
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** Everything up to the last line an Actions runner marked `##[error]`, or all of it. */
|
|
918
|
+
function throughLastError(log: string): string {
|
|
919
|
+
const lines = log.split("\n");
|
|
920
|
+
const last = lines.findLastIndex((line) => line.includes("##[error]"));
|
|
921
|
+
return last === -1 ? log : lines.slice(0, last + 1).join("\n");
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* The Actions job id behind a check's link, or nothing when the check does not
|
|
926
|
+
* report from one. An external app's check has a link of its own shape and no
|
|
927
|
+
* log REST can give, which is a reason to skip it and never a reason to fail.
|
|
928
|
+
*/
|
|
929
|
+
function actionsJobId(link: string | undefined): string | undefined {
|
|
930
|
+
const match = link === undefined ? null : ACTIONS_JOB_URL.exec(link);
|
|
931
|
+
return match ? (match[1] as string) : undefined;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* The end of a log, under a fixed cap, saying what it left out.
|
|
936
|
+
*
|
|
937
|
+
* The tail is the part worth carrying: a runner prints the assertion or the
|
|
938
|
+
* stack that ended the job last, under however much setup noise came first.
|
|
939
|
+
*/
|
|
940
|
+
function tail(log: string): string {
|
|
941
|
+
const lines = log.split("\n");
|
|
942
|
+
let kept = lines.slice(-MAX_LOG_LINES);
|
|
943
|
+
while (kept.length > 1 && kept.join("\n").length > MAX_LOG_CHARS) kept = kept.slice(1);
|
|
944
|
+
|
|
945
|
+
const text = kept.join("\n");
|
|
946
|
+
const omitted = lines.length - kept.length;
|
|
947
|
+
|
|
948
|
+
// A single line longer than the whole cap keeps its own tail: the error is at
|
|
949
|
+
// the end of it. Its own start is cut too, which the count alone would not say.
|
|
950
|
+
if (text.length > MAX_LOG_CHARS) {
|
|
951
|
+
const earlier = omitted > 0 ? `${omitted} earlier lines and the start of this one` : "the start of this line";
|
|
952
|
+
return `… (${earlier} omitted)\n${text.slice(-MAX_LOG_CHARS)}`;
|
|
953
|
+
}
|
|
954
|
+
return omitted > 0 ? `… (${omitted} earlier lines omitted)\n${text}` : text;
|
|
955
|
+
}
|