@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/implement.ts CHANGED
@@ -1,37 +1,62 @@
1
- // The building blocks of the default `implement` flow: find a queued issue,
1
+ // The building blocks of the `implement` recipe: find a queued issue,
2
2
  // claim it, prepare a worktree, let the agent implement it, run the local gate,
3
3
  // open the pull request, wait for CI and hand off for review. Each block is an
4
4
  // activity, so a flow can reorder them, leave one out, or put its own step
5
5
  // from .chernabog/stages/ in between.
6
6
 
7
- import { createHash } from 'node:crypto';
8
-
9
- import * as DateTime from 'effect/DateTime';
10
- import * as Duration from 'effect/Duration';
11
- import * as Effect from 'effect/Effect';
12
- import * as Option from 'effect/Option';
13
- import * as ChildProcess from 'effect/process/ChildProcess';
14
- import * as ChildProcessSpawner from 'effect/process/ChildProcessSpawner';
15
- import * as Schema from 'effect/Schema';
16
- import * as Stream from 'effect/Stream';
17
-
18
- import { NeedsHuman, Skip, StepFailed } from './errors.ts';
19
- import { activity, sleep } from './flow.ts';
20
- import type { Json } from './json.ts';
21
- import { type ClaimMarker, claimMarker, latestMarker, sessionMarker } from './markers.ts';
22
- import { pathsMatching } from './paths.ts';
23
- import { renderPrompt } from './prompt.ts';
24
- import { Agent, type AgentResult, Git, GitHub, type Issue, Repo, Run, RunLog, Usage, type WorkItem, Worktree } from './services.ts';
7
+ import { createHash } from "node:crypto";
8
+
9
+ import * as DateTime from "effect/DateTime";
10
+ import * as Duration from "effect/Duration";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Option from "effect/Option";
13
+ import * as ChildProcess from "effect/process/ChildProcess";
14
+ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15
+ import * as Schema from "effect/Schema";
16
+ import * as Stream from "effect/Stream";
17
+
18
+ import { ADDRESS, CONSIDER } from "./default-prompts.ts";
19
+ import { CiTimedOut, NeedsHuman, NothingCommitted, Skip, StepFailed } from "./errors.ts";
20
+ import { activity, reportAs, sleep } from "./flow.ts";
21
+ import type { Json } from "./json.ts";
22
+ import { type ClaimMarker, claimMarker, latestMarker, sessionMarker } from "./markers.ts";
23
+ import { pathsMatching } from "./paths.ts";
24
+ import { renderPrompt, renderPromptOr } from "./prompt.ts";
25
+ import { requestReview } from "./pull-request.ts";
26
+ import type { ReviewResult } from "./review.ts";
27
+ import {
28
+ Agent,
29
+ type AgentResult,
30
+ Git,
31
+ GitHub,
32
+ type Issue,
33
+ Repo,
34
+ Run,
35
+ RunLog,
36
+ Usage,
37
+ type WorkItem,
38
+ Worktree,
39
+ } from "./services.ts";
25
40
 
26
41
  export const branchFor = (issue: number) => `auto/issue-${issue}`;
27
42
 
28
- export const IssueItem = Schema.Struct({ issue: Schema.Finite });
43
+ // An issue to implement, and the label that queued it, when it's not eligible's.
44
+ export const IssueItem = Schema.Struct({
45
+ issue: Schema.Finite,
46
+ label: Schema.optionalKey(Schema.String),
47
+ });
29
48
 
