@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/release.ts CHANGED
@@ -1,29 +1,60 @@
1
1
  import {
2
- agentWork,
2
+ agent,
3
3
  artifact,
4
4
  ask,
5
+ auto,
6
+ Bump,
7
+ BumpPolicy,
8
+ bumpPolicy,
9
+ BumpPolicyName,
10
+ call,
11
+ type CalledLoop,
12
+ CalverFormat,
13
+ chain,
14
+ ChangeRequestResult,
5
15
  claim,
16
+ compare,
17
+ ComparedChange,
18
+ type ComparedSide,
19
+ type Comparison,
6
20
  defineLoop,
7
- mergeChangeRequest,
8
- pipelineMoved,
9
- pipelineStatus,
21
+ DeployTargetName,
22
+ letGo,
10
23
  release,
24
+ type ReleaseChange,
25
+ type ReleaseTask,
26
+ ReleaseRoleInput,
27
+ ReleaseRoleOutput,
28
+ ReleaseRoleStatus,
11
29
  ReleaseScope,
12
30
  ReleaseTrigger,
31
+ releasesOn,
13
32
  ResolvedReleaseTrigger,
14
33
  ResolvedDeliveryTarget,
15
- rerunPipeline,
16
- runDeploy,
34
+ type RunContext,
35
+ runContext,
36
+ semverTags,
17
37
  ShippedScope,
18
38
  shippedScope,
39
+ step,
19
40
  StepFailed,
20
41
  type LoopEvent,
21
42
  verify,
22
- waitFor
43
+ type VersionRequest,
44
+ VersionScheme,
45
+ versionScheme,
46
+ VersionSchemeName,
47
+ type Versions
23
48
  } from '@kitman-sh/sdk/loop'
24
49
  import * as Effect from 'effect/Effect'
50
+ import * as Layer from 'effect/Layer'
51
+ import * as Option from 'effect/Option'
25
52
  import * as Schema from 'effect/Schema'
26
53
  import { DeliveryFields, deliveryLayerWords, epicOf } from './delivery'
54
+ import deployLoop, { defaultTarget, type DeployOutput } from './deploy'
55
+ import landLoop, { LandInput, LandOutput } from './land'
56
+
57
+ const releaser = agent('releaser')
27
58
 
28
59
  /** An id a full-auto answer's evidence can carry: Kitman refuses an empty one or one over 240 characters. */
29
60
  const ApprovalRef = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(240))
@@ -32,92 +63,185 @@ const ApprovalRef = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLengt
32
63
  export const approvalRef = (event: LoopEvent | undefined) =>
33
64
  [event?.payload.reviewId, event?.payload.approvalId].find(Schema.is(ApprovalRef))
34
65
 
35
- const Input = Schema.Struct({
36
- /** The tag to release; the drafting agent proposes one when left out. */
37
- tag: Schema.optional(Schema.String),
38
- /** The revision to tag; the Run's base branch head when left out. */
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),
42
- /** A release ChangeRequest to wait for, merge, and tag the merge of. */
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),
46
- /** What the release deploys to; one Release deploys to it at a time. The deploy Event type when left out. */
47
- deployTarget: Schema.optional(Schema.String),
48
- /** The Event type the deploy reports; `deploy` when left out. Its payload names the `tag` and a `status`. */
49
- deployEvent: Schema.optional(Schema.String),
50
- /** How long to wait for the deploy; 60 when left out. */
51
- deployTimeoutMinutes: Schema.optional(Schema.Int),
52
- /** The repository to release; the Run's Task's, else its Team's default, when left out. */
53
- repoBindingId: Schema.optional(Schema.String),
54
- /** This Run's own release trigger, over its Project's, Team's and Workspace's; `merge` releases now, as for a hotfix. */
55
- releaseTrigger: Schema.optional(ReleaseTrigger),
56
- /** The release trigger the Run uses and the layer it came from; Kitman sets it when the Run starts. */
57
- releaseWhen: Schema.optional(ResolvedReleaseTrigger),
58
- /** The Milestone or Project whose completion started this Release, and the Tasks it ships. */
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
65
- })
66
+ /** A Version Scheme's or Bump Policy's name: a shipped one, or one a Kit provides as a Layer. */
67
+ const SchemeName = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9._-]{1,60}$/u))
66
68
 
67
- const Drafted = Schema.Struct({
68
- /** The next version's tag. */
69
+ /** What a Release stopped after its notes cut and drafted, which a second Run goes on from `approve` with. */
70
+ export const ReleaseDraft = Schema.Struct({
69
71
  tag: Schema.String,
70
- /** The latest release tag before it; left out when there is none. */
71
- previousTag: Schema.optional(Schema.String),
72
+ revision: Schema.String.annotate({ description: 'The revision the gate proved.' }),
73
+ previousTag: Schema.NullOr(Schema.String),
74
+ bump: Schema.optionalKey(Bump),
75
+ changeRequests: Schema.Array(ComparedChange),
76
+ unlinked: Schema.Int,
77
+ truncated: Schema.optionalKey(Schema.Boolean),
72
78
  title: Schema.String,
73
79
  notes: Schema.String,
74
- /** The ChangeRequests the notes cover. */
75
- changeRequests: Schema.Array(Schema.String)
80
+ lands: Schema.optionalKey(Schema.Struct({ source: Schema.String, target: Schema.String })).annotate({
81
+ description: 'The branch an approval lands, and where, before the merge is tagged.'
82
+ })
76
83
  })
77
84
 
78
- type Drafted = typeof Drafted.Type
85
+ export type ReleaseDraft = typeof ReleaseDraft.Type
79
86
 
80
- /** The draft, its version picked again once the Release holds the deploy target. */
81
- const Picked = Schema.Struct({
82
- ...Drafted.fields,
83
- /** A release tag that already contains the revision and is not this Release's own tag at it, which leaves nothing to release. */
84
- releasedIn: Schema.optional(Schema.String)
87
+ const Input = Schema.Struct({
88
+ stopAfter: Schema.optional(Schema.Literal('notes')).annotate({
89
+ description:
90
+ 'Runs `gate`, `cut` and `notes` and ends `drafted`, returning the tag, the revision and the notes as `drafted`, asking nothing and landing or tagging nothing.'
91
+ }),
92
+ drafted: Schema.optional(ReleaseDraft).annotate({
93
+ description:
94
+ 'What a Release with `stopAfter` returned: this Run proves its revision with `gate` again and goes on from `approve` with it, running no cut or notes of its own.'
95
+ }),
96
+ approvedByCaller: Schema.optional(Schema.Boolean).annotate({
97
+ description:
98
+ 'Set by a Loop that calls this one with `drafted` after its own Question approved it, as release-set: `approve` asks nothing. A Run no Run started asks anyway.'
99
+ }),
100
+ tag: Schema.optional(Schema.String).annotate({
101
+ description: 'The tag to release; the Version Scheme gives one when left out.'
102
+ }),
103
+ revision: Schema.optional(Schema.String).annotate({
104
+ description: "The revision to tag; the Run's base branch head when left out."
105
+ }),
106
+ branch: Schema.optional(Schema.String).annotate({
107
+ description: "The branch to gate and tag, which the Run starts from; the repository's default branch when left out."
108
+ }),
109
+ review: Schema.optional(ApprovalRef).annotate({
110
+ description: 'The approval of the change being released, recorded with a full-auto approval of the release.'
111
+ }),
112
+ land: Schema.optional(Schema.Union([Schema.Boolean, Schema.String])).annotate({
113
+ description:
114
+ "Delivers the Run's base branch with the Land Loop after approval and tags the merge: `true` into the branch it delivers into, or the branch named."
115
+ }),
116
+ deliversInto: Schema.optional(Schema.String).annotate({
117
+ description: "Set by Kitman: the branch the Run's `branch` delivers into, when it is a Milestone's or a Project's."
118
+ }),
119
+ taskId: Schema.optional(Schema.String).annotate({
120
+ description: "The Task it delivers, whose Project's release trigger the Run uses."
121
+ }),
122
+ readyHead: Schema.optional(Schema.String).annotate({
123
+ description: 'The head `change_request.ready` found approved and green, when that Event started the Run.'
124
+ }),
125
+ deploy: Schema.optional(Schema.Boolean).annotate({
126
+ description:
127
+ 'Deploys the release with the Deploy Loop as a Child Run; `false` ends it published, holding no deploy claim.'
128
+ }),
129
+ deployTarget: Schema.optional(DeployTargetName).annotate({
130
+ description:
131
+ 'The Deploy Target the release deploys to, `production` when left out; one Release deploys to it at a time. The targets a promotion passes on the way are held only while each deploys.'
132
+ }),
133
+ deployPromote: Schema.optional(Schema.Boolean).annotate({
134
+ description:
135
+ "Promotes the release through the repository's Deploy Targets in their order up to `deployTarget`, as the Deploy Loop's `promote` does, instead of deploying to `deployTarget` alone."
136
+ }),
137
+ deployEvent: Schema.optional(Schema.String).annotate({
138
+ description:
139
+ 'The Event type the deploy reports; `deploy` when left out. Its payload names the `tag` and a `status`.'
140
+ }),
141
+ deployTimeoutMinutes: Schema.optional(Schema.Int).annotate({
142
+ description: 'How long to wait for the deploy; 60 when left out.'
143
+ }),
144
+ repoBindingId: Schema.optional(Schema.String).annotate({
145
+ description: "The repository to release; the Run's Task's, else its Team's default, when left out."
146
+ }),
147
+ releaseTrigger: Schema.optional(ReleaseTrigger).annotate({
148
+ description:
149
+ "This Run's own release trigger, over its Project's, Team's and Workspace's; `merge` releases now, as for a hotfix."
150
+ }),
151
+ continues: ReleaseRoleInput.fields.continues.annotate({
152
+ description:
153
+ 'A Release whose Run published `tag` at `revision` and failed after it: this Run deploys that tag, and gates, cuts and publishes nothing. Release now sets it from the Release Kitman recorded.'
154
+ }),
155
+ releaseScope: ReleaseRoleInput.fields.releaseScope.annotate({
156
+ description: 'The Milestone or Project whose completion started this Release, and the Tasks it ships.'
157
+ }),
158
+ closesProject: Schema.optional(Schema.Boolean).annotate({
159
+ description:
160
+ "Whether the release.due that started it closes its Project; a Milestone's that does not is a release candidate under `project-name`."
161
+ }),
162
+ candidate: ReleaseRoleInput.fields.candidate.annotate({
163
+ description:
164
+ "Without `closesProject`, whether it cuts a release candidate under `project-name`; `false` cuts the Project's version. A Milestone's scope is a candidate when left out."
165
+ }),
166
+ reopened: Schema.optional(Schema.Boolean).annotate({
167
+ description:
168
+ "Whether a revert reopened what closed after its Project's close was released; `project-name` then gives the next free patch."
169
+ }),
170
+ scheme: Schema.optional(SchemeName).annotate({
171
+ description:
172
+ "The Version Scheme by name: `auto` (the Project's name when it holds a version, else semver from tags), `semver-tags`, `project-name`, `calver`, or one a Kit provides as a Layer; `auto` when left out. Semver from tags stands behind any that gives no version."
173
+ }),
174
+ bumpPolicy: Schema.optional(SchemeName).annotate({
175
+ description:
176
+ 'The Bump Policy by name: `outcome`, `conventional-commits`, `labels`, `fixed`, or one a Kit provides as a Layer; `outcome` when left out.'
177
+ }),
178
+ bump: Schema.optional(Bump).annotate({
179
+ description: 'How far the version moves, over what the Bump Policy says.'
180
+ }),
181
+ prerelease: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9A-Za-z-]{1,40}$/u))).annotate({
182
+ description: 'Makes the version a prerelease with this identifier, such as `rc`, `beta` or `next`.'
183
+ }),
184
+ prefix: Schema.optional(Schema.String.check(Schema.isPattern(/^[A-Za-z0-9._/-]{1,60}$/u))).annotate({
185
+ description:
186
+ 'Counts only tags with this prefix, such as `web-v`, and tags with it; the one earlier tags use when left out.'
187
+ }),
188
+ calverFormat: Schema.optional(CalverFormat).annotate({
189
+ description: "The `calver` scheme's format; `YYYY.MM.MICRO` when left out."
190
+ }),
191
+ bumpLabels: Schema.optional(
192
+ Schema.Struct({
193
+ major: Schema.optionalKey(Schema.String),
194
+ minor: Schema.optionalKey(Schema.String),
195
+ patch: Schema.optionalKey(Schema.String)
196
+ })
197
+ ).annotate({ description: "The `labels` policy's label for each bump." }),
198
+ fixedBump: Schema.optional(Bump).annotate({
199
+ description: "The `fixed` policy's bump; `patch` when left out."
200
+ }),
201
+ ...DeliveryFields
85
202
  })
86
203
 
