@chernabog/sdk 0.11.1 → 0.13.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/src/implement.ts CHANGED
@@ -51,6 +51,7 @@ import * as Stream from "effect/Stream";
51
51
 
52
52
  import * as Ci from "./ci.ts";
53
53
  import { ADDRESS, CONSIDER } from "./default-prompts.ts";
54
+ import * as Phases from "./phases.ts";
54
55
  import { LABELS as PLAN_LABELS } from "./plan-labels.ts";
55
56
  import { renderPrompt, renderPromptOr } from "./prompt.ts";
56
57
  import { requestReview } from "./pull-request.ts";
@@ -62,10 +63,23 @@ import { issueValidity } from "./still-valid.ts";
62
63
  // The work branch of an issue, as core's claims name it.
63
64
  export const branchFor = Claims.branchFor;
64
65
 
65
- // An issue to implement, and the label that queued it, when it's not eligible's.
66
+ // The pull request a CI job's run parked on (awaitingCi), and the round of
67
+ // CI its record names, which the job that resumes the work waits on.
68
+ export const ResumingCi = Schema.Struct({
69
+ pullRequest: Schema.Finite,
70
+ url: Schema.String,
71
+ round: Schema.Finite,
72
+ });
73
+
74
+ export type ResumingCi = typeof ResumingCi.Type;
75
+
76
+ // An issue to implement, and the label that queued it, when it's not
77
+ // eligible's; or one whose run a CI job parked on its pull request's CI,
78
+ // to resume at that wait.
66
79
  export const IssueItem = Schema.Struct({
67
80
  issue: Schema.Finite,
68
81
  label: Schema.optionalKey(Schema.String),
82
+ resumeCi: Schema.optionalKey(ResumingCi),
69
83
  });
70
84
 
71
85
  export const issueItem = (
@@ -1145,6 +1159,7 @@ export const askForClarification = (
1145
1159
  ].join("\n"),
1146
1160
  );
1147
1161
  yield* github.addLabel(issue, labels.needsClarification);
1162
+ yield* Phases.record(Phases.issueItem(issue), Phases.PHASES.issue.askedQuestions);
1148
1163
  yield* dropInProgress(issue);
1149
1164
  yield* github.deleteBranch(branchFor(issue));
1150
1165
  yield* (yield* Worktree).remove(branchFor(issue));
@@ -1388,10 +1403,42 @@ const CiReading = Schema.Union([
1388
1403
 
1389
1404
  type CiReading = typeof CiReading.Type;
1390
1405
 
1391
- // Polls the pull request's checks durably until they stop pending, or ciTimeout passes.
1392
- const awaitChecks = (pullRequest: number, round: number, options: RepeatOptions) =>
1406
+ // The signal a run parked on its pull request's CI waits on. No trigger
1407
+ // reports it: the run parks only in a CI job, which ends there, and the job
1408
+ // that resumes the work is a new run (see CiWait.park).
1409
+ export const CI_SETTLED = "ci-settled";
1410
+
1411
+ // How a wait for CI goes on: `park` names the item (Phases.issueItem or
1412
+ // pullRequestItem) a CI job's run records awaitingCi on before it parks,
1413
+ // rather than polling through the wait on a billed runner. The flow then
1414
+ // resumes from that record in the next job, at `firstRound`, the round the
1415
+ // record names. Without `park`, or outside a CI job (Repo's ciJob), it polls.
1416
+ export type CiWait = RepeatOptions & {
1417
+ readonly park?: string;
1418
+ readonly firstRound?: number;
1419
+ };
1420
+
1421
+ // The item to park on, when this run is a CI job's and the flow can resume.
1422
+ const parkingOn = (options: CiWait) =>
1423
+ Effect.map(Repo.use(Effect.succeed), (repo) =>
1424
+ Option.filter(Option.fromUndefinedOr(options.park), () => repo.ciJob === true),
1425
+ );
1426
+
1427
+ // Records that the item waits on this round of CI, then parks; in a CI job,
1428
+ // the job ends there.
1429
+ const parkOnCi = (item: string, round: number, timeout: Duration.Duration, options: CiWait) =>
1430
+ activity(
1431
+ named(options, `awaiting-ci-${round}`),
1432
+ Phases.record(item, Phases.awaitingCi(round)),
1433
+ ).pipe(Effect.andThen(awaitSignal([CI_SETTLED], { id: named(options, `ci-${round}`), timeout })));
1434
+
1435
+ // Polls the pull request's checks durably until they stop pending, or
1436
+ // ciTimeout passes. In a CI job, with somewhere to park, a first reading
1437
+ // still pending parks instead (parkOnCi).
1438
+ const awaitChecks = (pullRequest: number, round: number, options: CiWait) =>
1393
1439
  Effect.gen(function* () {
1394
1440
  const { timeout } = yield* Settings.ci;
1441
+ const parking = yield* parkingOn(options);
1395
1442
 
1396
1443
  const maxPolls = Math.max(
1397
1444
  1,
@@ -1408,6 +1455,10 @@ const awaitChecks = (pullRequest: number, round: number, options: RepeatOptions)
1408
1455
  });
1409
1456
  }
1410
1457
 
1458
+ if (poll === 2 && Option.isSome(parking)) {
1459
+ yield* parkOnCi(parking.value, round, timeout, options);
1460
+ }
1461
+
1411
1462
  if (poll > 1) {
1412
1463
  yield* sleep(named(options, `ci-${round}-wait-${poll}`), CI_POLL);
1413
1464
  }
@@ -1422,18 +1473,26 @@ const awaitChecks = (pullRequest: number, round: number, options: RepeatOptions)
1422
1473
  return reading;
1423
1474
  });
