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