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