@chernabog/sdk 0.11.0 → 0.12.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.
@@ -18,7 +18,6 @@ import {
18
18
  StepFailed,
19
19
  type WorkItem,
20
20
  } from "@chernabog/core";
21
- import * as Arr from "effect/Array";
22
21
  import * as Effect from "effect/Effect";
23
22
  import * as Option from "effect/Option";
24
23
  import * as Schema from "effect/Schema";
@@ -35,7 +34,9 @@ import {
35
34
  ToPerson,
36
35
  type WorktreePath,
37
36
  } from "./block.ts";
37
+ import * as Events from "./events.ts";
38
38
  import * as Implement from "./implement.ts";
39
+ import { PHASES } from "./phases.ts";
39
40
  import { renderPrompt } from "./prompt.ts";
40
41
  import * as PullRequest from "./pull-request.ts";
41
42
  import * as Review from "./review.ts";
@@ -450,24 +451,7 @@ export const resolveConflictsBlocks = {
450
451
  readonly base: BaseBranch;
451
452
  readonly pushed: Pushed;
452
453
  }) =>
453
- activity(
454
- "ask-approver-again",
455
- Effect.gen(function* () {
456
- const approval = Option.filter(
457
- Arr.last(yield* Review.decisiveReviews(input.pr)),
458
- (review) => review.state === "APPROVED",
459
- );
460
-
461
- if (Option.isNone(approval)) {
462
- return Option.none<string>();
463
- }
464
-
465
- yield* (yield* GitHub).requestReviewers(input.pr, [approval.value.author]);
466
-
467
- return Option.some(approval.value.author);
468
- }),
469
- Schema.Option(Schema.String),
470
- ).pipe(
454
+ Review.askApproverAgain(input.pr).pipe(
471
455
  Effect.map((approver) =>
472
456
  Option.match(approver, {
473
457
  onNone: () => `#${input.pr}: merged ${input.base} and resolved its conflicts`,
@@ -484,6 +468,7 @@ export const resolveConflictsBlocks = {
484
468
  },
485
469
  outcomes: {},
486
470
  mustRoute: [],
471
+ records: [{ item: "pull-request", phase: PHASES.pullRequest.reviewAskedAgain }],
487
472
  contributes: {},
488
473
  }),
489
474
  };
@@ -500,38 +485,43 @@ export const resolveConflictsSources = {
500
485
  // person has one labelled auto:needs-human, and a run of another flow one it
501
486
  // owns; both are left alone. The key carries the head, so a conflict that
502
487
  // comes back after a later push is new work.
503
- "pr.conflicting": defineSource("pr.conflicting", "conflict", () => ({
504
- trigger: Effect.gen(function* () {
505
- const github = yield* GitHub;
506
- const repo = yield* Repo;
507
- const labelNames = yield* Settings.labels;
508
- const items: Array<WorkItem> = [];
488
+ "pr.conflicting": defineSource(
489
+ "pr.conflicting",
490
+ "conflict",
491
+ () => ({
492
+ trigger: Effect.gen(function* () {
493
+ const github = yield* GitHub;
494
+ const repo = yield* Repo;
495
+ const labelNames = yield* Settings.labels;
496
+ const items: Array<WorkItem> = [];
497
+
498
+ for (const pull of yield* Review.authoredByMe) {
499
+ if (pull.labels.includes(labelNames.needsHuman) || (yield* Review.ownedByARun(pull))) {
500
+ continue;
501
+ }
509
502
 
510
- for (const pull of yield* Review.authoredByMe) {
511
- if (pull.labels.includes(labelNames.needsHuman) || (yield* Review.ownedByARun(pull))) {
512
- continue;
513
- }
503
+ const state = yield* github
504
+ .request("GET", `/repos/${repo.slug}/pulls/${pull.number}`, Option.none())
505
+ .pipe(Effect.flatMap(decodeIn(MergeState, "trigger")));
514
506
 
515
- const state = yield* github
516
- .request("GET", `/repos/${repo.slug}/pulls/${pull.number}`, Option.none())
517
- .pipe(Effect.flatMap(decodeIn(MergeState, "trigger")));
507
+ if (state.mergeable_state !== "dirty") {
508
+ continue;
509
+ }
518
510
 
519
- if (state.mergeable_state !== "dirty") {
520
- continue;
511
+ items.push({
512
+ key: `pr-${pull.number}-${pull.headSha.slice(0, 7)}`,
513
+ title: pull.title,
514
+ url: pull.url,
515
+ data: { pullRequest: pull.number, headRef: pull.headRef, baseRef: pull.baseRef },
516
+ });
521
517
  }
522
518
 
523
- items.push({
524
- key: `pr-${pull.number}-${pull.headSha.slice(0, 7)}`,
525
- title: pull.title,
526
- url: pull.url,
527
- data: { pullRequest: pull.number, headRef: pull.headRef, baseRef: pull.baseRef },
528
- });
529
- }
530
-
531
- return items;
532
- }).pipe(reportAs("trigger")),
533
- contributes: { ownWork: true },
534
- })),
519
+ return items;
520
+ }).pipe(reportAs("trigger")),
521
+ contributes: { ownWork: true },
522
+ }),
523
+ { events: [Events.baseMoved] },
524
+ ),
535
525
  };
536
526
 
537
527
  // A pull request this persona wrote that conflicts with its base. A run owns
package/src/review.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  latestMarker,
19
19
  Machine,
20
20
  NeedsHuman,
21
+ type PhaseRecord,
21
22
  type PullRequest,
22
23
  Repo,
23
24
  ReviewerSeat,
@@ -34,12 +35,14 @@ import {
34
35
  type WorkItem,
35
36
  Worktree,
36
37
  } from "@chernabog/core";
38
+ import * as Arr from "effect/Array";
37
39
  import * as Effect from "effect/Effect";
38
40
  import * as Option from "effect/Option";
39
41
  import * as Schema from "effect/Schema";
40
42
 
41
43
  import { RECHECK } from "./default-prompts.ts";
42
44
  import { ADOPTED_LABEL, sessionIdFor } from "./implement.ts";
45
+ import * as Phases from "./phases.ts";
43
46
  import { renderPrompt, renderPromptOr } from "./prompt.ts";
44
47
  import * as PullRequestSteps from "./pull-request.ts";
45
48
  import * as Routing from "./routing.ts";
@@ -115,13 +118,23 @@ const sameLogin = (left: string, right: string) => left.toLowerCase() === right.
115
118
  // flow that uses it, or any block that reviews, requires ReviewerSeat.
116
119
  export const reviewerLogin = ReviewerSeat.use((seat) => seat.login);
117
120
 
121
+ // An open pull request that asks this persona for a review: how many reviews
122
+ // it has submitted on it so far, and the pull request's record, none for one
123
+ // with no phase recorded yet.
124
+ export type ReviewRequest = {
125
+ readonly pull: PullRequest;
126
+ readonly reviewed: number;
127
+ readonly record: Option.Option<PhaseRecord>;
128
+ };
129
+
118
130
  // Open pull requests that ask this persona for a review, each with how many
119
- // reviews it has submitted on it so far. One a run of another flow owns is
120
- // left out. It requires the persona's seat in the reviewer pool.
131
+ // reviews it has submitted on it so far and its record. One a run of another
132
+ // flow owns is left out. It requires the persona's seat in the reviewer pool.
121
133
  export const reviewRequests = Effect.gen(function* () {
122
134
  const github = yield* GitHub;
123
135
  const me = yield* reviewerLogin;
124
- const found: Array<{ readonly pull: PullRequest; readonly reviewed: number }> = [];
136
+ const all = yield* Phases.records;
137
+ const found: Array<ReviewRequest> = [];
125
138
 
126
139
  for (const pull of yield* github.openPullRequests) {
127
140
  if (!pull.requestedReviewers.some((login) => sameLogin(login, me))) {
@@ -137,12 +150,159 @@ export const reviewRequests = Effect.gen(function* () {
137
150
  reviewed: (yield* github.reviews(pull.number)).filter((review) =>
138
151
  sameLogin(review.author, me),
139
152
  ).length,
153
+ record: Phases.recordOf(all, Phases.pullRequestItem(pull.number)),
140
154
  });
141
155
  }
142
156
 
143
157
  return found;
144
158
  });
145
159
 
160
+ // What a review request asks of this persona, by the pull request's phase:
161
+ // its first review (review's), a review again (re-review's), one whose
162
+ // record moves on to review-asked-again first, or a record GitHub disagrees
163
+ // with, which status shows rather than starting either.
164
+ type Asked =
165
+ | { readonly kind: "first" }
166
+ | { readonly kind: "again"; readonly record: Option.Option<PhaseRecord> }
167
+ | { readonly kind: "reconcile"; readonly record: PhaseRecord }
168
+ | { readonly kind: "disagrees"; readonly reason: string };
169
+
170
+ const P = Phases.PHASES.pullRequest;
171
+
172
+ // Today's inference, for a pull request with no record: see askedOf.
173
+ const legacyAsked = (request: ReviewRequest): Asked => {
174
+ if (request.reviewed === 0) {
175
+ return { kind: "first" };
176
+ }
177
+
178
+ return { kind: "again", record: Option.none() };
179
+ };
180
+
181
+ // A pull request with a record is read by its phase, not by how many times
182
+ // this persona reviewed it. Migration: one with no record, such as one
183
+ // handed off before phases were recorded, or one a person opened, falls back
184
+ // to the review count (legacyAsked). Drop the count a release after phases
185
+ // became the record, keeping "first" for an item with none.
186
+ const askedOf = (request: ReviewRequest, me: string): Asked =>
187
+ Option.match(request.record, {
188
+ onNone: () => legacyAsked(request),
189
+ onSome: (found): Asked => {
190
+ if (found.phase === P.reviewAskedAgain) {
191
+ return { kind: "again", record: Option.some(found) };
192
+ }
193
+
194
+ // Waiting on a first review, or a person's turn, then a review asked of
195
+ // this persona: its first, or, when it has reviewed already, again. An
196
+ // adopted pull request it reviewed before the hand-off is one.
197
+ if (
198
+ Phases.holds(found, [P.reviewAsked, P.draft, P.readyForPerson]) &&
199
+ request.reviewed === 0
200
+ ) {
201
+ return { kind: "first" };
202
+ }
203
+
204
+ if (
205
+ Phases.holds(found, [P.reviewAsked, P.changesAsked, P.approved, P.draft, P.readyForPerson])
206
+ ) {
207
+ return { kind: "reconcile", record: found };
208
+ }
209
+
210
+ return {
211
+ kind: "disagrees",
212
+ reason: `its record says ${found.phase}, but GitHub asks ${me} for a review`,
213
+ };
214
+ },
215
+ });
216
+
217
+ // review.requested's items: open pull requests that ask this persona for its
218
+ // first review, routed by their assignees and reviewers, as `pr-7`. One whose
219
+ // record GitHub disagrees with is held, with why, for status to show.
220
+ export const requestedFirst = Effect.gen(function* () {
221
+ const me = yield* reviewerLogin;
222
+ const items: Array<WorkItem> = [];
223
+
224
+ for (const request of yield* reviewRequests) {
225
+ const asked = askedOf(request, me);
226
+ const item = reviewItem(request.pull, `pr-${request.pull.number}`);
227
+
228
+ if (asked.kind === "first") {
229
+ items.push(yield* routed(request.pull, item));
230
+ }
231
+
232
+ if (asked.kind === "disagrees") {
233
+ items.push({ ...item, held: `#${request.pull.number}: ${asked.reason}` });
234
+ }
235
+ }
236
+
237
+ return items;
238
+ });
239
+
240
+ // Who moves a record from what a source reads on GitHub, outside any run.
241
+ const observer = (source: string) => `observer:${source}`;
242
+
243
+ // The key a request to review again runs under: the record it reads, or the
244
+ // one reconciling moves it to; the review count for a pull request with no
245
+ // record (askedOf). None for a request that isn't to review again, or whose
246
+ // record another writer moved elsewhere first.
247
+ const againKey = (request: ReviewRequest, asked: Asked) => {
248
+ const item = Phases.pullRequestItem(request.pull.number);
249
+
250
+ if (asked.kind === "again") {
251
+ return Effect.succeedSome(
252
+ Option.match(asked.record, {
253
+ onNone: () => `pr-${request.pull.number}-review-${request.reviewed + 1}`,
254
+ onSome: (found) => Phases.keyFor(item, found),
255
+ }),
256
+ );
257
+ }
258
+
259
+ if (asked.kind !== "reconcile") {
260
+ return Effect.succeedNone;
261
+ }
262
+
263
+ return Phases.reconcile(
264
+ item,
265
+ Option.some(asked.record),
266
+ P.reviewAskedAgain,
267
+ observer("review.requestedAgain"),
268
+ ).pipe(
269
+ Effect.map((found) =>
270
+ Option.map(
271
+ Option.filter(found, (record) => record.phase === P.reviewAskedAgain),
272
+ (record) => Phases.keyFor(item, record),
273
+ ),
274
+ ),
275
+ );
276
+ };
277
+
278
+ // review.requestedAgain's items: open pull requests that ask this persona to
279
+ // review again, unless a person has them (auto:needs-human), routed by their
280
+ // assignees and reviewers. Each item's key carries the record it reads,
281
+ // `pr-7-review-asked-again-1a2b3c4`, so each request is a run of its own. A
282
+ // review asked again of a pull request whose record says changes asked or
283
+ // approved, such as a person asking after a fix of their own, moves the record
284
+ // to review-asked-again first. One with no record keys by the review count,
285
+ // `pr-7-review-2`, as before phases.
286
+ export const requestedAgain = Effect.gen(function* () {
287
+ const labelNames = yield* Settings.labels;
288
+ const me = yield* reviewerLogin;
289
+ const items: Array<WorkItem> = [];
290
+
291
+ for (const request of yield* reviewRequests) {
292
+ if (request.pull.labels.includes(labelNames.needsHuman)) {
293
+ continue;
294
+ }
295
+
296
+ const key = yield* againKey(request, askedOf(request, me));
297
+
298
+ for (const found of Option.toArray(key)) {
299
+ items.push(yield* routed(request.pull, reviewItem(request.pull, found)));
300
+ }
301
+ }
302
+
303
+ return items;
304
+ });
305
+
146
306
  // Whether this machine acts as the login, among the logins it acts as.
147
307
  const actsAs = (here: ReadonlyArray<string>, login: string) =>
148
308
  here.some((own) => sameLogin(own, login));
@@ -425,6 +585,15 @@ const headingFor = (verdict: Verdict["verdict"], reviewer: string) => {
425
585
  return `Changes requested by ${reviewer}`;
426
586
  };
427
587
 
588
+ // The phase a review leaves its pull request in.
589
+ const phaseAfter = (verdict: Verdict["verdict"]): Phases.Phase => {
590
+ if (verdict === "approve") {
591
+ return Phases.PHASES.pullRequest.approved;
592
+ }
593
+
594
+ return Phases.PHASES.pullRequest.changesAsked;
595
+ };
596
+
428
597
  const eventOf = (verdict: Verdict["verdict"]): ReviewEvent => {
429
598
  if (verdict === "approve") {
430
599
  return "APPROVE";
@@ -448,6 +617,7 @@ const postReview = (pull: PullRequest, review: ReviewMarker, verdict: Verdict, h
448
617
  event,
449
618
  });
450
619
  yield* github.comment(pull.number, `${heading} at \`${pull.headSha.slice(0, 7)}\`. ${marker}`);
620
+ yield* Phases.record(Phases.pullRequestItem(pull.number), phaseAfter(verdict.verdict));
451
621
  });
452
622
 
453
623
  const reviewAndPost = (pullRequest: number, round: number, role: Option.Option<string>) =>
@@ -729,6 +899,149 @@ export type AddressItem = typeof AddressItem.Type;
729
899
 
730
900
  export const addressItemOf = itemData(AddressItem);
731
901
 
902
+ // The latest approval or request for changes, when it asks for changes on
903
+ // the pull request's head: nothing was pushed since.
904
+ const changesOnHead = (pull: PullRequest, decisive: ReadonlyArray<SubmittedReview>) =>
905
+ Option.filter(
906
+ Arr.last(decisive),
907
+ (review) => review.state === "CHANGES_REQUESTED" && review.commitSha === pull.headSha,
908
+ );
909
+
910
+ // Today's inference, for a pull request with no record: the latest decisive
911
+ // review asks for changes on the head, keyed by the count of decisive
912
+ // reviews. Migration: drop it a release after phases became the record.
913
+ const legacyChanges = (pull: PullRequest) =>
914
+ Effect.gen(function* () {
915
+ const decisive = yield* decisiveReviews(pull.number);
916
+ const latest = changesOnHead(pull, decisive);
917
+
918
+ if (Option.isNone(latest) || (yield* ownedByARun(pull))) {
919
+ return Option.none<WorkItem>();
920
+ }
921
+
922
+ return Option.some(addressItem(pull, latest.value, decisive.length));
923
+ });
924
+
925
+ // The phases a review that asks for changes on the head moves a pull request
926
+ // on from: a person's review, which no run was there to record.
927
+ const CHANGES_FROM = [P.reviewAsked, P.reviewAskedAgain, P.approved, P.draft, P.readyForPerson];
928
+
929
+ const shortSha = (sha: string) => sha.slice(0, 7);
930
+
931
+ // Why a pull request whose record says changes asked isn't one to address,
932
+ // by its latest approval or request for changes.
933
+ const changesDisagree = (pull: PullRequest, latest: Option.Option<SubmittedReview>) =>
934
+ Option.match(
935
+ Option.filter(latest, (review) => review.state === "CHANGES_REQUESTED"),
936
+ {
937
+ onNone: () =>
938
+ `#${pull.number}: its record says changes asked, but its latest review asks for none`,
939
+ onSome: (review) =>
940
+ `#${pull.number}: changes were asked at ${shortSha(review.commitSha)}, but its head has moved to ${shortSha(pull.headSha)} since; ask ${review.author} to review again`,
941
+ },
942
+ );
943
+
944
+ // The record a pull request with changes asked on its head holds: its own
945
+ // when it says so, or else the one reconciling it moves it to.
946
+ const changesAskedRecord = (item: string, found: PhaseRecord) => {
947
+ if (found.phase === P.changesAsked) {
948
+ return Effect.succeedSome(found);
949
+ }
950
+
951
+ return Phases.reconcile(
952
+ item,
953
+ Option.some(found),
954
+ P.changesAsked,
955
+ observer("review.changesRequested"),
956
+ );
957
+ };
958
+
959
+ // One pull request with a record, for changesToAddress: an item to address
960
+ // when its record says changes asked and the review it names is on the head;
961
+ // held, with why, when GitHub disagrees; moved to changes-asked first when a
962
+ // review asks for changes on the head of one in a phase before it.
963
+ const changesByRecord = (pull: PullRequest, found: PhaseRecord) =>
964
+ Effect.gen(function* () {
965
+ const item = Phases.pullRequestItem(pull.number);
966
+ const asks = found.phase === P.changesAsked;
967
+
968
+ if (!asks && !Phases.holds(found, [...CHANGES_FROM, P.mergeHeld])) {
969
+ return Option.none<WorkItem>();
970
+ }
971
+
972
+ const decisive = yield* decisiveReviews(pull.number);
973
+ const latest = changesOnHead(pull, decisive);
974
+
975
+ if ((!asks && Option.isNone(latest)) || (yield* ownedByARun(pull))) {
976
+ return Option.none<WorkItem>();
977
+ }
978
+
979
+ if (Option.isNone(latest)) {
980
+ return Option.some<WorkItem>({
981
+ ...reviewItem(pull, Phases.keyFor(item, found)),
982
+ held: changesDisagree(pull, Arr.last(decisive)),
983
+ });
984
+ }
985
+
986
+ if (found.phase === P.mergeHeld) {
987
+ return Option.some<WorkItem>({
988
+ ...reviewItem(pull, Phases.keyFor(item, found)),
989
+ held: `#${pull.number}: its merge is held for a green base, but ${latest.value.author} has asked for changes since`,
990
+ });
991
+ }
992
+
993
+ const now = Option.filter(
994
+ yield* changesAskedRecord(item, found),
995
+ (record) => record.phase === P.changesAsked,
996
+ );
997
+
998
+ return Option.map(now, (record) => ({
999
+ ...addressItem(pull, latest.value, decisive.length),
1000
+ key: Phases.keyFor(item, record),
1001
+ }));
1002
+ });
1003
+
1004
+ // A held item stays here, for status to show why; any other is routed.
1005
+ const routedUnlessHeld = (pull: PullRequest, item: WorkItem) => {
1006
+ if (Option.isSome(Option.fromUndefinedOr(item.held))) {
1007
+ return Effect.succeed(item);
1008
+ }
1009
+
1010
+ return routed(pull, item);
1011
+ };
1012
+
1013
+ // review.changesRequested's items: pull requests this persona wrote whose
1014
+ // record says changes asked, by the review that asks them, on the current
1015
+ // head, so nothing was pushed since. Each item's key carries the record,
1016
+ // `pr-7-changes-asked-1a2b3c4`. A person's review that asks for changes on
1017
+ // the head of one whose record is before it moves the record on first. One a
1018
+ // person has (auto:needs-human), or a run of another flow owns, is left
1019
+ // alone; one whose record GitHub disagrees with is held, with why, for status
1020
+ // to show. One with no record is read from its reviews (legacyChanges). Each
1021
+ // is routed by its assignees and reviewers.
1022
+ export const changesToAddress = Effect.gen(function* () {
1023
+ const labelNames = yield* Settings.labels;
1024
+ const all = yield* Phases.records;
1025
+ const items: Array<WorkItem> = [];
1026
+
1027
+ for (const pull of yield* authoredByMe) {
1028
+ if (pull.labels.includes(labelNames.needsHuman)) {
1029
+ continue;
1030
+ }
1031
+
1032
+ const found = yield* Option.match(Phases.recordOf(all, Phases.pullRequestItem(pull.number)), {
1033
+ onNone: () => legacyChanges(pull),
1034
+ onSome: (record) => changesByRecord(pull, record),
1035
+ });
1036
+
1037
+ for (const item of Option.toArray(found)) {
1038
+ items.push(yield* routedUnlessHeld(pull, item));
1039
+ }
1040
+ }
1041
+
1042
+ return items;
1043
+ });
1044
+
732
1045
  // The author's session, from the marker the implement run left; a fresh one
733
1046
  // for `purpose` if there is none. Outside an activity, for a block that reads
734
1047
  // it under a name of its own.
@@ -850,6 +1163,10 @@ export const requestAgain = (pullRequest: number, reviewer: string, said: string
850
1163
  const github = yield* GitHub;
851
1164
  yield* github.comment(pullRequest, said);
852
1165
  yield* github.requestReviewers(pullRequest, [reviewer]);
1166
+ yield* Phases.record(
1167
+ Phases.pullRequestItem(pullRequest),
1168
+ Phases.PHASES.pullRequest.reviewAskedAgain,
1169
+ );
853
1170
  });
854
1171
 
855
1172
  // Asks the reviewer who requested the changes to review again, which starts
@@ -859,3 +1176,28 @@ export const askAgain = (pullRequest: number, round: number, reviewer: string, s
859
1176
  `ask-again-${round}`,
860
1177
  requestAgain(pullRequest, reviewer, `Addressed review ${round}: ${summary}`),
861
1178
  );
1179
+
1180
+ // After resolve-conflicts merged the base in: when the pull request's latest
1181
+ // approval or request for changes is an approval, asks its reviewer to review
1182
+ // again, since they approved the code before the merge, and records
1183
+ // review-asked-again. The approver, or none, with no approval to ask again.
1184
+ export const askApproverAgain = (pullRequest: number) =>
1185
+ activity(
1186
+ "ask-approver-again",
1187
+ Effect.gen(function* () {
1188
+ const approval = Option.filter(
1189
+ Arr.last(yield* decisiveReviews(pullRequest)),
1190
+ (review) => review.state === "APPROVED",
1191
+ );
1192
+
1193
+ if (Option.isNone(approval)) {
1194
+ return Option.none<string>();
1195
+ }
1196
+
1197
+ yield* (yield* GitHub).requestReviewers(pullRequest, [approval.value.author]);
1198
+ yield* Phases.record(Phases.pullRequestItem(pullRequest), P.reviewAskedAgain);
1199
+
1200
+ return Option.some(approval.value.author);
1201
+ }),
1202
+ Schema.Option(Schema.String),
1203
+ );