204
+ type Input = typeof Input.Type
205
+
206
+ /** What the releaser writes: everything else in the release Kitman reads from the repository. */
207
+ const Notes = Schema.Struct({ title: Schema.String, notes: Schema.String })
208
+
209
+ type Notes = typeof Notes.Type
210
+
87
211
  const Output = Schema.Struct({
88
- status: Schema.Literals([
89
- 'gate_failed',
90
- 'not_mergeable',
91
- 'rejected',
92
- 'deployed',
93
- /** A release candidate the deploy script published and did not deploy. */
94
- 'published',
95
- 'rolled_back',
96
- 'deploy_failed',
97
- /** The deploy failed after production changed, and so did the rollback: production may be broken. */
98
- 'rollback_failed',
99
- 'timed_out',
100
- /** Its trigger is a Milestone or Project being done, and this Run was not started by one nor told to release now. */
101
- 'not_due',
102
- /** A Milestone or Project started it without the version to cut, which a Release never picks for itself. */
103
- 'no_version',
104
- /** An existing tag already contains the revision, as when another Release tagged it first; never for a Milestone or Project. */
105
- 'nothing_to_release'
106
- ]),
107
- /** Why it stopped, or what happened, in a line. */
108
- reason: Schema.String,
109
- tag: Schema.optional(Schema.String),
110
- notesArtifactId: Schema.optional(Schema.String),
111
- /** A person chose Leave it in the recover Question. */
112
- leftUndeployed: Schema.optional(Schema.Boolean),
113
- revision: Schema.optional(Schema.String),
114
- url: Schema.optional(Schema.String),
115
- /** The release trigger the Run used and the layer it came from. */
116
- releaseWhen: Schema.optional(ResolvedReleaseTrigger),
117
- /** Where the Run's delivery lands and the layer it came from. */
118
- deliversTo: Schema.optional(ResolvedDeliveryTarget),
119
- /** The Milestone or Project that triggered it, and the Tasks it shipped. */
120
- shipped: Schema.optional(ShippedScope)
212
+ ...ReleaseRoleOutput.fields,
213
+ status: ReleaseRoleStatus.annotate({
214
+ description: 'How the Release ended, such as deployed, published, gate_failed or not_due.'
215
+ }),
216
+ reason: Schema.String.annotate({ description: 'Why it stopped, or what happened, in a line.' }),
217
+ tag: Schema.optional(Schema.String).annotate({ description: 'The tag it released, when it got that far.' }),
218
+ drafted: Schema.optional(ReleaseDraft).annotate({
219
+ description: 'With `stopAfter`, what a second Run given it as Input goes on from `approve` with.'
220
+ }),
221
+ notesArtifactId: Schema.optional(Schema.String).annotate({ description: 'The Artifact holding the release notes.' }),
222
+ changeRequests: Schema.optional(Schema.Array(ComparedChange)).annotate({
223
+ description: 'The ChangeRequests merged since the previous version, with their Tasks, as `compare` read them.'
224
+ }),
225
+ leftUndeployed: Schema.optional(Schema.Boolean).annotate({
226
+ description: 'A person chose Leave it in the recover Question.'
227
+ }),
228
+ revision: Schema.optional(Schema.String).annotate({ description: 'The revision it tagged.' }),
229
+ landed: Schema.optional(ChangeRequestResult).annotate({
230
+ description: 'The ChangeRequest that delivered the branch, with `land`; started again, the Release continues on it.'
231
+ }),
232
+ squashed: Schema.optional(Schema.Boolean).annotate({
233
+ description: 'The forge squashed the landed branch, so the tags on it are not ancestors of the new tag.'
234
+ }),
235
+ url: Schema.optional(Schema.String).annotate({ description: 'The published release, when the forge gave one.' }),
236
+ releaseWhen: Schema.optional(ResolvedReleaseTrigger).annotate({
237
+ description: 'The release trigger the Run used and the layer it came from.'
238
+ }),
239
+ deliversTo: Schema.optional(ResolvedDeliveryTarget).annotate({
240
+ description: "Where the Run's delivery lands and the layer it came from."
241
+ }),
242
+ shipped: Schema.optional(ShippedScope).annotate({
243
+ description: 'The Milestone or Project that triggered it, and the Tasks it shipped.'
244
+ })
121
245
  })
122
246
 
123
247
  type Output = typeof Output.Type
@@ -149,60 +273,147 @@ const scopePrompt = (scope: ReleaseScope | undefined) =>
149
273
  scope.tasks.map(task => `- ${task.key} ${task.title}`).join('\n')
150
274
  ]
151
275
 
152
- /** What a Milestone or Project releases of its Project's version: its next release candidate, or the version itself. */
153
- type Cut = { readonly version: string; readonly candidate: boolean }
276
+ /** The revision the gate proved, which is tagged unless the Release lands it first. */
277
+ export class Gated extends Schema.TaggedClass<Gated>()('Gated', { revision: Schema.String }) {}
278
+
279
+ export class GateFailed extends Schema.TaggedError<GateFailed>()('GateFailed', {
280
+ reason: Schema.String,
281
+ revision: Schema.String
282
+ }) {}
283
+
284
+ /** The version a Release cuts at a revision and what it holds since the previous one, read from the repository. */
285
+ export class Cut extends Schema.TaggedClass<Cut>()('Cut', {
286
+ tag: Schema.String,
287
+ /** The tag before it, null when none does. */
288
+ previousTag: Schema.NullOr(Schema.String),
289
+ /** The bump the tag is of; left out for a `tag` the Input gave. */
290
+ bump: Schema.optionalKey(Bump),
291
+ /** What merged since the previous tag, as `compare` read it; none when there is no previous tag. */
292
+ changeRequests: Schema.Array(ComparedChange),
293
+ /** Commits since the previous tag that no ChangeRequest merged as. */
294
+ unlinked: Schema.Int,
295
+ truncated: Schema.optionalKey(Schema.Boolean)
296
+ }) {}
297
+
298
+ /** Nothing merged since the previous version, or a later version already holds the revision. */
299
+ export class NothingToRelease extends Schema.TaggedError<NothingToRelease>()('NothingToRelease', {
300
+ reason: Schema.String,
301
+ /** The tag that already releases the revision. */
302
+ tag: Schema.optionalKey(Schema.String)
303
+ }) {}
304
+
305
+ /** The bump's version is tagged where the revision does not reach it. */
306
+ export class VersionTaken extends Schema.TaggedError<VersionTaken>()('VersionTaken', { reason: Schema.String }) {}
307
+
308
+ /** What the releaser wrote. */
309
+ export class Drafted extends Schema.TaggedClass<Drafted>()('Drafted', {
310
+ title: Schema.String,
311
+ notes: Schema.String
312
+ }) {}
154
313
 
155
- const nextCandidateWords = (version: string) =>
156
- `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`
314
+ export class Approved extends Schema.TaggedClass<Approved>()('Approved', {}) {}
157
315
 
