@chernabog/sdk 0.3.1 → 0.6.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/review.ts CHANGED
@@ -1,303 +1,547 @@
1
- // The building blocks of the default `review` and `fix` flows. A review run
2
- // stays inside one workflow: after each review it waits on whichever comes
3
- // first, the author's push or the staleness timeout. It ends when the pull
4
- // request closes, the timeout labels it stale, or the loop cap hands it to a
5
- // person. The fix flow is the author, for pull requests an agent wrote: it
6
- // resumes the session that implemented them, addresses the review and pushes.
7
-
8
- import * as Effect from 'effect/Effect';
9
- import * as Option from 'effect/Option';
10
- import * as Record from 'effect/Record';
11
- import * as Schema from 'effect/Schema';
12
-
13
- import { NeedsHuman, StepFailed } from './errors.ts';
14
- import { activity, awaitSignal } from './flow.ts';
15
- import { fixWithAgent, push, sessionIdFor, waitForCi } from './implement.ts';
16
- import type { Json } from './json.ts';
17
- import { latestMarker, reviewMarker, SessionMarker, sessionMarker } from './markers.ts';
18
- import { renderPrompt } from './prompt.ts';
19
- import { Agent, Git, GitHub, type PullRequest, Repo, type ReviewNote, Run, type WorkItem, Worktree } from './services.ts';
20
-
21
- export { type ReviewMarker, reviewMarker, type SessionMarker, sessionMarker } from './markers.ts';
1
+ // The building blocks of the `review`, `re-review` and `address-review`
2
+ // recipes, which work through GitHub's own review requests: a pull request asks one reviewer
3
+ // from the team's pool once its CI is green (Implement.handOff), `review` runs
4
+ // as a persona whose review is requested on a pull request it hasn't reviewed,
5
+ // and `re-review` as one asked again, resuming its own review session. On the
6
+ // automated path (auto:ship), the approving reviewer merges, when that's safe.
7
+ // `address-review` is the author's side: it answers a review that asks for
8
+ // changes in the session that wrote the code, and asks the reviewer again.
9
+
10
+ import * as Effect from "effect/Effect";
11
+ import * as Option from "effect/Option";
12
+ import * as Schema from "effect/Schema";
13
+
14
+ import { RECHECK } from "./default-prompts.ts";
15
+ import { NeedsHuman, StepFailed } from "./errors.ts";
16
+ import { activity } from "./flow.ts";
17
+ import { sessionIdFor } from "./implement.ts";
18
+ import type { Json } from "./json.ts";
19
+ import {
20
+ latestMarker,
21
+ type ReviewMarker,
22
+ reviewMarker,
23
+ SessionMarker,
24
+ sessionMarker,
25
+ } from "./markers.ts";
26
+ import { renderPrompt, renderPromptOr } from "./prompt.ts";
27
+ import * as PullRequestSteps from "./pull-request.ts";
28
+ import { adapterFor, type RoleOptions } from "./roles.ts";
29
+ import {
30
+ Agent,
31
+ Git,
32
+ GitHub,
33
+ type PullRequest,
34
+ Repo,
35
+ ReviewerSeat,
36
+ type ReviewEvent,
37
+ type ReviewNote,
38
+ Run,
39
+ type SubmittedReview,
40
+ type WorkItem,
41
+ Worktree,
42
+ } from "./services.ts";
43
+
44
+ export { type ReviewMarker, reviewMarker, type SessionMarker, sessionMarker } from "./markers.ts";
22
45
 
23
46
  // Agent-written pull requests come from claim branches.
24
- export const isAgentBranch = (branch: string) => branch.startsWith('auto/');
47
+ export const isAgentBranch = (branch: string) => branch.startsWith("auto/");
25
48
 
26
- export const ReviewItem = Schema.Struct({ pullRequest: Schema.Finite, headRef: Schema.String, agentWritten: Schema.Boolean });
49
+ export const ReviewItem = Schema.Struct({
50
+ pullRequest: Schema.Finite,
51
+ headRef: Schema.String,
52
+ agentWritten: Schema.Boolean,
53
+ });
27
54
 
28
55
  export type ReviewItem = typeof ReviewItem.Type;
29
56
 
30
- export const FixItem = Schema.Struct({ ...ReviewItem.fields, round: Schema.Finite, reviewedSha: Schema.String });
31
-
32
- export type FixItem = typeof FixItem.Type;
33
-
34
57
  const itemData =
35
58
  <A>(schema: Schema.Codec<A, Json>) =>
36
59
  (item: WorkItem) =>
37
- Schema.decodeEffect(schema)(item.data).pipe(Effect.mapError((issue) => new StepFailed({ step: 'work item', message: `${item.key}: ${issue.message}` })));
60
+ Schema.decodeEffect(schema)(item.data).pipe(
61
+ Effect.mapError(
62
+ (issue) => new StepFailed({ step: "work item", message: `${item.key}: ${issue.message}` }),
63
+ ),
64
+ );
38
65
 
39
66
  export const pullRequestOf = itemData(ReviewItem);
40
- const fixItemOf = itemData(FixItem);
41
67
 
