@chernabog/sdk 0.4.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plan.ts ADDED
@@ -0,0 +1,762 @@
1
+ // The building blocks of the `plan` recipe: the agent reads a spec issue and
2
+ // the code, and proposes the tasks the spec splits into and which blocks
3
+ // which; the code checks the plan and adds a verify task, a person approves it
4
+ // on the spec, and the spec becomes an epic of sub-issues, each linked to what
5
+ // blocks it. The agent answers with data only: each task's labels decide which
6
+ // of the repo's flows picks it up.
7
+
8
+ import type * as Duration from "effect/Duration";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Option from "effect/Option";
11
+ import * as Schema from "effect/Schema";
12
+
13
+ import { NeedsHuman, StepFailed } from "./errors.ts";
14
+ import { activity, awaitSignal, type FlowLabel } from "./flow.ts";
15
+ import {
16
+ askForClarification as askImplementClarification,
17
+ branchFor,
18
+ issueItem,
19
+ sessionIdFor,
20
+ } from "./implement.ts";
21
+ import type { Json } from "./json.ts";
22
+ import { hasMarker, planMarker, planNodeMarker } from "./markers.ts";
23
+ import { renderPrompt } from "./prompt.ts";
24
+ import {
25
+ Agent,
26
+ type Comment,
27
+ GitHub,
28
+ type Issue,
29
+ type Labels,
30
+ Repo,
31
+ Run,
32
+ type WorkItem,
33
+ Worktree,
34
+ } from "./services.ts";
35
+
36
+ // The labels of a plan's life on its spec: queued, proposed and waiting on a
37
+ // person, approved, and made into an epic.
38
+ export const LABELS = {
39
+ plan: "auto:plan",
40
+ proposed: "auto:plan-proposed",
41
+ approved: "auto:plan-approved",
42
+ epic: "auto:epic",
43
+ } as const;
44
+
45
+ // For a flow's `labels`, so `chernabog labels` creates them.
46
+ export const flowLabels: ReadonlyArray<FlowLabel> = [
47
+ {
48
+ name: LABELS.plan,
49
+ color: "5319e7",
50
+ description: "Chernabog drafts a plan of sub-issues for this spec",
51
+ },
52
+ {
53
+ name: LABELS.proposed,
54
+ color: "fbca04",
55
+ description: "A plan is posted on this spec and waits for a person",
56
+ },
57
+ {
58
+ name: LABELS.approved,
59
+ color: "0e8a16",
60
+ description: "A person approved the plan: Chernabog makes its sub-issues",
61
+ },
62
+ { name: LABELS.epic, color: "3e4b9e", description: "An epic of sub-issues a plan made" },
63
+ ];
64
+
65
+ // Who takes a task: an agent unattended (auto:eligible), a person with an
66
+ // agent (`chernabog start`), or a person alone, for a decision (auto:needs-human).
67
+ export const Kind = Schema.Literals(["auto", "hybrid", "human"]);
68
+
69
+ export type Kind = typeof Kind.Type;
70
+
71
+ const isKind = Schema.is(Kind);
72
+
73
+ // One task. `kind` is checked in code rather than by the schema, so a plan
74
+ // with an unknown kind goes back to the agent instead of failing the step.
75
+ export const PlanNode = Schema.Struct({
76
+ key: Schema.String,
77
+ title: Schema.String,
78
+ body: Schema.String,
79
+ kind: Schema.String,
80
+ blockedBy: Schema.Array(Schema.String),
81
+ });
82
+
83
+ export type PlanNode = typeof PlanNode.Type;
84
+
85
+ export const Plan = Schema.Array(PlanNode);
86
+
87
+ export type Plan = typeof Plan.Type;
88
+
89
+ export const PlanDraft = Schema.Struct({
90
+ status: Schema.Literals(["plan", "needs-clarification"]),
91
+ summary: Schema.String,
92
+ nodes: Plan,
93
+ questions: Schema.optionalKey(Schema.String),
94
+ });
95
+
96
+ export type PlanDraft = typeof PlanDraft.Type;
97
+
98
+ export const planDraftJsonSchema = {
99
+ type: "object",
100
+ properties: {
101
+ status: { type: "string", enum: ["plan", "needs-clarification"] },
102
+ summary: {
103
+ type: "string",
104
+ description: "The plan in two or three sentences: how the work splits and why in this order",
105
+ },
106
+ nodes: {
107
+ type: "array",
108
+ description: "The tasks, each one reviewable pull request; empty for needs-clarification",
109
+ items: {
110
+ type: "object",
111
+ properties: {
112
+ key: {
113
+ type: "string",
114
+ description: "Stable within the plan: lowercase letters, digits and dashes",
115
+ },
116
+ title: { type: "string", description: "The issue title" },
117
+ body: {
118
+ type: "string",
119
+ description: "The issue body in Markdown: what to do, and its acceptance criteria",
120
+ },
121
+ kind: { type: "string", enum: ["auto", "hybrid", "human"] },
122
+ blockedBy: {
123
+ type: "array",
124
+ items: { type: "string" },
125
+ description: "Keys of the tasks that must land before this one starts",
126
+ },
127
+ },
128
+ required: ["key", "title", "body", "kind", "blockedBy"],
129
+ additionalProperties: false,
130
+ },
131
+ },
132
+ questions: {
133
+ type: "string",
134
+ description: "For needs-clarification: numbered questions, each led by a recommendation",
135
+ },
136
+ },
137
+ required: ["status", "summary", "nodes"],
138
+ additionalProperties: false,
139
+ } satisfies Json;
140
+
141
+ // The task the code adds last, blocked by every other.
142
+ export const VERIFY = "verify";
143
+
144
+ const KEY = /^[a-z0-9][a-z0-9-]*$/;
145
+
146
+ const sizeProblems = (size: number, limit: number) => {
147
+ if (size === 0) {
148
+ return ["the plan has no tasks"];
149
+ }
150
+
151
+ if (size > limit) {
152
+ return [`the plan has ${size} tasks, and may have at most ${limit}`];
153
+ }
154
+
155
+ return [];
156
+ };
157
+
158
+ const keyProblems = (keys: ReadonlyArray<string>) => {
159
+ const repeated = [...new Set(keys.filter((key, index) => keys.indexOf(key) !== index))];
160
+
161
+ return [
162
+ ...repeated.map((key) => `key \`${key}\` names more than one task`),
163
+ ...keys.flatMap((key) => {
164
+ if (key === VERIFY) {
165
+ return [`key \`${VERIFY}\` is kept for the verify task Chernabog adds`];
166
+ }
167
+
168
+ if (!KEY.test(key)) {
169
+ return [`key \`${key}\` must be lowercase letters, digits and dashes`];
170
+ }
171
+
172
+ return [];
173
+ }),
174
+ ];
175
+ };
176
+
177
+ const nodeProblems = (node: PlanNode, known: ReadonlySet<string>) => [
178
+ ...Option.toArray(
179
+ Option.liftPredicate(
180
+ `task \`${node.key}\` has kind \`${node.kind}\`; it must be auto, hybrid or human`,
181
+ () => !isKind(node.kind),
182
+ ),
183
+ ),
184
+ ...Option.toArray(
185
+ Option.liftPredicate(`task \`${node.key}\` has no title`, () => node.title.trim() === ""),
186
+ ),
187
+ ...node.blockedBy
188
+ .filter((blocker) => !known.has(blocker))
189
+ .map((blocker) => `task \`${node.key}\` is blocked by \`${blocker}\`, which no task is`),
190
+ ];
191
+
192
+ // The tasks that never become free to start, by taking away, round by round,
193
+ // those whose blockers have all been taken away.
194
+ const cycleProblems = (nodes: Plan, known: ReadonlySet<string>) => {
195
+ const waiting = new Map(
196
+ nodes.map((node) => [node.key, node.blockedBy.filter((blocker) => known.has(blocker))]),
197
+ );
198
+
199
+ for (let freed = true; freed;) {
200
+ freed = false;
201
+
202
+ for (const [key, blockers] of waiting) {
203
+ if (blockers.every((blocker) => !waiting.has(blocker))) {
204
+ waiting.delete(key);
205
+ freed = true;
206
+ }
207
+ }
208
+ }
209
+
210
+ if (waiting.size === 0) {
211
+ return [];
212
+ }
213
+
214
+ return [
215
+ `blockedBy forms a cycle among ${[...waiting.keys()].map((key) => `\`${key}\``).join(", ")}`,
216
+ ];
217
+ };
218
+
219
+ // What is wrong with a plan, if anything: its size, keys that repeat or
220
+ // can't be used, unknown kinds, blockers no task is, and cycles.
221
+ export const checkPlan = (nodes: Plan, limit: number): ReadonlyArray<string> => {
222
+ const known = new Set(nodes.map((node) => node.key));
223
+
224
+ return [
225
+ ...sizeProblems(nodes.length, limit),
226
+ ...keyProblems(nodes.map((node) => node.key)),
227
+ ...nodes.flatMap((node) => nodeProblems(node, known)),
228
+ ...cycleProblems(nodes, known),
229
+ ];
230
+ };
231
+
232
+ const HEADING = /^(#{1,6})\s/;
233
+
234
+ const headingLevel = (line: string) =>
235
+ Option.map(Option.fromNullishOr(HEADING.exec(line)), (match) => match[1].length);
236
+
237
+ // The spec's section headed "Acceptance criteria", up to the next heading at
238
+ // its level or above. None when the spec has no such heading.
239
+ export const acceptanceCriteria = (body: string): Option.Option<string> => {
240
+ const lines = body.split("\n");
241
+ const start = lines.findIndex((line) => /^#{1,6}\s+acceptance criteria/i.test(line.trim()));
242
+
243
+ return Option.flatMap(
244
+ Option.liftPredicate(start, (found) => found >= 0),
245
+ (found) =>
246
+ Option.map(headingLevel(lines[found].trim()), (level) => {
247
+ const rest = lines.slice(found + 1);
248
+
249
+ const end = rest.findIndex((line) =>
250
+ Option.exists(headingLevel(line), (other) => other <= level),
251
+ );
252
+
253
+ if (end >= 0) {
254
+ return rest.slice(0, end).join("\n").trim();
255
+ }
256
+
257
+ return rest.join("\n").trim();
258
+ }),
259
+ );
260
+ };
261
+
262
+ // The plan with the verify task added: a person checks what merged against
263
+ // the spec's acceptance criteria once every other task is closed.
264
+ export const withVerify = (spec: Issue, nodes: Plan): Plan => [
265
+ ...nodes,
266
+ {
267
+ key: VERIFY,
268
+ title: `Verify: ${spec.title}`,
269
+ body: [
270
+ `Check that the work planned for #${spec.number} meets its acceptance criteria, now that every other task has landed.`,
271
+ "",
272
+ "## Acceptance criteria",
273
+ "",
274
+ Option.getOrElse(
275
+ acceptanceCriteria(spec.body),
276
+ () =>
277
+ `#${spec.number} names none under that heading: check the work against the whole spec.`,
278
+ ),
279
+ ].join("\n"),
280
+ kind: "human",
281
+ blockedBy: nodes.map((node) => node.key),
282
+ },
283
+ ];
284
+
285
+ const quoted = (text: string) => text.replace(/"/g, "#quot;");
286
+
287
+ // The plan as a Mermaid graph, each arrow from a task to one it blocks.
288
+ export const mermaid = (nodes: Plan) => {
289
+ const ids = new Map(nodes.map((node, index) => [node.key, `t${index + 1}`]));
290
+ const idOf = (key: string) => ids.get(key) ?? key;
291
+
292
+ return [
293
+ "```mermaid",
294
+ "graph TD",
295
+ ...nodes.map(
296
+ (node) => ` ${idOf(node.key)}["${quoted(`${node.key}: ${node.title} (${node.kind})`)}"]`,
297
+ ),
298
+ ...nodes.flatMap((node) =>
299
+ node.blockedBy.map((blocker) => ` ${idOf(blocker)} --> ${idOf(node.key)}`),
300
+ ),
301
+ "```",
302
+ ].join("\n");
303
+ };
304
+
305
+ const roundOf = (round: number) =>
306
+ Option.match(
307
+ Option.liftPredicate(round, (later) => later > 1),
308
+ { onNone: () => "", onSome: (later) => ` (round ${later})` },
309
+ );
310
+
311
+ const blockersOf = (node: PlanNode) =>
312
+ Option.match(
313
+ Option.liftPredicate(node.blockedBy, (blockers) => blockers.length > 0),
314
+ {
315
+ onNone: () => "Blocked by nothing.",
316
+ onSome: (blockers) => `Blocked by ${blockers.map((key) => `\`${key}\``).join(", ")}.`,
317
+ },
318
+ );
319
+
320
+ // The plan's comment on its spec: the summary, the graph, each task folded,
321
+ // and how to answer it.
322
+ export const planComment = (round: number, summary: string, nodes: Plan) =>
323
+ [
324
+ `## Proposed plan${roundOf(round)}`,
325
+ "",
326
+ summary,
327
+ "",
328
+ mermaid(nodes),
329
+ "",
330
+ ...nodes.flatMap((node) => [
331
+ `<details><summary><code>${node.key}</code>: ${node.title} (${node.kind})</summary>`,
332
+ "",
333
+ blockersOf(node),
334
+ "",
335
+ node.body,
336
+ "",
337
+ "</details>",
338
+ "",
339
+ ]),
340
+ `To approve it, add the label \`${LABELS.approved}\`. To change it, comment with what to change, and Chernabog drafts it again.`,
341
+ "",
342
+ planMarker.write({ round }),
343
+ ].join("\n");
344
+
345
+ // The comments of the repo's owners, members and collaborators since the
346
+ // latest plan was posted, other than Chernabog's own: a person's answer to it.
347
+ const sinceLatestPlan = (comments: ReadonlyArray<Comment>) => {
348
+ const posted = comments.findLastIndex((comment) => Option.isSome(planMarker.read(comment.body)));
349
+
350
+ return comments
351
+ .slice(posted + 1)
352
+ .filter((comment) => posted >= 0 && comment.trusted && !hasMarker(comment.body));
353
+ };
354
+
355
+ const feedbackOf = (comments: ReadonlyArray<Comment>) =>
356
+ Option.liftPredicate(
357
+ sinceLatestPlan(comments)
358
+ .map((comment) => `${comment.author}: ${comment.body}`)
359
+ .join("\n\n"),
360
+ (text) => text !== "",
361
+ );
362
+
363
+ // Specs whose posted plan a person has answered, as signals to the run
364
+ // waiting on each: `approved` when it carries the approval label, or
365
+ // `changes-requested` when someone commented since. Never starts a run.
366
+ export const answers = Effect.gen(function* () {
367
+ const github = yield* GitHub;
368
+ const items: Array<WorkItem> = [];
369
+
370
+ for (const spec of yield* github.issuesLabelled(LABELS.proposed)) {
371
+ let signal = Option.some("approved");
372
+
373
+ if (!spec.labels.includes(LABELS.approved)) {
374
+ signal = Option.as(
375
+ feedbackOf(yield* github.trustedComments(spec.number)),
376
+ "changes-requested",
377
+ );
378
+ }
379
+
380
+ for (const found of Option.toArray(signal)) {
381
+ items.push({ ...issueItem(spec), signals: [found], wakeOnly: true });
382
+ }
383
+ }
384
+
385
+ return items;
386
+ });
387
+
388
+ const RESUME_PROMPT =
389
+ "You were interrupted. Continue from where you left off, then give your final answer in the required format.";
390
+
391
+ // The prompt that starts a plan, from .chernabog/prompts/plan.md.
392
+ const specPrompt = (spec: number) =>
393
+ Effect.gen(function* () {
394
+ const github = yield* GitHub;
395
+ const repo = yield* Repo;
396
+ const details = yield* github.issue(spec);
397
+ const comments = yield* github.trustedComments(spec);
398
+
399
+ return yield* renderPrompt("plan", {
400
+ repo: repo.slug,
401
+ issue: spec,
402
+ title: details.title,
403
+ body: details.body,
404
+ comments: comments
405
+ .filter((comment) => !hasMarker(comment.body))
406
+ .map((comment) => `${comment.author}: ${comment.body}`),
407
+ base: repo.baseBranch,
408
+ planNodes: repo.limits.planNodes,
409
+ humanOnly: repo.humanOnly,
410
+ notes: repo.notes,
411
+ });
412
+ });
413
+
414
+ type Asking = { readonly prompt: string; readonly resume: string };
415
+
416
+ // The read-only checkout the agent drafts a spec's plan in.
417
+ export const planCheckout = (spec: number) => `plan-issue-${spec}`;
418
+
419
+ // Removes the plan's checkout once the run is done with it, however it ends:
420
+ // an epic, questions on the spec, or a person's.
421
+ export const doneDrafting = (spec: number) =>
422
+ activity(
423
+ `clean-up-${planCheckout(spec)}`,
424
+ Worktree.use((worktree) => worktree.remove(planCheckout(spec))),
425
+ );
426
+
427
+ // Asks the agent for a plan in a read-only checkout of the base branch, in
428
+ // the run's one planning session: `resume` when the session exists, and
429
+ // otherwise `prompt`, which must stand on its own.
430
+ const askForPlan = <E, R>(name: string, spec: number, asking: Effect.Effect<Asking, E, R>) =>
431
+ activity(
432
+ name,
433
+ Effect.gen(function* () {
434
+ const repo = yield* Repo;
435
+ const run = yield* Run;
436
+ const { prompt, resume } = yield* asking;
437
+
438
+ const worktree = yield* (yield* Worktree).checkout(
439
+ planCheckout(spec),
440
+ `origin/${repo.baseBranch}`,
441
+ );
442
+
443
+ const result = yield* (yield* Agent).run({
444
+ cwd: worktree,
445
+ prompt,
446
+ sessionId: sessionIdFor(run.runId, "plan"),
447
+ resumePrompt: Option.some(resume),
448
+ outputSchema: Option.some(planDraftJsonSchema),
449
+ adapter: Option.none(),
450
+ });
451
+
452
+ return yield* Schema.decodeUnknownEffect(PlanDraft)(result.output).pipe(
453
+ Effect.mapError(
454
+ (issue) => new StepFailed({ step: name, message: `agent answer: ${issue.message}` }),
455
+ ),
456
+ );
457
+ }),
458
+ PlanDraft,
459
+ );
460
+
461
+ const followUp = (spec: number, text: string) =>
462
+ Effect.map(specPrompt(spec), (prompt) => ({ prompt: `${prompt}\n\n${text}`, resume: text }));
463
+
464
+ // The agent drafts the plan, or redrafts it with what a person asked to change.
465
+ export const draft = (spec: number, round: number, changes: Option.Option<string>) =>
466
+ askForPlan(
467
+ `draft-plan-${round}`,
468
+ spec,
469
+ Option.match(changes, {
470
+ onNone: () => Effect.map(specPrompt(spec), (prompt) => ({ prompt, resume: RESUME_PROMPT })),
471
+ onSome: (asked) =>
472
+ followUp(
473
+ spec,
474
+ `A person read the plan you proposed and asked for changes:\n\n${asked}\n\nDraft the plan again with them, and give your final answer.`,
475
+ ),
476
+ }),
477
+ );
478
+
479
+ const fix = (spec: number, round: number, attempt: number, problems: ReadonlyArray<string>) =>
480
+ askForPlan(
481
+ `fix-plan-${round}-${attempt}`,
482
+ spec,
483
+ followUp(
484
+ spec,
485
+ `The plan fails Chernabog's checks:\n\n${problems.map((problem) => `- ${problem}`).join("\n")}\n\nFix it, and give your final answer again.`,
486
+ ),
487
+ );
488
+
489
+ // Drafts the plan and checks it, sending the agent back with what is wrong up
490
+ // to limits.planRounds times. A plan that still fails needs a person.
491
+ export const checkedDraft = (spec: number, round: number, changes: Option.Option<string>) =>
492
+ Effect.gen(function* () {
493
+ const repo = yield* Repo;
494
+ let answer = yield* draft(spec, round, changes);
495
+
496
+ for (let attempt = 1; answer.status === "plan"; attempt++) {
497
+ const problems = checkPlan(answer.nodes, repo.limits.planNodes);
498
+
499
+ if (problems.length === 0) {
500
+ return answer;
501
+ }
502
+
503
+ if (attempt > repo.limits.planRounds) {
504
+ return yield* new NeedsHuman({
505
+ reason: `the plan still fails its checks after ${repo.limits.planRounds} attempts to fix it:\n\n${problems.map((problem) => `- ${problem}`).join("\n")}`,
506
+ });
507
+ }
508
+
509
+ answer = yield* fix(spec, round, attempt, problems);
510
+ }
511
+
512
+ return answer;
513
+ });
514
+
515
+ // Posts the agent's questions on the spec, releases the claim and stops, as
516
+ // implement does. The requeue hint names auto:plan.
517
+ export const askForClarification = (spec: number, answer: PlanDraft) =>
518
+ askImplementClarification(
519
+ spec,
520
+ {
521
+ status: "needs-clarification",
522
+ summary: answer.summary,
523
+ title: "",
524
+ body: "",
525
+ questions: answer.questions ?? answer.summary,
526
+ },
527
+ { label: LABELS.plan },
528
+ );
529
+
530
+ // Posts the plan on the spec, with the verify task added, and labels it as
531
+ // waiting on a person. Returns the plan as posted, which is the one created.
532
+ export const propose = (spec: number, round: number, answer: PlanDraft) =>
533
+ activity(
534
+ `propose-plan-${round}`,
535
+ Effect.gen(function* () {
536
+ const github = yield* GitHub;
537
+ const plan = withVerify(yield* github.issue(spec), answer.nodes);
538
+ yield* github.comment(spec, planComment(round, answer.summary, plan));
539
+ yield* github.addLabel(spec, LABELS.proposed);
540
+
541
+ return plan;
542
+ }),
543
+ Plan,
544
+ );
545
+
546
+ // Parks the run until a person answers the plan: `approved`,
547
+ // `changes-requested`, or `timeout` once `timeout` passes.
548
+ export const awaitAnswer = (round: number, timeout: Duration.Input) =>
549
+ awaitSignal(["approved", "changes-requested"], { id: `plan-${round}`, timeout });
550
+
551
+ // What a person asked to change, from their comments since the plan.
552
+ export const changesAsked = (spec: number, round: number) =>
553
+ activity(
554
+ `changes-asked-${round}`,
555
+ Effect.gen(function* () {
556
+ const github = yield* GitHub;
557
+ yield* github.removeLabel(spec, LABELS.proposed);
558
+
559
+ return Option.getOrElse(
560
+ feedbackOf(yield* github.trustedComments(spec)),
561
+ () => "Nothing in the comments says what; make the plan clearer.",
562
+ );
563
+ }),
564
+ Schema.String,
565
+ );
566
+
567
+ const labelsFor = (kind: string, labels: Labels): ReadonlyArray<string> => {
568
+ if (kind === "auto") {
569
+ return [labels.eligible];
570
+ }
571
+
572
+ if (kind === "human") {
573
+ return [labels.needsHuman];
574
+ }
575
+
576
+ return [];
577
+ };
578
+
579
+ const NOTES: Readonly<Record<Kind, string>> = {
580
+ auto: "An agent takes it once nothing blocks it.",
581
+ hybrid: "For a person and an agent together: `chernabog start` with this issue's number.",
582
+ human: "For a person to decide.",
583
+ };
584
+
585
+ const noteFor = (kind: string) =>
586
+ Option.match(Option.liftPredicate(kind, isKind), {
587
+ onNone: () => "",
588
+ onSome: (known) => NOTES[known],
589
+ });
590
+
591
+ const nodeBody = (spec: number, node: PlanNode) =>
592
+ [
593
+ node.body,
594
+ "",
595
+ "---",
596
+ `Task \`${node.key}\` of the plan for #${spec}. ${noteFor(node.kind)}`,
597
+ "",
598
+ planNodeMarker.write({ spec, key: node.key }),
599
+ ].join("\n");
600
+
601
+ const Made = Schema.Array(
602
+ Schema.Struct({ number: Schema.Finite, body: Schema.OptionFromNullOr(Schema.String) }),
603
+ );
604
+
605
+ // The issues this spec's plan already made, by key: its sub-issues, and the
606
+ // issues this login opened lately, for one made just before a crash and not
607
+ // yet a sub-issue.
608
+ const madeFor = (spec: number) =>
609
+ Effect.gen(function* () {
610
+ const github = yield* GitHub;
611
+ const repo = yield* Repo;
612
+ const login = yield* github.login;
613
+
614
+ const recent = yield* github.request(
615
+ "GET",
616
+ `/repos/${repo.slug}/issues?state=all&creator=${encodeURIComponent(login)}&sort=created&direction=desc&per_page=100`,
617
+ Option.none(),
618
+ );
619
+
620
+ const found = [
621
+ ...(yield* github.subIssues(spec)).map((issue) => ({
622
+ number: issue.number,
623
+ body: Option.some(issue.body),
624
+ })),
625
+ ...Option.getOrElse(Schema.decodeUnknownOption(Made)(recent), () => []),
626
+ ];
627
+
628
+ const made = new Map<string, number>();
629
+
630
+ for (const issue of found) {
631
+ for (const marker of Option.toArray(Option.flatMap(issue.body, planNodeMarker.read))) {
632
+ if (marker.spec === spec) {
633
+ made.set(marker.key, issue.number);
634
+ }
635
+ }
636
+ }
637
+
638
+ return made;
639
+ });
640
+
641
+ export const Created = Schema.Array(Schema.Struct({ key: Schema.String, issue: Schema.Finite }));
642
+
643
+ export type Created = typeof Created.Type;
644
+
645
+ // Makes each task an issue and a sub-issue of the spec, links each to the
646
+ // tasks that block it, and only then labels them, so no flow picks one up
647
+ // before its blockers are linked. Safe to repeat: a task's issue is found by
648
+ // its marker, and links and labels already there stay.
649
+ export const create = (spec: number, plan: Plan) =>
650
+ activity(
651
+ "create-issues",
652
+ Effect.gen(function* () {
653
+ const github = yield* GitHub;
654
+ const repo = yield* Repo;
655
+ const made = yield* madeFor(spec);
656
+
657
+ for (const node of plan) {
658
+ if (!made.has(node.key)) {
659
+ const issue = yield* github.createIssue({
660
+ title: node.title,
661
+ body: nodeBody(spec, node),
662
+ labels: [],
663
+ });
664
+
665
+ made.set(node.key, issue.number);
666
+ }
667
+ }
668
+
669
+ const numberOf = (key: string) =>
670
+ Effect.fromOption(Option.fromUndefinedOr(made.get(key))).pipe(
671
+ Effect.mapError(
672
+ () => new StepFailed({ step: "create-issues", message: `no issue for \`${key}\`` }),
673
+ ),
674
+ );
675
+
676
+ const created: Array<Created[number]> = [];
677
+
678
+ for (const node of plan) {
679
+ const issue = yield* numberOf(node.key);
680
+ yield* github.addSubIssue(spec, issue);
681
+
682
+ for (const blocker of node.blockedBy) {
683
+ yield* github.addBlockedBy(issue, yield* numberOf(blocker));
684
+ }
685
+
686
+ created.push({ key: node.key, issue });
687
+ }
688
+
689
+ for (const node of plan) {
690
+ for (const label of labelsFor(node.kind, repo.labels)) {
691
+ yield* github.addLabel(yield* numberOf(node.key), label);
692
+ }
693
+ }
694
+
695
+ return created;
696
+ }),
697
+ Created,
698
+ );
699
+
700
+ // Labels the spec an epic, which the epic flow picks up, releases the claim,
701
+ // and says on it which issue each task became.
702
+ export const becomeEpic = (spec: number, plan: Plan, created: Created) =>
703
+ activity(
704
+ "epic",
705
+ Effect.gen(function* () {
706
+ const github = yield* GitHub;
707
+ const repo = yield* Repo;
708
+ yield* github.addLabel(spec, LABELS.epic);
709
+
710
+ for (const label of [LABELS.approved, LABELS.proposed, repo.labels.inProgress]) {
711
+ yield* github.removeLabel(spec, label);
712
+ }
713
+
714
+ yield* github.deleteBranch(branchFor(spec));
715
+
716
+ const lines = created.map(({ issue, key }) => {
717
+ const title = Option.match(Option.fromUndefinedOr(plan.find((node) => node.key === key)), {
718
+ onNone: () => key,
719
+ onSome: (node) => node.title,
720
+ });
721
+
722
+ return `- #${issue} \`${key}\`: ${title}`;
723
+ });
724
+
725
+ yield* github.comment(
726
+ spec,
727
+ [
728
+ `The plan is approved: this issue is now an epic of ${created.length} sub-issues.`,
729
+ "",
730
+ ...lines,
731
+ ].join("\n"),
732
+ );
733
+
734
+ return `#${spec}: an epic of ${created.length} sub-issues`;
735
+ }),
736
+ Schema.String,
737
+ );
738
+
739
+ // Labels the spec for a person, says why, and releases the claim, so
740
+ // labelling it auto:plan again starts over.
741
+ export const handToHuman = (spec: number, reason: string) =>
742
+ activity(
743
+ "needs-human",
744
+ Effect.gen(function* () {
745
+ const github = yield* GitHub;
746
+ const repo = yield* Repo;
747
+ yield* github.addLabel(spec, repo.labels.needsHuman);
748
+
749
+ for (const label of [LABELS.proposed, repo.labels.inProgress]) {
750
+ yield* github.removeLabel(spec, label);
751
+ }
752
+
753
+ yield* github.deleteBranch(branchFor(spec));
754
+ yield* github.comment(
755
+ spec,
756
+ `Chernabog stopped planning and needs a person: ${reason}\n\nTo plan it again, apply \`${LABELS.plan}\`.`,
757
+ );
758
+
759
+ return `#${spec} needs a person: ${reason}`;
760
+ }),
761
+ Schema.String,
762
+ );