158
- const tagWords = (tag: string | undefined, cut: Cut | undefined) => {
159
- if (cut?.candidate === true)
160
- return `The release is a release candidate of ${cut.version}, numbered again once it is tagged. Give as tag ${nextCandidateWords(cut.version)}.`
316
+ /** A person asked for these changes to the notes, which `notes` redrafts from. */
317
+ export class Edit extends Schema.TaggedClass<Edit>()('Edit', { edit: Schema.String }) {}
318
+
319
+ export class Rejected extends Schema.TaggedError<Rejected>()('Rejected', { reason: Schema.String }) {}
320
+
321
+ /** The Land Loop merged the branch at `revision`. */
322
+ export class Landed extends Schema.TaggedClass<Landed>()('Landed', {
323
+ revision: Schema.String,
324
+ changeRequest: Schema.optionalKey(ChangeRequestResult),
325
+ /** The merge does not reach the head that was gated, as when the forge squashed it. */
326
+ squashed: Schema.optionalKey(Schema.Literal(true))
327
+ }) {}
328
+
329
+ /** The branches do not differ: `revision` is the head of the branch landed on. */
330
+ export class NothingToLand extends Schema.TaggedClass<NothingToLand>()('NothingToLand', {
331
+ revision: Schema.String
332
+ }) {}
333
+
334
+ export class NotLanded extends Schema.TaggedError<NotLanded>()('NotLanded', {
335
+ reason: Schema.String,
336
+ changeRequest: Schema.optionalKey(ChangeRequestResult)
337
+ }) {}
338
+
339
+ export class Published extends Schema.TaggedClass<Published>()('Published', {
340
+ tag: Schema.String,
341
+ revision: Schema.String,
342
+ url: Schema.String
343
+ }) {}
344
+
345
+ /** The forge found the tag at another revision (`elsewhere`), or released by another Run at this one. */
346
+ export class TagTaken extends Schema.TaggedError<TagTaken>()('TagTaken', {
347
+ tag: Schema.String,
348
+ reason: Schema.String,
349
+ releasedByOther: Schema.Boolean
350
+ }) {}
351
+
352
+ /** The Deploy Loop deployed the tag, or published a release candidate it does not deploy. */
353
+ export class Deployed extends Schema.TaggedClass<Deployed>()('Deployed', {
354
+ status: Schema.Literals(['deployed', 'published']),
355
+ reason: Schema.String
356
+ }) {}
357
+
358
+ /** The Deploy Loop's guard held the deploy. */
359
+ export class NotDeployed extends Schema.TaggedError<NotDeployed>()('NotDeployed', { reason: Schema.String }) {}
360
+
361
+ export class DeployFailed extends Schema.TaggedError<DeployFailed>()('DeployFailed', {
362
+ status: Schema.Literals(['rolled_back', 'deploy_failed', 'rollback_failed', 'timed_out']),
363
+ reason: Schema.String,
364
+ leftUndeployed: Schema.optionalKey(Schema.Literal(true))
365
+ }) {}
366
+
367
+ const changeLine = (change: ComparedChange) => {
368
+ const tasks = change.tasks.map(
369
+ task => `${task.key} ${task.title}${task.outcome === undefined ? '' : ` (${task.outcome})`}`
370
+ )
371
+
372
+ return `- ${change.number} ${change.title} (${change.url}): ${tasks.length === 0 ? 'no Task' : tasks.join('; ')}`
373
+ }
161
374
 
162
- const given = tag ?? cut?.version
375
+ const contentsPrompt = (cut: Cut, revision: string) => {
376
+ if (cut.previousTag === null)
377
+ return [
378
+ `There is no earlier release tag, so this is the first release: draft its notes from the repository’s history (\`git log ${revision}\`).`
379
+ ]
163
380
 
164
- return given === undefined
165
- ? '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.'
166
- : `The release is tagged ${given}.`
381
+ return [
382
+ cut.changeRequests.length === 0
383
+ ? `No ChangeRequest has merged since ${cut.previousTag}.`
384
+ : `These ChangeRequests merged since ${cut.previousTag}, each with the Tasks it delivers and their Outcome:\n${cut.changeRequests.map(changeLine).join('\n')}`,
385
+ ...(cut.truncated === true ? ['The list stops short: read the rest with `git log`.'] : []),
386
+ ...(cut.unlinked === 0
387
+ ? []
388
+ : [
389
+ `${cut.unlinked} commits since ${cut.previousTag} merged with no ChangeRequest: read them with \`git log ${cut.previousTag}..${revision}\`.`
390
+ ])
391
+ ]
167
392
  }
168
393
 
169
- const draftPrompt = (
170
- tag: string | undefined,
171
- cut: Cut | undefined,
172
- changeRequestId: string | undefined,
173
- scope?: ReleaseScope
174
- ) =>
394
+ const notesPrompt = (cut: Cut, revision: string, scope: ReleaseScope | undefined) =>
175
395
  [
176
- 'Fetch the base branch and tags first (`git fetch origin --tags`).',
177
- 'Draft the release notes for the ChangeRequests merged since the last release tag on the base branch, including those with no linked Task.',
396
+ `Write the release notes for ${cut.tag}.`,
397
+ `It tags ${revision}. Your checkout may be at another commit, so read history up to ${revision}, not HEAD, fetching it first if your checkout lacks it.`,
398
+ ...contentsPrompt(cut, revision),
178
399
  ...scopePrompt(scope),
179
- ...(changeRequestId === undefined ? [] : [`The release ChangeRequest ${changeRequestId} is part of it.`]),
180
- 'Group them by what a user of the software notices, and name each ChangeRequest you cover.',
181
- tagWords(tag, cut),
182
- 'Give the latest earlier release tag as previousTag, or leave it out when there is none.'
400
+ 'Group them by what a user of the software notices, and name each ChangeRequest you cover. Give a title and the notes: Kitman reads the version and the ChangeRequests from the repository itself.'
183
401
  ].join('\n\n')
184
402
 
185
403
  const regexSpecial = /[.*+?^$()|[\]{}\\]/g
186
404
 
187
405
  const escaped = (text: string) => text.replaceAll(regexSpecial, '\\$&')
188
406
 
189
- /** The number of `tag` as a release candidate of `version`; undefined when it is not one. */
190
- const candidateNumber = (tag: string, version: string) => {
191
- const [, number] = new RegExp(`^${escaped(version)}-rc\\.(\\d+)$`).exec(tag) ?? []
192
-
193
- return number === undefined ? undefined : Number(number)
194
- }
195
-
196
- /** `text` naming `tag` where it named `taken`; `-rc.1` is not read inside `-rc.10`. */
407
+ /** `text` naming `tag` where it named `taken` as a whole tag: `v1.3.3` is not read inside `v1.3.3-rc.1`, nor `-rc.1` in `-rc.10`. */
197
408
  const renameTag = (text: string, taken: string, tag: string) =>
198
- text.replaceAll(new RegExp(`${escaped(taken)}(?!\\d)`, 'g'), tag)
409
+ taken === tag ? text : text.replaceAll(new RegExp(`(?<![\\w.-])${escaped(taken)}(?![\\w-]|\\.\\w)`, 'g'), () => tag)
199
410
 
200
411
  const isTagElsewhere = (failed: StepFailed) => failed.reason.includes('TAG_ELSEWHERE')
201
412
 
202
413
  /** Another Run already published the tag at this revision. */
203
414
  const isReleasedByOther = (failed: StepFailed) => failed.reason.includes('TAG_RELEASED')
204
415
 
205
- const redraftPrompt = (drafted: Drafted, edit: string) =>
416
+ const redraftPrompt = (drafted: Notes, edit: string) =>
206
417
  [
207
418
  'Redraft these release notes as asked, keeping the tag and everything not mentioned.',
208
419
  `Asked: ${edit}`,
@@ -211,329 +422,390 @@ const redraftPrompt = (drafted: Drafted, edit: string) =>
211
422
  '```'
212
423
  ].join('\n\n')
213
424
 
214
- const pickInstructions = (drafted: Drafted, revision: string, givenTag: string | undefined, cut: Cut | undefined) => {
215
- // A Milestone or Project cuts its own release even at a revision another tag contains, so its Tasks are published.
216
- if (cut !== undefined)
217
- return [
218
- `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.`
219
- ]
425
+ /** Why a bump has no free tag, naming the bumps that have one; Release never guesses another number. */
426
+ const takenWords = (read: Versions, bump: Bump, where: string) => {
427
+ const free = Bump.literals.flatMap(other => {
428
+ const tag = read.next[other]
220
429
 
221
- const ownTag = givenTag ?? drafted.tag
430
+ return tag === undefined ? [] : [`${other} gives ${tag}`]
431
+ })
222
432
 
223
- return [
224
- `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.`,
225
- givenTag === undefined
226
- ? `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.`
227
- : `Otherwise give the draft unchanged. The release is tagged ${givenTag}.`
228
- ]
433
+ return `A ${bump} release would be ${read.taken?.[bump] ?? 'a version'}, which is tagged where ${where} does not reach it. Give \`tag\`${free.length === 0 ? '' : `, or a \`bump\` whose tag is free: ${free.join(', ')}`}.`
229
434
  }
230
435
 
231
- const pickPrompt = (drafted: Drafted, revision: string, givenTag: string | undefined, cut: Cut | undefined) =>
232
- [
233
- '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.',
234
- ...pickInstructions(drafted, revision, givenTag, cut),
235
- '```json',
236
- JSON.stringify(drafted, null, 2),
237
- '```'
238
- ].join('\n\n')
239
-
240
436
  const approval = ['Approve', 'Edit notes', 'Reject'] as const
241
437
 
242
- /**
243
- * Waits at no model cost until the release ChangeRequest is green, approved and mergeable, and gives the head that
244
- * passed; or why it stopped. `round` names a gate run again after the head moved.
245
- */
246
- const readyToMerge = (changeRequestId: string, round = 1) =>
438
+ const outcomeWords: Record<DeployOutput['status'], string> = {
439
+ deployed: 'deployed',
440
+ published: 'published, not deployed',
441
+ rolled_back: 'rolled back',
442
+ deploy_failed: 'failed to deploy',
443
+ rollback_failed: 'failed to deploy, and the rollback failed too',
444
+ timed_out: 'did not report a deploy in time',
445
+ not_deployed: 'not deployed'
446
+ }
447
+
448
+ /** A Version Scheme and Bump Policy of a Kit's own, which a Release uses when its Input's `scheme` or `bumpPolicy` names it. */
449
+ export type ReleaseVersioning = {
450
+ readonly versionScheme?: Layer.Layer<VersionScheme>
451
+ readonly bumpPolicy?: Layer.Layer<BumpPolicy>
452
+ }
453
+
454
+ const unnamed = (kind: string, name: string, shipped: readonly string[]) =>
455
+ new StepFailed({
456
+ step: 'cut',
457
+ reason: `No ${kind} is named ${name}: give one of ${shipped.join(', ')}, or the name of one the Kit provides as a Layer`
458
+ })
459
+
460
+ /** The Version Scheme the Input names, a Kit's own of that name else a shipped one, with semver from tags behind it. */
461
+ const schemeOf = (input: Input) =>
247
462
  Effect.gen(function* () {
248
- // A newer head whose pipeline finishes while approval is awaited is gated afresh, up to 10 times.
249
- for (let pass = 1; ; pass++) {
250
- const at = (name: string) => {
251
- const named = pass === 1 ? name : `${name}:moved:${pass}`
463
+ const name = input.scheme ?? 'auto'
464
+ const provided = yield* Effect.serviceOption(VersionScheme)
252
465
 
253
- return round === 1 ? named : `${named}:${round}`
254
- }
466
+ const named =
467
+ Option.isSome(provided) && provided.value.name === name
468
+ ? provided.value
469
+ : Schema.is(VersionSchemeName)(name)
470
+ ? versionScheme(name, input.calverFormat === undefined ? {} : { calverFormat: input.calverFormat })
471
+ : yield* unnamed('Version Scheme', name, VersionSchemeName.literals)
255
472
 
256
- let read = yield* pipelineStatus(at('gate'), { changeRequestId })
473
+ return named === semverTags || named === auto ? named : { ...chain(named, semverTags), name: named.name }
474
+ })
257
475
 
258
- // Read again after each pipeline Event, on whichever head is newest, so the gate judges what the forge says now.
259
- for (let look = 1; look <= 10 && (read.status === 'running' || read.status === 'none'); look++) {
260
- const again = (name: string) => at(look === 1 ? name : `${name}:${look}`)
476
+ /** The Bump Policy the Input names: a Kit's own of that name, else a shipped one. */
477
+ const policyOf = (input: Input) =>
478
+ Effect.gen(function* () {
479
+ const name = input.bumpPolicy ?? 'outcome'
480
+ const provided = yield* Effect.serviceOption(BumpPolicy)
261
481
 
262
- yield* pipelineMoved(again('gate:pipeline'), changeRequestId, read)
263
- read = yield* pipelineStatus(again('gate:after'), { changeRequestId })
264
- }
482
+ if (Option.isSome(provided) && provided.value.name === name) return provided.value
265
483
 
266
- if (read.status !== 'success') {
267
- const failing = read.jobs.filter(job => job.status === 'failed').map(job => job.name)
484
+ if (!Schema.is(BumpPolicyName)(name)) return yield* unnamed('Bump Policy', name, BumpPolicyName.literals)
268
485
 
269
- return {
270
- status: 'gate_failed',
271
- reason: `The pipeline at ${read.head} is ${read.status}${failing.length === 0 ? '' : `: ${failing.join(', ')}`}`,
272
- revision: read.head
273
- } satisfies Output
274
- }
486
+ return bumpPolicy(name, {
487
+ ...(input.bumpLabels === undefined ? undefined : { labels: input.bumpLabels }),
488
+ ...(input.fixedBump === undefined ? undefined : { fixed: input.fixedBump })
489
+ })
490
+ })
275
491
 
276
- const approved = yield* waitFor(at('approved'), {
277
- event: 'change_request.approval',
278
- // An approval of an earlier commit does not approve the one whose pipeline passed.
279
- filter: { changeRequestId, approved: true, head: read.head },
280
- timeout: '7 days',
281
- or:
282
- read.readAt === undefined
283
- ? []
284
- : [{ event: 'change_request.pipeline', filter: { changeRequestId }, since: read.readAt }]
285
- })
492
+ /** The Project a Milestone's or Project's completion releases; a Milestone is a candidate unless it closes the Project. */
493
+ const projectOf = (input: Input): VersionRequest['project'] => {
494
+ const scope = input.releaseScope
286
495
 
287
- if (approved.type !== 'change_request.approval') {
288
- if (pass >= 10)
289
- return {
290
- status: 'not_mergeable',
291
- reason: `ChangeRequest ${changeRequestId} kept moving while it awaited approval`
292
- } satisfies Output
496
+ if (scope === undefined) return undefined
293
497
 
294
- continue
295
- }
498
+ return {
499
+ ...(scope.projectName === undefined ? undefined : { name: scope.projectName }),
500
+ candidate:
501
+ input.closesProject === undefined ? (input.candidate ?? scope.kind === 'milestone') : !input.closesProject,
502
+ ...(input.reopened === true ? { reopened: true } : undefined)
503
+ }
504
+ }
296
505
 
297
- const mergeable = yield* waitFor(at('mergeable'), {
298
- event: 'change_request.mergeable',
299
- filter: { changeRequestId },
300
- timeout: '1 hour'
301
- })
506
+ /** A Task as Kitman holds it for the Bump Policy: its Outcome, none when its Task Type has none, and its labels. */
507
+ const heldTask = (task: ReleaseScope['tasks'][number]): ReleaseTask => ({
508
+ key: task.key,
509
+ ...(task.outcome === undefined ? undefined : { outcome: task.outcome }),
510
+ ...(task.labels === undefined ? undefined : { labels: task.labels })
511
+ })
512
+
513
+ /**
514
+ * What the Bump Policy reads: the changes the releaser read, each Task's Outcome and labels taken from Kitman where the
515
+ * Milestone or Project holds the Task, and the Tasks it ships that no change names as one change of their own.
516
+ */
517
+ const policyChanges = (
518
+ changes: readonly ReleaseChange[],
519
+ scope: ReleaseScope | undefined
520
+ ): readonly ReleaseChange[] => {
521
+ if (scope === undefined) return changes
522
+
523
+ const held = new Map(scope.tasks.map(task => [task.key, task]))
302
524
 
303
- if (mergeable.payload.mergeable === false)
304
- return {
305
- status: 'not_mergeable',
306
- reason: `ChangeRequest ${changeRequestId} does not merge cleanly; bring it up to date first`
307
- } satisfies Output
525
+ const read = changes.map(change => {
526
+ if (change.tasks === undefined) return change
308
527
 
309
- const review = approvalRef(approved)
528
+ return {
529
+ ...change,
530
+ tasks: change.tasks.map(task => {
531
+ const kept = held.get(task.key)
310
532
 
311
- return { passed: read.head, ...(review === undefined ? undefined : { review }) }
533
+ return kept === undefined ? task : heldTask(kept)
534
+ })
312
535
  }
313
- }).pipe(
314
- Effect.catchTags({
315
- WaitTimedOut: timedOut =>
316
- Effect.succeed({
317
- status: 'not_mergeable',
318
- reason: `Nothing happened on ChangeRequest ${changeRequestId} while waiting for ${timedOut.event}`
319
- } satisfies Output),
320
- ChangeRequestClosed: closed =>
321
- Effect.succeed({
322
- status: 'not_mergeable',
323
- reason: `ChangeRequest ${changeRequestId} was ${closed.merged ? 'merged' : 'closed'} before Kitman released it`
324
- } satisfies Output)
325
- })
326
- )
536
+ })
537
+
538
+ const named = new Set(read.flatMap(change => (change.tasks ?? []).map(task => task.key)))
539
+ const unnamed = scope.tasks.filter(task => !named.has(task.key))
327
540
 
328
- const recovery = (previous: string | undefined) =>
329
- previous === undefined
330
- ? (['Retry the deploy', 'Leave it'] as const)
331
- : (['Retry the deploy', `Roll back to ${previous}`, 'Leave it'] as const)
541
+ return unnamed.length === 0 ? read : [...read, { tasks: unnamed.map(heldTask) }]
542
+ }
543
+
544
+ /** A ChangeRequest `compare` found, as a Bump Policy reads it. */
545
+ const releaseChange = (change: ComparedChange): ReleaseChange => ({
546
+ changeRequest: change.number,
547
+ title: change.title,
548
+ tasks: change.tasks.map(task => ({
549
+ key: task.key,
550
+ ...(task.outcome === undefined ? undefined : { outcome: task.outcome }),
551
+ ...(task.labels === undefined ? undefined : { labels: task.labels })
552
+ }))
553
+ })
554
+
555
+ /** What `compare` found, as a Bump Policy reads it: its ChangeRequests, and every commit's message, theirs or a push's. */
556
+ const releaseChanges = (contents: ComparedSide | undefined): readonly ReleaseChange[] => [
557
+ ...(contents?.changeRequests ?? []).map(releaseChange),
558
+ ...(contents?.messages === undefined || contents.messages.length === 0 ? [] : [{ commits: contents.messages }])
559
+ ]
560
+
561
+ const releaseResource = (input: Input, context: RunContext) =>
562
+ `release:${input.repoBindingId ?? context.repository?.repoBinding.id ?? 'repository'}`
332
563
 