42
- const reviewItem = (pull: PullRequest): WorkItem => ({
43
- key: `pr-${pull.number}`,
68
+ // A pull request as a work item, keyed by `key`, for a trigger to report.
69
+ export const reviewItem = (pull: PullRequest, key: string): WorkItem => ({
70
+ key,
44
71
  title: pull.title,
45
72
  url: pull.url,
46
- data: { pullRequest: pull.number, headRef: pull.headRef, agentWritten: isAgentBranch(pull.headRef) },
73
+ data: {
74
+ pullRequest: pull.number,
75
+ headRef: pull.headRef,
76
+ agentWritten: isAgentBranch(pull.headRef),
77
+ },
47
78
  assignees: pull.assignees,
48
79
  reviewers: pull.requestedReviewers,
49
80
  });
50
81
 
51
- // The head the latest review saw.
52
- const reviewedSha = (pull: PullRequest) =>
82
+ const commentBodies = (pull: PullRequest) =>
53
83
  GitHub.use((github) => github.comments(pull.number)).pipe(
54
- Effect.map((comments) =>
55
- latestMarker(
56
- reviewMarker.read,
57
- comments.map((comment) => comment.body),
58
- ).pipe(Option.map((marker) => marker.sha)),
59
- ),
84
+ Effect.map((comments) => comments.map((comment) => comment.body)),
60
85
  );
61
86
 
62
- const changedSinceReview = (pull: PullRequest) => reviewedSha(pull).pipe(Effect.map(Option.exists((sha) => sha !== pull.headSha)));
87
+ // Whether a run of another flow owns the pull request; the standalone flows leave it alone.
88
+ const ownedByARunOf = (bodies: ReadonlyArray<string>) =>
89
+ PullRequestSteps.ownerOf(bodies).pipe(Effect.map(Option.isSome));
63
90
 
64
- // Pull requests to review, and the signals that wake reviews already waiting:
65
- // "pushed" when a pull request changed since its last review (for one an agent
66
- // wrote, once the fix flow handed it back), "closed" when it merged or closed.
67
- export const trigger = Effect.gen(function* () {
68
- const github = yield* GitHub;
69
- const repo = yield* Repo;
70
- const items: Array<WorkItem> = [];
91
+ export const ownedByARun = (pull: PullRequest) =>
92
+ commentBodies(pull).pipe(Effect.flatMap(ownedByARunOf));
71
93
 
72
- for (const pull of yield* github.pullRequestsLabelled(repo.labels.needsReview)) {
73
- const item = reviewItem(pull);
94
+ const sameLogin = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
74
95
 
75
- if (yield* changedSinceReview(pull)) items.push({ ...item, signals: ['pushed'] });
76
- else items.push(item);
77
- }
96
+ // The login this persona reviews as, from its seat in the reviewer pool. A
97
+ // flow that uses it, or any block that reviews, requires ReviewerSeat.
98
+ export const reviewerLogin = ReviewerSeat.use((seat) => seat.login);
78
99
 
79
- for (const pull of yield* github.pullRequestsLabelled(repo.labels.changesRequested)) {
80
- if (!isAgentBranch(pull.headRef) && (yield* changedSinceReview(pull))) items.push({ ...reviewItem(pull), signals: ['pushed'], wakeOnly: true });
81
- }
100
+ // Open pull requests that ask this persona for a review, each with how many
101
+ // reviews it has submitted on it so far. One a run of another flow owns is
102
+ // left out. It requires the persona's seat in the reviewer pool.
103
+ export const reviewRequests = Effect.gen(function* () {
104
+ const github = yield* GitHub;
105
+ const me = yield* reviewerLogin;
106
+ const found: Array<{ readonly pull: PullRequest; readonly reviewed: number }> = [];
82
107
 
83
- for (const label of [repo.labels.changesRequested, repo.labels.approved, repo.labels.needsReview]) {
84
- for (const pull of yield* github.closedPullRequestsLabelled(label)) items.push({ ...reviewItem(pull), signals: ['closed'], wakeOnly: true });
108
+ for (const pull of yield* github.openPullRequests) {
109
+ if (!pull.requestedReviewers.some((login) => sameLogin(login, me))) {
110
+ continue;
111
+ }
112
+
113
+ if (yield* ownedByARun(pull)) {
114
+ continue;
115
+ }
116
+
117
+ found.push({
118
+ pull,
119
+ reviewed: (yield* github.reviews(pull.number)).filter((review) =>
120
+ sameLogin(review.author, me),
121
+ ).length,
122
+ });
85
123
  }
86
124
 
87
- return items;
125
+ return found;
88
126
  });
89
127
 
90
128
  export const Verdict = Schema.Struct({
91
- verdict: Schema.Literals(['approve', 'request-changes']),
129
+ verdict: Schema.Literals(["approve", "request-changes"]),
92
130
  summary: Schema.String,
93
- comments: Schema.Array(Schema.Struct({ path: Schema.String, line: Schema.Finite, body: Schema.String })),
131
+ comments: Schema.Array(
132
+ Schema.Struct({ path: Schema.String, line: Schema.Finite, body: Schema.String }),
133
+ ),
94
134
  });
95
135
 
96
136
  export type Verdict = typeof Verdict.Type;
97
137
 
98
138
  export const verdictJsonSchema = {
99
- type: 'object',
139
+ type: "object",
100
140
  properties: {
101
- verdict: { type: 'string', enum: ['approve', 'request-changes'] },
102
- summary: { type: 'string', description: 'The review: what is right, what must change and why, in Markdown' },
141
+ verdict: { type: "string", enum: ["approve", "request-changes"] },
142
+ summary: {
143
+ type: "string",
144
+ description: "The review: what is right, what must change and why, in Markdown",
145
+ },
103
146
  comments: {
104
- type: 'array',
105
- description: 'Comments on lines the pull request changed',
147
+ type: "array",
148
+ description: "Comments on lines the pull request changed",
106
149
  items: {
107
- type: 'object',
108
- properties: { path: { type: 'string' }, line: { type: 'number' }, body: { type: 'string' } },
109
- required: ['path', 'line', 'body'],
150
+ type: "object",
151
+ properties: {
152
+ path: { type: "string" },
153
+ line: { type: "number" },
154
+ body: { type: "string" },
155
+ },
156
+ required: ["path", "line", "body"],
110
157
  additionalProperties: false,
111
158
  },
112
159
  },
113
160
  },
114
- required: ['verdict', 'summary', 'comments'],
161
+ required: ["verdict", "summary", "comments"],
115
162
  additionalProperties: false,
116
163
  } satisfies Json;
117
164
 
118
- const ReviewResult = Schema.Struct({ verdict: Schema.Literals(['approve', 'request-changes']), sha: Schema.String });
165
+ const ReviewComments = Schema.Array(
166
+ Schema.Struct({ path: Schema.String, line: Schema.Finite, body: Schema.String }),
167
+ );
168
+
169
+ // A posted review: its verdict and the head it saw, and, from Review.round and
170
+ // Review.recheck, what it said and the session to resume it in. Those are
171
+ // optional only so that results saved before they existed still read back.
172
+ export const ReviewResult = Schema.Struct({
173
+ verdict: Schema.Literals(["approve", "request-changes"]),
174
+ sha: Schema.String,
175
+ round: Schema.optionalKey(Schema.Finite),
176
+ summary: Schema.optionalKey(Schema.String),
177
+ comments: Schema.optionalKey(ReviewComments),
178
+ sessionId: Schema.optionalKey(Schema.String),
179
+ adapter: Schema.optionalKey(Schema.String),
180
+ });
181
+
182
+ export type ReviewResult = typeof ReviewResult.Type;
119
183
 
120
- const withoutMarkers = (body: string) => body.replace(/<!--.*?-->/gs, '').trim();
184
+ // What a re-check found of each earlier finding.
185
+ export const Finding = Schema.Struct({ finding: Schema.String, remediated: Schema.Boolean });
186
+
187
+ export type Finding = typeof Finding.Type;
188
+
189
+ export const RecheckResult = Schema.Struct({
190
+ ...ReviewResult.fields,
191
+ findings: Schema.Array(Finding),
192
+ });
193
+
194
+ export type RecheckResult = typeof RecheckResult.Type;
195
+
196
+ const RecheckVerdict = Schema.Struct({ ...Verdict.fields, findings: Schema.Array(Finding) });
197
+
198
+ export const recheckJsonSchema = {
199
+ ...verdictJsonSchema,
200
+ properties: {
201
+ ...verdictJsonSchema.properties,
202
+ findings: {
203
+ type: "array",
204
+ description: "Each finding of the earlier review, and whether the new code remediates it",
205
+ items: {
206
+ type: "object",
207
+ properties: { finding: { type: "string" }, remediated: { type: "boolean" } },
208
+ required: ["finding", "remediated"],
209
+ additionalProperties: false,
210
+ },
211
+ },
212
+ },
213
+ required: [...verdictJsonSchema.required, "findings"],
214
+ } satisfies Json;
215
+
216
+ // Cuts out each <!-- … --> and looks again from the start, so a marker nested
217
+ // in another can't survive the outer one's removal. An unclosed one hides the
218
+ // rest of the body, as it would in the rendered comment.
219
+ const withoutMarkers = (body: string): string => {
220
+ const start = body.indexOf("<!--");
221
+
222
+ if (start === -1) {
223
+ return body.trim();
224
+ }
225
+
226
+ const end = body.indexOf("-->", start + "<!--".length);
227
+
228
+ if (end === -1) {
229
+ return body.slice(0, start).trim();
230
+ }
231
+
232
+ return withoutMarkers(body.slice(0, start) + body.slice(end + "-->".length));
233
+ };
121
234
 
122
235
  const describeNote = (note: ReviewNote) =>
123
236
  Option.match(note.location, {
124
237
  onNone: () => `${note.author}: ${withoutMarkers(note.body)}`,
125
- onSome: (location) => `${note.author} on ${location.path}:${location.line}: ${withoutMarkers(note.body)}`,
238
+ onSome: (location) =>
239
+ `${note.author} on ${location.path}:${location.line}: ${withoutMarkers(note.body)}`,
126
240
  });
127
241
 
128
- const headingFor = (verdict: Verdict['verdict'], reviewer: string) => {
129
- if (verdict === 'approve') return `Approved by ${reviewer}`;
242
+ const headingFor = (verdict: Verdict["verdict"], reviewer: string) => {
243
+ if (verdict === "approve") {
244
+ return `Approved by ${reviewer}`;
245
+ }
130
246
 
131
247
  return `Changes requested by ${reviewer}`;
132
248
  };
133
249
 
134
- // One review of the pull request's current head, in a detached worktree, by the
135
- // flow's agent (flows.review.agent) in a fresh session that is given the earlier
136
- // reviews. Posts it and moves the labels.
137
- export const reviewRound = (pullRequest: number, round: number) =>
250
+ const eventOf = (verdict: Verdict["verdict"]): ReviewEvent => {
251
+ if (verdict === "approve") {
252
+ return "APPROVE";
253
+ }
254
+
255
+ return "REQUEST_CHANGES";
256
+ };
257
+
258
+ // Posts a review of the head with its marker: as a real review, approving or
259
+ // requesting changes, and as a plain comment, which later runs read back. The
260
+ // marker records who reviewed in which session, so a re-review resumes it.
261
+ const postReview = (pull: PullRequest, review: ReviewMarker, verdict: Verdict, heading: string) =>
262
+ Effect.gen(function* () {
263
+ const github = yield* GitHub;
264
+ const marker = reviewMarker.write(review);
265
+ const event = eventOf(verdict.verdict);
266
+ yield* github.review(pull.number, {
267
+ body: `**${heading}** (review ${review.round})\n\n${verdict.summary}\n\n${marker}`,
268
+ commitSha: pull.headSha,
269
+ comments: verdict.comments,
270
+ event,
271
+ });
272
+ yield* github.comment(pull.number, `${heading} at \`${pull.headSha.slice(0, 7)}\`. ${marker}`);
273
+ });
274
+
275
+ const reviewAndPost = (pullRequest: number, round: number, role: Option.Option<string>) =>
276
+ Effect.gen(function* () {
277
+ const github = yield* GitHub;
278
+ const repo = yield* Repo;
279
+ const run = yield* Run;
280
+ const pull = yield* github.pullRequest(pullRequest);
281
+
282
+ const worktree = yield* (yield* Worktree).checkout(
283
+ `review-pr-${pullRequest}`,
284
+ `origin/${pull.headRef}`,
285
+ );
286
+
287
+ const earlier = (yield* github.reviewComments(pullRequest)).filter((note) => note.trusted);
288
+
289
+ const prompt = yield* renderPrompt("review", {
290
+ repo: repo.slug,
291
+ pullRequest,
292
+ title: pull.title,
293
+ body: pull.body,
294
+ base: pull.baseRef,
295
+ round,
296
+ earlier: earlier.map(describeNote),
297
+ humanOnly: repo.humanOnly,
298
+ notes: repo.notes,
299
+ });
300
+
301
+ const adapter = yield* adapterFor(role);
302
+ const sessionId = sessionIdFor(run.runId, `review-${round}`);
303
+
304
+ const result = yield* (yield* Agent).run({
305
+ cwd: worktree,
306
+ prompt,
307
+ sessionId,
308
+ resumePrompt: Option.none(),
309
+ outputSchema: Option.some(verdictJsonSchema),
310
+ adapter,
311
+ });
312
+
313
+ const verdict = yield* Schema.decodeUnknownEffect(Verdict)(result.output).pipe(
314
+ Effect.mapError(
315
+ (issue) =>
316
+ new StepFailed({ step: `review-${round}`, message: `reviewer answer: ${issue.message}` }),
317
+ ),
318
+ );
319
+
320
+ const by = Option.getOrElse(adapter, () => repo.agent);
321
+ const me = yield* reviewerLogin;
322
+ yield* postReview(
323
+ pull,
324
+ { sha: pull.headSha, round, verdict: verdict.verdict, reviewer: me, sessionId, adapter: by },
325
+ verdict,
326
+ headingFor(verdict.verdict, by),
327
+ );
328
+
329
+ return {
330
+ verdict: verdict.verdict,
331
+ sha: pull.headSha,
332
+ round,
333
+ summary: verdict.summary,
334
+ comments: verdict.comments,
335
+ sessionId,
336
+ adapter: by,
337
+ };
338
+ });
339
+
340
+ // One review of the pull request's current head, in a detached worktree, in a
341
+ // fresh session that is given the earlier reviews. The reviewer is the role's
342
+ // adapter (the persona's roles pick, or flows.<flow>.agents), else the flow's
343
+ // agent (flows.<flow>.agent). Posts it as a real review.
344
+ const reviewOnly = (pullRequest: number, round: number, options: RoleOptions = {}) =>
138
345
  activity(
346
+ `review-${round}`,
347
+ reviewAndPost(pullRequest, round, Option.fromUndefinedOr(options.role)),
348
+ ReviewResult,
349
+ );
350
+
351
+ export { reviewOnly as round };
352
+
353
+ // Resumes the reviewer's session from `review` with the change since the head
354
+ // it saw, and posts what it finds as the next review: a verdict, and whether
355
+ // each finding of `review` is remediated. Its prompt is
356
+ // .chernabog/prompts/recheck.md, or the SDK's own.
357
+ export const recheck = (pullRequest: number, review: ReviewResult) => {
358
+ const round = (review.round ?? 1) + 1;
359
+
360
+ return activity(
139
361
  `review-${round}`,
140
362
  Effect.gen(function* () {
141
363
  const github = yield* GitHub;
142
364
  const repo = yield* Repo;
143
- const run = yield* Run;
365
+
366
+ const sessionId = Option.fromUndefinedOr(review.sessionId);
367
+
368
+ if (Option.isNone(sessionId)) {
369
+ return yield* new StepFailed({
370
+ step: `review-${round}`,
371
+ message:
372
+ "the review carries no session to resume; re-check a review from Review.round or Review.recheck",
373
+ });
374
+ }
375
+
144
376
  const pull = yield* github.pullRequest(pullRequest);
145
- const worktree = yield* (yield* Worktree).checkout(`review-pr-${pullRequest}`, `origin/${pull.headRef}`);
146
- const earlier = (yield* github.reviewComments(pullRequest)).filter((note) => note.trusted);
147
377
 
148
- const prompt = yield* renderPrompt('review', {
149
- repo: repo.slug,
378
+ const worktree = yield* (yield* Worktree).checkout(
379
+ `review-pr-${pullRequest}`,
380
+ `origin/${pull.headRef}`,
381
+ );
382
+
383
+ const prompt = yield* renderPromptOr("recheck", RECHECK, {
150
384
  pullRequest,
151
- title: pull.title,
152
- body: pull.body,
153
- base: pull.baseRef,
154
- round,
155
- earlier: earlier.map(describeNote),
156
- humanOnly: repo.humanOnly,
157
- notes: repo.notes,
385
+ round: round - 1,
386
+ reviewedSha: review.sha,
387
+ headSha: pull.headSha,
158
388
  });
159
389
 
160
- const adapter = Record.get(repo.flowAgents, run.flow);
390
+ const adapter = Option.fromUndefinedOr(review.adapter);
161
391
 
162
392
  const result = yield* (yield* Agent).run({
163
393
  cwd: worktree,
164
394
  prompt,
165
- sessionId: sessionIdFor(run.runId, `review-${round}`),
166
- resumePrompt: Option.none(),
167
- outputSchema: Option.some(verdictJsonSchema),
395
+ sessionId: sessionId.value,
396
+ resumePrompt: Option.some(prompt),
397
+ outputSchema: Option.some(recheckJsonSchema),
168
398
  adapter,
169
399
  });
170
400
 
171
- const verdict = yield* Schema.decodeUnknownEffect(Verdict)(result.output).pipe(
172
- Effect.mapError((issue) => new StepFailed({ step: `review-${round}`, message: `reviewer answer: ${issue.message}` })),
401
+ const verdict = yield* Schema.decodeUnknownEffect(RecheckVerdict)(result.output).pipe(
402
+ Effect.mapError(
403
+ (issue) =>
404
+ new StepFailed({
405
+ step: `review-${round}`,
406
+ message: `reviewer answer: ${issue.message}`,
407
+ }),
408
+ ),
173
409
  );
174
410
 
175
- const heading = headingFor(verdict.verdict, Option.getOrElse(adapter, () => repo.agent));
176
- const marker = reviewMarker.write({ sha: pull.headSha, round, verdict: verdict.verdict });
177
- yield* github.review(pullRequest, { body: `**${heading}** (review ${round})\n\n${verdict.summary}\n\n${marker}`, commitSha: pull.headSha, comments: verdict.comments });
178
- // The marker also goes in a plain comment, which the trigger reads back.
179
- yield* github.comment(pullRequest, `${heading} at \`${pull.headSha.slice(0, 7)}\`. ${marker}`);
180
- yield* github.removeLabel(pullRequest, repo.labels.needsReview);
181
-
182
- if (verdict.verdict === 'approve') yield* github.addLabel(pullRequest, repo.labels.approved);
183
- else yield* github.addLabel(pullRequest, repo.labels.changesRequested);
411
+ const by = Option.getOrElse(adapter, () => repo.agent);
412
+ const me = yield* reviewerLogin;
413
+ yield* postReview(
414
+ pull,
415
+ {
416
+ sha: pull.headSha,
417
+ round,
418
+ verdict: verdict.verdict,
419
+ reviewer: me,
420
+ sessionId: sessionId.value,
421
+ adapter: by,
422
+ },
423
+ verdict,
424
+ headingFor(verdict.verdict, by),
425
+ );
184
426
 
185
- return { verdict: verdict.verdict, sha: pull.headSha };
427
+ return {
428
+ verdict: verdict.verdict,
429
+ sha: pull.headSha,
430
+ round,
431
+ summary: verdict.summary,
432
+ comments: verdict.comments,
433
+ sessionId: sessionId.value,
434
+ adapter: by,
435
+ findings: verdict.findings,
436
+ };
186
437
  }),
187
- ReviewResult,
438
+ RecheckResult,
188
439
  );
440
+ };
189
441
 
190
- // Moves a pull request from some labels to another, saying why when there is something to say.
191
- type Relabel = { readonly remove: ReadonlyArray<string>; readonly add: string; readonly comment: Option.Option<string> };
192
-
193
- const relabel = (name: string, pullRequest: number, change: Relabel) =>
442
+ // Removes the review's checkout of the pull request, once the run is done
443
+ // with it; a re-review checks it out again. Review.round and Review.recheck
444
+ // leave it, for a flow of your own to remove when it's done.
445
+ export const doneReviewing = (pullRequest: number) =>
194
446
  activity(
195
- name,
196
- Effect.gen(function* () {
197
- const github = yield* GitHub;
198
-
199
- for (const label of change.remove) yield* github.removeLabel(pullRequest, label);
200
-
201
- yield* github.addLabel(pullRequest, change.add);
202
-
203
- if (Option.isSome(change.comment)) yield* github.comment(pullRequest, change.comment.value);
204
- }),
447
+ `clean-up-review-pr-${pullRequest}`,
448
+ Worktree.use((worktree) => worktree.remove(`review-pr-${pullRequest}`)),
205
449
  );
206
450
 
207
- // Removes the worktrees of a pull request that merged or closed: the branch's own and the review's.
208
- export const cleanUp = (pullRequest: number, headRef: string) =>
451
+ // This persona's latest review of the pull request, as its marker recorded
452
+ // it, to resume: none when it has none, or one posted before markers named
453
+ // their reviewer.
454
+ export const latestOwnReview = (pullRequest: number) =>
209
455
  activity(
210
- 'clean-up',
456
+ "find-review",
211
457
  Effect.gen(function* () {
212
- const worktree = yield* Worktree;
213
- yield* worktree.remove(`review-pr-${pullRequest}`);
214
- yield* worktree.remove(headRef);
458
+ const github = yield* GitHub;
459
+ const me = yield* reviewerLogin;
460
+ const bodies = (yield* github.comments(pullRequest)).map((comment) => comment.body);
461
+
462
+ const mine = latestMarker(
463
+ (body) =>
464
+ Option.filter(reviewMarker.read(body), (marker) =>
465
+ Option.exists(Option.fromUndefinedOr(marker.reviewer), (reviewer) =>
466
+ sameLogin(reviewer, me),
467
+ ),
468
+ ),
469
+ bodies,
470
+ );
215
471
 
216
- return `#${pullRequest} closed; worktrees removed`;
472
+ return Option.match(mine, {
473
+ onNone: () => Option.none<ReviewResult>(),
474
+ onSome: (marker) =>
475
+ Option.some<ReviewResult>({
476
+ verdict: marker.verdict,
477
+ sha: marker.sha,
478
+ round: marker.round,
479
+ ...Option.match(Option.fromUndefinedOr(marker.sessionId), {
480
+ onNone: () => ({}),
481
+ onSome: (sessionId) => ({ sessionId }),
482
+ }),
483
+ ...Option.match(Option.fromUndefinedOr(marker.adapter), {
484
+ onNone: () => ({}),
485
+ onSome: (adapter) => ({ adapter }),
486
+ }),
487
+ }),
488
+ });
217
489
  }),
218
- Schema.String,
490
+ Schema.Option(ReviewResult),
219
491
  );
220
492
 
221
- // How long an approved pull request's worktrees wait for it to merge before the run lets go.
222
- const APPROVED_WAIT = '14 days';
223
-
224
- const afterApproval = (pullRequest: number, headRef: string) =>
225
- Effect.gen(function* () {
226
- const closed = yield* awaitSignal(['closed'], { id: 'approved', timeout: APPROVED_WAIT });
227
-
228
- if (closed === 'closed') return yield* cleanUp(pullRequest, headRef);
229
-
230
- return `#${pullRequest} approved; a person merges`;
231
- });
232
-
233
- export const workflow = (item: WorkItem) =>
234
- Effect.gen(function* () {
235
- const repo = yield* Repo;
236
- const { headRef, pullRequest } = yield* pullRequestOf(item);
237
-
238
- for (let round = 1; ; round++) {
239
- const { verdict } = yield* reviewRound(pullRequest, round);
240
-
241
- if (verdict === 'approve') return yield* afterApproval(pullRequest, headRef);
242
-
243
- if (round >= repo.limits.reviewRounds) {
244
- yield* relabel('needs-human', pullRequest, {
245
- remove: [repo.labels.changesRequested],
246
- add: repo.labels.needsHuman,
247
- comment: Option.some(`Still changes requested after ${round} reviews, so a person takes it from here.`),
248
- });
249
-
250
- return yield* new NeedsHuman({ reason: `#${pullRequest}: still changes requested after ${round} reviews` });
251
- }
252
-
253
- const woke = yield* awaitSignal(['pushed', 'closed'], { id: `round-${round}`, timeout: repo.limits.staleAfter });
254
-
255
- if (woke === 'closed') return yield* cleanUp(pullRequest, headRef);
256
-
257
- if (woke === 'timeout') {
258
- yield* relabel(`stale-${round}`, pullRequest, {
259
- remove: [repo.labels.changesRequested],
260
- add: repo.labels.stale,
261
- comment: Option.some('No push since the last review, so this is marked stale.'),
262
- });
493
+ // Open pull requests this persona wrote.
494
+ export const authoredByMe = Effect.gen(function* () {
495
+ const github = yield* GitHub;
496
+ const me = yield* github.login;
263
497
 
264
- return `#${pullRequest} went stale waiting for a push`;
265
- }
498
+ return (yield* github.openPullRequests).filter((pull) => sameLogin(pull.author, me));
499
+ });
266
500
 
267
- yield* relabel(`re-review-${round}`, pullRequest, { remove: [repo.labels.changesRequested], add: repo.labels.needsReview, comment: Option.none() });
268
- }
269
- });
501
+ // The pull request's approvals and requests for changes, oldest first; comments don't count.
502
+ export const decisiveReviews = (pullRequest: number) =>
503
+ GitHub.use((github) => github.reviews(pullRequest)).pipe(
504
+ Effect.map((reviews) =>
505
+ reviews.filter(
506
+ (review) => review.state === "APPROVED" || review.state === "CHANGES_REQUESTED",
507
+ ),
508
+ ),
509
+ );
270
510
 
271
- // The fix flow's work items: agent-written pull requests with changes requested
272
- // and no push since, one per review that asked.
273
- export const fixTrigger = Effect.gen(function* () {
274
- const github = yield* GitHub;
275
- const repo = yield* Repo;
276
- const items: Array<WorkItem> = [];
511
+ // address-review's work item for a review that asks for changes, the
512
+ // `count`th decisive review of the pull request.
513
+ export const addressItem = (
514
+ pull: PullRequest,
515
+ review: SubmittedReview,
516
+ count: number,
517
+ ): WorkItem => ({
518
+ key: `pr-${pull.number}-changes-${count}`,
519
+ title: pull.title,
520
+ url: pull.url,
521
+ data: {
522
+ pullRequest: pull.number,
523
+ headRef: pull.headRef,
524
+ agentWritten: isAgentBranch(pull.headRef),
525
+ reviewer: review.author,
526
+ reviewedSha: review.commitSha,
527
+ },
528
+ assignees: pull.assignees,
529
+ });
277
530
 
278
- for (const pull of yield* github.pullRequestsLabelled(repo.labels.changesRequested)) {
279
- const reviewed = latestMarker(
280
- reviewMarker.read,
281
- (yield* github.comments(pull.number)).map((comment) => comment.body),
282
- );
531
+ export const AddressItem = Schema.Struct({
532
+ ...ReviewItem.fields,
533
+ reviewer: Schema.String,
534
+ reviewedSha: Schema.String,
535
+ });
283
536
 
284
- if (isAgentBranch(pull.headRef) && Option.isSome(reviewed) && reviewed.value.sha === pull.headSha) {
285
- items.push({
286
- key: `pr-${pull.number}-review-${reviewed.value.round}`,
287
- title: pull.title,
288
- url: pull.url,
289
- data: { pullRequest: pull.number, headRef: pull.headRef, agentWritten: true, round: reviewed.value.round, reviewedSha: reviewed.value.sha },
290
- });
291
- }
292
- }
537
+ export type AddressItem = typeof AddressItem.Type;
293
538
 
294
- return items;
295
- });
539
+ export const addressItemOf = itemData(AddressItem);
296
540
 
297
541
  // The author's session, from the marker the implement run left; a fresh one if there is none.
298
- const authorSession = (pullRequest: number) =>
542
+ export const authorSession = (pullRequest: number) =>
299
543
  activity(
300
- 'find-author',
544
+ "find-author",
301
545
  Effect.gen(function* () {
302
546
  const github = yield* GitHub;
303
547
  const run = yield* Run;
@@ -308,14 +552,20 @@ const authorSession = (pullRequest: number) =>
308
552
  (yield* github.comments(pullRequest)).map((comment) => comment.body),
309
553
  );
310
554
 
311
- return Option.getOrElse(found, () => ({ adapter: repo.agent, sessionId: sessionIdFor(run.runId, 'fix'), issue: 0, branch: '' }));
555
+ return Option.getOrElse(found, () => ({
556
+ adapter: repo.agent,
557
+ sessionId: sessionIdFor(run.runId, "address-review"),
558
+ issue: 0,
559
+ branch: "",
560
+ }));
312
561
  }),
313
562
  SessionMarker,
314
563
  );
315
564
 
316
- const prepareFix = (headRef: string) =>
565
+ // The author's worktree on the pull request's branch, brought up to date.
566
+ export const prepareAuthorWorktree = (headRef: string) =>
317
567
  activity(
318
- 'prepare-worktree',
568
+ "prepare-worktree",
319
569
  Effect.gen(function* () {
320
570
  const path = yield* (yield* Worktree).ensure(headRef);
321
571
  yield* (yield* Git).pull(path, headRef);
@@ -331,70 +581,66 @@ const describeReviewLine = (note: ReviewNote) =>
331
581
  onSome: (location) => `${location.path}:${location.line}: ${withoutMarkers(note.body)}`,
332
582
  });
333
583
 
334
- const readReview = (fix: FixItem) =>
584
+ // The review that asks for changes, as the author considers it: its round,
585
+ // from the reviewer's marker, and what the reviewer said.
586
+ export const changesAsked = (address: AddressItem) =>
335
587
  activity(
336
- 'read-review',
588
+ "read-review",
337
589
  Effect.gen(function* () {
338
- const notes = (yield* (yield* GitHub).reviewComments(fix.pullRequest)).filter((note) => note.trusted);
590
+ const github = yield* GitHub;
591
+ const bodies = (yield* github.comments(address.pullRequest)).map((comment) => comment.body);
592
+
593
+ const marker = latestMarker(
594
+ (body) =>
595
+ Option.filter(reviewMarker.read(body), (found) => found.sha === address.reviewedSha),
596
+ bodies,
597
+ );
339
598
 
340
- return yield* renderPrompt('fix', { pullRequest: fix.pullRequest, round: fix.round, review: notes.map(describeReviewLine) });
599
+ const notes = (yield* github.reviewComments(address.pullRequest)).filter(
600
+ (note) => note.trusted && sameLogin(note.author, address.reviewer),
601
+ );
602
+
603
+ const round = Option.getOrElse(
604
+ Option.map(marker, (found) => found.round),
605
+ () => 1,
606
+ );
607
+
608
+ return {
609
+ verdict: "request-changes" as const,
610
+ sha: address.reviewedSha,
611
+ round,
612
+ summary: notes.map(describeReviewLine).join("\n\n"),
613
+ };
341
614
  }),
342
- Schema.String,
615
+ ReviewResult,
343
616
  );
344
617
 
345
- const checkChanged = (fix: FixItem, worktree: string) =>
618
+ // Fails with NeedsHuman when the author committed nothing since the review.
619
+ export const checkChanged = (
620
+ pullRequest: number,
621
+ round: number,
622
+ reviewedSha: string,
623
+ worktree: string,
624
+ ) =>
346
625
  activity(
347
- 'check-changed',
626
+ `check-changed-${round}`,
348
627
  Effect.gen(function* () {
349
- if ((yield* (yield* Git).headSha(worktree)) === fix.reviewedSha) {
350
- return yield* new NeedsHuman({ reason: `#${fix.pullRequest}: the author agent committed nothing in answer to review ${fix.round}` });
628
+ if ((yield* (yield* Git).headSha(worktree)) === reviewedSha) {
629
+ return yield* new NeedsHuman({
630
+ reason: `#${pullRequest}: the author agent committed nothing in answer to review ${round}`,
631
+ });
351
632
  }
352
633
  }),
353
634
  );
354
635
 
355
- const fixPullRequest = (fix: FixItem) =>
356
- Effect.gen(function* () {
357
- const repo = yield* Repo;
358
- const author = yield* authorSession(fix.pullRequest);
359
- const session = { sessionId: Option.some(author.sessionId), adapter: Option.some(author.adapter) };
360
- const worktree = yield* prepareFix(fix.headRef);
361
- const prompt = yield* readReview(fix);
362
- const outcome = yield* fixWithAgent(`address-review-${fix.round}`, worktree, prompt, session);
363
-
364
- if (outcome.status === 'needs-clarification') {
365
- return yield* new NeedsHuman({ reason: `the author agent needs a person to answer review ${fix.round}:\n\n${outcome.questions ?? outcome.summary}` });
366
- }
367
-
368
- yield* checkChanged(fix, worktree);
369
- yield* push(`push-fix-${fix.round}`, worktree, fix.headRef);
370
- yield* waitForCi(fix.pullRequest, worktree, { ...session, branch: fix.headRef });
371
- yield* relabel('hand-back', fix.pullRequest, {
372
- remove: [repo.labels.changesRequested],
373
- add: repo.labels.needsReview,
374
- comment: Option.some(`Addressed review ${fix.round}: ${outcome.summary}`),
375
- });
376
-
377
- return `#${fix.pullRequest}: addressed review ${fix.round}`;
378
- });
379
-
380
- // Resumes the author's session with the review, pushes the fix once CI is
381
- // green, and hands the pull request back for another review.
382
- export const fixWorkflow = (item: WorkItem) =>
383
- Effect.gen(function* () {
384
- const fix = yield* fixItemOf(item);
385
-
386
- return yield* fixPullRequest(fix).pipe(
387
- Effect.catchTag('NeedsHuman', (needsHuman) =>
388
- Effect.gen(function* () {
389
- const repo = yield* Repo;
390
- yield* relabel('needs-human', fix.pullRequest, {
391
- remove: [repo.labels.changesRequested],
392
- add: repo.labels.needsHuman,
393
- comment: Option.some(`Chernabog stopped and needs a person: ${needsHuman.reason}`),
394
- });
395
-
396
- return yield* needsHuman;
397
- }),
398
- ),
399
- );
400
- });
636
+ // Asks the reviewer who requested the changes to review again, which starts
637
+ // their re-review.
638
+ export const askAgain = (pullRequest: number, round: number, reviewer: string, summary: string) =>
639
+ activity(
640
+ `ask-again-${round}`,
641
+ Effect.gen(function* () {
642
+ const github = yield* GitHub;
643
+ yield* github.comment(pullRequest, `Addressed review ${round}: ${summary}`);
644
+ yield* github.requestReviewers(pullRequest, [reviewer]);
645
+ }),
646
+ );