@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/shepherd.ts CHANGED
@@ -1,54 +1,72 @@
1
1
  import {
2
- agentWork,
3
2
  approveChangeRequest,
4
3
  ask,
5
4
  call,
6
5
  type CalledLoop,
7
6
  claim,
8
- type Claim,
7
+ ClaimResult,
8
+ Conflict,
9
9
  comment,
10
- Continuing,
11
10
  defineLoop,
11
+ EpicDelivery,
12
+ green,
13
+ isBlocking,
14
+ isUnansweredQuestion,
15
+ landed,
12
16
  letGo,
13
- mergeChangeRequest,
17
+ level,
18
+ liveBranches,
19
+ LoopEvent,
20
+ MergedFinding,
21
+ mergeTurnResource,
14
22
  note,
23
+ PipelineCanceled,
24
+ PipelineFailed,
15
25
  pipelineMoved,
26
+ PipelineNotRun,
27
+ PipelineStatus,
16
28
  pipelineStatus,
17
29
  ReleaseTrigger,
18
- ResolvedReleaseTrigger,
30
+ releasesOn,
19
31
  reportPipeline,
20
32
  rerunPipeline,
33
+ ResolvedDeliveryTarget,
34
+ ResolvedReleaseTrigger,
21
35
  reviewThreads,
22
- syncBase,
36
+ runContext,
37
+ step,
38
+ Unapproved,
23
39
  verify,
24
40
  waitFor,
25
- type EpicDelivery,
26
41
  writeBack,
27
- isBlocking,
28
- isUnansweredQuestion,
29
- type BaseSync,
30
- type MergedFinding,
31
- type PipelineStatus,
32
- type ReviewThreads
42
+ ChangeRequestClosed,
43
+ StepFailed,
44
+ WaitTimedOut,
45
+ type LoopServices,
46
+ type ReviewThreads,
47
+ type StepError
33
48
  } from '@kitman-sh/sdk/loop'
34
49
  import * as Effect from 'effect/Effect'
35
50
  import * as Schema from 'effect/Schema'
36
- import release, { approvalRef } from './release'
37
- import landEpic, { LandEpicInput, LandEpicOutput } from './land-epic'
51
+ import { implementer } from './agents'
52
+ import backport from './backport'
53
+ import { BackportInput, BackportOutput } from './backport-schemas'
54
+ import { approved } from './approved'
38
55
  import { DeliveryFields, epicOf, ownDeliveryTarget } from './delivery'
39
- import { verifyHead } from './change-request-body'
40
- import type { OutOfScopeFinding } from './out-of-scope'
41
- import type { ReviewedScope } from './reviewed-scope'
42
- import review, { ReviewInput, ReviewOutput } from './review'
43
- import { ShepherdOutput } from './shepherd-output'
56
+ import landEpic, { LandEpicInput, LandEpicOutput } from './land-epic'
57
+ import { OutOfScopeFinding } from './out-of-scope'
58
+ import release, { approvalRef } from './release'
59
+ import review from './review'
60
+ import { ReviewedScope } from './reviewed-scope'
61
+ import { BackportOffer, BackportStarted, HandBack, ShepherdOutput } from './shepherd-output'
44
62
  import { OneSentence } from './text-limits'
45
63
 
46
- /** Review, by its schemas: Build calls this Loop and Review calls Build, so Review's definition may not be ready yet. */
47
- const reviewLoop = () => ({ id: 'review', input: ReviewInput, output: ReviewOutput })
48
-
49
64
  /** Land epic, by its schemas: it calls this Loop, so its definition may not be ready yet. */
50
65
  const landEpicLoop = () => ({ id: 'land-epic', input: LandEpicInput, output: LandEpicOutput })
51
66
 
67
+ /** Backport, by its schemas: it calls this Loop, so its definition may not be ready yet. */
68
+ const backportLoop = () => ({ id: 'backport', input: BackportInput, output: BackportOutput })
69
+
52
70
  /** How often a merge into an epic branch calls Land epic while another Run works that branch, and how far apart. */
53
71
  const landingCalls = 6
54
72
 
@@ -81,28 +99,58 @@ type RoundKind = keyof typeof roundLimits
81
99
  const handBackAnswer = 'Hand back to Build'
82
100
 
83
101
  const Input = Schema.Struct({
84
- /** The open ChangeRequest to see through to merge; the Run works on its branch. */
85
- changeRequestId: Schema.String,
86
- taskId: Schema.optional(Schema.String),
87
- /** Merges once it is approved, green and mergeable, without asking. */
88
- merge: Schema.optional(Schema.Boolean),
89
- /** Why each test verify never ran is unverified, for the person asked whether to merge. */
90
- notRun: Schema.optional(Schema.Array(Schema.String)),
91
- /** The target branch, for merging it in on a conflict, when Kitman does not say the ChangeRequest's own. */
92
- branch: Schema.optional(Schema.String),
93
- /** The ChangeRequest's branch and target, as Kitman puts the Run on it. */
94
- continuing: Schema.optional(Continuing),
95
- /** Times it looks at the ChangeRequest before asking whether to go on; 20 when left out. */
96
- maxCycles: Schema.optional(Schema.Int),
97
- /** This Run's own release trigger, over its Project's, Team's and Workspace's; `merge` releases this merge, as for a hotfix. */
98
- releaseTrigger: Schema.optional(ReleaseTrigger),
99
- /** The release trigger the Run uses and the layer it came from; Kitman sets it when the Run starts. */
100
- releaseWhen: Schema.optional(ResolvedReleaseTrigger),
102
+ changeRequestId: Schema.String.annotate({
103
+ description: 'The open ChangeRequest to see through to merge; the Run works on its branch.'
104
+ }),
105
+ taskId: Schema.optional(Schema.String).annotate({
106
+ description: 'The Task the ChangeRequest delivers, whose release trigger and delivery target the Run uses.'
107
+ }),
108
+ merge: Schema.optional(Schema.Boolean).annotate({
109
+ description: 'Merges once it is approved, green and mergeable, without asking.'
110
+ }),
111
+ hold: Schema.optional(Schema.Boolean).annotate({
112
+ description:
113
+ 'Stops as ready once it is level with its target, green and approved, merging nothing and asking nothing about a merge; it catches up a ChangeRequest that is only behind.'
114
+ }),
115
+ level: Schema.optional(Schema.Boolean).annotate({
116
+ description:
117
+ 'Merges only a head level with its target, read again on its turn, catching up first even where the forge would merge it behind.'
118
+ }),
119
+ head: Schema.optional(Schema.String).annotate({
120
+ description:
121
+ 'The head approved to merge, as a Release approved it: Shepherd merges it, or a head its own catch-up pushed from it, and stops for a person at any other.'
122
+ }),
123
+ notRun: Schema.optional(Schema.Array(Schema.String)).annotate({
124
+ description: 'Why each test verify never ran is unverified, for the person asked whether to merge.'
125
+ }),
126
+ branch: Schema.optional(Schema.String).annotate({
127
+ description: "The target branch, for merging it in on a conflict, when Kitman does not say the ChangeRequest's own."
128
+ }),
129
+ maxCycles: Schema.optional(Schema.Int).annotate({
130
+ description: 'Times it looks at the ChangeRequest before asking whether to go on; 20 when left out.'
131
+ }),
132
+ releaseTrigger: Schema.optional(ReleaseTrigger).annotate({
133
+ description:
134
+ "This Run's own release trigger, over its Project's, Team's and Workspace's; `merge` releases this merge, as for a hotfix."
135
+ }),
136
+ backportTo: Schema.optional(Schema.Array(Schema.String)).annotate({
137
+ description:
138
+ 'Live branches each merge is backported to without asking, as a Team sets with an Input Default; every other live branch is only offered a Backport.'
139
+ }),
140
+ offersBackports: Schema.optional(Schema.Boolean).annotate({
141
+ description: "false offers and starts no Backport after the merge, as a Backport's own Shepherd does."
142
+ }),
101
143
  ...DeliveryFields
102
144
  })
103
145
 
104
146
  const layerWords = { run: 'this Run', project: 'its Project', team: 'its Team', workspace: 'the Workspace' } as const
105
147
 
148
+ const releaseWhenWords = {
149
+ milestone: 'when its Milestone is done',
150
+ project: 'when its Project is done',
151
+ manual: 'when a person, a Schedule or a Loop starts it'
152
+ } as const
153
+
106
154
  export { ShepherdOutput }
107
155
 
108
156
  const Output = ShepherdOutput
@@ -138,7 +186,9 @@ const failingJobs = (pipeline: PipelineStatus) =>
138
186
  pipeline.jobs.flatMap(job => (job.status === 'failed' ? [job.name] : []))
139
187
 
140
188
  /** The failing checks the head of the target branch fails too, and those it passes; any other is not known. */
141
- type OnTarget = { readonly failed: readonly string[]; readonly passed: readonly string[] }
189
+ const OnTarget = Schema.Struct({ failed: Schema.Array(Schema.String), passed: Schema.Array(Schema.String) })
190
+
191
+ type OnTarget = typeof OnTarget.Type
142
192
 