333
564
  /**
334
- * Proves the release before anyone is asked: the approved checks pass on the revision to tag, or a release
335
- * ChangeRequest is green, approved and mergeable. A failed check runs once more in a fresh checkout; one that passes
336
- * there is recorded as an environment failure. It then asks once, with no default, whether to release the drafted
337
- * notes, which can be edited in place. On approval it merges the ChangeRequest when there is one, holds the deploy
338
- * target so two Releases never tag or deploy over each other, taking it over from a Release that failed holding it,
339
- * and picks the version again under it: a revision an existing tag already contains ends as nothing to release. It
340
- * then tags and publishes once (its own release of the tag at the same revision counts as done; one at another is
341
- * never moved) and waits for the deploy. A release candidate the repository's deploy script only publishes ends
342
- * published, not deployed, and is never rolled back for it. A failed or late deploy asks whether
343
- * to retry (it runs the tag's failed pipeline again and waits), roll back to the previous tag (it runs that
344
- * tag's pipeline again in full and waits for its deploy), or leave it, which it does by default.
345
- *
346
- * Under a Milestone or Project release trigger, it releases only when that Milestone's or Project's completion starts
347
- * it, with the Project's version and the Tasks it ships, which it records; without a version it stops rather than
348
- * choose one. A Milestone's release candidate is numbered under the deploy target, after the latest one the repository
349
- * has, and gives way to the next when the forge finds it taken; the version itself is never moved. Either is released
350
- * even at a revision another tag contains. A Run whose `releaseTrigger` is `merge` releases anyway. A Team can turn on
351
- * starting it on each head of a ChangeRequest delivering a Task that is approved and passed its pipeline while no Run
352
- * works the ChangeRequest; it releases that only under a `merge` trigger.
565
+ * Proves the revision to release before anyone is asked: the approved checks pass on it. A failed check runs once more
566
+ * in a fresh checkout; one that passes there is recorded as an environment failure.
353
567
  */
