@kitman-sh/software-engineering 0.14.8 → 0.15.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 CHANGED
@@ -1,6 +1,5 @@
1
1
  import {
2
- agentWork,
3
- agentWorkOnce,
2
+ agent,
4
3
  artifact,
5
4
  ask,
6
5
  call,
@@ -10,21 +9,24 @@ import {
10
9
  createTasks,
11
10
  CreateTasksResult,
12
11
  defineLoop,
13
- integrationBranch,
12
+ integrated,
14
13
  isPlanApproval,
14
+ leftForPickup,
15
15
  mergeChangeRequest,
16
16
  PlanAddressed,
17
17
  PlanApproval,
18
18
  PlanDeclined,
19
19
  type PlanReview,
20
- type PlanTicket,
21
20
  readPlanReview,
22
21
  planWaves,
23
- UnattendedPlanApproval,
24
- type IntegrationBranch
22
+ IntegrationBranch,
23
+ PlanTicket,
24
+ step,
25
+ UnattendedPlanApproval
25
26
  } from '@kitman-sh/sdk/loop'
26
27
  import * as Effect from 'effect/Effect'
27
28
  import * as Schema from 'effect/Schema'
29
+ import { reviewer } from './agents'
28
30
  import build from './build'
29
31
  import {
30
32
  DeclinedConcern,
@@ -36,17 +38,21 @@ import {
36
38
  type DisputedConcern
37
39
  } from './plan-review'
38
40
 
41
+ const planner = agent('planner')
42
+
39
43
  const Input = Schema.Struct({
40
- /** What to plan. */
41
- words: Schema.String,
42
- /** The Team's default RepoBinding when left out. */
43
- repoBindingId: Schema.optional(Schema.String),
44
- /** The branch the plan is delivered to; each repository's default branch when left out. */
45
- branch: Schema.optional(Schema.String),
46
- /** The Project the plan's Tasks land in. */
47
- projectId: Schema.optional(Schema.String),
48
- /** Approves each revision and implements it when nobody answers within an hour; files it as Tasks otherwise. */
49
- implement: Schema.optional(Schema.Boolean)
44
+ words: Schema.String.annotate({ description: 'What to plan.' }),
45
+ repoBindingId: Schema.optional(Schema.String).annotate({
46
+ description: "The Team's default RepoBinding when left out."
47
+ }),
48
+ branch: Schema.optional(Schema.String).annotate({
49
+ description: "The branch the plan is delivered to; each repository's default branch when left out."
50
+ }),
51
+ projectId: Schema.optional(Schema.String).annotate({ description: "The Project the plan's Tasks land in." }),
52
+ implement: Schema.optional(Schema.Boolean).annotate({
53
+ description:
54
+ 'Approves each revision and implements it when nobody answers within an hour; files it as Tasks otherwise.'
55
+ })
50
56
  })
51
57
 
52
58
  const Plan = Schema.Struct({
@@ -83,6 +89,13 @@ const ReworkedAnswer = Schema.Struct({
83
89
  comments: Schema.Struct({ addressed: Schema.Array(PlanAddressed), declined: Schema.Array(PlanDeclined) })
84
90
  })
85
91
 
92
+ /** A concern the plan reviewer still holds after the revision, and why the planner did not act on it. */
93
+ const Disputed = Schema.Struct({
94
+ ticket: Schema.optional(Schema.String),
95
+ concern: Schema.String,
96
+ declined: Schema.optional(Schema.String)
97
+ })
98
+
86
99
  /** The criteria a ticket names that the base branch already meets. */
87
100
  const CriteriaCheck = Schema.Struct({
88
101
  alreadyMet: Schema.Array(Schema.Struct({ key: Schema.String, criterion: Schema.String }))
@@ -101,22 +114,36 @@ const TicketResult = Schema.Struct({
101
114
 
102
115
  type TicketResult = typeof TicketResult.Type
103
116
 
117
+ const Undelivered = Schema.Struct({ repoBindingId: Schema.String, reason: Schema.String })
118
+
104
119
  const Output = Schema.Struct({
105
- title: Schema.String,
106
- outOfScope: Schema.Array(Schema.String),
107
- afterMerge: Schema.Array(Schema.String),
108
- /** Tickets the base already does all of, left out of the plan. */
109
- rejected: Schema.Array(Rejected),
110
- /** Why the Run stopped where it did, when it was not a person's choice. */
111
- stopped: Schema.optional(Schema.String),
112
- implemented: Schema.Boolean,
113
- tickets: Schema.Array(TicketResult),
114
- /** One ChangeRequest per repository with merged work, from its integration branch into its base branch. */
115
- deliveries: Schema.Array(ChangeRequestResult),
116
- /** The Task made for each ticket by File as Tasks. */
117
- tasks: Schema.optional(CreateTasksResult.fields.tasks),
118
- /** The ChangeRequest for the ADRs and glossary the grilling changed. */
119
- docs: Schema.optional(ChangeRequestResult)
120
+ title: Schema.String.annotate({ description: "The plan's title." }),
121
+ outOfScope: Schema.Array(Schema.String).annotate({
122
+ description: 'What the plan deliberately leaves out, one item each.'
123
+ }),
124
+ afterMerge: Schema.Array(Schema.String).annotate({ description: 'Outcomes only visible once the work merges.' }),
125
+ rejected: Schema.Array(Rejected).annotate({
126
+ description: 'Tickets the base already does all of, left out of the plan.'
127
+ }),
128
+ stopped: Schema.optional(Schema.String).annotate({
129
+ description: "Why the Run stopped where it did, when it was not a person's choice."
130
+ }),
131
+ implemented: Schema.Boolean.annotate({
132
+ description: 'Whether the plan was implemented, rather than only filed as Tasks.'
133
+ }),
134
+ tickets: Schema.Array(TicketResult).annotate({ description: 'Each ticket of the plan and what became of it.' }),
135
+ deliveries: Schema.Array(ChangeRequestResult).annotate({
136
+ description: 'One ChangeRequest per repository with merged work, from its integration branch into its base branch.'
137
+ }),
138
+ undelivered: Schema.optional(Schema.Array(Undelivered)).annotate({
139
+ description: 'Each repository with merged work that got no delivery, and why.'
140
+ }),
141
+ tasks: Schema.optional(CreateTasksResult.fields.tasks).annotate({
142
+ description: 'The Task made for each ticket by File as Tasks.'
143
+ }),
144
+ docs: Schema.optional(ChangeRequestResult).annotate({
145
+ description: 'The ChangeRequest for the ADRs and glossary the grilling changed.'
146
+ })
120
147
  })
121
148
 
122
149
  const menu = ['Implement now', 'File as Tasks', 'Refine', 'Finish'] as const
@@ -133,12 +160,6 @@ const menuDescriptions: Record<Choice, string> = {
133
160
  Finish: 'Ends the Run with the plan as it is.'
134
161
  }
135
162
 
136
- const onConflict = ['Rebuild on the integration branch', 'Skip'] as const
137
-
138
- const onHeld = ['Merge again', ...onConflict] as const
139
-
140
- const onUnverified = ['Skip', 'Merge'] as const
141
-
142
163
  const onFailure = ['Retry with a steer', 'Skip it and its dependents', 'Stop here'] as const
143
164
 
144
165
  const ticketRules = [
@@ -254,11 +275,10 @@ const answeredText = ({ addressed, declined }: Answered) =>
254
275
 
255
276
  const rework = (step: string, prompt: string, answered: Answered | undefined) =>
256
277
  answered === undefined
257
- ? agentWorkOnce(step, { agent: 'planner', prompt: [prompt, ticketRules].join('\n\n'), output: Reworked }).pipe(
278
+ ? planner(step, { prompt: [prompt, ticketRules].join('\n\n'), output: Reworked }).pipe(
258
279
  Effect.map(({ declined, ...plan }) => ({ plan: { plan }, declined }))
259
280
  )
260
- : agentWorkOnce(step, {
261
- agent: 'planner',
281
+ : planner(step, {
262
282
  prompt: [prompt, ticketRules, answeredText(answered)].join('\n\n'),
263
283
  output: ReworkedAnswer
264
284
  }).pipe(
@@ -272,17 +292,16 @@ const rework = (step: string, prompt: string, answered: Answered | undefined) =>
272
292
  * A plan revision ready for a person: the plan reviewer checked it, the planner answered its concerns, and its criteria
273
293
  * were checked against the base, which rejects a ticket with nothing left to do.
274
294
  */
275
- const checked = (draft: Draft, revision: number, asked: readonly string[]) =>
295
+ const checked = (draft: Draft, asked: readonly string[]) =>
276
296
  Effect.gen(function* () {
277
- const reviewed = yield* reviewPlan(`plan-review:${revision}`, {
297
+ const reviewed = yield* reviewPlan('plan-review', {
278
298
  plan: draft,
279
299
  asked: asked.join('\n\n'),
280
300
  text: ({ plan }) => planText(plan),
281
301
  revise: (step, prompt) => rework(step, prompt, draft.answered)
282
302
  })
283
303
 
284
- const check = yield* agentWork(`criteria-check:${revision}`, {
285
- agent: 'reviewer',
304
+ const check = yield* reviewer('criteria-check', {
286
305
  prompt: criteriaPrompt(reviewed.plan.plan),
287
306
  output: CriteriaCheck
288
307
  })
@@ -303,17 +322,16 @@ const checked = (draft: Draft, revision: number, asked: readonly string[]) =>
303
322
  */
304
323
  const storePlan = (
305
324
  { plan, disputed, answered }: Draft & { readonly disputed: readonly DisputedConcern[] },
306
- suffix: string,
307
325
  revision: number
308
326
  ) =>
309
327
  Effect.gen(function* () {
310
- yield* artifact(`spec${suffix}`, {
328
+ yield* artifact('spec', {
311
329
  kind: 'plan_spec',
312
330
  title: plan.title,
313
331
  text: plan.spec,
314
332
  data: { outOfScope: [...plan.outOfScope] }
315
333
  })
316
- yield* artifact(`tickets${suffix}`, {
334
+ yield* artifact('tickets', {
317
335
  kind: 'plan_tickets',
318
336
  title: `Tickets for ${plan.title}`,
319
337
  text: plan.tickets.map(ticketText).join('\n\n'),
@@ -326,7 +344,7 @@ const storePlan = (
326
344
  ...(outcome === undefined ? undefined : { outcome })
327
345
  }))
328
346
  })
329
- yield* artifact(`document${suffix}`, {
347
+ yield* artifact('document', {
330
348
  kind: 'plan_document',
331
349
  title: plan.title,
332
350
  text: documentText(plan, disputed),
@@ -376,39 +394,303 @@ const buildWords = (ticket: PlanTicket) =>
376
394
  ...outOfScopeText(ticket)
377
395
  ].join('\n\n')
378
396
 
379
- const settled = (ticket: PlanTicket, result: Omit<TicketResult, 'key' | 'title'>): TicketResult => ({
380
- key: ticket.key,
381
- title: ticket.title,
382
- ...result
397
+ export class Drafted extends Schema.TaggedClass<Drafted>()('Drafted', {
398
+ plan: Plan,
399
+ rejected: Schema.Array(Rejected),
400
+ revision: Schema.Int,
401
+ /** What the plan reviewer still disputes in this revision. */
402
+ disputed: Schema.Array(Disputed),
403
+ /** What the person asked for, in turn: the goal, then each review's comments and each refine's words. */
404
+ asked: Schema.Array(Schema.String),
405
+ /** The ChangeRequest for the ADR and glossary changes, which only the first revision opens. */
406
+ docs: Schema.optionalKey(ChangeRequestResult)
407
+ }) {}
408
+
409
+ export const drafted = step('drafted', {
410
+ payload: { words: Schema.String.annotate({ description: 'What to plan.' }) },
411
+ success: Drafted,
412
+ run: ({ words }) =>
413
+ Effect.gen(function* () {
414
+ const first = yield* planner('plan', { skill: 'grill-with-docs', prompt: planPrompt(words), output: Plan })
415
+
416
+ const docs =
417
+ first.docs === undefined
418
+ ? undefined
419
+ : yield* changeRequest('docs', { title: first.docs.title, body: first.docs.summary })
420
+
421
+ const asked = [words]
422
+ const { plan, rejected, disputed } = yield* checked({ plan: first }, asked)
423
+
424
+ yield* storePlan({ plan, disputed }, 1)
425
+
426
+ return new Drafted({
427
+ plan,
428
+ rejected,
429
+ revision: 1,
430
+ disputed,
431
+ asked,
432
+ ...(docs === undefined ? undefined : { docs })
433
+ })
434
+ })
383
435
  })
384
436
 
385
- /**
386
- * Builds a ticket from the integration head, then merges its ChangeRequest into the integration branch. When verify
387
- * never ran some of its tests, the user chooses to merge it or skip it. On a conflict the user chooses to rebuild from
388
- * the head as it is now, or to give the ticket up; on a merge the forge only holds back, also to merge it again.
389
- * `steer` is a person's words for a retry; `label` names its Steps apart from the first try's.
390
- */
391
- const buildTicket = (
392
- ticket: PlanTicket,
393
- start: IntegrationBranch,
394
- taskId: string | undefined,
395
- retry?: { readonly label: string; readonly steer: string }
396
- ) =>
397
- Effect.gen(function* () {
398
- let head = start
399
- const name = retry === undefined ? ticket.key : `${ticket.key}:${retry.label}`
437
+ export class PlanApproved extends Schema.TaggedClass<PlanApproved>()('PlanApproved', {
438
+ revision: Schema.Int,
439
+ /** Plan review passed it: the plan reviewer disputes nothing, or a person approved it over what it disputes. */
440
+ reviewed: Schema.Boolean
441
+ }) {}
442
+
443
+ export const planReviewed = step('planReviewed', {
444
+ payload: {
445
+ draft: Drafted,
446
+ implement: Schema.Boolean.annotate({ description: 'Approves the revision when nobody answers within an hour.' })
447
+ },
448
+ success: Schema.Union([PlanApproved, Drafted]),
449
+ key: ({ draft }) => String(draft.revision),
450
+ run: ({ draft: { plan, revision, disputed, asked }, implement }) =>
451
+ Effect.gen(function* () {
452
+ const answer = yield* ask('review', {
453
+ prompt: [
454
+ `Review revision ${revision} of the plan "${plan.title}": approve it, or request changes by commenting on what should change.`,
455
+ ...(disputed.length === 0
456
+ ? []
457
+ : [
458
+ `The plan reviewer still disputes ${disputed.length} point${disputed.length === 1 ? '' : 's'}, listed at the end of the plan.`
459
+ ])
460
+ ].join(' '),
461
+ freeText: true,
462
+ recommended: PlanApproval,
463
+ recommendationReason: 'Approve it once the plan reads right; until then the Run waits for you.',
464
+ ...(implement ? { default: UnattendedPlanApproval, timeout: '1 hour' } : { default: null }),
465
+ unattendedAuto: UnattendedPlanApproval
466
+ })
467
+
468
+ if (isPlanApproval(answer))
469
+ return new PlanApproved({ revision, reviewed: disputed.length === 0 || answer !== UnattendedPlanApproval })
470
+
471
+ const review = readPlanReview(answer, revision, documentText(plan, disputed))
472
+
473
+ const revised = yield* planner('revise-plan', {
474
+ prompt: revisePrompt(documentText(plan, disputed), review),
475
+ output: Revised
476
+ })
477
+
478
+ const { addressed, declined, ...next } = revised
479
+ const count = review.comments.length
480
+ const askedNow = [...asked, commentsText(review)]
481
+ const after = yield* checked({ plan: next, answered: { review, addressed, declined } }, askedNow)
482
+
483
+ yield* storePlan(after, revision + 1)
484
+ yield* artifact('changes', {
485
+ kind: 'plan_changes',
486
+ title: `Revision ${revision + 1} of ${after.plan.title}`,
487
+ text: changelog(plan, after.plan, `${count} review comment${count === 1 ? '' : 's'}`)
488
+ })
489
+
490
+ return new Drafted({
491
+ plan: after.plan,
492
+ rejected: after.rejected,
493
+ disputed: after.disputed,
494
+ revision: revision + 1,
495
+ asked: askedNow
496
+ })
497
+ })
498
+ })
499
+
500
+ export class ImplementNow extends Schema.TaggedClass<ImplementNow>()('ImplementNow', {}) {}
501
+
502
+ export class FileAsTasks extends Schema.TaggedClass<FileAsTasks>()('FileAsTasks', {}) {}
503
+
504
+ export class Refine extends Schema.TaggedClass<Refine>()('Refine', {}) {}
400
505
 
401
- for (let attempt = 1; ; attempt++) {
402
- const suffix = attempt === 1 ? '' : `:${attempt}`
506
+ export class Finish extends Schema.TaggedClass<Finish>()('Finish', {}) {}
403
507
 
508
+ export const chosen = step('chosen', {
509
+ payload: {
510
+ title: Schema.String.annotate({ description: "The plan's title." }),
511
+ filed: Schema.Boolean.annotate({ description: 'This revision is filed as Tasks already.' }),
512
+ implement: Schema.Boolean.annotate({ description: 'Implements the plan when nobody answers within an hour.' })
513
+ },
514
+ success: Schema.Union([ImplementNow, FileAsTasks, Refine, Finish]),
515
+ run: ({ title, filed: isFiled, implement }) =>
516
+ Effect.gen(function* () {
517
+ const options = menu.filter(option => !(option === 'File as Tasks' && isFiled))
518
+
519
+ const fallback: Choice = implement ? 'Implement now' : isFiled ? 'Finish' : 'File as Tasks'
520
+
521
+ const answer = yield* ask('next', {
522
+ prompt: `What next for the plan "${title}"?`,
523
+ options: options.map(option => ({ value: option, description: menuDescriptions[option] })),
524
+ recommended: fallback,
525
+ recommendationReason:
526
+ fallback === 'Implement now'
527
+ ? 'You asked for the plan to be implemented.'
528
+ : fallback === 'Finish'
529
+ ? 'The plan is filed as Tasks, so nothing is lost by finishing.'
530
+ : 'Filing keeps the plan as Tasks a person or a Build can pick up later.',
531
+ default: fallback,
532
+ timeout: '1 hour'
533
+ })
534
+
535
+ switch (answer) {
536
+ case 'Implement now':
537
+ return new ImplementNow({})
538
+ case 'File as Tasks':
539
+ return new FileAsTasks({})
540
+ case 'Refine':
541
+ return new Refine({})
542
+ case 'Finish':
543
+ return new Finish({})
544
+ }
545
+ })
546
+ })
547
+
548
+ export const refined = step('refined', {
549
+ payload: { draft: Drafted },
550
+ success: Drafted,
551
+ run: ({ draft: { plan, revision, disputed, asked } }) =>
552
+ Effect.gen(function* () {
553
+ const words = yield* ask('refine', {
554
+ prompt: 'What should change in the plan?',
555
+ freeText: true,
556
+ informationOnly: true,
557
+ recommendationReason: 'You chose to refine it, so only you know what should change.'
558
+ })
559
+
560
+ const changed = yield* planner('refine-plan', {
561
+ prompt: refinePrompt(documentText(plan, disputed), words),
562
+ output: Plan
563
+ })
564
+
565
+ const askedNow = [...asked, words]
566
+ const after = yield* checked({ plan: changed }, askedNow)
567
+
568
+ yield* storePlan(after, revision + 1)
569
+ yield* artifact('changes', {
570
+ kind: 'plan_changes',
571
+ title: `Revision ${revision + 1} of ${after.plan.title}`,
572
+ text: changelog(plan, after.plan, words)
573
+ })
574
+
575
+ return new Drafted({
576
+ plan: after.plan,
577
+ rejected: after.rejected,
578
+ disputed: after.disputed,
579
+ revision: revision + 1,
580
+ asked: askedNow
581
+ })
582
+ })
583
+ })
584
+
585
+ export class Filed extends Schema.TaggedClass<Filed>()('Filed', {
586
+ revision: Schema.Int,
587
+ tasks: CreateTasksResult.fields.tasks
588
+ }) {}
589
+
590
+ /** Holds the Tasks from pickup, so that Plan can build them itself. */
591
+ export const filed = step('filed', {
592
+ payload: {
593
+ tickets: Schema.Array(PlanTicket),
594
+ revision: Schema.Int,
595
+ projectId: Schema.optional(Schema.String).annotate({ description: 'The Project the Tasks land in.' }),
596
+ planReviewed: Schema.Boolean.annotate({
597
+ description: 'Plan review passed the tickets, so each Task records it and its first Build runs at lower effort.'
598
+ })
599
+ },
600
+ success: Filed,
601
+ run: ({ tickets, revision, projectId, planReviewed }) =>
602
+ Effect.map(
603
+ createTasks('file-tasks', {
604
+ tickets,
605
+ builds: true,
606
+ planReviewed,
607
+ ...(projectId === undefined ? undefined : { projectId })
608
+ }),
609
+ ({ tasks }) => new Filed({ revision, tasks })
610
+ )
611
+ })
612
+
613
+ const unmerged = {
614
+ repoBindingId: Schema.String,
615
+ changeRequest: Schema.optionalKey(ChangeRequestResult),
616
+ reason: Schema.String
617
+ }
618
+
619
+ export class Merged extends Schema.TaggedClass<Merged>()('Merged', {
620
+ repoBindingId: Schema.String,
621
+ changeRequest: ChangeRequestResult
622
+ }) {}
623
+
624
+ /** Its Build failed, or a person gave up on its merge. */
625
+ export class Failed extends Schema.TaggedClass<Failed>()('Failed', unmerged) {}
626
+
627
+ export class Skipped extends Schema.TaggedClass<Skipped>()('Skipped', {
628
+ ...unmerged,
629
+ /** It was skipped because it failed, so the Output says it failed. */
630
+ failed: Schema.optionalKey(Schema.Literal(true))
631
+ }) {}
632
+
633
+ /** A person stopped the whole plan. */
634
+ export class Stopped extends Schema.TaggedClass<Stopped>()('Stopped', unmerged) {}
635
+
636
+ const unmergedOf = ({ repoBindingId, changeRequest: open, reason }: Failed) => ({
637
+ repoBindingId,
638
+ reason,
639
+ ...(open === undefined ? undefined : { changeRequest: open })
640
+ })
641
+
642
+ const skippedUnbuilt = ({ key, title }: PlanTicket, reason: string): TicketResult => ({
643
+ key,
644
+ title,
645
+ status: 'skipped',
646
+ reason
647
+ })
648
+
649
+ const resultOf = ({ key, title }: PlanTicket, outcome: Merged | Failed | Skipped | Stopped): TicketResult => {
650
+ if (outcome._tag === 'Merged')
651
+ return {
652
+ key,
653
+ title,
654
+ status: 'merged',
655
+ repoBindingId: outcome.repoBindingId,
656
+ changeRequest: outcome.changeRequest
657
+ }
658
+
659
+ return {
660
+ key,
661
+ title,
662
+ status: outcome._tag === 'Skipped' && outcome.failed !== true ? 'skipped' : 'failed',
663
+ repoBindingId: outcome.repoBindingId,
664
+ ...(outcome.changeRequest === undefined ? undefined : { changeRequest: outcome.changeRequest }),
665
+ reason: outcome.reason
666
+ }
667
+ }
668
+
669
+ export class Built extends Schema.TaggedClass<Built>()('Built', {
670
+ changeRequest: ChangeRequestResult,
671
+ revision: Schema.String
672
+ }) {}
673
+
674
+ const buildOf = {
675
+ ticket: PlanTicket,
676
+ head: IntegrationBranch.annotate({ description: 'The integration branch and head it builds from.' }),
677
+ taskId: Schema.optional(Schema.String).annotate({ description: "The ticket's Task; none when it got none." }),
678
+ steer: Schema.optional(Schema.String).annotate({ description: "A person's words for a retry of a failed ticket." })
679
+ }
680
+
681
+ export const buildTried = step('buildTried', {
682
+ payload: buildOf,
683
+ success: Schema.Union([Built, Failed, Skipped]),
684
+ run: ({ ticket, head, taskId, steer }) =>
685
+ Effect.gen(function* () {
404
686
  const words =
405
- retry === undefined
687
+ steer === undefined
406
688
  ? taskId === undefined
407
689
  ? { words: buildWords(ticket) }
408
690
  : undefined
409
- : { words: `${buildWords(ticket)}\n\nAn earlier Build of this failed. ${retry.steer}` }
691
+ : { words: `${buildWords(ticket)}\n\nAn earlier Build of this failed. ${steer}` }
410
692
 
411
- const built = yield* call(`build:${name}${suffix}`, build, {
693
+ const built = yield* call('build', build, {
412
694
  ...words,
413
695
  ...(taskId === undefined ? undefined : { taskId }),
414
696
  repoBindingId: head.repoBindingId,
@@ -427,18 +709,15 @@ const buildTicket = (
427
709
  })
428
710
  )
429
711
 
430
- if (built instanceof ChildFailed)
431
- return settled(ticket, { status: 'failed', repoBindingId: head.repoBindingId, reason: built.reason })
432
-
433
- const delivered = { repoBindingId: head.repoBindingId, changeRequest: built.changeRequest }
712
+ if (built instanceof ChildFailed) return new Failed({ repoBindingId: head.repoBindingId, reason: built.reason })
434
713
 
435
714
  if (built.notRun !== undefined && built.notRun.length > 0) {
436
- const unverified = yield* ask(`unverified:${name}${suffix}`, {
715
+ const unverified = yield* ask('unverified', {
437
716
  prompt: `Verify never ran some tests of the ChangeRequest for ${ticket.key} (${built.changeRequest.url}):\n${built.notRun.map(item => `- ${item}`).join('\n')}\n\nMerge it once they pass by hand, or skip it and the tickets it blocks?`,
438
717
  options: [
439
718
  { value: 'Skip', description: 'Leaves it and the tickets it blocks unmerged.' },
440
719
  { value: 'Merge', description: 'Merges it into the integration branch, for when the tests pass by hand.' }
441
- ] satisfies { readonly value: (typeof onUnverified)[number]; readonly description: string }[],
720
+ ],
442
721
  recommended: 'Skip',
443
722
  recommendationReason: 'Nobody has seen these tests pass, so merging would land them as if they had.',
444
723
  default: 'Skip',
@@ -446,240 +725,385 @@ const buildTicket = (
446
725
  })
447
726
 
448
727
  if (unverified === 'Skip')
449
- return settled(ticket, { status: 'skipped', ...delivered, reason: 'Verify never ran some of its tests' })
728
+ return new Skipped({
729
+ repoBindingId: head.repoBindingId,
730
+ changeRequest: built.changeRequest,
731
+ reason: 'Verify never ran some of its tests'
732
+ })
450
733
  }
451
734
 
452
- const rebuild = {
453
- value: 'Rebuild on the integration branch',
454
- description: 'Builds the ticket again from the branch as it is now.'
455
- } as const
735
+ return new Built({ changeRequest: built.changeRequest, revision: built.revision })
736
+ })
737
+ })
738
+
739
+ export class MergeAgain extends Schema.TaggedClass<MergeAgain>()('MergeAgain', {}) {}
740
+
741
+ export class Rebuild extends Schema.TaggedClass<Rebuild>()('Rebuild', {}) {}
742
+
743
+ const rebuild = {
744
+ value: 'Rebuild on the integration branch',
745
+ description: 'Builds the ticket again from the branch as it is now.'
746
+ } as const
747
+
748
+ const skip = { value: 'Skip', description: 'Leaves it and the tickets it blocks undelivered.' } as const
749
+
750
+ export const mergeTried = step('mergeTried', {
751
+ payload: {
752
+ ticketKey: Schema.String,
753
+ head: IntegrationBranch,
754
+ changeRequest: ChangeRequestResult,
755
+ revision: Schema.String.annotate({ description: 'The head its Build verified, the only one that merges.' })
756
+ },
757
+ success: Schema.Union([Merged, MergeAgain, Rebuild, Failed]),
758
+ run: ({ ticketKey, head, changeRequest: open, revision }) =>
759
+ Effect.gen(function* () {
760
+ const delivery = { repoBindingId: head.repoBindingId, changeRequest: open }
456
761
 
457
- const skip = { value: 'Skip', description: 'Leaves it and the tickets it blocks undelivered.' } as const
458
- let choice: (typeof onHeld)[number] = 'Merge again'
459
- let refusal = `It conflicted with ${head.branch}`
762
+ // Only what the Build verified merges; a commit pushed to its branch since is rebuilt or skipped like a
763
+ // conflict. The integration branch's own ChangeRequest is verified again, so one behind it is rebased onto it.
764
+ const merged = yield* mergeChangeRequest('merge', { changeRequestId: open.id, head: revision, rebase: true })
460
765
 
461
- for (let again = 0; choice === 'Merge again'; again++) {
462
- const label = again === 0 ? suffix : `${suffix}:again:${again}`
766
+ if (merged.status === 'merged') return new Merged(delivery)
767
+ const request = `The ChangeRequest for ${ticketKey} (${open.url})`
463
768
 
464
- // Only what the Build verified merges; a commit pushed to its branch since is rebuilt or skipped like a
465
- // conflict. The integration branch's own ChangeRequest is verified again, so one behind it is rebased onto it.
466
- const merged = yield* mergeChangeRequest(`merge:${name}${label}`, {
467
- changeRequestId: built.changeRequest.id,
468
- head: built.revision,
469
- rebase: true
769
+ if (merged.status === 'conflict' && merged.reason === 'not_ready') {
770
+ const held = yield* ask('conflict', {
771
+ prompt: `${request} cannot merge into ${head.branch} yet: the forge holds it back, as for approvals, unresolved discussions, a draft or a pipeline that must pass first. Merge it again once that is settled, rebuild ${ticketKey} on the integration branch as it is now, or skip it and the tickets it blocks?`,
772
+ options: [
773
+ {
774
+ value: 'Merge again',
775
+ description: 'Tries the merge again, for once whatever holds it back is settled.'
776
+ },
777
+ rebuild,
778
+ skip
779
+ ],
780
+ recommended: 'Merge again',
781
+ recommendationReason:
782
+ 'Nothing conflicts, so a rebuild meets the same hold, and skipping also drops every ticket it blocks.',
783
+ default: 'Skip',
784
+ timeout: '1 hour'
470
785
  })
471
786
 
472
- if (merged.status === 'merged') return settled(ticket, { status: 'merged', ...delivered })
473
- const request = `The ChangeRequest for ${ticket.key} (${built.changeRequest.url})`
787
+ if (held === 'Merge again') return new MergeAgain({})
474
788
 
475
- if (merged.status === 'conflict' && merged.reason === 'not_ready') {
476
- refusal = `The forge held it back from ${head.branch}`
789
+ if (held === 'Rebuild on the integration branch') return new Rebuild({})
477
790
 
478
- choice = yield* ask(`conflict:${name}${label}`, {
479
- prompt: `${request} cannot merge into ${head.branch} yet: the forge holds it back, as for approvals, unresolved discussions, a draft or a pipeline that must pass first. Merge it again once that is settled, rebuild ${ticket.key} on the integration branch as it is now, or skip it and the tickets it blocks?`,
480
- options: [
481
- {
482
- value: 'Merge again',
483
- description: 'Tries the merge again, for once whatever holds it back is settled.'
484
- },
485
- rebuild,
486
- skip
487
- ] satisfies { readonly value: (typeof onHeld)[number]; readonly description: string }[],
488
- recommended: 'Merge again',
489
- recommendationReason:
490
- 'Nothing conflicts, so a rebuild meets the same hold, and skipping also drops every ticket it blocks.',
491
- default: 'Skip',
492
- timeout: '1 hour'
493
- })
494
- } else {
495
- const behind = merged.status === 'conflict' && merged.reason === 'behind'
496
- refusal = `${behind ? 'It stayed behind' : 'It conflicted with'} ${head.branch}`
497
-
498
- choice = yield* ask(`conflict:${name}${label}`, {
499
- prompt: `${request} ${merged.status === 'moved' ? 'changed after it was built' : `${behind ? 'is behind' : 'conflicts with'} ${head.branch}`}. Rebuild ${ticket.key} on the integration branch as it is now, or skip it and the tickets it blocks?`,
500
- options: [rebuild, skip] satisfies {
501
- readonly value: (typeof onConflict)[number]
502
- readonly description: string
503
- }[],
504
- recommended: 'Rebuild on the integration branch',
505
- recommendationReason:
506
- 'A rebuild on the current branch usually resolves a conflict, and skipping also drops every ticket it blocks.',
507
- default: 'Skip',
508
- timeout: '1 hour'
509
- })
510
- }
791
+ return new Failed({ ...delivery, reason: `The forge held it back from ${head.branch}` })
511
792
  }
512
793
 
513
- if (choice === 'Skip') return settled(ticket, { status: 'failed', ...delivered, reason: refusal })
794
+ const behind = merged.status === 'conflict' && merged.reason === 'behind'
514
795
 
515
- head = yield* integrationBranch(`rebuild-from:${name}:${attempt + 1}`, {
516
- repoBindingId: head.repoBindingId
796
+ const conflicting = yield* ask('conflict', {
797
+ prompt: `${request} ${merged.status === 'moved' ? 'changed after it was built' : `${behind ? 'is behind' : 'conflicts with'} ${head.branch}`}. Rebuild ${ticketKey} on the integration branch as it is now, or skip it and the tickets it blocks?`,
798
+ options: [rebuild, skip],
799
+ recommended: 'Rebuild on the integration branch',
800
+ recommendationReason:
801
+ 'A rebuild on the current branch usually resolves a conflict, and skipping also drops every ticket it blocks.',
802
+ default: 'Skip',
803
+ timeout: '1 hour'
517
804
  })
518
- }
519
- })
520
805
 
521
- const deliveryBody = (plan: Plan, results: readonly TicketResult[]) => {
806
+ if (conflicting === 'Rebuild on the integration branch') return new Rebuild({})
807
+
808
+ return new Failed({
809
+ ...delivery,
810
+ reason: `${behind ? 'It stayed behind' : 'It conflicted with'} ${head.branch}`
811
+ })
812
+ })
813
+ })
814
+
815
+ export const ticketBuilt = step('ticketBuilt', {
816
+ payload: buildOf,
817
+ success: Schema.Union([Merged, Failed, Skipped]),
818
+ key: ({ ticket }) => ticket.key,
819
+ run: ({ ticket, head: start, taskId, steer }) =>
820
+ Effect.gen(function* () {
821
+ let head = start
822
+
823
+ for (;;) {
824
+ const built = yield* buildTried({ ticket, head, taskId, steer })
825
+
826
+ if (built._tag !== 'Built') return built
827
+ const { changeRequest: open, revision } = built
828
+
829
+ const merged = yield* mergeTried({ ticketKey: ticket.key, head, changeRequest: open, revision }).pipe(
830
+ Effect.repeat({ while: tried => tried._tag === 'MergeAgain' })
831
+ )
832
+
833
+ if (merged._tag === 'Merged' || merged._tag === 'Failed') return merged
834
+
835
+ head = yield* integrated({ repoBindingId: head.repoBindingId })
836
+ }
837
+ })
838
+ })
839
+
840
+ export class Steer extends Schema.TaggedClass<Steer>()('Steer', { words: Schema.String }) {}
841
+
842
+ export class SkipIt extends Schema.TaggedClass<SkipIt>()('SkipIt', {}) {}
843
+
844
+ export class StopHere extends Schema.TaggedClass<StopHere>()('StopHere', {}) {}
845
+
846
+ export const failureAnswered = step('failureAnswered', {
847
+ payload: { ticketKey: Schema.String, reason: Schema.String },
848
+ success: Schema.Union([Steer, SkipIt, StopHere]),
849
+ run: ({ ticketKey, reason }) =>
850
+ Effect.gen(function* () {
851
+ const choice = yield* ask('failed', {
852
+ prompt: `The Build of ${ticketKey} failed: ${reason}. Retry it with a steer, skip it and the tickets it blocks, or stop here?`,
853
+ options: onFailure,
854
+ recommended: 'Retry with a steer',
855
+ recommendationReason:
856
+ 'The reason it failed is above, so a steer can aim the retry at it; skipping also drops the tickets it blocks.',
857
+ default: 'Skip it and its dependents',
858
+ timeout: '1 hour'
859
+ })
860
+
861
+ if (choice === 'Skip it and its dependents') return new SkipIt({})
862
+
863
+ if (choice === 'Stop here') return new StopHere({})
864
+
865
+ const words = yield* ask('steer', {
866
+ prompt: `What should the retry of ${ticketKey} do differently?`,
867
+ freeText: true,
868
+ recommended: `Address the failure: ${reason}`,
869
+ recommendationReason: 'Pointing the retry at the reason it failed is the least a steer should do.',
870
+ default: null
871
+ })
872
+
873
+ return new Steer({ words })
874
+ })
875
+ })
876
+
877
+ export const retried = step('retried', {
878
+ payload: {
879
+ ticket: PlanTicket,
880
+ failure: Failed,
881
+ repoBindingId: Schema.optional(Schema.String).annotate({
882
+ description: "The ticket's RepoBinding; the Team's default when left out."
883
+ }),
884
+ taskId: buildOf.taskId
885
+ },
886
+ success: Schema.Union([Merged, Skipped, Stopped]),
887
+ key: ({ ticket }) => ticket.key,
888
+ run: ({ ticket, failure: first, repoBindingId, taskId }) =>
889
+ Effect.gen(function* () {
890
+ let failure = first
891
+
892
+ for (;;) {
893
+ const answer = yield* failureAnswered({ ticketKey: ticket.key, reason: failure.reason })
894
+
895
+ if (answer._tag === 'SkipIt') return new Skipped({ ...unmergedOf(failure), failed: true })
896
+
897
+ if (answer._tag === 'StopHere') return new Stopped(unmergedOf(failure))
898
+
899
+ const head = yield* integrated({ repoBindingId })
900
+ const again = yield* ticketBuilt({ ticket, head, taskId, steer: answer.words })
901
+
902
+ if (again._tag !== 'Failed') return again
903
+ failure = again
904
+ }
905
+ })
906
+ })
907
+
908
+ const deliveryBody = (title: string, results: readonly TicketResult[]) => {
522
909
  const line = (result: TicketResult) =>
523
910
  result.status === 'merged' && result.changeRequest !== undefined
524
911
  ? `- **${result.key}** [${result.title}](${result.changeRequest.url}); its evidence is on that ChangeRequest`
525
912
  : `- **${result.key}** ${result.title}: ${result.reason ?? result.status}`
526
913
 
527
- const section = (title: string, status: TicketResult['status']) => {
914
+ const section = (heading: string, status: TicketResult['status']) => {
528
915
  const lines = results.flatMap(result => (result.status === status ? [line(result)] : []))
529
916
 
530
- return lines.length === 0 ? [] : [`## ${title}`, lines.join('\n')]
917
+ return lines.length === 0 ? [] : [`## ${heading}`, lines.join('\n')]
531
918
  }
532
919
 
533
920
  return [
534
- `Delivers the plan "${plan.title}".`,
921
+ `Delivers the plan "${title}".`,
535
922
  ...section('Merged', 'merged'),
536
923
  ...section('Failed', 'failed'),
537
924
  ...section('Skipped', 'skipped')
538
925
  ].join('\n\n')
539
926
  }
540
927
 
541
- type Filed = { readonly revision: number; readonly tasks: typeof CreateTasksResult.Type.tasks }
928
+ export class Delivered extends Schema.TaggedClass<Delivered>()('Delivered', {
929
+ deliveries: Schema.Array(ChangeRequestResult),
930
+ undelivered: Schema.Array(Undelivered)
931
+ }) {}
932
+
933
+ export const delivered = step('delivered', {
934
+ payload: {
935
+ title: Schema.String.annotate({ description: "The plan's title." }),
936
+ results: Schema.Array(TicketResult),
937
+ integrations: Schema.Array(Schema.Struct({ repoBindingId: Schema.String, branch: Schema.String })).annotate({
938
+ description: "Each repository's integration branch."
939
+ })
940
+ },
941
+ success: Delivered,
942
+ run: ({ title, results, integrations }) =>
943
+ Effect.gen(function* () {
944
+ const merged = [
945
+ ...new Set(results.flatMap(result => (result.status === 'merged' ? (result.repoBindingId ?? []) : [])))
946
+ ].flatMap(repo => integrations.filter(integration => integration.repoBindingId === repo))
947
+
948
+ const opened = yield* Effect.forEach(merged, ({ repoBindingId, branch }) =>
949
+ changeRequest(`deliver:${repoBindingId}`, {
950
+ title,
951
+ body: deliveryBody(
952
+ title,
953
+ results.filter(result => result.repoBindingId === repoBindingId || result.repoBindingId === undefined)
954
+ ),
955
+ source: branch,
956
+ repoBindingId
957
+ }).pipe(Effect.map(delivery => ({ repoBindingId, branch, delivery })))
958
+ )
959
+
960
+ return new Delivered({
961
+ deliveries: opened.flatMap(({ delivery }) =>
962
+ delivery.status === 'open' ? [{ id: delivery.id, number: delivery.number, url: delivery.url }] : []
963
+ ),
964
+ undelivered: opened.flatMap(({ repoBindingId, branch, delivery }) =>
965
+ delivery.status === 'open'
966
+ ? []
967
+ : [
968
+ {
969
+ repoBindingId,
970
+ reason:
971
+ delivery.status === 'nothing'
972
+ ? `${branch} has nothing its target lacks`
973
+ : delivery.team === 'no Team'
974
+ ? `a ChangeRequest in no Team is open from ${branch}`
975
+ : `${delivery.team} holds the ChangeRequest from ${branch}`
976
+ }
977
+ ]
978
+ )
979
+ })
980
+ })
981
+ })
982
+
983
+ /** The draft a person approved, and whether plan review passed it. */
984
+ const approvedDraft = (first: Drafted, implement: boolean) =>
985
+ Effect.gen(function* () {
986
+ let draft = first
987
+
988
+ for (;;) {
989
+ const reviewed = yield* planReviewed({ draft, implement })
990
+
991
+ if (reviewed._tag === 'PlanApproved') return { draft, reviewed: reviewed.reviewed }
992
+ draft = reviewed
993
+ }
994
+ })
542
995
 
543
996
  /**
544
- * Makes a Task per ticket (or takes those File as Tasks made of this revision), then builds the tickets in waves on an
545
- * integration branch per repository: a wave starts from the integration heads once its blockers' ChangeRequests are
546
- * merged, so each Build contains its blockers' code. A failed ticket asks: retry it with a person's steer, skip it and
547
- * its dependents (the default), or stop. Finally one ChangeRequest per repository delivers the integration branch.
997
+ * Builds the tickets in waves on an integration branch per repository: a wave starts from the integration heads once
998
+ * its blockers' ChangeRequests are merged, so each Build contains its blockers' code. A failed ticket is retried,
999
+ * skipped with its dependents, or stops the rest, as a person says.
548
1000
  */
549
- const implement = (
550
- input: typeof Input.Type,
551
- plan: Plan,
552
- revision: number,
553
- planReviewed: boolean,
554
- filed: Filed | undefined
555
- ) =>
1001
+ const builtInWaves = (input: typeof Input.Type, plan: Plan, tasks: Filed['tasks']) =>
556
1002
  Effect.gen(function* () {
557
- const tasks =
558
- filed?.revision === revision
559
- ? filed.tasks
560
- : (yield* createTasks('tasks', {
561
- tickets: plan.tickets,
562
- builds: true,
563
- planReviewed,
564
- ...(input.projectId === undefined ? undefined : { projectId: input.projectId })
565
- })).tasks
566
-
567
1003
  const taskOf = new Map(tasks.map(task => [task.key, task.taskId]))
568
1004
  const results = new Map<string, TicketResult>()
1005
+ const branches = new Map<string, string>()
1006
+ const repoOf = (ticket: PlanTicket) => ticket.repoBindingId ?? input.repoBindingId
569
1007
  const waves = yield* planWaves(plan.tickets)
570
1008
  let stopped: string | undefined
571
1009
 
572
- for (const [index, wave] of waves.entries()) {
1010
+ for (const wave of waves) {
573
1011
  const ready: PlanTicket[] = []
574
1012
 
575
1013
  for (const ticket of wave) {
576
- const unmerged = ticket.blockedBy.find(key => results.get(key)?.status !== 'merged')
577
-
578
- if (stopped !== undefined) results.set(ticket.key, settled(ticket, { status: 'skipped', reason: stopped }))
579
- else if (unmerged === undefined) ready.push(ticket)
580
- else
581
- results.set(
582
- ticket.key,
583
- settled(ticket, { status: 'skipped', reason: `blocked by ${unmerged}, which was not merged` })
584
- )
1014
+ const blocker = ticket.blockedBy.find(key => results.get(key)?.status !== 'merged')
1015
+
1016
+ if (stopped !== undefined) results.set(ticket.key, skippedUnbuilt(ticket, stopped))
1017
+ else if (blocker === undefined) ready.push(ticket)
1018
+ else results.set(ticket.key, skippedUnbuilt(ticket, `blocked by ${blocker}, which was not merged`))
585
1019
  }
586
1020
 
587
- const repoOf = (ticket: PlanTicket) => ticket.repoBindingId ?? input.repoBindingId
588
1021
  const heads = new Map<string | undefined, IntegrationBranch>()
589
1022
 
590
- for (const repo of new Set(ready.map(repoOf)))
591
- heads.set(
592
- repo,
593
- yield* integrationBranch(
594
- `integration:wave-${index + 1}:${repo ?? 'default'}`,
595
- repo === undefined ? {} : { repoBindingId: repo }
596
- )
597
- )
1023
+ for (const repoBindingId of new Set(ready.map(repoOf))) {
1024
+ const head = yield* integrated({ repoBindingId })
598
1025
 
599
- const built = yield* Effect.forEach(
600
- ready.flatMap(ticket => {
601
- const head = heads.get(repoOf(ticket))
602
-
603
- return head === undefined ? [] : [buildTicket(ticket, head, taskOf.get(ticket.key))]
604
- }),
605
- building => building,
606
- { concurrency: 'unbounded' }
607
- )
608
-
609
- for (const first of built) {
610
- const ticket = ready.find(entry => entry.key === first.key)
611
- let result = first
612
-
613
- for (let retry = 1; ticket !== undefined && result.status === 'failed' && stopped === undefined; retry++) {
614
- const choice = yield* ask(`failed:${ticket.key}:${retry}`, {
615
- prompt: `The Build of ${ticket.key} failed: ${result.reason ?? 'no reason given'}. Retry it with a steer, skip it and the tickets it blocks, or stop here?`,
616
- options: onFailure,
617
- recommended: 'Retry with a steer',
618
- recommendationReason:
619
- 'The reason it failed is above, so a steer can aim the retry at it; skipping also drops the tickets it blocks.',
620
- default: 'Skip it and its dependents',
621
- timeout: '1 hour'
622
- })
1026
+ heads.set(repoBindingId, head)
1027
+ branches.set(head.repoBindingId, head.branch)
1028
+ }
623
1029
 
624
- if (choice === 'Skip it and its dependents') break
1030
+ const starts = ready.flatMap(ticket => {
1031
+ const head = heads.get(repoOf(ticket))
625
1032
 
626
- if (choice === 'Stop here') {
627
- stopped = `Stopped after ${ticket.key} failed`
628
- break
629
- }
630
-
631
- const steer = yield* ask(`steer:${ticket.key}:${retry}`, {
632
- prompt: `What should the retry of ${ticket.key} do differently?`,
633
- freeText: true,
634
- recommended: `Address the failure: ${result.reason ?? 'find out why it failed first'}`,
635
- recommendationReason: 'Pointing the retry at the reason it failed is the least a steer should do.',
636
- default: null
637
- })
1033
+ return head === undefined ? [] : [{ ticket, head, taskId: taskOf.get(ticket.key) }]
1034
+ })
638
1035
 
639
- const head = yield* integrationBranch(`integration:${ticket.key}:retry-${retry}`, {
640
- ...(repoOf(ticket) === undefined ? undefined : { repoBindingId: repoOf(ticket) })
641
- })
1036
+ const built = yield* Effect.forEach(
1037
+ starts,
1038
+ start => Effect.map(ticketBuilt(start), outcome => ({ ...start, outcome })),
1039
+ { concurrency: 'unbounded' }
1040
+ )
642
1041
 
643
- result = yield* buildTicket(ticket, head, taskOf.get(ticket.key), { label: `retry-${retry}`, steer })
644
- }
1042
+ for (const { ticket, taskId, outcome } of built) {
1043
+ const ended =
1044
+ outcome._tag === 'Failed' && stopped === undefined
1045
+ ? yield* retried({ ticket, failure: outcome, repoBindingId: repoOf(ticket), taskId })
1046
+ : outcome
645
1047
 
646
- results.set(result.key, result)
1048
+ if (ended._tag === 'Stopped') stopped = `Stopped after ${ticket.key} failed`
1049
+ results.set(ticket.key, resultOf(ticket, ended))
647
1050
  }
648
1051
  }
649
1052
 
650
- const ordered = plan.tickets.flatMap(ticket => results.get(ticket.key) ?? [])
1053
+ return {
1054
+ tickets: plan.tickets.flatMap(ticket => results.get(ticket.key) ?? []),
1055
+ integrations: [...branches].map(([repoBindingId, branch]) => ({ repoBindingId, branch })),
1056
+ stopped
1057
+ }
1058
+ })
651
1059
 
652
- const repos = [
653
- ...new Set(ordered.flatMap(result => (result.status === 'merged' ? (result.repoBindingId ?? []) : [])))
654
- ]
1060
+ /** Filed tickets by key, held from pickup while this Run could still build them as its own Child Runs. */
1061
+ type Held = Map<string, PlanTicket>
655
1062
 
656
- const deliveries = yield* Effect.forEach(repos, repo =>
657
- changeRequest(`deliver:${repo}`, {
658
- title: plan.title,
659
- body: deliveryBody(
660
- plan,
661
- ordered.filter(result => result.repoBindingId === repo || result.repoBindingId === undefined)
662
- ),
663
- integration: repo
664
- })
665
- )
1063
+ const filedAndHeld = (held: Held, { plan, revision }: Drafted, projectId: string | undefined, planReviewed: boolean) =>
1064
+ Effect.tap(filed({ tickets: plan.tickets, revision, projectId, planReviewed }), () =>
1065
+ Effect.sync(() => {
1066
+ for (const ticket of plan.tickets) held.set(ticket.key, ticket)
1067
+ })
1068
+ )
1069
+
1070
+ /** Leaves the held Tasks for pickup, but for those of the tickets this Run builds. */
1071
+ const heldLeftForPickup = (held: Held, projectId: string | undefined, building: readonly PlanTicket[] = []) =>
1072
+ Effect.suspend(() => {
1073
+ const tickets = [...held.values()].filter(ticket => !building.some(built => built.key === ticket.key))
666
1074
 
667
- return { tickets: ordered, deliveries, tasks, ...(stopped === undefined ? undefined : { stopped }) }
1075
+ held.clear()
1076
+
1077
+ return tickets.length === 0 ? Effect.void : leftForPickup({ tickets, projectId })
668
1078
  })
669
1079
 
1080
+ /** The Output fields the plan itself gives, before any of its tickets is built. */
1081
+ const outputOfPlan = ({ plan, rejected }: Drafted, docs: Drafted['docs'], asTasks: Filed | undefined) => ({
1082
+ title: plan.title,
1083
+ outOfScope: plan.outOfScope,
1084
+ afterMerge: plan.afterMerge,
1085
+ rejected,
1086
+ implemented: false,
1087
+ tickets: [],
1088
+ deliveries: [],
1089
+ ...(asTasks === undefined ? undefined : { tasks: asTasks.tasks }),
1090
+ ...(docs === undefined ? undefined : { docs })
1091
+ })
1092
+
670
1093
  /**
671
1094
  * Plans from the goal and the code: the planner runs grill-with-docs, asking only the decisions that change the
672
1095
  * tickets, and Plan opens a docs ChangeRequest for the ADR and glossary changes it left. A plan reviewer checks each
673
1096
  * revision, and the planner answers its concerns once. Plan then checks each ticket's criteria against the base, stores
674
1097
  * the spec and tickets as Run artifacts, and waits for a person to approve the revision, the planner revising it from
675
1098
  * their review until they do. Then it asks what next, at most six times: build the tickets, file them as Tasks, refine
676
- * the plan from the user's words, or finish (ADR-0051). Nobody answering the menu files it as Tasks; started with
677
- * `implement`, nobody answering approves each revision and implements it.
1099
+ * the plan from the user's words, or finish (ADR-0051). Nobody answering the menu files it as Tasks; started with `implement`, nobody answering
1100
+ * approves each revision and implements it.
678
1101
  */
679
1102
  export default defineLoop({
680
1103
  id: 'plan',
681
- version: '3.1.0',
1104
+ version: '4.0.0',
682
1105
  title: 'Plan',
1106
+ description: 'Plans a goal into reviewed tickets and a spec, then builds them or files them as Tasks.',
683
1107
  input: Input,
684
1108
  output: Output,
685
1109
  agents: { planner: 'planner', reviewer: 'reviewer', 'plan-reviewer': 'plan-reviewer' },
@@ -693,209 +1117,70 @@ export default defineLoop({
693
1117
  'change_request',
694
1118
  'write_back',
695
1119
  'create_tasks',
1120
+ 'create_branch',
696
1121
  'merge_change_request',
697
1122
  'read_change_request',
698
1123
  'post_comment'
699
1124
  ],
700
1125
  calls: () => [build],
701
- run: input =>
702
- Effect.gen(function* () {
703
- const drafted = yield* agentWorkOnce('plan', {
704
- agent: 'planner',
705
- skill: 'grill-with-docs',
706
- prompt: planPrompt(input.words),
707
- output: Plan
708
- })
709
-
710
- const docs =
711
- drafted.docs === undefined
712
- ? undefined
713
- : yield* changeRequest('docs', { title: drafted.docs.title, body: drafted.docs.summary })
714
-
715
- let revision = 1
716
- const asked = [input.words]
717
- let { plan, rejected, disputed } = yield* checked({ plan: drafted }, revision, asked)
718
- let filed: Filed | undefined
719
- let planReviewed = false
720
-
721
- yield* storePlan({ plan, disputed }, '', revision)
722
-
723
- const project = input.projectId === undefined ? undefined : { projectId: input.projectId }
724
-
725
- // Filed tickets by key, held from pickup while this Run could still build them as its own Child Runs.
726
- const held = new Map<string, PlanTicket>()
727
- let implementing = false
728
-
729
- const file = (step: string) =>
730
- Effect.gen(function* () {
731
- const made = yield* createTasks(step, { tickets: plan.tickets, builds: true, planReviewed, ...project })
732
-
733
- for (const ticket of plan.tickets) held.set(ticket.key, ticket)
734
- filed = { revision, tasks: made.tasks }
735
- })
736
-
737
- /** Leaves the held Tasks, but for those Implement now builds, for pickup to start. */
738
- const release = (building: readonly PlanTicket[] = []) => {
739
- const tickets = [...held.values()].filter(ticket => !building.some(built => built.key === ticket.key))
740
-
741
- held.clear()
742
-
743
- return tickets.length === 0
744
- ? Effect.void
745
- : Effect.asVoid(createTasks('release-tasks', { tickets, releases: true, ...project }))
746
- }
747
-
748
- const ended = (rest: { readonly implemented: boolean; readonly stopped?: string }) => ({
749
- title: plan.title,
750
- outOfScope: plan.outOfScope,
751
- afterMerge: plan.afterMerge,
752
- rejected,
753
- tickets: [],
754
- deliveries: [],
755
- ...(filed === undefined ? undefined : { tasks: filed.tasks }),
756
- ...(docs === undefined ? undefined : { docs }),
757
- ...rest
758
- })
759
-
760
- /** Asks a person to approve the revision, and has the planner revise it from their comments until they do. */
761
- const approve = () =>
762
- Effect.gen(function* () {
763
- for (;;) {
764
- const answer = yield* ask(`review:${revision}`, {
765
- prompt: [
766
- `Review revision ${revision} of the plan "${plan.title}": approve it, or request changes by commenting on what should change.`,
767
- ...(disputed.length === 0
768
- ? []
769
- : [
770
- `The plan reviewer still disputes ${disputed.length} point${disputed.length === 1 ? '' : 's'}, listed at the end of the plan.`
771
- ])
772
- ].join(' '),
773
- freeText: true,
774
- recommended: PlanApproval,
775
- recommendationReason: 'Approve it once the plan reads right; until then the Run waits for you.',
776
- ...(input.implement === true
777
- ? { default: UnattendedPlanApproval, timeout: '1 hour' }
778
- : { default: null }),
779
- unattendedAuto: UnattendedPlanApproval
780
- })
781
-
782
- if (isPlanApproval(answer)) {
783
- planReviewed = disputed.length === 0 || answer !== UnattendedPlanApproval
784
-
785
- return
1126
+ run: input => {
1127
+ const { projectId, implement = false } = input
1128
+ const held: Held = new Map()
1129
+
1130
+ return Effect.gen(function* () {
1131
+ const first = yield* drafted({ words: input.words })
1132
+ const { docs } = first
1133
+ let { draft, reviewed: planReviewed } = yield* approvedDraft(first, implement)
1134
+ let asTasks: Filed | undefined
1135
+
1136
+ for (let round = 1; round <= maxRounds; round++) {
1137
+ const { plan, revision } = draft
1138
+ const { tickets } = plan
1139
+ const isFiled = asTasks?.revision === revision
1140
+ const choice = yield* chosen({ title: plan.title, filed: isFiled, implement })
1141
+
1142
+ switch (choice._tag) {
1143
+ case 'ImplementNow': {
1144
+ yield* heldLeftForPickup(held, projectId, tickets)
1145
+
1146
+ if (asTasks?.revision !== revision) asTasks = yield* filed({ tickets, revision, projectId, planReviewed })
1147
+ const built = yield* builtInWaves(input, plan, asTasks.tasks)
1148
+ const { integrations, stopped } = built
1149
+ const delivery = yield* delivered({ title: plan.title, results: built.tickets, integrations })
1150
+
1151
+ return {
1152
+ ...outputOfPlan(draft, docs, asTasks),
1153
+ implemented: true,
1154
+ tickets: built.tickets,
1155
+ deliveries: delivery.deliveries,
1156
+ ...(delivery.undelivered.length === 0 ? undefined : { undelivered: delivery.undelivered }),
1157
+ ...(stopped === undefined ? undefined : { stopped })
786
1158
  }
787
-
788
- const review = readPlanReview(answer, revision, documentText(plan, disputed))
789
-
790
- const revised = yield* agentWorkOnce(`revise-plan:${revision}`, {
791
- agent: 'planner',
792
- prompt: revisePrompt(documentText(plan, disputed), review),
793
- output: Revised
794
- })
795
-
796
- const { addressed, declined, ...next } = revised
797
- const before = plan
798
- const count = review.comments.length
799
-
800
- revision++
801
- asked.push(commentsText(review))
802
-
803
- const ready = yield* checked({ plan: next, answered: { review, addressed, declined } }, revision, asked)
804
-
805
- ;({ plan, rejected, disputed } = ready)
806
- yield* storePlan(ready, `:review-${revision}`, revision)
807
- yield* artifact(`changes:review-${revision}`, {
808
- kind: 'plan_changes',
809
- title: `Revision ${revision} of ${plan.title}`,
810
- text: changelog(before, plan, `${count} review comment${count === 1 ? '' : 's'}`)
811
- })
812
1159
  }
813
- })
814
1160
 
815
- const decide = Effect.gen(function* () {
816
- for (let round = 1; round <= maxRounds; round++) {
817
- const isFiled = filed?.revision === revision
818
-
819
- const options = menu.filter(option => !(option === 'File as Tasks' && isFiled))
820
-
821
- const fallback: Choice = input.implement === true ? 'Implement now' : isFiled ? 'Finish' : 'File as Tasks'
822
-
823
- const answer = yield* ask(`next:${round}`, {
824
- prompt: `What next for the plan "${plan.title}"?`,
825
- options: options.map(option => ({ value: option, description: menuDescriptions[option] })),
826
- recommended: fallback,
827
- recommendationReason:
828
- fallback === 'Implement now'
829
- ? 'You asked for the plan to be implemented.'
830
- : fallback === 'Finish'
831
- ? 'The plan is filed as Tasks, so nothing is lost by finishing.'
832
- : 'Filing keeps the plan as Tasks a person or a Build can pick up later.',
833
- default: fallback,
834
- timeout: '1 hour'
835
- })
836
-
837
- const choice = menu.find(option => option === answer) ?? fallback
838
-
839
- switch (choice) {
840
- case 'Finish':
841
- yield* release()
842
-
843
- return ended({ implemented: false })
844
- case 'Implement now': {
845
- implementing = true
846
- yield* release(plan.tickets)
1161
+ case 'FileAsTasks':
1162
+ asTasks = yield* filedAndHeld(held, draft, projectId, planReviewed)
1163
+ break
847
1164
 
848
- const delivered = yield* implement(input, plan, revision, planReviewed, filed)
1165
+ case 'Refine':
1166
+ ;({ draft, reviewed: planReviewed } = yield* approvedDraft(yield* refined({ draft }), implement))
1167
+ break
849
1168
 
850
- return { ...ended({ implemented: true }), ...delivered }
851
- }
1169
+ case 'Finish':
1170
+ yield* heldLeftForPickup(held, projectId)
852
1171
 
853
- case 'File as Tasks':
854
- yield* file(`file-tasks:${round}`)
855
- break
856
-
857
- case 'Refine': {
858
- const words = yield* ask(`refine:${round}`, {
859
- prompt: 'What should change in the plan?',
860
- freeText: true,
861
- informationOnly: true,
862
- recommendationReason: 'You chose to refine it, so only you know what should change.'
863
- })
864
-
865
- const refined = yield* agentWorkOnce(`refine-plan:${round}`, {
866
- agent: 'planner',
867
- prompt: refinePrompt(documentText(plan, disputed), words),
868
- output: Plan
869
- })
870
-
871
- const before = plan
872
-
873
- revision++
874
- asked.push(words)
875
- ;({ plan, rejected, disputed } = yield* checked({ plan: refined }, revision, asked))
876
- yield* storePlan({ plan, disputed }, `:${round}`, revision)
877
- yield* artifact(`changes:${round}`, {
878
- kind: 'plan_changes',
879
- title: `Revision ${revision} of ${plan.title}`,
880
- text: changelog(before, plan, words)
881
- })
882
- yield* approve()
883
- break
884
- }
885
- }
1172
+ return outputOfPlan(draft, docs, asTasks)
886
1173
  }
1174
+ }
887
1175
 
888
- if (filed?.revision !== revision) yield* file('file-tasks:last')
889
- yield* release()
890
-
891
- return ended({
892
- implemented: false,
893
- stopped: `No decision after ${maxRounds} rounds, so the tickets are filed as Tasks for a person to pick up`
894
- })
895
- })
1176
+ if (asTasks?.revision !== draft.revision) asTasks = yield* filedAndHeld(held, draft, projectId, planReviewed)
896
1177
 
897
- yield* approve()
1178
+ yield* heldLeftForPickup(held, projectId)
898
1179
 
899
- return yield* decide.pipe(Effect.tapError(() => (implementing ? Effect.void : Effect.ignore(release()))))
900
- })
1180
+ return {
1181
+ ...outputOfPlan(draft, docs, asTasks),
1182
+ stopped: `No decision after ${maxRounds} rounds, so the tickets are filed as Tasks for a person to pick up`
1183
+ }
1184
+ }).pipe(Effect.tapError(() => Effect.ignore(heldLeftForPickup(held, projectId))))
1185
+ }
901
1186
  })