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