354
- export default defineLoop({
355
- id: 'release',
356
- version: '2.4.0',
357
- title: 'Release',
358
- input: Input,
359
- output: Output,
360
- agents: { releaser: 'releaser' },
361
- checkout: 'read',
362
- // Kitman records release.due per repository when a Milestone or Project closes under that trigger.
363
- when: [
364
- {
365
- event: 'release.due',
366
- input: {
367
- version: 'version',
368
- candidate: 'candidate',
369
- releaseScope: 'releaseScope',
370
- releaseWhen: 'releaseWhen',
371
- repoBindingId: 'repoBindingId'
372
- }
373
- },
374
- {
375
- event: 'change_request.ready',
376
- filter: { busy: false },
377
- input: { changeRequestId: 'changeRequestId', taskId: 'taskId' },
378
- optIn: true,
379
- description:
380
- '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.'
381
- }
382
- ],
383
- capabilities: [
384
- 'agent_work',
385
- 'ask',
386
- 'verify',
387
- 'claim',
388
- 'publish_release',
389
- 'read_change_request',
390
- 'merge_change_request'
391
- ],
392
- run: input =>
568
+ export const gate = step('gate', {
569
+ payload: {
570
+ revision: Schema.optional(Schema.String).annotate({
571
+ description: "The commit to verify; the Run's base branch head when left out."
572
+ })
573
+ },
574
+ success: Gated,
575
+ error: GateFailed,
576
+ run: ({ revision }) =>
393
577
  Effect.gen(function* () {
394
- const when = input.releaseWhen
395
-
396
- // A Milestone's or Project's completion starts the Release it waits for; a merge does not, unless this Run says so.
397
- if (when !== undefined && when.trigger !== 'merge' && input.releaseScope === undefined)
398
- return {
399
- status: 'not_due',
400
- reason: `Release runs when ${triggerWords[when.trigger]}, as ${layerWords[when.layer]} says; this Run did not override that`
401
- } satisfies Output
402
-
403
- const epic = epicOf(input)
404
-
405
- // Under epic delivery a sub-task's work reaches the default branch only with its epic's ChangeRequest.
406
- if (epic !== undefined && !epic.done)
407
- return {
408
- status: 'not_due',
409
- reason: `Its Task lands on ${epic.branch}, as ${deliveryLayerWords[input.deliversTo?.layer ?? 'workspace']} says; Release runs once epic ${epic.key} merges into ${epic.defaultBranch}`
410
- } satisfies Output
411
-
412
- if (input.releaseScope !== undefined && input.tag === undefined && input.version === undefined)
413
- return {
414
- status: 'no_version',
415
- reason:
416
- 'Kitman cut no version for this Milestone or Project: its Project’s name does not start with a full semver version, such as 0.11.0. Release it with a tag.',
417
- shipped: shippedScope(input.releaseScope)
418
- } satisfies Output
419
-
420
- const changeRequestId = input.changeRequestId
421
- // The commit the gate proved, and the one tagged or merged: never the branch head read again later.
422
- let gated: string
423
- let review = input.review
424
-
425
- if (changeRequestId === undefined) {
426
- // A failure an earlier Release recorded at this tree may be its checkout's, so it is run again.
427
- const gate = yield* verify('gate', {
428
- ...(input.revision === undefined ? undefined : { revision: input.revision }),
429
- rerunFailed: true
430
- })
431
-
432
- if (!gate.passed) {
433
- const failed = gate.checks.filter(check => check.status !== 'passed' && !check.preExisting)
578
+ // A failure an earlier Release recorded at this tree may be its checkout's, so it is run again.
579
+ const first = yield* verify('verify', {
580
+ ...(revision === undefined ? undefined : { revision }),
581
+ rerunFailed: true
582
+ })
434
583
 
435
- // Once more in a fresh checkout of the same commit: a check that passes there failed on its environment.
436
- const retry = yield* verify('gate:retry', {
437
- revision: gate.revision,
438
- ...(failed.length === 0 ? undefined : { checks: failed.map(check => check.name) }),
439
- rerunFailed: true
440
- })
584
+ if (first.passed) return new Gated({ revision: first.revision })
441
585
 
442
- const environmental = failed.filter(check =>
443
- retry.checks.some(again => again.name === check.name && again.status === 'passed')
444
- )
586
+ const failed = first.checks.filter(check => check.status !== 'passed' && !check.preExisting)
445
587
 
446
- const names = environmental.map(check => check.name).join(', ')
588
+ // Once more in a fresh checkout of the same commit: a check that passes there failed on its environment.
589
+ const retry = yield* verify('retry', {
590
+ revision: first.revision,
591
+ ...(failed.length === 0 ? undefined : { checks: failed.map(check => check.name) }),
592
+ rerunFailed: true
593
+ })
447
594
 
448
- if (environmental.length > 0)
449
- yield* artifact('environment-failure', {
450
- kind: 'gate_environment_failure',
451
- title: `${names} failed on the gate's checkout at ${gate.revision}`,
452
- text: `These checks failed at ${gate.revision} and passed in a fresh checkout of it, so the first checkout's environment failed them, not the code: ${names}.`,
453
- data: {
454
- revision: gate.revision,
455
- checks: environmental.map(check => ({
456
- name: check.name,
457
- failedEvidenceId: check.evidenceId,
458
- ...(check.outputTail === undefined ? undefined : { outputTail: check.outputTail })
459
- }))
460
- }
461
- })
595
+ const environmental = failed.filter(check =>
596
+ retry.checks.some(again => again.name === check.name && again.status === 'passed')
597
+ )
462
598
 
463
- // A retry passes only when its checks passed: one failing again may read as pre-existing against a moved target.
464
- const failing = retry.checks.filter(check => check.status !== 'passed').map(check => check.name)
599
+ const names = environmental.map(check => check.name).join(', ')
465
600
 
466
- if (!retry.passed || retry.checks.length === 0 || failing.length > 0) {
467
- return {
468
- status: 'gate_failed',
469
- reason: `The checks fail at ${retry.revision}, and again in a fresh checkout: ${(failing.length > 0 ? failing : failed.map(check => check.name)).join(', ')}`,
470
- revision: retry.revision
471
- } satisfies Output
601
+ if (environmental.length > 0)
602
+ yield* artifact('environment-failure', {
603
+ kind: 'gate_environment_failure',
604
+ title: `${names} failed on the gate's checkout at ${first.revision}`,
605
+ text: `These checks failed at ${first.revision} and passed in a fresh checkout of it, so the first checkout's environment failed them, not the code: ${names}.`,
606
+ data: {
607
+ revision: first.revision,
608
+ checks: environmental.map(check => ({
609
+ name: check.name,
610
+ failedEvidenceId: check.evidenceId,
611
+ ...(check.outputTail === undefined ? undefined : { outputTail: check.outputTail })
612
+ }))
472
613
  }
473
- }
614
+ })
474
615
 
475
- gated = gate.revision
476
- } else {
477
- const ready = yield* readyToMerge(changeRequestId)
616
+ // A retry passes only when its checks passed: one failing again may read as pre-existing against a moved target.
617
+ const failing = retry.checks.filter(check => check.status !== 'passed').map(check => check.name)
618
+
619
+ if (!retry.passed || retry.checks.length === 0 || failing.length > 0)
620
+ return yield* new GateFailed({
621
+ reason: `The checks fail at ${retry.revision}, and again in a fresh checkout: ${(failing.length > 0 ? failing : failed.map(check => check.name)).join(', ')}`,
622
+ revision: retry.revision
623
+ })
478
624
 
479
- if (!('passed' in ready)) return ready
480
- gated = ready.passed
481
- review = ready.review
625
+ return new Gated({ revision: first.revision })
626
+ })
627
+ })
628
+
629
+ /**
630
+ * Cuts the version a Release tags, with no agent. The Input's Version Scheme gives the previous tag and the next at
631
+ * `revision`, or at the head of `on` for a branch the Release lands on; `compare` what `revision`, and the head of `on`,
632
+ * hold since the previous tag; and the Input's `tag` or the scheme's next tag for the Input's `bump`, else the Bump
633
+ * Policy's, is the tag. Landing, it releases nothing only when neither side holds anything newer.
634
+ */
635
+ export const cut = step('cut', {
636
+ payload: {
637
+ input: Input,
638
+ revision: Schema.String.annotate({ description: 'The commit to tag, or to land and tag the merge of.' }),
639
+ on: Schema.optional(Schema.String).annotate({
640
+ description: 'The branch the revision lands on first, whose head the previous version is read on.'
641
+ })
642
+ },
643
+ success: Cut,
644
+ error: Schema.Union([NothingToRelease, VersionTaken]),
645
+ run: ({ input, revision, on }) =>
646
+ Effect.gen(function* () {
647
+ const scheme = yield* schemeOf(input)
648
+ const project = projectOf(input)
649
+ const at = on === undefined ? revision : `origin/${on}`
650
+
651
+ const request = {
652
+ revision: at,
653
+ ...(input.prerelease === undefined ? undefined : { prerelease: input.prerelease }),
654
+ ...(input.prefix === undefined ? undefined : { prefix: input.prefix })
482
655
  }
483
656
 
484
- const cut: Cut | undefined =
485
- input.tag === undefined && input.version !== undefined
486
- ? { version: input.version, candidate: input.candidate === true }
487
- : undefined
657
+ const read = yield* scheme.versions({
658
+ step: 'version',
659
+ ...request,
660
+ ...(project === undefined ? undefined : { project })
661
+ })
662
+
663
+ const previous = read?.previous
664
+ const later = read?.containedIn
488
665
 
489
- /** The tag to cut: a given one, a Project's version, or a candidate of it the releaser numbered, else `fallback`. */
490
- const tagOf = (proposed: string, fallback: string) => {
491
- if (cut === undefined) return input.tag ?? proposed
666
+ // The branch landed on is held by a later tag; what lands on it is too only when that tag holds the revision.
667
+ const laterHolds =
668
+ later === undefined
669
+ ? false
670
+ : on === undefined || (yield* compare('contained', { base: later.tag, head: revision })).ahead.commits === 0
492
671
 
493
- if (!cut.candidate) return cut.version
672
+ // A Milestone or Project releases its Tasks even at a revision a tag already holds.
673
+ if (later !== undefined && laterHolds && input.releaseScope === undefined)
674
+ return yield* new NothingToRelease({
675
+ reason: `${later.tag} already holds ${on === undefined ? revision : `${revision} and ${on}`}, so releasing it would tag older code after newer`,
676
+ tag: later.tag
677
+ })
678
+
679
+ const compared =
680
+ previous === undefined ? undefined : yield* compare('contents', { base: previous.tag, head: revision })
681
+
682
+ const onTarget =
683
+ previous === undefined || on === undefined
684
+ ? undefined
685
+ : yield* compare('contents:target', { base: previous.tag, head: at })
686
+
687
+ const contents = compared?.ahead
688
+ const targetContents = onTarget?.ahead
689
+
690
+ if (
691
+ contents?.commits === 0 &&
692
+ (targetContents === undefined || targetContents.commits === 0) &&
693
+ previous !== undefined &&
694
+ input.releaseScope === undefined
695
+ )
696
+ return yield* new NothingToRelease({
697
+ reason: `Nothing has merged since ${previous.tag}, which already holds ${on === undefined ? revision : `${revision} and ${on}`}`,
698
+ tag: previous.tag
699
+ })
494
700
 
495
- return candidateNumber(proposed, cut.version) === undefined ? fallback : proposed
701
+ const changeRequests = [
702
+ ...(contents?.changeRequests ?? []),
703
+ ...(targetContents?.changeRequests ?? []).filter(
704
+ change => !(contents?.changeRequests ?? []).some(held => held.id === change.id)
705
+ )
706
+ ]
707
+
708
+ const found = {
709
+ previousTag: previous?.tag ?? null,
710
+ changeRequests,
711
+ unlinked: Math.max(contents?.unlinked ?? 0, targetContents?.unlinked ?? 0),
712
+ ...(compared?.truncated === true || onTarget?.truncated === true ? { truncated: true } : undefined)
496
713
  }
497
714
 
498
- let drafted = yield* agentWork('draft-notes', {
499
- agent: 'releaser',
500
- prompt: draftPrompt(input.tag, cut, changeRequestId, input.releaseScope),
501
- output: Drafted
502
- })
715
+ if (input.tag !== undefined) return new Cut({ tag: input.tag, ...found })
503
716
 
504
- let tag = tagOf(drafted.tag, cut === undefined ? drafted.tag : `${cut.version}-rc.1`)
717
+ const bump =
718
+ input.bump ??
719
+ (yield* (yield* policyOf(input)).bump(
720
+ policyChanges([...releaseChanges(contents), ...releaseChanges(targetContents)], input.releaseScope)
721
+ ))
505
722
 
506
- const recordNotes = (step: string) =>
507
- artifact(step, {
508
- kind: 'release_notes',
509
- title: drafted.title,
510
- text: drafted.notes,
511
- data: {
512
- tag,
513
- changeRequests: drafted.changeRequests,
514
- ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
515
- }
516
- })
723
+ if (read === undefined) return yield* new VersionTaken({ reason: 'No version to release' })
724
+
725
+ const tag = read.next[bump]
726
+
727
+ if (tag === undefined) return yield* new VersionTaken({ reason: takenWords(read, bump, on ?? revision) })
728
+
729
+ return new Cut({ tag, bump, ...found })
730
+ })
731
+ })
732
+
733
+ const releaseDueInput = {
734
+ closesProject: 'closesProject',
735
+ reopened: 'reopened',
736
+ releaseScope: 'releaseScope',
737
+ repoBindingId: 'repoBindingId',
738
+ // A Milestone's or Project's target branch, where its work is: the Release gates and tags that branch's head.
739
+ branch: 'branch'
740
+ }
741
+
742
+ export const notes = step('notes', {
743
+ payload: {
744
+ cut: Cut,
745
+ revision: Schema.String.annotate({ description: 'The commit the cut read, which the notes read history up to.' }),
746
+ releaseScope: Schema.optional(ReleaseScope),
747
+ redraft: Schema.optional(Schema.Struct({ drafted: Notes, edit: Schema.String })).annotate({
748
+ description: 'The draft a person asked to change, and what they asked.'
749
+ })
750
+ },
751
+ success: Drafted,
752
+ run: ({ cut, revision, releaseScope, redraft }) =>
753
+ Effect.map(
754
+ releaser('draft', {
755
+ prompt:
756
+ redraft === undefined
757
+ ? notesPrompt(cut, revision, releaseScope)
758
+ : redraftPrompt(redraft.drafted, redraft.edit),
759
+ output: Notes
760
+ }),
761
+ written => new Drafted(written)
762
+ )
763
+ })
764
+
765
+ /**
766
+ * The one Question: whether to release `tag` with these notes, with no default. A full-auto Team answers Approve. Edit
767
+ * notes asks what to change, which `notes` redrafts; Reject asks why, and nothing is tagged.
768
+ */
769
+ export const approve = step('approve', {
770
+ payload: {
771
+ tag: Schema.String,
772
+ notes: Schema.String,
773
+ intro: Schema.optional(Schema.String).annotate({ description: 'Why it asks again, said before the Question.' }),
774
+ lands: Schema.optional(Schema.Struct({ source: Schema.String, target: Schema.String })).annotate({
775
+ description: 'The branch an approval lands, and where, before the merge is tagged.'
776
+ }),
777
+ review: Schema.optional(ApprovalRef),
778
+ head: Schema.String.annotate({ description: 'The revision it releases: the one the gate proved, or the merge.' })
779
+ },
780
+ success: Schema.Union([Approved, Edit]),
781
+ error: Rejected,
782
+ run: ({ tag, notes: text, intro, lands, review, head }) =>
783
+ Effect.gen(function* () {
784
+ const landing =
785
+ lands === undefined ? '' : ` Approving lands ${lands.source} into ${lands.target} first, and tags the merge.`
517
786
 
518
787
  // The question has no default: a release goes out only when someone says so.
519
788
  for (let round = 1; ; round++) {
520
- const answer = yield* ask(round === 1 ? 'approve' : `approve:${round}`, {
521
- 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}`,
789
+ const answer = yield* ask(round === 1 ? 'ask' : `ask:${round}`, {
790
+ prompt: `${intro ?? ''}Release ${tag} with these notes?${landing}\n\n${text}`,
522
791
  options: [
523
- { value: 'Approve', description: 'Tags, publishes and deploys it.' },
792
+ {
793
+ value: 'Approve',
794
+ description:
795
+ lands === undefined ? 'Tags, publishes and deploys it.' : 'Lands, tags, publishes and deploys it.'
796
+ },
524
797
  { value: 'Edit notes', description: 'Say what to change; the notes are redrafted.' },
525
798
  { value: 'Reject', description: 'Keeps the draft and releases nothing.' }
526
799
  ] satisfies { readonly value: (typeof approval)[number]; readonly description: string }[],
527
800
  recommended: 'Approve',
528
- recommendationReason:
529
- 'The release is proved: its checks pass, or its ChangeRequest is green, approved and mergeable.',
801
+ recommendationReason: 'The release is proved: its checks pass.',
530
802
  default: null,
531
803
  // A full-auto Team has handed releasing a proved change to Kitman.
532
804
  auto: 'Approve',
533
- evidence: { ...(review === undefined ? undefined : { review }), head: gated }
805
+ evidence: { ...(review === undefined ? undefined : { review }), head }
534
806
  })
535
807
 
536
- if (answer === 'Approve') break
808
+ if (answer === 'Approve') return new Approved()
537
809
 
538
810
  if (answer === 'Reject') {
539
811
  const why = yield* ask('reject-why', {
@@ -545,12 +817,10 @@ export default defineLoop({
545
817
  timeout: '1 day'
546
818
  })
547
819
 
548
- const kept = yield* recordNotes('notes')
549
-
550
- return { status: 'rejected', reason: why, tag, notesArtifactId: kept.artifactId } satisfies Output
820
+ return yield* new Rejected({ reason: why })
551
821
  }
552
822
 
553
- const edit = yield* ask(`edit:${round}`, {
823
+ const edit = yield* ask(round === 1 ? 'edit' : `edit:${round}`, {
554
824
  prompt: 'What should change in the notes?',
555
825
  freeText: true,
556
826
  informationOnly: true,
@@ -559,240 +829,799 @@ export default defineLoop({
559
829
  timeout: '1 day'
560
830
  })
561
831
 
562
- if (edit.trim() === '') continue
563
-
564
- drafted = yield* agentWork(`redraft:${round}`, {
565
- agent: 'releaser',
566
- prompt: redraftPrompt(drafted, edit),
567
- output: Drafted
568
- })
832
+ if (edit.trim() !== '') return new Edit({ edit })
569
833
  }
834
+ })
835
+ })
570
836
 
571
- let notes = yield* recordNotes('notes')
837
+ /** Land, by its schemas: its Shepherd calls this Loop, so its definition's type may not be ready yet. */
838
+ const landBySchemas = () => ({ id: 'land', input: LandInput, output: LandOutput })
572
839
 
573
- let revision = gated
840
+ /**
841
+ * Delivers `source` into `target` with the Land Loop as a Child Run, which opens the ChangeRequest between them or
842
+ * continues on the open one, and has Shepherd merge `gated`, or a catch-up of it, once it is level, green and approved,
843
+ * asking nothing more and starting no Release of its own. With nothing to land, it gives the head of `target`, once
844
+ * that holds `gated`.
845
+ */
846
+ export const landStep = step('land', {
847
+ payload: {
848
+ source: Schema.String,
849
+ target: Schema.String,
850
+ gated: Schema.String.annotate({ description: 'The revision of `source` the gate proved.' }),
851
+ repoBindingId: Schema.optional(Schema.String)
852
+ },
853
+ success: Schema.Union([Landed, NothingToLand]),
854
+ error: NotLanded,
855
+ run: ({ source, target, gated, repoBindingId }) =>
856
+ Effect.gen(function* () {
857
+ const delivered = yield* call('land', landBySchemas(), {
858
+ source,
859
+ target,
860
+ merge: true,
861
+ head: gated,
862
+ releaseTrigger: 'manual',
863
+ ...(repoBindingId === undefined ? undefined : { repoBindingId })
864
+ })
865
+
866
+ const changeRequest =
867
+ delivered.changeRequest === undefined ? undefined : { changeRequest: delivered.changeRequest }
574
868
 
575
- if (changeRequestId !== undefined) {
576
- // A head pushed while waiting for approval has passed nothing: it goes through the gate before it merges.
577
- for (let round = 1; ; round++) {
578
- const merged = yield* mergeChangeRequest(round === 1 ? 'merge' : `merge:${round}`, {
579
- changeRequestId,
580
- head: gated
869
+ if (delivered.status === 'nothing') {
870
+ const landedOn = yield* compare('landed-on', { base: gated, head: `origin/${target}` })
871
+
872
+ // Land also ends so when its ChangeRequest closed unmerged: then `target` lacks what was gated.
873
+ if (landedOn.behind.commits > 0)
874
+ return yield* new NotLanded({
875
+ reason: `${target} does not hold ${gated}: ${delivered.reason}`,
876
+ ...changeRequest
581
877
  })
582
878
 
583
- if (merged.status === 'conflict')
584
- return {
585
- status: 'not_mergeable',
586
- reason: `ChangeRequest ${changeRequestId} no longer merges cleanly`,
587
- tag,
588
- notesArtifactId: notes.artifactId
589
- } satisfies Output
879
+ return new NothingToLand({ revision: landedOn.head })
880
+ }
590
881
 
591
- if (merged.status === 'merged') {
592
- revision = merged.revision
593
- break
594
- }
882
+ if (delivered.status !== 'landed' || delivered.revision === undefined)
883
+ return yield* new NotLanded({ reason: delivered.reason, ...changeRequest })
595
884
 
596
- if (round >= 3)
597
- return {
598
- status: 'not_mergeable',
599
- reason: `ChangeRequest ${changeRequestId} kept moving while it was gated; it is at ${merged.head}`,
600
- tag,
601
- notesArtifactId: notes.artifactId
602
- } satisfies Output
885
+ // A gated head the merge's history lacks, or that no longer resolves, was squashed or rebased away.
886
+ const merged = yield* compare('merged', { base: gated, head: delivered.revision }).pipe(
887
+ Effect.catchTag('StepFailed', () => Effect.undefined)
888
+ )
603
889
 
604
- const ready = yield* readyToMerge(changeRequestId, round + 1)
605
-
606
- if (!('passed' in ready)) return { ...ready, tag, notesArtifactId: notes.artifactId }
607
- gated = ready.passed
608
- review = ready.review
609
-
610
- // The release was approved at an earlier head, so this one is approved on its own approval and gate.
611
- const again = yield* ask(`approve:merge:${round + 1}`, {
612
- prompt: `ChangeRequest ${changeRequestId} moved to ${gated} after ${tag} was approved; its pipeline passed and it is approved again. Release ${tag} from it?`,
613
- options: [
614
- { value: 'Approve', description: 'Merges this head, then tags, publishes and deploys it.' },
615
- { value: 'Reject', description: 'Keeps the draft and releases nothing.' }
616
- ],
617
- recommended: 'Approve',
618
- recommendationReason: 'This head is green, approved and mergeable, like the one you approved.',
619
- default: null,
620
- auto: 'Approve',
621
- evidence: { ...(review === undefined ? undefined : { review }), head: gated }
890
+ return new Landed({
891
+ revision: delivered.revision,
892
+ ...changeRequest,
893
+ ...(merged === undefined || merged.behind.commits > 0 ? { squashed: true } : undefined)
894
+ })
895
+ })
896
+ })
897
+
898
+ /** Tags `revision` and publishes the release once; its own release of the tag at the same revision counts as done. */
899
+ export const publish = step('publish', {
900
+ payload: {
901
+ tag: Schema.String,
902
+ revision: Schema.String,
903
+ title: Schema.String,
904
+ notes: Schema.String,
905
+ prerelease: Schema.optional(Schema.Boolean),
906
+ previousTag: Schema.optional(Schema.NullOr(Schema.String)),
907
+ branch: Schema.optional(Schema.String).annotate({
908
+ description: "The branch the revision is on, for the Release record; the Run's base branch when left out."
909
+ }),
910
+ squashed: Schema.optional(Schema.Boolean).annotate({
911
+ description: 'The forge squashed the branch landed to make the revision, for the Release record.'
912
+ })
913
+ },
914
+ success: Published,
915
+ error: TagTaken,
916
+ run: ({ tag, revision, title, notes: text, prerelease, previousTag, branch, squashed }) =>
917
+ release('tag', {
918
+ tag,
919
+ revision,
920
+ title,
921
+ notes: text,
922
+ ...(prerelease === true ? { prerelease: true } : undefined),
923
+ ...(previousTag === undefined ? undefined : { previousTag }),
924
+ ...(branch === undefined ? undefined : { branch }),
925
+ ...(squashed === true ? { squashed: true } : undefined)
926
+ }).pipe(
927
+ Effect.map(released => new Published(released)),
928
+ Effect.catchTag('StepFailed', (failed): Effect.Effect<never, StepFailed | TagTaken> =>
929
+ isTagElsewhere(failed) || isReleasedByOther(failed)
930
+ ? Effect.fail(new TagTaken({ tag, reason: failed.reason, releasedByOther: isReleasedByOther(failed) }))
931
+ : Effect.fail(failed)
932
+ )
933
+ )
934
+ })
935
+
936
+ /** Deploys the tag with the Deploy Loop as a Child Run, ending as that Deploy ended. */
937
+ export const deployStep = step('deploy', {
938
+ payload: {
939
+ tag: Schema.String,
940
+ target: Schema.String,
941
+ promote: Schema.optional(Schema.Boolean),
942
+ previous: Schema.optional(Schema.String),
943
+ deployEvent: Schema.optional(Schema.String),
944
+ deployTimeoutMinutes: Schema.optional(Schema.Int)
945
+ },
946
+ success: Deployed,
947
+ error: Schema.Union([NotDeployed, DeployFailed]),
948
+ run: ({ tag, target, promote, previous, deployEvent, deployTimeoutMinutes }) =>
949
+ Effect.gen(function* () {
950
+ const deployed: DeployOutput = yield* call('deploy', deployLoop, {
951
+ tag,
952
+ target,
953
+ ...(promote === undefined ? undefined : { promote }),
954
+ ...(previous === undefined ? undefined : { previous }),
955
+ ...(deployEvent === undefined ? undefined : { deployEvent }),
956
+ ...(deployTimeoutMinutes === undefined ? undefined : { deployTimeoutMinutes })
957
+ })
958
+
959
+ const { reason } = deployed
960
+ const left = deployed.leftUndeployed === true ? { leftUndeployed: true as const } : undefined
961
+
962
+ switch (deployed.status) {
963
+ case 'deployed':
964
+ return new Deployed({ status: 'deployed', reason })
965
+ case 'published':
966
+ return new Deployed({ status: 'published', reason })
967
+ case 'not_deployed':
968
+ return yield* new NotDeployed({ reason })
969
+ case 'rolled_back':
970
+ return yield* new DeployFailed({ status: 'rolled_back', reason, ...left })
971
+ case 'deploy_failed':
972
+ return yield* new DeployFailed({ status: 'deploy_failed', reason, ...left })
973
+ case 'rollback_failed':
974
+ return yield* new DeployFailed({ status: 'rollback_failed', reason, ...left })
975
+ case 'timed_out':
976
+ return yield* new DeployFailed({ status: 'timed_out', reason, ...left })
977
+ }
978
+ })
979
+ })
980
+
981
+ /** The branch `land` delivers into: `true` is the one the base branch delivers into, else the default branch. */
982
+ const landTarget = (input: Input, defaultBranch: () => string | undefined) =>
983
+ input.land === undefined || input.land === false
984
+ ? undefined
985
+ : input.land === true
986
+ ? (input.deliversInto ?? defaultBranch())
987
+ : input.land
988
+
989
+ /**
990
+ * Releases a revision as Steps a fork can replace with a Layer. It holds the repository's release claim from before
991
+ * `cut` until `publish` tagged, so no other Release of it cuts or tags meanwhile, whichever `cut` a fork provides.
992
+ * With `deployPromote`, `deploy` promotes the tag along the repository's Deploy Targets up to `deployTarget`.
993
+ * With `continues`, naming a tag an earlier Release published and failed after, it only deploys that tag.
994
+ *
995
+ * Under a Milestone or Project release trigger, it releases only when that Milestone's or Project's completion starts
996
+ * it, with the Tasks it ships: its `milestone` When Clause starts it for a Milestone that does not close its Project,
997
+ * and its `project` When Clause for the close. A Task in no Project releases on merge under either trigger, as nothing
998
+ * can close. Its Version Scheme picks the version, with semver from tags behind one that gives none. Under `manual` it
999
+ * releases whenever a person, a Schedule or another Loop starts it, and never on a ready ChangeRequest, which a Team can
1000
+ * turn on where it releases on merge: it then lands that ChangeRequest's branch into its target, continuing on the same
1001
+ * ChangeRequest.
1002
+ */
1003
+ export const releaseWith = (versioning: ReleaseVersioning = {}) =>
1004
+ defineLoop({
1005
+ id: 'release',
1006
+ version: '5.2.0',
1007
+ title: 'Release',
1008
+ description: 'Tags and publishes a release of what merged, and follows its deploy.',
1009
+ role: 'release',
1010
+ input: Input,
1011
+ output: Output,
1012
+ agents: { releaser: 'releaser' },
1013
+ checkout: 'read',
1014
+ // Kitman records release.due per repository when a Milestone or Project closes under that trigger; one for all of
1015
+ // them, `releaseSet`, starts release-set instead.
1016
+ when: [
1017
+ {
1018
+ name: 'milestone',
1019
+ event: 'release.due',
1020
+ filter: { closesProject: false, releaseSet: [false, null] },
1021
+ input: releaseDueInput,
1022
+ description: 'Releases a Milestone once its Tasks are done, when it does not close its Project.'
1023
+ },
1024
+ {
1025
+ name: 'project',
1026
+ event: 'release.due',
1027
+ filter: { closesProject: true, releaseSet: [false, null] },
1028
+ input: releaseDueInput,
1029
+ description: 'Releases a Project once its Tasks are done, with the last Milestone that closes it.'
1030
+ },
1031
+ {
1032
+ event: 'change_request.ready',
1033
+ filter: { busy: false },
1034
+ input: {
1035
+ branch: 'sourceBranch',
1036
+ land: 'targetBranch',
1037
+ repoBindingId: 'repoBindingId',
1038
+ taskId: 'taskId',
1039
+ readyHead: 'head'
1040
+ },
1041
+ optIn: true,
1042
+ description:
1043
+ 'Lands and releases a ChangeRequest delivering a Task once it is approved and green and no Run works it, only when it releases on merge: under a merge release trigger, or for a Task in no Project under a Milestone or Project trigger; otherwise each such Run ends not_due.'
1044
+ }
1045
+ ],
1046
+ capabilities: ['agent_work', 'ask', 'call', 'verify', 'claim', 'publish_release', 'read_change_request'],
1047
+ calls: (): readonly CalledLoop[] => [deployLoop, landLoop],
1048
+ run: input => {
1049
+ // What the Release holds, once it has cut its version.
1050
+ let contents: readonly ComparedChange[] | undefined
1051
+
1052
+ /** The cut, or why it cut no version. */
1053
+ const cutting = (payload: typeof cut.payloadSchema.Type) =>
1054
+ cut(payload).pipe(
1055
+ Effect.catchTags({
1056
+ VersionTaken: uncut => Effect.succeed(uncut),
1057
+ NothingToRelease: uncut => Effect.succeed(uncut)
622
1058
  })
1059
+ )
1060
+
1061
+ /** How the Release ends when `cut` cuts no version; `extra` is what it got as far as. */
1062
+ const uncut = (ended: VersionTaken | NothingToRelease, extra: Partial<Output>): Output => {
1063
+ switch (ended._tag) {
1064
+ case 'VersionTaken':
1065
+ return { ...extra, status: 'version_taken', reason: ended.reason }
1066
+ case 'NothingToRelease':
1067
+ contents = []
623
1068
 
624
- if (again !== 'Approve')
625
1069
  return {
626
- status: 'rejected',
627
- reason: `Not released from ${gated}, the head ChangeRequest ${changeRequestId} moved to`,
628
- tag,
629
- notesArtifactId: notes.artifactId
630
- } satisfies Output
1070
+ ...extra,
1071
+ status: 'nothing_to_release',
1072
+ reason: ended.reason,
1073
+ ...(ended.tag === undefined ? undefined : { tag: ended.tag })
1074
+ }
631
1075
  }
632
1076
  }
633
1077
 
634
- const deployEvent = input.deployEvent ?? 'deploy'
635
-
636
- // Held until the Run completes, so the next Release deploys after this one is settled. One a failed Release kept
637
- // is taken over, since a Release always deploys what is newest.
638
- yield* claim('deploy-target', { resource: `deploy:${input.deployTarget ?? deployEvent}`, takeOverOwnLoop: true })
1078
+ const deploys = input.deploy !== false
639
1079
 
640
- const { releasedIn, ...picked } = yield* agentWork('pick-version', {
641
- agent: 'releaser',
642
- prompt: pickPrompt({ ...drafted, tag }, revision, input.tag, cut),
643
- output: Picked
1080
+ const claimDeployTarget = claim('deploy-target', {
1081
+ resource: `deploy:${input.deployTarget ?? defaultTarget}`,
1082
+ takeOverOwnLoop: true,
1083
+ keep: 'run'
644
1084
  })
645
1085
 
646
- const alreadyReleased = (released: string, reason: string) =>
647
- ({
648
- status: 'nothing_to_release',
649
- reason,
650
- tag: released,
651
- notesArtifactId: notes.artifactId,
652
- revision
653
- }) satisfies Output
654
-
655
- if (cut === undefined && releasedIn !== undefined)
656
- return alreadyReleased(releasedIn, `${revision} is already released in ${releasedIn}`)
657
-
658
- const pickedTag = tagOf(picked.tag, tag)
659
-
660
- const repicked =
661
- cut === undefined
662
- ? picked
663
- : {
664
- ...picked,
665
- title: renameTag(picked.title, tag, pickedTag),
666
- notes: renameTag(picked.notes, tag, pickedTag)
667
- }
1086
+ /** Deploys a published tag, unless the Input says not to, and ends as that Deploy ended. */
1087
+ const deployPublished = (
1088
+ published: {
1089
+ readonly tag: string
1090
+ readonly revision: string
1091
+ readonly url?: string | undefined
1092
+ readonly previousTag?: string | undefined
1093
+ readonly notesArtifactId?: string | undefined
1094
+ readonly squashed?: boolean | undefined
1095
+ },
1096
+ landed: Partial<Output> = {}
1097
+ ) =>
1098
+ Effect.gen(function* () {
1099
+ const { tag, previousTag, squashed } = published
1100
+ const at = published.url === undefined ? '' : `. ${published.url}`
1101
+
1102
+ const settled = {
1103
+ tag,
1104
+ revision: published.revision,
1105
+ ...(published.notesArtifactId === undefined ? undefined : { notesArtifactId: published.notesArtifactId }),
1106
+ ...(published.url === undefined ? undefined : { url: published.url }),
1107
+ ...landed
1108
+ }
668
1109
 
669
- const changed = pickedTag !== tag || repicked.notes !== drafted.notes || repicked.title !== drafted.title
1110
+ const report = (status: DeployOutput['status'], detail: string) =>
1111
+ artifact('report', {
1112
+ kind: 'release_report',
1113
+ title: `${tag} ${outcomeWords[status]}`,
1114
+ text: `${tag} at ${published.revision}: ${detail}${at}`,
1115
+ data: {
1116
+ tag,
1117
+ status,
1118
+ revision: published.revision,
1119
+ ...(published.url === undefined ? undefined : { url: published.url }),
1120
+ detail,
1121
+ ...(squashed === true ? { squashed } : undefined)
1122
+ }
1123
+ })
670
1124
 
671
- drafted = repicked
672
- tag = pickedTag
1125
+ if (!deploys) {
1126
+ const reason = `${tag} published; deploy: false, so it was not deployed`
673
1127
 
674
- if (changed) notes = yield* recordNotes('notes:picked')
1128
+ yield* report('published', reason)
1129
+
1130
+ return { status: 'published', reason, ...settled } satisfies Output
1131
+ }
675
1132
 
676
- const publish = (step: string) =>
677
- release(step, { tag, revision, title: drafted.title, notes: drafted.notes }).pipe(
678
- Effect.catchTag('StepFailed', failed =>
679
- isTagElsewhere(failed) || isReleasedByOther(failed) ? Effect.succeed(failed) : Effect.fail(failed)
1133
+ const deployed = yield* deployStep({
1134
+ tag,
1135
+ target: input.deployTarget ?? defaultTarget,
1136
+ ...(input.deployPromote === undefined ? undefined : { promote: input.deployPromote }),
1137
+ ...(previousTag === undefined ? undefined : { previous: previousTag }),
1138
+ ...(input.deployEvent === undefined ? undefined : { deployEvent: input.deployEvent }),
1139
+ ...(input.deployTimeoutMinutes === undefined
1140
+ ? undefined
1141
+ : { deployTimeoutMinutes: input.deployTimeoutMinutes })
1142
+ }).pipe(
1143
+ Effect.catchTags({
1144
+ NotDeployed: held => Effect.succeed(held),
1145
+ DeployFailed: failed => Effect.succeed(failed)
1146
+ })
680
1147
  )
681
- )
682
1148
 
683
- const approved = { tag, title: drafted.title, notes: drafted.notes }
1149
+ if (deployed._tag === 'NotDeployed') {
1150
+ yield* report('not_deployed', deployed.reason)
1151
+
1152
+ return { status: 'not_deployed', reason: deployed.reason, ...settled } satisfies Output
1153
+ }
1154
+
1155
+ if (deployed._tag === 'DeployFailed') {
1156
+ yield* report(deployed.status, deployed.reason)
1157
+
1158
+ // Each status written out, so the build's outline of Release names every end.
1159
+ const status = (
1160
+ {
1161
+ rolled_back: 'rolled_back',
1162
+ deploy_failed: 'deploy_failed',
1163
+ rollback_failed: 'rollback_failed',
1164
+ timed_out: 'timed_out'
1165
+ } as const
1166
+ )[deployed.status]
1167
+
1168
+ return {
1169
+ status,
1170
+ reason: deployed.reason,
1171
+ ...(deployed.leftUndeployed === true ? { leftUndeployed: true } : undefined),
1172
+ ...settled
1173
+ } satisfies Output
1174
+ }
1175
+
1176
+ yield* report(deployed.status, deployed.reason)
1177
+
1178
+ return {
1179
+ status: deployed.status === 'deployed' ? 'deployed' : 'published',
1180
+ reason: deployed.reason,
1181
+ ...settled
1182
+ } satisfies Output
1183
+ })
1184
+
1185
+ return Effect.gen(function* () {
1186
+ const context = yield* runContext
1187
+ const { releaseTrigger: when } = context
1188
+ const releases = releasesOn(when)
1189
+
1190
+ if (releases === 'manual' && input.readyHead !== undefined)
1191
+ return {
1192
+ status: 'not_due',
1193
+ reason: `Release runs only when a person, a Schedule or a Loop starts it, as ${layerWords[when.layer]} says; a ready ChangeRequest does not`
1194
+ } satisfies Output
1195
+
1196
+ // A Milestone's or Project's completion starts the Release it waits for; a merge does not, unless this Run says so.
1197
+ if ((releases === 'milestone' || releases === 'project') && input.releaseScope === undefined)
1198
+ return {
1199
+ status: 'not_due',
1200
+ reason: `Release runs when ${triggerWords[releases]}, as ${layerWords[when.layer]} says; this Run did not override that`
1201
+ } satisfies Output
684
1202
 
685
- let released = yield* publish('tag')
1203
+ const epic = epicOf(input)
686
1204
 
687
- if (released instanceof StepFailed && cut === undefined && isReleasedByOther(released))
688
- return alreadyReleased(tag, `${tag} is already released at ${revision} by another Run`)
1205
+ // Under epic delivery a sub-task's work reaches the default branch only with its epic's ChangeRequest.
1206
+ if (epic !== undefined && !epic.done)
1207
+ return {
1208
+ status: 'not_due',
1209
+ reason: `Its Task lands on ${epic.branch}, as ${deliveryLayerWords[input.deliversTo?.layer ?? 'workspace']} says; Release runs once epic ${epic.key} merges into ${epic.defaultBranch}`
1210
+ } satisfies Output
689
1211
 
690
- // A tag is never moved, so a release candidate already tagged gives way to the next; a version has no next.
691
- for (let round = 2; released instanceof StepFailed; round++) {
692
- if (cut?.candidate !== true || round > 20) return yield* released
1212
+ // Its tag is out already: tagging it again would only find it taken, so the Release goes on to deploy it.
1213
+ if (input.continues !== undefined) {
1214
+ if (deploys) yield* claimDeployTarget
693
1215
 
694
- tag = `${cut.version}-rc.${(candidateNumber(tag, cut.version) ?? 0) + 1}`
695
- // Only the tag changes from what was approved, so nothing is published unreviewed.
696
- drafted = {
697
- ...drafted,
698
- title: renameTag(approved.title, approved.tag, tag),
699
- notes: renameTag(approved.notes, approved.tag, tag)
1216
+ return yield* deployPublished(input.continues)
700
1217
  }
701
- notes = yield* recordNotes(`notes:${round}`)
702
- released = yield* publish(`tag:${round}`)
703
- }
704
1218
 
705
- const deployed = (step: string, deployTag: string) =>
706
- waitFor(step, {
707
- event: deployEvent,
708
- filter: { tag: deployTag },
709
- timeout: `${input.deployTimeoutMinutes ?? 60} minutes`
710
- }).pipe(
711
- Effect.map(deploy =>
712
- deploy.payload.status === 'failed' ? ('deploy_failed' as const) : ('deployed' as const)
713
- ),
714
- Effect.catchTag('WaitTimedOut', () => Effect.succeed('timed_out' as const))
1219
+ const target = landTarget(input, () => context.repository?.defaultBranch)
1220
+
1221
+ const source =
1222
+ target === undefined
1223
+ ? undefined
1224
+ : (context.baseBranch?.branch ?? input.branch ?? context.repository?.defaultBranch)
1225
+
1226
+ if (target !== undefined && source === undefined)
1227
+ return yield* new StepFailed({ step: 'land', reason: 'The Run has no base branch to land' })
1228
+
1229
+ const lands = source === undefined || target === undefined || source === target ? undefined : { source, target }
1230
+
1231
+ const resumed = input.drafted
1232
+
1233
+ // The commit the gate proved: never the branch head read again later. A draft's revision is proved again, as
1234
+ // anything that starts Release can name one.
1235
+ const toProve = resumed?.revision ?? input.revision
1236
+
1237
+ const proved = yield* gate(toProve === undefined ? {} : { revision: toProve }).pipe(
1238
+ Effect.catchTag('GateFailed', failed => Effect.succeed(failed))
715
1239
  )
716
1240
 
717
- const settled = { tag, notesArtifactId: notes.artifactId, revision: released.revision, url: released.url }
1241
+ if (proved._tag === 'GateFailed')
1242
+ return { status: 'gate_failed', reason: proved.reason, revision: proved.revision } satisfies Output
1243
+
1244
+ const gated = proved.revision
1245
+
1246
+ yield* claim('repository', { resource: releaseResource(input, context), takeOverOwnLoop: true, keep: 'run' })
1247
+
1248
+ const first =
1249
+ resumed === undefined
1250
+ ? yield* cutting({
1251
+ input,
1252
+ revision: gated,
1253
+ ...(lands === undefined ? undefined : { on: lands.target })
1254
+ })
1255
+ : new Cut({
1256
+ tag: resumed.tag,
1257
+ previousTag: resumed.previousTag,
1258
+ ...(resumed.bump === undefined ? undefined : { bump: resumed.bump }),
1259
+ changeRequests: resumed.changeRequests,
1260
+ unlinked: resumed.unlinked,
1261
+ ...(resumed.truncated === undefined ? undefined : { truncated: resumed.truncated })
1262
+ })
1263
+
1264
+ if (first._tag !== 'Cut') return uncut(first, { revision: gated })
1265
+
1266
+ let picked = first
1267
+ contents = picked.changeRequests
1268
+ let tag = picked.tag
1269
+ let previousTag = picked.previousTag ?? undefined
1270
+ let recordedPrevious: string | null | undefined = picked.previousTag
1271
+ let squashed = false
1272
+
1273
+ const recordNotes = (name: string, drafted: Notes) =>
1274
+ artifact(name, {
1275
+ kind: 'release_notes',
1276
+ title: drafted.title,
1277
+ text: drafted.notes,
1278
+ data: {
1279
+ tag,
1280
+ ...(previousTag === undefined ? undefined : { previousTag }),
1281
+ changeRequests: picked.changeRequests,
1282
+ ...(squashed ? { squashed } : undefined),
1283
+ ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
1284
+ }
1285
+ })
718
1286
 
719
- // The repository deploys itself from the Runner when it has a deploy script, which rolls back on its own.
720
- const ran = yield* runDeploy('run-deploy', { tag, previousTag: drafted.previousTag })
1287
+ // What an approval still lands: nothing once `land` ran.
1288
+ let landing = lands
721
1289
 
722
- if (ran.status !== 'none') {
723
- const status = ran.status === 'failed' ? 'deploy_failed' : ran.status
1290
+ const scope = input.releaseScope === undefined ? undefined : { releaseScope: input.releaseScope }
724
1291
 
725
- const outcome = {
726
- deployed: 'deployed',
727
- published: 'published, not deployed',
728
- rolled_back: 'rolled back',
729
- deploy_failed: 'failed to deploy',
730
- rollback_failed: 'failed to deploy, and the rollback failed too'
731
- }[status]
1292
+ /** Drafts the notes, unless `given`, and asks until they are approved, redrafting each edit; or the rejection. */
1293
+ const drafting = (from: Cut, revision: string, intro?: string, given?: Notes) =>
1294
+ Effect.gen(function* () {
1295
+ let draft: Notes = given ?? (yield* notes({ cut: from, revision, ...scope }))
732
1296
 
733
- yield* artifact('report', {
734
- kind: 'release_report',
735
- title: `${tag} ${outcome}`,
736
- text: `${tag} at ${released.revision}: ${ran.detail}. ${released.url}`,
737
- data: { tag, status, revision: released.revision, url: released.url, detail: ran.detail }
738
- })
1297
+ for (;;) {
1298
+ const answer = yield* approve({
1299
+ tag: from.tag,
1300
+ notes: draft.notes,
1301
+ ...(intro === undefined ? undefined : { intro }),
1302
+ ...(landing === undefined ? undefined : { lands: landing }),
1303
+ ...(input.review === undefined || revision !== gated ? undefined : { review: input.review }),
1304
+ head: revision
1305
+ }).pipe(Effect.catchTag('Rejected', rejected => Effect.succeed(rejected)))
739
1306
 
740
- return { status, reason: ran.detail, ...settled } satisfies Output
741
- }
1307
+ if (answer._tag === 'Approved') return { outcome: 'approved', draft } as const
742
1308
 
743
- let status = yield* deployed('deploy', tag)
1309
+ if (answer._tag === 'Rejected') return { outcome: 'rejected', reason: answer.reason, draft } as const
744
1310
 
745
- for (let round = 1; status !== 'deployed'; round++) {
746
- const options = recovery(drafted.previousTag)
1311
+ draft = yield* notes({
1312
+ cut: from,
1313
+ revision,
1314
+ ...scope,
1315
+ redraft: { drafted: { title: draft.title, notes: draft.notes }, edit: answer.edit }
1316
+ })
1317
+ }
1318
+ })
747
1319
 
748
- const answer = yield* ask(`recover:${round}`, {
749
- prompt: `${tag} ${status === 'timed_out' ? 'did not report a deploy in time' : 'failed to deploy'}. What now?`,
750
- options,
751
- recommended: 'Retry the deploy',
752
- recommendationReason:
753
- 'A failed or late deploy is often passing, and a retry runs only the failed jobs of the same tag.',
754
- // Waits for a person, so Leave it is always their choice.
755
- default: null
756
- })
1320
+ const rejectedAs = (name: string, rejected: { readonly reason: string; readonly draft: Notes }) =>
1321
+ Effect.map(
1322
+ recordNotes(name, rejected.draft),
1323
+ kept =>
1324
+ ({
1325
+ status: 'rejected',
1326
+ reason: rejected.reason,
1327
+ tag,
1328
+ notesArtifactId: kept.artifactId
1329
+ }) satisfies Output
1330
+ )
1331
+
1332
+ if (resumed === undefined && input.stopAfter === 'notes') {
1333
+ const draft = yield* notes({ cut: picked, revision: gated, ...scope })
757
1334
 
758
- if (answer === 'Leave it')
759
1335
  return {
760
- status,
761
- reason: `${tag} at ${released.revision} was left undeployed`,
762
- leftUndeployed: true,
763
- ...settled
1336
+ status: 'drafted',
1337
+ reason: `${tag} is gated at ${gated} and its notes drafted; nothing is tagged until a Release goes on from approve with them`,
1338
+ tag,
1339
+ revision: gated,
1340
+ drafted: {
1341
+ tag,
1342
+ revision: gated,
1343
+ previousTag: picked.previousTag,
1344
+ ...(picked.bump === undefined ? undefined : { bump: picked.bump }),
1345
+ changeRequests: picked.changeRequests,
1346
+ unlinked: picked.unlinked,
1347
+ ...(picked.truncated === undefined ? undefined : { truncated: picked.truncated }),
1348
+ title: draft.title,
1349
+ notes: draft.notes,
1350
+ ...(lands === undefined ? undefined : { lands })
1351
+ }
764
1352
  } satisfies Output
1353
+ }
1354
+
1355
+ const approvedByCaller =
1356
+ resumed !== undefined && input.approvedByCaller === true && context.startedBy.kind === 'run'
1357
+
1358
+ const firstDraft = approvedByCaller
1359
+ ? ({ outcome: 'approved', draft: { title: resumed.title, notes: resumed.notes } } as const)
1360
+ : yield* drafting(
1361
+ picked,
1362
+ gated,
1363
+ undefined,
1364
+ resumed === undefined ? undefined : { title: resumed.title, notes: resumed.notes }
1365
+ )
1366
+
1367
+ if (firstDraft.outcome === 'rejected') return yield* rejectedAs('release-notes', firstDraft)
1368
+
1369
+ let drafted = firstDraft.draft
1370
+ let notesRecord = yield* recordNotes('release-notes', drafted)
1371
+ let revision = gated
1372
+ let landed: Partial<Output> = {}
1373
+
1374
+ if (lands !== undefined) {
1375
+ const delivered = yield* landStep({
1376
+ ...lands,
1377
+ gated,
1378
+ ...(input.repoBindingId === undefined ? undefined : { repoBindingId: input.repoBindingId })
1379
+ }).pipe(Effect.catchTag('NotLanded', notLanded => Effect.succeed(notLanded)))
1380
+
1381
+ landing = undefined
1382
+
1383
+ if (delivered._tag === 'NotLanded')
1384
+ return {
1385
+ status: 'not_mergeable',
1386
+ reason: `${lands.source} did not land on ${lands.target}, so nothing was tagged: ${delivered.reason}`,
1387
+ tag,
1388
+ notesArtifactId: notesRecord.artifactId,
1389
+ revision: gated,
1390
+ ...(delivered.changeRequest === undefined ? undefined : { landed: delivered.changeRequest })
1391
+ } satisfies Output
765
1392
 
766
- if (answer === 'Retry the deploy') {
767
- yield* rerunPipeline(`deploy:rerun-${round}`, { ref: tag })
768
- status = yield* deployed(`deploy:retry-${round}`, tag)
769
- continue
1393
+ revision = delivered.revision
1394
+ squashed = delivered._tag === 'Landed' && delivered.squashed === true
1395
+ const landedBy = delivered._tag === 'Landed' ? delivered.changeRequest?.id : undefined
1396
+
1397
+ landed = {
1398
+ ...(delivered._tag === 'Landed' && delivered.changeRequest !== undefined
1399
+ ? { landed: delivered.changeRequest }
1400
+ : undefined),
1401
+ ...(squashed ? { squashed: true } : undefined)
1402
+ }
1403
+
1404
+ if (revision !== gated) {
1405
+ // The merge can reach tags the gated head does not, so the version is cut again at what is tagged.
1406
+ const atMerge = yield* cutting({ input, revision })
1407
+
1408
+ if (atMerge._tag !== 'Cut')
1409
+ return uncut(atMerge, { notesArtifactId: notesRecord.artifactId, revision, ...landed })
1410
+
1411
+ // The merge lists the ChangeRequest that landed the branch, which the gated head could not.
1412
+ const idsOf = (from: Cut) => from.changeRequests.map(change => change.id).filter(id => id !== landedBy)
1413
+
1414
+ // Of what the merge adds to the gated head, the landing ChangeRequest's own is a merge commit, a squash,
1415
+ // both, or nothing for a fast-forward. Anything else is other work, even where no ChangeRequest shows it.
1416
+ const addsWork = (added: Comparison) =>
1417
+ added.truncated === true ||
1418
+ added.ahead.commits > 2 ||
1419
+ added.ahead.unlinked > 0 ||
1420
+ added.ahead.changeRequests.some(change => change.id !== landedBy)
1421
+
1422
+ // A merge commit over a squash is kept only when the target it merged into held nothing the draft lacked.
1423
+ const targetMoved = Effect.map(
1424
+ compare('merge:target', { base: gated, head: `${revision}^1` }),
1425
+ moved => moved.truncated === true || moved.ahead.commits > 0
1426
+ )
1427
+
1428
+ const mergeAddsWork = compare('merge:added', { base: gated, head: revision }).pipe(
1429
+ Effect.flatMap(added =>
1430
+ addsWork(added) ? Effect.succeed(true) : added.ahead.commits === 2 ? targetMoved : Effect.succeed(false)
1431
+ ),
1432
+ Effect.catchTag('StepFailed', () => Effect.succeed(true))
1433
+ )
1434
+
1435
+ const sameContents =
1436
+ atMerge.previousTag === picked.previousTag &&
1437
+ JSON.stringify(idsOf(atMerge)) === JSON.stringify(idsOf(picked)) &&
1438
+ !(yield* mergeAddsWork)
1439
+
1440
+ const recordedAgain =
1441
+ atMerge.tag !== tag || JSON.stringify(atMerge.changeRequests) !== JSON.stringify(picked.changeRequests)
1442
+
1443
+ const approvedTag = tag
1444
+
1445
+ picked = atMerge
1446
+ contents = atMerge.changeRequests
1447
+ tag = atMerge.tag
1448
+ previousTag = atMerge.previousTag ?? undefined
1449
+ recordedPrevious = atMerge.previousTag
1450
+
1451
+ if (sameContents) {
1452
+ drafted = {
1453
+ title: renameTag(drafted.title, approvedTag, tag),
1454
+ notes: renameTag(drafted.notes, approvedTag, tag)
1455
+ }
1456
+
1457
+ if (recordedAgain || squashed) notesRecord = yield* recordNotes('release-notes:merged', drafted)
1458
+ } else {
1459
+ const redrafted = yield* drafting(
1460
+ picked,
1461
+ revision,
1462
+ `${lands.source} landed on ${lands.target} at ${revision}, which holds other changes${atMerge.previousTag === null ? '' : ` since ${atMerge.previousTag}`} than the notes approved for ${approvedTag}, so they were drafted again. `
1463
+ )
1464
+
1465
+ if (redrafted.outcome === 'rejected')
1466
+ return { ...(yield* rejectedAs('release-notes:merged', redrafted)), revision, ...landed }
1467
+ drafted = redrafted.draft
1468
+ notesRecord = yield* recordNotes('release-notes:merged', drafted)
1469
+ }
1470
+ } else if (squashed) notesRecord = yield* recordNotes('release-notes:merged', drafted)
770
1471
  }
771
1472
 
772
- const previous = drafted.previousTag ?? tag
1473
+ // A claim a dead Release kept is taken over, since a Release always deploys what is newest.
1474
+ if (deploys) yield* claimDeployTarget
1475
+
1476
+ const alreadyReleased = (released: string, reason: string) =>
1477
+ ({
1478
+ status: 'nothing_to_release',
1479
+ reason,
1480
+ tag: released,
1481
+ notesArtifactId: notesRecord.artifactId,
1482
+ revision,
1483
+ ...landed
1484
+ }) satisfies Output
1485
+
1486
+ const publishing = () =>
1487
+ publish({
1488
+ tag,
1489
+ revision,
1490
+ title: drafted.title,
1491
+ notes: drafted.notes,
1492
+ ...(input.prerelease === undefined ? undefined : { prerelease: true }),
1493
+ ...(recordedPrevious === undefined ? undefined : { previousTag: recordedPrevious }),
1494
+ ...(lands === undefined ? undefined : { branch: lands.target }),
1495
+ ...(squashed ? { squashed: true } : undefined)
1496
+ }).pipe(Effect.catchTag('TagTaken', taken => Effect.succeed(taken)))
1497
+
1498
+ // The forge holds the tag at another revision, and the Version Scheme gives no other to take.
1499
+ const versionTaken = (taken: TagTaken) =>
1500
+ ({
1501
+ status: 'version_taken',
1502
+ reason: `${tag} is tagged where ${revision} does not reach it, and no other version is free: ${taken.reason}`,
1503
+ tag,
1504
+ notesArtifactId: notesRecord.artifactId,
1505
+ revision,
1506
+ ...landed
1507
+ }) satisfies Output
773
1508
 
774
- yield* rerunPipeline(`deploy:redeploy-${round}`, { ref: previous, all: true })
775
- const back = yield* deployed(`deploy:rollback-${round}`, previous)
1509
+ let approved = { tag, previousTag, title: drafted.title, notes: drafted.notes }
1510
+ const scoped = input.tag === undefined && input.releaseScope !== undefined
776
1511
 
777
- if (back === 'deployed')
778
- return { status: 'rolled_back', reason: `Rolled back to ${previous}`, ...settled } satisfies Output
779
- status = back
780
- }
1512
+ let released = yield* publishing()
781
1513
 
782
- yield* artifact('report', {
783
- kind: 'release_report',
784
- title: `${tag} deployed`,
785
- text: `${tag} at ${released.revision} deployed. ${released.url}`,
786
- data: { tag, status, revision: released.revision, url: released.url }
787
- })
1514
+ // A tag is never moved, so one tagged first, outside the Releases the repository's claim orders, gives way to
1515
+ // the next tag the Version Scheme gives; one it gives again has no next.
1516
+ for (let round = 2; released._tag === 'TagTaken'; round++) {
1517
+ const taken = released
788
1518
 
789
- return { status: 'deployed', reason: `${tag} deployed`, ...settled } satisfies Output
790
- }).pipe(
791
- Effect.map((output): Output => ({
792
- ...output,
793
- ...(input.releaseWhen === undefined ? undefined : { releaseWhen: input.releaseWhen }),
794
- ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo }),
795
- ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
796
- }))
797
- )
798
- })
1519
+ if (!scoped && taken.releasedByOther)
1520
+ return alreadyReleased(tag, `${tag} is already released at ${revision} by another Run`)
1521
+
1522
+ const bump = picked.bump
1523
+
1524
+ if (bump === undefined || round > 20) return versionTaken(taken)
1525
+
1526
+ const project = projectOf(input)
1527
+
1528
+ const again = yield* (yield* schemeOf(input)).versions({
1529
+ step: `version:tag:${round}`,
1530
+ revision,
1531
+ ...(input.prerelease === undefined ? undefined : { prerelease: input.prerelease }),
1532
+ ...(input.prefix === undefined ? undefined : { prefix: input.prefix }),
1533
+ ...(project === undefined ? undefined : { project })
1534
+ })
1535
+
1536
+ // The notes were approved for the range since the previous version, and nothing newer may already hold it.
1537
+ const rangeMoved =
1538
+ again !== undefined &&
1539
+ (again.previous?.tag !== approved.previousTag || (!scoped && again.containedIn !== undefined))
1540
+
1541
+ if (rangeMoved) {
1542
+ // The approved notes describe the range the recut replaced, so the Output does not cite them.
1543
+ contents = undefined
1544
+ const recut = yield* cutting({ input, revision })
1545
+
1546
+ if (recut._tag !== 'Cut') return uncut(recut, { tag, revision, ...landed })
1547
+
1548
+ if (recut.tag === tag) return versionTaken(taken)
1549
+
1550
+ picked = recut
1551
+ contents = picked.changeRequests
1552
+ tag = picked.tag
1553
+ previousTag = picked.previousTag ?? undefined
1554
+ recordedPrevious = picked.previousTag
1555
+
1556
+ const redrafted = yield* drafting(
1557
+ picked,
1558
+ revision,
1559
+ `${approved.tag} was tagged elsewhere, and ${picked.previousTag ?? 'a version'} was tagged at an ancestor of ${revision} after the notes were approved, so they were drafted again. `
1560
+ )
1561
+
1562
+ if (redrafted.outcome === 'rejected')
1563
+ return { ...(yield* rejectedAs(`release-notes:tag:${round}`, redrafted)), revision, ...landed }
1564
+ drafted = redrafted.draft
1565
+ notesRecord = yield* recordNotes(`release-notes:${round}`, drafted)
1566
+ approved = { tag, previousTag, title: drafted.title, notes: drafted.notes }
1567
+ released = yield* publishing()
1568
+ continue
1569
+ }
1570
+
1571
+ const next = again?.next[bump]
1572
+
1573
+ if (next === undefined)
1574
+ return {
1575
+ status: 'version_taken',
1576
+ reason: again === undefined ? 'No version to release' : takenWords(again, bump, revision),
1577
+ tag,
1578
+ notesArtifactId: notesRecord.artifactId,
1579
+ revision,
1580
+ ...landed
1581
+ } satisfies Output
1582
+
1583
+ if (next === tag) return versionTaken(taken)
1584
+
1585
+ tag = next
1586
+ previousTag = again?.previous?.tag
1587
+ recordedPrevious = again === undefined ? undefined : (previousTag ?? null)
1588
+ // Only the tag changes from what was approved, so nothing is published unreviewed.
1589
+ drafted = {
1590
+ title: renameTag(approved.title, approved.tag, tag),
1591
+ notes: renameTag(approved.notes, approved.tag, tag)
1592
+ }
1593
+ notesRecord = yield* recordNotes(`release-notes:${round}`, drafted)
1594
+ released = yield* publishing()
1595
+ }
1596
+
1597
+ const published = released
1598
+
1599
+ yield* letGo('repository:let-go', { status: 'granted', resource: releaseResource(input, context) })
1600
+
1601
+ return yield* deployPublished(
1602
+ {
1603
+ tag,
1604
+ revision: published.revision,
1605
+ url: published.url,
1606
+ notesArtifactId: notesRecord.artifactId,
1607
+ squashed,
1608
+ ...(previousTag === undefined ? undefined : { previousTag })
1609
+ },
1610
+ landed
1611
+ )
1612
+ }).pipe(
1613
+ Effect.flatMap(output =>
1614
+ Effect.map(runContext, ({ releaseTrigger }): Output => ({
1615
+ ...output,
1616
+ releaseWhen: releaseTrigger,
1617
+ ...(contents === undefined ? undefined : { changeRequests: contents }),
1618
+ ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo }),
1619
+ ...(input.releaseScope === undefined ? undefined : { shipped: shippedScope(input.releaseScope) })
1620
+ }))
1621
+ ),
1622
+ Effect.provide(Layer.mergeAll(versioning.versionScheme ?? Layer.empty, versioning.bumpPolicy ?? Layer.empty))
1623
+ )
1624
+ }
1625
+ })
1626
+
1627
+ export default releaseWith()