@chernabog/recipes 0.1.0 → 0.2.1

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/flows/epic.ts ADDED
@@ -0,0 +1,823 @@
1
+ // Works through an epic: claim an open issue labelled auto:epic, and for each
2
+ // of its tasks an agent may take that nothing holds back, implement it as
3
+ // implement does, as a pull request on the base branch or stacked on the
4
+ // branch of the one task it builds on. Tasks that don't build on each other
5
+ // run at once. A stack is only pull requests whose base is the branch of the
6
+ // one below: no rebase, no force-push. Between rounds the run keeps one
7
+ // status comment on the epic, and parks until a layer's pull request changes;
8
+ // each layer's review, changes and conflicts are the review, address-review,
9
+ // re-review and resolve-conflicts flows' to do. When a layer's head moves, as
10
+ // a fix pushed on it does, the run carries the change up its stack: it merges
11
+ // each layer's moved base into the layer above, bottom to top. With `ship`
12
+ // set, its layers are on the automated path: each pull request it opens is
13
+ // labelled auto:ship, and once a layer's layer below has merged, the run
14
+ // moves it onto the branch that one merged into, brings it up to date, and
15
+ // merges it when its approval stands. It ends once every sub-issue is closed.
16
+ //
17
+ // Each block is a durable activity from @chernabog/sdk, and a task's carry
18
+ // its number (`implement#task-12`), so tasks in one run never share a step.
19
+ // Side effects belong inside activities or steps, never in the workflow body,
20
+ // which runs again whenever the run resumes.
21
+ //
22
+ // This file is chernabog's epic recipe, and this repo's to change:
23
+ // `chernabog recipes diff` shows how it differs from the recipe's current
24
+ // version. The names of its steps ("claim-epic", "epic-tasks-1") are the keys
25
+ // a run in flight resumes by, so renaming one restarts that step.
26
+
27
+ import {
28
+ activity,
29
+ awaitSignal,
30
+ Claims,
31
+ defineFlow,
32
+ Epic,
33
+ Git,
34
+ GitHub,
35
+ Implement,
36
+ Plan,
37
+ PullRequest,
38
+ Repo,
39
+ reportAs,
40
+ Review,
41
+ Routing,
42
+ Run,
43
+ Settings,
44
+ Stack,
45
+ Worktree,
46
+ } from "@chernabog/sdk";
47
+ import * as Effect from "effect/Effect";
48
+ import * as Option from "effect/Option";
49
+ import * as Schema from "effect/Schema";
50
+
51
+ // Tasks implemented at once, unless the flow's atOnce setting says otherwise.
52
+ const AT_ONCE = 2;
53
+
54
+ // How long the run parks before it looks at the epic again with no signal,
55
+ // for what changes no layer: a person's task closed, say.
56
+ const LOOK_AGAIN_AFTER = "1 day";
57
+
58
+ // What config.yaml may set for this flow alone, under flows.<name>.settings.
59
+ const Own = Schema.Struct({
60
+ atOnce: Schema.optionalKey(
61
+ Schema.Int.annotate({
62
+ description: `How many of the epic's ready tasks the run implements at once. Default: ${AT_ONCE}.`,
63
+ }),
64
+ ),
65
+ ship: Schema.optionalKey(
66
+ Schema.Boolean.annotate({
67
+ description:
68
+ "Whether the epic's layers are on the automated path: each pull request the run opens is labelled auto:ship, and the run merges each approved layer once the layers below it have merged.",
69
+ }),
70
+ ),
71
+ });
72
+
73
+ // Whether this run's layers ship, read once, so a replay decides the same.
74
+ const shipsLayers = activity(
75
+ "ships",
76
+ Effect.map(Settings.read(Own), (own) => own.ship === true),
77
+ Schema.Boolean,
78
+ );
79
+
80
+ // How many tasks the run implements at once, at least one, read once.
81
+ const atOnce = activity(
82
+ "at-once",
83
+ Effect.map(Settings.read(Own), (own) => Math.max(1, own.atOnce ?? AT_ONCE)),
84
+ Schema.Int,
85
+ );
86
+
87
+ // The id a task's steps carry on an attempt: `task-12` the first time,
88
+ // `task-12-2` once a person has handed it back.
89
+ const attemptId = (issue: number, attempt: number) => {
90
+ if (attempt === 1) {
91
+ return `task-${issue}`;
92
+ }
93
+
94
+ return `task-${issue}-${attempt}`;
95
+ };
96
+
97
+ // How the run's pull requests are queued: by auto:ship when its layers ship,
98
+ // which labels each pull request auto:ship too, the automated path.
99
+ const queuedAs = (ships: boolean) =>
100
+ Effect.gen(function* () {
101
+ if (!ships) {
102
+ return {};
103
+ }
104
+
105
+ return { label: (yield* Settings.labels).ship };
106
+ });
107
+
108
+ // Lets the task's claim go once its attempt ends with a person, as a step of
109
+ // the attempt's own, so a later attempt lets it go again.
110
+ const releaseTask = (issue: number, id: string) =>
111
+ activity(`release-claim#${id}`, Claims.release(Claims.issue(issue)));
112
+
113
+ // Where a stacked task's pull request goes once its work is done, as the step
114
+ // `task-base#<id>`: its base, or, when the layer below merged while the task
115
+ // was implemented (and its branch was deleted with it), the branch that one
116
+ // merged into, and as far down as the layers below it merged too (#249). The
117
+ // work is brought up to date with the new base as a stack's layer is
118
+ // (Stack.updateFromBase): a squash or rebase of the layer below is recorded as
119
+ // already here, so its review shows only the task's change, and its edits of
120
+ // lines that layer added are no conflict. A merge that conflicts is undone and
121
+ // left to resolve-conflicts, as any conflict with its base is.
122
+ const TaskBase = Schema.Struct({ base: Schema.String });
123
+
124
+ const settleBase = (id: string, claimed: Option.Option<string>, worktree: string) =>
125
+ activity(
126
+ `task-base#${id}`,
127
+ Effect.gen(function* () {
128
+ const github = yield* GitHub;
129
+ const integration = yield* Settings.base;
130
+ const base = Option.getOrElse(claimed, () => integration);
131
+ let target = base;
132
+ // The merged pull request whose base is `target`.
133
+ let lower = Option.none<number>();
134
+
135
+ while (target !== integration) {
136
+ const below = Option.filter(
137
+ yield* github.pullRequestForBranch(target),
138
+ (pull) => pull.state === "merged",
139
+ );
140
+
141
+ if (Option.isNone(below)) {
142
+ break;
143
+ }
144
+
145
+ target = below.value.baseRef;
146
+ lower = Option.some(below.value.number);
147
+ }
148
+
149
+ if (Option.isNone(lower)) {
150
+ return { base };
151
+ }
152
+
153
+ const updated = yield* Stack.updateFromBase(worktree, { lower: lower.value });
154
+
155
+ if (!updated.clean) {
156
+ const git = yield* Git;
157
+ yield* git.run(["merge", "--abort"], worktree).pipe(Effect.ignore);
158
+ }
159
+
160
+ return { base: updated.base };
161
+ }),
162
+ TaskBase,
163
+ );
164
+
165
+ // Implements one ready task as implement does, on its base, with its own
166
+ // steps and session. A task that needs a person is handed to one, and lets
167
+ // its claim go; the run carries on with the rest either way.
168
+ const implementTask = (
169
+ epic: number,
170
+ task: Epic.Layer,
171
+ attempt: number,
172
+ ships: boolean,
173
+ withPerson: Set<number>,
174
+ ) =>
175
+ Effect.gen(function* () {
176
+ const issue = task.number;
177
+ const id = attemptId(issue, attempt);
178
+ let pullRequest = Option.none<number>();
179
+
180
+ const toPerson = (reason: string) =>
181
+ Implement.handToHuman(issue, reason, pullRequest, { id }).pipe(
182
+ Effect.tap(() => releaseTask(issue, id)),
183
+ Effect.tap(() => Effect.sync(() => withPerson.add(issue))),
184
+ );
185
+
186
+ return yield* Effect.gen(function* () {
187
+ const { base, branch } = yield* Implement.claim(issue, { base: task.base, id });
188
+
189
+ const session = yield* Implement.sessionFor({ id });
190
+ const worktree = yield* Implement.prepareWorktree(branch, { base, id });
191
+ const outcome = yield* Implement.implementWithAgent(issue, worktree, { base, id });
192
+
193
+ if (outcome.status === "needs-clarification") {
194
+ return yield* Implement.askForClarification(issue, outcome, { id }).pipe(
195
+ Effect.tap(() => releaseTask(issue, id)),
196
+ );
197
+ }
198
+
199
+ return yield* Effect.gen(function* () {
200
+ yield* Implement.localGate(worktree, { id, session });
201
+ const settled = yield* settleBase(id, Option.fromUndefinedOr(base), worktree);
202
+ yield* Implement.push(`push#${id}`, worktree, branch, { base: settled.base });
203
+
204
+ const opened = yield* Implement.openPullRequest(issue, outcome, {
205
+ base: settled.base,
206
+ id,
207
+ partOf: epic,
208
+ ...(yield* queuedAs(ships)),
209
+ });
210
+
211
+ pullRequest = Option.some(opened.number);
212
+
213
+ yield* Implement.waitForCi(
214
+ opened.number,
215
+ worktree,
216
+ { ...session, branch, base: settled.base },
217
+ { id },
218
+ );
219
+
220
+ return yield* Implement.handOff(issue, opened, outcome, { needsReview: true, id });
221
+ }).pipe(
222
+ Effect.catchTags({
223
+ NeedsHuman: (needsHuman) => toPerson(needsHuman.reason),
224
+ NothingCommitted: (nothing) =>
225
+ toPerson(`the agent finished without committing anything on ${nothing.branch}`),
226
+ PushRejected: (rejected) => toPerson(rejected.message),
227
+ CiTimedOut: (timedOut) => toPerson(timedOut.message),
228
+ PullRequestClosed: (closed) => toPerson(closed.message),
229
+ }),
230
+ );
231
+ }).pipe(
232
+ Effect.catchTags({
233
+ // Another run holds the task: it is that run's.
234
+ Skip: (skipped) => Effect.succeed(skipped.reason),
235
+ // A task deleted or transferred under the run leaves nothing to do.
236
+ NotFound: (gone) => Effect.succeed(gone.message),
237
+ StepFailed: (failed) => toPerson(`${failed.step}: ${failed.message}`),
238
+ }),
239
+ );
240
+ });
241
+
242
+ // What the run reads of a stacked layer before it carries the layers below up
243
+ // to it, as the step `stack-base-<round>#<pull request>`: the branch it is
244
+ // built on and that branch's head, none once it is gone, and whether a person
245
+ // has the layer. The saved head is the layer's recorded base, so a replay
246
+ // compares as the run first did.
247
+ const StackBase = Schema.Struct({
248
+ base: Schema.String,
249
+ baseSha: Schema.Option(Schema.String),
250
+ withPerson: Schema.Boolean,
251
+ });
252
+
253
+ const readBase = (round: number, pullRequest: number) =>
254
+ activity(
255
+ `stack-base-${round}#${pullRequest}`,
256
+ Effect.gen(function* () {
257
+ const github = yield* GitHub;
258
+ const labelNames = yield* Settings.labels;
259
+ const pull = yield* github.pullRequest(pullRequest);
260
+
261
+ return {
262
+ base: pull.baseRef,
263
+ baseSha: yield* github.branchSha(pull.baseRef),
264
+ withPerson: pull.labels.includes(labelNames.needsHuman),
265
+ };
266
+ }).pipe(
267
+ // A pull request gone under the run leaves nothing to bring up to date.
268
+ Effect.catchTag("NotFound", () =>
269
+ Effect.succeed({ base: "", baseSha: Option.none<string>(), withPerson: false }),
270
+ ),
271
+ ),
272
+ StackBase,
273
+ );
274
+
275
+ // The run's worktree on the layer's branch, brought up to its remote, as the
276
+ // step `prepare-worktree#refresh-<key>`. After a hand-back it is reset to the
277
+ // remote: the refresh that went to a person may have left a merge unfinished
278
+ // there, and the person may have pushed the layer on.
279
+ const refreshWorktree = (branch: string, key: string, attempt: number) =>
280
+ activity(
281
+ `prepare-worktree#refresh-${key}`,
282
+ Effect.gen(function* () {
283
+ const run = yield* Run;
284
+ const git = yield* Git;
285
+ const path = yield* (yield* Worktree).ensure(branch, { runId: run.runId });
286
+
287
+ if (attempt > 1) {
288
+ yield* git.run(["fetch", "--quiet", "origin", branch], path);
289
+ yield* git.run(["reset", "--quiet", "--hard", `origin/${branch}`], path);
290
+ yield* git.run(["clean", "-fdq"], path);
291
+ } else {
292
+ yield* git.pull(path, branch);
293
+ }
294
+
295
+ return path;
296
+ }),
297
+ Schema.String,
298
+ );
299
+
300
+ // Hands a layer whose refresh needs a person to one: labelled auto:needs-human,
301
+ // with the reason. Keyed by the refresh, so a later one goes to a person too.
302
+ const refreshToPerson = (pullRequest: number, key: string, reason: string) =>
303
+ activity(
304
+ `needs-human#refresh-${key}`,
305
+ Effect.gen(function* () {
306
+ const github = yield* GitHub;
307
+ const labelNames = yield* Settings.labels;
308
+ yield* github.addLabel(pullRequest, labelNames.needsHuman);
309
+ yield* github.comment(
310
+ pullRequest,
311
+ `Chernabog stopped bringing this layer up to date with its base and needs a person: ${reason}`,
312
+ );
313
+ }),
314
+ ).pipe(Effect.as(`#${pullRequest}: ${reason}`));
315
+
316
+ // What one refresh did: whether the layer was carried, whether it pushed,
317
+ // and whether it went to a person.
318
+ type Carried = { readonly carried: boolean; readonly pushed: boolean; readonly toPerson: boolean };
319
+
320
+ // Brings one layer up to date with its base at `baseSha` (Stack.refreshLayer):
321
+ // merges it in, adjusts the layer when the base changed what it builds on,
322
+ // pushes and waits for CI. `lower`, once the layer below has merged, is its
323
+ // pull request, so a squash of it is reconciled rather than merged again. One that needs a person is handed to one, and
324
+ // reads as not carried, so the layers above it wait. Every step is keyed by
325
+ // the pull request, the base's sha and, after a hand-back, the attempt, so the
326
+ // refresh after one runs again rather than replaying the outcome it saved.
327
+ const refresh = (
328
+ layer: Epic.Layer,
329
+ pullRequest: number,
330
+ base: string,
331
+ baseSha: string,
332
+ attempt: number,
333
+ lower: Option.Option<number> = Option.none(),
334
+ ) => {
335
+ const again = Option.match(
336
+ Option.filter(Option.some(attempt), (count) => count > 1),
337
+ { onNone: () => "", onSome: (count) => `-${count}` },
338
+ );
339
+
340
+ const key = `${pullRequest}-${baseSha.slice(0, 12)}${again}`;
341
+
342
+ const toPerson = (reason: string) =>
343
+ refreshToPerson(pullRequest, key, reason).pipe(
344
+ Effect.as<Carried>({ carried: false, pushed: false, toPerson: true }),
345
+ );
346
+
347
+ return Effect.gen(function* () {
348
+ const branch = Claims.branchFor(layer.number);
349
+ const worktree = yield* refreshWorktree(branch, key, attempt);
350
+
351
+ const refreshed = yield* Stack.refreshLayer(worktree, {
352
+ pullRequest,
353
+ branch,
354
+ base,
355
+ baseSha,
356
+ attempt,
357
+ ...Option.match(lower, { onNone: () => ({}), onSome: (below) => ({ lower: below }) }),
358
+ });
359
+
360
+ return { carried: true, pushed: !refreshed.upToDate, toPerson: false } satisfies Carried;
361
+ }).pipe(
362
+ Effect.catchTags({
363
+ NeedsHuman: (needsHuman) => toPerson(needsHuman.reason),
364
+ StepFailed: (failed) => toPerson(`${failed.step}: ${failed.message}`),
365
+ NothingCommitted: (nothing) => toPerson(`nothing to push on ${nothing.branch}`),
366
+ PushRejected: (rejected) => toPerson(rejected.message),
367
+ CiTimedOut: (timedOut) => toPerson(timedOut.message),
368
+ // A layer closed or gone under the run has nothing above it to carry.
369
+ PullRequestClosed: () =>
370
+ Effect.succeed<Carried>({ carried: false, pushed: false, toPerson: false }),
371
+ NotFound: () => Effect.succeed<Carried>({ carried: false, pushed: false, toPerson: false }),
372
+ }),
373
+ );
374
+ };
375
+
376
+ // The epic's layers in review on the branch of another in review, bottom to
377
+ // top: each after the one it is stacked on.
378
+ const stackedLayers = (progress: Epic.Progress) => {
379
+ const inReview = new Map(
380
+ progress.layers
381
+ .filter(
382
+ (layer) =>
383
+ layer.state === "in-review" && Option.isSome(Option.fromUndefinedOr(layer.pullRequest)),
384
+ )
385
+ .map((layer) => [layer.number, layer]),
386
+ );
387
+
388
+ const depthOf = (layer: Epic.Layer) => {
389
+ let depth = 0;
390
+ let below = Option.fromUndefinedOr(layer.stackedOn);
391
+
392
+ while (Option.isSome(below) && inReview.has(below.value) && depth < inReview.size) {
393
+ depth += 1;
394
+ below = Option.fromUndefinedOr(inReview.get(below.value)?.stackedOn);
395
+ }
396
+
397
+ return depth;
398
+ };
399
+
400
+ return [...inReview.values()]
401
+ .filter((layer) => depthOf(layer) > 0)
402
+ .toSorted((left, right) => depthOf(left) - depthOf(right));
403
+ };
404
+
405
+ // What the run keeps between rounds about carrying layers up and landing
406
+ // them, by pull request: the base head it last brought each layer up to, its
407
+ // refresh attempt, the layers whose refresh it handed to a person, the layer
408
+ // below each was last seen stacked on, and the layers it has brought up to
409
+ // date with that one's merge. Rebuilt from the rounds' saved results
410
+ // whenever the run resumes.
411
+ type Upkeep = {
412
+ readonly attempts: Map<number, number>;
413
+ readonly recorded: Map<number, string>;
414
+ readonly withPerson: Set<number>;
415
+ readonly below: Map<number, number>;
416
+ readonly caughtUp: Set<number>;
417
+ };
418
+
419
+ // Carries each layer's change up its stack, bottom to top: a layer whose base
420
+ // branch's head is not the one it was last brought up to is refreshed, then
421
+ // the one above it reads its own base, now moved too. A layer a person has,
422
+ // or whose refresh went to one, waits, and so do the layers above it; the
423
+ // rest of the epic carries on. A layer the run handed to a person and that
424
+ // no longer carries auto:needs-human is handed back: its next refresh is a
425
+ // new attempt. Whether anything was pushed.
426
+ const carryUp = (round: number, progress: Epic.Progress, upkeep: Upkeep) =>
427
+ Effect.gen(function* () {
428
+ const { attempts, recorded, withPerson } = upkeep;
429
+ const waiting = new Set<number>();
430
+ let pushed = false;
431
+
432
+ for (const layer of stackedLayers(progress)) {
433
+ const pullRequest = layer.pullRequest ?? 0;
434
+
435
+ if (Option.exists(Option.fromUndefinedOr(layer.stackedOn), (below) => waiting.has(below))) {
436
+ waiting.add(layer.number);
437
+ continue;
438
+ }
439
+
440
+ const read = yield* readBase(round, pullRequest);
441
+
442
+ if (read.withPerson || Option.isNone(read.baseSha)) {
443
+ waiting.add(layer.number);
444
+ continue;
445
+ }
446
+
447
+ if (withPerson.delete(pullRequest)) {
448
+ attempts.set(pullRequest, (attempts.get(pullRequest) ?? 1) + 1);
449
+ }
450
+
451
+ const baseSha = read.baseSha.value;
452
+
453
+ if (recorded.get(pullRequest) === baseSha) {
454
+ continue;
455
+ }
456
+
457
+ const attempt = attempts.get(pullRequest) ?? 1;
458
+ const refreshed = yield* refresh(layer, pullRequest, read.base, baseSha, attempt);
459
+
460
+ if (refreshed.toPerson) {
461
+ withPerson.add(pullRequest);
462
+ }
463
+
464
+ if (!refreshed.carried) {
465
+ waiting.add(layer.number);
466
+ continue;
467
+ }
468
+
469
+ recorded.set(pullRequest, baseSha);
470
+ pushed = pushed || refreshed.pushed;
471
+ }
472
+
473
+ return pushed;
474
+ });
475
+
476
+ // What the run reads of a layer before it lands it, as the step
477
+ // `land-read-<round>#<pull request>`: the branch it is on, whether it ships,
478
+ // whether a person has it, and where it lands: the branch the layer below
479
+ // merged into once that one has, the flow's integration base otherwise, and
480
+ // that branch's head.
481
+ const Landing = Schema.Struct({
482
+ base: Schema.String,
483
+ ships: Schema.Boolean,
484
+ withPerson: Schema.Boolean,
485
+ target: Schema.String,
486
+ targetSha: Schema.Option(Schema.String),
487
+ });
488
+
489
+ const readLanding = (round: number, pullRequest: number, lower: Option.Option<number>) =>
490
+ activity(
491
+ `land-read-${round}#${pullRequest}`,
492
+ Effect.gen(function* () {
493
+ const github = yield* GitHub;
494
+ const labelNames = yield* Settings.labels;
495
+ const pull = yield* github.pullRequest(pullRequest);
496
+
497
+ const target = yield* Option.match(lower, {
498
+ onNone: () => Settings.base,
499
+ onSome: (below) => Effect.map(github.pullRequest(below), (merged) => merged.baseRef),
500
+ });
501
+
502
+ return {
503
+ base: pull.baseRef,
504
+ ships: PullRequest.ships(pull, labelNames),
505
+ withPerson: pull.labels.includes(labelNames.needsHuman),
506
+ target,
507
+ targetSha: yield* github.branchSha(target),
508
+ };
509
+ }).pipe(
510
+ // A pull request gone under the run leaves nothing to land.
511
+ Effect.catchTag("NotFound", () =>
512
+ Effect.succeed({
513
+ base: "",
514
+ ships: false,
515
+ withPerson: false,
516
+ target: "",
517
+ targetSha: Option.none<string>(),
518
+ }),
519
+ ),
520
+ ),
521
+ Landing,
522
+ );
523
+
524
+ // Moves the layer onto `target`, the branch the layer below merged into, as
525
+ // GitHub does by itself when the merged branch is deleted.
526
+ const retarget = (round: number, pullRequest: number, target: string) =>
527
+ activity(
528
+ `retarget-${round}#${pullRequest}`,
529
+ Effect.gen(function* () {
530
+ const repo = yield* Repo;
531
+
532
+ yield* (yield* GitHub).request(
533
+ "PATCH",
534
+ `/repos/${repo.slug}/pulls/${pullRequest}`,
535
+ Option.some({ base: target }),
536
+ );
537
+ }),
538
+ );
539
+
540
+ // The pull request of the layer below a layer that has merged, if the layer
541
+ // was stacked on one: the one it is stacked on now, or, once GitHub moved it
542
+ // onto the base, the one the run last saw it stacked on.
543
+ const mergedBelow = (layer: Epic.Layer, progress: Epic.Progress, upkeep: Upkeep) => {
544
+ const pullRequest = layer.pullRequest ?? 0;
545
+
546
+ const lower = Option.orElse(
547
+ Option.flatMap(Option.fromUndefinedOr(layer.stackedOn), (below) =>
548
+ Option.fromUndefinedOr(progress.layers.find((other) => other.number === below)?.pullRequest),
549
+ ),
550
+ () => Option.fromUndefinedOr(upkeep.below.get(pullRequest)),
551
+ );
552
+
553
+ return Option.filter(lower, (below) =>
554
+ progress.layers.some((other) => other.pullRequest === below && other.state === "merged"),
555
+ );
556
+ };
557
+
558
+ // Whether the layer is still stacked on a layer that has not merged, and so
559
+ // waits; the run remembers which one, for after GitHub moves it onto the base.
560
+ const stillStacked = (layer: Epic.Layer, progress: Epic.Progress, upkeep: Upkeep) => {
561
+ const on = Option.flatMap(Option.fromUndefinedOr(layer.stackedOn), (number) =>
562
+ Option.fromUndefinedOr(progress.layers.find((other) => other.number === number)),
563
+ );
564
+
565
+ if (!Option.exists(on, (lower) => lower.state !== "merged")) {
566
+ return false;
567
+ }
568
+
569
+ const lower = Option.flatMap(on, (found) => Option.fromUndefinedOr(found.pullRequest));
570
+
571
+ for (const [pullRequest, below] of Option.toArray(
572
+ Option.all([Option.fromUndefinedOr(layer.pullRequest), lower]),
573
+ )) {
574
+ upkeep.below.set(pullRequest, below);
575
+ }
576
+
577
+ return true;
578
+ };
579
+
580
+ // Brings a layer whose layer below merged up to date with the branch that one
581
+ // merged into, first moving it there unless GitHub already has. Whether the
582
+ // layer may merge in this round: it was already up to date, and not moved.
583
+ const catchUp = (
584
+ round: number,
585
+ layer: Epic.Layer,
586
+ pullRequest: number,
587
+ read: typeof Landing.Type,
588
+ lower: number,
589
+ upkeep: Upkeep,
590
+ ) =>
591
+ Effect.gen(function* () {
592
+ const moved = read.base !== read.target;
593
+
594
+ if (moved) {
595
+ yield* retarget(round, pullRequest, read.target);
596
+ }
597
+
598
+ const refreshed = yield* refresh(
599
+ layer,
600
+ pullRequest,
601
+ read.target,
602
+ Option.getOrElse(read.targetSha, () => ""),
603
+ upkeep.attempts.get(pullRequest) ?? 1,
604
+ Option.some(lower),
605
+ );
606
+
607
+ if (refreshed.toPerson) {
608
+ upkeep.withPerson.add(pullRequest);
609
+ }
610
+
611
+ if (refreshed.carried) {
612
+ upkeep.caughtUp.add(pullRequest);
613
+ }
614
+
615
+ return {
616
+ moved: moved || refreshed.pushed,
617
+ mayMerge: refreshed.carried && !moved && !refreshed.pushed,
618
+ };
619
+ });
620
+
621
+ // Merges the layer when PullRequest.merge finds that safe, as a step of this
622
+ // round; a refusal leaves it for a later round. Whether it merged.
623
+ const tryMerge = (round: number, pullRequest: number) =>
624
+ PullRequest.merge(pullRequest, { method: "squash", id: `land-${round}` }).pipe(
625
+ Effect.as(true),
626
+ Effect.catchTags({
627
+ MergeRefused: () => Effect.succeed(false),
628
+ PullRequestClosed: () => Effect.succeed(false),
629
+ NotFound: () => Effect.succeed(false),
630
+ }),
631
+ );
632
+
633
+ // Lands one layer in review, if it ships and may: brought up to date once its
634
+ // layer below merged, and merged once it is on the base. Whether it moved.
635
+ const landLayer = (
636
+ round: number,
637
+ layer: Epic.Layer,
638
+ pullRequest: number,
639
+ progress: Epic.Progress,
640
+ upkeep: Upkeep,
641
+ ) =>
642
+ Effect.gen(function* () {
643
+ if (stillStacked(layer, progress, upkeep)) {
644
+ return false;
645
+ }
646
+
647
+ const pending = Option.filter(
648
+ mergedBelow(layer, progress, upkeep),
649
+ () => !upkeep.caughtUp.has(pullRequest),
650
+ );
651
+
652
+ const read = yield* readLanding(round, pullRequest, pending);
653
+
654
+ if (!read.ships || read.withPerson || Option.isNone(read.targetSha)) {
655
+ return false;
656
+ }
657
+
658
+ // A layer whose refresh went to a person, and that a person handed back.
659
+ if (upkeep.withPerson.delete(pullRequest)) {
660
+ upkeep.attempts.set(pullRequest, (upkeep.attempts.get(pullRequest) ?? 1) + 1);
661
+ }
662
+
663
+ if (Option.isSome(pending)) {
664
+ const caught = yield* catchUp(round, layer, pullRequest, read, pending.value, upkeep);
665
+
666
+ if (!caught.mayMerge) {
667
+ return caught.moved;
668
+ }
669
+ } else if (read.base !== read.target) {
670
+ return false;
671
+ }
672
+
673
+ return yield* tryMerge(round, pullRequest);
674
+ });
675
+
676
+ // Lands the epic's layers on the automated path, each once the layers below
677
+ // it have merged. A layer whose layer below merged is moved onto the branch
678
+ // that one merged into, unless GitHub already moved it, and brought up to
679
+ // date with it, the squash reconciled; a layer on the base is merged when
680
+ // PullRequest.merge finds that safe, as it does once its approval stands and
681
+ // its checks are green. A layer still stacked on an open one waits, and so
682
+ // does one a person has. A refused merge is tried again in a later round, or
683
+ // merged by the review flows on their approval. Whether anything moved.
684
+ const land = (round: number, progress: Epic.Progress, upkeep: Upkeep) =>
685
+ Effect.gen(function* () {
686
+ let moved = false;
687
+
688
+ for (const layer of progress.layers.filter((one) => one.state === "in-review")) {
689
+ for (const pullRequest of Option.toArray(Option.fromUndefinedOr(layer.pullRequest))) {
690
+ const landed = yield* landLayer(round, layer, pullRequest, progress, upkeep);
691
+ moved = moved || landed;
692
+ }
693
+ }
694
+
695
+ return moved;
696
+ });
697
+
698
+ // Round after round: read where the epic stands, write its status comment,
699
+ // carry each moved layer's change up its stack, land the layers that ship
700
+ // and may, start every ready task, and
701
+ // with none left to start, park until a layer changes. A task the run
702
+ // attempted starts again only once it has read as something other than ready
703
+ // since, as one a person handed back with auto:eligible after its questions
704
+ // or a hand-off has; one still ready after its attempt, as one another run
705
+ // holds, waits. An attempt that ended with a person counts as read so: a
706
+ // round runs only once every task started with it ends, so a person may hand
707
+ // the task back before any round reads it with them (#249). The counts are
708
+ // rebuilt from the rounds' saved results whenever the run resumes.
709
+ const workThrough = (epic: number, ships: boolean, concurrency: number) =>
710
+ Effect.gen(function* () {
711
+ const attempts = new Map<number, number>();
712
+ const handedBack = new Set<number>();
713
+ // Tasks whose attempt ended with a person.
714
+ const withPerson = new Set<number>();
715
+
716
+ const upkeep: Upkeep = {
717
+ attempts: new Map(),
718
+ recorded: new Map(),
719
+ withPerson: new Set(),
720
+ below: new Map(),
721
+ caughtUp: new Set(),
722
+ };
723
+
724
+ for (let round = 1; ; round++) {
725
+ const progress = yield* Epic.progress(epic, round);
726
+ yield* Epic.postStatus(epic, round, progress);
727
+
728
+ if (Epic.finished(progress)) {
729
+ return `#${epic}: every task is closed`;
730
+ }
731
+
732
+ // A refresh moved layers' heads: read the epic again before going on.
733
+ if (yield* carryUp(round, progress, upkeep)) {
734
+ continue;
735
+ }
736
+
737
+ // A layer merged, moved or was brought up to date: read the epic again.
738
+ if (ships && (yield* land(round, progress, upkeep))) {
739
+ continue;
740
+ }
741
+
742
+ for (const layer of progress.layers) {
743
+ if (
744
+ attempts.has(layer.number) &&
745
+ (layer.state !== "ready" || withPerson.has(layer.number))
746
+ ) {
747
+ handedBack.add(layer.number);
748
+ withPerson.delete(layer.number);
749
+ }
750
+ }
751
+
752
+ const ready = Epic.startable(progress).filter(
753
+ (task) => !attempts.has(task.number) || handedBack.has(task.number),
754
+ );
755
+
756
+ if (ready.length > 0) {
757
+ const starts = ready.map((task) => {
758
+ const attempt = (attempts.get(task.number) ?? 0) + 1;
759
+ attempts.set(task.number, attempt);
760
+ handedBack.delete(task.number);
761
+
762
+ return { task, attempt };
763
+ });
764
+
765
+ yield* Effect.forEach(
766
+ starts,
767
+ (start) => implementTask(epic, start.task, start.attempt, ships, withPerson),
768
+ {
769
+ concurrency,
770
+ discard: true,
771
+ },
772
+ );
773
+ continue;
774
+ }
775
+
776
+ yield* awaitSignal([Epic.LAYER_CHANGED], {
777
+ id: `epic-${round}`,
778
+ timeout: LOOK_AGAIN_AFTER,
779
+ });
780
+ }
781
+ });
782
+
783
+ // What config.yaml may set for this flow, under settings: or flows.<name>.settings.
784
+ const settings = Schema.Struct({
785
+ ...Routing.Settings.fields,
786
+ ...Settings.Labels.fields,
787
+ ...Settings.Base.fields,
788
+ ...Settings.Board.fields,
789
+ ...Settings.LocalGate.fields,
790
+ ...Settings.Rules.fields,
791
+ ...Settings.Ci.fields,
792
+ ...Settings.Reviewers.fields,
793
+ ...Settings.Stacks.fields,
794
+ ...Own.fields,
795
+ });
796
+
797
+ export default defineFlow({
798
+ trigger: Epic.queued.pipe(reportAs("trigger")),
799
+ gate: Implement.gate,
800
+ concurrency: 1,
801
+ labels: Effect.map(Settings.declaredLabels, (set) => [
802
+ ...set,
803
+ ...Plan.flowLabels.filter((label) => label.name === Plan.LABELS.epic),
804
+ ]),
805
+ settings,
806
+ // Doctor warns when no reviewer its pull requests may ask is a persona here.
807
+ doctor: [Review.poolCheck],
808
+ // An epic closed, or claimed by another run, ends the run as superseded.
809
+ stillValid: Epic.stillValid,
810
+ // Its markers are the SDK's own: claim refs, labels, assignments, branches.
811
+ markers: [],
812
+ workflow: (item) =>
813
+ Effect.gen(function* () {
814
+ const epic = yield* Implement.issueOf(item);
815
+ yield* Epic.claim(epic);
816
+ const ships = yield* shipsLayers;
817
+ const concurrency = yield* atOnce;
818
+
819
+ // However the run ends, its claim on the epic goes, and the engine lets
820
+ // its tasks' claims go too; a run parked between rounds keeps them.
821
+ return yield* workThrough(epic, ships, concurrency).pipe(Claims.releasing(Claims.epic(epic)));
822
+ }),
823
+ });