@chernabog/sdk 0.4.0 → 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,136 +1,176 @@
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));
57
-
58
- const changedSinceReview = (pull: PullRequest, bodies: ReadonlyArray<string>) => Option.exists(reviewedSha(bodies), (sha) => sha !== pull.headSha);
59
-
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));
82
+ const commentBodies = (pull: PullRequest) =>
83
+ GitHub.use((github) => github.comments(pull.number)).pipe(
84
+ Effect.map((comments) => comments.map((comment) => comment.body)),
85
+ );
63
86
 
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* () {
69
- const github = yield* GitHub;
70
- const repo = yield* Repo;
71
- const items: Array<WorkItem> = [];
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));
72
90
 
73
- for (const pull of yield* github.pullRequestsLabelled(repo.labels.needsReview)) {
74
- const bodies = yield* commentBodies(pull);
91
+ export const ownedByARun = (pull: PullRequest) =>
92
+ commentBodies(pull).pipe(Effect.flatMap(ownedByARunOf));
75
93
 
76
- if (yield* ownedByARun(bodies)) continue;
94
+ const sameLogin = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
77
95
 
78
- const item = reviewItem(pull);
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);
79
99
 
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;
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 }> = [];
86
107
 
87
- const bodies = yield* commentBodies(pull);
108
+ for (const pull of yield* github.openPullRequests) {
109
+ if (!pull.requestedReviewers.some((login) => sameLogin(login, me))) {
110
+ continue;
111
+ }
88
112
 
89
- if (changedSinceReview(pull, bodies) && !(yield* ownedByARun(bodies))) items.push({ ...reviewItem(pull), signals: ['pushed'], wakeOnly: true });
90
- }
113
+ if (yield* ownedByARun(pull)) {
114
+ continue;
115
+ }
91
116
 
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 });
117
+ found.push({
118
+ pull,
119
+ reviewed: (yield* github.reviews(pull.number)).filter((review) =>
120
+ sameLogin(review.author, me),
121
+ ).length,
122
+ });
94
123
  }
95
124
 
96
- return items;
125
+ return found;
97
126
  });
98
127
 
99
128
  export const Verdict = Schema.Struct({
100
- verdict: Schema.Literals(['approve', 'request-changes']),
129
+ verdict: Schema.Literals(["approve", "request-changes"]),
101
130
  summary: Schema.String,
102
- 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
+ ),
103
134
  });
104
135
 
105
136
  export type Verdict = typeof Verdict.Type;
106
137
 
107
138
  export const verdictJsonSchema = {
108
- type: 'object',
139
+ type: "object",
109
140
  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' },
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
+ },
112
146
  comments: {
113
- type: 'array',
114
- description: 'Comments on lines the pull request changed',
147
+ type: "array",
148
+ description: "Comments on lines the pull request changed",
115
149
  items: {
116
- type: 'object',
117
- properties: { path: { type: 'string' }, line: { type: 'number' }, body: { type: 'string' } },
118
- 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"],
119
157
  additionalProperties: false,
120
158
  },
121
159
  },
122
160
  },
123
- required: ['verdict', 'summary', 'comments'],
161
+ required: ["verdict", "summary", "comments"],
124
162
  additionalProperties: false,
125
163
  } satisfies Json;
126
164
 
127
- const ReviewComments = Schema.Array(Schema.Struct({ path: Schema.String, line: Schema.Finite, body: Schema.String }));
165
+ const ReviewComments = Schema.Array(
166
+ Schema.Struct({ path: Schema.String, line: Schema.Finite, body: Schema.String }),
167
+ );
128
168
 
129
169
  // A posted review: its verdict and the head it saw, and, from Review.round and
130
170
  // Review.recheck, what it said and the session to resume it in. Those are
131
171
  // optional only so that results saved before they existed still read back.
