@chernabog/sdk 0.10.0 → 0.11.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.
@@ -0,0 +1,826 @@
1
+ // The post-merge blocks: watching push CI on the merge commit of a pull
2
+ // request this persona wrote, once it merged into the base branch, and, when
3
+ // the merge turned it red, filing a follow-up issue with the failed runs and
4
+ // the tail of their logs, so implement takes the fix on. A red merge of a
5
+ // follow-up's own fix goes to a person rather than to another follow-up.
6
+ //
7
+ // Each merge is watched once: the run's first step comments on the pull
8
+ // request with a hidden marker, which the source looks for. The follow-up
9
+ // carries a marker with the merge commit's sha, so a run that resumes after
10
+ // filing finds it rather than filing another.
11
+
12
+ import {
13
+ activity,
14
+ type CiFailedRun,
15
+ GitHub,
16
+ type Json,
17
+ NeedsHuman,
18
+ Repo,
19
+ reportAs,
20
+ sleep,
21
+ StepFailed,
22
+ type WorkItem,
23
+ } from "@chernabog/core";
24
+ import * as Arr from "effect/Array";
25
+ import * as Brand from "effect/Brand";
26
+ import * as DateTime from "effect/DateTime";
27
+ import * as Duration from "effect/Duration";
28
+ import * as Effect from "effect/Effect";
29
+ import * as Option from "effect/Option";
30
+ import * as Schema from "effect/Schema";
31
+
32
+ import {
33
+ BaseBranch,
34
+ defineBlock,
35
+ defineSource,
36
+ type FailureContext,
37
+ IssueNumber,
38
+ PullRequestNumber,
39
+ ToPerson,
40
+ } from "./block.ts";
41
+ import * as PullRequest from "./pull-request.ts";
42
+ import * as Settings from "./settings.ts";
43
+
44
+ // A commit, by its sha: the merge commit a run watches.
45
+ export type CommitSha = string & Brand.Brand<"CommitSha">;
46
+
47
+ export const CommitSha = Brand.nominal<CommitSha>();
48
+
49
+ // Only merges this recent are watched, so enrolling a repo doesn't watch its history.
50
+ const WATCH_WITHIN = Duration.days(1);
51
+ const CI_POLL = Duration.minutes(1);
52
+
53
+ // How long a merge commit may go with no CI run before the repo is taken to
54
+ // run none for it, unless the flow's noCiGrace setting says otherwise.
55
+ const NO_CI_GRACE = Duration.minutes(10);
56
+
57
+ // "10 minutes": a duration as config may write one.
58
+ const isDurationText = (text: string): text is `${number} ${Duration.Unit}` =>
59
+ /^\d+(?:\.\d+)? (?:nano|micro|milli|second|minute|hour|day|week)s?$/.test(text);
60
+
61
+ const durationOf = (text: string) =>
62
+ Option.flatMap(Option.liftPredicate(text, isDurationText), Duration.fromInput);
63
+
64
+ // What config.yaml may set for a flow that watches merges, under flows.<name>.settings.
65
+ const Own = Schema.Struct({
66
+ noCiGrace: Schema.optionalKey(
67
+ Schema.String.pipe(
68
+ Schema.check(
69
+ Schema.makeFilter(
70
+ (text: string) =>
71
+ Option.isSome(durationOf(text)) || `"${text}" is not a duration, such as "10 minutes"`,
72
+ ),
73
+ ),
74
+ ).annotate({
75
+ description: `How long a merge commit may go with no CI run before the run takes the repo to run none for it, such as "10 minutes". Default: ${Duration.format(NO_CI_GRACE)}.`,
76
+ }),
77
+ ),
78
+ });
79
+
80
+ // A hidden marker in a comment or an issue body, as chernabog's own are written.
81
+ const marker = <A>(name: string, schema: Schema.Codec<A, Json>) => {
82
+ const pattern = new RegExp(`<!-- chernabog-${name} (\\{.*?\\}) -->`);
83
+ const codec = Schema.fromJsonString(schema);
84
+
85
+ return {
86
+ write: (value: A) => `<!-- chernabog-${name} ${Schema.encodeSync(codec)(value)} -->`,
87
+ read: (body: string): Option.Option<A> =>
88
+ Option.fromNullishOr(body.match(pattern)).pipe(
89
+ Option.flatMap((match) => Schema.decodeOption(codec)(match[1])),
90
+ ),
91
+ };
92
+ };
93
+
94
+ // On the merged pull request: a run watched its merge commit.
95
+ const watchedMarker = marker("post-merge-watched", Schema.Struct({ sha: Schema.String }));
96
+
97
+ // On a follow-up issue: the merge commit whose red CI it is for.
98
+ const followUpMarker = marker(
99
+ "post-merge",
100
+ Schema.Struct({ sha: Schema.String, pullRequest: Schema.Finite }),
101
+ );
102
+
103
+ // What a work item says of a merged pull request.
104
+ const MergedItem = Schema.Struct({
105
+ pullRequest: Schema.Finite,
106
+ url: Schema.String,
107
+ title: Schema.String,
108
+ mergeSha: Schema.String,
109
+ baseRef: Schema.String,
110
+ // The issue the pull request closes, when it names one.
111
+ issue: Schema.optionalKey(Schema.Finite),
112
+ });
113
+
114
+ const ClosedPulls = Schema.Array(
115
+ Schema.Struct({
116
+ number: Schema.Finite,
117
+ title: Schema.String,
118
+ html_url: Schema.String,
119
+ body: Schema.OptionFromNullOr(Schema.String),
120
+ user: Schema.Struct({ login: Schema.String }),
121
+ merged_at: Schema.OptionFromNullOr(Schema.String),
122
+ merge_commit_sha: Schema.OptionFromNullOr(Schema.String),
123
+ base: Schema.Struct({ ref: Schema.String }),
124
+ head: Schema.Struct({ ref: Schema.String }),
125
+ }),
126
+ );
127
+
128
+ const decodeIn =
129
+ <A>(schema: Schema.Codec<A, Json>, step: string) =>
130
+ (json: Json) =>
131
+ Schema.decodeEffect(schema)(json).pipe(
132
+ Effect.mapError((issue) => new StepFailed({ step, message: issue.message })),
133
+ );
134
+
135
+ const sameLogin = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
136
+
137
+ // The issue a pull request closes: the one its body names, or its claim branch's.
138
+ const closedIssue = (body: string, headRef: string) => {
139
+ const named =
140
+ body.match(/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?) #(\d+)/i) ??
141
+ headRef.match(/^auto\/issue-(\d+)$/);
142
+
143
+ return Option.map(Option.fromNullishOr(named), (match) => Number(match[1]));
144
+ };
145
+
146
+ const isRecent = (mergedAt: string, now: DateTime.Utc) =>
147
+ Option.match(DateTime.make(mergedAt), {
148
+ onNone: () => false,
149
+ onSome: (at) =>
150
+ Duration.isLessThanOrEqualTo(
151
+ Duration.millis(DateTime.toEpochMillis(now) - DateTime.toEpochMillis(at)),
152
+ WATCH_WITHIN,
153
+ ),
154
+ });
155
+
156
+ const FailedRun = Schema.Struct({
157
+ name: Schema.String,
158
+ url: Schema.String,
159
+ job: Schema.Option(Schema.Finite),
160
+ workflowRun: Schema.Option(Schema.Finite),
161
+ });
162
+
163
+ // The merge commit's CI as one poll read it: pending with nothing to wait on
164
+ // is no CI yet.
165
+ const MergeCi = Schema.Union([
166
+ Schema.Struct({ state: Schema.Literal("pending"), waitingOn: Schema.Array(Schema.String) }),
167
+ Schema.Struct({ state: Schema.Literal("green") }),
168
+ Schema.Struct({
169
+ state: Schema.Literal("red"),
170
+ failedChecks: Schema.Array(Schema.String),
171
+ failedRuns: Schema.Array(FailedRun),
172
+ }),
173
+ ]);
174
+
175
+ type MergeCi = typeof MergeCi.Type;
176
+
177
+ // Red CI on a merge commit: the checks that failed, and the runs to read why.
178
+ export type RedCi = Extract<MergeCi, { readonly state: "red" }>;
179
+
180
+ const readMergeCi = (sha: string, poll: number) =>
181
+ activity(
182
+ `ci-${poll}`,
183
+ Effect.gen(function* () {
184
+ const report = yield* (yield* GitHub).commitCiState(sha, { event: "push" });
185
+
186
+ switch (report.state) {
187
+ case "pending":
188
+ return { state: "pending" as const, waitingOn: report.waitingOn };
189
+ case "green":
190
+ return { state: "green" as const };
191
+ case "red":
192
+ return {
193
+ state: "red" as const,
194
+ failedChecks: report.failedChecks,
195
+ failedRuns: [...report.failedRuns],
196
+ };
197
+ }
198
+ }),
199
+ MergeCi,
200
+ );
201
+
202
+ const WatchLimits = Schema.Struct({ grace: Schema.Duration, timeout: Schema.Duration });
203
+
204
+ type WatchLimits = typeof WatchLimits.Type;
205
+
206
+ // The no-CI grace and the CI timeout, read once, so a replay decides the same.
207
+ const watchLimits = activity(
208
+ "watch-limits",
209
+ Effect.gen(function* () {
210
+ const own = yield* Settings.read(Own);
211
+ const ci = yield* Settings.ci;
212
+
213
+ return {
214
+ grace: Option.getOrElse(
215
+ Option.flatMap(Option.fromUndefinedOr(own.noCiGrace), durationOf),
216
+ () => NO_CI_GRACE,
217
+ ),
218
+ timeout: ci.timeout,
219
+ };
220
+ }),
221
+ WatchLimits,
222
+ );
223
+
224
+ // What a watch of the merge commit came to, as merged.awaitCi gives it.
225
+ type Watched = {
226
+ readonly state: "none" | "green" | "red";
227
+ readonly summary: string;
228
+ readonly red: Option.Option<RedCi>;
229
+ };
230
+
231
+ // The merge commit, as summaries and the follow-up name it.
232
+ type Merge = {
233
+ readonly pr: PullRequestNumber;
234
+ readonly sha: CommitSha;
235
+ readonly base: BaseBranch;
236
+ };
237
+
238
+ const shortOf = (sha: CommitSha) => sha.slice(0, 7);
239
+
240
+ // Polls the merge commit's push CI durably until it stops pending. No run
241
+ // within the noCiGrace setting is no CI for this push; still pending after
242
+ // the ciTimeout setting is a person's to look at.
243
+ const awaitMergeCi = (merge: Merge, limits: WatchLimits) =>
244
+ Effect.gen(function* () {
245
+ const grace = Duration.toMillis(limits.grace);
246
+ const timeout = Duration.toMillis(limits.timeout);
247
+ const every = Duration.toMillis(CI_POLL);
248
+
249
+ for (let poll = 1; ; poll++) {
250
+ if (poll > 1) {
251
+ yield* sleep(`ci-${poll}-wait`, CI_POLL);
252
+ }
253
+
254
+ const reading = yield* readMergeCi(merge.sha, poll);
255
+
256
+ if (reading.state !== "pending") {
257
+ return reading;
258
+ }
259
+
260
+ const waited = (poll - 1) * every;
261
+
262
+ if (reading.waitingOn.length === 0 && waited >= grace) {
263
+ return { state: "none" as const };
264
+ }
265
+
266
+ if (waited >= timeout) {
267
+ return yield* new NeedsHuman({
268
+ reason: `CI on ${merge.base} at ${merge.sha} stayed pending for ${Duration.format(limits.timeout)} after #${merge.pr} merged`,
269
+ });
270
+ }
271
+ }
272
+ });
273
+
274
+ // What the watch came to, with what a document's end says of it.
275
+ const watched = (
276
+ merge: Merge,
277
+ limits: WatchLimits,
278
+ ci: RedCi | { readonly state: "green" } | { readonly state: "none" },
279
+ ): Watched => {
280
+ const pr = `#${merge.pr}`;
281
+ const short = shortOf(merge.sha);
282
+
283
+ switch (ci.state) {
284
+ case "none":
285
+ return {
286
+ state: ci.state,
287
+ summary: `${pr}: no CI ran on ${short} within ${Duration.format(limits.grace)}; taken as none for this push`,
288
+ red: Option.none(),
289
+ };
290
+ case "green":
291
+ return { state: ci.state, summary: `${pr}: CI on ${short} is green`, red: Option.none() };
292
+ case "red":
293
+ return { state: ci.state, summary: "", red: Option.some(ci) };
294
+ }
295
+ };
296
+
297
+ const Parents = Schema.Struct({ parents: Schema.Array(Schema.Struct({ sha: Schema.String })) });
298
+
299
+ // Whether push CI was already red on the merge commit's first parent, the
300
+ // base branch as it was before the merge.
301
+ const redBeforeMerge = (sha: CommitSha) =>
302
+ activity(
303
+ "ci-before-merge",
304
+ Effect.gen(function* () {
305
+ const github = yield* GitHub;
306
+ const repo = yield* Repo;
307
+
308
+ const commit = yield* github
309
+ .request("GET", `/repos/${repo.slug}/commits/${sha}`, Option.none())
310
+ .pipe(Effect.flatMap(decodeIn(Parents, "ci-before-merge")));
311
+
312
+ const parent = Arr.head(commit.parents);
313
+
314
+ if (Option.isNone(parent)) {
315
+ return false;
316
+ }
317
+
318
+ return (yield* github.commitCiState(parent.value.sha, { event: "push" })).state === "red";
319
+ }),
320
+ Schema.Boolean,
321
+ );
322
+
323
+ // The follow-up this flow filed that the merged pull request fixed, if it fixed one.
324
+ const fixesAFollowUp = (closes: Option.Option<IssueNumber>) =>
325
+ activity(
326
+ "closes-follow-up",
327
+ Effect.gen(function* () {
328
+ if (Option.isNone(closes)) {
329
+ return Option.none<number>();
330
+ }
331
+
332
+ const issue = yield* (yield* GitHub).issue(closes.value).pipe(
333
+ Effect.asSome,
334
+ Effect.catchTag("NotFound", () => Effect.succeedNone),
335
+ );
336
+
337
+ return Option.map(
338
+ Option.filter(issue, (found) => Option.isSome(followUpMarker.read(found.body))),
339
+ (found) => found.number,
340
+ );
341
+ }),
342
+ Schema.Option(Schema.Finite),
343
+ ).pipe(Effect.map(Option.map(IssueNumber)));
344
+
345
+ const FailureDetail = Schema.Struct({
346
+ name: Schema.String,
347
+ url: Schema.String,
348
+ logTail: Schema.Option(Schema.String),
349
+ });
350
+
351
+ // A failed run's link and the tail of its failed jobs' logs.
352
+ export type FailureDetail = typeof FailureDetail.Type;
353
+
354
+ // Each failed run's link and the tail of its failed jobs' logs.
355
+ const failureDetails = (runs: ReadonlyArray<CiFailedRun>) =>
356
+ activity(
357
+ "failure-details",
358
+ Effect.gen(function* () {
359
+ const github = yield* GitHub;
360
+ const details: Array<FailureDetail> = [];
361
+
362
+ for (const run of runs) {
363
+ const found = yield* github.ciFailureDetails(run);
364
+ details.push({ name: run.name, url: found.url, logTail: found.logTail });
365
+ }
366
+
367
+ return details;
368
+ }),
369
+ Schema.Array(FailureDetail),
370
+ );
371
+
372
+ // A fence longer than any run of backticks in the text it holds.
373
+ const fenced = (text: string) => {
374
+ const longest = Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length));
375
+ const fence = "`".repeat(Math.max(3, longest + 1));
376
+
377
+ return `${fence}text\n${text.trimEnd()}\n${fence}`;
378
+ };
379
+
380
+ // The merged pull request, as the follow-up names it.
381
+ type Merged = Merge & { readonly url: string; readonly title: string };
382
+
383
+ const followUpBody = (
384
+ merged: Merged,
385
+ slug: string,
386
+ ci: RedCi,
387
+ details: ReadonlyArray<FailureDetail>,
388
+ fixed: Option.Option<IssueNumber>,
389
+ ) => {
390
+ const commit = `[\`${shortOf(merged.sha)}\`](https://github.com/${slug}/commit/${merged.sha})`;
391
+
392
+ const runs = details.map((detail) =>
393
+ [
394
+ `### [${detail.name}](${detail.url})`,
395
+ Option.match(detail.logTail, {
396
+ onNone: () => "No log to show; open the run for its output.",
397
+ onSome: fenced,
398
+ }),
399
+ ].join("\n\n"),
400
+ );
401
+
402
+ const unlinked = ci.failedChecks.filter(
403
+ (check) => !details.some((detail) => detail.name === check),
404
+ );
405
+
406
+ return [
407
+ `CI on \`${merged.base}\` went red on ${commit}, the merge commit of #${merged.pr} ([${merged.title}](${merged.url})). CI on the commit before it was not red, so the merge is the likely cause.`,
408
+ ...Option.match(fixed, {
409
+ onNone: () => [],
410
+ onSome: (issue) => [
411
+ `#${merged.pr} was the fix for #${issue}, itself a follow-up of a red merge, so this one is for a person rather than another follow-up.`,
412
+ ],
413
+ }),
414
+ "## Failed runs",
415
+ ...runs,
416
+ ...Arr.match(unlinked, {
417
+ onEmpty: () => [],
418
+ onNonEmpty: (names) => [`Also failed: ${names.join(", ")}.`],
419
+ }),
420
+ "## Acceptance criteria",
421
+ [
422
+ `- [ ] CI on \`${merged.base}\` passes again: the failed checks above pass on the fix.`,
423
+ `- [ ] The fix keeps what #${merged.pr} meant to change, or its pull request says why not.`,
424
+ ].join("\n"),
425
+ followUpMarker.write({ sha: merged.sha, pullRequest: merged.pr }),
426
+ ].join("\n\n");
427
+ };
428
+
429
+ const Made = Schema.Array(
430
+ Schema.Struct({ number: Schema.Finite, body: Schema.OptionFromNullOr(Schema.String) }),
431
+ );
432
+
433
+ // The follow-up already filed for this merge commit, among the issues this login opened lately.
434
+ const filedFor = (sha: CommitSha) =>
435
+ Effect.gen(function* () {
436
+ const github = yield* GitHub;
437
+ const repo = yield* Repo;
438
+ const login = yield* github.login;
439
+
440
+ const recent = yield* github.request(
441
+ "GET",
442
+ `/repos/${repo.slug}/issues?state=all&creator=${encodeURIComponent(login)}&sort=created&direction=desc&per_page=100`,
443
+ Option.none(),
444
+ );
445
+
446
+ const made = Option.getOrElse(Schema.decodeUnknownOption(Made)(recent), () => []);
447
+
448
+ return Option.fromUndefinedOr(
449
+ made.find((issue) =>
450
+ Option.exists(
451
+ Option.flatMap(issue.body, followUpMarker.read),
452
+ (found) => found.sha === sha,
453
+ ),
454
+ )?.number,
455
+ );
456
+ });
457
+
458
+ // Files the follow-up, or finds the one a run filed before it crashed.
459
+ const fileFollowUp = (merged: Merged, body: string, fixed: Option.Option<IssueNumber>) =>
460
+ activity(
461
+ "file-follow-up",
462
+ Effect.gen(function* () {
463
+ const existing = yield* filedFor(merged.sha);
464
+
465
+ if (Option.isSome(existing)) {
466
+ return existing.value;
467
+ }
468
+
469
+ const labelNames = yield* Settings.labels;
470
+
471
+ const issue = yield* (yield* GitHub).createIssue({
472
+ title: `CI is red on ${merged.base} after #${merged.pr} merged`,
473
+ body,
474
+ labels: [
475
+ Option.match(fixed, {
476
+ onNone: () => labelNames.eligible,
477
+ onSome: () => labelNames.needsHuman,
478
+ }),
479
+ ],
480
+ });
481
+
482
+ return issue.number;
483
+ }),
484
+ Schema.Finite,
485
+ ).pipe(Effect.map(IssueNumber));
486
+
487
+ // Step names, which more than one block may use: an implement flow's CI is
488
+ // ci-<round>-<poll>, and this watch's ci-<poll>.
489
+ const CI_STEPS = "ci";
490
+
491
+ export const postMergeBlocks = {
492
+ "merged.markWatched": defineBlock({
493
+ name: "merged.markWatched",
494
+ about:
495
+ "Comments on the merged pull request that a run is watching CI on its merge commit, with a hidden marker (chernabog-post-merge-watched). pr.mergedRecently leaves a pull request with that marker alone, so each merge is watched once.",
496
+ inputKinds: {
497
+ pr: "PullRequestNumber: the merged pull request, trigger.pr",
498
+ sha: "CommitSha: its merge commit, trigger.sha",
499
+ base: "BaseBranch: the branch it merged into, trigger.base",
500
+ },
501
+ outputKinds: "nothing",
502
+ outcomeKinds: {},
503
+ inputs: { pr: "required", sha: "required", base: "required" },
504
+ run: (input: {
505
+ readonly pr: PullRequestNumber;
506
+ readonly sha: CommitSha;
507
+ readonly base: BaseBranch;
508
+ }) =>
509
+ PullRequest.comment(
510
+ input.pr,
511
+ `Watching CI on \`${input.base}\` at ${input.sha}, this pull request's merge commit. ${watchedMarker.write({ sha: input.sha })}`,
512
+ ),
513
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
514
+ outcomes: {},
515
+ mustRoute: [],
516
+ contributes: {},
517
+ }),
518
+
519
+ "merged.awaitCi": defineBlock({
520
+ name: "merged.awaitCi",
521
+ about:
522
+ "Waits for push CI on the merge commit, reading it once a minute, durably (ci-1, then ci-2-wait and ci-2, and on), with the noCiGrace and ciTimeout settings read once first (watch-limits). Comes to green, to red, or to none when no CI run started within noCiGrace (10 minutes by default). Still pending after ciTimeout, the run ends needing a person. Only push runs count, so a pull request's runs on the same commit don't.",
523
+ inputKinds: {
524
+ pr: "PullRequestNumber: the merged pull request, trigger.pr",
525
+ sha: "CommitSha: its merge commit, trigger.sha",
526
+ base: "BaseBranch: the branch it merged into, trigger.base",
527
+ },
528
+ outputKinds: {
529
+ state: "none, green or red",
530
+ summary: "for `end`'s summary, on none and green",
531
+ red: "the red CI, on red",
532
+ },
533
+ outcomeKinds: {
534
+ none: "an object: summary, for end's summary",
535
+ green: "an object: summary, for end's summary",
536
+ red: "the red CI: failedChecks and failedRuns, for merged.failureDetails and merged.fileFollowUp",
537
+ },
538
+ waits: true,
539
+ stepNames: ["watch-limits", CI_STEPS],
540
+ inputs: { pr: "required", sha: "required", base: "required" },
541
+ run: (input: Merge) =>
542
+ Effect.gen(function* () {
543
+ const limits = yield* watchLimits;
544
+
545
+ return watched(input, limits, yield* awaitMergeCi(input, limits));
546
+ }),
547
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
548
+ outcomes: {
549
+ none: (ci: Watched) =>
550
+ Option.liftPredicate({ summary: ci.summary }, () => ci.state === "none"),
551
+ green: (ci: Watched) =>
552
+ Option.liftPredicate({ summary: ci.summary }, () => ci.state === "green"),
553
+ red: (ci: Watched) => ci.red,
554
+ },
555
+ mustRoute: ["none", "green", "red"],
556
+ exhaustive: true,
557
+ contributes: { settings: { ...Settings.Ci.fields, ...Own.fields } },
558
+ }),
559
+
560
+ "merged.redBefore": defineBlock({
561
+ name: "merged.redBefore",
562
+ about:
563
+ "Reads push CI on the merge commit's first parent, the base branch as it was before the merge (ci-before-merge). Comes to already-red when it was red there too: the merge didn't break it. The commit before may still be running CI, which reads as not red.",
564
+ inputKinds: {
565
+ pr: "PullRequestNumber: the merged pull request, trigger.pr",
566
+ sha: "CommitSha: its merge commit, trigger.sha",
567
+ },
568
+ outputKinds: {
569
+ redBefore: "boolean: whether CI was red before the merge",
570
+ summary: "for `end`'s summary, on already-red",
571
+ },
572
+ outcomeKinds: { "already-red": "an object: summary, for end's summary" },
573
+ inputs: { pr: "required", sha: "required" },
574
+ run: (input: { readonly pr: PullRequestNumber; readonly sha: CommitSha }) =>
575
+ redBeforeMerge(input.sha).pipe(
576
+ Effect.map((redBefore) => ({
577
+ redBefore,
578
+ summary: `#${input.pr}: CI on ${shortOf(input.sha)} is red, as it already was before the merge; filed nothing`,
579
+ })),
580
+ ),
581
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
582
+ outcomes: {
583
+ "already-red": (before: { readonly redBefore: boolean; readonly summary: string }) =>
584
+ Option.liftPredicate({ summary: before.summary }, () => before.redBefore),
585
+ },
586
+ mustRoute: ["already-red"],
587
+ contributes: {},
588
+ }),
589
+
590
+ "merged.closesFollowUp": defineBlock({
591
+ name: "merged.closesFollowUp",
592
+ about:
593
+ "Whether the issue the merged pull request closes is itself a follow-up of a red merge, by its hidden marker (chernabog-post-merge) (closes-follow-up). Its output is that issue, or none, for merged.fileFollowUp and merged.linkFollowUp: a red merge of a follow-up's own fix goes to a person, not to another follow-up.",
594
+ inputKinds: { issue: "Option<IssueNumber>: the issue it closes, trigger.issue" },
595
+ outputKinds: { fixed: "Option<IssueNumber>: the follow-up it fixed, if any" },
596
+ outcomeKinds: {},
597
+ inputs: { issue: "required" },
598
+ run: (input: { readonly issue: Option.Option<IssueNumber> }) =>
599
+ fixesAFollowUp(input.issue).pipe(Effect.map((fixed) => ({ fixed }))),
600
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
601
+ outcomes: {},
602
+ mustRoute: [],
603
+ contributes: {},
604
+ }),
605
+
606
+ "merged.failureDetails": defineBlock({
607
+ name: "merged.failureDetails",
608
+ about:
609
+ "Each failed run's link and the tail of its failed jobs' logs (failure-details), for merged.fileFollowUp.",
610
+ inputKinds: { ci: "the red CI, from merged.awaitCi's red" },
611
+ outputKinds: { details: "each failed run: name, url and the tail of its log" },
612
+ outcomeKinds: {},
613
+ inputs: { ci: "required" },
614
+ run: (input: { readonly ci: RedCi }) =>
615
+ failureDetails(input.ci.failedRuns).pipe(Effect.map((details) => ({ details }))),
616
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
617
+ outcomes: {},
618
+ mustRoute: [],
619
+ contributes: {},
620
+ }),
621
+
622
+ "merged.fileFollowUp": defineBlock({
623
+ name: "merged.fileFollowUp",
624
+ about:
625
+ "Files an issue, CI is red on <base> after #<n> merged, linking the merged pull request, the merge commit and each failed run with the tail of its log, with acceptance criteria for the fix (file-follow-up). It is labelled auto:eligible so implement takes it, or auto:needs-human when the pull request was a follow-up's own fix. Its body carries a hidden marker with the merge commit's sha (chernabog-post-merge): a run that resumes after filing finds that issue among the ones the persona opened lately and files no other.",
626
+ inputKinds: {
627
+ pr: "PullRequestNumber: the merged pull request, trigger.pr",
628
+ url: "its URL, trigger.url",
629
+ title: "its title, trigger.title",
630
+ sha: "CommitSha: its merge commit, trigger.sha",
631
+ base: "BaseBranch: the branch it merged into, trigger.base",
632
+ ci: "the red CI, from merged.awaitCi's red",
633
+ details: "from merged.failureDetails",
634
+ fixed: "Option<IssueNumber>: from merged.closesFollowUp",
635
+ },
636
+ outputKinds: "IssueNumber: the follow-up",
637
+ outcomeKinds: {},
638
+ inputs: {
639
+ pr: "required",
640
+ url: "required",
641
+ title: "required",
642
+ sha: "required",
643
+ base: "required",
644
+ ci: "required",
645
+ details: "required",
646
+ fixed: "required",
647
+ },
648
+ run: (input: {
649
+ readonly pr: PullRequestNumber;
650
+ readonly url: string;
651
+ readonly title: string;
652
+ readonly sha: CommitSha;
653
+ readonly base: BaseBranch;
654
+ readonly ci: RedCi;
655
+ readonly details: ReadonlyArray<FailureDetail>;
656
+ readonly fixed: Option.Option<IssueNumber>;
657
+ }) =>
658
+ Effect.gen(function* () {
659
+ const repo = yield* Repo;
660
+ const body = followUpBody(input, repo.slug, input.ci, input.details, input.fixed);
661
+
662
+ return yield* fileFollowUp(input, body, input.fixed);
663
+ }),
664
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
665
+ outcomes: {},
666
+ mustRoute: [],
667
+ contributes: {},
668
+ }),
669
+
670
+ "merged.linkFollowUp": defineBlock({
671
+ name: "merged.linkFollowUp",
672
+ about:
673
+ "Comments on the merged pull request that CI went red on its merge commit, linking the follow-up. Its output is a summary, for end's summary.",
674
+ inputKinds: {
675
+ pr: "PullRequestNumber: the merged pull request, trigger.pr",
676
+ sha: "CommitSha: its merge commit, trigger.sha",
677
+ base: "BaseBranch: the branch it merged into, trigger.base",
678
+ followUp: "IssueNumber: from merged.fileFollowUp",
679
+ fixed: "Option<IssueNumber>: from merged.closesFollowUp",
680
+ },
681
+ outputKinds: "a summary, for `end`'s summary",
682
+ outcomeKinds: {},
683
+ inputs: {
684
+ pr: "required",
685
+ sha: "required",
686
+ base: "required",
687
+ followUp: "required",
688
+ fixed: "required",
689
+ },
690
+ run: (input: {
691
+ readonly pr: PullRequestNumber;
692
+ readonly sha: CommitSha;
693
+ readonly base: BaseBranch;
694
+ readonly followUp: IssueNumber;
695
+ readonly fixed: Option.Option<IssueNumber>;
696
+ }) =>
697
+ Effect.gen(function* () {
698
+ const purpose = Option.match(input.fixed, {
699
+ onNone: () => "to fix it",
700
+ onSome: () => "for a person",
701
+ });
702
+
703
+ yield* PullRequest.comment(
704
+ input.pr,
705
+ `CI on \`${input.base}\` went red on this pull request's merge commit: #${input.followUp} is ${purpose}.`,
706
+ );
707
+
708
+ const pr = `#${input.pr}`;
709
+ const short = shortOf(input.sha);
710
+
711
+ if (Option.isSome(input.fixed)) {
712
+ return `${pr}: CI on ${short} is red after a follow-up's fix; filed #${input.followUp} for a person`;
713
+ }
714
+
715
+ return `${pr}: CI on ${short} is red; filed #${input.followUp} to fix it`;
716
+ }),
717
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
718
+ outcomes: {},
719
+ mustRoute: [],
720
+ contributes: {},
721
+ }),
722
+ };
723
+
724
+ export const postMergeSources = {
725
+ // Pull requests this persona wrote that merged into the base branch in the
726
+ // last day, among the 30 closed most lately, and that no run has watched yet.
727
+ "pr.mergedRecently": defineSource("pr.mergedRecently", "merged", () => ({
728
+ trigger: Effect.gen(function* () {
729
+ const github = yield* GitHub;
730
+ const repo = yield* Repo;
731
+ const base = yield* Settings.base;
732
+ const me = yield* github.login;
733
+ const now = yield* DateTime.now;
734
+ const items: Array<WorkItem> = [];
735
+
736
+ const closed = yield* github
737
+ .request(
738
+ "GET",
739
+ `/repos/${repo.slug}/pulls?state=closed&sort=updated&direction=desc&per_page=30`,
740
+ Option.none(),
741
+ )
742
+ .pipe(Effect.flatMap(decodeIn(ClosedPulls, "trigger")));
743
+
744
+ for (const pull of closed) {
745
+ if (
746
+ !sameLogin(pull.user.login, me) ||
747
+ pull.base.ref !== base ||
748
+ Option.isNone(pull.merge_commit_sha) ||
749
+ !Option.exists(pull.merged_at, (at) => isRecent(at, now))
750
+ ) {
751
+ continue;
752
+ }
753
+
754
+ const comments = yield* github.trustedComments(pull.number);
755
+
756
+ if (comments.some((comment) => Option.isSome(watchedMarker.read(comment.body)))) {
757
+ continue;
758
+ }
759
+
760
+ const issue = closedIssue(
761
+ Option.getOrElse(pull.body, () => ""),
762
+ pull.head.ref,
763
+ );
764
+
765
+ items.push({
766
+ key: `merged-${pull.number}`,
767
+ title: pull.title,
768
+ url: pull.html_url,
769
+ data: {
770
+ pullRequest: pull.number,
771
+ url: pull.html_url,
772
+ title: pull.title,
773
+ mergeSha: pull.merge_commit_sha.value,
774
+ baseRef: pull.base.ref,
775
+ ...Option.match(issue, { onNone: () => ({}), onSome: (number) => ({ issue: number }) }),
776
+ },
777
+ });
778
+ }
779
+
780
+ return items;
781
+ }).pipe(reportAs("trigger")),
782
+ contributes: { settings: Settings.Base.fields, ownWork: true },
783
+ })),
784
+ };
785
+
786
+ // A pull request this persona wrote, merged into the base branch. A run only
787
+ // reads CI and files issues, so nothing else is owned or claimed. A failure
788
+ // going to a person labels the merged pull request auto:needs-human and
789
+ // comments why.
790
+ export const mergedSubject = {
791
+ fields: ["pr", "url", "title", "sha", "base", "issue"],
792
+ kinds: {
793
+ pr: "PullRequestNumber",
794
+ url: "its URL",
795
+ title: "its title",
796
+ sha: "CommitSha",
797
+ base: "BaseBranch",
798
+ issue: "Option<IssueNumber>",
799
+ },
800
+ failureContext: [],
801
+ read: (item: WorkItem) =>
802
+ Schema.decodeUnknownEffect(MergedItem)(item.data).pipe(
803
+ Effect.mapError((issue) => new StepFailed({ step: "item", message: issue.message })),
804
+ Effect.map((merged) => ({
805
+ pr: PullRequestNumber(merged.pullRequest),
806
+ url: merged.url,
807
+ title: merged.title,
808
+ sha: CommitSha(merged.mergeSha),
809
+ base: BaseBranch(merged.baseRef),
810
+ issue: Option.map(Option.fromUndefinedOr(merged.issue), IssueNumber),
811
+ })),
812
+ ),
813
+ scope: <A, E, R>(
814
+ trigger: { readonly pr: PullRequestNumber },
815
+ _options: { readonly claims: boolean },
816
+ body: (context: FailureContext) => Effect.Effect<A, E | ToPerson, R>,
817
+ ) =>
818
+ Effect.suspend(() => body({ pr: Option.some(trigger.pr) })).pipe(
819
+ Effect.catchIf(
820
+ (failure): failure is ToPerson => failure instanceof ToPerson,
821
+ (failure) => PullRequest.handToPerson(trigger.pr, failure.reason),
822
+ ),
823
+ ),
824
+ // The recipe declares none: a merged pull request stays merged.
825
+ stillValid: Option.none(),
826
+ };