@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/sweep.ts CHANGED
@@ -1,38 +1,51 @@
1
1
  import {
2
- agentWork,
2
+ agent,
3
3
  artifact,
4
4
  call,
5
- changeRequest,
6
5
  ChangeRequestResult,
7
6
  closeChangeRequest,
8
7
  defineLoop,
8
+ DuplicateStep,
9
+ type OpenChangeRequest,
9
10
  openChangeRequests,
10
11
  ownChangeRequests,
11
12
  pipelineStatus,
13
+ step,
14
+ stepName,
12
15
  testsNotRunReasons,
13
16
  verify,
14
- type OpenChangeRequests,
15
- type VerifyResult
17
+ VerifyResult
16
18
  } from '@kitman-sh/sdk/loop'
17
19
  import * as Effect from 'effect/Effect'
18
20
  import * as Schema from 'effect/Schema'
19
- import { notVerifiedSection, verifyHead } from './change-request-body'
21
+ import { implementer } from './agents'
22
+ import { notVerifiedSection, verifyHead, withoutOutput } from './change-request-body'
23
+ import { opened } from './opened'
20
24
  import shepherd from './shepherd'
21
25
  import { OneSentence } from './text-limits'
22
26
 
27
+ const assessor = agent('assessor')
28
+
23
29
  const Input = Schema.Struct({
24
- /** The dependency bots' logins; Renovate's and Dependabot's on GitHub when left out. */
25
- authors: Schema.optional(Schema.NonEmptyArray(Schema.String)),
26
- /** The branch the batch targets; the repository's default branch when left out. */
27
- branch: Schema.optional(Schema.String),
28
- repoBindingId: Schema.optional(Schema.String),
29
- /** Rounds of fixing what the batch breaks before an update is dropped instead; 2 when left out. */
30
- maxFixRounds: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(5)))
30
+ authors: Schema.optional(Schema.NonEmptyArray(Schema.String)).annotate({
31
+ description: "The dependency bots' logins; Renovate's and Dependabot's on GitHub when left out."
32
+ }),
33
+ branch: Schema.optional(Schema.String).annotate({
34
+ description: "The branch the batch targets; the repository's default branch when left out."
35
+ }),
36
+ repoBindingId: Schema.optional(Schema.String).annotate({
37
+ description: "The repository to sweep; the Team's default repository when left out."
38
+ }),
39
+ maxFixRounds: Schema.optional(
40
+ Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(5))
41
+ ).annotate({
42
+ description: 'Rounds of fixing what the batch breaks before an update is dropped instead; 2 when left out.'
43
+ })
31
44
  })
32
45
 
33
46
  const Decision = Schema.Literals(['batch', 'alone', 'hold'])
34
47
 
