@kitman-sh/software-engineering 0.11.0-rc.5 → 0.11.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/release.ts CHANGED
@@ -11,23 +11,38 @@ import {
11
11
  ReleaseScope,
12
12
  ReleaseTrigger,
13
13
  ResolvedReleaseTrigger,
14
+ ResolvedDeliveryTarget,
14
15
  rerunPipeline,
16
+ runDeploy,
15
17
  ShippedScope,
16
18
  shippedScope,
19
+ StepFailed,
20
+ type LoopEvent,
17
21
  verify,
18
22
  waitFor
19
23
  } from '@kitman-sh/sdk/loop'
20
24
  import * as Effect from 'effect/Effect'
21
25
  import * as Schema from 'effect/Schema'
22
- import { FindingDetail } from './text-limits'
26
+ import { DeliveryFields, deliveryLayerWords, epicOf } from './delivery'
27
+
28
+ /** An id a full-auto answer's evidence can carry: Kitman refuses an empty one or one over 240 characters. */
29
+ const ApprovalRef = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(240))
30
+
31
+ /** What identifies a `change_request.approval` Event's approval: a Kitman review's id, else the forge approval's `approvalId`. */
32
+ export const approvalRef = (event: LoopEvent | undefined) =>
33
+ [event?.payload.reviewId, event?.payload.approvalId].find(Schema.is(ApprovalRef))
23
34
 