143
193
  const ciFixPrompt = (pipeline: PipelineStatus, target: string, onTarget: OnTarget) => {
144
194
  const unknown = failingJobs(pipeline).filter(
@@ -168,13 +218,6 @@ const ciFixPrompt = (pipeline: PipelineStatus, target: string, onTarget: OnTarge
168
218
  ].join('\n\n')
169
219
  }
170
220
 
171
- /** A claim's resource name for the turn to merge into `target`, on `repository` when the read named it. */
172
- const turnResource = (target: string, repository: string | undefined) =>
173
- `merge:${repository === undefined ? '' : `${repository}:`}${target}`
174
- .toLowerCase()
175
- .replace(/[^a-z0-9._:-]+/g, '-')
176
- .slice(0, 128)
177
-
178
221
  const threadLine = (thread: ReviewThreads['threads'][number]) =>
179
222
  [
180
223
  `### Thread ${thread.id}${thread.path === undefined ? '' : ` on ${thread.path}${thread.line === undefined ? '' : `:${thread.line}`}`}`,
@@ -196,27 +239,6 @@ const reviewFixPrompt = (reviewed: string, findings: readonly MergedFinding[]) =
196
239
  findingLines(findings)
197
240
  ].join('\n')
198
241
 
199
- type CatchUp = NonNullable<Extract<BaseSync, { readonly status: 'merged' }>['catchUp']>
200
-
201
- /**
202
- * What a catch-up merge leaves to approve: nothing new, so the approval carries; only the files it settled or changed
203
- * after the merge, to review; or a change to the branch's own diff elsewhere, which only a fresh approval covers.
204
- */
205
- const catchUpVerdict = (
206
- catchUp: CatchUp
207
- ):
208
- | { readonly kind: 'carry' }
209
- | { readonly kind: 'review'; readonly files: readonly string[] }
210
- | { readonly kind: 'changed'; readonly why: string } => {
211
- if (catchUp.truncated) return { kind: 'changed', why: 'it changed more files than the Runner compares' }
212
- const files = [...new Set([...catchUp.conflicted, ...catchUp.rewritten])]
213
- const elsewhere = catchUp.changed.filter(file => !files.includes(file))
214
-
215
- if (elsewhere.length > 0) return { kind: 'changed', why: `the branch's own diff changed in ${elsewhere.join(', ')}` }
216
-
217
- return files.length === 0 ? { kind: 'carry' } : { kind: 'review', files }
218
- }
219
-
220
242
  const repliesPrompt = (threads: ReviewThreads['threads']) =>
221
243
  [
222
244
  'Reviewers left these comments on the ChangeRequest. For each thread, apply what you agree with and give the reply to post on it: what you changed, or why you did not. A comment that asks a question gets an answer and no change.',
@@ -227,1494 +249,2277 @@ const repliesPrompt = (threads: ReviewThreads['threads']) =>
227
249
  /** A thread's key changes when someone adds to it, so a new comment on an answered thread is answered again. */
228
250
  const threadKey = (thread: ReviewThreads['threads'][number]) => `${thread.id}:${thread.comments.length}`
229
251
 
230
- /** A passing review of a head with tests verify never ran: Shepherd's own `review` Step, or another Run's it `reuses`. */
231
- type UnranReview = { readonly notRun: readonly string[] } & ({ readonly review: string } | { readonly reuses: string })
252
+ /** What a Run sees through, the same at every look. */
253
+ export const Charge = Schema.Struct({
254
+ changeRequestId: Schema.String,
255
+ /** The ChangeRequest's own target: an offer's `branch` may be the offering Run's branch, which is this one. */
256
+ target: Schema.String,
257
+ hold: Schema.Boolean,
258
+ merge: Schema.Boolean,
259
+ level: Schema.optionalKey(Schema.Boolean),
260
+ head: Schema.optionalKey(Schema.String),
261
+ taskId: Schema.optional(Schema.String),
262
+ notRun: Schema.optional(Schema.Array(Schema.String)),
263
+ maxCycles: Schema.Int,
264
+ releaseWhen: ResolvedReleaseTrigger,
265
+ deliversTo: Schema.optional(ResolvedDeliveryTarget)
266
+ })
232
267
 
233
- /**
234
- * Takes an open ChangeRequest to merge: it waits on its Events with no model time between them, fixes a pipeline the
235
- * branch broke (after ruling out a flake and a target branch that fails the same check, which it waits out), answers
236
- * each new review thread on the thread, merges the target branch in when it is behind, and merges once approved, green
237
- * and mergeable when told to or when a person says so. A branch the forge says conflicts, or is behind with a failing
238
- * pipeline, merges its target in before any pipeline is run or fixed; one that is only behind catches up when its merge
239
- * finds it behind, on its turn. One whose merge Shepherd cannot settle goes back to Build. It merges the
240
- * target in and merges only while it holds the target's turn, so ChangeRequests for one target land one at a time, in
241
- * order. A head with a passed Review of the whole change that any Run recorded, such as the Build that shipped it, is
242
- * approved with that Review instead of being reviewed again. A head nobody approved gets a review of what changed since the last approved head, and the head a catch-up
243
- * pushed gets its pipeline started and its review as soon as the forge shows it, not once its pipeline passes. It runs one ci-fix and two
244
- * head-fix rounds, each judged by the pipeline at the head the last fix pushed, then hands the ChangeRequest back to
245
- * Build, and stops as needs you, with why, instead of spinning. Left for a person to merge, it watches the target for up to
246
- * a week, runs the repository's checks that read the target again at the head each time the target moves, and catches
247
- * up when they fail, as when the target gained a migration the head's own does not build on. After merging it starts Release only when its release
248
- * trigger is `merge`; under a Milestone or Project trigger that completion starts Release instead. A Team can turn on
249
- * starting it when the forge fails the pipeline of a ChangeRequest that delivers a Task.
250
- */
251
- export default defineLoop({
252
- id: 'shepherd',
253
- version: '1.11.0',
254
- title: 'Shepherd',
255
- input: Input,
256
- output: Output,
257
- agents: { implementer: 'implementer' },
258
- checkout: 'write',
259
- when: [
260
- {
261
- event: 'change_request.pipeline',
262
- filter: { status: 'failed', source: 'forge', linked: true },
263
- input: { changeRequestId: 'changeRequestId', taskId: 'taskId' },
264
- optIn: true
265
- }
266
- ],
267
- capabilities: [
268
- 'agent_work',
269
- 'read_change_request',
270
- 'post_comment',
271
- 'merge_change_request',
272
- 'approve_change_request',
273
- 'call',
274
- 'write_back',
275
- 'ask',
276
- 'verify',
277
- 'claim'
278
- ],
279
- calls: (): readonly CalledLoop[] => [review, release, landEpic],
280
- offers: [{ id: 'build', title: 'Hand back to Build', loop: 'build', from: 'handBack' }],
281
- run: input => {
282
- const changeRequestId = input.changeRequestId
283
- // The ChangeRequest's own target: an offer's `branch` may be the offering Run's branch, which is this one.
284
- const target = input.continuing?.targetBranch ?? input.branch ?? 'HEAD'
285
- const answered = new Set<string>()
286
- const reranHeads = new Set<string>()
287
- const ranOnRunner = new Set<string>()
288
- /** Heads nobody approved whose approval was left to a person, so they are not asked about again. */
289
- const leftToPerson = new Set<string>()
290
- /** The last review of an unapproved head's open findings, for the review of the head that fixes them. */
291
- let headFindings: readonly MergedFinding[] = []
292
- /** The head that review read. */
293
- let headFindingsAt: string | undefined
294
- /** The last review's findings kept apart as out of scope, for the next review and a Build handed the ChangeRequest. */
295
- let outOfScopeFindings: readonly OutOfScopeFinding[] = []
296
- /** That review's scope judgement. */
297
- let headScope: ReviewedScope | undefined
298
- /** Each head a review passed but left unapproved, as verify never ran these of its tests. */
299
- const unranAt = new Map<string, UnranReview>()
300
- const rounds: Record<RoundKind, number> = { 'ci-fix': 0, 'head-fix': 0 }
301
- /** Rounds past the limit a person allowed. */
302
- const allowed: Record<RoundKind, number> = { 'ci-fix': 0, 'head-fix': 0 }
303
- let replies = 0
304
- let stalledAt: string | undefined
305
- let stalls = 0
306
-
307
- /** The files a catch-up merge settled or changed, still to review at the head it pushed or a later one. */
308
- let unreviewed:
309
- | {
310
- readonly files: readonly string[]
311
- readonly synced: string
312
- /** The base sync whose merged-from head's approval covers the rest of the change. */
313
- readonly sync: string
314
- /** The head that base sync merged from. */
315
- readonly from: string
316
- readonly earlier: readonly MergedFinding[]
317
- /** The head the review that found `earlier` read. */
318
- readonly reviewed?: string
319
- }
320
- | undefined
321
-
322
- /** The head the last catch-up pushed, to review as soon as the forge shows it rather than once its pipeline passes. */
323
- let reviewOnceShown: string | undefined
324
- /** The head the last catch-up pushed, whose pipeline runs before Shepherd catches up again. */
325
- let pipelineFirst: string | undefined
326
- /** Heads Shepherd's own review passed, approved or left to a person for tests verify never ran, or it reused a Review of. */
327
- const reviewedHeads = new Set<string>()
328
- /** Each passed Review another Run recorded that stood for a review of a head here. */
329
- const reused: { readonly review: string; readonly head: string }[] = []
330
- /** Heads it tried to approve with a Review another Run recorded, so a refusal is not asked again. */
331
- const reuseTried = new Set<string>()
332
- /** The id of the approval Shepherd's own review recorded, by the head it approved. */
333
- const approvalOf = new Map<string, string>()
334
-
335
- /** Why an approval of the head is still needed after a catch-up merge, for a person who is left to give it. */
336
- let notCarried: string | undefined
337
- // The last merge did not go in as the ChangeRequest is: its target moved on, or it conflicts.
338
- let behind = false
339
- /** The head a catch-up merge or a fix pushed, until the forge shows it, how many reads showed another, and who pushed it. */
340
- let pushed: { readonly head: string; stale: number; readonly by: string } | undefined
341
-
342
- /**
343
- * The head the last fix round started from, until a read shows another or the round is known to have pushed
344
- * nothing; whether the round says it left a change, and how many looks found no pipeline on its push.
345
- */
346
- let fixedFrom: { readonly head: string; readonly changed: boolean; looks: number } | undefined
347
-
348
- /**
349
- * Each head a sync pushed or a sync for the forge's conflict or needed rebase started from, with the target's head
350
- * it took in, where the forge gave it; a blocker the forge shows again at both means the sync could not settle it.
351
- */
352
- const syncedFor = new Set<string>()
353
- const syncedKey = (head: string, targetHead: string) => `${head}@${targetHead}`
354
- /** The heads a sync for the forge's blocker started from or pushed, judged by when the target's head is unknown. */
355
- const blockerSynced = new Set<string>()
356
- /** How often the forge's blocker has been looked at again at a head a sync settled it for. */
357
- const blockerRechecks = new Map<string, number>()
358
-
359
- /** How the last catch-up's base sync ended. */
360
- let lastSync: BaseSync['status'] | undefined
361
-
362
- /** The head the checks that read the target last ran at, and the target's head they read then. */
363
- let targetChecked: { readonly head: string; readonly targetHead: string } | undefined
364
-
365
- /** The target's turn: held from the sync before the merge until the merge, so one ChangeRequest merges at a time. */
366
- let turn: Claim | undefined
367
- let turns = 0
368
- let passes = 0
369
- let repository: string | undefined
370
-
371
- /**
372
- * The head whose failure the target branch shares, the target's head then, and whether anything merged into the
373
- * target since.
374
- */
375
- let redTarget: { readonly head: string; readonly targetHead: string | undefined; moved: boolean } | undefined
376
-
377
- const fixRounds = () => rounds['ci-fix'] + rounds['head-fix']
378
-
379
- const done = (status: Output['status'], reason: string): Output => ({
380
- status,
381
- reason,
382
- fixRounds: fixRounds(),
383
- replies,
384
- ...(reused.length === 0 ? undefined : { reused }),
385
- ...(input.releaseWhen === undefined ? undefined : { releaseWhen: input.releaseWhen }),
386
- ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo }),
387
- ...(status === 'needs_you' || status === 'handed_back' ? { unsettled: [reason] } : undefined)
388
- })
268
+ type Charge = typeof Charge.Type
389
269
 
390
- const releaseWhen = input.releaseWhen
391
- const epic = epicOf(input)
392
-
393
- /**
394
- * Calls Land epic once this merge is in the epic branch: it takes in the default branch, and opens the epic's
395
- * ChangeRequest once every sub-task is done. While another Run works the epic branch Kitman refuses it, so it calls
396
- * again once that Run can have ended: a landing that started before this merge saw this sub-task still open. One
397
- * that saw every sub-task done, as epic.ready starts when this merge closes the last, lands the epic itself.
398
- */
399
- const landEpicAfter = (landing: EpicDelivery) =>
400
- Effect.gen(function* () {
401
- for (let attempt = 1; ; attempt++) {
402
- const step = attempt === 1 ? 'land-epic' : `land-epic:${attempt}`
403
-
404
- const called = yield* call(step, landEpicLoop(), {
405
- taskId: landing.taskId,
406
- ...ownDeliveryTarget(input)
407
- }).pipe(
408
- Effect.map(landed => ({ status: landed.status, reason: landed.reason })),
409
- Effect.catchTags({
410
- ChildFailed: failed => Effect.succeed({ status: 'failed', reason: failed.reason }),
411
- StepFailed: refused => Effect.succeed({ status: landingStatus(refused.code), reason: refused.reason })
412
- })
413
- )
270
+ type Rounds = Record<RoundKind, number>
414
271
 
415
- if (called.status !== 'busy') return called
272
+ const noRounds: Rounds = { 'ci-fix': 0, 'head-fix': 0 }
416
273
 
417
- if (attempt === landingCalls) return { status: 'refused', reason: called.reason }
274
+ const withCount = (rounds: Rounds, kind: RoundKind, count: number): Rounds => ({ ...rounds, [kind]: count })
418
275
 
419
- yield* waitFor(`land-epic-busy:${attempt}`, {
420
- event: 'change_request.closed',
421
- filter: {
422
- merged: true,
423
- targetBranch: landing.branch,
424
- ...(repository === undefined ? undefined : { repository })
425
- },
426
- timeout: landingRetry
427
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
428
- }
429
- })
276
+ /** The files a catch-up merge settled or changed, still to review at the head it pushed or a later one. */
277
+ const Unreviewed = Schema.Struct({
278
+ files: Schema.Array(Schema.String),
279
+ synced: Schema.String,
280
+ /** The base sync whose merged-from head's approval covers the rest of the change. */
281
+ sync: Schema.String,
282
+ /** The head that base sync merged from, when the Runner said. */
283
+ from: Schema.optional(Schema.String),
284
+ earlier: Schema.Array(MergedFinding),
285
+ /** The head the review that found `earlier` read. */
286
+ reviewed: Schema.optional(Schema.String)
287
+ })
430
288
 
431
- const handBack = (
432
- reason: string,
433
- open: string,
434
- review?: {
435
- readonly reviewed: string
436
- readonly earlier: readonly MergedFinding[]
437
- readonly scope?: ReviewedScope
438
- }
439
- ): Output => ({
440
- ...done('handed_back', reason),
441
- handBack: {
442
- changeRequestId,
443
- words: `Shepherd handed ChangeRequest ${changeRequestId} back: ${reason}. Fix it forward on its branch:\n${open}`,
444
- ...(input.taskId === undefined ? undefined : { taskId: input.taskId }),
445
- // Build's target, over the offer's default of this Run's branch, which is the ChangeRequest's own.
446
- ...(target === 'HEAD' ? undefined : { branch: target }),
447
- ...review,
448
- ...(outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings })
449
- }
450
- })
289
+ type Unreviewed = typeof Unreviewed.Type
451
290
 
452
- /** Takes the target's turn, waiting for any Run ahead; why not, when it was left to another. */
453
- const takeTurn = () =>
454
- Effect.gen(function* () {
455
- if (turn !== undefined) return undefined
291
+ /** A passing review of a head with tests verify never ran: Shepherd's own `review` Step, or another Run's it `reuses`. */
292
+ const UnranReview = Schema.Struct({
293
+ head: Schema.String,
294
+ notRun: Schema.Array(Schema.String),
295
+ review: Schema.optional(Schema.String),
296
+ reuses: Schema.optional(Schema.String)
297
+ })
456
298
 
457
- return yield* claim(`turn:${++turns}`, { resource: turnResource(target, repository) }).pipe(
458
- Effect.map(granted => {
459
- turn = granted
299
+ /** The target's turn: held from the sync before the merge until the merge. */
300
+ const Turn = ClaimResult.members[0]
301
+
302
+ const FixedFrom = Schema.Struct({ head: Schema.String, changed: Schema.Boolean, looks: Schema.Int })
303
+
304
+ /** What Shepherd learned of the ChangeRequest so far, which each Step hands the next. */
305
+ export const Shepherding = Schema.Struct({
306
+ repository: Schema.optional(Schema.String),
307
+ answered: Schema.Array(Schema.String),
308
+ reranHeads: Schema.Array(Schema.String),
309
+ ranOnRunner: Schema.Array(Schema.String),
310
+ /** Heads nobody approved whose approval was left to a person, so they are not asked about again. */
311
+ leftToPerson: Schema.Array(Schema.String),
312
+ /** The last review of an unapproved head's open findings, for the review of the head that fixes them. */
313
+ headFindings: Schema.Array(MergedFinding),
314
+ /** The head that review read. */
315
+ headFindingsAt: Schema.optional(Schema.String),
316
+ /** That review's scope judgement. */
317
+ headScope: Schema.optional(ReviewedScope),
318
+ /** The last review's findings kept apart as out of scope, for the next review and a Build handed the ChangeRequest. */
319
+ outOfScopeFindings: Schema.Array(OutOfScopeFinding),
320
+ /** Each head a review passed but left unapproved, as verify never ran these of its tests. */
321
+ unranAt: Schema.Array(UnranReview),
322
+ replies: Schema.Int,
323
+ stalledAt: Schema.optional(Schema.String),
324
+ stalls: Schema.Int,
325
+ unreviewed: Schema.optional(Unreviewed),
326
+ /** The head the last catch-up pushed, to review as soon as the forge shows it rather than once its pipeline passes. */
327
+ reviewOnceShown: Schema.optional(Schema.String),
328
+ /** The head the last catch-up pushed, whose pipeline runs before Shepherd catches up again. */
329
+ pipelineFirst: Schema.optional(Schema.String),
330
+ /** Heads Shepherd's own review passed, approved or left to a person for tests verify never ran, or it reused a Review of. */
331
+ reviewedHeads: Schema.Array(Schema.String),
332
+ /** Each passed Review another Run recorded that stood for a review of a head here. */
333
+ reused: Schema.Array(Schema.Struct({ review: Schema.String, head: Schema.String })),
334
+ /** Heads it tried to approve with a Review another Run recorded, so a refusal is not asked again. */
335
+ reuseTried: Schema.Array(Schema.String),
336
+ /** The id of the approval Shepherd's own review recorded, by the head it approved. */
337
+ approvalOf: Schema.Array(Schema.Struct({ head: Schema.String, approval: Schema.String })),
338
+ /** Why an approval of the head is still needed after a catch-up merge, for a person who is left to give it. */
339
+ notCarried: Schema.optional(Schema.String),
340
+ /** The last merge did not go in as the ChangeRequest is: its target moved on, or it conflicts. */
341
+ behind: Schema.Boolean,
342
+ /** The head a catch-up merge or a fix pushed, until the forge shows it, how many reads showed another, and who pushed it. */
343
+ pushed: Schema.optional(Schema.Struct({ head: Schema.String, stale: Schema.Int, by: Schema.String })),
344
+ /**
345
+ * The head the last fix round started from, until a read shows another or the round is known to have pushed
346
+ * nothing; whether the round says it left a change, and how many looks found no pipeline on its push.
347
+ */
348
+ fixedFrom: Schema.optional(FixedFrom),
349
+ /**
350
+ * Each head a sync pushed or a sync for the forge's conflict or needed rebase started from, with the target's head
351
+ * it took in, where the forge gave it; a blocker the forge shows again at both means the sync could not settle it.
352
+ */
353
+ syncedFor: Schema.Array(Schema.String),
354
+ /** The heads a sync for the forge's blocker started from or pushed, judged by when the target's head is unknown. */
355
+ blockerSynced: Schema.Array(Schema.String),
356
+ /** How often the forge's blocker has been looked at again at a head a sync settled it for. */
357
+ blockerRechecks: Schema.Array(Schema.Struct({ head: Schema.String, rechecks: Schema.Int })),
358
+ /** How the last catch-up's base sync ended. */
359
+ lastSync: Schema.optional(Schema.Literals(['up_to_date', 'merged'])),
360
+ /** The head the checks that read the target last ran at, and the target's head they read then. */
361
+ targetChecked: Schema.optional(Schema.Struct({ head: Schema.String, targetHead: Schema.String })),
362
+ turn: Schema.optional(Turn),
363
+ /** Heads a catch-up pushed from the Charge's `head` or from another of these, each of which merges in its place. */
364
+ caughtUpFrom: Schema.optionalKey(Schema.Array(Schema.String)),
365
+ /**
366
+ * The head whose failure the target branch shares, the target's head then, and whether anything merged into the
367
+ * target since.
368
+ */
369
+ redTarget: Schema.optional(
370
+ Schema.Struct({ head: Schema.String, targetHead: Schema.optional(Schema.String), moved: Schema.Boolean })
371
+ )
372
+ })
460
373
 
461
- return undefined
462
- }),
463
- Effect.catchTag('StepFailed', error => Effect.succeed(error.reason))
464
- )
465
- })
374
+ type Shepherding = typeof Shepherding.Type
375
+
376
+ const unshepherded: Shepherding = {
377
+ answered: [],
378
+ reranHeads: [],
379
+ ranOnRunner: [],
380
+ leftToPerson: [],
381
+ headFindings: [],
382
+ outOfScopeFindings: [],
383
+ unranAt: [],
384
+ replies: 0,
385
+ stalls: 0,
386
+ reviewedHeads: [],
387
+ reused: [],
388
+ reuseTried: [],
389
+ approvalOf: [],
390
+ behind: false,
391
+ syncedFor: [],
392
+ blockerSynced: [],
393
+ blockerRechecks: []
394
+ }
466
395
 
467
- /** Gives the target's turn to the next Run waiting, before work that takes a while or once merged. */
468
- const passTurn = () =>
469
- Effect.gen(function* () {
470
- if (turn === undefined) return
471
- const held = turn
396
+ /** The look ends here, and the next starts from `at`, and from `read` when it read the pipeline already. */
397
+ export class Again extends Schema.TaggedClass<Again>()('Again', {
398
+ at: Shepherding,
399
+ read: Schema.optional(PipelineStatus)
400
+ }) {}
401
+
402
+ /** The look goes on from `at`. */
403
+ export class Onward extends Schema.TaggedClass<Onward>()('Onward', { at: Shepherding }) {}
404
+
405
+ /** The Run stops for a person, for `reason`; held, with the files a catch-up could not settle in `conflicts`. */
406
+ export class NeedsYou extends Schema.TaggedClass<NeedsYou>()('NeedsYou', {
407
+ at: Shepherding,
408
+ reason: Schema.String,
409
+ conflicts: Schema.optional(Schema.Array(Schema.String))
410
+ }) {}
411
+
412
+ /** The ChangeRequest is ready: held, or left for a person to merge. */
413
+ export class Ready extends Schema.TaggedClass<Ready>()('Ready', { at: Shepherding, reason: Schema.String }) {}
414
+
415
+ /** Someone else merged the ChangeRequest. */
416
+ export class MergedElsewhere extends Schema.TaggedClass<MergedElsewhere>()('MergedElsewhere', {
417
+ at: Shepherding,
418
+ reason: Schema.String
419
+ }) {}
420
+
421
+ /** The ChangeRequest goes back to Build with what still stands. */
422
+ export class HandedBack extends Schema.TaggedClass<HandedBack>()('HandedBack', {
423
+ at: Shepherding,
424
+ reason: Schema.String,
425
+ handBack: HandBack
426
+ }) {}
427
+
428
+ /** Each way the Run stops short of its own merge. */
429
+ const Ended = [NeedsYou, Ready, MergedElsewhere, HandedBack] as const
430
+
431
+ type Ended = NeedsYou | Ready | MergedElsewhere | HandedBack
432
+
433
+ /** It merged at `revision`, approved by `review` where Kitman knows the approval. */
434
+ export class Landed extends Schema.TaggedClass<Landed>()('Landed', {
435
+ at: Shepherding,
436
+ revision: Schema.String,
437
+ review: Schema.optional(Schema.String)
438
+ }) {}
439
+
440
+ /** What a round of fixes leaves standing: the hand-back's reason, without its rounds, and what is open. */
441
+ const Standing = Schema.Struct({
442
+ reason: Schema.String,
443
+ open: Schema.String,
444
+ review: Schema.optional(
445
+ Schema.Struct({
446
+ reviewed: Schema.String,
447
+ earlier: Schema.Array(MergedFinding),
448
+ scope: Schema.optional(ReviewedScope)
449
+ })
450
+ )
451
+ })
472
452
 
473
- turn = undefined
474
- yield* letGo(`pass-turn:${++passes}`, held)
475
- })
453
+ /** The pipeline at `pipeline`'s head fails on the branch's own account: a ci-fix round is due. */
454
+ export class CiFixDue extends Schema.TaggedClass<CiFixDue>()('CiFixDue', {
455
+ at: Shepherding,
456
+ pipeline: PipelineStatus,
457
+ onTarget: OnTarget,
458
+ handBack: Standing
459
+ }) {}
460
+
461
+ /** A review found what blocks `head`: a head-fix round fixes it, or the hand-back carries it to Build. */
462
+ export class Wanted extends Schema.TaggedClass<Wanted>()('Wanted', {
463
+ at: Shepherding,
464
+ head: Schema.String,
465
+ findings: Schema.Array(MergedFinding),
466
+ /** What the fix is asked to fix, as the prompt names it. */
467
+ subject: Schema.String,
468
+ /** The catch-up's files it reviewed, when it reviewed only those. */
469
+ files: Schema.optional(Unreviewed),
470
+ scope: Schema.optional(ReviewedScope),
471
+ handBack: Standing
472
+ }) {}
473
+
474
+ /** The review passed; `approved` when it approved the head. */
475
+ export class Passed extends Schema.TaggedClass<Passed>()('Passed', { at: Shepherding, approved: Schema.Boolean }) {}
476
+
477
+ /** The head's approval is left to a person. */
478
+ export class Left extends Schema.TaggedClass<Left>()('Left', { at: Shepherding }) {}
479
+
480
+ /** Another round may run, within `limit`, which a person may have raised by one. */
481
+ export class RoundTaken extends Schema.TaggedClass<RoundTaken>()('RoundTaken', { limit: Schema.Int }) {}
482
+
483
+ /** The rounds ran out, and nobody allowed another. */
484
+ export class RoundsSpent extends Schema.TaggedClass<RoundsSpent>()('RoundsSpent', {}) {}
485
+
486
+ /** The checks that read the target passed against it. */
487
+ export class TargetPassed extends Schema.TaggedClass<TargetPassed>()('TargetPassed', { at: Shepherding }) {}
488
+
489
+ /** A read of a red target showed the ChangeRequest or the target moved. */
490
+ export class TargetMoved extends Schema.TaggedClass<TargetMoved>()('TargetMoved', {}) {}
491
+
492
+ /** A wait for the target to move, and the Event that ended it, when one did. */
493
+ export class Waited extends Schema.TaggedClass<Waited>()('Waited', {
494
+ woke: Schema.optional(LoopEvent),
495
+ read: Schema.optional(PipelineStatus)
496
+ }) {}
497
+
498
+ const withAdded = (list: readonly string[], item: string) => (list.includes(item) ? list : [...list, item])
499
+
500
+ const approvalAt = (at: Shepherding, head: string) => at.approvalOf.find(entry => entry.head === head)?.approval
501
+
502
+ const unranOf = (at: Shepherding, head: string) => at.unranAt.find(entry => entry.head === head)
503
+
504
+ const done = (
505
+ charge: Charge,
506
+ at: Shepherding,
507
+ fixRounds: number,
508
+ status: Output['status'],
509
+ reason: string,
510
+ revision?: string
511
+ ): Output => ({
512
+ status,
513
+ reason,
514
+ fixRounds,
515
+ replies: at.replies,
516
+ ...(revision === undefined ? undefined : { revision }),
517
+ ...(at.reused.length === 0 ? undefined : { reused: at.reused }),
518
+ releaseWhen: charge.releaseWhen,
519
+ ...(charge.deliversTo === undefined ? undefined : { deliversTo: charge.deliversTo }),
520
+ ...(status === 'needs_you' || status === 'handed_back' ? { unsettled: [reason] } : undefined)
521
+ })
476
522
 
477
- /** Whether another round of `kind` may run: past its limit, only when a person says so. */
478
- const mayFix = (kind: RoundKind, cycle: number, open: string) =>
479
- Effect.gen(function* () {
480
- if (rounds[kind] < roundLimits[kind] + allowed[kind]) return true
523
+ /** The Output of a Run that stopped short of its own merge. */
524
+ const outputOf = (charge: Charge, end: Ended, fixRounds: number): Output =>
525
+ end._tag === 'HandedBack'
526
+ ? { ...done(charge, end.at, fixRounds, 'handed_back', end.reason), handBack: end.handBack }
527
+ : end._tag === 'Ready'
528
+ ? done(charge, end.at, fixRounds, 'ready', end.reason)
529
+ : end._tag === 'MergedElsewhere'
530
+ ? done(charge, end.at, fixRounds, 'merged', end.reason)
531
+ : {
532
+ ...done(charge, end.at, fixRounds, 'needs_you', end.reason),
533
+ ...(end.conflicts === undefined ? undefined : { conflicts: end.conflicts })
534
+ }
481
535
 
482
- const answer = yield* ask(`rounds:${cycle}`, {
483
- prompt: `Shepherd has run ${rounds[kind]} ${kind} rounds, its limit, and ${open} still stands. Hand the ChangeRequest back to Build?`,
484
- options: [
485
- {
486
- value: handBackAnswer,
487
- description: 'Stops here; the ChangeRequest stays open, with a Build offer that carries what is open.'
488
- },
489
- { value: 'One more round', description: `Runs one more ${kind} round here.` }
490
- ],
491
- recommended: handBackAnswer,
492
- recommendationReason:
493
- 'More rounds here have not settled it, and Build fixes and reviews the change as a whole.',
494
- default: handBackAnswer,
495
- // A full-auto Team stops the loop rather than going round again.
496
- auto: handBackAnswer,
497
- timeout: '1 hour'
498
- })
536
+ // Only a held Run, or one that merges only level, acts on `behind`, which costs forge calls.
537
+ const readsBehind = (charge: Charge) => (charge.hold || charge.level === true ? { behind: true as const } : undefined)
499
538
 
500
- if (answer !== handBackAnswer) allowed[kind]++
539
+ /** Whether `head` is the one the Charge approved to merge, or a catch-up of it. */
540
+ const approvedToMerge = (charge: Charge, at: Shepherding, head: string) =>
541
+ charge.head === undefined || charge.head === head || (at.caughtUpFrom ?? []).includes(head)
501
542
 
502
- return answer !== handBackAnswer
503
- })
543
+ /** What full auto relies on to take its answer: the approval of the ChangeRequest head, and `head`. */
544
+ const evidenceAt = (review: string | undefined, head: string) => ({
545
+ ...(review === undefined ? undefined : { review }),
546
+ head
547
+ })
504
548
 
505
- const reportSteps = { run: 'pipeline-report', rerun: 'pipeline-rereport', fix: 'pipeline-fix-report' } as const
506
-
507
- /**
508
- * Runs the repository's pipeline on a Runner at `head`, the Run's own head when left out, and reports it: the
509
- * revision it ran at, or the reason it could not run.
510
- */
511
- const runOnRunner = (
512
- step: keyof typeof reportSteps,
513
- cycle: number,
514
- head: string | undefined,
515
- checks: readonly string[]
516
- ) =>
517
- Effect.gen(function* () {
518
- const verification = `pipeline-${step}:${cycle}`
519
-
520
- const ran = yield* verify(verification, {
521
- ...(head === undefined ? undefined : { revision: head }),
522
- checks
523
- }).pipe(
524
- Effect.map(result => ({ revision: result.revision })),
525
- Effect.catchTag('StepFailed', error => Effect.succeed({ failed: error.reason }))
526
- )
549
+ const syncedKey = (head: string, targetHead: string) => `${head}@${targetHead}`
550
+
551
+ /** Takes the target's turn, waiting for any Run ahead, held until passed or the Run ends; why not, when refused. */
552
+ const takeTurn = (charge: Charge, at: Shepherding) =>
553
+ at.turn !== undefined
554
+ ? Effect.succeed({ at })
555
+ : claim('turn', {
556
+ resource: mergeTurnResource(at.repository, charge.target),
557
+ changeRequestId: charge.changeRequestId,
558
+ keep: 'run'
559
+ }).pipe(
560
+ Effect.map(granted => ({ at: { ...at, turn: granted } })),
561
+ Effect.catchTag('StepFailed', error => Effect.succeed({ refused: error.reason }))
562
+ )
563
+
564
+ /** Gives the target's turn to the next Run waiting, before work that takes a while or once merged. */
565
+ const passTurn = (at: Shepherding) =>
566
+ at.turn === undefined ? Effect.succeed(at) : Effect.as(letGo('pass-turn', at.turn), { ...at, turn: undefined })
567
+
568
+ /** Runs the pipeline at `pipeline`'s head on the Runner or waits for it once: the read after, or why it could not run. */
569
+ const lookOnce = (charge: Charge, pipeline: PipelineStatus) =>
570
+ green({ changeRequestId: charge.changeRequestId, read: pipeline, looks: 1, ...readsBehind(charge) }).pipe(
571
+ Effect.map(looked => ({ pipeline: looked.pipeline })),
572
+ Effect.catchTags({
573
+ PipelineFailed: failed => Effect.succeed({ pipeline: failed.pipeline }),
574
+ PipelineCanceled: canceled => Effect.succeed({ pipeline: canceled.pipeline }),
575
+ PipelineNotRun: notRun => Effect.succeed({ failed: notRun.reason })
576
+ })
577
+ )
527
578
 
528
- if ('revision' in ran) yield* reportPipeline(`${reportSteps[step]}:${cycle}`, { changeRequestId, verification })
579
+ /**
580
+ * Runs the repository's pipeline on a Runner at `head`, the Run's own head when left out, and reports it: the revision
581
+ * it ran at, or the reason it could not run.
582
+ */
583
+ const runOnRunner = (
584
+ changeRequestId: string,
585
+ kind: 'fix' | 'rerun',
586
+ head: string | undefined,
587
+ checks: readonly string[]
588
+ ) =>
589
+ Effect.gen(function* () {
590
+ const verification = kind === 'fix' ? 'pipeline-fix' : 'pipeline-rerun'
591
+
592
+ const ran = yield* verify(verification, {
593
+ ...(head === undefined ? undefined : { revision: head }),
594
+ checks
595
+ }).pipe(
596
+ Effect.map(result => ({ revision: result.revision })),
597
+ Effect.catchTag('StepFailed', error => Effect.succeed({ failed: error.reason }))
598
+ )
529
599
 
530
- return ran
600
+ if ('revision' in ran)
601
+ yield* reportPipeline(kind === 'fix' ? 'pipeline-fix-report' : 'pipeline-rereport', {
602
+ changeRequestId,
603
+ verification
531
604
  })
532
605
 
533
- /**
534
- * What the last fix round pushed from `pipeline`, the head it started from, which the forge can show for a while
535
- * after the push: on a Runner it runs the pipeline at the Run's own head, which is what the round pushed; otherwise
536
- * the head of the forge's next pipeline says, and a round that left a change but has no such pipeline yet is
537
- * `unknown`. The Output to stop with, when the pipeline cannot run.
538
- */
539
- const pushedByFix = (cycle: number, pipeline: PipelineStatus, changed: boolean) =>
540
- Effect.gen(function* () {
541
- if (pipeline.runnerChecks === undefined) {
542
- if (!changed) return 'nothing' as const
543
-
544
- const woke = yield* pipelineMoved(`fix-pushed:${cycle}`, changeRequestId, pipeline, '5 minutes').pipe(
545
- Effect.catchTag('WaitTimedOut', () => Effect.undefined)
546
- )
547
-
548
- const head = woke?.payload.head
549
-
550
- if (!Schema.is(Schema.String)(head) || head === pipeline.head) return 'unknown' as const
551
- pushed = { head, stale: 0, by: 'the fix' }
606
+ return ran
607
+ })
608
+
609
+ /** The wait for a merge into the target, or for this ChangeRequest to close, since `since`. */
610
+ const mergedInto = (charge: Charge, repository: string | undefined, since: string | undefined) => ({
611
+ event: 'change_request.closed',
612
+ filter: {
613
+ merged: true,
614
+ ...(charge.target === 'HEAD' ? undefined : { targetBranch: charge.target }),
615
+ ...(repository === undefined ? undefined : { repository })
616
+ },
617
+ or: [{ event: 'change_request.closed', filter: { changeRequestId: charge.changeRequestId } }],
618
+ ...(since === undefined ? undefined : { since })
619
+ })
552
620
 
553
- return 'pushed' as const
621
+ /** How a wait for the target ended this ChangeRequest, when the Event that woke it closed this one. */
622
+ const closedBy = (charge: Charge, at: Shepherding, woke: LoopEvent | undefined, mergedBy: string) =>
623
+ woke?.payload.changeRequestId !== charge.changeRequestId
624
+ ? undefined
625
+ : woke.payload.merged === true
626
+ ? new MergedElsewhere({ at, reason: `${mergedBy} merged the ChangeRequest` })
627
+ : new NeedsYou({ at, reason: 'The ChangeRequest was closed' })
628
+
629
+ /** Stops the Run with what still stands, for Build to fix forward: the hand-back. */
630
+ export const handedBack = step('handedBack', {
631
+ payload: { charge: Charge, at: Shepherding, ...Standing.fields },
632
+ success: HandedBack,
633
+ run: ({ charge, at, reason, open, review: reviewed }) =>
634
+ Effect.succeed(
635
+ new HandedBack({
636
+ at,
637
+ reason,
638
+ handBack: {
639
+ changeRequestId: charge.changeRequestId,
640
+ words: `Shepherd handed ChangeRequest ${charge.changeRequestId} back: ${reason}. Fix it forward on its branch:\n${open}`,
641
+ ...(charge.taskId === undefined ? undefined : { taskId: charge.taskId }),
642
+ // Build's target, over the offer's default of this Run's branch, which is the ChangeRequest's own.
643
+ ...(charge.target === 'HEAD' ? undefined : { branch: charge.target }),
644
+ ...reviewed,
645
+ ...(at.outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings: at.outOfScopeFindings })
554
646
  }
647
+ })
648
+ )
649
+ })
555
650
 
556
- const ran = yield* runOnRunner('fix', cycle, undefined, pipeline.runnerChecks)
651
+ /**
652
+ * Ends a look, or a round, that failed past what its Steps settle, with what it knew when the failing Step began: a
653
+ * Question nobody answers in full auto hands the ChangeRequest back, and a budget, a wait or a closed ChangeRequest
654
+ * stops the Run.
655
+ */
656
+ const endedOn =
657
+ (charge: Charge, at: Shepherding) =>
658
+ <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A | Ended, E | StepError, R | LoopServices> =>
659
+ effect.pipe(
660
+ Effect.catch((error): Effect.Effect<Ended, E | StepError, LoopServices> => {
661
+ // An unanswered Question's reason carries the agent's own words, which may mention a time budget.
662
+ if (error instanceof StepFailed && isUnansweredQuestion(error.reason))
663
+ return handedBack({
664
+ charge,
665
+ at,
666
+ reason: `Step "${error.step}" stopped on a Question nobody answers in full auto`,
667
+ open: error.reason
668
+ })
557
669
 
558
- if ('failed' in ran) return done('needs_you', `The pipeline could not run on the Runner: ${ran.failed}`)
670
+ if (error instanceof StepFailed && error.reason.includes('time budget'))
671
+ return Effect.succeed(new NeedsYou({ at, reason: `Step "${error.step}" ran past its ${stepBudget} budget` }))
672
+
673
+ if (error instanceof WaitTimedOut)
674
+ return Effect.succeed(
675
+ new NeedsYou({
676
+ at,
677
+ reason:
678
+ error.event === 'change_request.approval' && at.notCarried !== undefined
679
+ ? `Nobody approved the head after ${at.notCarried}`
680
+ : `Nothing happened on the ChangeRequest while waiting for ${error.event}`
681
+ })
682
+ )
559
683
 
560
- if (ran.revision === pipeline.head) return 'nothing' as const
561
- ranOnRunner.add(ran.revision)
562
- pushed = { head: ran.revision, stale: 0, by: 'the fix' }
684
+ if (error instanceof ChangeRequestClosed)
685
+ return Effect.succeed(
686
+ error.merged
687
+ ? new MergedElsewhere({ at, reason: 'Someone else merged the ChangeRequest' })
688
+ : new NeedsYou({ at, reason: 'The ChangeRequest was closed' })
689
+ )
563
690
 
564
- return 'pushed' as const
691
+ return Effect.fail(error)
565
692
  })
693
+ )
566
694
 
567
- /**
568
- * How the head of the target branch does on the failing checks: the forge's own checks on it, and the rest of the
569
- * repository's Runner checks run there on a Runner.
570
- */
571
- const checkTarget = (cycle: number, pipeline: PipelineStatus) =>
572
- Effect.gen(function* () {
573
- const failing = failingJobs(pipeline)
574
- const onForge = (pipeline.target?.jobs ?? []).filter(job => failing.includes(job.name))
575
- const failed = onForge.flatMap(job => (job.status === 'failed' ? [job.name] : []))
576
- const passed = onForge.flatMap(job => (job.status === 'success' ? [job.name] : []))
577
-
578
- const onRunner = failing.filter(
579
- name => !failed.includes(name) && !passed.includes(name) && (pipeline.runnerChecks ?? []).includes(name)
580
- )
695
+ /** Whether another round of `kind` may run, `taken` of them having run: past `limit`, only when a person says so. */
696
+ export const roundAllowed = step('roundAllowed', {
697
+ payload: {
698
+ kind: Schema.Literals(['ci-fix', 'head-fix']),
699
+ taken: Schema.Int,
700
+ limit: Schema.Int,
701
+ /** What still stands, as the Question names it. */
702
+ standing: Schema.String
703
+ },
704
+ success: Schema.Union([RoundTaken, RoundsSpent]),
705
+ run: ({ kind, taken, limit, standing }) =>
706
+ Effect.gen(function* () {
707
+ if (taken < limit) return new RoundTaken({ limit })
708
+
709
+ const answer = yield* ask('rounds', {
710
+ prompt: `Shepherd has run ${taken} ${kind} rounds, its limit, and ${standing} still stands. Hand the ChangeRequest back to Build?`,
711
+ options: [
712
+ {
713
+ value: handBackAnswer,
714
+ description: 'Stops here; the ChangeRequest stays open, with a Build offer that carries what is open.'
715
+ },
716
+ { value: 'One more round', description: `Runs one more ${kind} round here.` }
717
+ ],
718
+ recommended: handBackAnswer,
719
+ recommendationReason:
720
+ 'More rounds here have not settled it, and Build fixes and reviews the change as a whole.',
721
+ default: handBackAnswer,
722
+ // A full-auto Team stops the loop rather than going round again.
723
+ auto: handBackAnswer,
724
+ timeout: '1 hour'
725
+ })
581
726
 
582
- if (onRunner.length === 0) return { failed, passed }
727
+ return answer === handBackAnswer ? new RoundsSpent() : new RoundTaken({ limit: limit + 1 })
728
+ })
729
+ })
583
730
 
584
- const atTarget = yield* verify(`target-check:${cycle}`, {
585
- revision: `origin/${target}`,
586
- checks: onRunner
587
- }).pipe(Effect.catchTag('StepFailed', () => Effect.undefined))
731
+ /**
732
+ * What the last fix round pushed from `pipeline`, the head it started from, which the forge can show for a while after
733
+ * the push: on a Runner it runs the pipeline at the Run's own head, which is what the round pushed; otherwise the head
734
+ * of the forge's next pipeline says. A round that left a change but has no such pipeline yet is looked at again, three
735
+ * times at most.
736
+ */
737
+ export const pushSeen = step('pushSeen', {
738
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, fixedFrom: FixedFrom },
739
+ success: Schema.Union([Again, Onward, ...Ended]),
740
+ run: ({ charge, at, pipeline, fixedFrom }) =>
741
+ Effect.gen(function* () {
742
+ const nothing = new Onward({ at: { ...at, fixedFrom: undefined } })
588
743
 
589
- const ran = atTarget?.checks.filter(check => onRunner.includes(check.name)) ?? []
744
+ if (pipeline.runnerChecks === undefined) {
745
+ if (!fixedFrom.changed) return nothing
590
746
 
591
- return {
592
- failed: [...failed, ...ran.flatMap(check => (check.status === 'failed' ? [check.name] : []))],
593
- passed: [...passed, ...ran.flatMap(check => (check.status === 'passed' ? [check.name] : []))]
594
- }
595
- })
747
+ const woke = yield* pipelineMoved('fix-pushed', charge.changeRequestId, pipeline, '5 minutes').pipe(
748
+ Effect.catchTag('WaitTimedOut', () => Effect.undefined)
749
+ )
596
750
 
597
- /** Records why it waits rather than fixing, then waits for something to merge into the target. */
598
- const waitOutTarget = (cycle: number, pipeline: PipelineStatus, why: string) =>
599
- Effect.gen(function* () {
600
- yield* passTurn()
601
- yield* note(`target-red:${cycle}`, {
602
- text: `Shepherd is waiting for ${target} to change instead of fixing ${pipeline.head}: ${why}`
603
- }).pipe(Effect.catchTag('StepFailed', () => Effect.void))
751
+ const head = woke?.payload.head
604
752
 
605
- // Only a read that names the target's head can tell a push straight to it, which makes no Event.
606
- const targetHead = pipeline.target?.head
753
+ if (Schema.is(Schema.String)(head) && head !== pipeline.head)
754
+ return new Again({ at: { ...at, pushed: { head, stale: 0, by: 'the fix' } } })
607
755
 
608
- const mergedInto = {
609
- event: 'change_request.closed',
610
- filter: {
611
- merged: true,
612
- ...(target === 'HEAD' ? undefined : { targetBranch: target }),
613
- ...(repository === undefined ? undefined : { repository })
614
- },
615
- or: [{ event: 'change_request.closed', filter: { changeRequestId } }],
616
- timeout: targetHead === undefined ? ('1 hour' as const) : pipelineRun,
617
- ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
618
- }
756
+ const looks = fixedFrom.looks + 1
619
757
 
620
- let woke = yield* waitFor(`target-moved:${cycle}`, mergedInto).pipe(
621
- Effect.catchTag('WaitTimedOut', () => Effect.undefined)
622
- )
758
+ if (looks < 3) return new Again({ at: { ...at, fixedFrom: { ...fixedFrom, looks } } })
623
759
 
624
- // Reading again each pipeline run is part of this one look, so it costs no look of its own.
625
- for (let look = 2; woke === undefined && targetHead !== undefined && look <= targetLooks; look++) {
626
- const again = yield* pipelineStatus(`target-read:${cycle}:${look}`, { changeRequestId })
760
+ return new NeedsYou({
761
+ at,
762
+ reason: `The fix from ${fixedFrom.head} left a change, but the forge showed no pipeline on a new head after three looks`
763
+ })
764
+ }
627
765
 
628
- if (again.head !== pipeline.head || again.target?.head !== targetHead) break
766
+ const ran = yield* runOnRunner(charge.changeRequestId, 'fix', undefined, pipeline.runnerChecks)
629
767
 
630
- woke = yield* waitFor(`target-moved:${cycle}:${look}`, mergedInto).pipe(
631
- Effect.catchTag('WaitTimedOut', () => Effect.undefined)
632
- )
633
- }
768
+ if ('failed' in ran)
769
+ return new NeedsYou({ at, reason: `The pipeline could not run on the Runner: ${ran.failed}` })
634
770
 
635
- if (woke?.payload.changeRequestId === changeRequestId)
636
- return woke.payload.merged === true
637
- ? done('merged', 'Someone else merged the ChangeRequest')
638
- : done('needs_you', 'The ChangeRequest was closed')
771
+ if (ran.revision === pipeline.head) return nothing
639
772
 
640
- redTarget = { head: pipeline.head, targetHead, moved: woke !== undefined }
773
+ return new Again({
774
+ at: {
775
+ ...at,
776
+ ranOnRunner: withAdded(at.ranOnRunner, ran.revision),
777
+ pushed: { head: ran.revision, stale: 0, by: 'the fix' }
778
+ }
779
+ })
780
+ })
781
+ })
782
+
783
+ /**
784
+ * Approves the head of `pipeline` with the passed Review of the whole change at it that another Run recorded, such as
785
+ * the Build that shipped it, rather than reviewing it again; later heads are reviewed only since it. Like its own review,
786
+ * it leaves a head with tests verify never ran unapproved until a person chooses to merge it. `Again` once it stands for
787
+ * the head's review, so the next read shows its approval.
788
+ */
789
+ export const reviewReused = step('reviewReused', {
790
+ payload: {
791
+ charge: Charge,
792
+ at: Shepherding,
793
+ pipeline: PipelineStatus,
794
+ reviewed: Schema.Struct({ review: Schema.String, notRun: Schema.optional(Schema.Array(Schema.String)) })
795
+ },
796
+ success: Schema.Union([Again, Onward]),
797
+ run: ({ charge, at: before, pipeline, reviewed }) =>
798
+ Effect.gen(function* () {
799
+ const { head } = pipeline
800
+ const at = { ...before, reuseTried: withAdded(before.reuseTried, head) }
801
+ const notRun = [...new Set([...(charge.notRun ?? []), ...(reviewed.notRun ?? [])])]
802
+ const reused = [...at.reused, { review: reviewed.review, head }]
803
+
804
+ if (notRun.length > 0)
805
+ return new Again({
806
+ at: {
807
+ ...at,
808
+ unranAt: [...at.unranAt, { head, notRun, reuses: reviewed.review }],
809
+ reviewedHeads: withAdded(at.reviewedHeads, head),
810
+ reused
811
+ }
812
+ })
641
813
 
642
- return undefined
814
+ const recorded = yield* approveChangeRequest('reuse', {
815
+ changeRequestId: charge.changeRequestId,
816
+ head,
817
+ summary: `Review ${reviewed.review} passed the whole change at ${head}, so Shepherd approves it without reviewing it again.`,
818
+ reuses: reviewed.review
819
+ }).pipe(
820
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
821
+ )
822
+
823
+ if (!recorded.approved) return new Onward({ at })
824
+
825
+ return new Again({
826
+ at: {
827
+ ...at,
828
+ approvalOf: [...at.approvalOf, { head, approval: recorded.reviewId }],
829
+ reviewedHeads: withAdded(at.reviewedHeads, head),
830
+ reused
831
+ }
643
832
  })
833
+ })
834
+ })
644
835
 
645
- /**
646
- * Merges the target branch in while holding its turn, and carries the approval to the head it pushes when the merge
647
- * left the branch's own change as it was; the Output to stop with, when it cannot.
648
- */
649
- const catchUp = (cycle: number, targetHead: string | undefined, forBlocker = false) =>
650
- Effect.gen(function* () {
651
- const refused = yield* takeTurn()
836
+ /**
837
+ * Merges the target branch in while holding its turn, and carries the approval to the head it pushes when the merge
838
+ * left the branch's own change as it was. A conflict it cannot settle hands the ChangeRequest back to Build, or stops a
839
+ * held Run for a person.
840
+ */
841
+ export const caughtUp = step('caughtUp', {
842
+ payload: {
843
+ charge: Charge,
844
+ at: Shepherding,
845
+ head: Schema.String,
846
+ targetHead: Schema.optional(Schema.String),
847
+ forBlocker: Schema.optional(Schema.Boolean)
848
+ },
849
+ success: Schema.Union([Again, ...Ended]),
850
+ run: ({ charge, at: before, head, targetHead, forBlocker }) =>
851
+ Effect.gen(function* () {
852
+ const { changeRequestId, target, hold } = charge
853
+ const turn = yield* takeTurn(charge, before)
854
+
855
+ if ('refused' in turn)
856
+ return new NeedsYou({ at: before, reason: `The turn to merge into ${target} was refused: ${turn.refused}` })
857
+
858
+ const synced = yield* level({
859
+ changeRequestId,
860
+ head,
861
+ agent: 'implementer',
862
+ target,
863
+ ...(turn.at.unreviewed === undefined ? undefined : { unreviewed: turn.at.unreviewed.files })
864
+ }).pipe(Effect.catchTag('Conflict', conflict => Effect.succeed(conflict)))
865
+
866
+ if (synced._tag === 'Conflict') {
867
+ const reason = `Merging ${target} in conflicts on ${synced.files.join(', ')}: ${synced.reason}`
868
+
869
+ if (hold) return new NeedsYou({ at: turn.at, reason, conflicts: synced.files })
870
+
871
+ return yield* handedBack({
872
+ charge,
873
+ at: turn.at,
874
+ reason,
875
+ open: synced.files.map(file => `- ${file}`).join('\n')
876
+ })
877
+ }
652
878
 
653
- if (refused !== undefined) return done('needs_you', `The turn to merge into ${target} was refused: ${refused}`)
879
+ // A held Run merges nothing, so it needs the turn only while it catches up.
880
+ const held = hold ? yield* passTurn(turn.at) : turn.at
881
+
882
+ if (synced._tag === 'Level') return new Again({ at: { ...held, lastSync: 'up_to_date' } })
883
+ const merged = { ...held, lastSync: 'merged' as const }
884
+ const caught = synced.head === undefined ? undefined : { head: synced.head, from: synced.from }
885
+ const { unreviewed } = merged
886
+
887
+ const reviewing =
888
+ synced.unreviewed.length === 0
889
+ ? { unreviewed: undefined, notCarried: synced.carried ? undefined : synced.why }
890
+ : caught !== undefined && unreviewed !== undefined
891
+ ? {
892
+ // With no fix since the files' merge, the review need not cover this merge's target commits; otherwise
893
+ // `since` keeps covering the fixes, and this merge with them.
894
+ unreviewed:
895
+ caught.from === unreviewed.synced
896
+ ? { ...unreviewed, files: synced.unreviewed, synced: caught.head }
897
+ : { ...unreviewed, files: synced.unreviewed }
898
+ }
899
+ : caught !== undefined
900
+ ? {
901
+ notCarried: undefined,
902
+ unreviewed: {
903
+ files: synced.unreviewed,
904
+ synced: caught.head,
905
+ sync: synced.sync,
906
+ from: caught.from,
907
+ earlier: []
908
+ }
909
+ }
910
+ : undefined
911
+
912
+ const at = { ...merged, ...reviewing }
913
+
914
+ if (caught === undefined) return new Again({ at })
915
+
916
+ const pushedAt = {
917
+ ...at,
918
+ pushed: { head: caught.head, stale: 0, by: 'the catch-up' },
919
+ reviewOnceShown: caught.head,
920
+ pipelineFirst: caught.head,
921
+ syncedFor:
922
+ targetHead === undefined ? at.syncedFor : withAdded(at.syncedFor, syncedKey(caught.head, targetHead)),
923
+ blockerSynced: forBlocker === true ? withAdded(at.blockerSynced, caught.head) : at.blockerSynced,
924
+ ...(charge.head !== undefined && approvedToMerge(charge, at, head)
925
+ ? { caughtUpFrom: withAdded(at.caughtUpFrom ?? [], caught.head) }
926
+ : undefined)
927
+ }
654
928
 
655
- const synced = yield* syncBase(`sync:${cycle}`, { agent: 'implementer', target })
929
+ // The forge can show the old head for a moment after the push; the next look reads it once it shows this one.
930
+ const ended = yield* waitFor('pushed', {
931
+ event: 'change_request.mergeable',
932
+ filter: { changeRequestId, head: caught.head },
933
+ timeout: '5 minutes'
934
+ }).pipe(
935
+ Effect.asVoid,
936
+ Effect.catchTag('WaitTimedOut', () => Effect.void),
937
+ // Ends with the turn it holds, for the Run to let go.
938
+ endedOn(charge, pushedAt)
939
+ )
940
+
941
+ return ended ?? new Again({ at: pushedAt })
942
+ })
943
+ })
656
944
 
657
- lastSync = synced.status
945
+ /**
946
+ * How the head of the target branch does on the failing checks: the forge's own checks on it, and the rest of the
947
+ * repository's Runner checks run there on a Runner.
948
+ */
949
+ export const targetChecked = step('targetChecked', {
950
+ payload: { charge: Charge, pipeline: PipelineStatus },
951
+ success: OnTarget,
952
+ run: ({ charge, pipeline }) =>
953
+ Effect.gen(function* () {
954
+ const failing = failingJobs(pipeline)
955
+ const onForge = (pipeline.target?.jobs ?? []).filter(job => failing.includes(job.name))
956
+ const failed = onForge.flatMap(job => (job.status === 'failed' ? [job.name] : []))
957
+ const passed = onForge.flatMap(job => (job.status === 'success' ? [job.name] : []))
958
+
959
+ const onRunner = failing.filter(
960
+ name => !failed.includes(name) && !passed.includes(name) && (pipeline.runnerChecks ?? []).includes(name)
961
+ )
962
+
963
+ if (onRunner.length === 0) return { failed, passed }
964
+
965
+ const atTarget = yield* verify('target-check', { revision: `origin/${charge.target}`, checks: onRunner }).pipe(
966
+ Effect.catchTag('StepFailed', () => Effect.undefined)
967
+ )
968
+
969
+ const ran = atTarget?.checks.filter(check => onRunner.includes(check.name)) ?? []
970
+
971
+ return {
972
+ failed: [...failed, ...ran.flatMap(check => (check.status === 'failed' ? [check.name] : []))],
973
+ passed: [...passed, ...ran.flatMap(check => (check.status === 'passed' ? [check.name] : []))]
974
+ }
975
+ })
976
+ })
658
977
 
659
- if (synced.status === 'conflict')
660
- return handBack(
661
- `Merging ${target} in conflicts on ${synced.files.join(', ')}: ${synced.reason}`,
662
- synced.files.map(file => `- ${file}`).join('\n')
663
- )
978
+ /** Reads a red target again, a pipeline run after the last wait, and waits once more while nothing moved. */
979
+ export const targetReread = step('targetReread', {
980
+ payload: { charge: Charge, repository: Schema.optional(Schema.String), pipeline: PipelineStatus },
981
+ success: Schema.Union([TargetMoved, Waited]),
982
+ run: ({ charge, repository, pipeline }) =>
983
+ Effect.gen(function* () {
984
+ const again = yield* pipelineStatus('target-read', { changeRequestId: charge.changeRequestId })
664
985
 
665
- if (synced.status !== 'merged') return undefined
666
- const caught = synced.catchUp
667
-
668
- const verdict =
669
- caught === undefined
670
- ? ({ kind: 'changed', why: 'its Runner did not report what it did to the branch' } as const)
671
- : catchUpVerdict(caught)
672
-
673
- if (verdict.kind === 'changed') {
674
- unreviewed = undefined
675
- notCarried = `merging ${target} in changed it: ${verdict.why}`
676
- } else if (caught !== undefined && unreviewed !== undefined) {
677
- const files = [...new Set([...unreviewed.files, ...(verdict.kind === 'review' ? verdict.files : [])])]
678
-
679
- // With no fix since the files' merge, the review need not cover this merge's target commits; otherwise
680
- // `since` keeps covering the fixes, and this merge with them.
681
- unreviewed =
682
- caught.from === unreviewed.synced ? { ...unreviewed, files, synced: caught.head } : { ...unreviewed, files }
683
- } else if (caught !== undefined && verdict.kind === 'review') {
684
- notCarried = undefined
685
- unreviewed = {
686
- files: verdict.files,
687
- synced: caught.head,
688
- sync: `sync:${cycle}`,
689
- from: caught.from,
690
- earlier: []
691
- }
692
- } else if (caught !== undefined) {
693
- notCarried = undefined
694
-
695
- const carried = yield* approveChangeRequest(`carry:${cycle}`, {
696
- changeRequestId,
697
- head: caught.head,
698
- summary: `Merging ${target} in left the branch's own diff as it was approved.`,
699
- carries: `sync:${cycle}`
700
- }).pipe(
701
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
702
- )
986
+ if (again.head !== pipeline.head || again.target?.head !== pipeline.target?.head) return new TargetMoved()
703
987
 
704
- if (!carried.approved) notCarried = `the approval was not carried: ${carried.reason}`
705
- }
988
+ const woke = yield* waitFor('target-moved', {
989
+ ...mergedInto(charge, repository, pipeline.readAt),
990
+ timeout: pipelineRun
991
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
706
992
 
707
- // The forge can show the old head for a moment after the push; the next look reads it once it shows this one.
708
- if (caught !== undefined) {
709
- pushed = { head: caught.head, stale: 0, by: 'the catch-up' }
710
- reviewOnceShown = caught.head
711
- pipelineFirst = caught.head
993
+ return new Waited({ woke })
994
+ })
995
+ })
712
996
 
713
- if (targetHead !== undefined) syncedFor.add(syncedKey(caught.head, targetHead))
997
+ /** Records why it waits rather than fixing, then waits for something to merge into the target. */
998
+ export const waitedOut = step('waitedOut', {
999
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, why: Schema.String },
1000
+ success: Schema.Union([Again, ...Ended]),
1001
+ run: ({ charge, at: before, pipeline, why }) =>
1002
+ Effect.gen(function* () {
1003
+ const at = yield* passTurn(before)
714
1004
 
715
- if (forBlocker) blockerSynced.add(caught.head)
1005
+ yield* note('target-red', {
1006
+ text: `Shepherd is waiting for ${charge.target} to change instead of fixing ${pipeline.head}: ${why}`
1007
+ }).pipe(Effect.catchTag('StepFailed', () => Effect.void))
716
1008
 
717
- yield* waitFor(`pushed:${cycle}`, {
718
- event: 'change_request.mergeable',
719
- filter: { changeRequestId, head: caught.head },
720
- timeout: '5 minutes'
721
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
722
- }
1009
+ // Only a read that names the target's head can tell a push straight to it, which makes no Event.
1010
+ const targetHead = pipeline.target?.head
723
1011
 
724
- return undefined
725
- })
1012
+ const first = yield* waitFor('target-moved', {
1013
+ ...mergedInto(charge, at.repository, pipeline.readAt),
1014
+ timeout: targetHead === undefined ? '1 hour' : pipelineRun
1015
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
726
1016
 
727
- const stop = (output: Output) => ({ kind: 'stop', output }) as const
1017
+ const wokeBy = (woke: LoopEvent | undefined) =>
1018
+ closedBy(charge, at, woke, 'Someone else') ??
1019
+ new Again({ at: { ...at, redTarget: { head: pipeline.head, targetHead, moved: woke !== undefined } } })
728
1020
 
729
- /**
730
- * Left for a person to merge: watches the target and runs the checks that read it again at `pipeline`'s head each
731
- * time it moves, and catches up when they fail, so the person merges a head that builds on the target. `again` when
732
- * the ChangeRequest goes round once more, or `stop` with the Output: `ready` once the looks run out.
733
- */
734
- const watchTarget = (cycle: number, pipeline: PipelineStatus, ready: Output) =>
735
- Effect.gen(function* () {
736
- const checks = pipeline.targetChecks ?? []
1021
+ if (first !== undefined || targetHead === undefined) return wokeBy(first)
737
1022
 
738
- if (checks.length === 0) return stop(ready)
1023
+ // Reading again each pipeline run is part of this one look, so it costs no look of its own.
1024
+ for (let look = 2; look <= targetLooks; look++) {
1025
+ const again = yield* targetReread({ charge, repository: at.repository, pipeline })
739
1026
 
740
- yield* passTurn()
1027
+ if (again._tag === 'TargetMoved') return wokeBy(undefined)
741
1028
 
742
- /** Runs the checks against the target as it is now; `again` or `stop` when they fail, else undefined. */
743
- const runChecks = (step: string, targetHead: string | undefined) =>
744
- Effect.gen(function* () {
745
- const checked = yield* verify(step, { revision: pipeline.head, checks }).pipe(
746
- Effect.catchTag('StepFailed', error => Effect.succeed({ failed: error.reason }))
747
- )
1029
+ if (again.woke !== undefined) return wokeBy(again.woke)
1030
+ }
748
1031
 
749
- if ('failed' in checked)
750
- return stop(
751
- done('needs_you', `${checks.join(', ')} could not run against ${target} as it moved: ${checked.failed}`)
752
- )
1032
+ return wokeBy(undefined)
1033
+ })
1034
+ })
753
1035
 
754
- if (targetHead !== undefined) targetChecked = { head: pipeline.head, targetHead }
1036
+ /** Has the implementer fix a failing pipeline, after ruling out a flake and a target branch that fails the same check. */
1037
+ export const ciFixed = step('ciFixed', {
1038
+ payload: { target: Schema.String, pipeline: PipelineStatus, onTarget: OnTarget },
1039
+ success: CiFix,
1040
+ run: ({ target, pipeline, onTarget }) =>
1041
+ implementer('ci-fix', { prompt: ciFixPrompt(pipeline, target, onTarget), output: CiFix, timeout: stepBudget })
1042
+ })
755
1043
 
756
- if (checked.passed) return undefined
1044
+ /** Runs a failing pipeline again once, on the Runner or the forge, when the ci-fix found its failure a flake. */
1045
+ export const reran = step('reran', {
1046
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, summary: Schema.String },
1047
+ success: Schema.Union([Again, ...Ended]),
1048
+ run: ({ charge, at, pipeline, summary }) =>
1049
+ Effect.gen(function* () {
1050
+ const { changeRequestId } = charge
757
1051
 
758
- const stopped = yield* catchUp(cycle, targetHead)
1052
+ if (pipeline.source === 'reported') {
1053
+ // Only a pipeline that runs on the Runner can be run again; nothing on the forge can run a report.
1054
+ if (pipeline.runnerChecks === undefined)
1055
+ return new NeedsYou({ at, reason: `The failing job passed when run again, outside the forge: ${summary}` })
759
1056
 
760
- if (stopped !== undefined) return stop(stopped)
1057
+ if (at.reranHeads.includes(pipeline.head))
1058
+ return new NeedsYou({ at, reason: `The failing job failed again when run again on the Runner: ${summary}` })
761
1059
 
762
- if (lastSync === 'up_to_date')
763
- return stop(
764
- done(
765
- 'needs_you',
766
- `${checks.join(', ')} failed at ${pipeline.head} against ${target}, which has nothing new to merge in`
767
- )
768
- )
1060
+ const ran = yield* runOnRunner(changeRequestId, 'rerun', pipeline.head, pipeline.runnerChecks)
1061
+ const rerun = { ...at, reranHeads: [...at.reranHeads, pipeline.head] }
769
1062
 
770
- return { kind: 'again' } as const
771
- })
1063
+ if ('failed' in ran)
1064
+ return new NeedsYou({ at: rerun, reason: `The pipeline could not run on the Runner: ${ran.failed}` })
772
1065
 
773
- const isChecked = (targetHead: string | undefined) =>
774
- targetHead !== undefined && targetChecked?.head === pipeline.head && targetChecked.targetHead === targetHead
1066
+ return new Again({ at: rerun })
1067
+ }
775
1068
 
776
- // The target may have moved before this read, and the head's own checks need not have read it.
777
- if (!isChecked(pipeline.target?.head)) {
778
- const first = yield* runChecks(`target-verify:${cycle}:0`, pipeline.target?.head)
1069
+ if (at.reranHeads.includes(pipeline.head))
1070
+ return new NeedsYou({ at, reason: `The failing job failed again when run again on the forge: ${summary}` })
779
1071
 
780
- if (first !== undefined) return first
781
- }
1072
+ yield* rerunPipeline('rerun', { changeRequestId })
1073
+ // Until the forge reports the rerun, a read still shows the failure it reran.
1074
+ yield* pipelineMoved('rerun-wait', changeRequestId, pipeline).pipe(
1075
+ Effect.catchTag('WaitTimedOut', () => Effect.void)
1076
+ )
782
1077
 
783
- let since = pipeline.readAt
1078
+ return new Again({ at: { ...at, reranHeads: [...at.reranHeads, pipeline.head] } })
1079
+ })
1080
+ })
784
1081
 
785
- for (let look = 1; look <= watchLooks; look++) {
786
- const woke = yield* waitFor(`watch:${cycle}:${look}`, {
787
- event: 'change_request.closed',
788
- filter: {
789
- merged: true,
790
- ...(target === 'HEAD' ? undefined : { targetBranch: target }),
791
- ...(repository === undefined ? undefined : { repository })
792
- },
793
- or: [{ event: 'change_request.closed', filter: { changeRequestId } }],
794
- timeout: watchLook,
795
- ...(since === undefined ? undefined : { since })
796
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
797
-
798
- if (woke?.payload.changeRequestId === changeRequestId)
799
- return stop(
800
- woke.payload.merged === true
801
- ? done('merged', 'A person merged the ChangeRequest')
802
- : done('needs_you', 'The ChangeRequest was closed')
803
- )
1082
+ /** Posts one reply on its review thread. */
1083
+ export const replied = step('replied', {
1084
+ payload: { changeRequestId: Schema.String, threadId: Schema.String, reply: Schema.String },
1085
+ key: ({ threadId }) => threadId,
1086
+ run: ({ changeRequestId, threadId, reply }) => comment('reply', { changeRequestId, threadId, body: reply })
1087
+ })
804
1088
 
805
- const again = yield* pipelineStatus(`watch-read:${cycle}:${look}`, { changeRequestId })
1089
+ /**
1090
+ * Answers each review thread nobody answered since its last comment, on the thread: `Again` when a reply changed the
1091
+ * code, so the head it pushed is checked.
1092
+ */
1093
+ export const answered = step('answered', {
1094
+ payload: { charge: Charge, at: Shepherding },
1095
+ success: Schema.Union([Again, Onward]),
1096
+ run: ({ charge, at: before }) =>
1097
+ Effect.gen(function* () {
1098
+ const { changeRequestId } = charge
806
1099
 
807
- since = again.readAt ?? since
1100
+ const threads = (yield* reviewThreads('threads', { changeRequestId })).threads.filter(
1101
+ thread => !before.answered.includes(threadKey(thread))
1102
+ )
808
1103
 
809
- if (again.head !== pipeline.head) return { kind: 'again' } as const
1104
+ if (threads.length === 0) return new Onward({ at: before })
810
1105
 
811
- // A push straight to the target makes no Event: only a read that names its head shows it.
812
- const targetHead = again.target?.head
1106
+ const at = yield* passTurn(before)
813
1107
 
814
- if (woke === undefined && (targetHead === undefined || isChecked(targetHead))) continue
1108
+ const answers = yield* implementer('comments', {
1109
+ prompt: repliesPrompt(threads),
1110
+ output: Replies,
1111
+ timeout: stepBudget
1112
+ })
815
1113
 
816
- const ran = yield* runChecks(`target-verify:${cycle}:${look}`, targetHead)
1114
+ for (const answer of answers.replies)
1115
+ yield* replied({ changeRequestId, threadId: answer.threadId, reply: answer.reply })
817
1116
 
818
- if (ran !== undefined) return ran
819
- }
1117
+ const replies = {
1118
+ ...at,
1119
+ replies: at.replies + answers.replies.length,
1120
+ answered: [...at.answered, ...threads.map(thread => `${thread.id}:${thread.comments.length + 1}`)]
1121
+ }
820
1122
 
821
- return stop(ready)
822
- })
1123
+ return answers.replies.some(answer => answer.changed) ? new Again({ at: replies }) : new Onward({ at: replies })
1124
+ })
1125
+ })
1126
+
1127
+ /** Reviews the files a catch-up merge settled, at the head of `pipeline`, and approves it on a pass. */
1128
+ export const filesReviewed = step('filesReviewed', {
1129
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, files: Unreviewed },
1130
+ success: Schema.Union([Wanted, Passed]),
1131
+ run: ({ charge, at: before, pipeline, files }) =>
1132
+ Effect.gen(function* () {
1133
+ const { head } = pipeline
1134
+ const passed = yield* passTurn(before)
1135
+
1136
+ const reviewing = yield* approved({
1137
+ changeRequestId: charge.changeRequestId,
1138
+ head,
1139
+ target: charge.target,
1140
+ unreviewed: { files: files.files, caughtUp: files.synced, sync: files.sync },
1141
+ ...(files.earlier.length === 0 ? undefined : { earlier: files.earlier }),
1142
+ ...(files.reviewed === undefined ? undefined : { reviewed: files.reviewed }),
1143
+ ...(passed.outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings: passed.outOfScopeFindings })
1144
+ }).pipe(
1145
+ Effect.catchTags({
1146
+ ChangesWanted: wanted => Effect.succeed(wanted),
1147
+ ApprovalRefused: ({ reason, outOfScopeFindings }) =>
1148
+ Effect.succeed({ _tag: 'NotApproved', why: reason, outOfScopeFindings } as const),
1149
+ LeftToPerson: ({ why, outOfScopeFindings }) =>
1150
+ Effect.succeed({ _tag: 'NotApproved', why, outOfScopeFindings } as const)
1151
+ })
1152
+ )
823
1153
 
824
- /**
825
- * Reviews the files a catch-up merge settled, at `head`, and approves it on a pass: `fixing` when a fix round ran for
826
- * its findings, `approved` or `unapproved` once the review passed, or `stop` with the Output.
827
- */
828
- const reviewMergedFiles = (cycle: number, pipeline: PipelineStatus, files: NonNullable<typeof unreviewed>) =>
829
- Effect.gen(function* () {
830
- const { head } = pipeline
1154
+ const at = { ...passed, outOfScopeFindings: reviewing.outOfScopeFindings ?? [] }
831
1155
 
832
- yield* passTurn()
1156
+ if (reviewing._tag === 'ChangesWanted') {
1157
+ const blocking = reviewing.findings.filter(isBlocking)
833
1158
 
834
- const reviewed = yield* call(`review:${cycle}`, reviewLoop(), {
835
- base: `origin/${target}`,
1159
+ return new Wanted({
1160
+ at,
836
1161
  head,
837
- deliveredBy: changeRequestId,
838
- files: files.files,
839
- ...(head === files.synced ? undefined : { since: files.synced }),
840
- ...(files.earlier.length === 0 ? undefined : { earlier: files.earlier }),
841
- ...(files.reviewed === undefined ? undefined : { reviewed: files.reviewed }),
842
- ...(outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings })
1162
+ findings: reviewing.findings,
1163
+ subject: 'the files the catch-up merge changed',
1164
+ files,
1165
+ handBack: {
1166
+ reason: `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')}`,
1167
+ open: findingLines(blocking),
1168
+ // Nobody read the rest of a change whose merged-from head is not approved, so Build reviews it whole.
1169
+ review:
1170
+ files.from !== undefined && pipeline.approved === files.from
1171
+ ? { reviewed: head, earlier: reviewing.findings }
1172
+ : undefined
1173
+ }
843
1174
  })
1175
+ }
844
1176
 
845
- outOfScopeFindings = reviewed.outOfScopeFindings ?? []
846
-
847
- if (reviewed.blocking) {
848
- const blocking = reviewed.findings.filter(isBlocking)
1177
+ if (reviewing._tag === 'NotApproved')
1178
+ return new Passed({
1179
+ at: {
1180
+ ...at,
1181
+ unreviewed: undefined,
1182
+ notCarried: `merging ${charge.target} in, whose files' review passed but did not approve it: ${reviewing.why}`
1183
+ },
1184
+ approved: false
1185
+ })
849
1186
 
850
- if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
851
- return stop(
852
- handBack(
853
- `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
854
- findingLines(blocking),
855
- // Nobody read the rest of a change whose merged-from head is not approved, so Build reviews it whole.
856
- pipeline.approved === files.from ? { reviewed: head, earlier: reviewed.findings } : undefined
857
- )
858
- )
859
- rounds['head-fix']++
1187
+ return new Passed({
1188
+ at: {
1189
+ ...at,
1190
+ unreviewed: undefined,
1191
+ approvalOf:
1192
+ reviewing.approval === undefined
1193
+ ? at.approvalOf
1194
+ : [...at.approvalOf, { head, approval: reviewing.approval }],
1195
+ reviewedHeads: withAdded(at.reviewedHeads, head)
1196
+ },
1197
+ approved: true
1198
+ })
1199
+ })
1200
+ })
860
1201
 
861
- const fix = yield* agentWork(`review-fix:${cycle}`, {
862
- agent: 'implementer',
863
- prompt: reviewFixPrompt('the files the catch-up merge changed', blocking),
864
- output: ReviewFix,
865
- timeout: stepBudget
866
- })
1202
+ /**
1203
+ * Has Kitman review the head of `pipeline`, which nobody approved, when a person or full auto says so, and approves it
1204
+ * on a pass: `Left` when its approval is left to a person.
1205
+ */
1206
+ export const headReviewed = step('headReviewed', {
1207
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, which: Schema.String },
1208
+ success: Schema.Union([Wanted, Passed, Left, NeedsYou]),
1209
+ run: ({ charge, at: before, pipeline, which }) =>
1210
+ Effect.gen(function* () {
1211
+ const { head } = pipeline
1212
+ // Only what changed since the last approved head is unreviewed; the rest was approved as it stands.
1213
+ const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved
1214
+ const passed = yield* passTurn(before)
1215
+
1216
+ if (passed.leftToPerson.includes(head)) return new Left({ at: passed })
1217
+
1218
+ const reviewing = yield* approved({
1219
+ changeRequestId: charge.changeRequestId,
1220
+ head,
1221
+ target: charge.target,
1222
+ which,
1223
+ ...(since === undefined ? undefined : { approved: since }),
1224
+ ...(charge.notRun === undefined ? undefined : { notRun: charge.notRun }),
1225
+ ...(passed.headFindings.length === 0 ? undefined : { earlier: passed.headFindings }),
1226
+ ...(passed.headFindingsAt === undefined ? undefined : { reviewed: passed.headFindingsAt }),
1227
+ ...(passed.headScope === undefined ? undefined : { scope: passed.headScope }),
1228
+ ...(passed.outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings: passed.outOfScopeFindings })
1229
+ }).pipe(
1230
+ Effect.catchTags({
1231
+ ChangesWanted: wanted => Effect.succeed(wanted),
1232
+ ApprovalRefused: refused => Effect.succeed(refused),
1233
+ LeftToPerson: left => Effect.succeed(left)
1234
+ })
1235
+ )
867
1236
 
868
- unreviewed = { ...files, earlier: reviewed.findings, reviewed: head }
869
- fixedFrom = { head, changed: fix.changed, looks: 0 }
1237
+ const at = { ...passed, outOfScopeFindings: reviewing.outOfScopeFindings ?? [] }
870
1238
 
871
- return { kind: 'fixing' } as const
872
- }
1239
+ if (reviewing._tag === 'ChangesWanted') {
1240
+ const blocking = reviewing.findings.filter(isBlocking)
873
1241
 
874
- const approval = yield* approveChangeRequest(`approve:${cycle}`, {
875
- changeRequestId,
1242
+ return new Wanted({
1243
+ at,
876
1244
  head,
877
- summary: `A review of the files merging ${target} in changed (${files.files.join(', ')}) passed with nothing blocking.`,
878
- review: `review:${cycle}`,
879
- carries: files.sync
880
- }).pipe(
881
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
882
- )
1245
+ findings: reviewing.findings,
1246
+ subject: since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`,
1247
+ scope: reviewing.scope,
1248
+ handBack: {
1249
+ reason: `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')}`,
1250
+ open: [findingLines(blocking), ...(reviewing.scope?.unmet ?? []).map(item => `- Not done: ${item}`)].join(
1251
+ '\n'
1252
+ ),
1253
+ review: {
1254
+ reviewed: head,
1255
+ earlier: reviewing.findings,
1256
+ ...(reviewing.scope === undefined ? undefined : { scope: reviewing.scope })
1257
+ }
1258
+ }
1259
+ })
1260
+ }
883
1261
 
884
- unreviewed = undefined
1262
+ const unran =
1263
+ reviewing._tag === 'LeftToPerson' && reviewing.notRun !== undefined && reviewing.review !== undefined
1264
+ ? { head, notRun: reviewing.notRun, review: reviewing.review }
1265
+ : undefined
885
1266
 
886
- if (!approval.approved) {
887
- notCarried = `merging ${target} in, whose files' review passed but did not approve it: ${approval.reason}`
1267
+ if (reviewing._tag === 'LeftToPerson' && unran === undefined)
1268
+ return new Left({ at: { ...at, leftToPerson: [...at.leftToPerson, head] } })
888
1269
 
889
- return { kind: 'unapproved' } as const
890
- }
1270
+ const cleared = { ...at, headFindings: [], headFindingsAt: undefined, headScope: undefined }
891
1271
 
892
- approvalOf.set(head, approval.reviewId)
893
- reviewedHeads.add(head)
1272
+ if (reviewing._tag === 'ApprovalRefused')
1273
+ return new NeedsYou({
1274
+ at: cleared,
1275
+ reason: `The review of ${head} passed, but did not approve it: ${reviewing.reason}`
1276
+ })
894
1277
 
895
- return { kind: 'approved' } as const
1278
+ return new Passed({
1279
+ at: {
1280
+ ...cleared,
1281
+ unranAt: unran === undefined ? cleared.unranAt : [...cleared.unranAt, unran],
1282
+ approvalOf:
1283
+ unran === undefined && reviewing._tag === 'Approved' && reviewing.approval !== undefined
1284
+ ? [...cleared.approvalOf, { head, approval: reviewing.approval }]
1285
+ : cleared.approvalOf,
1286
+ reviewedHeads: withAdded(cleared.reviewedHeads, head)
1287
+ },
1288
+ approved: true
896
1289
  })
1290
+ })
1291
+ })
897
1292
 
898
- /**
899
- * Has Kitman review the head of `pipeline`, which nobody approved, when a person or full auto says so, and approves
900
- * it on a pass: `fixing` when a fix round ran for its findings, `left` when its approval is left to a person,
901
- * `reviewed` once the review passed, or `stop` with the Output.
902
- */
903
- const reviewHead = (cycle: number, pipeline: PipelineStatus, which: string) =>
904
- Effect.gen(function* () {
905
- const head = pipeline.head
906
- // Only what changed since the last approved head is unreviewed; the rest was approved as it stands.
907
- const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved
908
-
909
- const reviewIt = leftToPerson.has(head)
910
- ? 'Wait'
911
- : yield* ask(`unapproved:${cycle}`, {
912
- prompt: `Nobody has approved ${head}, ${which}. Have Kitman review it?`,
913
- options: [
914
- {
915
- value: 'Review',
916
- description:
917
- since === undefined
918
- ? "Kitman's Review reads the whole change at this head and approves it if nothing blocks."
919
- : `Kitman's Review reads what changed since ${since}, the last approved head, and approves it if nothing there blocks.`
920
- },
921
- { value: 'Wait', description: 'Waits for a person to approve this head.' }
922
- ],
923
- recommended: 'Review',
924
- recommendationReason: 'A passing Review of the change is what approved the head Build shipped.',
925
- default: 'Wait',
926
- // A full-auto Team merges what its Review approved, including heads Shepherd pushed itself.
927
- auto: 'Review',
928
- evidence: { head },
929
- timeout: '1 hour'
930
- })
1293
+ /** Has the implementer fix what a review of the head found blocking: a head-fix round. */
1294
+ export const headFixed = step('headFixed', {
1295
+ payload: {
1296
+ subject: Schema.String,
1297
+ blocking: Schema.Array(MergedFinding),
1298
+ files: Schema.Boolean.annotate({ description: 'It fixes what a review of the files a catch-up changed found.' })
1299
+ },
1300
+ success: ReviewFix,
1301
+ run: ({ subject, blocking, files }) =>
1302
+ implementer(files ? 'review-fix' : 'head-fix', {
1303
+ prompt: reviewFixPrompt(subject, blocking),
1304
+ output: ReviewFix,
1305
+ timeout: stepBudget
1306
+ })
1307
+ })
931
1308
 
932
- yield* passTurn()
1309
+ /** Runs the checks that read the target against it as it is now, at the head of `pipeline`, and catches up when they fail. */
1310
+ export const targetVerified = step('targetVerified', {
1311
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, targetHead: Schema.optional(Schema.String) },
1312
+ success: Schema.Union([TargetPassed, Again, ...Ended]),
1313
+ run: ({ charge, at: before, pipeline, targetHead }) =>
1314
+ Effect.gen(function* () {
1315
+ const checks = pipeline.targetChecks ?? []
1316
+
1317
+ const checked = yield* verify('target-verify', { revision: pipeline.head, checks }).pipe(
1318
+ Effect.catchTag('StepFailed', error => Effect.succeed({ failed: error.reason }))
1319
+ )
1320
+
1321
+ if ('failed' in checked)
1322
+ return new NeedsYou({
1323
+ at: before,
1324
+ reason: `${checks.join(', ')} could not run against ${charge.target} as it moved: ${checked.failed}`
1325
+ })
933
1326
 
934
- if (reviewIt === 'Wait') {
935
- leftToPerson.add(head)
1327
+ const at = targetHead === undefined ? before : { ...before, targetChecked: { head: pipeline.head, targetHead } }
936
1328
 
937
- return { kind: 'left' } as const
938
- }
1329
+ if (checked.passed) return new TargetPassed({ at })
939
1330
 
940
- const { notRun: headNotRun } = yield* verifyHead(`head-verify:${cycle}`, head)
941
- const notRun = [...new Set([...(input.notRun ?? []), ...headNotRun])]
1331
+ const caught = yield* caughtUp({ charge, at, head: pipeline.head, targetHead })
942
1332
 
943
- const reviewed = yield* call(`head-review:${cycle}`, reviewLoop(), {
944
- base: `origin/${target}`,
945
- head,
946
- deliveredBy: changeRequestId,
947
- ...(notRun.length === 0 ? undefined : { notRun }),
948
- ...(since === undefined ? undefined : { approved: since }),
949
- ...(headFindings.length === 0 ? undefined : { earlier: headFindings }),
950
- ...(headFindingsAt === undefined ? undefined : { reviewed: headFindingsAt }),
951
- ...(outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings }),
952
- ...(headScope === undefined ? undefined : { scope: headScope })
1333
+ if (caught._tag === 'Again' && caught.at.lastSync === 'up_to_date')
1334
+ return new NeedsYou({
1335
+ at: caught.at,
1336
+ reason: `${checks.join(', ')} failed at ${pipeline.head} against ${charge.target}, which has nothing new to merge in`
953
1337
  })
954
1338
 
955
- outOfScopeFindings = reviewed.outOfScopeFindings ?? []
956
-
957
- if (reviewed.blocking) {
958
- const blocking = reviewed.findings.filter(isBlocking)
959
-
960
- if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
961
- return stop(
962
- handBack(
963
- `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
964
- [findingLines(blocking), ...(reviewed.scope?.unmet ?? []).map(item => `- Not done: ${item}`)].join(
965
- '\n'
966
- ),
967
- {
968
- reviewed: head,
969
- earlier: reviewed.findings,
970
- ...(reviewed.scope === undefined ? undefined : { scope: reviewed.scope })
971
- }
972
- )
973
- )
974
- rounds['head-fix']++
1339
+ return caught
1340
+ })
1341
+ })
975
1342
 
976
- const fix = yield* agentWork(`head-fix:${cycle}`, {
977
- agent: 'implementer',
978
- prompt: reviewFixPrompt(
979
- since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`,
980
- blocking
981
- ),
982
- output: ReviewFix,
983
- timeout: stepBudget
984
- })
1343
+ /** Where a watch of the target left off: what it knew, and when it last read the ChangeRequest. */
1344
+ export class Watching extends Schema.TaggedClass<Watching>()('Watching', {
1345
+ at: Shepherding,
1346
+ since: Schema.optional(Schema.String)
1347
+ }) {}
985
1348
 
986
- headFindings = reviewed.findings
987
- headFindingsAt = head
988
- headScope = reviewed.scope
989
- fixedFrom = { head, changed: fix.changed, looks: 0 }
1349
+ /** Whether the checks that read the target last ran at `head` against `targetHead`. */
1350
+ const checkedAgainst = (at: Shepherding, head: string, targetHead: string | undefined) =>
1351
+ targetHead !== undefined && at.targetChecked?.head === head && at.targetChecked.targetHead === targetHead
990
1352
 
991
- return { kind: 'fixing' } as const
992
- }
993
-
994
- headFindings = []
995
- headFindingsAt = undefined
996
- headScope = undefined
997
-
998
- if (notRun.length > 0) unranAt.set(head, { notRun, review: `head-review:${cycle}` })
999
- else {
1000
- const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
1001
- changeRequestId,
1002
- head,
1003
- summary:
1004
- since === undefined
1005
- ? `A review of the whole change at ${head} passed with nothing blocking.`
1006
- : `A review of what changed between ${since}, the last approved head, and ${head} passed with nothing blocking.`,
1007
- review: `head-review:${cycle}`
1008
- }).pipe(
1009
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
1010
- )
1353
+ /**
1354
+ * Waits one look for the target to move, left for a person to merge, then reads the ChangeRequest again, and runs the
1355
+ * checks that read the target at `pipeline`'s head once more when the target moved. `Watching` while nothing changed.
1356
+ */
1357
+ export const targetLooked = step('targetLooked', {
1358
+ payload: { charge: Charge, pipeline: PipelineStatus, watching: Watching },
1359
+ success: Schema.Union([Watching, Again, ...Ended]),
1360
+ run: ({ charge, pipeline, watching }) =>
1361
+ Effect.gen(function* () {
1362
+ const { at, since } = watching
1011
1363
 
1012
- if (!recorded.approved)
1013
- return stop(done('needs_you', `The review of ${head} passed, but did not approve it: ${recorded.reason}`))
1364
+ const woke = yield* waitFor('watch', { ...mergedInto(charge, at.repository, since), timeout: watchLook }).pipe(
1365
+ Effect.catchTag('WaitTimedOut', () => Effect.undefined)
1366
+ )
1014
1367
 
1015
- approvalOf.set(head, recorded.reviewId)
1016
- }
1368
+ const closed = closedBy(charge, at, woke, 'A person')
1017
1369
 
1018
- reviewedHeads.add(head)
1370
+ if (closed !== undefined) return closed
1019
1371
 
1020
- return { kind: 'reviewed' } as const
1021
- })
1372
+ const read = yield* pipelineStatus('watch-read', { changeRequestId: charge.changeRequestId })
1373
+ const readSince = read.readAt ?? since
1022
1374
 
1023
- /**
1024
- * Approves the head of `pipeline` with the passed Review of the whole change at it that another Run recorded, such
1025
- * as the Build that shipped it, rather than reviewing it again; later heads are reviewed only since it. Like its own
1026
- * review, it leaves a head with tests verify never ran unapproved until a person chooses to merge it.
1027
- */
1028
- const reuseReview = (cycle: number, pipeline: PipelineStatus, reviewed: NonNullable<PipelineStatus['reviewed']>) =>
1029
- Effect.gen(function* () {
1030
- const { head } = pipeline
1375
+ if (read.head !== pipeline.head) return new Again({ at })
1031
1376
 
1032
- reuseTried.add(head)
1377
+ // A push straight to the target makes no Event: only a read that names its head shows it.
1378
+ const targetHead = read.target?.head
1033
1379
 
1034
- const notRun = [...new Set([...(input.notRun ?? []), ...(reviewed.notRun ?? [])])]
1380
+ if (woke === undefined && (targetHead === undefined || checkedAgainst(at, pipeline.head, targetHead)))
1381
+ return new Watching({ at, since: readSince })
1035
1382
 
1036
- if (notRun.length > 0) {
1037
- unranAt.set(head, { notRun, reuses: reviewed.review })
1038
- reviewedHeads.add(head)
1039
- reused.push({ review: reviewed.review, head })
1383
+ const ran = yield* targetVerified({ charge, at, pipeline, targetHead })
1040
1384
 
1041
- return true
1042
- }
1385
+ return ran._tag === 'TargetPassed' ? new Watching({ at: ran.at, since: readSince }) : ran
1386
+ })
1387
+ })
1043
1388
 
1044
- const recorded = yield* approveChangeRequest(`reuse:${cycle}`, {
1045
- changeRequestId,
1046
- head,
1047
- summary: `Review ${reviewed.review} passed the whole change at ${head}, so Shepherd approves it without reviewing it again.`,
1048
- reuses: reviewed.review
1049
- }).pipe(
1050
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
1051
- )
1389
+ /**
1390
+ * Left for a person to merge: watches the target and runs the checks that read it again at `pipeline`'s head each time
1391
+ * it moves, and catches up when they fail, so the person merges a head that builds on the target. `Again` when the
1392
+ * ChangeRequest goes round once more; `Ready`, for `ready`, once the looks run out.
1393
+ */
1394
+ export const targetWatched = step('targetWatched', {
1395
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, ready: Schema.String },
1396
+ success: Schema.Union([Again, ...Ended]),
1397
+ run: ({ charge, at: before, pipeline, ready }) =>
1398
+ Effect.gen(function* () {
1399
+ if ((pipeline.targetChecks ?? []).length === 0) return new Ready({ at: before, reason: ready })
1052
1400
 
1053
- if (!recorded.approved) return false
1401
+ const at = yield* passTurn(before)
1054
1402
 
1055
- approvalOf.set(head, recorded.reviewId)
1056
- reviewedHeads.add(head)
1057
- reused.push({ review: reviewed.review, head })
1403
+ // The target may have moved before this read, and the head's own checks need not have read it.
1404
+ const first = checkedAgainst(at, pipeline.head, pipeline.target?.head)
1405
+ ? new TargetPassed({ at })
1406
+ : yield* targetVerified({ charge, at, pipeline, targetHead: pipeline.target?.head })
1058
1407
 
1059
- return true
1060
- })
1408
+ if (first._tag !== 'TargetPassed') return first
1061
1409
 
1062
- /** Reviews the head the last catch-up pushed, if `pipeline` shows it and it still needs a review. */
1063
- const reviewCaughtUp = (cycle: number, pipeline: PipelineStatus) =>
1064
- Effect.gen(function* () {
1065
- const head = reviewOnceShown
1410
+ let watching = new Watching({ at: first.at, since: pipeline.readAt })
1066
1411
 
1067
- reviewOnceShown = undefined
1412
+ for (let look = 1; look <= watchLooks; look++) {
1413
+ const next = yield* targetLooked({ charge, pipeline, watching })
1068
1414
 
1069
- if (head !== pipeline.head) return undefined
1415
+ if (next._tag !== 'Watching') return next
1416
+ watching = next
1417
+ }
1070
1418
 
1071
- if (unreviewed !== undefined) return yield* reviewMergedFiles(cycle, pipeline, unreviewed)
1419
+ return new Ready({ at: watching.at, reason: ready })
1420
+ })
1421
+ })
1072
1422
 
1073
- if (notCarried !== undefined && pipeline.approved !== head)
1074
- return yield* reviewHead(cycle, pipeline, 'the head its catch-up merge pushed')
1423
+ const EpicLanding = Schema.Struct({ status: Schema.String, reason: Schema.String })
1424
+
1425
+ /** Calls Land epic once, and waits for the epic branch to be free when another Run works it, unless this is the last call. */
1426
+ export const landingTried = step('landingTried', {
1427
+ payload: { charge: Charge, landing: EpicDelivery, repository: Schema.optional(Schema.String), last: Schema.Boolean },
1428
+ success: EpicLanding,
1429
+ run: ({ charge, landing, repository, last }) =>
1430
+ Effect.gen(function* () {
1431
+ const called = yield* call('land-epic', landEpicLoop(), {
1432
+ taskId: landing.taskId,
1433
+ ...ownDeliveryTarget(charge)
1434
+ }).pipe(
1435
+ Effect.map(landed => ({ status: landed.status, reason: landed.reason })),
1436
+ Effect.catchTags({
1437
+ ChildFailed: failed => Effect.succeed({ status: 'failed', reason: failed.reason }),
1438
+ StepFailed: refused => Effect.succeed({ status: landingStatus(refused.code), reason: refused.reason })
1439
+ })
1440
+ )
1075
1441
 
1076
- return undefined
1077
- })
1442
+ if (called.status !== 'busy' || last) return called
1078
1443
 
1079
- return Effect.gen(function* () {
1080
- for (let cycle = 1; ; cycle++) {
1081
- if (cycle > (input.maxCycles ?? 20)) {
1082
- const goOn = yield* ask(`continue:${cycle}`, {
1083
- prompt: `Shepherd has looked at this ChangeRequest ${cycle - 1} times without landing it. Keep going?`,
1084
- options: ['Keep going', 'Stop'],
1085
- recommended: 'Stop',
1086
- recommendationReason: `${cycle - 1} looks have not landed it, so something needs a person rather than another look.`,
1087
- default: 'Stop',
1088
- timeout: '1 hour'
1089
- })
1444
+ yield* waitFor('busy', {
1445
+ event: 'change_request.closed',
1446
+ filter: {
1447
+ merged: true,
1448
+ targetBranch: landing.branch,
1449
+ ...(repository === undefined ? undefined : { repository })
1450
+ },
1451
+ timeout: landingRetry
1452
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
1090
1453
 
1091
- if (goOn === 'Stop') return done('needs_you', `Stopped after ${cycle - 1} looks without landing it`)
1092
- }
1454
+ return called
1455
+ })
1456
+ })
1093
1457
 
1094
- const pipeline = yield* pipelineStatus(`pipeline:${cycle}`, { changeRequestId })
1458
+ /**
1459
+ * Calls Land epic once this merge is in the epic branch: it takes in the default branch, and opens the epic's
1460
+ * ChangeRequest once every sub-task is done. While another Run works the epic branch Kitman refuses it, so it calls
1461
+ * again once that Run can have ended: a landing that started before this merge saw this sub-task still open. One that
1462
+ * saw every sub-task done, as epic.ready starts when this merge closes the last, lands the epic itself.
1463
+ */
1464
+ export const epicLanded = step('epicLanded', {
1465
+ payload: { charge: Charge, landing: EpicDelivery, repository: Schema.optional(Schema.String) },
1466
+ success: EpicLanding,
1467
+ run: ({ charge, landing, repository }) =>
1468
+ Effect.gen(function* () {
1469
+ for (let attempt = 1; ; attempt++) {
1470
+ const called = yield* landingTried({ charge, landing, repository, last: attempt === landingCalls })
1095
1471
 
1096
- repository = pipeline.repository ?? repository
1472
+ if (called.status !== 'busy') return called
1097
1473
 
1098
- // The forge can show an older head for a while after a catch-up push: nothing is gated on any head but the
1099
- // pushed one, so look again; a person's push on top of it stops it for them.
1100
- if (pushed !== undefined && pipeline.head !== pushed.head) {
1101
- if (++pushed.stale > 5)
1102
- return done(
1103
- 'needs_you',
1104
- `The forge still shows ${pipeline.head}, not ${pushed.head} that ${pushed.by} pushed`
1105
- )
1474
+ if (attempt === landingCalls) return { status: 'refused', reason: called.reason }
1475
+ }
1476
+ })
1477
+ })
1106
1478
 
1107
- // Only an Event since this read settles it, so the one that settled the last wait does not end it at once.
1108
- yield* waitFor(`pushed-again:${cycle}`, {
1109
- event: 'change_request.mergeable',
1110
- filter: { changeRequestId, head: pushed.head },
1111
- timeout: '1 minute',
1112
- ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
1113
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
1479
+ /** Starts Release on the merge, once a person or full auto says so, and reports what it did. */
1480
+ export const released = step('released', {
1481
+ payload: {
1482
+ charge: Charge,
1483
+ at: Shepherding,
1484
+ fixRounds: Schema.Int,
1485
+ revision: Schema.String,
1486
+ review: Schema.optional(Schema.String),
1487
+ epic: Schema.optional(EpicDelivery)
1488
+ },
1489
+ success: ShepherdOutput,
1490
+ run: ({ charge, at, fixRounds, revision, review: approval, epic }) =>
1491
+ Effect.gen(function* () {
1492
+ const { releaseWhen } = charge
1493
+
1494
+ const ship = yield* ask('ship', {
1495
+ prompt: `Merged at ${revision}. Release it now?`,
1496
+ options: [
1497
+ { value: 'Release', description: 'Starts Release on the merge: it gates, tags, publishes and deploys it.' },
1498
+ { value: 'Not now', description: 'Leaves the release to a person or a later Release.' }
1499
+ ],
1500
+ recommended: 'Release',
1501
+ recommendationReason: 'The merge is approved and green, so it is ready to ship.',
1502
+ default: 'Not now',
1503
+ auto: 'Release',
1504
+ evidence: evidenceAt(approval, revision),
1505
+ timeout: '1 hour'
1506
+ })
1114
1507
 
1115
- continue
1116
- }
1508
+ if (ship === 'Not now') return done(charge, at, fixRounds, 'merged', `Merged at ${revision}`, revision)
1509
+
1510
+ const releasing = yield* call('release', release, {
1511
+ revision,
1512
+ ...(approval === undefined ? undefined : { review: approval }),
1513
+ // Release resolves the same layers for the same Task; only this Run's own choice needs passing on.
1514
+ ...(releaseWhen.layer === 'run' ? { releaseTrigger: releaseWhen.trigger } : undefined),
1515
+ // A sub-task merged straight into the default branch ships past its unlanded epic; the epic's own merge
1516
+ // lands the epic, so its Release resolves the same layers.
1517
+ ...(epic !== undefined && epic.own !== true
1518
+ ? { deliveryTarget: 'default_branch' as const }
1519
+ : ownDeliveryTarget(charge))
1520
+ })
1117
1521
 
1118
- pushed = undefined
1522
+ // A failed gate changed nothing in production, and the next merge's Release gates this revision with its own.
1523
+ const handedOn =
1524
+ releasing.status === 'gate_failed' &&
1525
+ (yield* ask('release-gate-failed', {
1526
+ prompt: `Merged at ${revision}, but its Release gate failed: ${releasing.reason}`,
1527
+ options: [
1528
+ {
1529
+ value: 'Next Release',
1530
+ description: 'Leaves the revision to the next Release, which gates it with the next merge.'
1531
+ },
1532
+ { value: 'Taken over', description: 'A person looks at the failing checks from here.' }
1533
+ ],
1534
+ recommended: 'Next Release',
1535
+ recommendationReason:
1536
+ 'Nothing was tagged or deployed, and the gate already ran the failure again in a fresh checkout.',
1537
+ // No default: outside full auto a person decides.
1538
+ default: null,
1539
+ auto: 'Next Release'
1540
+ })) === 'Next Release'
1119
1541
 
1120
- // The round limit judges only the pipeline at the head the last fix left, so a push the read misses goes first.
1121
- if (fixedFrom !== undefined && pipeline.head !== fixedFrom.head) fixedFrom = undefined
1542
+ if (handedOn)
1543
+ return {
1544
+ ...done(
1545
+ charge,
1546
+ at,
1547
+ fixRounds,
1548
+ 'merged',
1549
+ `Merged at ${revision}; its Release gate failed, so the next Release ships it`,
1550
+ revision
1551
+ ),
1552
+ release: { runStatus: releasing.status, reason: releasing.reason }
1553
+ }
1122
1554
 
1123
- if (fixedFrom !== undefined) {
1124
- const found = yield* pushedByFix(cycle, pipeline, fixedFrom.changed)
1555
+ // It merged either way; a Release that did not deploy needs a person, unless it only published a candidate, was rejected, found it released or a person left it.
1556
+ if (
1557
+ releasing.leftUndeployed !== true &&
1558
+ releasing.status !== 'deployed' &&
1559
+ releasing.status !== 'published' &&
1560
+ releasing.status !== 'rejected' &&
1561
+ releasing.status !== 'gate_failed' &&
1562
+ releasing.status !== 'not_due' &&
1563
+ releasing.status !== 'nothing_to_release'
1564
+ )
1565
+ yield* ask('release-failed', {
1566
+ prompt: `Merged at ${revision}, but its Release ended ${releasing.status}: ${releasing.reason}`,
1567
+ options: [{ value: 'Taken over', description: 'A person looks at the release and production from here.' }],
1568
+ recommended: 'Taken over',
1569
+ recommendationReason: 'The merge is in, but production may not run it, or may be broken.',
1570
+ // No default: full auto runs unattended, and would take it at once and finish as merged.
1571
+ default: null
1572
+ })
1125
1573
 
1126
- if (found === 'unknown') {
1127
- if (++fixedFrom.looks < 3) continue
1574
+ return {
1575
+ ...done(charge, at, fixRounds, 'merged', `Merged at ${revision}; Release: ${releasing.reason}`, revision),
1576
+ release: {
1577
+ runStatus: releasing.status,
1578
+ reason: releasing.reason,
1579
+ ...(releasing.tag === undefined ? undefined : { tag: releasing.tag })
1580
+ }
1581
+ }
1582
+ })
1583
+ })
1128
1584
 
1129
- return done(
1130
- 'needs_you',
1131
- `The fix from ${fixedFrom.head} left a change, but the forge showed no pipeline on a new head after three looks`
1132
- )
1133
- }
1585
+ /** Starts a Backport of the merge to `branch`, and reports how it ended. */
1586
+ export const backportStarted = step('backportStarted', {
1587
+ payload: { charge: Charge, branch: Schema.String, auto: Schema.Boolean },
1588
+ key: ({ branch }) => branch,
1589
+ success: BackportStarted,
1590
+ run: ({ charge, branch, auto }) =>
1591
+ call('backport', backportLoop(), {
1592
+ mergedChangeRequestId: charge.changeRequestId,
1593
+ branch,
1594
+ ...(charge.merge
1595
+ ? { merge: true }
1596
+ : // Left for a person to merge, it stops once ready, so this Run and its offers do not wait on them.
1597
+ auto
1598
+ ? undefined
1599
+ : { hold: true })
1600
+ }).pipe(
1601
+ Effect.map(ended => ({ branch, status: ended.status, reason: ended.reason })),
1602
+ Effect.catchTags({
1603
+ ChildFailed: failed => Effect.succeed({ branch, status: 'failed', reason: failed.reason }),
1604
+ StepFailed: refused => Effect.succeed({ branch, status: 'refused', reason: refused.reason })
1605
+ })
1606
+ )
1607
+ })
1134
1608
 
1135
- if (found === 'nothing') fixedFrom = undefined
1136
- else if (found === 'pushed') continue
1137
- else return found
1138
- }
1609
+ const Backported = Schema.Struct({
1610
+ backports: Schema.optional(Schema.Array(BackportOffer)),
1611
+ backportsUnread: Schema.optional(Schema.String),
1612
+ backported: Schema.optional(Schema.Array(BackportStarted))
1613
+ })
1139
1614
 
1140
- const reviewedElsewhere =
1141
- pipeline.approved === pipeline.head || reviewedHeads.has(pipeline.head) || reuseTried.has(pipeline.head)
1142
- ? undefined
1143
- : pipeline.reviewed
1615
+ /**
1616
+ * After a merge, a Backport for each other live branch of the repository: started, all at once, for those `backportTo`
1617
+ * names, and offered for the rest, so none starts unless a person takes it.
1618
+ */
1619
+ export const backported = step('backported', {
1620
+ payload: { charge: Charge, backportTo: Schema.Array(Schema.String) },
1621
+ success: Backported,
1622
+ run: ({ charge, backportTo }) =>
1623
+ Effect.gen(function* () {
1624
+ const { changeRequestId } = charge
1625
+
1626
+ const live = yield* liveBranches('live-branches', { changeRequestId }).pipe(
1627
+ Effect.map(read => ({ branches: read.branches, unread: undefined })),
1628
+ Effect.catchTag('StepFailed', refused => Effect.succeed({ branches: [], unread: refused.reason }))
1629
+ )
1630
+
1631
+ if (live.unread !== undefined) return { backportsUnread: live.unread }
1632
+
1633
+ const automatic = new Set(backportTo)
1634
+ const offered = live.branches.filter(live => !automatic.has(live.branch))
1635
+
1636
+ const started = live.branches.filter(live => automatic.has(live.branch))
1637
+ const delivery = started.length === 0 || charge.merge ? undefined : (yield* runContext).team?.delivery
1638
+
1639
+ const backports = yield* Effect.forEach(
1640
+ started,
1641
+ ({ branch }) => backportStarted({ charge, branch, auto: delivery === 'auto' }),
1642
+ { concurrency: 'unbounded' }
1643
+ )
1644
+
1645
+ return {
1646
+ ...(offered.length === 0
1647
+ ? undefined
1648
+ : {
1649
+ backports: offered.map((live): BackportOffer => ({
1650
+ mergedChangeRequestId: changeRequestId,
1651
+ branch: live.branch,
1652
+ title: `Backport to ${live.branch}`,
1653
+ source: live.source
1654
+ }))
1655
+ }),
1656
+ ...(backports.length === 0 ? undefined : { backported: backports })
1657
+ }
1658
+ })
1659
+ })
1144
1660
 
1145
- // Read again, so this head's approval is what the gates below see.
1146
- if (reviewedElsewhere !== undefined && (yield* reuseReview(cycle, pipeline, reviewedElsewhere))) continue
1661
+ /**
1662
+ * The forge still shows an older head than the one a catch-up or a fix pushed, as it can for a while after the push:
1663
+ * nothing is gated on any head but the pushed one, so it looks again, and a person's push on top of it stops it for them.
1664
+ */
1665
+ export const pushShown = step('pushShown', {
1666
+ payload: {
1667
+ charge: Charge,
1668
+ at: Shepherding,
1669
+ pipeline: PipelineStatus,
1670
+ pushed: Schema.Struct({ head: Schema.String, stale: Schema.Int, by: Schema.String })
1671
+ },
1672
+ success: Schema.Union([Again, NeedsYou]),
1673
+ run: ({ charge, at, pipeline, pushed }) =>
1674
+ Effect.gen(function* () {
1675
+ const stale = pushed.stale + 1
1676
+
1677
+ if (stale > 5)
1678
+ return new NeedsYou({
1679
+ at,
1680
+ reason: `The forge still shows ${pipeline.head}, not ${pushed.head} that ${pushed.by} pushed`
1681
+ })
1147
1682
 
1148
- // Behind alone waits for the merge, which catches up while holding the turn: catching up any sooner is undone
1149
- // by every merge that lands before this one's turn. A failing pipeline catches up first, so a ci-fix never
1150
- // chases what the target already fixed.
1151
- const pipelineFailed = pipeline.status === 'failed' || pipeline.status === 'canceled'
1152
- const blocked = pipeline.conflicts === true || (pipeline.needsRebase === true && pipelineFailed)
1153
- const caughtUpHead = pipeline.head === pipelineFirst
1154
- // The forge runs no pipeline for this repository: its pipeline runs on a Runner and is reported to Kitman.
1155
- const onRunnerDue = pipeline.status === 'none' && pipeline.runnerChecks !== undefined
1683
+ // Only an Event since this read settles it, so the one that settled the last wait does not end it at once.
1684
+ yield* waitFor('pushed-again', {
1685
+ event: 'change_request.mergeable',
1686
+ filter: { changeRequestId: charge.changeRequestId, head: pushed.head },
1687
+ timeout: '1 minute',
1688
+ ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
1689
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
1156
1690
 
1157
- // Run this head's pipeline before reviewing it or catching up again.
1158
- if (onRunnerDue && (!blocked || caughtUpHead)) {
1159
- if (ranOnRunner.has(pipeline.head))
1160
- return done('needs_you', `The pipeline ran on the Runner at ${pipeline.head}, but no result was recorded`)
1161
- ranOnRunner.add(pipeline.head)
1691
+ return new Again({ at: { ...at, pushed: { ...pushed, stale } } })
1692
+ })
1693
+ })
1162
1694
 
1163
- const ran = yield* runOnRunner('run', cycle, pipeline.head, pipeline.runnerChecks ?? [])
1695
+ /** Runs the pipeline at `pipeline`'s head on the Runner, or waits for it, once: `Again` from the read after. */
1696
+ const lookedOnce = (charge: Charge, at: Shepherding, pipeline: PipelineStatus) =>
1697
+ Effect.map(lookOnce(charge, pipeline), ran =>
1698
+ 'failed' in ran
1699
+ ? new NeedsYou({ at, reason: `The pipeline could not run on the Runner: ${ran.failed}` })
1700
+ : new Again({ at, read: ran.pipeline })
1701
+ )
1164
1702
 
1165
- if ('failed' in ran) return done('needs_you', `The pipeline could not run on the Runner: ${ran.failed}`)
1703
+ /**
1704
+ * The forge says the head conflicts or needs its target merged in, though a sync already took the target in at it:
1705
+ * most likely the forge's answer for an older head, as GitLab works mergeability out after a push and shows the last
1706
+ * answer meanwhile. It looks again three times, then hands the ChangeRequest back, or stops a held Run for a person.
1707
+ */
1708
+ export const blockerRechecked = step('blockerRechecked', {
1709
+ payload: { charge: Charge, at: Shepherding, pipeline: PipelineStatus, blocker: Schema.String },
1710
+ success: Schema.Union([Again, ...Ended]),
1711
+ run: ({ charge, at: before, pipeline, blocker }) =>
1712
+ Effect.gen(function* () {
1713
+ const { head } = pipeline
1714
+ const rechecks = (before.blockerRechecks.find(entry => entry.head === head)?.rechecks ?? 0) + 1
1715
+
1716
+ const at = {
1717
+ ...before,
1718
+ blockerRechecks: [...before.blockerRechecks.filter(entry => entry.head !== head), { head, rechecks }]
1719
+ }
1166
1720
 
1167
- continue
1168
- }
1721
+ if (rechecks <= 3) {
1722
+ yield* waitFor('recheck', {
1723
+ event: 'change_request.mergeable',
1724
+ filter: { changeRequestId: charge.changeRequestId, head },
1725
+ timeout: '2 minutes',
1726
+ ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
1727
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
1169
1728
 
1170
- // A catch-up's head is reviewed once the forge shows it, not once the target stops moving, so the next clean
1171
- // catch-up carries its approval. A head that may merge on this read is read again after its approval, which the
1172
- // merge gates would otherwise not see.
1173
- const reviewing = yield* reviewCaughtUp(cycle, pipeline)
1729
+ return new Again({ at })
1730
+ }
1174
1731
 
1175
- if (reviewing?.kind === 'stop') return reviewing.output
1732
+ const still = `The forge still says ${head} ${blocker} after merging it in, and three more looks said the same`
1176
1733
 
1177
- const approvedHere = reviewing?.kind === 'approved' || reviewing?.kind === 'reviewed'
1734
+ if (charge.hold)
1735
+ return new NeedsYou({
1736
+ at,
1737
+ reason: `${still}; merging it in named no conflicting files`,
1738
+ ...(pipeline.conflicts === true ? { conflicts: [] } : undefined)
1739
+ })
1178
1740
 
1179
- if (reviewing?.kind === 'fixing' || (approvedHere && !blocked && pipeline.status === 'success')) continue
1741
+ return yield* handedBack({
1742
+ charge,
1743
+ at,
1744
+ reason: still,
1745
+ open: `Merge ${charge.target} into the branch and settle what conflicts.`
1746
+ })
1747
+ })
1748
+ })
1180
1749
 
1181
- // Wait for this head's running pipeline before catching up again.
1182
- if (blocked && !(pipeline.status === 'running' && caughtUpHead)) {
1183
- const blocker = pipeline.conflicts === true ? `conflicts with ${target}` : `needs ${target} merged in`
1184
- const targetHead = pipeline.target?.head
1750
+ /**
1751
+ * A failing pipeline at the head: it merges in a target that moved since the failure was found to be the target's, waits
1752
+ * out a target that fails the same checks, and otherwise finds a ci-fix due.
1753
+ */
1754
+ const failureWeighed = (charge: Charge, at: Shepherding, pipeline: PipelineStatus) =>
1755
+ Effect.gen(function* () {
1756
+ const { target } = charge
1757
+ const { head } = pipeline
1758
+ const { redTarget } = at
1759
+ const targetHead = pipeline.target?.head
1760
+
1761
+ // The target moved since its failure was found to be the target's: merge it in, which may mend it. Its head says
1762
+ // so where the forge gave it; else a merge into it does.
1763
+ const targetMoved =
1764
+ redTarget?.head === head &&
1765
+ (redTarget.targetHead !== undefined && pipeline.target !== undefined
1766
+ ? pipeline.target.head !== redTarget.targetHead
1767
+ : redTarget.moved)
1768
+
1769
+ if (targetMoved) return yield* caughtUp({ charge, at: { ...at, redTarget: undefined }, head, targetHead })
1770
+
1771
+ const onTarget = yield* targetChecked({ charge, pipeline })
1772
+ const failing = failingJobs(pipeline)
1773
+
1774
+ if (failing.length > 0 && failing.every(name => onTarget.failed.includes(name)))
1775
+ return yield* waitedOut({
1776
+ charge,
1777
+ at,
1778
+ pipeline,
1779
+ why: `${target} fails ${failing.join(', ')} at its own head too, so no fix here can mend it`
1780
+ })
1185
1781
 
1186
- const syncedAlready =
1187
- targetHead === undefined
1188
- ? blockerSynced.has(pipeline.head)
1189
- : syncedFor.has(syncedKey(pipeline.head, targetHead))
1782
+ // The target passes now what it failed, with nothing merged that this read shows: merge it in.
1783
+ if (onTarget.passed.length > 0 && redTarget?.head === head)
1784
+ return yield* caughtUp({ charge, at: { ...at, redTarget: undefined }, head, targetHead })
1190
1785
 
1191
- if (syncedAlready) {
1192
- // This head already took the target in, so the blocker is most likely the forge's answer for an older head:
1193
- // GitLab works mergeability out after a push and shows the last answer meanwhile. Look again before giving up.
1194
- const rechecks = (blockerRechecks.get(pipeline.head) ?? 0) + 1
1786
+ // Kitman could not check the target, and a ci-fix found its failure the target's: wait on, fixing nothing.
1787
+ if (redTarget?.head === head)
1788
+ return yield* waitedOut({ charge, at, pipeline, why: `${target} still fails as ${head} does` })
1195
1789
 
1196
- blockerRechecks.set(pipeline.head, rechecks)
1790
+ const stalls = at.stalledAt === head ? at.stalls + 1 : 0
1197
1791
 
1198
- if (rechecks <= 3) {
1199
- yield* waitFor(`recheck:${cycle}`, {
1200
- event: 'change_request.mergeable',
1201
- filter: { changeRequestId, head: pipeline.head },
1202
- timeout: '2 minutes',
1203
- ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
1204
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
1792
+ if (stalls >= 2)
1793
+ return new NeedsYou({
1794
+ at: { ...at, stalls },
1795
+ reason: `Two fixes pushed nothing new; the pipeline at ${head} still fails`
1796
+ })
1205
1797
 
1206
- continue
1207
- }
1798
+ // The fix takes a while, so the next Run waiting merges first.
1799
+ const fixing = yield* passTurn({ ...at, stalls, stalledAt: head })
1208
1800
 
1209
- return handBack(
1210
- `The forge still says ${pipeline.head} ${blocker} after merging it in, and three more looks said the same`,
1211
- `Merge ${target} into the branch and settle what conflicts.`
1212
- )
1213
- }
1801
+ return new CiFixDue({
1802
+ at: fixing,
1803
+ pipeline,
1804
+ onTarget,
1805
+ handBack: { reason: `The pipeline at ${head} still fails`, open: failedJobs(pipeline).join('\n\n') }
1806
+ })
1807
+ })
1214
1808
 
1215
- if (targetHead !== undefined) syncedFor.add(syncedKey(pipeline.head, targetHead))
1216
- blockerSynced.add(pipeline.head)
1217
- behind = false
1809
+ /** A review comment posted since `pipeline` was read, which goes round again to be read and answered. */
1810
+ const commentedSince = (charge: Charge, pipeline: PipelineStatus) => ({
1811
+ event: 'change_request.comment',
1812
+ filter: { changeRequestId: charge.changeRequestId },
1813
+ ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
1814
+ })
1218
1815
 
1219
- const stopped = yield* catchUp(cycle, targetHead, true)
1816
+ /**
1817
+ * Held, it stops once level with its target, green and approved, merging nothing: the target may have moved while it
1818
+ * answered threads and waited for the approval, so it reads the ChangeRequest again first.
1819
+ */
1820
+ export const heldReady = step('heldReady', {
1821
+ payload: { charge: Charge, at: Shepherding, head: Schema.String },
1822
+ success: Schema.Union([Again, NeedsYou, Ready]),
1823
+ run: ({ charge, at, head }) =>
1824
+ Effect.gen(function* () {
1825
+ const { target } = charge
1826
+ const again = yield* pipelineStatus('held', { changeRequestId: charge.changeRequestId, ...readsBehind(charge) })
1827
+
1828
+ if (again.head !== head || again.conflicts === true || again.needsRebase === true || again.behind === true)
1829
+ return new Again({ at, read: again })
1830
+
1831
+ const levelSaid = again.behind === undefined ? `Not known to be level with ${target}` : `Level with ${target}`
1832
+ const unapproved = unranOf(at, head)
1833
+
1834
+ if (unapproved !== undefined)
1835
+ return new NeedsYou({
1836
+ at,
1837
+ reason: `${levelSaid} and green at ${head}, reviewed with nothing blocking, but not approved: verify never ran ${unapproved.notRun.join('; ')}`
1838
+ })
1220
1839
 
1221
- if (stopped !== undefined) return stopped
1840
+ if (again.behind === undefined)
1841
+ return new NeedsYou({
1842
+ at,
1843
+ reason: `Green and approved at ${head}, but the forge could not say whether it is level with ${target}`
1844
+ })
1222
1845
 
1223
- continue
1224
- }
1846
+ return new Ready({ at, reason: `Level with ${target}, green and approved at ${head}; held, not merged` })
1847
+ })
1848
+ })
1225
1849
 
1226
- if (pipeline.status === 'none' || pipeline.status === 'running') {
1227
- yield* pipelineMoved(`wait:${cycle}`, changeRequestId, pipeline)
1850
+ /**
1851
+ * Merges the head of `pipeline` on its target's turn, once a person chose to merge a head whose review left it
1852
+ * unapproved and Kitman recorded that approval. A head pushed meanwhile, or a target that moved on, goes round again.
1853
+ */
1854
+ export const mergedOnTurn = step('mergedOnTurn', {
1855
+ payload: {
1856
+ charge: Charge,
1857
+ at: Shepherding,
1858
+ pipeline: PipelineStatus,
1859
+ approvedBy: Schema.optional(LoopEvent)
1860
+ },
1861
+ success: Schema.Union([Again, NeedsYou, Landed]),
1862
+ // What `landed` fails with past the refusals it settles here, as it always failed the Run.
1863
+ error: Schema.Union([PipelineFailed, PipelineCanceled, PipelineNotRun, Unapproved, Conflict]),
1864
+ run: ({ charge, at: before, pipeline, approvedBy }) =>
1865
+ Effect.gen(function* () {
1866
+ const { changeRequestId, target } = charge
1867
+ const { head } = pipeline
1868
+ const unapproved = unranOf(before, head)
1869
+
1870
+ const recorded =
1871
+ unapproved === undefined
1872
+ ? undefined
1873
+ : yield* approveChangeRequest('head-approve', {
1874
+ changeRequestId,
1875
+ head,
1876
+ summary: `A review of ${head} passed with nothing blocking; a person chose to merge it though verify never ran some of its tests.`,
1877
+ ...(unapproved.reuses === undefined
1878
+ ? unapproved.review === undefined
1879
+ ? undefined
1880
+ : { review: unapproved.review }
1881
+ : { reuses: unapproved.reuses })
1882
+ }).pipe(
1883
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
1884
+ )
1228
1885
 
1229
- continue
1230
- }
1886
+ if (recorded !== undefined && !recorded.approved)
1887
+ return new NeedsYou({
1888
+ at: before,
1889
+ reason: `The review of ${head} passed, but did not approve it: ${recorded.reason}`
1890
+ })
1231
1891
 
1232
- if (pipeline.status === 'failed' || pipeline.status === 'canceled') {
1233
- // The target moved since its failure was found to be the target's: merge it in, which may mend it. Its head
1234
- // says so where the forge gave it; else a merge into it does.
1235
- const targetMoved =
1236
- redTarget?.head === pipeline.head &&
1237
- (redTarget.targetHead !== undefined && pipeline.target !== undefined
1238
- ? pipeline.target.head !== redTarget.targetHead
1239
- : redTarget.moved)
1892
+ const approvedAt =
1893
+ recorded === undefined
1894
+ ? before
1895
+ : { ...before, approvalOf: [...before.approvalOf, { head, approval: recorded.reviewId }] }
1240
1896
 
1241
- if (targetMoved) {
1242
- redTarget = undefined
1897
+ // A Run ahead of it merges first; its merge moves the target, which this merge then finds and catches up with.
1898
+ const turn = yield* takeTurn(charge, approvedAt)
1243
1899
 
1244
- const stopped = yield* catchUp(cycle, pipeline.target?.head)
1900
+ if ('refused' in turn)
1901
+ return new NeedsYou({ at: approvedAt, reason: `The turn to merge into ${target} was refused: ${turn.refused}` })
1245
1902
 
1246
- if (stopped !== undefined) return stopped
1903
+ if (!approvedToMerge(charge, turn.at, head))
1904
+ return new NeedsYou({
1905
+ at: yield* passTurn(turn.at),
1906
+ reason: `The head moved to ${head} from ${charge.head ?? head}, the one approved to merge, so it was not merged`
1907
+ })
1247
1908
 
1248
- continue
1249
- }
1909
+ // Read on the turn, so nothing merges into the target between this read and the merge.
1910
+ if (charge.level === true) {
1911
+ const now = yield* pipelineStatus('level', { changeRequestId, behind: true })
1250
1912
 
1251
- const onTarget = yield* checkTarget(cycle, pipeline)
1252
- const failing = failingJobs(pipeline)
1913
+ if (now.head !== head) return new Again({ at: turn.at, read: now })
1253
1914
 
1254
- if (failing.length > 0 && failing.every(name => onTarget.failed.includes(name))) {
1255
- const stopped = yield* waitOutTarget(
1256
- cycle,
1257
- pipeline,
1258
- `${target} fails ${failing.join(', ')} at its own head too, so no fix here can mend it`
1259
- )
1915
+ if (now.behind === undefined)
1916
+ return new NeedsYou({
1917
+ at: yield* passTurn(turn.at),
1918
+ reason: `Green and approved at ${head}, but the forge could not say whether it is level with ${target}`
1919
+ })
1260
1920
 
1261
- if (stopped !== undefined) return stopped
1921
+ if (now.behind || now.conflicts === true || now.needsRebase === true)
1922
+ return new Again({ at: { ...turn.at, behind: true } })
1923
+ }
1262
1924
 
1263
- continue
1264
- }
1925
+ const merged = yield* landed({
1926
+ changeRequestId,
1927
+ agent: 'implementer',
1928
+ approve: () => Effect.void,
1929
+ ...(target === 'HEAD' ? undefined : { target }),
1930
+ read: pipeline,
1931
+ catchUp: false,
1932
+ ...(turn.at.repository === undefined ? undefined : { repository: turn.at.repository })
1933
+ }).pipe(Effect.catchTag('MergeRefused', refused => Effect.succeed(refused)))
1934
+
1935
+ if (merged._tag === 'MergeRefused' && merged.cause === 'turn')
1936
+ return new NeedsYou({ at: turn.at, reason: `The turn to merge into ${target} was refused: ${merged.reason}` })
1937
+
1938
+ // Its target moved on, with no Event to say so, or it conflicts: merge the target in, as for a not-mergeable one.
1939
+ if (merged._tag === 'MergeRefused')
1940
+ return new Again({ at: merged.cause === 'moved' ? turn.at : { ...turn.at, behind: true } })
1941
+
1942
+ const passed = yield* passTurn(turn.at)
1943
+
1944
+ return new Landed({
1945
+ at: passed,
1946
+ revision: merged.revision,
1947
+ review: approvalAt(passed, head) ?? approvalRef(approvedBy)
1948
+ })
1949
+ })
1950
+ })
1265
1951
 
1266
- // The target passes now what it failed, with nothing merged that this read shows: merge it in.
1267
- if (onTarget.passed.length > 0 && redTarget?.head === pipeline.head) {
1268
- redTarget = undefined
1952
+ /**
1953
+ * One look at the ChangeRequest: it reads its pipeline, and does what that read says is next. It runs the pipeline,
1954
+ * waits out a target that fails the same check or finds a ci-fix due, catches up with its target, answers its review
1955
+ * threads, gets its head approved or finds a head-fix due, and merges it on its target's turn. `Again` goes round once
1956
+ * more; a fix that is due goes back to `run`, whose rounds it counts against.
1957
+ */
1958
+ export const looked = step('looked', {
1959
+ payload: {
1960
+ charge: Charge,
1961
+ at: Shepherding,
1962
+ cycle: Schema.Int,
1963
+ read: Schema.optional(PipelineStatus).annotate({ description: 'The read the last look ended on.' })
1964
+ },
1965
+ success: Schema.Union([Again, Landed, CiFixDue, Wanted, ...Ended]),
1966
+ error: mergedOnTurn.errorSchema,
1967
+ run: ({ charge, at: begun, cycle, read }) =>
1968
+ Effect.gen(function* () {
1969
+ const { changeRequestId, target, hold } = charge
1970
+ const goal = hold ? 'getting it level, green and approved' : 'landing it'
1971
+ const looks = cycle - 1
1972
+
1973
+ const goOn =
1974
+ cycle > charge.maxCycles
1975
+ ? yield* ask('continue', {
1976
+ prompt: `Shepherd has looked at this ChangeRequest ${looks} times without ${goal}. Keep going?`,
1977
+ options: ['Keep going', 'Stop'],
1978
+ recommended: 'Stop',
1979
+ recommendationReason: `${looks} looks have not ${hold ? 'held it ready' : 'landed it'}, so something needs a person rather than another look.`,
1980
+ default: 'Stop',
1981
+ timeout: '1 hour'
1982
+ })
1983
+ : undefined
1269
1984
 
1270
- const stopped = yield* catchUp(cycle, pipeline.target?.head)
1985
+ if (goOn === 'Stop') return new NeedsYou({ at: begun, reason: `Stopped after ${looks} looks without ${goal}` })
1271
1986
 
1272
- if (stopped !== undefined) return stopped
1987
+ // The answer can come an hour later, so the look reads again.
1988
+ const pipeline =
1989
+ (goOn === undefined ? read : undefined) ??
1990
+ (yield* pipelineStatus('pipeline', { changeRequestId, ...readsBehind(charge) }))
1273
1991
 
1274
- continue
1275
- }
1992
+ const { head } = pipeline
1993
+ const known = { ...begun, repository: pipeline.repository ?? begun.repository }
1276
1994
 
1277
- // Kitman could not check the target, and a ci-fix found its failure the target's: wait on, fixing nothing.
1278
- if (redTarget?.head === pipeline.head) {
1279
- const stopped = yield* waitOutTarget(cycle, pipeline, `${target} still fails as ${pipeline.head} does`)
1995
+ if (known.pushed !== undefined && head !== known.pushed.head)
1996
+ return yield* pushShown({ charge, at: known, pipeline, pushed: known.pushed }).pipe(endedOn(charge, known))
1280
1997
 
1281
- if (stopped !== undefined) return stopped
1998
+ // The round limit judges only the pipeline at the head the last fix left, so a push the read misses goes first.
1999
+ const current = {
2000
+ ...known,
2001
+ pushed: undefined,
2002
+ fixedFrom: known.fixedFrom?.head === head ? known.fixedFrom : undefined
2003
+ }
1282
2004
 
1283
- continue
1284
- }
2005
+ const seen =
2006
+ current.fixedFrom === undefined
2007
+ ? new Onward({ at: current })
2008
+ : yield* pushSeen({ charge, at: current, pipeline, fixedFrom: current.fixedFrom }).pipe(
2009
+ endedOn(charge, current)
2010
+ )
1285
2011
 
1286
- if (stalledAt === pipeline.head) stalls++
1287
- else stalls = 0
2012
+ if (seen._tag !== 'Onward') return seen
1288
2013
 
1289
- if (stalls >= 2)
1290
- return done('needs_you', `Two fixes pushed nothing new; the pipeline at ${pipeline.head} still fails`)
2014
+ const reviewedElsewhere =
2015
+ pipeline.approved === head || seen.at.reviewedHeads.includes(head) || seen.at.reuseTried.includes(head)
2016
+ ? undefined
2017
+ : pipeline.reviewed
1291
2018
 
1292
- if (!(yield* mayFix('ci-fix', cycle, `the failing pipeline at ${pipeline.head}`)))
1293
- return handBack(
1294
- `The pipeline at ${pipeline.head} still fails after ${rounds['ci-fix']} ci-fix rounds`,
1295
- failedJobs(pipeline).join('\n\n')
2019
+ // Read again, so this head's approval is what the gates below see.
2020
+ const reusing =
2021
+ reviewedElsewhere === undefined
2022
+ ? seen
2023
+ : yield* reviewReused({ charge, at: seen.at, pipeline, reviewed: reviewedElsewhere }).pipe(
2024
+ endedOn(charge, seen.at)
1296
2025
  )
1297
- stalledAt = pipeline.head
1298
- yield* passTurn()
1299
-
1300
- const fixed = yield* agentWork(`ci-fix:${cycle}`, {
1301
- agent: 'implementer',
1302
- prompt: ciFixPrompt(pipeline, target, onTarget),
1303
- output: CiFix,
1304
- timeout: stepBudget
2026
+
2027
+ if (reusing._tag !== 'Onward') return reusing
2028
+
2029
+ // Behind alone waits for the merge, which catches up while holding the turn: catching up any sooner is undone by
2030
+ // every merge that lands before this one's turn. A held Run, which never merges, catches up at once. A failing
2031
+ // pipeline catches up first, so a ci-fix never chases what the target already fixed.
2032
+ const pipelineFailed = pipeline.status === 'failed' || pipeline.status === 'canceled'
2033
+ const heldBehind = hold && (pipeline.needsRebase === true || pipeline.behind === true)
2034
+ const blocked = pipeline.conflicts === true || (pipeline.needsRebase === true && pipelineFailed) || heldBehind
2035
+ const caughtUpHead = head === reusing.at.pipelineFirst
2036
+ // The forge runs no pipeline for this repository: its pipeline runs on a Runner and is reported to Kitman.
2037
+ const onRunnerDue = pipeline.status === 'none' && pipeline.runnerChecks !== undefined
2038
+
2039
+ // Run this head's pipeline before reviewing it or catching up again.
2040
+ if (onRunnerDue && (!blocked || caughtUpHead)) {
2041
+ if (reusing.at.ranOnRunner.includes(head))
2042
+ return new NeedsYou({
2043
+ at: reusing.at,
2044
+ reason: `The pipeline ran on the Runner at ${head}, but no result was recorded`
1305
2045
  })
1306
2046
 
1307
- // Only a round that fixed something counts: one that found the target's failure or a flake changed nothing.
1308
- if (fixed.verdict === 'fixed') {
1309
- rounds['ci-fix']++
1310
- fixedFrom = { head: pipeline.head, changed: true, looks: 0 }
1311
- }
2047
+ const running = { ...reusing.at, ranOnRunner: [...reusing.at.ranOnRunner, head] }
1312
2048
 
1313
- if (fixed.verdict === 'pre_existing') {
1314
- const stopped = yield* waitOutTarget(
1315
- cycle,
1316
- pipeline,
1317
- `the failure is pre-existing on the target branch: ${fixed.summary}`
1318
- )
2049
+ return yield* lookedOnce(charge, running, pipeline).pipe(endedOn(charge, running))
2050
+ }
1319
2051
 
1320
- if (stopped !== undefined) return stopped
2052
+ // A catch-up's head is reviewed once the forge shows it, not once the target stops moving, so the next clean
2053
+ // catch-up carries its approval. A head that may merge on this read is read again after its approval, which the
2054
+ // merge gates would otherwise not see.
2055
+ const shownAt = { ...reusing.at, reviewOnceShown: undefined }
2056
+
2057
+ const shown =
2058
+ reusing.at.reviewOnceShown !== head
2059
+ ? new Onward({ at: shownAt })
2060
+ : shownAt.unreviewed !== undefined
2061
+ ? yield* filesReviewed({ charge, at: shownAt, pipeline, files: shownAt.unreviewed }).pipe(
2062
+ endedOn(charge, shownAt)
2063
+ )
2064
+ : shownAt.notCarried !== undefined && pipeline.approved !== head
2065
+ ? yield* headReviewed({
2066
+ charge,
2067
+ at: shownAt,
2068
+ pipeline,
2069
+ which: 'the head its catch-up merge pushed'
2070
+ }).pipe(endedOn(charge, shownAt))
2071
+ : new Onward({ at: shownAt })
2072
+
2073
+ if (shown._tag !== 'Onward' && shown._tag !== 'Passed' && shown._tag !== 'Left') return shown
2074
+
2075
+ if (shown._tag === 'Passed' && shown.approved && !blocked && pipeline.status === 'success')
2076
+ return new Again({ at: shown.at })
2077
+
2078
+ // Wait for this head's running pipeline before catching up again.
2079
+ if (blocked && !(pipeline.status === 'running' && caughtUpHead)) {
2080
+ const blocker = pipeline.conflicts === true ? `conflicts with ${target}` : `needs ${target} merged in`
2081
+ const targetHead = pipeline.target?.head
1321
2082
 
1322
- continue
1323
- }
2083
+ const syncedAlready =
2084
+ targetHead === undefined
2085
+ ? shown.at.blockerSynced.includes(head)
2086
+ : shown.at.syncedFor.includes(syncedKey(head, targetHead))
1324
2087
 
1325
- if (fixed.verdict === 'flaky') {
1326
- if (pipeline.source === 'reported') {
1327
- // Only a pipeline that runs on the Runner can be run again; nothing on the forge can run a report.
1328
- if (pipeline.runnerChecks === undefined)
1329
- return done('needs_you', `The failing job passed when run again, outside the forge: ${fixed.summary}`)
2088
+ if (syncedAlready)
2089
+ return yield* blockerRechecked({ charge, at: shown.at, pipeline, blocker }).pipe(endedOn(charge, shown.at))
1330
2090
 
1331
- if (reranHeads.has(pipeline.head))
1332
- return done('needs_you', `The failing job failed again when run again on the Runner: ${fixed.summary}`)
1333
- reranHeads.add(pipeline.head)
2091
+ const syncing = {
2092
+ ...shown.at,
2093
+ syncedFor:
2094
+ targetHead === undefined ? shown.at.syncedFor : withAdded(shown.at.syncedFor, syncedKey(head, targetHead)),
2095
+ blockerSynced: withAdded(shown.at.blockerSynced, head),
2096
+ behind: false
2097
+ }
1334
2098
 
1335
- const ran = yield* runOnRunner('rerun', cycle, pipeline.head, pipeline.runnerChecks)
2099
+ return yield* caughtUp({ charge, at: syncing, head, targetHead, forBlocker: true }).pipe(
2100
+ endedOn(charge, syncing)
2101
+ )
2102
+ }
1336
2103
 
1337
- if ('failed' in ran) return done('needs_you', `The pipeline could not run on the Runner: ${ran.failed}`)
2104
+ if (pipeline.status === 'none' || pipeline.status === 'running')
2105
+ return yield* lookedOnce(charge, shown.at, pipeline).pipe(endedOn(charge, shown.at))
1338
2106
 
1339
- continue
1340
- }
2107
+ if (pipelineFailed) return yield* failureWeighed(charge, shown.at, pipeline).pipe(endedOn(charge, shown.at))
1341
2108
 
1342
- if (reranHeads.has(pipeline.head))
1343
- return done('needs_you', `The failing job failed again when run again on the forge: ${fixed.summary}`)
1344
- reranHeads.add(pipeline.head)
1345
- yield* rerunPipeline(`rerun:${cycle}`, { changeRequestId })
1346
- // Until the forge reports the rerun, a read still shows the failure it reran.
1347
- yield* pipelineMoved(`rerun-wait:${cycle}`, changeRequestId, pipeline).pipe(
1348
- Effect.catchTag('WaitTimedOut', () => Effect.void)
1349
- )
1350
- }
2109
+ const answering = { ...shown.at, redTarget: undefined }
2110
+ const replied = yield* answered({ charge, at: answering }).pipe(endedOn(charge, answering))
1351
2111
 
1352
- continue
1353
- }
2112
+ if (replied._tag !== 'Onward') return replied
1354
2113
 
1355
- redTarget = undefined
2114
+ const mergeable = yield* waitFor('mergeable', {
2115
+ event: 'change_request.mergeable',
2116
+ filter: { changeRequestId },
2117
+ timeout: '1 hour',
2118
+ or: [commentedSince(charge, pipeline)]
2119
+ }).pipe(endedOn(charge, replied.at))
1356
2120
 
1357
- const threads = (yield* reviewThreads(`threads:${cycle}`, { changeRequestId })).threads.filter(
1358
- thread => !answered.has(threadKey(thread))
1359
- )
2121
+ if ('_tag' in mergeable) return mergeable
1360
2122
 
1361
- if (threads.length > 0) {
1362
- yield* passTurn()
2123
+ if (mergeable.type === 'change_request.comment') return new Again({ at: replied.at })
1363
2124
 
1364
- const answers = yield* agentWork(`comments:${cycle}`, {
1365
- agent: 'implementer',
1366
- prompt: repliesPrompt(threads),
1367
- output: Replies,
1368
- timeout: stepBudget
1369
- })
2125
+ // GitLab says `need_rebase` for a branch behind its target; the merge finds that and catches up on its turn, and
2126
+ // a held Run catches up now.
2127
+ if (
2128
+ (mergeable.payload.mergeable === false && (hold || mergeable.payload.mergeState !== 'need_rebase')) ||
2129
+ replied.at.behind
2130
+ ) {
2131
+ const catching = { ...replied.at, behind: false }
1370
2132
 
1371
- for (const answer of answers.replies) {
1372
- yield* comment(`reply:${cycle}:${answer.threadId}`, {
1373
- changeRequestId,
1374
- threadId: answer.threadId,
1375
- body: answer.reply
1376
- })
1377
- replies++
1378
- }
2133
+ return yield* caughtUp({ charge, at: catching, head, targetHead: pipeline.target?.head }).pipe(
2134
+ endedOn(charge, catching)
2135
+ )
2136
+ }
1379
2137
 
1380
- for (const thread of threads) answered.add(`${thread.id}:${thread.comments.length + 1}`)
2138
+ // Its own review approved a head only while this read still shows the approval: a request for changes takes it
2139
+ // back.
2140
+ const approvedBefore =
2141
+ replied.at.reviewedHeads.includes(head) &&
2142
+ (pipeline.approved === head || unranOf(replied.at, head) !== undefined)
2143
+
2144
+ const files =
2145
+ replied.at.unreviewed === undefined
2146
+ ? new Onward({ at: replied.at })
2147
+ : yield* filesReviewed({ charge, at: replied.at, pipeline, files: replied.at.unreviewed }).pipe(
2148
+ endedOn(charge, replied.at)
2149
+ )
1381
2150
 
1382
- if (answers.replies.some(answer => answer.changed)) continue
1383
- }
2151
+ if (files._tag !== 'Onward' && files._tag !== 'Passed') return files
2152
+
2153
+ const reviewedHere = approvedBefore || (files._tag === 'Passed' && files.approved)
2154
+
2155
+ // A newer head's finished pipeline goes round again, to gate that head and wait for its own approval. A reported
2156
+ // pipeline has no forge run to finish on a push, so an approval of a newer head goes round instead.
2157
+ const moved =
2158
+ pipeline.readAt === undefined
2159
+ ? []
2160
+ : [
2161
+ { event: 'change_request.pipeline', filter: { changeRequestId }, since: pipeline.readAt },
2162
+ ...(pipeline.source === 'reported'
2163
+ ? [
2164
+ {
2165
+ event: 'change_request.approval',
2166
+ filter: { changeRequestId, approved: true },
2167
+ since: pipeline.readAt
2168
+ }
2169
+ ]
2170
+ : [])
2171
+ ]
2172
+
2173
+ // Held, it waits for approval holding the branch, so a conflict Kitman records goes round to settle it here.
2174
+ const conflicted = hold ? [{ event: 'delivery.conflicted', filter: { changeRequestId } }] : []
2175
+
2176
+ const approval = {
2177
+ event: 'change_request.approval',
2178
+ // An approval of an earlier commit does not approve the one whose pipeline passed.
2179
+ filter: { changeRequestId, approved: true, head },
2180
+ or: [commentedSince(charge, pipeline), ...moved, ...conflicted]
2181
+ }
1384
2182
 
1385
- // A review comment posted since this look began goes round again, to be read and answered.
1386
- const commented = {
1387
- event: 'change_request.comment',
1388
- filter: { changeRequestId },
1389
- ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
1390
- }
2183
+ // Kitman's approval of the head settles this at once, as Build's of the head it shipped does. A forge approval
2184
+ // is no Kitman review, so it waits behind the question below, which a full-auto Team answers with a Review.
2185
+ const byKitman = <Wait extends { readonly event: string; readonly filter: object }>(wait: Wait) =>
2186
+ wait.event === 'change_request.approval' ? { ...wait, filter: { ...wait.filter, source: 'kitman' } } : wait
2187
+
2188
+ const kitmanApproval =
2189
+ reviewedHere || files.at.leftToPerson.includes(head)
2190
+ ? undefined
2191
+ : yield* waitFor('approved', {
2192
+ ...byKitman(approval),
2193
+ or: approval.or.map(byKitman),
2194
+ timeout: '1 minute'
2195
+ }).pipe(
2196
+ Effect.map(woke =>
2197
+ woke.type === 'change_request.approval' && woke.payload.source !== 'kitman' ? undefined : woke
2198
+ ),
2199
+ Effect.catchTag('WaitTimedOut', () => Effect.undefined),
2200
+ endedOn(charge, files.at)
2201
+ )
1391
2202
 
1392
- const mergeable = yield* waitFor(`mergeable:${cycle}`, {
1393
- event: 'change_request.mergeable',
1394
- filter: { changeRequestId },
1395
- timeout: '1 hour',
1396
- or: [commented]
1397
- })
2203
+ if (kitmanApproval !== undefined && '_tag' in kitmanApproval) return kitmanApproval
1398
2204
 
1399
- if (mergeable.type === commented.event) continue
2205
+ const headReview =
2206
+ !reviewedHere && kitmanApproval === undefined
2207
+ ? yield* headReviewed({ charge, at: files.at, pipeline, which: 'the head whose pipeline passed' }).pipe(
2208
+ endedOn(charge, files.at)
2209
+ )
2210
+ : new Onward({ at: files.at })
1400
2211
 
1401
- // GitLab says `need_rebase` for a branch behind its target; the merge finds that and catches up on its turn.
1402
- if ((mergeable.payload.mergeable === false && mergeable.payload.mergeState !== 'need_rebase') || behind) {
1403
- behind = false
2212
+ if (headReview._tag !== 'Onward' && headReview._tag !== 'Passed' && headReview._tag !== 'Left') return headReview
1404
2213
 
1405
- const stopped = yield* catchUp(cycle, pipeline.target?.head)
2214
+ const { at } = headReview
1406
2215
 
1407
- if (stopped !== undefined) return stopped
2216
+ const approvedBy =
2217
+ headReview._tag === 'Left'
2218
+ ? yield* waitFor('approval', { ...approval, timeout: '7 days' }).pipe(endedOn(charge, at))
2219
+ : kitmanApproval
1408
2220
 
1409
- continue
1410
- }
2221
+ if (approvedBy !== undefined && '_tag' in approvedBy) return approvedBy
1411
2222
 
1412
- // Its own review approved a head only while this read still shows the approval: a request for changes takes it back.
1413
- let reviewedHere =
1414
- reviewedHeads.has(pipeline.head) && (pipeline.approved === pipeline.head || unranAt.has(pipeline.head))
2223
+ if (approvedBy !== undefined && approvedBy.type !== 'change_request.approval') return new Again({ at })
1415
2224
 
1416
- if (unreviewed !== undefined) {
1417
- const reviewing = yield* reviewMergedFiles(cycle, pipeline, unreviewed)
2225
+ // The approval of a newer head woke a wait on a reported pipeline: that head needs its own pipeline first.
2226
+ if (pipeline.source === 'reported' && approvedBy !== undefined && approvedBy.payload.head !== head)
2227
+ return new Again({ at })
1418
2228
 
1419
- if (reviewing.kind === 'stop') return reviewing.output
2229
+ if (hold) return yield* heldReady({ charge, at, head }).pipe(endedOn(charge, at))
1420
2230
 
1421
- if (reviewing.kind === 'fixing') continue
2231
+ const unapproved = unranOf(at, head)
2232
+ const notRun = unapproved?.notRun ?? charge.notRun ?? []
1422
2233
 
1423
- if (reviewing.kind === 'approved') reviewedHere = true
1424
- }
2234
+ // A head with tests verify never ran merges only on a person's say.
2235
+ const merge =
2236
+ charge.merge && notRun.length === 0
2237
+ ? 'Merge'
2238
+ : yield* ask('merge', {
2239
+ prompt:
2240
+ notRun.length === 0
2241
+ ? 'The ChangeRequest is approved, green and mergeable. Merge now?'
2242
+ : `The ChangeRequest is ${unapproved === undefined ? 'approved' : 'reviewed with nothing blocking but not approved'}, green and mergeable, but verify never ran some of its tests:\n${notRun.map(item => `- ${item}`).join('\n')}\n\nMerge now?`,
2243
+ options: [
2244
+ { value: 'Merge', description: 'Merges the head whose pipeline passed.' },
2245
+ { value: 'Wait', description: 'Leaves the merge to a person.' }
2246
+ ],
2247
+ recommended: notRun.length === 0 ? 'Merge' : 'Wait',
2248
+ recommendationReason:
2249
+ notRun.length === 0
2250
+ ? 'It is approved, green and mergeable, which is everything a merge waits for.'
2251
+ : 'Nobody has seen those tests pass, so run them by hand before it lands.',
2252
+ default: 'Wait',
2253
+ // A full-auto Team merges what its Review approved and its checks passed.
2254
+ ...(notRun.length === 0
2255
+ ? { auto: 'Merge', evidence: evidenceAt(approvalAt(at, head) ?? approvalRef(approvedBy), head) }
2256
+ : undefined),
2257
+ timeout: '1 hour'
2258
+ })
1425
2259
 
1426
- // A newer head's finished pipeline goes round again, to gate that head and wait for its own approval. A
1427
- // reported pipeline has no forge run to finish on a push, so an approval of a newer head goes round instead.
1428
- const moved =
1429
- pipeline.readAt === undefined
1430
- ? []
1431
- : [
1432
- { event: 'change_request.pipeline', filter: { changeRequestId }, since: pipeline.readAt },
1433
- ...(pipeline.source === 'reported'
1434
- ? [
1435
- {
1436
- event: 'change_request.approval',
1437
- filter: { changeRequestId, approved: true },
1438
- since: pipeline.readAt
1439
- }
1440
- ]
1441
- : [])
1442
- ]
1443
-
1444
- const approval = {
1445
- event: 'change_request.approval',
1446
- // An approval of an earlier commit does not approve the one whose pipeline passed.
1447
- filter: { changeRequestId, approved: true, head: pipeline.head },
1448
- or: [commented, ...moved]
1449
- }
2260
+ if (merge === 'Wait')
2261
+ return yield* targetWatched({
2262
+ charge,
2263
+ at,
2264
+ pipeline,
2265
+ ready:
2266
+ unapproved === undefined
2267
+ ? 'Approved, green and mergeable; left for a person to merge'
2268
+ : 'Reviewed, green and mergeable, but verify never ran some of its tests; left for a person to merge'
2269
+ }).pipe(endedOn(charge, at))
2270
+
2271
+ // A head pushed while waiting has passed nothing this look checked, so it goes round again.
2272
+ return yield* mergedOnTurn({ charge, at, pipeline, approvedBy }).pipe(endedOn(charge, at))
2273
+ }).pipe(endedOn(charge, begun))
2274
+ })
1450
2275
 
1451
- // Kitman's approval of the head settles this at once, as Build's of the head it shipped does. A forge approval
1452
- // is no Kitman review, so it waits behind the question below, which a full-auto Team answers with a Review.
1453
- const byKitman = <Wait extends { readonly event: string; readonly filter: object }>(wait: Wait) =>
1454
- wait.event === 'change_request.approval' ? { ...wait, filter: { ...wait.filter, source: 'kitman' } } : wait
1455
-
1456
- let approved =
1457
- reviewedHere || leftToPerson.has(pipeline.head)
1458
- ? undefined
1459
- : yield* waitFor(`approved:${cycle}`, {
1460
- ...byKitman(approval),
1461
- or: approval.or.map(byKitman),
1462
- timeout: '1 minute'
1463
- }).pipe(
1464
- Effect.map(woke =>
1465
- woke.type === 'change_request.approval' && woke.payload.source !== 'kitman' ? undefined : woke
1466
- ),
1467
- Effect.catchTag('WaitTimedOut', () => Effect.undefined)
1468
- )
2276
+ /** What a head-fix round leaves the next look: what it fixed, for the review of what it pushed, and its start. */
2277
+ const headFixedAt = (wanted: Wanted, changed: boolean): Shepherding => {
2278
+ const { at, head, findings, files, scope } = wanted
2279
+ const fixedFrom = { head, changed, looks: 0 }
1469
2280
 
1470
- if (!reviewedHere && approved === undefined) {
1471
- const reviewing = yield* reviewHead(cycle, pipeline, 'the head whose pipeline passed')
2281
+ return files === undefined
2282
+ ? { ...at, headFindings: findings, headFindingsAt: head, headScope: scope, fixedFrom }
2283
+ : { ...at, unreviewed: { ...files, earlier: findings, reviewed: head }, fixedFrom }
2284
+ }
1472
2285
 
1473
- if (reviewing.kind === 'stop') return reviewing.output
2286
+ /**
2287
+ * Takes an open ChangeRequest to merge, one look at a time: it waits on its Events with no model time between them,
2288
+ * fixes a pipeline the branch broke (after ruling out a flake and a target branch that fails the same check, which it
2289
+ * waits out), answers each new review thread on the thread, merges the target branch in when it is behind, and merges
2290
+ * once approved, green and mergeable when told to or when a person says so. A branch the forge says conflicts, or is
2291
+ * behind with a failing pipeline, merges its target in before any pipeline is run or fixed; one that is only behind
2292
+ * catches up when its merge finds it behind, on its turn. One whose merge Shepherd cannot settle goes back to Build. It
2293
+ * merges the target in and merges only while it holds the target's turn, so ChangeRequests for one target land one at a
2294
+ * time, in order. A head with a passed Review of the whole change that any Run recorded, such as the Build that shipped
2295
+ * it, is approved with that Review instead of being reviewed again. A head nobody approved gets a review of what changed
2296
+ * since the last approved head, and the head a catch-up pushed gets its pipeline started and its review as soon as the
2297
+ * forge shows it, not once its pipeline passes. It runs one ci-fix and two head-fix rounds, each judged by the pipeline
2298
+ * at the head the last fix pushed, then hands the ChangeRequest back to Build, and stops as needs you, with why, instead
2299
+ * of spinning. Left for a person to merge, it watches the target for up to a week, runs the repository's checks that
2300
+ * read the target again at the head each time the target moves, and catches up when they fail, as when the target
2301
+ * gained a migration the head's own does not build on. After merging it starts Release only when its release trigger is
2302
+ * `merge`; under a Milestone or Project trigger that completion starts Release instead, and under `manual` a person, a
2303
+ * Schedule or a Loop does. Then it offers a Backport for each other live branch of the repository, and starts one for
2304
+ * each its `backportTo` names. A Team can turn on starting it when the forge fails the pipeline of a ChangeRequest that
2305
+ * delivers a Task. With `hold` it does all of this but merge: it catches up a ChangeRequest that is only behind too,
2306
+ * and stops as `ready` once level, green and approved, with no merge Question; a conflict it cannot settle stops it as
2307
+ * needs you rather than going back to Build.
2308
+ */
2309
+ export default defineLoop({
2310
+ id: 'shepherd',
2311
+ version: '2.0.0',
2312
+ title: 'Shepherd',
2313
+ description:
2314
+ 'Takes an open ChangeRequest to merge: catches it up, fixes its pipeline, gets it approved and merges it.',
2315
+ input: Input,
2316
+ output: Output,
2317
+ agents: { implementer: 'implementer' },
2318
+ checkout: 'write',
2319
+ when: [
2320
+ {
2321
+ event: 'change_request.pipeline',
2322
+ filter: { status: 'failed', source: 'forge', linked: true },
2323
+ input: { changeRequestId: 'changeRequestId', taskId: 'taskId' },
2324
+ optIn: true
2325
+ }
2326
+ ],
2327
+ capabilities: [
2328
+ 'agent_work',
2329
+ 'read_change_request',
2330
+ 'post_comment',
2331
+ 'merge_change_request',
2332
+ 'approve_change_request',
2333
+ 'call',
2334
+ 'write_back',
2335
+ 'ask',
2336
+ 'verify',
2337
+ 'claim'
2338
+ ],
2339
+ calls: (): readonly CalledLoop[] => [review, release, landEpic, backport],
2340
+ offers: [
2341
+ { id: 'build', title: 'Hand back to Build', loop: 'build', from: 'handBack' },
2342
+ { id: 'backport', title: 'Backport', loop: 'backport', from: 'backports' }
2343
+ ],
2344
+ run: input =>
2345
+ Effect.gen(function* () {
2346
+ const { continuing, releaseTrigger: releaseWhen } = yield* runContext
2347
+
2348
+ const charge: Charge = {
2349
+ changeRequestId: input.changeRequestId,
2350
+ target: continuing?.targetBranch ?? input.branch ?? 'HEAD',
2351
+ hold: input.hold === true,
2352
+ merge: input.merge === true,
2353
+ ...(input.level === true ? { level: true } : undefined),
2354
+ ...(input.head === undefined ? undefined : { head: input.head.toLowerCase() }),
2355
+ taskId: input.taskId,
2356
+ notRun: input.notRun,
2357
+ maxCycles: input.maxCycles ?? 20,
2358
+ releaseWhen,
2359
+ deliversTo: input.deliversTo
2360
+ }
1474
2361
 
1475
- if (reviewing.kind === 'fixing') continue
2362
+ // The rounds of each kind it took, and how many it may take, which a person raises a round at a time.
2363
+ let rounds = noRounds
2364
+ let limits: Rounds = roundLimits
2365
+ let next: Again | Landed | Ended = new Again({ at: unshepherded })
2366
+
2367
+ for (let cycle = 1; next._tag === 'Again'; cycle++) {
2368
+ const look: Again | Landed | CiFixDue | Wanted | Ended = yield* looked({
2369
+ charge,
2370
+ at: next.at,
2371
+ cycle,
2372
+ read: next.read
2373
+ })
1476
2374
 
1477
- if (reviewing.kind === 'left')
1478
- approved = yield* waitFor(`approval:${cycle}`, { ...approval, timeout: '7 days' })
2375
+ if (look._tag !== 'CiFixDue' && look._tag !== 'Wanted') {
2376
+ next = look
2377
+ continue
1479
2378
  }
1480
2379
 
1481
- if (approved !== undefined && approved.type !== 'change_request.approval') continue
2380
+ const kind: RoundKind = look._tag === 'CiFixDue' ? 'ci-fix' : 'head-fix'
2381
+
2382
+ const round: RoundTaken | RoundsSpent = yield* roundAllowed({
2383
+ kind,
2384
+ taken: rounds[kind],
2385
+ limit: limits[kind],
2386
+ standing:
2387
+ look._tag === 'CiFixDue'
2388
+ ? `the failing pipeline at ${look.pipeline.head}`
2389
+ : look.findings
2390
+ .filter(isBlocking)
2391
+ .map(finding => finding.id)
2392
+ .join(', ')
2393
+ })
1482
2394
 
1483
- // The approval of a newer head woke a wait on a reported pipeline: that head needs its own pipeline first.
1484
- if (pipeline.source === 'reported' && approved !== undefined && approved.payload.head !== pipeline.head)
2395
+ if (round._tag === 'RoundsSpent') {
2396
+ next = yield* handedBack({
2397
+ charge,
2398
+ at: look.at,
2399
+ ...look.handBack,
2400
+ reason: `${look.handBack.reason} after ${rounds[kind]} ${kind} rounds`
2401
+ })
1485
2402
  continue
2403
+ }
1486
2404
 
1487
- const unapproved = unranAt.get(pipeline.head)
1488
- const notRun = unapproved?.notRun ?? input.notRun ?? []
1489
-
1490
- const approvedBy = () => approvalOf.get(pipeline.head) ?? approvalRef(approved)
2405
+ limits = withCount(limits, kind, round.limit)
1491
2406
 
1492
- /** What full auto relies on to take its answer: the approval of the ChangeRequest head, and `head`. */
1493
- const evidenceAt = (head: string) => {
1494
- const review = approvedBy()
2407
+ // A head-fix round counts once it is allowed.
2408
+ if (look._tag === 'Wanted') {
2409
+ rounds = withCount(rounds, 'head-fix', rounds['head-fix'] + 1)
1495
2410
 
1496
- return { ...(review === undefined ? undefined : { review }), head }
2411
+ next = yield* headFixed({
2412
+ subject: look.subject,
2413
+ blocking: look.findings.filter(isBlocking),
2414
+ files: look.files !== undefined
2415
+ }).pipe(
2416
+ Effect.map(fix => new Again({ at: headFixedAt(look, fix.changed) })),
2417
+ endedOn(charge, look.at)
2418
+ )
2419
+ continue
1497
2420
  }
1498
2421
 
1499
- // A head with tests verify never ran merges only on a person's say.
1500
- const merge =
1501
- input.merge === true && notRun.length === 0
1502
- ? 'Merge'
1503
- : yield* ask(`merge:${cycle}`, {
1504
- prompt:
1505
- notRun.length === 0
1506
- ? 'The ChangeRequest is approved, green and mergeable. Merge now?'
1507
- : `The ChangeRequest is ${unapproved === undefined ? 'approved' : 'reviewed with nothing blocking but not approved'}, green and mergeable, but verify never ran some of its tests:\n${notRun.map(item => `- ${item}`).join('\n')}\n\nMerge now?`,
1508
- options: [
1509
- { value: 'Merge', description: 'Merges the head whose pipeline passed.' },
1510
- { value: 'Wait', description: 'Leaves the merge to a person.' }
1511
- ],
1512
- recommended: notRun.length === 0 ? 'Merge' : 'Wait',
1513
- recommendationReason:
1514
- notRun.length === 0
1515
- ? 'It is approved, green and mergeable, which is everything a merge waits for.'
1516
- : 'Nobody has seen those tests pass, so run them by hand before it lands.',
1517
- default: 'Wait',
1518
- // A full-auto Team merges what its Review approved and its checks passed.
1519
- ...(notRun.length === 0 ? { auto: 'Merge', evidence: evidenceAt(pipeline.head) } : undefined),
1520
- timeout: '1 hour'
1521
- })
1522
-
1523
- if (merge === 'Wait') {
1524
- const watched = yield* watchTarget(
1525
- cycle,
1526
- pipeline,
1527
- done(
1528
- 'ready',
1529
- unapproved === undefined
1530
- ? 'Approved, green and mergeable; left for a person to merge'
1531
- : 'Reviewed, green and mergeable, but verify never ran some of its tests; left for a person to merge'
1532
- )
1533
- )
2422
+ const { at, pipeline, onTarget }: CiFixDue = look
1534
2423
 
1535
- if (watched.kind === 'stop') return watched.output
2424
+ const fixed: typeof CiFix.Type | Ended = yield* ciFixed({ target: charge.target, pipeline, onTarget }).pipe(
2425
+ endedOn(charge, at)
2426
+ )
1536
2427
 
2428
+ if (!('verdict' in fixed)) {
2429
+ next = fixed
1537
2430
  continue
1538
2431
  }
1539
2432
 
1540
- if (unapproved !== undefined) {
1541
- const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
1542
- changeRequestId,
1543
- head: pipeline.head,
1544
- summary: `A review of ${pipeline.head} passed with nothing blocking; a person chose to merge it though verify never ran some of its tests.`,
1545
- ...('reuses' in unapproved ? { reuses: unapproved.reuses } : { review: unapproved.review })
1546
- }).pipe(
1547
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
1548
- )
1549
-
1550
- if (!recorded.approved)
1551
- return done(
1552
- 'needs_you',
1553
- `The review of ${pipeline.head} passed, but did not approve it: ${recorded.reason}`
1554
- )
1555
-
1556
- approvalOf.set(pipeline.head, recorded.reviewId)
2433
+ // A ci-fix round counts only once it fixed something: one that found the target's failure or a flake changed
2434
+ // nothing.
2435
+ if (fixed.verdict === 'fixed') {
2436
+ rounds = withCount(rounds, 'ci-fix', rounds['ci-fix'] + 1)
2437
+ next = new Again({ at: { ...at, fixedFrom: { head: pipeline.head, changed: true, looks: 0 } } })
2438
+ continue
1557
2439
  }
1558
2440
 
1559
- // A Run ahead of it merges first; its merge moves the target, which this merge then finds and catches up with.
1560
- const refused = yield* takeTurn()
2441
+ next =
2442
+ fixed.verdict === 'pre_existing'
2443
+ ? yield* waitedOut({
2444
+ charge,
2445
+ at,
2446
+ pipeline,
2447
+ why: `the failure is pre-existing on the target branch: ${fixed.summary}`
2448
+ }).pipe(endedOn(charge, at))
2449
+ : yield* reran({ charge, at, pipeline, summary: fixed.summary }).pipe(endedOn(charge, at))
2450
+ }
1561
2451
 
1562
- if (refused !== undefined) return done('needs_you', `The turn to merge into ${target} was refused: ${refused}`)
2452
+ const fixRounds = rounds['ci-fix'] + rounds['head-fix']
1563
2453
 
1564
- // Only the head whose pipeline passed is merged: one pushed while waiting goes round again.
1565
- const merged = yield* mergeChangeRequest(`merge-change-request:${cycle}`, {
1566
- changeRequestId,
1567
- head: pipeline.head
1568
- })
2454
+ const { target } = charge
2455
+ const epic = epicOf(input)
1569
2456
 
1570
- // Its target moved on, with no Event to say so, or it conflicts: merge the target in, as for a not-mergeable one.
1571
- if (merged.status === 'conflict') behind = true
2457
+ // A sub-task's merge into its epic branch, by Shepherd or a person, reaches the others with the epic's own.
2458
+ const backports =
2459
+ input.offersBackports === false || (epic !== undefined && target === epic.branch)
2460
+ ? Effect.succeed({})
2461
+ : backported({ charge, backportTo: input.backportTo ?? [] })
1572
2462
 
1573
- if (merged.status !== 'merged') continue
1574
- yield* passTurn()
1575
- yield* writeBack('write-back', { milestone: 'merged' })
2463
+ if (next._tag !== 'Landed' && next._tag !== 'MergedElsewhere') return outputOf(charge, next, fixRounds)
1576
2464
 
1577
- // A sub-task lands on its epic's branch, which only the epic's own ChangeRequest takes to Release.
1578
- if (epic !== undefined && target === epic.branch) {
1579
- const landing = yield* landEpicAfter(epic)
2465
+ if (next._tag === 'MergedElsewhere') {
2466
+ yield* passTurn(next.at)
1580
2467
 
1581
- return {
1582
- ...done(
1583
- 'merged',
1584
- `Merged into ${epic.branch} at ${merged.revision}; Release waits for epic ${epic.key} to land on ${epic.defaultBranch}`
1585
- ),
1586
- epicLanding: landing
1587
- }
1588
- }
2468
+ return { ...(yield* backports), ...done(charge, next.at, fixRounds, 'merged', next.reason) }
2469
+ }
1589
2470
 
1590
- const defaultBranch = input.continuing?.defaultBranch
2471
+ const { at, revision, review: approval } = next
1591
2472
 
1592
- if (defaultBranch !== undefined && target !== defaultBranch)
1593
- return done(
1594
- 'merged',
1595
- `Merged into ${target} at ${merged.revision}, not into ${defaultBranch}: nothing is released until it reaches ${defaultBranch}`
1596
- )
2473
+ yield* writeBack('write-back', { milestone: 'merged' })
1597
2474
 
1598
- // A Milestone's or Project's completion starts its Release; this merge does not, unless the Run says so.
1599
- if (releaseWhen !== undefined && releaseWhen.trigger !== 'merge')
1600
- return done(
2475
+ // A sub-task lands on its epic's branch, which only the epic's own ChangeRequest takes to Release.
2476
+ if (epic !== undefined && target === epic.branch)
2477
+ return {
2478
+ ...done(
2479
+ charge,
2480
+ at,
2481
+ fixRounds,
1601
2482
  'merged',
1602
- `Merged at ${merged.revision}; Release runs when its ${releaseWhen.trigger === 'milestone' ? 'Milestone' : 'Project'} is done, as ${layerWords[releaseWhen.layer]} says`
1603
- )
1604
-
1605
- const ship = yield* ask('ship', {
1606
- prompt: `Merged at ${merged.revision}. Release it now?`,
1607
- options: [
1608
- { value: 'Release', description: 'Starts Release on the merge: it gates, tags, publishes and deploys it.' },
1609
- { value: 'Not now', description: 'Leaves the release to a person or a later Release.' }
1610
- ],
1611
- recommended: 'Release',
1612
- recommendationReason: 'The merge is approved and green, so it is ready to ship.',
1613
- default: 'Not now',
1614
- auto: 'Release',
1615
- evidence: evidenceAt(merged.revision),
1616
- timeout: '1 hour'
1617
- })
1618
-
1619
- if (ship === 'Not now') return done('merged', `Merged at ${merged.revision}`)
1620
-
1621
- const review = approvedBy()
2483
+ `Merged into ${epic.branch} at ${revision}; Release waits for epic ${epic.key} to land on ${epic.defaultBranch}`,
2484
+ revision
2485
+ ),
2486
+ epicLanding: yield* epicLanded({ charge, landing: epic, repository: at.repository })
2487
+ }
1622
2488
 
1623
- const released = yield* call('release', release, {
1624
- revision: merged.revision,
1625
- ...(review === undefined ? undefined : { review }),
1626
- // Release resolves the same layers for the same Task; only this Run's own choice needs passing on.
1627
- ...(releaseWhen?.layer === 'run' ? { releaseTrigger: releaseWhen.trigger } : undefined),
1628
- // A sub-task merged straight into the default branch ships past its unlanded epic; the epic's own merge
1629
- // lands the epic, so its Release resolves the same layers.
1630
- ...(epic !== undefined && epic.own !== true
1631
- ? { deliveryTarget: 'default_branch' as const }
1632
- : ownDeliveryTarget(input))
1633
- })
2489
+ const defaultBranch = continuing?.defaultBranch
1634
2490
 
1635
- // A failed gate changed nothing in production, and the next merge's Release gates this revision with its own.
1636
- const handedOn =
1637
- released.status === 'gate_failed' &&
1638
- (yield* ask('release-gate-failed', {
1639
- prompt: `Merged at ${merged.revision}, but its Release gate failed: ${released.reason}`,
1640
- options: [
1641
- {
1642
- value: 'Next Release',
1643
- description: 'Leaves the revision to the next Release, which gates it with the next merge.'
1644
- },
1645
- { value: 'Taken over', description: 'A person looks at the failing checks from here.' }
1646
- ],
1647
- recommended: 'Next Release',
1648
- recommendationReason:
1649
- 'Nothing was tagged or deployed, and the gate already ran the failure again in a fresh checkout.',
1650
- // No default: outside full auto a person decides.
1651
- default: null,
1652
- auto: 'Next Release'
1653
- })) === 'Next Release'
1654
-
1655
- if (handedOn)
1656
- return {
1657
- ...done('merged', `Merged at ${merged.revision}; its Release gate failed, so the next Release ships it`),
1658
- release: { runStatus: released.status, reason: released.reason }
1659
- }
2491
+ if (defaultBranch !== undefined && target !== defaultBranch)
2492
+ return {
2493
+ ...(yield* backports),
2494
+ ...done(
2495
+ charge,
2496
+ at,
2497
+ fixRounds,
2498
+ 'merged',
2499
+ `Merged into ${target} at ${revision}, not into ${defaultBranch}: nothing is released until it reaches ${defaultBranch}`,
2500
+ revision
2501
+ )
2502
+ }
1660
2503
 
1661
- // It merged either way; a Release that did not deploy needs a person, unless it only published a candidate, was rejected, found it released or a person left it.
1662
- if (
1663
- released.leftUndeployed !== true &&
1664
- released.status !== 'deployed' &&
1665
- released.status !== 'published' &&
1666
- released.status !== 'rejected' &&
1667
- released.status !== 'gate_failed' &&
1668
- released.status !== 'not_due' &&
1669
- released.status !== 'nothing_to_release'
1670
- )
1671
- yield* ask('release-failed', {
1672
- prompt: `Merged at ${merged.revision}, but its Release ended ${released.status}: ${released.reason}`,
1673
- options: [{ value: 'Taken over', description: 'A person looks at the release and production from here.' }],
1674
- recommended: 'Taken over',
1675
- recommendationReason: 'The merge is in, but production may not run it, or may be broken.',
1676
- // No default: full auto runs unattended, and would take it at once and finish as merged.
1677
- default: null
1678
- })
2504
+ // A Milestone's or Project's completion starts its Release; this merge does not, unless the Run says so.
2505
+ const releases = releasesOn(releaseWhen)
1679
2506
 
2507
+ if (releases !== 'merge')
1680
2508
  return {
1681
- ...done('merged', `Merged at ${merged.revision}; Release: ${released.reason}`),
1682
- release: {
1683
- runStatus: released.status,
1684
- reason: released.reason,
1685
- ...(released.tag === undefined ? undefined : { tag: released.tag })
1686
- }
2509
+ ...(yield* backports),
2510
+ ...done(
2511
+ charge,
2512
+ at,
2513
+ fixRounds,
2514
+ 'merged',
2515
+ `Merged at ${revision}; Release runs ${releaseWhenWords[releases]}, as ${layerWords[releaseWhen.layer]} says`,
2516
+ revision
2517
+ )
1687
2518
  }
2519
+
2520
+ return {
2521
+ ...(yield* released({ charge, at, fixRounds, revision, review: approval, epic })),
2522
+ ...(yield* backports)
1688
2523
  }
1689
- }).pipe(
1690
- Effect.catchIf(
1691
- (error): error is Extract<typeof error, { readonly _tag: 'StepFailed' }> =>
1692
- error._tag === 'StepFailed' && (isUnansweredQuestion(error.reason) || error.reason.includes('time budget')),
1693
- error =>
1694
- Effect.succeed(
1695
- // An unanswered Question's reason carries the agent's own words, which may mention a time budget.
1696
- isUnansweredQuestion(error.reason)
1697
- ? handBack(`Step "${error.step}" stopped on a Question nobody answers in full auto`, error.reason)
1698
- : done('needs_you', `Step "${error.step}" ran past its ${stepBudget} budget`)
1699
- )
1700
- ),
1701
- Effect.catchTags({
1702
- WaitTimedOut: timedOut =>
1703
- Effect.succeed(
1704
- done(
1705
- 'needs_you',
1706
- timedOut.event === 'change_request.approval' && notCarried !== undefined
1707
- ? `Nobody approved the head after ${notCarried}`
1708
- : `Nothing happened on the ChangeRequest while waiting for ${timedOut.event}`
1709
- )
1710
- ),
1711
- ChangeRequestClosed: ended =>
1712
- Effect.succeed(
1713
- ended.merged
1714
- ? done('merged', 'Someone else merged the ChangeRequest')
1715
- : done('needs_you', 'The ChangeRequest was closed')
1716
- )
1717
- })
1718
- )
1719
- }
2524
+ })
1720
2525
  })