35
- const Assessed = Schema.Struct({
48
+ const Assessment = Schema.Struct({
36
49
  updates: Schema.Array(
37
50
  Schema.Struct({
38
51
  number: Schema.String,
@@ -45,7 +58,7 @@ const Assessed = Schema.Struct({
45
58
  )
46
59
  })
47
60
 
48
- const Batched = Schema.Struct({
61
+ const Batch = Schema.Struct({
49
62
  /** The updates now on the branch. */
50
63
  applied: Schema.Array(Schema.String),
51
64
  /** The updates taken out, each with why. */
@@ -53,30 +66,52 @@ const Batched = Schema.Struct({
53
66
  summary: OneSentence
54
67
  })
55
68
 
56
- type Batched = typeof Batched.Type
69
+ const named = { number: Schema.String, title: Schema.String, url: Schema.String }
57
70
 
58
- const Placed = Schema.Struct({ number: Schema.String, title: Schema.String, url: Schema.String, reason: Schema.String })
71
+ const Placed = Schema.Struct({ ...named, reason: Schema.String })
59
72
 
60
73
  type Placed = typeof Placed.Type
61
74
 
62
75
  const Output = Schema.Struct({
63
- /** nothing_to_sweep: the bots have nothing open; reported: nothing could be batched or it did not pass. */
64
- status: Schema.Literals(['nothing_to_sweep', 'reported', 'opened', 'landed']),
65
- summary: Schema.String,
66
- landed: Schema.Array(Placed),
67
- /** Left for a person: updates that go alone, are held, or dropped out of the batch. */
68
- left: Schema.Array(Placed),
69
- reportArtifactId: Schema.optional(Schema.String),
70
- changeRequest: Schema.optional(ChangeRequestResult)
76
+ status: Schema.Literals(['nothing_to_sweep', 'reported', 'opened', 'landed']).annotate({
77
+ description: 'nothing_to_sweep: the bots have nothing open; reported: nothing could be batched or it did not pass.'
78
+ }),
79
+ summary: Schema.String.annotate({ description: 'What the sweep did, in a line.' }),
80
+ landed: Schema.Array(Placed).annotate({ description: 'The updates the batch took in.' }),
81
+ left: Schema.Array(Placed).annotate({
82
+ description: 'Left for a person: updates that go alone, are held, or dropped out of the batch.'
83
+ }),
84
+ reportArtifactId: Schema.optional(Schema.String).annotate({
85
+ description: 'The Artifact holding the report, when it wrote one.'
86
+ }),
87
+ changeRequest: Schema.optional(ChangeRequestResult).annotate({
88
+ description: "The batch's ChangeRequest, when it opened one."
89
+ })
71
90
  })
72
91
 
73
92
  type Output = typeof Output.Type
74
93
 
75
- type Bot = OpenChangeRequests['changeRequests'][number]
94
+ const Update = Schema.Struct({
95
+ ...named,
96
+ body: Schema.String,
97
+ sourceBranch: Schema.String,
98
+ head: Schema.String
99
+ })
100
+
101
+ type Update = typeof Update.Type
102
+
103
+ const updateOf = ({ number, title, url, body, sourceBranch, head }: typeof OpenChangeRequest.Type): Update => ({
104
+ number,
105
+ title,
106
+ url,
107
+ body,
108
+ sourceBranch,
109
+ head
110
+ })
76
111
 
77
112
  const defaultAuthors = ['renovate[bot]', 'dependabot[bot]'] as const
78
113
 
79
- const listing = (requests: readonly Bot[]) =>
114
+ const listing = (requests: readonly Update[]) =>
80
115
  requests
81
116
  .map(request =>
82
117
  [
@@ -87,7 +122,7 @@ const listing = (requests: readonly Bot[]) =>
87
122
  )
88
123
  .join('\n\n')
89
124
 
90
- const assessPrompt = (requests: readonly Bot[]) =>
125
+ const assessPrompt = (requests: readonly Update[]) =>
91
126
  [
92
127
  'These dependency updates are open. Read each one’s changelog and breaking-change notes, and what in this repository uses it.',
93
128
  listing(requests),
@@ -95,29 +130,35 @@ const assessPrompt = (requests: readonly Bot[]) =>
95
130
  'Say whether it bumps a major version. Change nothing.'
96
131
  ].join('\n\n')
97
132
 
98
- const batchPrompt = (requests: readonly Bot[], target: string) =>
133
+ const batchPrompt = (requests: readonly Update[], target: string) =>
99
134
  [
100
135
  `Bring these dependency updates onto this branch, which starts from ${target}: for each, merge \`origin/<branch>\` at the head named; Kitman fetched origin just before this Step, so do not fetch. Where lockfiles conflict, regenerate them with the package manager instead of hand-merging.`,
101
136
  listing(requests),
102
137
  'An update that cannot be brought in cleanly is dropped: leave it out and say why. Commit nothing yourself; Kitman pushes what you leave.'
103
138
  ].join('\n\n')
104
139
 
105
- const fixPrompt = (failed: VerifyResult, applied: readonly string[]) =>
140
+ const FailedCheck = Schema.Struct({ name: Schema.String, command: Schema.String })
141
+
142
+ const failedChecks = (head: VerifyResult) => head.checks.filter(check => check.status === 'failed')
143
+
144
+ const fixPrompt = (failed: readonly (typeof FailedCheck.Type)[], applied: readonly string[]) =>
106
145
  [
107
146
  `The batch of ${applied.map(number => `!${number}`).join(', ')} fails these checks:`,
108
- ...failed.checks.filter(check => check.status === 'failed').map(check => `- ${check.name}: \`${check.command}\``),
147
+ ...failed.map(check => `- ${check.name}: \`${check.command}\``),
109
148
  'Fix what an update broke, the way its changelog says to. If an update cannot be fixed in a small change, take it back out and drop it with the reason. Commit nothing yourself.'
110
149
  ].join('\n\n')
111
150
 
112
151
  const supersedes = 'Supersedes:'
113
152
 
114
153
  /** An update a batch brings in, at the head it was brought in at. */
115
- type Landing = Placed & { readonly head: string }
154
+ const Landing = Schema.Struct({ ...named, head: Schema.String })
155
+
156
+ type Landing = typeof Landing.Type
116
157
 
117
158
  const supersededLine = (update: Landing) => `- !${update.number} ${update.title} (${update.url}) at ${update.head}`
118
159
 
119
160
  /** The updates a batch's description says it supersedes, as `supersededLine` wrote them. */
120
- const supersededIn = (body: string): Landing[] => {
161
+ const supersededIn = (body: string): readonly Landing[] => {
121
162
  const after = body.split(supersedes)[1] ?? ''
122
163
  const listed = after.split('Left for a person:')[0] ?? ''
123
164
 
@@ -126,48 +167,10 @@ const supersededIn = (body: string): Landing[] => {
126
167
 
127
168
  return found === null
128
169
  ? []
129
- : [
130
- {
131
- number: found[1] ?? '',
132
- title: found[2] ?? '',
133
- url: found[3] ?? '',
134
- head: found[4] ?? '',
135
- reason: 'Verified in the batch'
136
- }
137
- ]
170
+ : [{ number: found[1] ?? '', title: found[2] ?? '', url: found[3] ?? '', head: found[4] ?? '' }]
138
171
  })
139
172
  }
140
173
 
141
- /**
142
- * Closes each update a merged batch landed, with a note pointing at the batch. One the bot pushed to after it was
143
- * batched stays open: its new head landed nowhere. Returns those, for a person.
144
- */
145
- const closeSuperseded = (landing: readonly Landing[], batchUrl: string) =>
146
- Effect.map(
147
- Effect.forEach(landing, ({ head, ...update }) =>
148
- Effect.map(
149
- closeChangeRequest(`close:${update.number}`, {
150
- number: update.number,
151
- head,
152
- note: `Landed in ${batchUrl} with the other dependency updates Sweep verified together.`
153
- }),
154
- closed =>
155
- closed.head === undefined
156
- ? []
157
- : [{ ...update, reason: `The bot pushed ${closed.head} after Sweep batched ${head}, so it stays open` }]
158
- )
159
- ),
160
- moved => moved.flat()
161
- )
162
-
163
- /** What landed and what is left once the updates that moved are left open. */
164
- const afterClosing = (landing: readonly Landing[], left: readonly Placed[], moved: readonly Placed[]) => ({
165
- landed: landing.flatMap(({ head: _head, ...update }) =>
166
- moved.some(open => open.number === update.number) ? [] : [update]
167
- ),
168
- left: [...left, ...moved]
169
- })
170
-
171
174
  const reportText = (landing: readonly Placed[], left: readonly Placed[], heading: string) =>
172
175
  [
173
176
  heading,
@@ -177,236 +180,412 @@ const reportText = (landing: readonly Placed[], left: readonly Placed[], heading
177
180
  : ['Left for a person:', ...left.map(update => `- !${update.number} ${update.title}: ${update.reason}`)])
178
181
  ].join('\n')
179
182
 
180
- /**
181
- * Gathers the dependency bot's open ChangeRequests, lands the safe ones together, and leaves the rest explained. Each
182
- * update is classified batch, alone or hold with a reason; a major version bump is never batched silently. The batch
183
- * is built from the bots' heads read again just before, verified, and fixed for a bounded number of rounds; an update
184
- * that still breaks drops out with its reason. One ChangeRequest names each update it supersedes and is shepherded to
185
- * merge once approved; then the superseded ChangeRequests are closed with a note.
186
- */
187
- export default defineLoop({
188
- id: 'sweep',
189
- version: '1.2.0',
190
- title: 'Sweep',
191
- input: Input,
192
- output: Output,
193
- agents: { assessor: 'investigator', implementer: 'implementer' },
194
- checkout: 'write',
195
- schedule: { rule: { frequency: 'weekly', daysOfWeek: [1], hour: 6, minute: 0 }, timezone: 'UTC' },
196
- capabilities: ['agent_work', 'verify', 'change_request', 'read_change_request', 'merge_change_request'],
197
- calls: () => [shepherd],
198
- run: input =>
199
- Effect.gen(function* () {
200
- const authors = input.authors ?? defaultAuthors
183
+ export class Listed extends Schema.TaggedClass<Listed>()('Listed', { updates: Schema.Array(Update) }) {}
201
184
 
202
- // A batch an earlier Sweep left open is landed, not batched again beside it.
203
- const [earlier] = (yield* ownChangeRequests('earlier')).changeRequests
185
+ export class NothingToSweep extends Schema.TaggedClass<NothingToSweep>()('NothingToSweep', {}) {}
204
186
 
205
- if (earlier !== undefined) {
206
- const { head } = yield* pipelineStatus('earlier-head', { changeRequestId: earlier.id })
207
- // Tests verify never ran at the batch's head are for a person to run before it lands, as when it was opened.
208
- const { notRun } = yield* verifyHead('earlier-verify', head)
187
+ /** A batch an earlier Sweep left open, which is landed instead of batching again beside it. */
188
+ export class LeftOpen extends Schema.TaggedClass<LeftOpen>()('LeftOpen', {
189
+ changeRequest: ChangeRequestResult,
190
+ /** The updates its description says it supersedes. */
191
+ landing: Schema.Array(Landing),
192
+ /** The tests verify never ran at its head, which are for a person to run before it lands. */
193
+ notRun: Schema.Array(Schema.String)
194
+ }) {}
209
195
 
210
- const landed = yield* call('land', shepherd, {
211
- changeRequestId: earlier.id,
212
- merge: notRun.length === 0,
213
- ...(notRun.length === 0 ? undefined : { notRun }),
214
- ...(input.branch === undefined ? undefined : { branch: input.branch })
215
- }).pipe(
216
- Effect.catchTag('StepFailed', refused =>
217
- refused.code === 'task_branch_busy' ? Effect.succeed({ held: refused.reason }) : Effect.fail(refused)
218
- )
219
- )
196
+ /** Lists what there is to sweep: the batch an earlier Sweep left open, or else the bots' open ChangeRequests. */
197
+ export const listed = step('listed', {
198
+ payload: { authors: Schema.NonEmptyArray(Schema.String) },
199
+ success: Schema.Union([Listed, NothingToSweep, LeftOpen]),
200
+ run: ({ authors }) =>
201
+ Effect.gen(function* () {
202
+ const [batch] = (yield* ownChangeRequests('earlier')).changeRequests
220
203
 
221
- if ('held' in landed)
222
- return {
223
- status: 'opened',
224
- summary: `${earlier.url}, from an earlier Sweep, is still open, and another Run works its branch, so Sweep left it to that Run: ${landed.held}`,
225
- landed: [],
226
- left: [],
227
- changeRequest: { id: earlier.id, number: earlier.number, url: earlier.url }
228
- } satisfies Output
204
+ if (batch !== undefined) {
205
+ const { head } = yield* pipelineStatus('earlier-head', { changeRequestId: batch.id })
206
+ const { notRun } = yield* verifyHead('earlier-verify', head)
229
207
 
230
- const summary = `${earlier.url}, from an earlier Sweep, is still open; Sweep took it on instead of batching again: ${landed.status}. ${landed.reason}`
231
- // Its description names what it supersedes, so merging it closes those as a fresh batch would.
232
- const landing = supersededIn(earlier.body)
208
+ return new LeftOpen({
209
+ changeRequest: { id: batch.id, number: batch.number, url: batch.url },
210
+ landing: supersededIn(batch.body),
211
+ notRun
212
+ })
213
+ }
233
214
 
234
- const settled = afterClosing(
235
- landing,
236
- [],
237
- landed.status === 'merged' ? yield* closeSuperseded(landing, earlier.url) : []
238
- )
215
+ const { changeRequests } = yield* openChangeRequests('bots', { authors })
239
216
 
240
- const stored = yield* artifact('report', {
241
- kind: 'sweep_report',
242
- title: 'Sweep',
243
- text: reportText(settled.landed, settled.left, summary)
244
- })
217
+ return changeRequests.length === 0 ? new NothingToSweep() : new Listed({ updates: changeRequests.map(updateOf) })
218
+ })
219
+ })
245
220
 
246
- return {
247
- status: landed.status === 'merged' ? 'landed' : 'opened',
248
- summary,
249
- ...settled,
250
- reportArtifactId: stored.artifactId,
251
- changeRequest: { id: earlier.id, number: earlier.number, url: earlier.url }
252
- } satisfies Output
253
- }
221
+ export class Assessed extends Schema.TaggedClass<Assessed>()('Assessed', {
222
+ decisions: Schema.Array(Schema.Struct({ number: Schema.String, decision: Decision, reason: Schema.String }))
223
+ }) {}
224
+
225
+ /** Decides for each update whether it is batched, goes alone or is held; a major version bump is never batched. */
226
+ export const assessed = step('assessed', {
227
+ payload: { updates: Schema.Array(Update) },
228
+ success: Assessed,
229
+ run: ({ updates }) =>
230
+ Effect.map(
231
+ assessor('assess', { prompt: assessPrompt(updates), output: Assessment }),
232
+ assessment =>
233
+ new Assessed({
234
+ decisions: updates.map(({ number }) => {
235
+ const decided = assessment.updates.find(update => update.number === number)
236
+
237
+ if (decided === undefined) return { number, decision: 'hold', reason: 'It was not assessed' }
238
+
239
+ return decided.major && decided.decision === 'batch'
240
+ ? { number, decision: 'alone', reason: `A major version bump goes alone. ${decided.reason}` }
241
+ : { number, decision: decided.decision, reason: decided.reason }
242
+ })
243
+ })
244
+ )
245
+ })
254
246
 
255
- const open = (yield* openChangeRequests('bots', { authors })).changeRequests
247
+ const toBatch = (updates: readonly Update[], { decisions }: Assessed) =>
248
+ updates.filter(({ number }) => decisions.some(entry => entry.number === number && entry.decision === 'batch'))
256
249
 
257
- if (open.length === 0)
258
- return {
259
- status: 'nothing_to_sweep',
260
- summary: 'The bots have nothing open.',
261
- landed: [],
262
- left: []
263
- } satisfies Output
250
+ const notBatched = (updates: readonly Update[], { decisions }: Assessed): readonly Placed[] =>
251
+ updates.flatMap(({ number, title, url }) => {
252
+ const decided = decisions.find(entry => entry.number === number)
264
253
 
265
- const assessed = yield* agentWork('assess', { agent: 'assessor', prompt: assessPrompt(open), output: Assessed })
254
+ return decided === undefined || decided.decision === 'batch' ? [] : [{ number, title, url, reason: decided.reason }]
255
+ })
266
256
 
267
- const decisions = open.map(request => {
268
- const decided = assessed.updates.find(update => update.number === request.number)
269
- const placed = { number: request.number, title: request.title, url: request.url }
257
+ export class Mended extends Schema.TaggedClass<Mended>()('Mended', {
258
+ batch: Batch,
259
+ /** Less what its checks printed, which its verify Step's entry holds. */
260
+ head: VerifyResult
261
+ }) {}
262
+
263
+ /** One round of fixing what the batch breaks, or dropping the update that breaks it, and verifying again. */
264
+ export const mended = step('mended', {
265
+ payload: { applied: Schema.Array(Schema.String), failing: Schema.Array(FailedCheck) },
266
+ success: Mended,
267
+ run: ({ applied, failing }) =>
268
+ Effect.gen(function* () {
269
+ const batch = yield* implementer('fix', { prompt: fixPrompt(failing, applied), output: Batch })
270
+ const head = yield* verify('verify', {})
270
271
 
271
- if (decided === undefined) return { ...placed, decision: 'hold', reason: 'It was not assessed' } as const
272
+ return new Mended({ batch, head: withoutOutput(head) })
273
+ })
274
+ })
272
275
 
273
- if (decided.major && decided.decision === 'batch')
274
- return { ...placed, decision: 'alone', reason: `A major version bump goes alone. ${decided.reason}` } as const
276
+ export class Verified extends Schema.TaggedClass<Verified>()('Verified', {
277
+ summary: Schema.String,
278
+ landing: Schema.Array(Landing),
279
+ /** Batched, but closed meanwhile or dropped out. */
280
+ left: Schema.Array(Placed),
281
+ /** Less what its checks printed, which its verify Step's entry holds. */
282
+ head: VerifyResult
283
+ }) {}
284
+
285
+ /** Nothing could be batched, or the batch did not pass. */
286
+ export class NothingLeft extends Schema.TaggedClass<NothingLeft>()('NothingLeft', {
287
+ reason: Schema.String,
288
+ /** What was batched, each with why it does not land. */
289
+ left: Schema.Array(Placed)
290
+ }) {}
291
+
292
+ /** Brings the batch onto the branch from the bots' heads as they are now, verifies it and fixes what it breaks. */
293
+ export const batched = step('batched', {
294
+ payload: {
295
+ batch: Schema.Array(Update),
296
+ authors: Schema.NonEmptyArray(Schema.String),
297
+ target: Schema.optional(Schema.String).annotate({
298
+ description: 'The branch the batch targets; the default branch when left out.'
299
+ }),
300
+ maxFixRounds: Schema.Int.annotate({ description: 'Rounds of fixing what the batch breaks.' })
301
+ },
302
+ success: Schema.Union([Verified, NothingLeft]),
303
+ run: ({ batch, authors, target = 'the default branch', maxFixRounds }) =>
304
+ Effect.gen(function* () {
305
+ if (batch.length === 0) return new NothingLeft({ reason: 'Nothing is safe to batch.', left: [] })
275
306
 
276
- return { ...placed, decision: decided.decision, reason: decided.reason }
277
- })
307
+ // The bots rebase on their own schedule: build from their heads as they are now, not as assessed.
308
+ const now = (yield* openChangeRequests('bots', { authors })).changeRequests.map(updateOf)
309
+ const open = now.filter(update => batch.some(({ number }) => number === update.number))
278
310
 
279
- const notBatched: Placed[] = decisions.flatMap(({ decision, ...placed }) =>
280
- decision === 'batch' ? [] : [placed]
311
+ const gone = batch.flatMap(({ number, title, url }) =>
312
+ open.some(update => update.number === number)
313
+ ? []
314
+ : [{ number, title, url, reason: 'It was closed or merged while Sweep ran' }]
281
315
  )
282
316
 
283
- const batch = decisions.filter(update => update.decision === 'batch')
317
+ let onBranch = yield* implementer('batch', { prompt: batchPrompt(open, target), output: Batch })
318
+ let head = withoutOutput(yield* verify('verify', {}))
319
+ const dropped = new Map(onBranch.dropped.map(drop => [drop.number, drop.reason]))
284
320
 
285
- const reported = (status: 'reported', summary: string, left: readonly Placed[]) =>
286
- Effect.map(
287
- artifact('report', { kind: 'sweep_report', title: 'Sweep', text: reportText([], left, summary) }),
288
- stored => ({ status, summary, landed: [], left, reportArtifactId: stored.artifactId }) satisfies Output
289
- )
321
+ for (let round = 1; !head.passed && round <= maxFixRounds && onBranch.applied.length > 0; round++) {
322
+ const fixed = yield* mended({
323
+ applied: onBranch.applied,
324
+ failing: failedChecks(head).map(({ name, command }) => ({ name, command }))
325
+ })
290
326
 
291
- if (batch.length === 0) return yield* reported('reported', 'Nothing is safe to batch.', notBatched)
327
+ onBranch = fixed.batch
328
+ head = fixed.head
292
329
 
293
- // The bots rebase on their own schedule: build from their heads as they are now, not as assessed.
294
- const now = (yield* openChangeRequests('bots:again', { authors })).changeRequests
295
- const toBatch = now.filter(request => batch.some(update => update.number === request.number))
330
+ for (const drop of onBranch.dropped) dropped.set(drop.number, drop.reason)
331
+ }
296
332
 
297
- const gone: Placed[] = batch.flatMap(update =>
298
- toBatch.some(request => request.number === update.number)
299
- ? []
300
- : [
301
- {
302
- number: update.number,
303
- title: update.title,
304
- url: update.url,
305
- reason: 'It was closed or merged while Sweep ran'
306
- }
307
- ]
333
+ const droppedOut = open.flatMap(({ number, title, url }) => {
334
+ const reason =
335
+ dropped.get(number) ?? (onBranch.applied.includes(number) ? undefined : 'It was not brought onto the branch')
336
+
337
+ return reason === undefined ? [] : [{ number, title, url, reason }]
338
+ })
339
+
340
+ const left = [...gone, ...droppedOut]
341
+
342
+ const landing = onBranch.applied.flatMap(applied =>
343
+ open.flatMap(({ number, title, url, head }) => (number === applied ? [{ number, title, url, head }] : []))
308
344
  )
309
345
 
310
- const target = input.branch ?? 'the default branch'
346
+ if (landing.length === 0) return new NothingLeft({ reason: 'No update survived the batch.', left })
347
+
348
+ if (!head.passed)
349
+ return new NothingLeft({
350
+ reason: `The batch still fails ${failedChecks(head)
351
+ .map(check => check.name)
352
+ .join(', ')} after ${maxFixRounds} rounds of fixing.`,
353
+ left: [
354
+ ...left,
355
+ ...landing.map(({ head: _head, ...update }) => ({ ...update, reason: 'The batch did not pass' }))
356
+ ]
357
+ })
311
358
 
312
- let batched: Batched = yield* agentWork('batch', {
313
- agent: 'implementer',
314
- prompt: batchPrompt(toBatch, target),
315
- output: Batched
316
- })
359
+ return new Verified({ summary: onBranch.summary, landing, left, head })
360
+ })
361
+ })
317
362
 
318
- let checked = yield* verify('verify', {})
319
- const maxFixRounds = input.maxFixRounds ?? 2
320
- const dropped = new Map(batched.dropped.map(drop => [drop.number, drop.reason]))
363
+ export class Closed extends Schema.TaggedClass<Closed>()('Closed', {}) {}
364
+
365
+ /** The bot pushed `head` after it was batched, so it stays open: that head landed nowhere. */
366
+ export class Moved extends Schema.TaggedClass<Moved>()('Moved', { head: Schema.String }) {}
367
+
368
+ /** Closes one superseded ChangeRequest, at the head the batch landed. */
369
+ export const closed = step('closed', {
370
+ payload: { number: Schema.String, head: Schema.String, batchUrl: Schema.String },
371
+ key: ({ number }) => number,
372
+ success: Schema.Union([Closed, Moved]),
373
+ run: ({ number, head, batchUrl }) =>
374
+ Effect.map(
375
+ closeChangeRequest('close', {
376
+ number,
377
+ head,
378
+ note: `Landed in ${batchUrl} with the other dependency updates Sweep verified together.`
379
+ }),
380
+ result => (result.head === undefined ? new Closed() : new Moved({ head: result.head }))
381
+ )
382
+ })
321
383
 
322
- for (let round = 1; !checked.passed && round <= maxFixRounds && batched.applied.length > 0; round++) {
323
- batched = yield* agentWork(`fix:${round}`, {
324
- agent: 'implementer',
325
- prompt: fixPrompt(checked, batched.applied),
326
- output: Batched
384
+ export class Superseded extends Schema.TaggedClass<Superseded>()('Superseded', {
385
+ /** Left open, each at the head the bot pushed after it was batched. */
386
+ moved: Schema.Array(Schema.Struct({ number: Schema.String, head: Schema.String }))
387
+ }) {}
388
+
389
+ /** Closes the ChangeRequests a merged batch landed, each with a note pointing at the batch. */
390
+ export const superseded = step('superseded', {
391
+ payload: {
392
+ landing: Schema.Array(Schema.Struct({ number: Schema.String, head: Schema.String })),
393
+ batchUrl: Schema.String
394
+ },
395
+ success: Superseded,
396
+ run: ({ landing, batchUrl }) =>
397
+ Effect.map(
398
+ Effect.forEach(landing, ({ number, head }, index) =>
399
+ Effect.gen(function* () {
400
+ // A second visit of a keyed Step would close it again; a number listed twice is a duplicate Step.
401
+ if (landing.findIndex(entry => entry.number === number) < index)
402
+ return yield* new DuplicateStep({ step: yield* stepName(`closed[${number}]`) })
403
+
404
+ const ended = yield* closed({ number, head, batchUrl })
405
+
406
+ return ended._tag === 'Closed' ? [] : [{ number, head: ended.head }]
327
407
  })
408
+ ),
409
+ moved => new Superseded({ moved: moved.flat() })
410
+ )
411
+ })
328
412
 
329
- for (const drop of batched.dropped) dropped.set(drop.number, drop.reason)
330
- checked = yield* verify(`verify:${round}`, {})
331
- }
413
+ const updatesTitle = (count: number) => `Update ${count} ${count === 1 ? 'dependency' : 'dependencies'}`
414
+
415
+ /** The batch's ChangeRequest. Sweep works for no Task, so nothing is written back. */
416
+ const batchRequest = ({ summary, landing, head }: Verified, left: readonly Placed[]) => {
417
+ const notVerified = notVerifiedSection(head)
418
+
419
+ return {
420
+ title: updatesTitle(landing.length),
421
+ body: [
422
+ summary,
423
+ ...(notVerified === undefined ? [] : [notVerified]),
424
+ supersedes,
425
+ ...landing.map(supersededLine),
426
+ ...(left.length === 0
427
+ ? []
428
+ : ['Left for a person:', ...left.map(update => `- !${update.number} ${update.title}: ${update.reason}`)])
429
+ ].join('\n\n'),
430
+ writeBack: false
431
+ }
432
+ }
332
433
 
333
- const titled = (number: string) => toBatch.find(request => request.number === number)
434
+ /** Tests the batch made verify skip are for a person to run before it lands. */
435
+ const landingOf = (changeRequestId: string, notRun: readonly string[], branch: string | undefined) => ({
436
+ changeRequestId,
437
+ merge: notRun.length === 0,
438
+ ...(notRun.length === 0 ? undefined : { notRun }),
439
+ ...(branch === undefined ? undefined : { branch })
440
+ })
334
441
 
335
- const droppedOut: Placed[] = toBatch.flatMap(request => {
336
- const reason =
337
- dropped.get(request.number) ??
338
- (batched.applied.includes(request.number) ? undefined : 'It was not brought onto the branch')
442
+ type Placing = Pick<Output, 'landed' | 'left'>
339
443
 
340
- return reason === undefined ? [] : [{ number: request.number, title: request.title, url: request.url, reason }]
444
+ const placing = (landing: readonly Landing[], left: readonly Placed[], moved: Superseded['moved'] = []): Placing => {
445
+ const movedTo = new Map(moved.map(({ number, head }) => [number, head]))
446
+
447
+ return {
448
+ landed: landing.flatMap(({ number, title, url }) =>
449
+ movedTo.has(number) ? [] : [{ number, title, url, reason: 'Verified in the batch' }]
450
+ ),
451
+ left: [
452
+ ...left,
453
+ ...landing.flatMap(({ number, title, url, head }) => {
454
+ const pushed = movedTo.get(number)
455
+ const reason = `The bot pushed ${pushed} after Sweep batched ${head}, so it stays open`
456
+
457
+ return pushed === undefined ? [] : [{ number, title, url, reason }]
341
458
  })
459
+ ]
460
+ }
461
+ }
342
462
 
343
- const left = [...notBatched, ...gone, ...droppedOut]
463
+ type Landed = { readonly status: string; readonly reason: string }
344
464
 
345
- const landing: Landing[] = batched.applied.flatMap(number => {
346
- const request = titled(number)
465
+ const heldSummary = ({ url }: ChangeRequestResult, held: string) =>
466
+ `${url}, from an earlier Sweep, is still open, and another Run works its branch, so Sweep left it to that Run: ${held}`
347
467
 
348
- return request === undefined
349
- ? []
350
- : [{ number, title: request.title, url: request.url, head: request.head, reason: 'Verified in the batch' }]
351
- })
468
+ const takenOnSummary = ({ url }: ChangeRequestResult, landed: Landed) =>
469
+ `${url}, from an earlier Sweep, is still open; Sweep took it on instead of batching again: ${landed.status}. ${landed.reason}`
470
+
471
+ const landedSummary = ({ url }: ChangeRequestResult, { landed }: Placing) => `Landed ${landed.length} in ${url}`
472
+
473
+ const openSummary = ({ url }: ChangeRequestResult, landed: Landed) => `${url} is ${landed.status}: ${landed.reason}`
352
474
 
353
- if (landing.length === 0) return yield* reported('reported', 'No update survived the batch.', left)
475
+ const batchHeading = ({ url }: ChangeRequestResult, landed: Landed) => `${url}: ${landed.status}. ${landed.reason}`
476
+
477
+ /** Stores the report, and gives the Output every end of a Sweep that has one shares. */
478
+ const ending = (
479
+ status: Output['status'],
480
+ summary: string,
481
+ { landed, left }: Placing,
482
+ more: { readonly changeRequest?: ChangeRequestResult; readonly heading?: string } = {}
483
+ ) =>
484
+ Effect.gen(function* () {
485
+ const stored = yield* artifact('report', {
486
+ kind: 'sweep_report',
487
+ title: 'Sweep',
488
+ text: reportText(landed, left, more.heading ?? summary)
489
+ })
354
490
 
355
- if (!checked.passed) {
356
- const failing = checked.checks.filter(check => check.status === 'failed').map(check => check.name)
491
+ return {
492
+ status,
493
+ summary,
494
+ landed,
495
+ left,
496
+ reportArtifactId: stored.artifactId,
497
+ ...(more.changeRequest === undefined ? undefined : { changeRequest: more.changeRequest })
498
+ } satisfies Output
499
+ })
357
500
 
358
- return yield* reported(
359
- 'reported',
360
- `The batch still fails ${failing.join(', ')} after ${maxFixRounds} rounds of fixing.`,
361
- [...left, ...landing.map(({ head: _head, ...update }) => ({ ...update, reason: 'The batch did not pass' }))]
501
+ /**
502
+ * Gathers the dependency bot's open ChangeRequests, lands the safe ones together, and leaves the rest explained. Each
503
+ * update is classified batch, alone or hold with a reason; a major version bump is never batched silently. The batch
504
+ * is built from the bots' heads read again just before, verified, and fixed for a bounded number of rounds; an update
505
+ * that still breaks drops out with its reason. One ChangeRequest names each update it supersedes and is shepherded to
506
+ * merge once approved; then the superseded ChangeRequests are closed with a note.
507
+ */
508
+ export default defineLoop({
509
+ id: 'sweep',
510
+ version: '2.0.0',
511
+ title: 'Sweep',
512
+ description: "Lands the dependency bot's safe updates together in one ChangeRequest and explains the rest.",
513
+ input: Input,
514
+ output: Output,
515
+ agents: { assessor: 'investigator', implementer: 'implementer' },
516
+ checkout: 'write',
517
+ schedule: { rule: { frequency: 'weekly', daysOfWeek: [1], hour: 6, minute: 0 }, timezone: 'UTC' },
518
+ capabilities: ['agent_work', 'verify', 'change_request', 'read_change_request', 'merge_change_request'],
519
+ calls: () => [shepherd],
520
+ run: input =>
521
+ Effect.gen(function* () {
522
+ const authors = input.authors ?? defaultAuthors
523
+ const found = yield* listed({ authors })
524
+
525
+ if (found._tag === 'NothingToSweep')
526
+ return {
527
+ status: 'nothing_to_sweep',
528
+ summary: 'The bots have nothing open.',
529
+ landed: [],
530
+ left: []
531
+ } satisfies Output
532
+
533
+ if (found._tag === 'LeftOpen') {
534
+ const { changeRequest, landing, notRun } = found
535
+
536
+ const landed = yield* call('land', shepherd, landingOf(changeRequest.id, notRun, input.branch)).pipe(
537
+ Effect.catchTag('StepFailed', refused =>
538
+ refused.code === 'task_branch_busy' ? Effect.succeed({ held: refused.reason }) : Effect.fail(refused)
539
+ )
362
540
  )
541
+
542
+ if ('held' in landed)
543
+ return {
544
+ status: 'opened',
545
+ summary: heldSummary(changeRequest, landed.held),
546
+ landed: [],
547
+ left: [],
548
+ changeRequest
549
+ } satisfies Output
550
+
551
+ const summary = takenOnSummary(changeRequest, landed)
552
+
553
+ if (landed.status !== 'merged') return yield* ending('opened', summary, placing(landing, []), { changeRequest })
554
+
555
+ const { moved } = yield* superseded({ landing, batchUrl: changeRequest.url })
556
+
557
+ return yield* ending('landed', summary, placing(landing, [], moved), { changeRequest })
363
558
  }
364
559
 
365
- const notVerified = notVerifiedSection(checked)
366
-
367
- const opened = yield* changeRequest('change-request', {
368
- title: `Update ${landing.length} ${landing.length === 1 ? 'dependency' : 'dependencies'}`,
369
- body: [
370
- batched.summary,
371
- ...(notVerified === undefined ? [] : [notVerified]),
372
- supersedes,
373
- ...landing.map(supersededLine),
374
- ...(left.length === 0
375
- ? []
376
- : ['Left for a person:', ...left.map(update => `- !${update.number} ${update.title}: ${update.reason}`)])
377
- ].join('\n\n')
378
- })
560
+ const { updates } = found
561
+ const assessment = yield* assessed({ updates })
562
+ const held = notBatched(updates, assessment)
379
563
 
380
- const landed = yield* call('land', shepherd, {
381
- changeRequestId: opened.id,
382
- // Tests the batch made verify skip are for a person to run before it lands.
383
- merge: notVerified === undefined,
384
- ...(notVerified === undefined ? undefined : { notRun: testsNotRunReasons(checked) }),
385
- ...(input.branch === undefined ? undefined : { branch: input.branch })
564
+ const made = yield* batched({
565
+ batch: toBatch(updates, assessment),
566
+ authors,
567
+ target: input.branch,
568
+ maxFixRounds: input.maxFixRounds ?? 2
386
569
  })
387
570
 
388
- const merged = landed.status === 'merged'
389
- const closed = afterClosing(landing, left, merged ? yield* closeSuperseded(landing, opened.url) : [])
571
+ const left = [...held, ...made.left]
390
572
 
391
- const stored = yield* artifact('report', {
392
- kind: 'sweep_report',
393
- title: 'Sweep',
394
- text: reportText(closed.landed, closed.left, `${opened.url}: ${landed.status}. ${landed.reason}`)
395
- })
573
+ if (made._tag === 'NothingLeft') return yield* ending('reported', made.reason, { landed: [], left })
396
574
 
397
- const settled = { ...closed, reportArtifactId: stored.artifactId, changeRequest: opened }
575
+ const { landing, head } = made
576
+ const { changeRequest } = yield* opened(batchRequest(made, left))
577
+ const landed = yield* call('land', shepherd, landingOf(changeRequest.id, testsNotRunReasons(head), input.branch))
578
+ const heading = batchHeading(changeRequest, landed)
398
579
 
399
- if (!merged)
400
- return {
401
- status: 'opened',
402
- summary: `${opened.url} is ${landed.status}: ${landed.reason}`,
403
- ...settled
404
- } satisfies Output
580
+ if (landed.status !== 'merged')
581
+ return yield* ending('opened', openSummary(changeRequest, landed), placing(landing, left), {
582
+ changeRequest,
583
+ heading
584
+ })
585
+
586
+ const { moved } = yield* superseded({ landing, batchUrl: changeRequest.url })
587
+ const placed = placing(landing, left, moved)
405
588
 
406
- return {
407
- status: 'landed',
408
- summary: `Landed ${closed.landed.length} in ${opened.url}`,
409
- ...settled
410
- } satisfies Output
589
+ return yield* ending('landed', landedSummary(changeRequest, placed), placed, { changeRequest, heading })
411
590
  })
412
591
  })