132
172
  export const ReviewResult = Schema.Struct({
133
- verdict: Schema.Literals(['approve', 'request-changes']),
173
+ verdict: Schema.Literals(["approve", "request-changes"]),
134
174
  sha: Schema.String,
135
175
  round: Schema.optionalKey(Schema.Finite),
136
176
  summary: Schema.optionalKey(Schema.String),
@@ -146,7 +186,10 @@ export const Finding = Schema.Struct({ finding: Schema.String, remediated: Schem
146
186
 
147
187
  export type Finding = typeof Finding.Type;
148
188
 
149
- export const RecheckResult = Schema.Struct({ ...ReviewResult.fields, findings: Schema.Array(Finding) });
189
+ export const RecheckResult = Schema.Struct({
190
+ ...ReviewResult.fields,
191
+ findings: Schema.Array(Finding),
192
+ });
150
193
 
151
194
  export type RecheckResult = typeof RecheckResult.Type;
152
195
 
@@ -157,41 +200,75 @@ export const recheckJsonSchema = {
157
200
  properties: {
158
201
  ...verdictJsonSchema.properties,
159
202
  findings: {
160
- type: 'array',
161
- description: 'Each finding of the earlier review, and whether the new code remediates it',
203
+ type: "array",
204
+ description: "Each finding of the earlier review, and whether the new code remediates it",
162
205
  items: {
163
- type: 'object',
164
- properties: { finding: { type: 'string' }, remediated: { type: 'boolean' } },
165
- required: ['finding', 'remediated'],
206
+ type: "object",
207
+ properties: { finding: { type: "string" }, remediated: { type: "boolean" } },
208
+ required: ["finding", "remediated"],
166
209
  additionalProperties: false,
167
210
  },
168
211
  },
169
212
  },
170
- required: [...verdictJsonSchema.required, 'findings'],
213
+ required: [...verdictJsonSchema.required, "findings"],
171
214
  } satisfies Json;
172
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("<!--");
173
221
 
174
- const withoutMarkers = (body: string) => body.replace(/<!--.*?-->/gs, '').trim();
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
+ };
175
234
 
176
235
  const describeNote = (note: ReviewNote) =>
177
236
  Option.match(note.location, {
178
237
  onNone: () => `${note.author}: ${withoutMarkers(note.body)}`,
179
- 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)}`,
180
240
  });
181
241
 
182
- const headingFor = (verdict: Verdict['verdict'], reviewer: string) => {
183
- 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
+ }
184
246
 
185
247
  return `Changes requested by ${reviewer}`;
186
248
  };
187
249
 
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) =>
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) =>
191
262
  Effect.gen(function* () {
192
263
  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 });
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
+ });
195
272
  yield* github.comment(pull.number, `${heading} at \`${pull.headSha.slice(0, 7)}\`. ${marker}`);
196
273
  });
197
274
 
@@ -201,10 +278,15 @@ const reviewAndPost = (pullRequest: number, round: number, role: Option.Option<s
201
278
  const repo = yield* Repo;
202
279
  const run = yield* Run;
203
280
  const pull = yield* github.pullRequest(pullRequest);
204
- const worktree = yield* (yield* Worktree).checkout(`review-pr-${pullRequest}`, `origin/${pull.headRef}`);
281
+
282
+ const worktree = yield* (yield* Worktree).checkout(
283
+ `review-pr-${pullRequest}`,
284
+ `origin/${pull.headRef}`,
285
+ );
286
+
205
287
  const earlier = (yield* github.reviewComments(pullRequest)).filter((note) => note.trusted);
206
288
 
207
- const prompt = yield* renderPrompt('review', {
289
+ const prompt = yield* renderPrompt("review", {
208
290
  repo: repo.slug,
209
291
  pullRequest,
210
292
  title: pull.title,
@@ -229,37 +311,48 @@ const reviewAndPost = (pullRequest: number, round: number, role: Option.Option<s
229
311
  });
230
312
 
231
313
  const verdict = yield* Schema.decodeUnknownEffect(Verdict)(result.output).pipe(
232
- Effect.mapError((issue) => new StepFailed({ step: `review-${round}`, message: `reviewer answer: ${issue.message}` })),
314
+ Effect.mapError(
315
+ (issue) =>
316
+ new StepFailed({ step: `review-${round}`, message: `reviewer answer: ${issue.message}` }),
317
+ ),
233
318
  );
234
319
 
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);
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
+ );
246
328
 
247
- if (verdict === 'approve') yield* github.addLabel(pullRequest, repo.labels.approved);
248
- else yield* github.addLabel(pullRequest, repo.labels.changesRequested);
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
+ };
249
338
  });
