@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/land.ts ADDED
@@ -0,0 +1,293 @@
1
+ import {
2
+ call,
3
+ type CalledLoop,
4
+ changeRequest,
5
+ ChangeRequestResult,
6
+ compare,
7
+ type Comparison,
8
+ defineLoop,
9
+ mergedChangeRequest,
10
+ pipelineStatus,
11
+ ReleaseTrigger,
12
+ type RunStarter,
13
+ runContext,
14
+ waitFor
15
+ } from '@kitman-sh/sdk/loop'
16
+ import * as Effect from 'effect/Effect'
17
+ import * as Schema from 'effect/Schema'
18
+ import shepherd from './shepherd'
19
+ import { ShepherdOutput } from './shepherd-output'
20
+
21
+ export const LandInput = Schema.Struct({
22
+ source: Schema.String.annotate({ description: 'The branch to deliver, such as release/next.' }),
23
+ target: Schema.optional(Schema.String).annotate({
24
+ description: "Where to deliver it; the branch `source` delivers into when left out, else the repository's default."
25
+ }),
26
+ hold: Schema.optional(Schema.Boolean).annotate({
27
+ description: 'Gets the ChangeRequest level, green and approved, and stops as ready, merging nothing.'
28
+ }),
29
+ title: Schema.optional(Schema.String).annotate({
30
+ description: "The ChangeRequest's title; `Land <source> into <target>` when left out."
31
+ }),
32
+ repoBindingId: Schema.optional(Schema.String).annotate({
33
+ description: "The repository to land in; the Team's default repository when left out."
34
+ }),
35
+ changeRequestId: Schema.optional(Schema.String).annotate({
36
+ description:
37
+ 'The open ChangeRequest from `source` into `target` to work on, opening none, as `delivery.conflicted` names the one that conflicts.'
38
+ }),
39
+ deliversInto: Schema.optional(Schema.String).annotate({
40
+ description: "Set by Kitman: the branch `source` delivers into, when it is a Milestone's or a Project's branch."
41
+ }),
42
+ merge: Schema.optional(Schema.Boolean).annotate({
43
+ description: 'Merges once it is level, green and approved without asking, as when a Release already asked.'
44
+ }),
45
+ head: Schema.optional(Schema.String).annotate({
46
+ description:
47
+ 'The head of `source` approved to merge, as a Release gated it: Land ends as `moved` at any other, and Shepherd merges only it or a catch-up of it.'
48
+ }),
49
+ releaseTrigger: Schema.optional(ReleaseTrigger).annotate({
50
+ description:
51
+ "Shepherd's own release trigger; `manual` starts no Release after the merge, as when a Release lands it."
52
+ })
53
+ })
54
+
55
+ export const LandOutput = Schema.Struct({
56
+ status: Schema.Literals(['landed', 'ready', 'nothing', 'elsewhere', 'busy', 'needs_you', 'moved']).annotate({
57
+ description:
58
+ 'landed: merged; ready: held level, green and approved; nothing: the branches do not differ, or the ChangeRequest it was given no longer delivers them; elsewhere: another Team holds the ChangeRequest; busy: another Run, such as the Shepherd of an earlier Land, works the source branch; needs_you: Shepherd stopped for a person; moved: the ChangeRequest is at another head than `head`, so nothing merged.'
59
+ }),
60
+ reason: Schema.String.annotate({ description: 'Why it ended as it did, in a line.' }),
61
+ revision: Schema.optional(Schema.String).annotate({ description: 'The merge revision, once it landed.' }),
62
+ team: Schema.optional(Schema.String).annotate({
63
+ description: 'The Team that holds the ChangeRequest, when elsewhere.'
64
+ }),
65
+ changeRequest: Schema.optional(ChangeRequestResult).annotate({ description: 'The ChangeRequest that delivers it.' }),
66
+ conflicts: Schema.optional(Schema.Array(Schema.String)).annotate({
67
+ description:
68
+ "With hold, the files of a conflict with `target` Shepherd could not settle; Kitman tells the Project's lead when a delivery Event started the Run."
69
+ }),
70
+ shepherd: Schema.optional(ShepherdOutput).annotate({ description: 'What Shepherd did with the ChangeRequest.' })
71
+ })
72
+
73
+ type Output = typeof LandOutput.Type
74
+
75
+ /** What Shepherd did, or that Kitman refused it because another Run works the branch or the ChangeRequest closed. */
76
+ type Shepherded = typeof ShepherdOutput.Type | { readonly busy: string } | { readonly gone: string }
77
+
78
+ const shepherdStatus = {
79
+ merged: 'landed',
80
+ ready: 'ready',
81
+ needs_you: 'needs_you',
82
+ handed_back: 'needs_you'
83
+ } as const satisfies { readonly [status in (typeof ShepherdOutput.Type)['status']]: Output['status'] }
84
+
85
+ /** How the forge names a ChangeRequest in a description, so the list names no title and no Task. */
86
+ const reference = (provider: string, change: { readonly number: string; readonly url: string }) =>
87
+ provider === 'gitlab' ? `!${change.number}` : provider === 'github' ? `#${change.number}` : change.url
88
+
89
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`
90
+
91
+ const bodyOf = (source: string, target: string, provider: string, { ahead, truncated }: Comparison) =>
92
+ [
93
+ `Delivers ${source} into ${target}.`,
94
+ ahead.changeRequests.length === 0
95
+ ? `It carries no merged ChangeRequest Kitman knows ${target} lacks.`
96
+ : [
97
+ `The merged ChangeRequests it carries that ${target} lacks:`,
98
+ '',
99
+ ...ahead.changeRequests.map(change => `- ${reference(provider, change)}`)
100
+ ].join('\n'),
101
+ ...(truncated === true ? [`It carries more than these; the list stops short.`] : []),
102
+ ...(ahead.unlinked === 0 ? [] : [`${plural(ahead.unlinked, 'commit')} reached ${source} through no ChangeRequest.`])
103
+ ].join('\n\n')
104
+
105
+ const between = { source: 'branch', target: 'base', repoBindingId: 'repository' }
106
+
107
+ /** Kitman records these only from what the forge said, and a Run they start never merges, whatever its Input says. */
108
+ const deliveryEvents: readonly string[] = ['delivery.missing', 'delivery.conflicted']
109
+
110
+ const startedByDelivery = (startedBy: RunStarter) =>
111
+ startedBy.kind === 'event' && deliveryEvents.includes(startedBy.type)
112
+
113
+ /** How long a conflict's Land waits, each time, for the Run that works the branch to leave it, about eight days in all. */
114
+ const busyWaits = ['10 minutes', '30 minutes', '1 hour', '2 hours', '4 hours', '8 hours', ...Array(8).fill('1 day')]
115
+
116
+ /** Opens the ChangeRequest from `source` into `target`, or continues on the open one. */
117
+ const openOrContinue = (source: string, target: string, title: string | undefined, provider: string) =>
118
+ Effect.gen(function* () {
119
+ const delivers = yield* compare('delivers', { base: `origin/${target}`, head: `origin/${source}` })
120
+
121
+ const opened = yield* changeRequest('change-request', {
122
+ source,
123
+ target,
124
+ title: title ?? `Land ${source} into ${target}`,
125
+ body: bodyOf(source, target, provider, delivers)
126
+ })
127
+
128
+ if (opened.status === 'nothing')
129
+ return {
130
+ status: 'stop',
131
+ output: { status: 'nothing', reason: `${target} already has every commit of ${source}` } satisfies Output
132
+ } as const
133
+
134
+ if (opened.status === 'elsewhere')
135
+ return {
136
+ status: 'stop',
137
+ output: {
138
+ status: 'elsewhere',
139
+ reason: `${opened.team} holds the ChangeRequest from ${source} into ${target}`,
140
+ team: opened.team
141
+ } satisfies Output
142
+ } as const
143
+
144
+ return {
145
+ status: 'open',
146
+ id: opened.id,
147
+ changeRequestOutput: { changeRequest: { id: opened.id, number: opened.number, url: opened.url } }
148
+ } as const
149
+ })
150
+
151
+ /** The ChangeRequest Land was given, while it still goes from `source` into `target`; Land opens no other. */
152
+ const delivering = (changeRequestId: string, source: string, target: string) =>
153
+ Effect.map(pipelineStatus('delivering', { changeRequestId }), read =>
154
+ read.sourceBranch === source && read.targetBranch === target
155
+ ? ({ status: 'open', id: changeRequestId, changeRequestOutput: {} } as const)
156
+ : ({
157
+ status: 'stop',
158
+ output: {
159
+ status: 'nothing',
160
+ reason: `ChangeRequest ${changeRequestId} no longer goes from ${source} into ${target}`
161
+ } satisfies Output
162
+ } as const)
163
+ )
164
+
165
+ /**
166
+ * Delivers `source` into `target`: opens the ChangeRequest between them, or continues on the open one, its body listing
167
+ * the merged ChangeRequests it carries by their forge references, and calls Shepherd to merge it, or with `hold` to
168
+ * get it level, green and approved and stop. It starts held on `delivery.missing`, so a target branch has its
169
+ * ChangeRequest open from its first merge, and on `delivery.conflicted`, so a conflict is settled when it appears.
170
+ */
171
+ const land = defineLoop({
172
+ id: 'land',
173
+ version: '1.2.0',
174
+ title: 'Land',
175
+ description: 'Delivers one branch into another through a ChangeRequest that Shepherd merges.',
176
+ input: LandInput,
177
+ output: LandOutput,
178
+ agents: {},
179
+ checkout: 'read',
180
+ when: [
181
+ { name: 'open-delivery', event: 'delivery.missing', input: between, values: { hold: true } },
182
+ {
183
+ name: 'level-delivery',
184
+ event: 'delivery.conflicted',
185
+ input: { ...between, changeRequestId: 'changeRequestId' },
186
+ values: { hold: true }
187
+ }
188
+ ],
189
+ capabilities: ['change_request', 'read_change_request', 'verify', 'call'],
190
+ calls: (): readonly CalledLoop[] => [shepherd],
191
+ run: input =>
192
+ Effect.gen(function* () {
193
+ const { repository, startedBy } = yield* runContext
194
+
195
+ if (repository === undefined) return yield* Effect.die(new Error('Land needs a repository to land in'))
196
+
197
+ const { source } = input
198
+ const target = input.target ?? input.deliversInto ?? repository.defaultBranch
199
+ const hold = input.hold === true || startedByDelivery(startedBy)
200
+ const given = input.changeRequestId
201
+
202
+ const opened =
203
+ given === undefined
204
+ ? yield* openOrContinue(source, target, input.title, repository.repoBinding.provider)
205
+ : yield* delivering(given, source, target)
206
+
207
+ if (opened.status !== 'open') return opened.output
208
+
209
+ const { changeRequestOutput } = opened
210
+ const changeRequestId = opened.id
211
+ const approvedHead = input.head?.toLowerCase()
212
+
213
+ if (approvedHead !== undefined) {
214
+ const { head } = yield* pipelineStatus('head', { changeRequestId })
215
+
216
+ if (head.toLowerCase() !== approvedHead)
217
+ return {
218
+ status: 'moved',
219
+ reason: `${source} moved to ${head} after ${approvedHead} was approved to merge, so nothing was merged`,
220
+ ...changeRequestOutput
221
+ } satisfies Output
222
+ }
223
+
224
+ const shepherdIn = (step: string) =>
225
+ call(step, shepherd, {
226
+ changeRequestId,
227
+ ...(hold ? { hold: true } : input.merge === true ? { merge: true, level: true } : undefined),
228
+ ...(approvedHead === undefined ? undefined : { head: approvedHead }),
229
+ ...(input.releaseTrigger === undefined ? undefined : { releaseTrigger: input.releaseTrigger })
230
+ }).pipe(
231
+ Effect.catchTag('StepFailed', refused =>
232
+ refused.code === 'task_branch_busy' || refused.code === 'epic_landing'
233
+ ? Effect.succeed<Shepherded>({ busy: refused.reason })
234
+ : refused.code === 'change_request_not_open'
235
+ ? Effect.succeed<Shepherded>({ gone: refused.reason })
236
+ : Effect.fail(refused)
237
+ )
238
+ )
239
+
240
+ let shepherded: Shepherded = yield* shepherdIn('shepherd')
241
+
242
+ // A conflict waits for the Run on the branch to leave it, so it is settled, or its lead hears it was not.
243
+ for (const [attempt, timeout] of busyWaits.entries()) {
244
+ if (!('busy' in shepherded) || given === undefined) break
245
+
246
+ const closed = yield* waitFor(`branch-free:${attempt + 1}`, {
247
+ event: 'change_request.closed',
248
+ filter: { changeRequestId },
249
+ timeout
250
+ }).pipe(
251
+ Effect.as(true),
252
+ Effect.catchTag('WaitTimedOut', () => Effect.succeed(false))
253
+ )
254
+
255
+ shepherded = closed
256
+ ? { gone: `ChangeRequest ${changeRequestId} closed` }
257
+ : yield* shepherdIn(`shepherd:${attempt + 1}`)
258
+ }
259
+
260
+ if ('gone' in shepherded)
261
+ return {
262
+ status: 'nothing',
263
+ reason: `The ChangeRequest no longer delivers ${source} into ${target}: ${shepherded.gone}`
264
+ } satisfies Output
265
+
266
+ if ('busy' in shepherded)
267
+ return given === undefined
268
+ ? ({ status: 'busy', reason: shepherded.busy, ...changeRequestOutput } satisfies Output)
269
+ : ({
270
+ status: 'needs_you',
271
+ reason: `${source} conflicts with ${target}, and another Run still worked the branch after eight days: ${shepherded.busy}`,
272
+ conflicts: [],
273
+ ...changeRequestOutput
274
+ } satisfies Output)
275
+
276
+ // Shepherd knows the revision only of a merge it made; one a person or another Run made, Kitman recorded.
277
+ const revision =
278
+ shepherded.status === 'merged'
279
+ ? (shepherded.revision ?? (yield* mergedChangeRequest('merged', { changeRequestId })).mergeRevision)
280
+ : undefined
281
+
282
+ return {
283
+ status: shepherdStatus[shepherded.status],
284
+ reason: shepherded.reason,
285
+ ...(revision === undefined ? undefined : { revision }),
286
+ ...(shepherded.conflicts === undefined ? undefined : { conflicts: shepherded.conflicts }),
287
+ ...changeRequestOutput,
288
+ shepherd: shepherded
289
+ } satisfies Output
290
+ })
291
+ })
292
+
293
+ export default land
package/src/landed.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { call, DeliveryTarget, step } from '@kitman-sh/sdk/loop'
2
+ import * as Schema from 'effect/Schema'
3
+ import shepherd from './shepherd'
4
+ import { ShepherdOutput } from './shepherd-output'
5
+
6
+ /** Has Shepherd see a ChangeRequest through to merge. The calling Loop lists Shepherd in `calls`. */
7
+ export const landed = step('landed', {
8
+ payload: {
9
+ changeRequestId: Schema.String.annotate({ description: 'The open ChangeRequest to land.' }),
10
+ notRun: Schema.optional(Schema.Array(Schema.String)).annotate({
11
+ description: 'Why each test verify never ran on its head is unverified.'
12
+ }),
13
+ taskId: Schema.optional(Schema.String).annotate({ description: 'The Task it delivers.' }),
14
+ branch: Schema.optional(Schema.String).annotate({
15
+ description: "The base branch it merges into, when the Run's Input named one."
16
+ }),
17
+ deliveryTarget: Schema.optional(DeliveryTarget).annotate({
18
+ description: "The Run's own delivery target, over its Project's, Team's and Workspace's."
19
+ })
20
+ },
21
+ success: ShepherdOutput,
22
+ run: ({ changeRequestId, notRun, taskId, branch, deliveryTarget }) =>
23
+ call('land', shepherd, {
24
+ changeRequestId,
25
+ ...(notRun === undefined ? undefined : { notRun }),
26
+ ...(taskId === undefined ? undefined : { taskId }),
27
+ ...(branch === undefined ? undefined : { branch }),
28
+ ...(deliveryTarget === undefined ? undefined : { deliveryTarget })
29
+ })
30
+ })
package/src/opened.ts ADDED
@@ -0,0 +1,79 @@
1
+ import {
2
+ approveChangeRequest,
3
+ ApproveChangeRequestResult,
4
+ changeRequest,
5
+ ChangeRequestResult,
6
+ comment,
7
+ step,
8
+ writeBack
9
+ } from '@kitman-sh/sdk/loop'
10
+ import * as Effect from 'effect/Effect'
11
+ import * as Schema from 'effect/Schema'
12
+
13
+ export class Opened extends Schema.TaggedClass<Opened>()('Opened', {
14
+ changeRequest: ChangeRequestResult,
15
+ /** Whether the head's approval was recorded, or why not; left out when the caller did not say it is settled. */
16
+ approval: Schema.optionalKey(ApproveChangeRequestResult)
17
+ }) {}
18
+
19
+ /**
20
+ * Opens the Run's ChangeRequest and writes that back to its Task, or reports on the ChangeRequest the Run continues,
21
+ * leaving its title and description alone; then approves the head when nothing is unsettled.
22
+ */
23
+ export const opened = step('opened', {
24
+ payload: {
25
+ title: Schema.String.annotate({ description: "A new ChangeRequest's title." }),
26
+ body: Schema.String.annotate({
27
+ description: "A new ChangeRequest's description, or the report on the one the Run continues."
28
+ }),
29
+ writeBack: Schema.optional(Schema.Boolean).annotate({
30
+ description:
31
+ 'Whether a new ChangeRequest is written back to the Task, which needs `write_back`; it is when left out.'
32
+ }),
33
+ continues: Schema.optional(
34
+ Schema.Struct({ changeRequestId: Schema.String, number: Schema.String, url: Schema.String })
35
+ ).annotate({ description: 'The open ChangeRequest to report on instead of opening one.' }),
36
+ report: Schema.optional(Schema.String).annotate({
37
+ description:
38
+ 'The key of the report on a continued ChangeRequest, which keeps one comment for it: a later report with the same key edits that comment.'
39
+ }),
40
+ settled: Schema.optional(
41
+ Schema.Struct({
42
+ head: Schema.String,
43
+ summary: Schema.String,
44
+ review: Schema.optional(Schema.String)
45
+ })
46
+ ).annotate({
47
+ description:
48
+ 'Given only when nothing is unsettled: the head to approve, what the approval says, and the Step of the passing Review it is, as `rallied` names it.'
49
+ })
50
+ },
51
+ success: Opened,
52
+ run: ({ title, body, writeBack: writesBack = true, continues, report, settled }) =>
53
+ Effect.gen(function* () {
54
+ const delivered =
55
+ continues === undefined
56
+ ? yield* changeRequest('change-request', { title, body })
57
+ : yield* comment('report', {
58
+ changeRequestId: continues.changeRequestId,
59
+ body,
60
+ ...(report === undefined ? undefined : { summary: report })
61
+ }).pipe(Effect.as({ id: continues.changeRequestId, number: continues.number, url: continues.url }))
62
+
63
+ if (continues === undefined && writesBack)
64
+ yield* writeBack('write-back', { milestone: 'change_request_opened', changeRequestUrl: delivered.url })
65
+
66
+ if (settled === undefined) return new Opened({ changeRequest: delivered })
67
+
68
+ const approval = yield* approveChangeRequest('approve', {
69
+ changeRequestId: delivered.id,
70
+ head: settled.head,
71
+ summary: settled.summary,
72
+ ...(settled.review === undefined ? undefined : { review: settled.review })
73
+ }).pipe(
74
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
75
+ )
76
+
77
+ return new Opened({ changeRequest: delivered, approval })
78
+ })
79
+ })
@@ -1,8 +1,10 @@
1
- import { agentWork, PlanTicket, planTicketsOf } from '@kitman-sh/sdk/loop'
1
+ import { agent, PlanTicket, planTicketsOf } from '@kitman-sh/sdk/loop'
2
2
  import * as Effect from 'effect/Effect'
3
3
  import * as Schema from 'effect/Schema'
4
4
  import { Reason } from './text-limits'
5
5
 
6
+ const planReviewer = agent('plan-reviewer')
7
+
6
8
  /** Tickets that each state their scope, as the plan reviewer checks it. */
7
9
  export const ScopedTickets = planTicketsOf(
8
10
  Schema.Struct({
@@ -40,7 +42,7 @@ export type DeclinedConcern = typeof DeclinedConcern.Type
40
42
  export type PlanConcern = typeof Concern.Type & { readonly id: string }
41
43
 
42
44
  /** A concern the reviewer holds after the revision, and why the planner did not act on it when it said so. */
43
- export type DisputedConcern = typeof Concern.Type & { readonly declined?: string }
45
+ export type DisputedConcern = typeof Concern.Type & { readonly declined?: string | undefined }
44
46
 
45
47
  type Revision<Plan> = { readonly plan: Plan; readonly declined: readonly DeclinedConcern[] }
46
48
 
@@ -130,8 +132,7 @@ const recheckPrompt = (
130
132
  */
131
133
  export const reviewPlan = <Plan, E, R>(step: string, { plan, asked, text, revise }: PlanUnderReview<Plan, E, R>) =>
132
134
  Effect.gen(function* () {
133
- const first = yield* agentWork(step, {
134
- agent: 'plan-reviewer',
135
+ const first = yield* planReviewer(step, {
135
136
  prompt: checkPrompt(asked, text(plan)),
136
137
  output: Check
137
138
  })
@@ -141,8 +142,7 @@ export const reviewPlan = <Plan, E, R>(step: string, { plan, asked, text, revise
141
142
  const concerns = first.concerns.map((concern, index) => ({ ...concern, id: `c${index + 1}` }))
142
143
  const revised = yield* revise(`${step}:revise`, revisePrompt(asked, text(plan), concerns))
143
144
 
144
- const again = yield* agentWork(`${step}:recheck`, {
145
- agent: 'plan-reviewer',
145
+ const again = yield* planReviewer(`${step}:recheck`, {
146
146
  prompt: recheckPrompt(asked, text(revised.plan), concerns, revised.declined),
147
147
  output: Recheck
148
148
  })
@@ -158,8 +158,7 @@ export const reviewPlan = <Plan, E, R>(step: string, { plan, asked, text, revise
158
158
 
159
159
  /** Has the calling Loop's `plan-reviewer` check tickets once, each concern on one of them. */
160
160
  export const reviewTickets = (step: string, tickets: typeof ScopedTickets.Type) =>
161
- agentWork(step, {
162
- agent: 'plan-reviewer',
161
+ planReviewer(step, {
163
162
  prompt: ticketsPrompt(tickets),
164
163
  output: Schema.Struct({
165
164
  concerns: Schema.Array(