24
35
  const Input = Schema.Struct({
25
36
  /** The tag to release; the drafting agent proposes one when left out. */
26
37
  tag: Schema.optional(Schema.String),
27
38
  /** The revision to tag; the Run's base branch head when left out. */
28
39
  revision: Schema.optional(Schema.String),
40
+ /** The approval of the change being released, recorded with a full-auto approval of the release. */
41
+ review: Schema.optional(ApprovalRef),
29
42
  /** A release ChangeRequest to wait for, merge, and tag the merge of. */
30
43
  changeRequestId: Schema.optional(Schema.String),
44
+ /** The Task it delivers, whose Project's release trigger the Run uses. */
45
+ taskId: Schema.optional(Schema.String),
31
46
  /** What the release deploys to; one Release deploys to it at a time. The deploy Event type when left out. */
32
47
  deployTarget: Schema.optional(Schema.String),
33
48
  /** The Event type the deploy reports; `deploy` when left out. Its payload names the `tag` and a `status`. */
@@ -41,7 +56,12 @@ const Input = Schema.Struct({
41
56
  /** The release trigger the Run uses and the layer it came from; Kitman sets it when the Run starts. */
42
57
  releaseWhen: Schema.optional(ResolvedReleaseTrigger),
43
58
  /** The Milestone or Project whose completion started this Release, and the Tasks it ships. */
44
- releaseScope: Schema.optional(ReleaseScope)
59
+ releaseScope: Schema.optional(ReleaseScope),
60
+ /** The Project's version its Milestone or Project releases; Kitman sets it when release.due starts the Run. */
61
+ version: Schema.optional(Schema.String),
62
+ /** Whether it releases the next release candidate of `version`, numbered once it holds the deploy target, or `version`. */
63
+ candidate: Schema.optional(Schema.Boolean),
64
+ ...DeliveryFields
45
65
  })
46
66
 
47
67
  const Drafted = Schema.Struct({
@@ -64,22 +84,6 @@ const Picked = Schema.Struct({
64
84
  releasedIn: Schema.optional(Schema.String)
65
85
  })
66
86
 
67
- /** What the repository's own deploy script did, as the releaser read it from its last line and exit code. */
68
- const Deployed = Schema.Struct({
69
- /** none: the repository has no `.kitman/deploy`, so the deploy is left to whatever sends the deploy Event. */
70
- status: Schema.Literals(['deployed', 'failed', 'rolled_back', 'rollback_failed', 'none']),
71
- detail: FindingDetail
72
- })
73
-
74
- const deployPrompt = (tag: string, previousTag: string | undefined) =>
75
- [
76
- `Deploy the release ${tag}, which Kitman has just tagged and pushed.`,
77
- `Fetch the base branch and tags (\`git fetch origin --tags\`). If neither the base branch head nor ${tag} has an executable \`.kitman/deploy\`, change nothing and answer status none.`,
78
- `Otherwise run \`.kitman/deploy ${tag}${previousTag === undefined ? '' : ` ${previousTag}`}\` from a checkout of the base branch head when it has the script, so a rerun of an older tag gets the script's later fixes, or else from the checkout of ${tag}, and do nothing else: it deploys the tag it is given, backs up, publishes, verifies and rolls back by itself, and may take an hour. Run it in the background with its output in a log file, and wait for it to exit, checking every few minutes; never start it twice.`,
79
- 'Answer with the status its last line `kitman-deploy: <status> <detail>` names, and that detail. If it exited without that line, answer failed with its exit code and the end of its log.',
80
- 'Never print, copy or summarise the variables or secrets it pulls.'
81
- ].join('\n\n')
82
-
83
87
  const Output = Schema.Struct({
84
88
  status: Schema.Literals([
85
89
  'gate_failed',
@@ -95,17 +99,21 @@ const Output = Schema.Struct({
95
99
  'not_due',
96
100
  /** A Milestone or Project started it without the version to cut, which a Release never picks for itself. */
97
101
  'no_version',
98
- /** An existing tag already contains the revision, as when another Release tagged it first. */
102
+ /** An existing tag already contains the revision, as when another Release tagged it first; never for a Milestone or Project. */
99
103
  'nothing_to_release'
100
104
  ]),
101
105
  /** Why it stopped, or what happened, in a line. */
102
106
  reason: Schema.String,
103
107
  tag: Schema.optional(Schema.String),
104
108
  notesArtifactId: Schema.optional(Schema.String),
109
+ /** A person chose Leave it in the recover Question. */
110
+ leftUndeployed: Schema.optional(Schema.Boolean),
105
111
  revision: Schema.optional(Schema.String),
106
112
  url: Schema.optional(Schema.String),
107
113
  /** The release trigger the Run used and the layer it came from. */
108
114
  releaseWhen: Schema.optional(ResolvedReleaseTrigger),
115
+ /** Where the Run's delivery lands and the layer it came from. */
116
+ deliversTo: Schema.optional(ResolvedDeliveryTarget),
109
117
  /** The Milestone or Project that triggered it, and the Tasks it shipped. */
110
118
  shipped: Schema.optional(ShippedScope)
111
119
  })
@@ -139,18 +147,59 @@ const scopePrompt = (scope: ReleaseScope | undefined) =>
139
147
  scope.tasks.map(task => `- ${task.key} ${task.title}`).join('\n')
140
148
  ]
141
149
 
142
- const draftPrompt = (tag: string | undefined, changeRequestId: string | undefined, scope?: ReleaseScope) =>
150
+ /** What a Milestone or Project releases of its Project's version: its next release candidate, or the version itself. */
151
+ type Cut = { readonly version: string; readonly candidate: boolean }
152
+
153
+ const nextCandidateWords = (version: string) =>
154
+ `the next release candidate of ${version} after the latest the repository has: one past the highest N of any ${version}-rc.N tag, or ${version}-rc.1 when there is none`
155
+
156
+ const tagWords = (tag: string | undefined, cut: Cut | undefined) => {
157
+ if (cut?.candidate === true)
158
+ return `The release is a release candidate of ${cut.version}, numbered again once it is tagged. Give as tag ${nextCandidateWords(cut.version)}.`
159
+
160
+ const given = tag ?? cut?.version
161
+
162
+ return given === undefined
163
+ ? 'Propose the next version tag, following the scheme earlier tags use. With no earlier tag, propose v0.1.0 and say so in the notes.'
164
+ : `The release is tagged ${given}.`
165
+ }
166
+
167
+ const draftPrompt = (
168
+ tag: string | undefined,
169
+ cut: Cut | undefined,
170
+ changeRequestId: string | undefined,
171
+ scope?: ReleaseScope
172
+ ) =>
143
173
  [
174
+ 'Fetch the base branch and tags first (`git fetch origin --tags`).',
144
175
  'Draft the release notes for the ChangeRequests merged since the last release tag on the base branch, including those with no linked Task.',
145
176
  ...scopePrompt(scope),
146
177
  ...(changeRequestId === undefined ? [] : [`The release ChangeRequest ${changeRequestId} is part of it.`]),
147
178
  'Group them by what a user of the software notices, and name each ChangeRequest you cover.',
148
- tag === undefined
149
- ? 'Propose the next version tag, following the scheme earlier tags use. With no earlier tag, propose v0.1.0 and say so in the notes.'
150
- : `The release is tagged ${tag}.`,
179
+ tagWords(tag, cut),
151
180
  'Give the latest earlier release tag as previousTag, or leave it out when there is none.'
152
181
  ].join('\n\n')
153
182
 
183
+ const regexSpecial = /[.*+?^$()|[\]{}\\]/g
184
+
185
+ const escaped = (text: string) => text.replaceAll(regexSpecial, '\\$&')
186
+
187
+ /** The number of `tag` as a release candidate of `version`; undefined when it is not one. */
188
+ const candidateNumber = (tag: string, version: string) => {
189
+ const [, number] = new RegExp(`^${escaped(version)}-rc\\.(\\d+)$`).exec(tag) ?? []
190
+
191
+ return number === undefined ? undefined : Number(number)
192
+ }
193
+
194
+ /** `text` naming `tag` where it named `taken`; `-rc.1` is not read inside `-rc.10`. */
195
+ const renameTag = (text: string, taken: string, tag: string) =>
196
+ text.replaceAll(new RegExp(`${escaped(taken)}(?!\\d)`, 'g'), tag)
197
+
198
+ const isTagElsewhere = (failed: StepFailed) => failed.reason.includes('TAG_ELSEWHERE')
199
+
200
+ /** Another Run already published the tag at this revision. */
201
+ const isReleasedByOther = (failed: StepFailed) => failed.reason.includes('TAG_RELEASED')
202
+
154
203
  const redraftPrompt = (drafted: Drafted, edit: string) =>
155
204
  [
156
205
  'Redraft these release notes as asked, keeping the tag and everything not mentioned.',
@@ -160,20 +209,31 @@ const redraftPrompt = (drafted: Drafted, edit: string) =>
160
209
  '```'
161
210
  ].join('\n\n')
162
211
 
163
- const pickPrompt = (drafted: Drafted, revision: string, givenTag: string | undefined) => {
212
+ const pickInstructions = (drafted: Drafted, revision: string, givenTag: string | undefined, cut: Cut | undefined) => {
213
+ // A Milestone or Project cuts its own release even at a revision another tag contains, so its Tasks are published.
214
+ if (cut !== undefined)
215
+ return [
216
+ `Fetch the tags (\`git fetch origin --tags\`). ${cut.candidate ? `Give as tag ${nextCandidateWords(cut.version)}, naming it in the title and notes where they name ${drafted.tag}, and` : `The release is tagged ${cut.version}: give the draft unchanged but for`} the latest release tag as previousTag. It is released even when another tag already contains ${revision}: leave releasedIn out.`
217
+ ]
218
+
164
219
  const ownTag = givenTag ?? drafted.tag
165
220
 
166
221
  return [
167
- 'This Release now holds the deploy target, so no other Release tags until it settles. Another Release may have tagged since these notes were drafted: pick their version again.',
168
222
  `Fetch the tags (\`git fetch origin --tags\`) and list the release tags that contain ${revision} (\`git tag --contains ${revision}\`). ${ownTag} at ${revision} itself, as \`git rev-list -n 1 ${ownTag}\` tells, is this Release tagged on an earlier attempt: ignore it. Any other, ${ownTag} at another commit included, means ${revision} is released already: give that tag as releasedIn and the draft unchanged.`,
169
223
  givenTag === undefined
170
224
  ? `Otherwise, when ${drafted.tag} is still free and the latest release tag is still ${drafted.previousTag ?? 'none'}, give the draft unchanged. When not, give the next version tag after the latest release tag, that latest tag as previousTag, and drop from the notes and changeRequests what it already released.`
171
- : `Otherwise give the draft unchanged. The release is tagged ${givenTag}.`,
225
+ : `Otherwise give the draft unchanged. The release is tagged ${givenTag}.`
226
+ ]
227
+ }
228
+
229
+ const pickPrompt = (drafted: Drafted, revision: string, givenTag: string | undefined, cut: Cut | undefined) =>
230
+ [
231
+ 'This Release now holds the deploy target, so no other Release tags until it settles. Another Release may have tagged since these notes were drafted: pick their version again.',
232
+ ...pickInstructions(drafted, revision, givenTag, cut),
172
233
  '```json',
173
234
  JSON.stringify(drafted, null, 2),
174
235
  '```'
175
236
  ].join('\n\n')
176
- }
177
237
 
178
238
  const approval = ['Approve', 'Edit notes', 'Reject'] as const
179
239
 
@@ -244,7 +304,9 @@ const readyToMerge = (changeRequestId: string, round = 1) =>
244
304
  reason: `ChangeRequest ${changeRequestId} does not merge cleanly; bring it up to date first`
245
305
  } satisfies Output
246
306
 
247
- return { passed: read.head }
307
+ const review = approvalRef(approved)
308
+
309
+ return { passed: read.head, ...(review === undefined ? undefined : { review }) }
248
310
  }
249
311
  }).pipe(
250
312
  Effect.catchTags({
@@ -273,33 +335,46 @@ const recovery = (previous: string | undefined) =>
273
335
  * notes, which can be edited in place. On approval it merges the ChangeRequest when there is one, holds the deploy
274
336
  * target so two Releases never tag or deploy over each other, taking it over from a Release that failed holding it,
275
337
  * and picks the version again under it: a revision an existing tag already contains ends as nothing to release. It
276
- * then tags and publishes once (a tag already released at the same revision counts as done; one at another is never
277
- * moved) and waits for the deploy. A failed or late deploy asks whether
338
+ * then tags and publishes once (its own release of the tag at the same revision counts as done; one at another is
339
+ * never moved) and waits for the deploy. A failed or late deploy asks whether
278
340
  * to retry (it runs the tag's failed pipeline again and waits), roll back to the previous tag (it runs that
279
341
  * tag's pipeline again in full and waits for its deploy), or leave it, which it does by default.
280
342
  *
281
343
  * Under a Milestone or Project release trigger, it releases only when that Milestone's or Project's completion starts
282
- * it, with the tag Kitman cut and the Tasks it ships, which it records; without that tag it stops rather than choose a
283
- * version. A Run whose `releaseTrigger` is `merge` releases anyway.
344
+ * it, with the Project's version and the Tasks it ships, which it records; without a version it stops rather than
345
+ * choose one. A Milestone's release candidate is numbered under the deploy target, after the latest one the repository
346
+ * has, and gives way to the next when the forge finds it taken; the version itself is never moved. Either is released
347
+ * even at a revision another tag contains. A Run whose `releaseTrigger` is `merge` releases anyway. A Team can turn on
348
+ * starting it on each head of a ChangeRequest delivering a Task that is approved and passed its pipeline while no Run
349
+ * works the ChangeRequest; it releases that only under a `merge` trigger.
284
350
  */
285
351
  export default defineLoop({
286
352
  id: 'release',
287
- version: '2.2.0',
353
+ version: '2.4.0',
288
354
  title: 'Release',
289
355
  input: Input,
290
356
  output: Output,
291
- agents: { releaser: 'releaser', deployer: 'deployer' },
357
+ agents: { releaser: 'releaser' },
292
358
  checkout: 'read',
293
359
  // Kitman records release.due per repository when a Milestone or Project closes under that trigger.
294
360
  when: [
295
361
  {
296
362
  event: 'release.due',
297
363
  input: {
298
- tag: 'tag',
364
+ version: 'version',
365
+ candidate: 'candidate',
299
366
  releaseScope: 'releaseScope',
300
367
  releaseWhen: 'releaseWhen',
301
368
  repoBindingId: 'repoBindingId'
302
369
  }
370
+ },
371
+ {
372
+ event: 'change_request.ready',
373
+ filter: { busy: false },
374
+ input: { changeRequestId: 'changeRequestId', taskId: 'taskId' },
375
+ optIn: true,
376
+ description:
377
+ 'Releases a ChangeRequest delivering a Task once it is approved and green and no Run works it, only under a merge release trigger; under a Milestone or Project trigger each such Run ends not_due.'
303
378
  }
304
379
  ],
305
380
  capabilities: [
@@ -322,7 +397,16 @@ export default defineLoop({
322
397
  reason: `Release runs when ${triggerWords[when.trigger]}, as ${layerWords[when.layer]} says; this Run did not override that`
323
398
  } satisfies Output
324
399
 
325
- if (input.releaseScope !== undefined && input.tag === undefined)
400
+ const epic = epicOf(input)
401
+
402
+ // Under epic delivery a sub-task's work reaches the default branch only with its epic's ChangeRequest.
403
+ if (epic !== undefined && !epic.done)
404
+ return {
405
+ status: 'not_due',
406
+ reason: `Its Task lands on ${epic.branch}, as ${deliveryLayerWords[input.deliversTo?.layer ?? 'workspace']} says; Release runs once epic ${epic.key} merges into ${epic.defaultBranch}`
407
+ } satisfies Output
408
+
409
+ if (input.releaseScope !== undefined && input.tag === undefined && input.version === undefined)
326
410
  return {
327
411
  status: 'no_version',
328
412
  reason:
@@ -333,6 +417,7 @@ export default defineLoop({
333
417
  const changeRequestId = input.changeRequestId
334
418
  // The commit the gate proved, and the one tagged or merged: never the branch head read again later.
335
419
  let gated: string
420
+ let review = input.review
336
421
 
337
422
  if (changeRequestId === undefined) {
338
423
  // A failure an earlier Release recorded at this tree may be its checkout's, so it is run again.
@@ -390,20 +475,47 @@ export default defineLoop({
390
475
 
391
476
  if (!('passed' in ready)) return ready
392
477
  gated = ready.passed
478
+ review = ready.review
479
+ }
480
+
481
+ const cut: Cut | undefined =
482
+ input.tag === undefined && input.version !== undefined
483
+ ? { version: input.version, candidate: input.candidate === true }
484
+ : undefined
485
+
486
+ /** The tag to cut: a given one, a Project's version, or a candidate of it the releaser numbered, else `fallback`. */
487
+ const tagOf = (proposed: string, fallback: string) => {
488
+ if (cut === undefined) return input.tag ?? proposed
489
+
490
+ if (!cut.candidate) return cut.version
491
+
492
+ return candidateNumber(proposed, cut.version) === undefined ? fallback : proposed
393
493
  }
394
494
 
395
495
  let drafted = yield* agentWork('draft-notes', {
396
496
  agent: 'releaser',
397
- prompt: draftPrompt(input.tag, changeRequestId, input.releaseScope),
497
+ prompt: draftPrompt(input.tag, cut, changeRequestId, input.releaseScope),
398
498
  output: Drafted
399
499
  })
400
500
 
401
- let tag = input.tag ?? drafted.tag
501
+ let tag = tagOf(drafted.tag, cut === undefined ? drafted.tag : `${cut.version}-rc.1`)
502
+
503
+ const recordNotes = (step: string) =>
504
+ artifact(step, {
505
+ kind: 'release_notes',
506
+ title: drafted.title,
507
+ text: drafted.notes,
508
+ data: {
509
+ tag,
510
+ changeRequests: drafted.changeRequests,
511
+ ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
512
+ }
513
+ })
402
514
 
403
515
  // The question has no default: a release goes out only when someone says so.
404
516
  for (let round = 1; ; round++) {
405
517
  const answer = yield* ask(round === 1 ? 'approve' : `approve:${round}`, {
406
- prompt: `Release ${tag} with these notes?\n\n${drafted.notes}`,
518
+ prompt: `Release ${cut?.candidate === true ? `${tag}, or the next release candidate of ${cut.version} still free when it is tagged,` : tag} with these notes?\n\n${drafted.notes}`,
407
519
  options: [
408
520
  { value: 'Approve', description: 'Tags, publishes and deploys it.' },
409
521
  { value: 'Edit notes', description: 'Say what to change; the notes are redrafted.' },
@@ -414,7 +526,8 @@ export default defineLoop({
414
526
  'The release is proved: its checks pass, or its ChangeRequest is green, approved and mergeable.',
415
527
  default: null,
416
528
  // A full-auto Team has handed releasing a proved change to Kitman.
417
- auto: 'Approve'
529
+ auto: 'Approve',
530
+ evidence: { ...(review === undefined ? undefined : { review }), head: gated }
418
531
  })
419
532
 
420
533
  if (answer === 'Approve') break
@@ -429,16 +542,7 @@ export default defineLoop({
429
542
  timeout: '1 day'
430
543
  })
431
544
 
432
- const kept = yield* artifact('notes', {
433
- kind: 'release_notes',
434
- title: drafted.title,
435
- text: drafted.notes,
436
- data: {
437
- tag,
438
- changeRequests: drafted.changeRequests,
439
- ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
440
- }
441
- })
545
+ const kept = yield* recordNotes('notes')
442
546
 
443
547
  return { status: 'rejected', reason: why, tag, notesArtifactId: kept.artifactId } satisfies Output
444
548
  }
@@ -461,16 +565,7 @@ export default defineLoop({
461
565
  })
462
566
  }
463
567
 
464
- let notes = yield* artifact('notes', {
465
- kind: 'release_notes',
466
- title: drafted.title,
467
- text: drafted.notes,
468
- data: {
469
- tag,
470
- changeRequests: drafted.changeRequests,
471
- ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
472
- }
473
- })
568
+ let notes = yield* recordNotes('notes')
474
569
 
475
570
  let revision = gated
476
571
 
@@ -507,6 +602,29 @@ export default defineLoop({
507
602
 
508
603
  if (!('passed' in ready)) return { ...ready, tag, notesArtifactId: notes.artifactId }
509
604
  gated = ready.passed
605
+ review = ready.review
606
+
607
+ // The release was approved at an earlier head, so this one is approved on its own approval and gate.
608
+ const again = yield* ask(`approve:merge:${round + 1}`, {
609
+ prompt: `ChangeRequest ${changeRequestId} moved to ${gated} after ${tag} was approved; its pipeline passed and it is approved again. Release ${tag} from it?`,
610
+ options: [
611
+ { value: 'Approve', description: 'Merges this head, then tags, publishes and deploys it.' },
612
+ { value: 'Reject', description: 'Keeps the draft and releases nothing.' }
613
+ ],
614
+ recommended: 'Approve',
615
+ recommendationReason: 'This head is green, approved and mergeable, like the one you approved.',
616
+ default: null,
617
+ auto: 'Approve',
618
+ evidence: { ...(review === undefined ? undefined : { review }), head: gated }
619
+ })
620
+
621
+ if (again !== 'Approve')
622
+ return {
623
+ status: 'rejected',
624
+ reason: `Not released from ${gated}, the head ChangeRequest ${changeRequestId} moved to`,
625
+ tag,
626
+ notesArtifactId: notes.artifactId
627
+ } satisfies Output
510
628
  }
511
629
  }
512
630
 
@@ -518,43 +636,68 @@ export default defineLoop({
518
636
 
519
637
  const { releasedIn, ...picked } = yield* agentWork('pick-version', {
520
638
  agent: 'releaser',
521
- prompt: pickPrompt({ ...drafted, tag }, revision, input.tag),
639
+ prompt: pickPrompt({ ...drafted, tag }, revision, input.tag, cut),
522
640
  output: Picked
523
641
  })
524
642
 
525
- if (releasedIn !== undefined)
526
- return {
643
+ const alreadyReleased = (released: string, reason: string) =>
644
+ ({
527
645
  status: 'nothing_to_release',
528
- reason: `${revision} is already released in ${releasedIn}`,
529
- tag: releasedIn,
646
+ reason,
647
+ tag: released,
530
648
  notesArtifactId: notes.artifactId,
531
649
  revision
532
- } satisfies Output
650
+ }) satisfies Output
533
651
 
534
- const pickedTag = input.tag ?? picked.tag
652
+ if (cut === undefined && releasedIn !== undefined)
653
+ return alreadyReleased(releasedIn, `${revision} is already released in ${releasedIn}`)
535
654
 
536
- if (pickedTag !== tag || picked.notes !== drafted.notes || picked.title !== drafted.title) {
537
- notes = yield* artifact('notes:picked', {
538
- kind: 'release_notes',
539
- title: picked.title,
540
- text: picked.notes,
541
- data: {
542
- tag: pickedTag,
543
- changeRequests: picked.changeRequests,
544
- ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
545
- }
546
- })
547
- }
655
+ const pickedTag = tagOf(picked.tag, tag)
656
+
657
+ const repicked =
658
+ cut === undefined
659
+ ? picked
660
+ : {
661
+ ...picked,
662
+ title: renameTag(picked.title, tag, pickedTag),
663
+ notes: renameTag(picked.notes, tag, pickedTag)
664
+ }
548
665
 
549
- drafted = picked
666
+ const changed = pickedTag !== tag || repicked.notes !== drafted.notes || repicked.title !== drafted.title
667
+
668
+ drafted = repicked
550
669
  tag = pickedTag
551
670
 
552
- const released = yield* release('tag', {
553
- tag,
554
- revision,
555
- title: drafted.title,
556
- notes: drafted.notes
557
- })
671
+ if (changed) notes = yield* recordNotes('notes:picked')
672
+
673
+ const publish = (step: string) =>
674
+ release(step, { tag, revision, title: drafted.title, notes: drafted.notes }).pipe(
675
+ Effect.catchTag('StepFailed', failed =>
676
+ isTagElsewhere(failed) || isReleasedByOther(failed) ? Effect.succeed(failed) : Effect.fail(failed)
677
+ )
678
+ )
679
+
680
+ const approved = { tag, title: drafted.title, notes: drafted.notes }
681
+
682
+ let released = yield* publish('tag')
683
+
684
+ if (released instanceof StepFailed && cut === undefined && isReleasedByOther(released))
685
+ return alreadyReleased(tag, `${tag} is already released at ${revision} by another Run`)
686
+
687
+ // A tag is never moved, so a release candidate already tagged gives way to the next; a version has no next.
688
+ for (let round = 2; released instanceof StepFailed; round++) {
689
+ if (cut?.candidate !== true || round > 20) return yield* released
690
+
691
+ tag = `${cut.version}-rc.${(candidateNumber(tag, cut.version) ?? 0) + 1}`
692
+ // Only the tag changes from what was approved, so nothing is published unreviewed.
693
+ drafted = {
694
+ ...drafted,
695
+ title: renameTag(approved.title, approved.tag, tag),
696
+ notes: renameTag(approved.notes, approved.tag, tag)
697
+ }
698
+ notes = yield* recordNotes(`notes:${round}`)
699
+ released = yield* publish(`tag:${round}`)
700
+ }
558
701
 
559
702
  const deployed = (step: string, deployTag: string) =>
560
703
  waitFor(step, {
@@ -571,12 +714,7 @@ export default defineLoop({
571
714
  const settled = { tag, notesArtifactId: notes.artifactId, revision: released.revision, url: released.url }
572
715
 
573
716
  // The repository deploys itself from the Runner when it has a deploy script, which rolls back on its own.
574
- const ran = yield* agentWork('run-deploy', {
575
- agent: 'deployer',
576
- prompt: deployPrompt(tag, drafted.previousTag),
577
- output: Deployed,
578
- timeout: '3 hours'
579
- })
717
+ const ran = yield* runDeploy('run-deploy', { tag, previousTag: drafted.previousTag })
580
718
 
581
719
  if (ran.status !== 'none') {
582
720
  const status = ran.status === 'failed' ? 'deploy_failed' : ran.status
@@ -609,12 +747,17 @@ export default defineLoop({
609
747
  recommended: 'Retry the deploy',
610
748
  recommendationReason:
611
749
  'A failed or late deploy is often passing, and a retry runs only the failed jobs of the same tag.',
612
- default: 'Leave it',
613
- timeout: '1 hour'
750
+ // Waits for a person, so Leave it is always their choice.
751
+ default: null
614
752
  })
615
753
 
616
754
  if (answer === 'Leave it')
617
- return { status, reason: `${tag} at ${released.revision} was left undeployed`, ...settled } satisfies Output
755
+ return {
756
+ status,
757
+ reason: `${tag} at ${released.revision} was left undeployed`,
758
+ leftUndeployed: true,
759
+ ...settled
760
+ } satisfies Output
618
761
 
619
762
  if (answer === 'Retry the deploy') {
620
763
  yield* rerunPipeline(`deploy:rerun-${round}`, { ref: tag })
@@ -644,6 +787,7 @@ export default defineLoop({
644
787
  Effect.map((output): Output => ({
645
788
  ...output,
646
789
  ...(input.releaseWhen === undefined ? undefined : { releaseWhen: input.releaseWhen }),
790
+ ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo }),
647
791
  ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
648
792
  }))
649
793
  )
package/src/review.ts CHANGED
@@ -16,12 +16,15 @@ import {
16
16
  RebuttalVerdict,
17
17
  pipelineStatus,
18
18
  resolveRevisions,
19
- ScopeJudgement
19
+ ResolvedDeliveryTarget,
20
+ ScopeJudgement,
21
+ settleRound
20
22
  } from '@kitman-sh/sdk/loop'
21
23
  import * as Effect from 'effect/Effect'
22
24
  import * as Schema from 'effect/Schema'
23
25
  import build, { BuildInput, BuildOutput } from './build'
24
26
  import { verifyHead } from './change-request-body'
27
+ import { DeliveryFields, ownDeliveryTarget } from './delivery'
25
28
  import { FindingDetail, OneSentence } from './text-limits'
26
29
 
27
30
  /** Build, by its schemas: the module imports this one, so its definition is not ready when this one loads. */
@@ -78,7 +81,8 @@ const Input = Schema.Struct({
78
81
  /** Why each head test verify never ran is unverified; a ChangeRequest's head is verified here too. */
79
82
  notRun: Schema.optional(Schema.Array(Schema.String)),
80
83
  /** What to do after a ChangeRequest's review without asking; Done when nobody answers. */
81
- next: Schema.optional(Schema.Literals(choices))
84
+ next: Schema.optional(Schema.Literals(choices)),
85
+ ...DeliveryFields
82
86
  })
83
87
 
84
88
  const FollowUpStatus = Schema.Literals(['fixed', 'changed', 'still_there'])
@@ -119,7 +123,9 @@ const Output = Schema.Struct({
119
123
  Schema.Struct({ head: Schema.String, approved: Schema.Boolean, reason: Schema.optional(Schema.String) })
120
124
  ),
121
125
  /** What happened after a ChangeRequest's review. */
122
- next: Schema.optional(Schema.Struct({ choice: Schema.Literals(choices), detail: Schema.optional(Schema.String) }))
126
+ next: Schema.optional(Schema.Struct({ choice: Schema.Literals(choices), detail: Schema.optional(Schema.String) })),
127
+ /** Where the reviewed delivery lands and the layer it came from. */
128
+ deliversTo: Schema.optional(ResolvedDeliveryTarget)
123
129
  })
124
130
 
125
131
  export class ReviewTargetMissing extends Schema.TaggedError<ReviewTargetMissing>()('ReviewTargetMissing', {
@@ -318,7 +324,7 @@ const fixBrief = (changeRequestId: string, findings: readonly MergedFinding[]) =
318
324
  */
319
325
  export default defineLoop({
320
326
  id: 'review',
321
- version: '3.7.0',
327
+ version: '3.8.0',
322
328
  title: 'Review',
323
329
  input: Input,
324
330
  output: Output,
@@ -383,17 +389,13 @@ export default defineLoop({
383
389
  const standing = new Set(answered.flatMap(entry => (entry.status === 'fixed' ? [] : [entry.id])))
384
390
 
385
391
  const verdicts = outputs.flatMap(([, output]) => output.verdicts ?? [])
386
- const rebutted = new Set((input.rebuttals ?? []).map(rebuttal => rebuttal.findingId))
387
392
 
388
- // A rebutted finding every verdict on it accepts is withdrawn, as Build's settleRound counts it.
389
- const withdrawn = (id: string) => {
390
- const on = verdicts.filter(verdict => verdict.findingId === id)
393
+ const settled = settleRound({ findings: earlier, rebuttals: input.rebuttals ?? [], verdicts })
391
394
 
392
- return rebutted.has(id) && on.length > 0 && on.every(verdict => verdict.accepted)
393
- }
395
+ const withdrawn = new Set(settled.withdrawn.map(entry => entry.finding.id))
394
396
 
395
- const carried = earlier.filter(finding => standing.has(finding.id) && !withdrawn(finding.id))
396
- const followUps = answered.filter(entry => !withdrawn(entry.id))
397
+ const carried = earlier.filter(finding => standing.has(finding.id) && !withdrawn.has(finding.id))
398
+ const followUps = answered.filter(entry => !withdrawn.has(entry.id))
397
399
 
398
400
  const sinceApproval = input.approved !== undefined && input.files === undefined
399
401
 
@@ -453,7 +455,8 @@ export default defineLoop({
453
455
  blocking: findings.some(isBlocking),
454
456
  artifactId: stored.artifactId,
455
457
  ...(approvedFindings.length === 0 ? undefined : { approvedFindings }),
456
- ...(scope === undefined ? undefined : { scope })
458
+ ...(scope === undefined ? undefined : { scope }),
459
+ ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo })
457
460
  }
458
461
 
459
462
  const changeRequestId = input.changeRequestId
@@ -517,14 +520,18 @@ export default defineLoop({
517
520
  const fixed = yield* call('fix', buildLoop(), {
518
521
  words: fixBrief(changeRequestId, findings),
519
522
  changeRequestId,
520
- maxRounds: 2
523
+ maxRounds: 2,
524
+ ...ownDeliveryTarget(input)
521
525
  })
522
526
 
523
527
  return { choice, detail: fixed.settled ? 'Fixed and pushed' : `Pushed; left: ${fixed.unsettled.join('; ')}` }
524
528
  }
525
529
 
526
530
  if (choice === 'Build from it') {
527
- const built = yield* call('build', buildLoop(), { words: fixBrief(changeRequestId, findings) })
531
+ const built = yield* call('build', buildLoop(), {
532
+ words: fixBrief(changeRequestId, findings),
533
+ ...ownDeliveryTarget(input)
534
+ })
528
535
 
529
536
  return { choice, detail: built.changeRequest.url }
530
537
  }
@@ -532,7 +539,11 @@ export default defineLoop({
532
539
  return { choice, detail: 'The review is kept as an artifact' }
533
540
  }).pipe(Effect.catchTag('ChildFailed', failed => Effect.succeed({ choice, detail: failed.reason })))
534
541
 
535
- return { ...reviewed, ...(approval === undefined ? undefined : { approval }), next }
542
+ return {
543
+ ...reviewed,
544
+ ...(approval === undefined ? undefined : { approval }),
545
+ next
546
+ }
536
547
  })
537
548
  })
538
549