@chernabog/sdk 0.9.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,1217 @@
1
+ // The epic's blocks: working through a stack of tasks round after round. What
2
+ // the recipe keeps in maps between rounds goes through its document as state,
3
+ // each block taking the state it reads and giving back the state it leaves.
4
+
5
+ import {
6
+ activity,
7
+ awaitSignal,
8
+ Claims,
9
+ Git,
10
+ GitHub,
11
+ Lanes,
12
+ NeedsHuman,
13
+ PlanNodes,
14
+ Repo,
15
+ reportAs,
16
+ Run,
17
+ Skip,
18
+ type WorkItem,
19
+ Worktree,
20
+ } from "@chernabog/core";
21
+ import * as Brand from "effect/Brand";
22
+ import * as Effect from "effect/Effect";
23
+ import * as Option from "effect/Option";
24
+ import * as Schema from "effect/Schema";
25
+
26
+ import {
27
+ BaseBranch,
28
+ type BranchName,
29
+ type Committed,
30
+ defineBlock,
31
+ defineSource,
32
+ type FailureContext,
33
+ type IssueNumber,
34
+ IssueNumber as IssueNumberOf,
35
+ LaneId,
36
+ pullRequestRef,
37
+ ToPerson,
38
+ type WorktreePath,
39
+ } from "./block.ts";
40
+ import * as Epic from "./epic.ts";
41
+ import * as Implement from "./implement.ts";
42
+ import * as Plan from "./plan.ts";
43
+ import * as PullRequest from "./pull-request.ts";
44
+ import * as Routing from "./routing.ts";
45
+ import * as Settings from "./settings.ts";
46
+ import * as Stack from "./stack.ts";
47
+
48
+ export type EpicNumber = number & Brand.Brand<"EpicNumber">;
49
+
50
+ const EpicNumber = Brand.nominal<EpicNumber>();
51
+
52
+ // Tasks implemented at once, unless the flow's atOnce setting says otherwise.
53
+ const AT_ONCE = 2;
54
+
55
+ // What config.yaml may set for this flow alone, under flows.<name>.settings.
56
+ const Own = Schema.Struct({
57
+ atOnce: Schema.optionalKey(
58
+ Schema.Int.annotate({
59
+ description: `How many of the epic's ready tasks the run implements at once. Default: ${AT_ONCE}.`,
60
+ }),
61
+ ),
62
+ ship: Schema.optionalKey(
63
+ Schema.Boolean.annotate({
64
+ description:
65
+ "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.",
66
+ }),
67
+ ),
68
+ });
69
+
70
+ // The id a task's steps carry on an attempt: `task-12` the first time,
71
+ // `task-12-2` once a person has handed it back.
72
+ const attemptId = (issue: number, attempt: number) => {
73
+ if (attempt === 1) {
74
+ return `task-${issue}`;
75
+ }
76
+
77
+ return `task-${issue}-${attempt}`;
78
+ };
79
+
80
+ // How the run's pull requests are queued: by auto:ship when its layers ship,
81
+ // which labels each pull request auto:ship too, the automated path.
82
+ const queuedAs = (ships: boolean) =>
83
+ Effect.gen(function* () {
84
+ if (!ships) {
85
+ return {};
86
+ }
87
+
88
+ return { label: (yield* Settings.labels).ship };
89
+ });
90
+
91
+ // Lets the task's claim go once its attempt ends with a person, as a step of
92
+ // the attempt's own, so a later attempt lets it go again.
93
+ const releaseTask = (issue: number, id: string) =>
94
+ activity(`release-claim#${id}`, Claims.release(Claims.issue(issue)));
95
+
96
+ // Where a stacked task's pull request goes once its work is done, as the step
97
+ // `task-base#<id>`: its base, or, when the layer below merged while the task
98
+ // was implemented (and its branch was deleted with it), the branch that one
99
+ // merged into, and as far down as the layers below it merged too (#249). The
100
+ // work is brought up to date with the new base as a stack's layer is
101
+ // (Stack.updateFromBase): a squash or rebase of the layer below is recorded as
102
+ // already here, so its review shows only the task's change, and its edits of
103
+ // lines that layer added are no conflict. A merge that conflicts is undone and
104
+ // left to resolve-conflicts, as any conflict with its base is. `step` is
105
+ // `task-base#<id>`, or `task-base-2#<id>` when GitHub refused that base.
106
+ const TaskBase = Schema.Struct({ base: Schema.String });
107
+
108
+ const settleBase = (step: string, claimed: Option.Option<string>, worktree: string) =>
109
+ activity(
110
+ step,
111
+ Effect.gen(function* () {
112
+ const github = yield* GitHub;
113
+ const integration = yield* Settings.base;
114
+ const base = Option.getOrElse(claimed, () => integration);
115
+ let target = base;
116
+ // The merged pull request whose base is `target`.
117
+ let lower = Option.none<number>();
118
+
119
+ while (target !== integration) {
120
+ const below = Option.filter(
121
+ yield* github.pullRequestForBranch(target),
122
+ (pull) => pull.state === "merged",
123
+ );
124
+
125
+ if (Option.isNone(below)) {
126
+ break;
127
+ }
128
+
129
+ target = below.value.baseRef;
130
+ lower = Option.some(below.value.number);
131
+ }
132
+
133
+ if (Option.isNone(lower)) {
134
+ return { base };
135
+ }
136
+
137
+ const updated = yield* Stack.updateFromBase(worktree, { lower: lower.value });
138
+
139
+ if (!updated.clean) {
140
+ const git = yield* Git;
141
+ yield* git.run(["merge", "--abort"], worktree).pipe(Effect.ignore);
142
+ }
143
+
144
+ return { base: updated.base };
145
+ }),
146
+ TaskBase,
147
+ );
148
+
149
+ // Whether the branch a task's pull request was refused on is gone, as the
150
+ // step `task-base-gone#<id>`: the layer below merged, and GitHub deleted its
151
+ // branch, between settleBase and the pull request (#320).
152
+ const baseGone = (id: string, base: string) =>
153
+ activity(
154
+ `task-base-gone#${id}`,
155
+ Effect.gen(function* () {
156
+ const github = yield* GitHub;
157
+
158
+ return Option.isNone(yield* github.branchSha(base));
159
+ }),
160
+ Schema.Boolean,
161
+ );
162
+
163
+ // What the run reads of a stacked layer before it carries the layers below up
164
+ // to it, as the step `stack-base-<round>#<pull request>`: the branch it is
165
+ // built on and that branch's head, none once it is gone, and whether a person
166
+ // has the layer. The saved head is the layer's recorded base, so a replay
167
+ // compares as the run first did.
168
+ const StackBase = Schema.Struct({
169
+ base: Schema.String,
170
+ baseSha: Schema.Option(Schema.String),
171
+ withPerson: Schema.Boolean,
172
+ });
173
+
174
+ const readBase = (round: number, pullRequest: number) =>
175
+ activity(
176
+ `stack-base-${round}#${pullRequest}`,
177
+ Effect.gen(function* () {
178
+ const github = yield* GitHub;
179
+ const labelNames = yield* Settings.labels;
180
+ const pull = yield* github.pullRequest(pullRequest);
181
+
182
+ return {
183
+ base: pull.baseRef,
184
+ baseSha: yield* github.branchSha(pull.baseRef),
185
+ withPerson: pull.labels.includes(labelNames.needsHuman),
186
+ };
187
+ }).pipe(
188
+ // A pull request gone under the run leaves nothing to bring up to date.
189
+ Effect.catchTag("NotFound", () =>
190
+ Effect.succeed({ base: "", baseSha: Option.none<string>(), withPerson: false }),
191
+ ),
192
+ ),
193
+ StackBase,
194
+ );
195
+
196
+ // The run's worktree on the layer's branch, brought up to its remote, as the
197
+ // step `prepare-worktree#refresh-<key>`. After a hand-back it is reset to the
198
+ // remote: the refresh that went to a person may have left a merge unfinished
199
+ // there, and the person may have pushed the layer on.
200
+ const refreshWorktree = (branch: string, key: string, attempt: number) =>
201
+ activity(
202
+ `prepare-worktree#refresh-${key}`,
203
+ Effect.gen(function* () {
204
+ const run = yield* Run;
205
+ const git = yield* Git;
206
+ const path = yield* (yield* Worktree).ensure(branch, { runId: run.runId });
207
+
208
+ if (attempt > 1) {
209
+ yield* git.run(["fetch", "--quiet", "origin", branch], path);
210
+ yield* git.run(["reset", "--quiet", "--hard", `origin/${branch}`], path);
211
+ yield* git.run(["clean", "-fdq"], path);
212
+ } else {
213
+ yield* git.pull(path, branch);
214
+ }
215
+
216
+ return path;
217
+ }),
218
+ Schema.String,
219
+ );
220
+
221
+ // Hands a layer whose refresh needs a person to one: labelled auto:needs-human,
222
+ // with the reason. Keyed by the refresh, so a later one goes to a person too.
223
+ const refreshToPerson = (pullRequest: number, key: string, reason: string) =>
224
+ activity(
225
+ `needs-human#refresh-${key}`,
226
+ Effect.gen(function* () {
227
+ const github = yield* GitHub;
228
+ const labelNames = yield* Settings.labels;
229
+ yield* github.addLabel(pullRequest, labelNames.needsHuman);
230
+ yield* github.comment(
231
+ pullRequest,
232
+ `Chernabog stopped bringing this layer up to date with its base and needs a person: ${reason}`,
233
+ );
234
+ }),
235
+ ).pipe(Effect.as(`#${pullRequest}: ${reason}`));
236
+
237
+ // What one refresh did: whether the layer was carried, whether it pushed,
238
+ // and whether it went to a person.
239
+ type Carried = { readonly carried: boolean; readonly pushed: boolean; readonly toPerson: boolean };
240
+
241
+ // Brings one layer up to date with its base at `baseSha` (Stack.refreshLayer):
242
+ // merges it in, adjusts the layer when the base changed what it builds on,
243
+ // pushes and waits for CI. `lower`, once the layer below has merged, is its
244
+ // pull request, so a squash of it is reconciled rather than merged again. One that needs a person is handed to one, and
245
+ // reads as not carried, so the layers above it wait. Every step is keyed by
246
+ // the pull request, the base's sha and, after a hand-back, the attempt, so the
247
+ // refresh after one runs again rather than replaying the outcome it saved.
248
+ const refresh = (
249
+ layer: Epic.Layer,
250
+ pullRequest: number,
251
+ base: string,
252
+ baseSha: string,
253
+ attempt: number,
254
+ lower: Option.Option<number> = Option.none(),
255
+ ) => {
256
+ const again = Option.match(
257
+ Option.filter(Option.some(attempt), (count) => count > 1),
258
+ { onNone: () => "", onSome: (count) => `-${count}` },
259
+ );
260
+
261
+ const key = `${pullRequest}-${baseSha.slice(0, 12)}${again}`;
262
+
263
+ const toPerson = (reason: string) =>
264
+ refreshToPerson(pullRequest, key, reason).pipe(
265
+ Effect.as<Carried>({ carried: false, pushed: false, toPerson: true }),
266
+ );
267
+
268
+ return Effect.gen(function* () {
269
+ const branch = Claims.branchFor(layer.number);
270
+ const worktree = yield* refreshWorktree(branch, key, attempt);
271
+
272
+ const refreshed = yield* Stack.refreshLayer(worktree, {
273
+ pullRequest,
274
+ branch,
275
+ base,
276
+ baseSha,
277
+ attempt,
278
+ ...Option.match(lower, { onNone: () => ({}), onSome: (below) => ({ lower: below }) }),
279
+ });
280
+
281
+ return { carried: true, pushed: !refreshed.upToDate, toPerson: false } satisfies Carried;
282
+ }).pipe(
283
+ Effect.catchTags({
284
+ NeedsHuman: (needsHuman) => toPerson(needsHuman.reason),
285
+ StepFailed: (failed) => toPerson(`${failed.step}: ${failed.message}`),
286
+ NothingCommitted: (nothing) => toPerson(`nothing to push on ${nothing.branch}`),
287
+ PushRejected: (rejected) => toPerson(rejected.message),
288
+ CiTimedOut: (timedOut) => toPerson(timedOut.message),
289
+ // A layer closed or gone under the run has nothing above it to carry.
290
+ PullRequestClosed: () =>
291
+ Effect.succeed<Carried>({ carried: false, pushed: false, toPerson: false }),
292
+ NotFound: () => Effect.succeed<Carried>({ carried: false, pushed: false, toPerson: false }),
293
+ }),
294
+ );
295
+ };
296
+
297
+ // The epic's layers in review on the branch of another in review, bottom to
298
+ // top: each after the one it is stacked on.
299
+ const stackedLayers = (progress: Epic.Progress) => {
300
+ const inReview = new Map(
301
+ progress.layers
302
+ .filter(
303
+ (layer) =>
304
+ layer.state === "in-review" && Option.isSome(Option.fromUndefinedOr(layer.pullRequest)),
305
+ )
306
+ .map((layer) => [layer.number, layer]),
307
+ );
308
+
309
+ const depthOf = (layer: Epic.Layer) => {
310
+ let depth = 0;
311
+ let below = Option.fromUndefinedOr(layer.stackedOn);
312
+
313
+ while (Option.isSome(below) && inReview.has(below.value) && depth < inReview.size) {
314
+ depth += 1;
315
+ below = Option.fromUndefinedOr(inReview.get(below.value)?.stackedOn);
316
+ }
317
+
318
+ return depth;
319
+ };
320
+
321
+ return [...inReview.values()]
322
+ .filter((layer) => depthOf(layer) > 0)
323
+ .toSorted((left, right) => depthOf(left) - depthOf(right));
324
+ };
325
+
326
+ // What the run keeps between rounds about carrying layers up and landing
327
+ // them, by pull request: the base head it last brought each layer up to, its
328
+ // refresh attempt, the layers whose refresh it handed to a person, the layer
329
+ // below each was last seen stacked on, and the layers it has brought up to
330
+ // date with that one's merge. Rebuilt from the rounds' saved results
331
+ // whenever the run resumes.
332
+ export type Upkeep = {
333
+ readonly attempts: Map<number, number>;
334
+ readonly recorded: Map<number, string>;
335
+ readonly withPerson: Set<number>;
336
+ readonly below: Map<number, number>;
337
+ readonly caughtUp: Set<number>;
338
+ };
339
+
340
+ const copyOf = (upkeep: Upkeep): Upkeep => ({
341
+ attempts: new Map(upkeep.attempts),
342
+ recorded: new Map(upkeep.recorded),
343
+ withPerson: new Set(upkeep.withPerson),
344
+ below: new Map(upkeep.below),
345
+ caughtUp: new Set(upkeep.caughtUp),
346
+ });
347
+
348
+ // Carries each layer's change up its stack, bottom to top: a layer whose base
349
+ // branch's head is not the one it was last brought up to is refreshed, then
350
+ // the one above it reads its own base, now moved too. A layer a person has,
351
+ // or whose refresh went to one, waits, and so do the layers above it; the
352
+ // rest of the epic carries on. A layer the run handed to a person and that
353
+ // no longer carries auto:needs-human is handed back: its next refresh is a
354
+ // new attempt. Whether anything was pushed.
355
+ const carryUp = (round: number, progress: Epic.Progress, kept: Upkeep) =>
356
+ Effect.gen(function* () {
357
+ const upkeep = copyOf(kept);
358
+ const { attempts, recorded, withPerson } = upkeep;
359
+ const waiting = new Set<number>();
360
+ let pushed = false;
361
+
362
+ for (const layer of stackedLayers(progress)) {
363
+ const pullRequest = layer.pullRequest ?? 0;
364
+
365
+ if (Option.exists(Option.fromUndefinedOr(layer.stackedOn), (below) => waiting.has(below))) {
366
+ waiting.add(layer.number);
367
+ continue;
368
+ }
369
+
370
+ const read = yield* readBase(round, pullRequest);
371
+
372
+ if (read.withPerson || Option.isNone(read.baseSha)) {
373
+ waiting.add(layer.number);
374
+ continue;
375
+ }
376
+
377
+ if (withPerson.delete(pullRequest)) {
378
+ attempts.set(pullRequest, (attempts.get(pullRequest) ?? 1) + 1);
379
+ }
380
+
381
+ const baseSha = read.baseSha.value;
382
+
383
+ if (recorded.get(pullRequest) === baseSha) {
384
+ continue;
385
+ }
386
+
387
+ const attempt = attempts.get(pullRequest) ?? 1;
388
+ const refreshed = yield* refresh(layer, pullRequest, read.base, baseSha, attempt);
389
+
390
+ if (refreshed.toPerson) {
391
+ withPerson.add(pullRequest);
392
+ }
393
+
394
+ if (!refreshed.carried) {
395
+ waiting.add(layer.number);
396
+ continue;
397
+ }
398
+
399
+ recorded.set(pullRequest, baseSha);
400
+ pushed = pushed || refreshed.pushed;
401
+ }
402
+
403
+ return { moved: pushed, stack: upkeep };
404
+ });
405
+
406
+ // What the run reads of a layer before it lands it, as the step
407
+ // `land-read-<round>#<pull request>`: the branch it is on, whether it ships,
408
+ // whether a person has it, and where it lands: the branch the layer below
409
+ // merged into once that one has, the flow's integration base otherwise, and
410
+ // that branch's head.
411
+ const Landing = Schema.Struct({
412
+ base: Schema.String,
413
+ ships: Schema.Boolean,
414
+ withPerson: Schema.Boolean,
415
+ target: Schema.String,
416
+ targetSha: Schema.Option(Schema.String),
417
+ });
418
+
419
+ const readLanding = (round: number, pullRequest: number, lower: Option.Option<number>) =>
420
+ activity(
421
+ `land-read-${round}#${pullRequest}`,
422
+ Effect.gen(function* () {
423
+ const github = yield* GitHub;
424
+ const labelNames = yield* Settings.labels;
425
+ const pull = yield* github.pullRequest(pullRequest);
426
+
427
+ const target = yield* Option.match(lower, {
428
+ onNone: () => Settings.base,
429
+ onSome: (below) => Effect.map(github.pullRequest(below), (merged) => merged.baseRef),
430
+ });
431
+
432
+ return {
433
+ base: pull.baseRef,
434
+ ships: PullRequest.ships(pull, labelNames),
435
+ withPerson: pull.labels.includes(labelNames.needsHuman),
436
+ target,
437
+ targetSha: yield* github.branchSha(target),
438
+ };
439
+ }).pipe(
440
+ // A pull request gone under the run leaves nothing to land.
441
+ Effect.catchTag("NotFound", () =>
442
+ Effect.succeed({
443
+ base: "",
444
+ ships: false,
445
+ withPerson: false,
446
+ target: "",
447
+ targetSha: Option.none<string>(),
448
+ }),
449
+ ),
450
+ ),
451
+ Landing,
452
+ );
453
+
454
+ // Moves the layer onto `target`, the branch the layer below merged into, as
455
+ // GitHub does by itself when the merged branch is deleted.
456
+ const retarget = (round: number, pullRequest: number, target: string) =>
457
+ activity(
458
+ `retarget-${round}#${pullRequest}`,
459
+ Effect.gen(function* () {
460
+ const repo = yield* Repo;
461
+
462
+ yield* (yield* GitHub).request(
463
+ "PATCH",
464
+ `/repos/${repo.slug}/pulls/${pullRequest}`,
465
+ Option.some({ base: target }),
466
+ );
467
+ }),
468
+ );
469
+
470
+ // The pull request of the layer below a layer that has merged, if the layer
471
+ // was stacked on one: the one it is stacked on now, or, once GitHub moved it
472
+ // onto the base, the one the run last saw it stacked on.
473
+ const mergedBelow = (layer: Epic.Layer, progress: Epic.Progress, upkeep: Upkeep) => {
474
+ const pullRequest = layer.pullRequest ?? 0;
475
+
476
+ const lower = Option.orElse(
477
+ Option.flatMap(Option.fromUndefinedOr(layer.stackedOn), (below) =>
478
+ Option.fromUndefinedOr(progress.layers.find((other) => other.number === below)?.pullRequest),
479
+ ),
480
+ () => Option.fromUndefinedOr(upkeep.below.get(pullRequest)),
481
+ );
482
+
483
+ return Option.filter(lower, (below) =>
484
+ progress.layers.some((other) => other.pullRequest === below && other.state === "merged"),
485
+ );
486
+ };
487
+
488
+ // Whether the layer is still stacked on a layer that has not merged, and so
489
+ // waits; the run remembers which one, for after GitHub moves it onto the base.
490
+ const stillStacked = (layer: Epic.Layer, progress: Epic.Progress, upkeep: Upkeep) => {
491
+ const on = Option.flatMap(Option.fromUndefinedOr(layer.stackedOn), (number) =>
492
+ Option.fromUndefinedOr(progress.layers.find((other) => other.number === number)),
493
+ );
494
+
495
+ if (!Option.exists(on, (lower) => lower.state !== "merged")) {
496
+ return false;
497
+ }
498
+
499
+ const lower = Option.flatMap(on, (found) => Option.fromUndefinedOr(found.pullRequest));
500
+
501
+ for (const [pullRequest, below] of Option.toArray(
502
+ Option.all([Option.fromUndefinedOr(layer.pullRequest), lower]),
503
+ )) {
504
+ upkeep.below.set(pullRequest, below);
505
+ }
506
+
507
+ return true;
508
+ };
509
+
510
+ // Brings a layer whose layer below merged up to date with the branch that one
511
+ // merged into, first moving it there unless GitHub already has. Whether the
512
+ // layer may merge in this round: it was already up to date, and not moved.
513
+ const catchUp = (
514
+ round: number,
515
+ layer: Epic.Layer,
516
+ pullRequest: number,
517
+ read: typeof Landing.Type,
518
+ lower: number,
519
+ upkeep: Upkeep,
520
+ ) =>
521
+ Effect.gen(function* () {
522
+ const moved = read.base !== read.target;
523
+
524
+ if (moved) {
525
+ yield* retarget(round, pullRequest, read.target);
526
+ }
527
+
528
+ const refreshed = yield* refresh(
529
+ layer,
530
+ pullRequest,
531
+ read.target,
532
+ Option.getOrElse(read.targetSha, () => ""),
533
+ upkeep.attempts.get(pullRequest) ?? 1,
534
+ Option.some(lower),
535
+ );
536
+
537
+ if (refreshed.toPerson) {
538
+ upkeep.withPerson.add(pullRequest);
539
+ }
540
+
541
+ if (refreshed.carried) {
542
+ upkeep.caughtUp.add(pullRequest);
543
+ }
544
+
545
+ return {
546
+ moved: moved || refreshed.pushed,
547
+ mayMerge: refreshed.carried && !moved && !refreshed.pushed,
548
+ };
549
+ });
550
+
551
+ // Merges the layer when PullRequest.merge finds that safe, as a step of this
552
+ // round; a refusal leaves it for a later round. Whether it merged.
553
+ const tryMerge = (round: number, pullRequest: number) =>
554
+ PullRequest.merge(pullRequest, { method: "squash", id: `land-${round}` }).pipe(
555
+ Effect.as(true),
556
+ Effect.catchTags({
557
+ MergeRefused: () => Effect.succeed(false),
558
+ PullRequestClosed: () => Effect.succeed(false),
559
+ NotFound: () => Effect.succeed(false),
560
+ }),
561
+ );
562
+
563
+ // Lands one layer in review, if it ships and may: brought up to date once its
564
+ // layer below merged, and merged once it is on the base. Whether it moved.
565
+ const landLayer = (
566
+ round: number,
567
+ layer: Epic.Layer,
568
+ pullRequest: number,
569
+ progress: Epic.Progress,
570
+ upkeep: Upkeep,
571
+ ) =>
572
+ Effect.gen(function* () {
573
+ if (stillStacked(layer, progress, upkeep)) {
574
+ return false;
575
+ }
576
+
577
+ const pending = Option.filter(
578
+ mergedBelow(layer, progress, upkeep),
579
+ () => !upkeep.caughtUp.has(pullRequest),
580
+ );
581
+
582
+ const read = yield* readLanding(round, pullRequest, pending);
583
+
584
+ if (!read.ships || read.withPerson || Option.isNone(read.targetSha)) {
585
+ return false;
586
+ }
587
+
588
+ // A layer whose refresh went to a person, and that a person handed back.
589
+ if (upkeep.withPerson.delete(pullRequest)) {
590
+ upkeep.attempts.set(pullRequest, (upkeep.attempts.get(pullRequest) ?? 1) + 1);
591
+ }
592
+
593
+ if (Option.isSome(pending)) {
594
+ const caught = yield* catchUp(round, layer, pullRequest, read, pending.value, upkeep);
595
+
596
+ if (!caught.mayMerge) {
597
+ return caught.moved;
598
+ }
599
+ } else if (read.base !== read.target) {
600
+ return false;
601
+ }
602
+
603
+ return yield* tryMerge(round, pullRequest);
604
+ });
605
+
606
+ // Lands the epic's layers on the automated path, each once the layers below
607
+ // it have merged. A layer whose layer below merged is moved onto the branch
608
+ // that one merged into, unless GitHub already moved it, and brought up to
609
+ // date with it, the squash reconciled; a layer on the base is merged when
610
+ // PullRequest.merge finds that safe, as it does once its approval stands and
611
+ // its checks are green. A layer still stacked on an open one waits, and so
612
+ // does one a person has. A refused merge is tried again in a later round, or
613
+ // merged by the review flows on their approval. Whether anything moved.
614
+ const land = (round: number, progress: Epic.Progress, kept: Upkeep) =>
615
+ Effect.gen(function* () {
616
+ const upkeep = copyOf(kept);
617
+ let moved = false;
618
+
619
+ for (const layer of progress.layers.filter((one) => one.state === "in-review")) {
620
+ for (const pullRequest of Option.toArray(Option.fromUndefinedOr(layer.pullRequest))) {
621
+ const landed = yield* landLayer(round, layer, pullRequest, progress, upkeep);
622
+ moved = moved || landed;
623
+ }
624
+ }
625
+
626
+ return { moved, stack: upkeep };
627
+ });
628
+
629
+ // What the run keeps between rounds about its tasks: each one's attempts,
630
+ // those a person handed back, those whose attempt ended with a person, and the
631
+ // sub-issues each waited on, as the rounds read them.
632
+ export type TaskState = {
633
+ readonly attempts: ReadonlyMap<number, number>;
634
+ readonly handedBack: ReadonlySet<number>;
635
+ readonly withPerson: ReadonlySet<number>;
636
+ readonly waitedOn: ReadonlyMap<number, ReadonlySet<number>>;
637
+ };
638
+
639
+ // How a task's attempt ended, for the next round to read.
640
+ export type LaneEnding = { readonly issue: number; readonly withPerson: boolean };
641
+
642
+ // A task to start: its lane carries its attempt.
643
+ export type TaskStart = {
644
+ readonly issue: IssueNumber;
645
+ readonly base: Option.Option<BaseBranch>;
646
+ readonly lane: LaneId;
647
+ };
648
+
649
+ // The tasks' state as a round leaves it once it has started some, which can't
650
+ // go on to the next round: epic.recordEndings says how each lane ended first.
651
+ export type TasksStarted = { readonly started: TaskState };
652
+
653
+ // What a loop starts with, by the name a document uses it by.
654
+ export const loopStates = {
655
+ "epic.tasks": (): TaskState => ({
656
+ attempts: new Map(),
657
+ handedBack: new Set(),
658
+ withPerson: new Set(),
659
+ waitedOn: new Map(),
660
+ }),
661
+ "stack.upkeep": (): Upkeep => ({
662
+ attempts: new Map(),
663
+ recorded: new Map(),
664
+ withPerson: new Set(),
665
+ below: new Map(),
666
+ caughtUp: new Set(),
667
+ }),
668
+ };
669
+
670
+ // The lanes of a task's attempts in this run so far, by the ids its steps
671
+ // carry (`task-12`, `task-12-2`): none for one it never started, as a person's.
672
+ const lanesOf = (task: number, attempts: ReadonlyMap<number, number>) =>
673
+ Array.from({ length: attempts.get(task) ?? 0 }, (_, index) => attemptId(task, index + 1));
674
+
675
+ // The ones to start now, by what the round read. A task the run attempted
676
+ // starts again only once it has read as something other than ready since, as
677
+ // one a person handed back with auto:eligible after its questions or a
678
+ // hand-off has; one still ready after its attempt, as one another run holds,
679
+ // waits. An attempt that ended with a person counts as read so: a round runs
680
+ // only once every task started with it ends, so a person may hand the task
681
+ // back before any round reads it with them (#249).
682
+ const planStarts = (progress: Epic.Progress, tasks: TaskState) => {
683
+ const attempts = new Map(tasks.attempts);
684
+ const handedBack = new Set(tasks.handedBack);
685
+ const withPerson = new Set(tasks.withPerson);
686
+
687
+ for (const layer of progress.layers) {
688
+ if (attempts.has(layer.number) && (layer.state !== "ready" || withPerson.has(layer.number))) {
689
+ handedBack.add(layer.number);
690
+ withPerson.delete(layer.number);
691
+ }
692
+ }
693
+
694
+ const ready = Epic.startable(progress).filter(
695
+ (task) => !attempts.has(task.number) || handedBack.has(task.number),
696
+ );
697
+
698
+ const starts = ready.map((task) => {
699
+ const attempt = (attempts.get(task.number) ?? 0) + 1;
700
+ attempts.set(task.number, attempt);
701
+ handedBack.delete(task.number);
702
+
703
+ return {
704
+ issue: IssueNumberOf(task.number),
705
+ base: Option.map(Option.fromUndefinedOr(task.base), BaseBranch),
706
+ lane: LaneId(attemptId(task.number, attempt)),
707
+ attempt,
708
+ };
709
+ });
710
+
711
+ return { attempts, handedBack, withPerson, waitedOn: tasks.waitedOn, starts };
712
+ };
713
+
714
+ // Publishes a task's work: its branch pushed, its pull request opened on the
715
+ // base it settled. The layer below can merge, and its branch go, after its
716
+ // base is settled and before the pull request opens: GitHub then refuses the
717
+ // base. The base is settled again, on what that layer merged into, and the
718
+ // pull request opened there, once (#320).
719
+ const publish = (input: {
720
+ readonly issue: IssueNumber;
721
+ readonly epic: EpicNumber;
722
+ readonly worktree: WorktreePath;
723
+ readonly branch: BranchName;
724
+ readonly base: Option.Option<BaseBranch>;
725
+ readonly outcome: Implement.ImplementOutcome;
726
+ readonly ship: boolean;
727
+ readonly lane: LaneId;
728
+ }) =>
729
+ Effect.gen(function* () {
730
+ const { branch, epic, issue, lane: id, outcome, worktree } = input;
731
+ const queued = yield* queuedAs(input.ship);
732
+
733
+ const pushAndOpen = (step: string, onBase: string, openId: string) =>
734
+ Effect.gen(function* () {
735
+ yield* Implement.push(`${step}#${id}`, worktree, branch, { base: onBase });
736
+
737
+ const opened = yield* Implement.openPullRequest(issue, outcome, {
738
+ base: onBase,
739
+ id: openId,
740
+ partOf: epic,
741
+ ...queued,
742
+ });
743
+
744
+ return { pr: pullRequestRef(opened), base: Option.some(BaseBranch(onBase)) };
745
+ });
746
+
747
+ const settled = yield* settleBase(`task-base#${id}`, input.base, worktree);
748
+
749
+ return yield* pushAndOpen("push", settled.base, id).pipe(
750
+ Effect.catchTag("StepFailed", (refused) =>
751
+ Effect.gen(function* () {
752
+ if (refused.step !== `open-pull-request#${id}` || !(yield* baseGone(id, settled.base))) {
753
+ return yield* refused;
754
+ }
755
+
756
+ const again = yield* settleBase(`task-base-2#${id}`, Option.some(settled.base), worktree);
757
+
758
+ if (again.base === settled.base) {
759
+ return yield* refused;
760
+ }
761
+
762
+ // openPullRequest names its step `open-pull-request#<id>`
763
+ // alone, so the retry's id carries the round.
764
+ return yield* pushAndOpen("push-2", again.base, `${id}-base-2`);
765
+ }),
766
+ ),
767
+ );
768
+ });
769
+
770
+ export const epicBlocks = {
771
+ "epic.claim": defineBlock({
772
+ name: "epic.claim",
773
+ about: "Claims the epic, so only this run works through it.",
774
+ inputKinds: { epic: "EpicNumber" },
775
+ outputKinds: "nothing",
776
+ outcomeKinds: {},
777
+ inputs: { epic: "required" },
778
+ run: (input: { readonly epic: EpicNumber }) => Epic.claim(input.epic),
779
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
780
+ outcomes: {},
781
+ mustRoute: [],
782
+ contributes: { settings: Settings.Base.fields },
783
+ }),
784
+
785
+ // Whether this run's layers ship, read once, so a replay decides the same.
786
+ "epic.ships": defineBlock({
787
+ name: "epic.ships",
788
+ // It reads the epic's settings, which no input shows.
789
+ suits: ["epic"],
790
+ about: "Reads the ship setting once: whether the epic's layers are on the automated path.",
791
+ inputKinds: {},
792
+ outputKinds: { value: "boolean, for `if` or stack.publish" },
793
+ outcomeKinds: {},
794
+ inputs: {},
795
+ run: (_: Record<never, never>) =>
796
+ activity(
797
+ "ships",
798
+ Effect.map(Settings.read(Own), (own) => own.ship === true),
799
+ Schema.Boolean,
800
+ ).pipe(Effect.map((value) => ({ value }))),
801
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
802
+ outcomes: {},
803
+ mustRoute: [],
804
+ contributes: { settings: Own.fields },
805
+ }),
806
+
807
+ // How many tasks the run implements at once, at least one, read once.
808
+ "epic.atOnce": defineBlock({
809
+ name: "epic.atOnce",
810
+ // It reads the epic's settings, which no input shows.
811
+ suits: ["epic"],
812
+ about: "Reads the atOnce setting once: how many tasks run at once, at least one.",
813
+ inputKinds: {},
814
+ outputKinds: { value: "number, for forEach atOnce" },
815
+ outcomeKinds: {},
816
+ inputs: {},
817
+ run: (_: Record<never, never>) =>
818
+ activity(
819
+ "at-once",
820
+ Effect.map(Settings.read(Own), (own) => Math.max(1, own.atOnce ?? AT_ONCE)),
821
+ Schema.Int,
822
+ ).pipe(Effect.map((value) => ({ value }))),
823
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
824
+ outcomes: {},
825
+ mustRoute: [],
826
+ contributes: { settings: Own.fields },
827
+ }),
828
+
829
+ "epic.progress": defineBlock({
830
+ name: "epic.progress",
831
+ about: "Reads where the epic stands this round.",
832
+ inputKinds: { epic: "EpicNumber", round: "the round" },
833
+ outputKinds: {
834
+ layers: "every sub-issue, with its state",
835
+ fingerprint: "what the status comment compares",
836
+ },
837
+ outcomeKinds: {},
838
+ needs: ["epic.claim"],
839
+ inputs: { epic: "required", round: "required" },
840
+ run: (input: { readonly epic: EpicNumber; readonly round: number }) =>
841
+ Epic.progress(input.epic, input.round),
842
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
843
+ outcomes: {},
844
+ mustRoute: [],
845
+ contributes: {},
846
+ }),
847
+
848
+ "epic.postStatus": defineBlock({
849
+ name: "epic.postStatus",
850
+ about: "Keeps one status comment on the epic up to date.",
851
+ inputKinds: { epic: "EpicNumber", round: "the round", progress: "from epic.progress" },
852
+ outputKinds: "nothing",
853
+ outcomeKinds: {},
854
+ before: ["epic.finished"],
855
+ inputs: { epic: "required", round: "required", progress: "required" },
856
+ run: (input: {
857
+ readonly epic: EpicNumber;
858
+ readonly round: number;
859
+ readonly progress: Epic.Progress;
860
+ }) => Epic.postStatus(input.epic, input.round, input.progress),
861
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
862
+ outcomes: {},
863
+ mustRoute: [],
864
+ contributes: {},
865
+ }),
866
+
867
+ // What each layer waits on as this round reads it: the sub-issues a held one
868
+ // waits on, and the one a stacked one is stacked on.
869
+ "epic.noteWaits": defineBlock({
870
+ name: "epic.noteWaits",
871
+ about: "Notes what each task waits on this round, for the run's lanes.",
872
+ inputKinds: { progress: "from epic.progress", tasks: "the epic.tasks state" },
873
+ outputKinds: { tasks: "the epic.tasks state, updated" },
874
+ outcomeKinds: {},
875
+ stepNames: [],
876
+ inputs: { progress: "required", tasks: "required" },
877
+ run: (input: { readonly progress: Epic.Progress; readonly tasks: TaskState }) =>
878
+ Effect.sync(() => {
879
+ const waitedOn = new Map(input.tasks.waitedOn);
880
+
881
+ for (const layer of input.progress.layers) {
882
+ const on = [
883
+ ...(layer.waitsOn ?? []),
884
+ ...Option.toArray(Option.fromUndefinedOr(layer.stackedOn)),
885
+ ];
886
+
887
+ if (on.length > 0) {
888
+ waitedOn.set(layer.number, new Set([...(waitedOn.get(layer.number) ?? []), ...on]));
889
+ }
890
+ }
891
+
892
+ return { tasks: { ...input.tasks, waitedOn } };
893
+ }),
894
+ failures: {},
895
+ outcomes: {},
896
+ mustRoute: [],
897
+ contributes: {},
898
+ }),
899
+
900
+ // Whether every task is closed, which ends the run.
901
+ "epic.finished": defineBlock({
902
+ name: "epic.finished",
903
+ about: "Whether every task is closed.",
904
+ inputKinds: { epic: "EpicNumber", progress: "from epic.progress" },
905
+ outputKinds: { finished: "boolean", summary: "a summary, for `end`'s summary" },
906
+ outcomeKinds: { finished: "a summary, for `end`'s summary" },
907
+ stepNames: [],
908
+ inputs: { epic: "required", progress: "required" },
909
+ run: (input: { readonly epic: EpicNumber; readonly progress: Epic.Progress }) =>
910
+ Effect.succeed({
911
+ finished: Epic.finished(input.progress),
912
+ summary: `#${input.epic}: every task is closed`,
913
+ }),
914
+ failures: {},
915
+ outcomes: {
916
+ finished: (read: { readonly finished: boolean; readonly summary: string }) =>
917
+ Option.liftPredicate(read.summary, () => read.finished),
918
+ },
919
+ mustRoute: ["finished"],
920
+ contributes: {},
921
+ }),
922
+
923
+ "stack.carryUp": defineBlock({
924
+ name: "stack.carryUp",
925
+ about:
926
+ "Carries a moved layer's change up its stack, bottom to top. A layer that needs a person holds the ones above it.",
927
+ inputKinds: {
928
+ round: "the round",
929
+ progress: "from epic.progress",
930
+ stack: "the stack.upkeep state",
931
+ },
932
+ outputKinds: {
933
+ moved: "boolean: whether it pushed anything",
934
+ stack: "the stack.upkeep state, updated",
935
+ },
936
+ outcomeKinds: { moved: "the stack.upkeep state, updated" },
937
+ before: ["stack.land", "epic.startable"],
938
+ inputs: { round: "required", progress: "required", stack: "required" },
939
+ run: (input: {
940
+ readonly round: number;
941
+ readonly progress: Epic.Progress;
942
+ readonly stack: Upkeep;
943
+ }) => carryUp(input.round, input.progress, input.stack),
944
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
945
+ outcomes: {
946
+ moved: (carried: { readonly moved: boolean; readonly stack: Upkeep }) =>
947
+ Option.liftPredicate(carried.stack, () => carried.moved),
948
+ },
949
+ mustRoute: ["moved"],
950
+ progressOn: ["moved"],
951
+ contributes: { settings: Settings.Stacks.fields },
952
+ }),
953
+
954
+ "stack.land": defineBlock({
955
+ name: "stack.land",
956
+ about: "Lands the layers that may, each once those below it have merged.",
957
+ inputKinds: {
958
+ round: "the round",
959
+ progress: "from epic.progress",
960
+ stack: "the stack.upkeep state",
961
+ },
962
+ outputKinds: {
963
+ moved: "boolean: whether anything moved",
964
+ stack: "the stack.upkeep state, updated",
965
+ },
966
+ outcomeKinds: { moved: "the stack.upkeep state, updated" },
967
+ before: ["epic.startable"],
968
+ inputs: { round: "required", progress: "required", stack: "required" },
969
+ run: (input: {
970
+ readonly round: number;
971
+ readonly progress: Epic.Progress;
972
+ readonly stack: Upkeep;
973
+ }) => land(input.round, input.progress, input.stack),
974
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
975
+ outcomes: {
976
+ moved: (landed: { readonly moved: boolean; readonly stack: Upkeep }) =>
977
+ Option.liftPredicate(landed.stack, () => landed.moved),
978
+ },
979
+ mustRoute: ["moved"],
980
+ progressOn: ["moved"],
981
+ contributes: { settings: Settings.MergeHold.fields },
982
+ }),
983
+
984
+ "epic.startable": defineBlock({
985
+ name: "epic.startable",
986
+ about:
987
+ "Decides which tasks to start this round: those ready that haven't been attempted, or that a person handed back.",
988
+ inputKinds: { progress: "from epic.progress", tasks: "the epic.tasks state" },
989
+ outputKinds: {
990
+ tasks: "the epic.tasks state, updated, for a round that starts nothing",
991
+ started: "the tasks as they were started, for epic.recordEndings",
992
+ starts:
993
+ "the tasks to start, for forEach: issue (IssueNumber), base (Option<BaseBranch>), lane (LaneId)",
994
+ },
995
+ outcomeKinds: { none: "the epic.tasks state, updated" },
996
+ stepNames: [],
997
+ inputs: { progress: "required", tasks: "required" },
998
+ run: (input: { readonly progress: Epic.Progress; readonly tasks: TaskState }) =>
999
+ Effect.gen(function* () {
1000
+ const { starts, ...tasks } = planStarts(input.progress, input.tasks);
1001
+
1002
+ // Each lane waited on the lanes of the tasks it waited on, and a later
1003
+ // attempt on the one before it. Declaring it again, as a resumed run
1004
+ // does, changes nothing.
1005
+ for (const start of starts) {
1006
+ yield* Lanes.declare(start.lane, [
1007
+ ...[...(tasks.waitedOn.get(start.issue) ?? [])].flatMap((below) =>
1008
+ lanesOf(below, tasks.attempts),
1009
+ ),
1010
+ ...Option.toArray(
1011
+ Option.map(
1012
+ Option.liftPredicate(start.attempt, (count) => count > 1),
1013
+ (count) => attemptId(start.issue, count - 1),
1014
+ ),
1015
+ ),
1016
+ ]);
1017
+ }
1018
+
1019
+ return { tasks, started: { started: tasks }, starts };
1020
+ }),
1021
+ failures: {},
1022
+ outcomes: {
1023
+ none: (planned: { readonly tasks: TaskState; readonly starts: ReadonlyArray<TaskStart> }) =>
1024
+ Option.liftPredicate(planned.tasks, () => planned.starts.length === 0),
1025
+ },
1026
+ mustRoute: ["none"],
1027
+ // Any task it starts is a new attempt.
1028
+ progressUnless: "none",
1029
+ contributes: {},
1030
+ }),
1031
+
1032
+ // Parks until a layer changes, or a day passes, for what changes no layer: a
1033
+ // person's task closed, say.
1034
+ "epic.park": defineBlock({
1035
+ name: "epic.park",
1036
+ fixed: ["lookAgainAfter"],
1037
+ about: "Parks the run until a layer changes, or `lookAgainAfter` passes.",
1038
+ inputKinds: { round: "the round", lookAgainAfter: 'how long: "1 day"' },
1039
+ outputKinds: "which came first",
1040
+ outcomeKinds: {},
1041
+ inputs: { round: "required", lookAgainAfter: "required" },
1042
+ run: (input: { readonly round: number; readonly lookAgainAfter: "1 day" }) =>
1043
+ awaitSignal([Epic.LAYER_CHANGED], {
1044
+ id: `epic-${input.round}`,
1045
+ timeout: input.lookAgainAfter,
1046
+ }),
1047
+ failures: { NeedsHuman: "told", Skip: "skip", StepFailed: "fail" },
1048
+ outcomes: {},
1049
+ mustRoute: [],
1050
+ waits: true,
1051
+ contributes: {},
1052
+ }),
1053
+
1054
+ "epic.recordEndings": defineBlock({
1055
+ name: "epic.recordEndings",
1056
+ about: "Records how each lane ended, for the next round to read.",
1057
+ inputKinds: {
1058
+ tasks: "the started output of epic.startable",
1059
+ endings: "the output of forEach",
1060
+ },
1061
+ outputKinds: { tasks: "the epic.tasks state, updated" },
1062
+ outcomeKinds: {},
1063
+ stepNames: [],
1064
+ inputs: { tasks: "required", endings: "required" },
1065
+ run: (input: { readonly tasks: TasksStarted; readonly endings: ReadonlyArray<LaneEnding> }) =>
1066
+ Effect.succeed({
1067
+ tasks: {
1068
+ ...input.tasks.started,
1069
+ withPerson: new Set([
1070
+ ...input.tasks.started.withPerson,
1071
+ ...input.endings.filter((ending) => ending.withPerson).map((ending) => ending.issue),
1072
+ ]),
1073
+ },
1074
+ }),
1075
+ failures: {},
1076
+ outcomes: {},
1077
+ mustRoute: [],
1078
+ contributes: {},
1079
+ }),
1080
+
1081
+ "stack.publish": defineBlock({
1082
+ name: "stack.publish",
1083
+ about:
1084
+ "Pushes a task's branch and opens its pull request, on the base it settles: the branch of the layer below, or what that one merged into.",
1085
+ inputKinds: {
1086
+ issue: "IssueNumber",
1087
+ epic: "EpicNumber",
1088
+ worktree: "WorktreePath",
1089
+ branch: "BranchName",
1090
+ base: "Option<BaseBranch>",
1091
+ outcome: "what the agent said",
1092
+ ship: "boolean: from epic.ships",
1093
+ lane: "LaneId",
1094
+ committed: "Committed: from agent.implement",
1095
+ },
1096
+ outputKinds: {
1097
+ pr: "a pull request: number, url",
1098
+ base: "Option<BaseBranch>: the base it opened on",
1099
+ },
1100
+ outcomeKinds: {},
1101
+ opens: ["hand-off"],
1102
+ inputs: {
1103
+ issue: "required",
1104
+ epic: "required",
1105
+ worktree: "required",
1106
+ branch: "required",
1107
+ base: "required",
1108
+ outcome: "required",
1109
+ ship: "required",
1110
+ lane: "required",
1111
+ committed: "required",
1112
+ },
1113
+ run: (input: {
1114
+ readonly issue: IssueNumber;
1115
+ readonly epic: EpicNumber;
1116
+ readonly worktree: WorktreePath;
1117
+ readonly branch: BranchName;
1118
+ readonly base: Option.Option<BaseBranch>;
1119
+ readonly outcome: Implement.ImplementOutcome;
1120
+ readonly ship: boolean;
1121
+ readonly lane: LaneId;
1122
+ readonly committed: Committed;
1123
+ }) => publish(input),
1124
+ failures: {
1125
+ NeedsHuman: "person",
1126
+ NotFound: "skip",
1127
+ NothingCommitted: "person",
1128
+ PushRejected: "person",
1129
+ Skip: "skip",
1130
+ StepFailed: "person",
1131
+ },
1132
+ outcomes: {},
1133
+ mustRoute: [],
1134
+ contributes: {},
1135
+ }),
1136
+
1137
+ // Lets the task's claim go once its attempt ends with a person, as a step of
1138
+ // the attempt's own, so a later attempt lets it go again.
1139
+ "issue.releaseClaim": defineBlock({
1140
+ name: "issue.releaseClaim",
1141
+ about: "Lets a task's claim go, as a step of its lane.",
1142
+ inputKinds: { issue: "IssueNumber", lane: "LaneId" },
1143
+ outputKinds: "nothing",
1144
+ outcomeKinds: {},
1145
+ closes: ["release-claim"],
1146
+ inputs: { issue: "required", lane: "required" },
1147
+ run: (input: { readonly issue: IssueNumber; readonly lane: LaneId }) =>
1148
+ releaseTask(input.issue, input.lane),
1149
+ failures: { NeedsHuman: "person", Skip: "skip", StepFailed: "person" },
1150
+ outcomes: {},
1151
+ mustRoute: [],
1152
+ contributes: {},
1153
+ }),
1154
+ };
1155
+
1156
+ type Scoped<A, E, R> = (context: FailureContext) => Effect.Effect<A, E, R>;
1157
+
1158
+ // How a line of work beside others ends: it can't end the run. A task that
1159
+ // needs a person is handed to one, and lets its claim go; one another run
1160
+ // holds, or that is gone, leaves nothing to do; the run carries on with the
1161
+ // rest either way.
1162
+ export const laneScopes = {
1163
+ "epic.task": <A, E, R>(task: TaskStart, body: Scoped<A, E | ToPerson | Skip, R>) => {
1164
+ const context: FailureContext = { pr: Option.none() };
1165
+
1166
+ // Each task's steps run in its lane of the forEach's node.
1167
+ return Effect.suspend(() => body(context)).pipe(
1168
+ PlanNodes.inLane(task.lane),
1169
+ Effect.as<LaneEnding>({ issue: task.issue, withPerson: false }),
1170
+ Effect.catchIf(
1171
+ (failure): failure is Skip => failure instanceof Skip,
1172
+ () => Effect.succeed<LaneEnding>({ issue: task.issue, withPerson: false }),
1173
+ ),
1174
+ Effect.catchIf(
1175
+ (failure): failure is ToPerson => failure instanceof ToPerson,
1176
+ (failure) =>
1177
+ Implement.handToHuman(task.issue, failure.reason, context.pr, { id: task.lane }).pipe(
1178
+ Effect.tap(() => releaseTask(task.issue, task.lane)),
1179
+ Effect.as<LaneEnding>({ issue: task.issue, withPerson: true }),
1180
+ ),
1181
+ ),
1182
+ );
1183
+ },
1184
+ };
1185
+
1186
+ export const epicSources = {
1187
+ "epic.queued": defineSource("epic.queued", "epic", () => ({
1188
+ trigger: Epic.queued.pipe(reportAs("trigger")),
1189
+ contributes: {
1190
+ settings: { ...Routing.Settings.fields, ...Settings.Board.fields },
1191
+ labels: Plan.flowLabels.filter((label) => label.name === Plan.LABELS.epic),
1192
+ },
1193
+ })),
1194
+ };
1195
+
1196
+ // However the run ends, its claim on the epic goes, and the engine lets its
1197
+ // tasks' claims go too; a run parked between rounds keeps them.
1198
+ export const epicSubject = {
1199
+ fields: ["epic"],
1200
+ kinds: { epic: "EpicNumber" },
1201
+ failureContext: [],
1202
+ read: (item: WorkItem) =>
1203
+ Implement.issueOf(item).pipe(Effect.map((epic) => ({ epic: EpicNumber(epic) }))),
1204
+ scope: <A, E, R>(
1205
+ trigger: { readonly epic: EpicNumber },
1206
+ _options: { readonly claims: boolean },
1207
+ body: Scoped<A, E | ToPerson, R>,
1208
+ ) =>
1209
+ Effect.suspend(() => body({ pr: Option.none() })).pipe(
1210
+ Effect.catchIf(
1211
+ (failure): failure is ToPerson => failure instanceof ToPerson,
1212
+ (failure) => Effect.fail(new NeedsHuman({ reason: failure.reason })),
1213
+ ),
1214
+ Claims.releasing(Claims.epic(trigger.epic)),
1215
+ ),
1216
+ stillValid: Option.some(Epic.stillValid),
1217
+ };