30
- export const issueItem = (issue: Issue): WorkItem => ({
49
+ export const issueItem = (
50
+ issue: Issue,
51
+ label: Option.Option<string> = Option.none(),
52
+ ): WorkItem => ({
31
53
  key: `issue-${issue.number}`,
32
54
  title: issue.title,
33
55
  url: issue.url,
34
- data: { issue: issue.number },
56
+ data: {
57
+ issue: issue.number,
58
+ ...Option.match(label, { onNone: () => ({}), onSome: (queued) => ({ label: queued }) }),
59
+ },
35
60
  assignees: issue.assignees,
36
61
  });
37
62
 
@@ -39,20 +64,56 @@ export const issueItem = (issue: Issue): WorkItem => ({
39
64
  export const issueOf = (item: WorkItem) =>
40
65
  Schema.decodeUnknownEffect(IssueItem)(item.data).pipe(
41
66
  Effect.map((data) => data.issue),
42
- Effect.mapError((issue) => new StepFailed({ step: 'work item', message: `${item.key} is not an issue: ${issue.message}` })),
67
+ Effect.mapError(
68
+ (issue) =>
69
+ new StepFailed({
70
+ step: "work item",
71
+ message: `${item.key} is not an issue: ${issue.message}`,
72
+ }),
73
+ ),
43
74
  );
44
75
 
45
76
  // A stable session id per run and purpose, so a rerun after a crash resumes
46
77
  // the agent's session instead of starting over.
47
78
  export const sessionIdFor = (runId: string, purpose: string) => {
48
- const hex = createHash('sha256').update(`${runId}/${purpose}`).digest('hex');
79
+ const hex = createHash("sha256").update(`${runId}/${purpose}`).digest("hex");
49
80
  const variant = ((Number.parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
50
81
 
51
82
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
52
83
  };
53
84
 
54
- // Issues labelled eligible, oldest first, each with its assignees.
55
- export const trigger = GitHub.use((github) => github.queuedIssues).pipe(Effect.map((issues) => issues.map(issueItem)));
85
+ // Issues with a queue label, oldest first, each with its assignees. A flow
86
+ // keyed by its own label pairs it with `claim(issue, queuedBy(item))`.
87
+ export const triggerFor = (label: string) =>
88
+ GitHub.use((github) => github.queuedIssuesLabelled(label)).pipe(
89
+ Effect.map((issues) => issues.map((issue) => issueItem(issue, Option.some(label)))),
90
+ reportAs("trigger"),
91
+ );
92
+
93
+ // Which label queued the issue: eligible unless the flow is keyed by its own.
94
+ export type QueueOptions = { readonly label?: string };
95
+
96
+ // The label that queued a work item from `trigger`, for claim,
97
+ // askForClarification and openPullRequest.
98
+ export const queuedBy = (item: WorkItem) =>
99
+ Schema.decodeUnknownEffect(IssueItem)(item.data).pipe(
100
+ Effect.map((data): QueueOptions =>
101
+ Option.match(Option.fromUndefinedOr(data.label), {
102
+ onNone: () => ({}),
103
+ onSome: (label) => ({ label }),
104
+ }),
105
+ ),
106
+ Effect.mapError(
107
+ (issue) =>
108
+ new StepFailed({
109
+ step: "work item",
110
+ message: `${item.key} is not an issue: ${issue.message}`,
111
+ }),
112
+ ),
113
+ );
114
+
115
+ const queueLabel = (options: QueueOptions) =>
116
+ Repo.use((repo) => Effect.succeed(options.label ?? repo.labels.eligible));
56
117
 
57
118
  // The account is the one machine config expects, and it has room for a task.
58
119
  export const gate = Effect.gen(function* () {
@@ -60,65 +121,80 @@ export const gate = Effect.gen(function* () {
60
121
  yield* usage.checkAccount;
61
122
  const decision = yield* usage.gate;
62
123
 
63
- if (!decision.launch) return yield* new Skip({ reason: `usage gate: ${decision.reason}` });
64
- });
124
+ if (!decision.launch) {
125
+ return yield* new Skip({ reason: `usage gate: ${decision.reason}` });
126
+ }
127
+ }).pipe(reportAs("gate"));
65
128
 
66
129
  // Issues are often public, so the comment says nothing about the machine: no
67
130
  // hostname, and no worktree path with the user's home in it.
68
131
  export const claimComment = (claim: ClaimMarker) =>
69
132
  [
70
133
  `Claimed by Chernabog at ${claim.claimedAt}, on branch \`${claim.branch}\`.`,
71
- '',
134
+ "",
72
135
  `- Run: \`${claim.runId}\``,
73
- '',
136
+ "",
74
137
  claimMarker.write(claim),
75
- ].join('\n');
138
+ ].join("\n");
76
139
 
77
140
  // Whether the claim on an existing branch is this run's. No marker at all means
78
141
  // this run crashed between creating the branch and commenting, while the issue
79
142
  // still says it is queued.
80
- const holdsClaim = (issue: number, runId: string) =>
143
+ const holdsClaim = (issue: number, runId: string, label: string) =>
81
144
  Effect.gen(function* () {
82
145
  const github = yield* GitHub;
83
- const repo = yield* Repo;
84
146
 
85
147
  const latest = latestMarker(
86
148
  claimMarker.read,
87
149
  (yield* github.comments(issue)).map((comment) => comment.body),
88
150
  );
89
151
 
90
- if (Option.isSome(latest)) return { ours: latest.value.runId === runId, commented: true };
152
+ if (Option.isSome(latest)) {
153
+ return { ours: latest.value.runId === runId, commented: true };
154
+ }
91
155
 
92
- return { ours: (yield* github.issue(issue)).labels.includes(repo.labels.eligible), commented: false };
156
+ return { ours: (yield* github.issue(issue)).labels.includes(label), commented: false };
93
157
  });
94
158
 
95
159
  // Creates the issue's branch, which only one run can do, then labels, assigns
96
160
  // and comments as a person picking it up would. Safe to repeat: a run that
97
- // already holds the claim keeps it.
98
- export const claim = (issue: number) =>
161
+ // already holds the claim keeps it. Removes the label that queued the issue.
162
+ export const claim = (issue: number, options: QueueOptions = {}) =>
99
163
  activity(
100
- 'claim',
164
+ "claim",
101
165
  Effect.gen(function* () {
102
166
  const github = yield* GitHub;
103
167
  const repo = yield* Repo;
104
168
  const run = yield* Run;
169
+ const label = yield* queueLabel(options);
105
170
  const branch = branchFor(issue);
106
171
  const baseSha = yield* github.branchSha(repo.baseBranch);
107
172
 
108
- if (Option.isNone(baseSha)) return yield* new StepFailed({ step: 'claim', message: `base branch ${repo.baseBranch} not found` });
173
+ if (Option.isNone(baseSha)) {
174
+ return yield* new StepFailed({
175
+ step: "claim",
176
+ message: `base branch ${repo.baseBranch} not found`,
177
+ });
178
+ }
109
179
 
110
- if ((yield* github.createBranch(branch, baseSha.value)) === 'already-exists') {
111
- const held = yield* holdsClaim(issue, run.runId);
180
+ if ((yield* github.createBranch(branch, baseSha.value)) === "already-exists") {
181
+ const held = yield* holdsClaim(issue, run.runId, label);
112
182
 
113
- if (!held.ours) return yield* new Skip({ reason: `#${issue} is already claimed (${branch} exists)` });
183
+ if (!held.ours) {
184
+ return yield* new Skip({ reason: `#${issue} is already claimed (${branch} exists)` });
185
+ }
114
186
 
115
- if (held.commented) return { branch };
187
+ if (held.commented) {
188
+ return { branch };
189
+ }
116
190
  }
117
191
 
118
192
  yield* github.addLabel(issue, repo.labels.inProgress);
119
- yield* github.removeLabel(issue, repo.labels.eligible);
193
+ yield* github.removeLabel(issue, label);
120
194
 
121
- if (Option.isSome(repo.board)) yield* github.moveToStatus(issue, repo.board.value.inProgressStatus);
195
+ if (Option.isSome(repo.board)) {
196
+ yield* github.moveToStatus(issue, repo.board.value.inProgressStatus);
197
+ }
122
198
 
123
199
  yield* github.assignSelf(issue);
124
200
  const claimedAt = DateTime.formatIso(yield* DateTime.now);
@@ -134,8 +210,20 @@ export const claim = (issue: number) =>
134
210
  export const shell = (command: string, cwd: string, env: Readonly<Record<string, string>>) =>
135
211
  Effect.gen(function* () {
136
212
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
137
- const handle = yield* spawner.spawn(ChildProcess.make('sh', ['-c', command], { cwd, env: { ...env, CI: '1' }, extendEnv: true, forceKillAfter: '5 seconds' }));
138
- const [output, exitCode] = yield* Effect.all([Stream.mkString(Stream.decodeText(handle.all)), handle.exitCode], { concurrency: 'unbounded' });
213
+
214
+ const handle = yield* spawner.spawn(
215
+ ChildProcess.make("sh", ["-c", command], {
216
+ cwd,
217
+ env: { ...env, CI: "1" },
218
+ extendEnv: true,
219
+ forceKillAfter: "5 seconds",
220
+ }),
221
+ );
222
+
223
+ const [output, exitCode] = yield* Effect.all(
224
+ [Stream.mkString(Stream.decodeText(handle.all)), handle.exitCode],
225
+ { concurrency: "unbounded" },
226
+ );
139
227
 
140
228
  return { exitCode: Number(exitCode), output };
141
229
  }).pipe(
@@ -143,12 +231,12 @@ export const shell = (command: string, cwd: string, env: Readonly<Record<string,
143
231
  Effect.mapError((error) => new StepFailed({ step: command, message: error.message })),
144
232
  );
145
233
 
146
- const tail = (text: string, lines = 80) => text.trimEnd().split('\n').slice(-lines).join('\n');
234
+ const tail = (text: string, lines = 80) => text.trimEnd().split("\n").slice(-lines).join("\n");
147
235
 
148
236
  // The worktree for the claim branch, with dependencies installed.
149
237
  export const prepareWorktree = (branch: string) =>
150
238
  activity(
151
- 'prepare-worktree',
239
+ "prepare-worktree",
152
240
  Effect.gen(function* () {
153
241
  const repo = yield* Repo;
154
242
  const path = yield* (yield* Worktree).ensure(branch);
@@ -156,7 +244,9 @@ export const prepareWorktree = (branch: string) =>
156
244
  if (Option.isSome(repo.install)) {
157
245
  const installed = yield* shell(repo.install.value, path, repo.env);
158
246
 
159
- if (installed.exitCode !== 0) return yield* new StepFailed({ step: 'install', message: tail(installed.output, 30) });
247
+ if (installed.exitCode !== 0) {
248
+ return yield* new StepFailed({ step: "install", message: tail(installed.output, 30) });
249
+ }
160
250
  }
161
251
 
162
252
  return path;
@@ -165,7 +255,7 @@ export const prepareWorktree = (branch: string) =>
165
255
  );
166
256
 
167
257
  export const ImplementOutcome = Schema.Struct({
168
- status: Schema.Literals(['done', 'needs-clarification']),
258
+ status: Schema.Literals(["done", "needs-clarification"]),
169
259
  summary: Schema.String,
170
260
  title: Schema.String,
171
261
  body: Schema.String,
@@ -175,29 +265,46 @@ export const ImplementOutcome = Schema.Struct({
175
265
  export type ImplementOutcome = typeof ImplementOutcome.Type;
176
266
 
177
267
  export const implementOutcomeJsonSchema = {
178
- type: 'object',
268
+ type: "object",
179
269
  properties: {
180
- status: { type: 'string', enum: ['done', 'needs-clarification'] },
181
- summary: { type: 'string', description: 'What changed and how it was tested, for the issue comment' },
182
- title: { type: 'string', description: 'The pull request title, following the repo commit convention' },
183
- body: { type: 'string', description: 'The pull request body in Markdown, without the Closes line' },
184
- questions: { type: 'string', description: 'For needs-clarification: numbered questions, each led by a recommendation' },
270
+ status: { type: "string", enum: ["done", "needs-clarification"] },
271
+ summary: {
272
+ type: "string",
273
+ description: "What changed and how it was tested, for the issue comment",
274
+ },
275
+ title: {
276
+ type: "string",
277
+ description: "The pull request title, following the repo commit convention",
278
+ },
279
+ body: {
280
+ type: "string",
281
+ description: "The pull request body in Markdown, without the Closes line",
282
+ },
283
+ questions: {
284
+ type: "string",
285
+ description: "For needs-clarification: numbered questions, each led by a recommendation",
286
+ },
185
287
  },
186
- required: ['status', 'summary', 'title', 'body'],
288
+ required: ["status", "summary", "title", "body"],
187
289
  additionalProperties: false,
188
290
  } satisfies Json;
189
291
 
190
- const RESUME_PROMPT = 'You were interrupted. Continue the task from where you left off, then give your final answer in the required format.';
292
+ const RESUME_PROMPT =
293
+ "You were interrupted. Continue the task from where you left off, then give your final answer in the required format.";
191
294
 
192
295
  const decodeOutcome = (result: AgentResult) =>
193
- Schema.decodeUnknownEffect(ImplementOutcome)(result.output).pipe(Effect.mapError((issue) => new StepFailed({ step: 'agent', message: `agent answer: ${issue.message}` })));
296
+ Schema.decodeUnknownEffect(ImplementOutcome)(result.output).pipe(
297
+ Effect.mapError(
298
+ (issue) => new StepFailed({ step: "agent", message: `agent answer: ${issue.message}` }),
299
+ ),
300
+ );
194
301
 
195
302
  // The agent implements the issue in the worktree and commits, from
196
303
  // .chernabog/prompts/implement.md. It answers done, with the pull request's
197
304
  // title and body, or needs-clarification, with its questions.
198
305
  export const implementWithAgent = (issue: number, worktree: string) =>
199
306
  activity(
200
- 'implement',
307
+ "implement",
201
308
  Effect.gen(function* () {
202
309
  const github = yield* GitHub;
203
310
  const repo = yield* Repo;
@@ -205,7 +312,7 @@ export const implementWithAgent = (issue: number, worktree: string) =>
205
312
  const details = yield* github.issue(issue);
206
313
  const comments = yield* github.trustedComments(issue);
207
314
 
208
- const prompt = yield* renderPrompt('implement', {
315
+ const prompt = yield* renderPrompt("implement", {
209
316
  repo: repo.slug,
210
317
  issue,
211
318
  title: details.title,
@@ -221,7 +328,7 @@ export const implementWithAgent = (issue: number, worktree: string) =>
221
328
  const result = yield* (yield* Agent).run({
222
329
  cwd: worktree,
223
330
  prompt,
224
- sessionId: sessionIdFor(run.runId, 'implement'),
331
+ sessionId: sessionIdFor(run.runId, "implement"),
225
332
  resumePrompt: Option.some(RESUME_PROMPT),
226
333
  outputSchema: Option.some(implementOutcomeJsonSchema),
227
334
  adapter: Option.none(),
@@ -232,13 +339,23 @@ export const implementWithAgent = (issue: number, worktree: string) =>
232
339
  ImplementOutcome,
233
340
  );
234
341
 
235
- // Which session a fix goes to: this run's implement session when none is given.
236
- export type AuthorSession = { readonly sessionId: Option.Option<string>; readonly adapter: Option.Option<string> };
342
+ // Which session a fix goes to: this run's implement session when none is
343
+ // given. withPerson: a person works in it with the agent, on the hybrid path.
344
+ export type AuthorSession = {
345
+ readonly sessionId: Option.Option<string>;
346
+ readonly adapter: Option.Option<string>;
347
+ readonly withPerson?: boolean;
348
+ };
237
349
 
238
350
  export const thisRunsSession: AuthorSession = { sessionId: Option.none(), adapter: Option.none() };
239
351
 
240
352
  // Sends the agent back into its session with a failure to fix.
241
- export const fixWithAgent = (name: string, worktree: string, prompt: string, session: AuthorSession) =>
353
+ export const fixWithAgent = (
354
+ name: string,
355
+ worktree: string,
356
+ prompt: string,
357
+ session: AuthorSession,
358
+ ) =>
242
359
  activity(
243
360
  name,
244
361
  Effect.gen(function* () {
@@ -247,10 +364,11 @@ export const fixWithAgent = (name: string, worktree: string, prompt: string, ses
247
364
  const result = yield* (yield* Agent).run({
248
365
  cwd: worktree,
249
366
  prompt,
250
- sessionId: Option.getOrElse(session.sessionId, () => sessionIdFor(run.runId, 'implement')),
367
+ sessionId: Option.getOrElse(session.sessionId, () => sessionIdFor(run.runId, "implement")),
251
368
  resumePrompt: Option.some(prompt),
252
369
  outputSchema: Option.some(implementOutcomeJsonSchema),
253
370
  adapter: session.adapter,
371
+ withPerson: session.withPerson === true,
254
372
  });
255
373
 
256
374
  return yield* decodeOutcome(result);
@@ -258,19 +376,148 @@ export const fixWithAgent = (name: string, worktree: string, prompt: string, ses
258
376
  ImplementOutcome,
259
377
  );
260
378
 
379
+ // The review's findings for a prompt: its summary, then each line comment.
380
+ const describeReview = (review: ReviewResult) =>
381
+ [
382
+ review.summary ?? `The review's verdict was ${review.verdict}.`,
383
+ ...(review.comments ?? []).map(
384
+ (comment) => `- ${comment.path}:${comment.line}: ${comment.body}`,
385
+ ),
386
+ ].join("\n\n");
387
+
388
+ export const Consideration = Schema.Struct({
389
+ status: Schema.Literals(["address", "decline"]),
390
+ reasons: Schema.String,
391
+ });
392
+
393
+ export type Consideration = typeof Consideration.Type;
394
+
395
+ export const considerationJsonSchema = {
396
+ type: "object",
397
+ properties: {
398
+ status: { type: "string", enum: ["address", "decline"] },
399
+ reasons: { type: "string", description: "Why, point by point, in Markdown" },
400
+ },
401
+ required: ["status", "reasons"],
402
+ additionalProperties: false,
403
+ } satisfies Json;
404
+
405
+ const authorWorktree = (pullRequest: number) =>
406
+ Effect.gen(function* () {
407
+ const pull = yield* (yield* GitHub).pullRequest(pullRequest);
408
+
409
+ return yield* (yield* Worktree).ensure(pull.headRef);
410
+ });
411
+
412
+ // Resumes the author's session with a review, and asks whether to address it
413
+ // or decline it, with reasons. Changes nothing. Its prompt is
414
+ // .chernabog/prompts/consider.md, or the SDK's own.
415
+ export const considerFindings = (
416
+ pullRequest: number,
417
+ review: ReviewResult,
418
+ session: AuthorSession,
419
+ ) => {
420
+ const round = review.round ?? 1;
421
+
422
+ return activity(
423
+ `consider-review-${round}`,
424
+ Effect.gen(function* () {
425
+ const run = yield* Run;
426
+ const worktree = yield* authorWorktree(pullRequest);
427
+
428
+ const prompt = yield* renderPromptOr("consider", CONSIDER, {
429
+ pullRequest,
430
+ round,
431
+ review: describeReview(review),
432
+ });
433
+
434
+ const result = yield* (yield* Agent).run({
435
+ cwd: worktree,
436
+ prompt,
437
+ sessionId: Option.getOrElse(session.sessionId, () => sessionIdFor(run.runId, "implement")),
438
+ resumePrompt: Option.some(prompt),
439
+ outputSchema: Option.some(considerationJsonSchema),
440
+ adapter: session.adapter,
441
+ withPerson: session.withPerson === true,
442
+ });
443
+
444
+ return yield* Schema.decodeUnknownEffect(Consideration)(result.output).pipe(
445
+ Effect.mapError(
446
+ (issue) =>
447
+ new StepFailed({
448
+ step: `consider-review-${round}`,
449
+ message: `agent answer: ${issue.message}`,
450
+ }),
451
+ ),
452
+ );
453
+ }),
454
+ Consideration,
455
+ );
456
+ };
457
+
458
+ // Resumes the author's session to make the changes a review asks for, and
459
+ // commit them, as fixWithAgent does for a failing check. Its prompt is
460
+ // .chernabog/prompts/address.md, or the SDK's own.
461
+ export const addressFindings = (
462
+ pullRequest: number,
463
+ review: ReviewResult,
464
+ session: AuthorSession,
465
+ ) =>
466
+ Effect.gen(function* () {
467
+ const round = review.round ?? 1;
468
+
469
+ const prepared = yield* activity(
470
+ `prepare-address-${round}`,
471
+ Effect.gen(function* () {
472
+ const worktree = yield* authorWorktree(pullRequest);
473
+
474
+ const prompt = yield* renderPromptOr("address", ADDRESS, {
475
+ pullRequest,
476
+ round,
477
+ review: describeReview(review),
478
+ });
479
+
480
+ return { worktree, prompt };
481
+ }),
482
+ Schema.Struct({ worktree: Schema.String, prompt: Schema.String }),
483
+ );
484
+
485
+ return yield* fixWithAgent(
486
+ `address-review-${round}`,
487
+ prepared.worktree,
488
+ prepared.prompt,
489
+ session,
490
+ );
491
+ });
492
+
261
493
  const requeueHint = (board: Option.Option<{ readonly readyStatus: string }>) =>
262
- Option.match(board, { onNone: () => 'apply', onSome: (found) => `set Status back to ${found.readyStatus} and apply` });
494
+ Option.match(board, {
495
+ onNone: () => "apply",
496
+ onSome: (found) => `set Status back to ${found.readyStatus} and apply`,
497
+ });
263
498
 
264
499
  // Posts the agent's questions, releases the claim and stops, as a person would
265
- // who needs an answer before going on.
266
- export const askForClarification = (issue: number, outcome: ImplementOutcome) =>
500
+ // who needs an answer before going on. The requeue hint names the label that queued it.
501
+ export const askForClarification = (
502
+ issue: number,
503
+ outcome: ImplementOutcome,
504
+ options: QueueOptions = {},
505
+ ) =>
267
506
  activity(
268
- 'needs-clarification',
507
+ "needs-clarification",
269
508
  Effect.gen(function* () {
270
509
  const github = yield* GitHub;
271
510
  const repo = yield* Repo;
511
+ const label = yield* queueLabel(options);
272
512
  const questions = outcome.questions ?? outcome.summary;
273
- yield* github.comment(issue, [questions, '', `To requeue: answer the questions above, then ${requeueHint(repo.board)} \`${repo.labels.eligible}\` again.`].join('\n'));
513
+ yield* github.comment(
514
+ issue,
515
+ [
516
+ questions,
517
+ "",
518
+ `To requeue: answer the questions above, then ${requeueHint(repo.board)} \`${label}\` again.`,
519
+ ].join("\n"),
520
+ );
274
521
  yield* github.addLabel(issue, repo.labels.needsClarification);
275
522
  yield* github.removeLabel(issue, repo.labels.inProgress);
276
523
  yield* github.deleteBranch(branchFor(issue));
@@ -283,9 +530,23 @@ export const askForClarification = (issue: number, outcome: ImplementOutcome) =>
283
530
 
284
531
  const LocalGateResult = Schema.Struct({ ok: Schema.Boolean, failure: Schema.String });
285
532
 
286
- const runLocalGate = (worktree: string, round: number) =>
533
+ // Tells apart two calls of a looping step in one run, such as the local gate
534
+ // before the pull request opens and again after a review's fix: their
535
+ // activities are named like `local-gate-1#fix-1`, as `step` does with its id.
536
+ export type RepeatOptions = { readonly id?: string };
537
+
538
+ // The session the local gate sends the agent back to: this run's implement session unless given.
539
+ export type LocalGateOptions = RepeatOptions & { readonly session?: AuthorSession };
540
+
541
+ const named = (options: RepeatOptions, name: string) =>
542
+ Option.match(Option.fromUndefinedOr(options.id), {
543
+ onNone: () => name,
544
+ onSome: (id) => `${name}#${id}`,
545
+ });
546
+
547
+ const runLocalGate = (worktree: string, round: number, options: RepeatOptions) =>
287
548
  activity(
288
- `local-gate-${round}`,
549
+ named(options, `local-gate-${round}`),
289
550
  Effect.gen(function* () {
290
551
  const repo = yield* Repo;
291
552
  const log = yield* RunLog;
@@ -294,35 +555,56 @@ const runLocalGate = (worktree: string, round: number) =>
294
555
  yield* log.log(`local gate: ${command}`);
295
556
  const result = yield* shell(command, worktree, repo.env);
296
557
 
297
- if (result.exitCode !== 0) return { ok: false, failure: `\`${command}\` exited ${result.exitCode}:\n\n${tail(result.output)}` };
558
+ if (result.exitCode !== 0) {
559
+ return {
560
+ ok: false,
561
+ failure: `\`${command}\` exited ${result.exitCode}:\n\n${tail(result.output)}`,
562
+ };
563
+ }
298
564
  }
299
565
 
300
- return { ok: true, failure: '' };
566
+ return { ok: true, failure: "" };
301
567
  }),
302
568
  LocalGateResult,
303
569
  );
304
570
 
305
571
  // Runs the repo's local gate, and sends the agent back to fix what fails, up to
306
572
  // limits.localGateRounds times.
307
- export const localGate = (worktree: string) =>
573
+ export const localGate = (worktree: string, options: LocalGateOptions = {}) =>
308
574
  Effect.gen(function* () {
309
575
  const repo = yield* Repo;
310
576
 
311
577
  for (let round = 1; ; round++) {
312
- const result = yield* runLocalGate(worktree, round);
578
+ const result = yield* runLocalGate(worktree, round, options);
313
579
 
314
- if (result.ok) return;
580
+ if (result.ok) {
581
+ return;
582
+ }
315
583
 
316
584
  if (round > repo.limits.localGateRounds) {
317
- return yield* new NeedsHuman({ reason: `the local gate still fails after ${repo.limits.localGateRounds} fix attempts:\n\n${result.failure}` });
585
+ return yield* new NeedsHuman({
586
+ reason: `the local gate still fails after ${repo.limits.localGateRounds} fix attempts:\n\n${result.failure}`,
587
+ });
318
588
  }
319
589
 
320
- yield* fixWithAgent(`fix-local-gate-${round}`, worktree, `The local gate failed. Fix the cause, commit, and answer again.\n\n${result.failure}`, thisRunsSession);
590
+ yield* fixWithAgent(
591
+ named(options, `fix-local-gate-${round}`),
592
+ worktree,
593
+ `The local gate failed. Fix the cause, commit, and answer again.\n\n${result.failure}`,
594
+ options.session ?? thisRunsSession,
595
+ );
321
596
  }
322
597
  });
323
598
 
324
- // Checks the branch has commits, touches no human-only paths, and pushes it.
325
- export const push = (name: string, worktree: string, branch: string) =>
599
+ // withPerson: a person is in the session that wrote the change, so it may
600
+ // touch humanOnlyPaths; a person still merges it (PullRequest.merge checks them again).
601
+ export type PushOptions = { readonly withPerson?: boolean };
602
+
603
+ // Checks the branch has commits and, unless a person is in the session,
604
+ // touches no human-only paths, and pushes it. Fails with NothingCommitted when
605
+ // there's nothing to push, and PushRejected when the remote refuses it, such
606
+ // as for a token without the workflow scope.
607
+ export const push = (name: string, worktree: string, branch: string, options: PushOptions = {}) =>
326
608
  activity(
327
609
  name,
328
610
  Effect.gen(function* () {
@@ -330,13 +612,20 @@ export const push = (name: string, worktree: string, branch: string) =>
330
612
  const repo = yield* Repo;
331
613
 
332
614
  if ((yield* git.commitsAhead(worktree, repo.baseBranch)) === 0) {
333
- return yield* new NeedsHuman({ reason: `the agent finished without committing anything on ${branch}` });
615
+ return yield* new NothingCommitted({ branch });
334
616
  }
335
617
 
336
- const touched = pathsMatching(yield* git.changedFiles(worktree, repo.baseBranch), repo.humanOnlyPaths);
337
-
338
- if (touched.length > 0) {
339
- return yield* new NeedsHuman({ reason: `the change touches paths a person must handle: ${touched.map((path) => `\`${path}\``).join(', ')}` });
618
+ if (options.withPerson !== true) {
619
+ const touched = pathsMatching(
620
+ yield* git.changedFiles(worktree, repo.baseBranch),
621
+ repo.humanOnlyPaths,
622
+ );
623
+
624
+ if (touched.length > 0) {
625
+ return yield* new NeedsHuman({
626
+ reason: `the change touches paths a person must handle: ${touched.map((path) => `\`${path}\``).join(", ")}`,
627
+ });
628
+ }
340
629
  }
341
630
 
342
631
  yield* git.push(worktree, branch);
@@ -347,25 +636,50 @@ export const PullRequestRef = Schema.Struct({ number: Schema.Finite, url: Schema
347
636
 
348
637
  export type PullRequestRef = typeof PullRequestRef.Type;
349
638
 
350
- // Opens the pull request for the branch, or finds the one already open.
351
- export const openPullRequest = (issue: number, outcome: ImplementOutcome) =>
639
+ const footer = (shipping: boolean) => {
640
+ if (shipping) {
641
+ return "Opened by Chernabog for an unattended run, on the automated path: it merges once its review approves.";
642
+ }
643
+
644
+ return "Opened by Chernabog for an unattended run. A person merges.";
645
+ };
646
+
647
+ // Opens the pull request for the branch, or finds the one already open. An
648
+ // issue queued by ship (auto:ship) gives its pull request the label too, the
649
+ // automated path, which merges once approved.
650
+ export const openPullRequest = (
651
+ issue: number,
652
+ outcome: ImplementOutcome,
653
+ options: QueueOptions = {},
654
+ ) =>
352
655
  activity(
353
- 'open-pull-request',
656
+ "open-pull-request",
354
657
  Effect.gen(function* () {
355
658
  const github = yield* GitHub;
356
659
  const repo = yield* Repo;
357
660
  const branch = branchFor(issue);
358
- const existing = Option.filter(yield* github.pullRequestForBranch(branch), (pull) => pull.state === 'open');
661
+ const shipping = options.label === repo.labels.ship;
359
662
 
360
- if (Option.isSome(existing)) return { number: existing.value.number, url: existing.value.url };
663
+ const existing = Option.filter(
664
+ yield* github.pullRequestForBranch(branch),
665
+ (pull) => pull.state === "open",
666
+ );
361
667
 
362
- const opened = yield* github.openPullRequest({
363
- head: branch,
364
- base: repo.baseBranch,
365
- title: outcome.title,
366
- body: `Closes #${issue}\n\n${outcome.body}\n\n---\nOpened by Chernabog for an unattended run. A person reviews and merges.`,
668
+ const opened = yield* Option.match(existing, {
669
+ onSome: Effect.succeed,
670
+ onNone: () =>
671
+ github.openPullRequest({
672
+ head: branch,
673
+ base: repo.baseBranch,
674
+ title: outcome.title,
675
+ body: `Closes #${issue}\n\n${outcome.body}\n\n---\n${footer(shipping)}`,
676
+ }),
367
677
  });
368
678
 
679
+ if (shipping) {
680
+ yield* github.addLabel(opened.number, repo.labels.ship);
681
+ }
682
+
369
683
  return { number: opened.number, url: opened.url };
370
684
  }),
371
685
  PullRequestRef,
@@ -374,27 +688,42 @@ export const openPullRequest = (issue: number, outcome: ImplementOutcome) =>
374
688
  const CI_POLL = Duration.minutes(1);
375
689
 
376
690
  const CiReading = Schema.Union([
377
- Schema.Struct({ state: Schema.Literal('pending'), waitingOn: Schema.Array(Schema.String) }),
378
- Schema.Struct({ state: Schema.Literal('green') }),
379
- Schema.Struct({ state: Schema.Literal('red'), failedChecks: Schema.Array(Schema.String) }),
691
+ Schema.Struct({ state: Schema.Literal("pending"), waitingOn: Schema.Array(Schema.String) }),
692
+ Schema.Struct({ state: Schema.Literal("green") }),
693
+ Schema.Struct({ state: Schema.Literal("red"), failedChecks: Schema.Array(Schema.String) }),
380
694
  ]);
381
695
 
382
696
  type CiReading = typeof CiReading.Type;
383
697
 
384
- // Polls the pull request's checks durably until they stop pending, or a person is needed.
385
- const awaitChecks = (pullRequest: number, round: number) =>
698
+ // Polls the pull request's checks durably until they stop pending, or limits.ciTimeout passes.
699
+ const awaitChecks = (pullRequest: number, round: number, options: RepeatOptions) =>
386
700
  Effect.gen(function* () {
387
701
  const repo = yield* Repo;
388
- const maxPolls = Math.max(1, Math.ceil(Duration.toMillis(repo.limits.ciTimeout) / Duration.toMillis(CI_POLL)));
389
- let reading: CiReading = { state: 'pending', waitingOn: [] };
390
702
 
391
- for (let poll = 1; reading.state === 'pending'; poll++) {
703
+ const maxPolls = Math.max(
704
+ 1,
705
+ Math.ceil(Duration.toMillis(repo.limits.ciTimeout) / Duration.toMillis(CI_POLL)),
706
+ );
707
+
708
+ let reading: CiReading = { state: "pending", waitingOn: [] };
709
+
710
+ for (let poll = 1; reading.state === "pending"; poll++) {
392
711
  if (poll > maxPolls) {
393
- return yield* new NeedsHuman({ reason: `CI on #${pullRequest} is still pending after ${Duration.format(Duration.fromInputUnsafe(repo.limits.ciTimeout))}` });
712
+ return yield* new CiTimedOut({
713
+ pullRequest,
714
+ after: Duration.format(Duration.fromInputUnsafe(repo.limits.ciTimeout)),
715
+ });
394
716
  }
395
717
 
396
- if (poll > 1) yield* sleep(`ci-${round}-wait-${poll}`, CI_POLL);
397
- reading = yield* activity(`ci-${round}-${poll}`, GitHub.use((github) => github.ciState(pullRequest)), CiReading);
718
+ if (poll > 1) {
719
+ yield* sleep(named(options, `ci-${round}-wait-${poll}`), CI_POLL);
720
+ }
721
+
722
+ reading = yield* activity(
723
+ named(options, `ci-${round}-${poll}`),
724
+ GitHub.use((github) => github.ciState(pullRequest)),
725
+ CiReading,
726
+ );
398
727
  }
399
728
 
400
729
  return reading;
@@ -404,71 +733,123 @@ export type CiBranch = AuthorSession & { readonly branch: string };
404
733
 
405
734
  // Waits durably for the pull request's checks. On red, the agent reads the
406
735
  // failure, fixes, commits, and the branch is pushed again, up to
407
- // limits.ciRounds times.
408
- export const waitForCi = (pullRequest: number, worktree: string, target: CiBranch) =>
736
+ // limits.ciRounds times. Fails with CiTimedOut when the checks stay pending
737
+ // past limits.ciTimeout, and as push does for a fix it can't push.
738
+ export const waitForCi = (
739
+ pullRequest: number,
740
+ worktree: string,
741
+ target: CiBranch,
742
+ options: RepeatOptions = {},
743
+ ) =>
409
744
  Effect.gen(function* () {
410
745
  const repo = yield* Repo;
411
746
 
412
747
  for (let round = 1; ; round++) {
413
- const reading = yield* awaitChecks(pullRequest, round);
748
+ const reading = yield* awaitChecks(pullRequest, round, options);
414
749
 
415
- if (reading.state !== 'red') return;
750
+ if (reading.state !== "red") {
751
+ return;
752
+ }
416
753
 
417
- const failed = reading.failedChecks.join(', ');
754
+ const failed = reading.failedChecks.join(", ");
418
755
 
419
- if (round > repo.limits.ciRounds) return yield* new NeedsHuman({ reason: `CI is still red after ${repo.limits.ciRounds} fix attempts: ${failed}` });
756
+ if (round > repo.limits.ciRounds) {
757
+ return yield* new NeedsHuman({
758
+ reason: `CI is still red after ${repo.limits.ciRounds} fix attempts: ${failed}`,
759
+ });
760
+ }
420
761
 
421
762
  yield* fixWithAgent(
422
- `fix-ci-${round}`,
763
+ named(options, `fix-ci-${round}`),
423
764
  worktree,
424
765
  [
425
766
  `CI failed on pull request #${pullRequest}: ${failed}.`,
426
767
  `Read why with \`gh run list --branch ${target.branch} --limit 5\` and \`gh run view <run id> --log-failed\`.`,
427
- 'Fix the cause and commit. A failure unrelated to your change may be re-run once with `gh run rerun <run id> --failed`. Then answer again.',
428
- ].join('\n'),
768
+ "Fix the cause and commit. A failure unrelated to your change may be re-run once with `gh run rerun <run id> --failed`. Then answer again.",
769
+ ].join("\n"),
429
770
  target,
430
771
  );
431
- yield* push(`push-ci-${round}`, worktree, target.branch);
772
+ yield* push(named(options, `push-ci-${round}`), worktree, target.branch, {
773
+ withPerson: target.withPerson === true,
774
+ });
432
775
  }
433
776
  });
434
777
 
778
+ const askForReview = (pullRequest: number, options: HandOffOptions) => {
779
+ if (options.needsReview) {
780
+ return requestReview(pullRequest).pipe(Effect.asVoid);
781
+ }
782
+
783
+ return Effect.void;
784
+ };
785
+
786
+ // Whether hand-off asks the team's reviewer pool for a review. A flow that
787
+ // reviews the pull request itself says false.
788
+ export type HandOffOptions = { readonly needsReview: boolean };
789
+
435
790
  // Hands the green pull request to review: the review trigger if the repo has
436
- // one, the needs-review label, and a closing comment on the issue.
437
- export const handOff = (issue: number, pullRequest: PullRequestRef, outcome: ImplementOutcome) =>
791
+ // one, a review requested of one reviewer from the pool (needs-review for a
792
+ // person without one) unless the options leave it off, and a closing comment
793
+ // on the issue.
794
+ export const handOff = (
795
+ issue: number,
796
+ pullRequest: PullRequestRef,
797
+ outcome: ImplementOutcome,
798
+ options: HandOffOptions = { needsReview: true },
799
+ ) =>
438
800
  activity(
439
- 'hand-off',
801
+ "hand-off",
440
802
  Effect.gen(function* () {
441
803
  const github = yield* GitHub;
442
804
  const repo = yield* Repo;
443
805
  const run = yield* Run;
444
806
 
445
- if (Option.isSome(repo.reviewTrigger)) yield* github.comment(pullRequest.number, repo.reviewTrigger.value);
807
+ if (Option.isSome(repo.reviewTrigger)) {
808
+ yield* github.comment(pullRequest.number, repo.reviewTrigger.value);
809
+ }
446
810
 
447
811
  // The fix flow resumes this session to answer a review.
448
- const session = { adapter: repo.agent, sessionId: sessionIdFor(run.runId, 'implement'), issue, branch: branchFor(issue) };
449
- yield* github.comment(pullRequest.number, `Implemented by ${repo.agent} for #${issue}. ${sessionMarker.write(session)}`);
450
- yield* github.addLabel(pullRequest.number, repo.labels.needsReview);
812
+ const session = {
813
+ adapter: repo.agent,
814
+ sessionId: sessionIdFor(run.runId, "implement"),
815
+ issue,
816
+ branch: branchFor(issue),
817
+ };
818
+
819
+ yield* github.comment(
820
+ pullRequest.number,
821
+ `Implemented by ${repo.agent} for #${issue}. ${sessionMarker.write(session)}`,
822
+ );
823
+
451
824
  yield* github.removeLabel(issue, repo.labels.inProgress);
452
- yield* github.comment(issue, `Pull request ready for review: ${pullRequest.url}\n\n${outcome.summary}`);
825
+ yield* github.comment(
826
+ issue,
827
+ `Pull request ready for review: ${pullRequest.url}\n\n${outcome.summary}`,
828
+ );
453
829
 
454
830
  return `#${issue}: ${pullRequest.url} is ready for review`;
455
831
  }),
456
832
  Schema.String,
457
- );
833
+ ).pipe(Effect.tap(() => askForReview(pullRequest.number, options)));
458
834
 
459
835
  // Labels the work item for a person and says why. No flow picks it up again.
460
836
  export const handToHuman = (issue: number, reason: string, pullRequest: Option.Option<number>) =>
461
837
  activity(
462
- 'needs-human',
838
+ "needs-human",
463
839
  Effect.gen(function* () {
464
840
  const github = yield* GitHub;
465
841
  const repo = yield* Repo;
466
842
  yield* github.addLabel(issue, repo.labels.needsHuman);
467
843
  yield* github.removeLabel(issue, repo.labels.inProgress);
468
844
 
469
- if (Option.isSome(pullRequest)) yield* github.addLabel(pullRequest.value, repo.labels.needsHuman);
845
+ if (Option.isSome(pullRequest)) {
846
+ yield* github.addLabel(pullRequest.value, repo.labels.needsHuman);
847
+ }
470
848
 
471
- yield* github.comment(issue, `Chernabog stopped and needs a person: ${reason}\n\nThe branch \`${branchFor(issue)}\` and its worktree are left as they are.`);
849
+ yield* github.comment(
850
+ issue,
851
+ `Chernabog stopped and needs a person: ${reason}\n\nThe branch \`${branchFor(issue)}\` and its worktree are left as they are.`,
852
+ );
472
853
 
473
854
  return `#${issue} needs a person: ${reason}`;
474
855
  }),
@@ -477,33 +858,3 @@ export const handToHuman = (issue: number, reason: string, pullRequest: Option.O
477
858
 
478
859
  // Ends the run as waiting on a person, once the issue says why.
479
860
  export const endForPerson = (summary: string) => Effect.fail(new NeedsHuman({ reason: summary }));
480
-
481
- // The whole default flow, for a flow file that wants it as it is.
482
- export const workflow = (item: WorkItem) =>
483
- Effect.gen(function* () {
484
- const issue = yield* issueOf(item);
485
- const { branch } = yield* claim(issue);
486
- let pullRequest = Option.none<number>();
487
- const toPerson = (reason: string) => handToHuman(issue, reason, pullRequest).pipe(Effect.flatMap(endForPerson));
488
-
489
- return yield* Effect.gen(function* () {
490
- const worktree = yield* prepareWorktree(branch);
491
- const outcome = yield* implementWithAgent(issue, worktree);
492
-
493
- if (outcome.status === 'needs-clarification') return yield* askForClarification(issue, outcome).pipe(Effect.flatMap(endForPerson));
494
-
495
- return yield* Effect.gen(function* () {
496
- yield* localGate(worktree);
497
- yield* push('push', worktree, branch);
498
- const opened = yield* openPullRequest(issue, outcome);
499
- pullRequest = Option.some(opened.number);
500
- yield* waitForCi(opened.number, worktree, { ...thisRunsSession, branch });
501
-
502
- return yield* handOff(issue, opened, outcome);
503
- }).pipe(Effect.catchTag('NeedsHuman', (needsHuman) => toPerson(needsHuman.reason)));
504
- }).pipe(
505
- // Any other failure once the issue is claimed hands it to a person, rather
506
- // than leaving it claimed with nobody working on it.
507
- Effect.catchTag('StepFailed', (failed) => toPerson(`${failed.step}: ${failed.message}`)),
508
- );
509
- });