1424
1475
 
1476
+ // Why an item a CI job parked on its pull request's CI (awaitingCi) can't
1477
+ // start yet, for a source to hold it with: the checks are still pending.
1478
+ // None once they're green or red, when the job that resumes it reads them.
1479
+ export const waitingOnCi = (pullRequest: number) =>
1480
+ Effect.map(Ci.pullRequestState(pullRequest), (reading) =>
1481
+ Option.liftPredicate(`waits on CI for #${pullRequest}`, () => reading.state === "pending"),
1482
+ );
1483
+
1425
1484
  export type CiBranch = AuthorSession & BaseOptions & { readonly branch: string };
1426
1485
 
1427
1486
  const waitForCiIn = <E, R>(
1428
1487
  pullRequest: number,
1429
1488
  fixIn: Effect.Effect<string, E, R>,
1430
1489
  target: CiBranch,
1431
- options: RepeatOptions,
1490
+ options: CiWait,
1432
1491
  ) =>
1433
1492
  Effect.gen(function* () {
1434
1493
  const { rounds } = yield* Settings.ci;
1435
1494
 
1436
- for (let round = 1; ; round++) {
1495
+ for (let round = options.firstRound ?? 1; ; round++) {
1437
1496
  const reading = yield* awaitChecks(pullRequest, round, options);
1438
1497
 
1439
1498
  if (reading.state !== "red") {
@@ -1472,12 +1531,14 @@ const waitForCiIn = <E, R>(
1472
1531
  // Waits durably for the pull request's checks. On red, the agent reads the
1473
1532
  // failure, fixes, commits, and the branch is pushed again, up to
1474
1533
  // limits.ciRounds times. Fails with CiTimedOut when the checks stay pending
1475
- // past limits.ciTimeout, and as push does for a fix it can't push.
1534
+ // past limits.ciTimeout, and as push does for a fix it can't push. In a CI
1535
+ // job, with `park`, it records the round it waits on and parks instead of
1536
+ // polling (CiWait).
1476
1537
  export const waitForCi = (
1477
1538
  pullRequest: number,
1478
1539
  worktree: string,
1479
1540
  target: CiBranch,
1480
- options: RepeatOptions = {},
1541
+ options: CiWait = {},
1481
1542
  ) => waitForCiIn(pullRequest, Effect.succeed(worktree), target, options);
1482
1543
 
1483
1544
  // As waitForCi, for a pull request with no worktree yet, such as an adopted
@@ -1486,7 +1547,7 @@ export const waitForCiMaking = <E, R>(
1486
1547
  pullRequest: number,
1487
1548
  worktree: Effect.Effect<string, E, R>,
1488
1549
  target: CiBranch,
1489
- options: RepeatOptions = {},
1550
+ options: CiWait = {},
1490
1551
  ) =>
1491
1552
  Effect.gen(function* () {
1492
1553
  let made = Option.none<string>();
@@ -1525,6 +1586,29 @@ export type HandOffOptions = {
1525
1586
  readonly adoptedBranch?: string;
1526
1587
  } & RepeatOptions;
1527
1588
 
1589
+ const handedOffAs = (options: { readonly draft?: boolean }): Phases.Phase => {
1590
+ if (options.draft === true) {
1591
+ return Phases.PHASES.pullRequest.draft;
1592
+ }
1593
+
1594
+ return Phases.PHASES.pullRequest.reviewAsked;
1595
+ };
1596
+
1597
+ // The phases a hand-off records: the pull request's, waiting for its first
1598
+ // review or, as a draft, for a person to mark it ready, and then the issue's,
1599
+ // whose progress goes on as the pull request's. In that order, so a crash
1600
+ // between the two leaves the pull request findable, and a replay of the
1601
+ // hand-off writes the issue's.
1602
+ export const recordHandOff = (
1603
+ issue: number,
1604
+ pullRequest: number,
1605
+ options: { readonly draft?: boolean },
1606
+ ) =>
1607
+ Effect.gen(function* () {
1608
+ yield* Phases.record(Phases.pullRequestItem(pullRequest), handedOffAs(options));
1609
+ yield* Phases.record(Phases.issueItem(issue), Phases.PHASES.issue.handedOff);
1610
+ });
1611
+
1528
1612
  // Hands the green pull request to review: a review requested of one reviewer
1529
1613
  // from the pool (needs-review for a person without one) unless the options leave it off, and a closing comment
1530
1614
  // on the issue.
@@ -1564,6 +1648,7 @@ export const handOff = (
1564
1648
  }
1565
1649
 
1566
1650
  yield* dropInProgress(issue);
1651
+ yield* recordHandOff(issue, pullRequest.number, options);
1567
1652
 
1568
1653
  if (options.draft === true) {
1569
1654
  yield* github.comment(
@@ -1596,7 +1681,11 @@ export const adoptedOutcome = (adopted: Adopted): ImplementOutcome => ({
1596
1681
  // review: `ready`, or `timeout` once `timeout` passes. Either way the issue's
1597
1682
  // awaiting-ready label comes off.
1598
1683
  export const awaitReady = (issue: number, pullRequest: number, timeout: Duration.Input) =>
1599
- awaitSignal(["ready"], { id: `draft-${pullRequest}`, timeout }).pipe(
1684
+ activity(
1685
+ `awaiting-ready-${pullRequest}`,
1686
+ Phases.record(Phases.issueItem(issue), Phases.PHASES.issue.awaitingReady),
1687
+ ).pipe(
1688
+ Effect.andThen(awaitSignal(["ready"], { id: `draft-${pullRequest}`, timeout })),
1600
1689
  Effect.tap(() =>
1601
1690
  activity(
1602
1691
  `ready-${pullRequest}`,
@@ -1639,6 +1728,100 @@ export const readied = Effect.gen(function* () {
1639
1728
  return items;
1640
1729
  });
1641
1730
 
1731
+ // Where implement parks in a CI job while its pull request's CI runs: on the
1732
+ // issue's record, which awaitingCi reads to resume the work.
1733
+ export const parkOnIssue = (issue: number): CiWait => ({ park: Phases.issueItem(issue) });
1734
+
1735
+ const ISSUE_RECORD = /^issue-(\d+)$/;
1736
+
1737
+ // The issue an item's record is kept for, by its claim's name; none for another item.
1738
+ const issueNamed = (name: string) =>
1739
+ Option.map(Option.fromNullOr(ISSUE_RECORD.exec(name)), (found) => Number(found[1]));
1740
+
1741
+ // One issue whose record says a CI job parked its run on CI, as a work item
1742
+ // that resumes the wait, when its pull request is still open on the issue's
1743
+ // branch and no person has it.
1744
+ const awaitingCiItem = (number: number, round: number) =>
1745
+ Effect.gen(function* () {
1746
+ const github = yield* GitHub;
1747
+ const labelNames = yield* Settings.labels;
1748
+
1749
+ const issue = yield* github.issue(number).pipe(
1750
+ Effect.asSome,
1751
+ Effect.catchTag("NotFound", () => Effect.succeedNone),
1752
+ );
1753
+
1754
+ const open = Option.filter(
1755
+ issue,
1756
+ (found) => found.state !== "closed" && !found.labels.includes(labelNames.needsHuman),
1757
+ );
1758
+
1759
+ if (Option.isNone(open)) {
1760
+ return Option.none<WorkItem>();
1761
+ }
1762
+
1763
+ const pull = Option.filter(
1764
+ yield* github.pullRequestForBranch(branchFor(number)),
1765
+ (found) => found.state === "open",
1766
+ );
1767
+
1768
+ if (Option.isNone(pull)) {
1769
+ return Option.none<WorkItem>();
1770
+ }
1771
+
1772
+ const resumeCi: ResumingCi = { pullRequest: pull.value.number, url: pull.value.url, round };
1773
+
1774
+ const item = yield* routed(open.value, {
1775
+ ...issueItem(open.value),
1776
+ data: { issue: number, resumeCi },
1777
+ });
1778
+
1779
+ return Option.some(
1780
+ Option.match(yield* waitingOnCi(pull.value.number), {
1781
+ onNone: () => item,
1782
+ onSome: (held) => ({ ...item, held }),
1783
+ }),
1784
+ );
1785
+ });
1786
+
1787
+ // Issues a CI job's implement run parked on its pull request's CI (their
1788
+ // record is awaitingCi), as work items that resume that wait: held while the
1789
+ // checks are pending, and free to start once they're green or red, when a
1790
+ // finished CI run (Events.ciCompleted) or the sweep plans them. One closed,
1791
+ // one a person has (auto:needs-human), or one whose pull request is no longer
1792
+ // open is left alone. Each is routed by its assignees.
1793
+ export const awaitingCi = Effect.gen(function* () {
1794
+ const items: Array<WorkItem> = [];
1795
+
1796
+ for (const [name, found] of yield* Phases.records) {
1797
+ const parked = Option.all({ number: issueNamed(name), round: Phases.ciRoundOf(found.phase) });
1798
+
1799
+ for (const { number, round } of Option.toArray(parked)) {
1800
+ for (const resumed of Option.toArray(yield* awaitingCiItem(number, round))) {
1801
+ items.push(resumed);
1802
+ }
1803
+ }
1804
+ }
1805
+
1806
+ return items;
1807
+ });
1808
+
1809
+ // The wait a work item from awaitingCi resumes; none for any other.
1810
+ export const resumingCi = (item: WorkItem): Option.Option<ResumingCi> =>
1811
+ Option.flatMap(Schema.decodeUnknownOption(IssueItem)(item.data), (data) =>
1812
+ Option.fromUndefinedOr(data.resumeCi),
1813
+ );
1814
+
1815
+ // What hand-off tells the issue when the job that opened the pull request
1816
+ // ended while its CI ran, and a later one handed it off.
1817
+ export const resumedOutcome: ImplementOutcome = {
1818
+ status: "done",
1819
+ summary:
1820
+ "CI passed after the job that opened it ended. The pull request says what changed and how it was tested.",
1821
+ title: "",
1822
+ body: "",
1823
+ };
1824
+
1642
1825
  // Labels the work item for a person and says why. No flow picks it up again.
1643
1826
  export const handToHuman = (
1644
1827
  issue: number,
package/src/index.ts CHANGED
@@ -11,8 +11,10 @@ export * as Ci from "./ci.ts";
11
11
  export * as Compose from "./compose.ts";
12
12
  export * as Epic from "./epic.ts";
13
13
  export type * as EpicBlocks from "./epic-blocks.ts";
14
+ export * as Events from "./events.ts";
14
15
  export * as Hybrid from "./hybrid.ts";
15
16
  export * as Implement from "./implement.ts";
17
+ export * as Phases from "./phases.ts";
16
18
  export * as Plan from "./plan.ts";
17
19
  export * from "./prompt.ts";
18
20
  export * as Review from "./review.ts";
package/src/phases.ts ADDED
@@ -0,0 +1,289 @@
1
+ // The phases an item reaches between runs, by kind of item, and what the
2
+ // catalogue declares of them: the phases each source reads and each block
3
+ // records (docs/run-progress/handoffs.md, questions 1 and 8). A phase is
4
+ // written by one flow and read by another, so these declarations are what the
5
+ // check across a repo's flows goes by (Compose.phaseGaps).
6
+ //
7
+ // Unlike labels, a repo can't rename these: no person reads or applies them.
8
+ // A team's own phases are strings it chooses, recorded with progress.advance.
9
+
10
+ import {
11
+ activity,
12
+ Claims,
13
+ CurrentNode,
14
+ type NodeAt,
15
+ Phase as CorePhase,
16
+ type PhaseRecord,
17
+ PhaseWriter,
18
+ Progress,
19
+ ProgressError,
20
+ Run,
21
+ type WorkItem,
22
+ } from "@chernabog/core";
23
+ import * as Arr from "effect/Array";
24
+ import * as Context from "effect/Context";
25
+ import * as Effect from "effect/Effect";
26
+ import * as Option from "effect/Option";
27
+ import * as Schema from "effect/Schema";
28
+
29
+ // What a phase is kept for. These are the names claim refs already use.
30
+ export type ItemKind = "issue" | "pull-request" | "epic";
31
+
32
+ export const ITEM_KINDS: ReadonlyArray<ItemKind> = ["issue", "pull-request", "epic"];
33
+
34
+ export const PHASES = {
35
+ issue: {
36
+ handedOff: "handed-off",
37
+ askedQuestions: "asked-questions",
38
+ awaitingReady: "awaiting-ready",
39
+ awaitingCi: "awaiting-ci",
40
+ proposed: "proposed",
41
+ becameEpic: "became-epic",
42
+ },
43
+ pullRequest: {
44
+ reviewAsked: "review-asked",
45
+ changesAsked: "changes-asked",
46
+ reviewAskedAgain: "review-asked-again",
47
+ approved: "approved",
48
+ mergeHeld: "merge-held",
49
+ readyForPerson: "ready-for-person",
50
+ draft: "draft",
51
+ watched: "watched",
52
+ awaitingCi: "awaiting-ci",
53
+ },
54
+ epic: { waiting: "waiting", finished: "finished" },
55
+ } as const;
56
+
57
+ type PhasesOf<Kind extends keyof typeof PHASES> =
58
+ (typeof PHASES)[Kind][keyof (typeof PHASES)[Kind]];
59
+
60
+ // One of the SDK's phases.
61
+ export type Phase = PhasesOf<"issue"> | PhasesOf<"pullRequest"> | PhasesOf<"epic">;
62
+
63
+ // The phase a CI job's run records before it parks on its pull request's CI
64
+ // (Implement.waitForCi's park): awaiting-ci for the first round, then
65
+ // awaiting-ci-2 once one fix of red CI was pushed, and so on, so the job that
66
+ // resumes it counts ciRounds on from there.
67
+ export const awaitingCi = (round: number) => {
68
+ if (round <= 1) {
69
+ return PHASES.issue.awaitingCi;
70
+ }
71
+
72
+ return `${PHASES.issue.awaitingCi}-${round}`;
73
+ };
74
+
75
+ const AWAITING_CI = /^awaiting-ci(?:-(\d+))?$/;
76
+
77
+ // The round of CI a phase awaitingCi recorded waits on; none for any other phase.
78
+ export const ciRoundOf = (phase: string): Option.Option<number> =>
79
+ Option.map(Option.fromNullOr(AWAITING_CI.exec(phase)), (found) =>
80
+ Option.match(Option.fromUndefinedOr(found[1]), {
81
+ onNone: () => 1,
82
+ onSome: Number,
83
+ }),
84
+ );
85
+
86
+ // What a source reads of an item with no record yet.
87
+ export const NO_RECORD = "none";
88
+
89
+ // The SDK's phases of each kind of item.
90
+ export const phasesOf = (item: ItemKind): ReadonlyArray<string> =>
91
+ Object.values(
92
+ { issue: PHASES.issue, "pull-request": PHASES.pullRequest, epic: PHASES.epic }[item],
93
+ );
94
+
95
+ // The item a run on each subject works on, which a team's own
96
+ // progress.advance step records its phase on. Four subjects are one pull
97
+ // request, seen by different flows.
98
+ export const SUBJECT_ITEMS = {
99
+ issue: "issue",
100
+ spec: "issue",
101
+ "pull-request": "pull-request",
102
+ "changes-asked": "pull-request",
103
+ conflict: "pull-request",
104
+ merged: "pull-request",
105
+ epic: "epic",
106
+ } as const satisfies { readonly [subject: string]: ItemKind };
107
+
108
+ // One phase a block may record on its way out.
109
+ export type Recorded = {
110
+ readonly item: ItemKind;
111
+ readonly phase: Phase;
112
+ // Recorded only when the block comes to this outcome; left out: on any
113
+ // ending that goes on.
114
+ readonly on?: string;
115
+ };
116
+
117
+ // The phases whose items a source finds, or a wake finds parked runs by.
118
+ // NO_RECORD for an item with no record yet.
119
+ export type Reading = {
120
+ readonly item: ItemKind;
121
+ readonly phases: ReadonlyArray<Phase | typeof NO_RECORD>;
122
+ };
123
+
124
+ // A phase a source moves an item to from what it reads on GitHub, such as a
125
+ // person's review, each from the phases it moves on from (question 5).
126
+ export type Reconciling = {
127
+ readonly item: ItemKind;
128
+ readonly from: ReadonlyArray<Phase | typeof NO_RECORD>;
129
+ readonly to: Phase;
130
+ };
131
+
132
+ // What a source declares of phases.
133
+ export type SourceProgress = {
134
+ readonly reads: ReadonlyArray<Reading>;
135
+ readonly reconciles?: ReadonlyArray<Reconciling>;
136
+ };
137
+
138
+ // As a phase is written: lower-case words joined by hyphens.
139
+ export const PHASE_NAME = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
140
+
141
+ // Reading and recording an item's phase, through core's Progress port, for the
142
+ // blocks that own a handoff and the sources that read one. Both a document's
143
+ // blocks and a recipe's own code call these, so the two record and read alike.
144
+
145
+ // The item a phase is kept for, named as its claim is.
146
+ export const issueItem = (issue: number) => Claims.issue(issue);
147
+ export const pullRequestItem = (pullRequest: number) => Claims.pullRequest(pullRequest);
148
+
149
+ const asPhase = Schema.decodeSync(CorePhase);
150
+ const asWriter = Schema.decodeSync(PhaseWriter);
151
+
152
+ // The times a run's write reads the item again after another writer moved it.
153
+ const RECORD_TRIES = 3;
154
+
155
+ // Records that `item` has reached `to`, as the run: from whatever phase it
156
+ // holds now, and nothing when it is there already, so a source that
157
+ // reconciled the same fact first, or a replay, writes no second record. A
158
+ // handoff happens whatever the item held before it, so a lost race reads
159
+ // again and moves on from what it finds. Call it inside the activity that
160
+ // makes the handoff, so a replay of a finished one doesn't write again.
161
+ export const record = (item: string, to: string) =>
162
+ Effect.gen(function* () {
163
+ const progress = yield* Progress;
164
+ const run = yield* Run;
165
+ const phase = asPhase(to);
166
+ const by = asWriter(run.runId);
167
+
168
+ for (let tries = 1; ; tries++) {
169
+ const current = yield* progress.read(item);
170
+
171
+ if (Option.exists(current, (found) => found.phase === phase)) {
172
+ return;
173
+ }
174
+
175
+ const from = Option.map(current, (found) => found.phase);
176
+
177
+ const moved = yield* progress.advance(item, { from, to: phase, by }).pipe(
178
+ Effect.as(false),
179
+ Effect.catchTag("PhaseMoved", (lost) => {
180
+ if (tries < RECORD_TRIES) {
181
+ return Effect.succeed(true);
182
+ }
183
+
184
+ return Effect.fail(new ProgressError({ message: lost.message }));
185
+ }),
186
+ );
187
+
188
+ if (!moved) {
189
+ return;
190
+ }
191
+ }
192
+ });
193
+
194
+ // Every item's record, in one read, for a source that looks at every open item.
195
+ export const records = Progress.use((progress) => progress.readAll);
196
+
197
+ // The record of `item` among `all`, from records.
198
+ export const recordOf = (all: ReadonlyMap<string, PhaseRecord>, item: string) =>
199
+ Option.fromUndefinedOr(all.get(item));
200
+
201
+ // Whether `found` holds one of `phases`.
202
+ export const holds = (found: PhaseRecord, phases: ReadonlyArray<Phase>) =>
203
+ phases.some((phase) => phase === found.phase);
204
+
205
+ // Moves `item` from the record a source read, `found`, to `to`, from a fact
206
+ // on GitHub that no run was there to record, such as a person's review
207
+ // (docs/run-progress/handoffs.md, question 5). Outside a run, so `by` names
208
+ // the source. Returns the record the item holds afterwards: the one written,
209
+ // or, when another writer moved it first, the one it moved it to.
210
+ export const reconcile = (item: string, found: Option.Option<PhaseRecord>, to: Phase, by: string) =>
211
+ Progress.use((progress) =>
212
+ progress
213
+ .advance(item, {
214
+ from: Option.map(found, (held) => held.phase),
215
+ to: asPhase(to),
216
+ by: asWriter(by),
217
+ })
218
+ .pipe(
219
+ Effect.asSome,
220
+ Effect.catchTag("PhaseMoved", () => progress.read(item)),
221
+ ),
222
+ );
223
+
224
+ // A work item's key for the record an item holds: the item, its phase and
225
+ // the record's version shortened as a head SHA is, `pr-7-changes-asked-1a2b3c4`.
226
+ // A new record is new work, as a new head is to pr.conflicting.
227
+ export const keyFor = (item: string, found: PhaseRecord) =>
228
+ `${item}-${found.phase}-${found.version.slice(0, 7)}`;
229
+
230
+ const PullRequestWork = Schema.Struct({ pullRequest: Schema.Finite });
231
+ const IssueWork = Schema.Struct({ issue: Schema.Finite });
232
+
233
+ // The item a run on `subject` works on, from its work item: the pull request
234
+ // its data names, or the issue, or the epic, whose claim is `epic-N` though
235
+ // its work item is the issue's. None for one that names neither.
236
+ export const itemOfWork = (subject: string, work: WorkItem): Option.Option<string> =>
237
+ Option.flatMap(
238
+ Option.map(
239
+ Arr.findFirst(Object.entries(SUBJECT_ITEMS), ([name]) => name === subject),
240
+ ([, kind]): ItemKind => kind,
241
+ ),
242
+ (kind) => {
243
+ if (kind === "pull-request") {
244
+ return Option.map(Schema.decodeUnknownOption(PullRequestWork)(work.data), (found) =>
245
+ pullRequestItem(found.pullRequest),
246
+ );
247
+ }
248
+
249
+ return Option.map(Schema.decodeUnknownOption(IssueWork)(work.data), (found) => {
250
+ if (kind === "epic") {
251
+ return Claims.epic(found.issue);
252
+ }
253
+
254
+ return issueItem(found.issue);
255
+ });
256
+ },
257
+ );
258
+
259
+ // The item a document's run records a team's own phase on (progress.advance):
260
+ // its work item's, as its subject sees it, which Blocks.assemble provides.
261
+ // None outside a document's run.
262
+ export const RecordedOn = Context.Reference<Option.Option<string>>("@chernabog/sdk/RecordedOn", {
263
+ defaultValue: () => Option.none(),
264
+ });
265
+
266
+ // The step a progress.advance records in: named by its node in the plan,
267
+ // with its round and lane, so each step records once and a replay finds it
268
+ // recorded, rather than moving the item back.
269
+ const advanceStep = (phase: string, node: Option.Option<NodeAt>) =>
270
+ Option.match(node, {
271
+ onNone: () => `progress-${phase}`,
272
+ onSome: (at) =>
273
+ [
274
+ `progress-${at.id}`,
275
+ ...Option.toArray(Option.map(at.round, (round) => `${round}`)),
276
+ ...Option.toArray(at.lane),
277
+ ].join("-"),
278
+ });
279
+
280
+ // Records `phase` on the item the document's run works on (RecordedOn), as
281
+ // the run, in a step of its own; nothing outside a document's run.
282
+ export const advanceRun = (phase: string) =>
283
+ Effect.gen(function* () {
284
+ const step = advanceStep(phase, yield* CurrentNode);
285
+
286
+ for (const item of Option.toArray(yield* RecordedOn)) {
287
+ yield* activity(step, record(item, phase));
288
+ }
289
+ });
@@ -22,7 +22,9 @@ import {
22
22
  IssueNumber,
23
23
  ToPerson,
24
24
  } from "./block.ts";
25
+ import * as Events from "./events.ts";
25
26
  import * as Implement from "./implement.ts";
27
+ import { PHASES } from "./phases.ts";
26
28
  import * as Plan from "./plan.ts";
27
29
  import * as Routing from "./routing.ts";
28
30
  import * as Settings from "./settings.ts";
@@ -85,19 +87,24 @@ export const specSubject = {
85
87
  };
86
88
 
87
89
  export const planSources = {
88
- "plan.queued": defineSource("plan.queued", "spec", () => ({
89
- trigger: Effect.gen(function* () {
90
- const queued = yield* (yield* GitHub).queuedIssuesLabelled(Plan.LABELS.plan);
90
+ "plan.queued": defineSource(
91
+ "plan.queued",
92
+ "spec",
93
+ () => ({
94
+ trigger: Effect.gen(function* () {
95
+ const queued = yield* (yield* GitHub).queuedIssuesLabelled(Plan.LABELS.plan);
91
96
 
92
- return yield* Effect.forEach(queued, (issue) =>
93
- Implement.routed(issue, Implement.issueItem(issue, Option.some(Plan.LABELS.plan))),
94
- );
95
- }).pipe(reportAs("trigger")),
96
- contributes: {
97
- settings: { ...Routing.Settings.fields, ...Settings.Board.fields },
98
- labels: Plan.flowLabels,
99
- },
100
- })),
97
+ return yield* Effect.forEach(queued, (issue) =>
98
+ Implement.routed(issue, Implement.issueItem(issue, Option.some(Plan.LABELS.plan))),
99
+ );
100
+ }).pipe(reportAs("trigger")),
101
+ contributes: {
102
+ settings: { ...Routing.Settings.fields, ...Settings.Board.fields },
103
+ labels: Plan.flowLabels,
104
+ },
105
+ }),
106
+ { events: [Events.issueLabelled] },
107
+ ),
101
108
  };
102
109
 
103
110
  // What every plan block suits: each reads or writes the spec's plan, whose
@@ -198,7 +205,12 @@ export const planBlocks = {
198
205
  mustRoute: ["approved", "changes"],
199
206
  exhaustive: true,
200
207
  waits: true,
201
- contributes: { wakes: Plan.answers.pipe(reportAs("trigger")) },
208
+ records: [{ item: "issue", phase: PHASES.issue.proposed }],
209
+ contributes: {
210
+ wakes: Plan.answers.pipe(reportAs("trigger")),
211
+ wakeEvents: [Events.commentCreated],
212
+ wakeReads: [{ item: "issue", phases: [PHASES.issue.proposed] }],
213
+ },
202
214
  }),
203
215
 
204
216
  "plan.changesAsked": defineBlock({
@@ -268,6 +280,7 @@ export const planBlocks = {
268
280
  failures: { NeedsHuman: "person", Skip: "skip", StepFailed: "person" },
269
281
  outcomes: {},
270
282
  mustRoute: [],
283
+ records: [{ item: "issue", phase: PHASES.issue.becameEpic }],
271
284
  contributes: {},
272
285
  }),
273
286