250
339
 
251
340
  // One review of the pull request's current head, in a detached worktree, in a
252
341
  // 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.
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.
255
344
  const reviewOnly = (pullRequest: number, round: number, options: RoleOptions = {}) =>
256
- activity(`review-${round}`, reviewAndPost(pullRequest, round, Option.fromUndefinedOr(options.role)), ReviewResult);
345
+ activity(
346
+ `review-${round}`,
347
+ reviewAndPost(pullRequest, round, Option.fromUndefinedOr(options.role)),
348
+ ReviewResult,
349
+ );
257
350
 
258
351
  export { reviewOnly as round };
259
352
 
260
353
  // 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
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
263
356
  // .chernabog/prompts/recheck.md, or the SDK's own.
264
357
  export const recheck = (pullRequest: number, review: ReviewResult) => {
265
358
  const round = (review.round ?? 1) + 1;
@@ -273,164 +366,182 @@ export const recheck = (pullRequest: number, review: ReviewResult) => {
273
366
  const sessionId = Option.fromUndefinedOr(review.sessionId);
274
367
 
275
368
  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' });
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
+ });
277
374
  }
278
375
 
279
376
  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 });
377
+
378
+ const worktree = yield* (yield* Worktree).checkout(
379
+ `review-pr-${pullRequest}`,
380
+ `origin/${pull.headRef}`,
381
+ );
382
+
383
+ const prompt = yield* renderPromptOr("recheck", RECHECK, {
384
+ pullRequest,
385
+ round: round - 1,
386
+ reviewedSha: review.sha,
387
+ headSha: pull.headSha,
388
+ });
389
+
282
390
  const adapter = Option.fromUndefinedOr(review.adapter);
283
391
 
284
- const result = yield* (yield* Agent).run({ cwd: worktree, prompt, sessionId: sessionId.value, resumePrompt: Option.some(prompt), outputSchema: Option.some(recheckJsonSchema), adapter });
392
+ const result = yield* (yield* Agent).run({
393
+ cwd: worktree,
394
+ prompt,
395
+ sessionId: sessionId.value,
396
+ resumePrompt: Option.some(prompt),
397
+ outputSchema: Option.some(recheckJsonSchema),
398
+ adapter,
399
+ });
285
400
 
286
401
  const verdict = yield* Schema.decodeUnknownEffect(RecheckVerdict)(result.output).pipe(
287
- Effect.mapError((issue) => new StepFailed({ step: `review-${round}`, message: `reviewer answer: ${issue.message}` })),
402
+ Effect.mapError(
403
+ (issue) =>
404
+ new StepFailed({
405
+ step: `review-${round}`,
406
+ message: `reviewer answer: ${issue.message}`,
407
+ }),
408
+ ),
288
409
  );
289
410
 
290
- const reviewer = Option.getOrElse(adapter, () => repo.agent);
291
- yield* postReview(pull, round, verdict, headingFor(verdict.verdict, reviewer));
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
+ );
292
426
 
293
- return { verdict: verdict.verdict, sha: pull.headSha, round, summary: verdict.summary, comments: verdict.comments, sessionId: sessionId.value, adapter: reviewer, findings: verdict.findings };
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
+ };
294
437
  }),
295
438
  RecheckResult,
296
439
  );
297
440
  };
298
441
 
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) =>
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) =>
304
446
  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
- }),
447
+ `clean-up-review-pr-${pullRequest}`,
448
+ Worktree.use((worktree) => worktree.remove(`review-pr-${pullRequest}`)),
314
449
  );
315
450
 
316
- // `round` and `labelVerdict` in one step: reviews, posts, and moves the labels.
317
- export const reviewRound = (pullRequest: number, round: number) =>
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) =>
318
455
  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,
456
+ "find-review",
330
457
  Effect.gen(function* () {
331
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
+ );
332
471
 
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`;
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
+ });
351
489
  }),
352
- Schema.String,
490
+ Schema.Option(ReviewResult),
353
491
  );
354
492
 
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 });
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;
389
497
 
390
- if (woke === 'closed') return yield* cleanUp(pullRequest, headRef);
498
+ return (yield* github.openPullRequests).filter((pull) => sameLogin(pull.author, me));
499
+ });
391
500
 
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
- });
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
+ );
398
510
 
399
- return `#${pullRequest} went stale waiting for a push`;
400
- }
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
+ });
401
530
 
402
- yield* relabel(`re-review-${round}`, pullRequest, { remove: [repo.labels.changesRequested], add: repo.labels.needsReview, comment: Option.none() });
403
- }
404
- });
531
+ export const AddressItem = Schema.Struct({
532
+ ...ReviewItem.fields,
533
+ reviewer: Schema.String,
534
+ reviewedSha: Schema.String,
535
+ });
405
536
 
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
- }
537
+ export type AddressItem = typeof AddressItem.Type;
426
538
 
427
- return items;
428
- });
539
+ export const addressItemOf = itemData(AddressItem);
429
540
 
430
541
  // The author's session, from the marker the implement run left; a fresh one if there is none.
431
- const authorSession = (pullRequest: number) =>
542
+ export const authorSession = (pullRequest: number) =>
432
543
  activity(
433
- 'find-author',
544
+ "find-author",
434
545
  Effect.gen(function* () {
435
546
  const github = yield* GitHub;
436
547
  const run = yield* Run;
@@ -441,14 +552,20 @@ const authorSession = (pullRequest: number) =>
441
552
  (yield* github.comments(pullRequest)).map((comment) => comment.body),
442
553
  );
443
554
 
444
- 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
+ }));
445
561
  }),
446
562
  SessionMarker,
447
563
  );
448
564
 
449
- 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) =>
450
567
  activity(
451
- 'prepare-worktree',
568
+ "prepare-worktree",
452
569
  Effect.gen(function* () {
453
570
  const path = yield* (yield* Worktree).ensure(headRef);
454
571
  yield* (yield* Git).pull(path, headRef);
@@ -464,70 +581,66 @@ const describeReviewLine = (note: ReviewNote) =>
464
581
  onSome: (location) => `${location.path}:${location.line}: ${withoutMarkers(note.body)}`,
465
582
  });
466
583
 
467
- 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) =>
468
587
  activity(
469
- 'read-review',
588
+ "read-review",
470
589
  Effect.gen(function* () {
471
- 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);
472
592
 
473
- return yield* renderPrompt('fix', { pullRequest: fix.pullRequest, round: fix.round, review: notes.map(describeReviewLine) });
593
+ const marker = latestMarker(
594
+ (body) =>
595
+ Option.filter(reviewMarker.read(body), (found) => found.sha === address.reviewedSha),
596
+ bodies,
597
+ );
598
+
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
+ };
474
614
  }),
475
- Schema.String,
615
+ ReviewResult,
476
616
  );
477
617
 
478
- 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
+ ) =>
479
625
  activity(
480
- 'check-changed',
626
+ `check-changed-${round}`,
481
627
  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}` });
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
+ });
484
632
  }
485
633
  }),
486
634
  );
487
635
 
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
- });
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
+ );