@kitman-sh/software-engineering 0.10.68 → 0.10.70

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
@@ -4,10 +4,14 @@ import {
4
4
  ask,
5
5
  call,
6
6
  type CalledLoop,
7
+ claim,
8
+ type Claim,
7
9
  comment,
8
10
  Continuing,
9
11
  defineLoop,
12
+ letGo,
10
13
  mergeChangeRequest,
14
+ note,
11
15
  pipelineMoved,
12
16
  pipelineStatus,
13
17
  reportPipeline,
@@ -35,6 +39,13 @@ const reviewLoop = () => ({ id: 'review', input: ReviewInput, output: ReviewOutp
35
39
  /** The model time one fix or round of replies may take before a person looks. */
36
40
  const stepBudget = '45 minutes'
37
41
 
42
+ /** Rounds of each kind a Run takes before it asks whether to hand the ChangeRequest back to Build. */
43
+ const roundLimits = { 'ci-fix': 1, 'head-fix': 2 } as const
44
+
45
+ type RoundKind = keyof typeof roundLimits
46
+
47
+ const handBackAnswer = 'Hand back to Build'
48
+
38
49
  const Input = Schema.Struct({
39
50
  /** The open ChangeRequest to see through to merge; the Run works on its branch. */
40
51
  changeRequestId: Schema.String,
@@ -45,8 +56,6 @@ const Input = Schema.Struct({
45
56
  branch: Schema.optional(Schema.String),
46
57
  /** The ChangeRequest's branch and target, as Kitman puts the Run on it. */
47
58
  continuing: Schema.optional(Continuing),
48
- /** Rounds of fixing a failed pipeline before it stops as needs you; 3 when left out. */
49
- maxFixRounds: Schema.optional(Schema.Int),
50
59
  /** Times it looks at the ChangeRequest before asking whether to go on; 20 when left out. */
51
60
  maxCycles: Schema.optional(Schema.Int)
52
61
  })
@@ -82,14 +91,46 @@ const failedJobs = (pipeline: PipelineStatus) =>
82
91
  : []
83
92
  )
84
93
 
85
- const ciFixPrompt = (pipeline: PipelineStatus, target: string) =>
86
- [
94
+ const failingJobs = (pipeline: PipelineStatus) =>
95
+ pipeline.jobs.flatMap(job => (job.status === 'failed' ? [job.name] : []))
96
+
97
+ /** The failing checks the head of the target branch fails too, and those it passes; any other is not known. */
98
+ type OnTarget = { readonly failed: readonly string[]; readonly passed: readonly string[] }
99
+
100
+ const ciFixPrompt = (pipeline: PipelineStatus, target: string, onTarget: OnTarget) => {
101
+ const unknown = failingJobs(pipeline).filter(
102
+ name => !onTarget.failed.includes(name) && !onTarget.passed.includes(name)
103
+ )
104
+
105
+ return [
87
106
  `The pipeline at ${pipeline.head} failed. These jobs failed, with the end of each log:`,
88
107
  ...failedJobs(pipeline),
89
108
  'Run the failing job once more here to rule out a flake; if it passes, change nothing and answer flaky.',
90
- `Then run it on the target branch (a worktree of \`origin/${target}\`, which Kitman fetched just before this Step; do not fetch). If it fails there too, the branch did not cause it: change nothing and answer pre_existing.`,
109
+ ...(onTarget.passed.length === 0
110
+ ? []
111
+ : [
112
+ `Kitman ran ${onTarget.passed.join(', ')} at the head of \`origin/${target}\` and they passed there, so do not run them on the target branch.`
113
+ ]),
114
+ ...(onTarget.failed.length === 0
115
+ ? []
116
+ : [
117
+ `${onTarget.failed.join(', ')} fail at the head of \`origin/${target}\` too: they are the target's to fix, so leave them as they are.`
118
+ ]),
119
+ ...(unknown.length === 0
120
+ ? []
121
+ : [
122
+ `Run ${unknown.join(', ')} on the target branch (a worktree of \`origin/${target}\`, which Kitman fetched just before this Step; do not fetch). If every failing job fails there too, the branch did not cause it: change nothing and answer pre_existing.`
123
+ ]),
91
124
  "Otherwise it is this branch's own failure: write or fix a test that shows it first, then fix it, and answer fixed. Kitman pushes what you leave."
92
125
  ].join('\n\n')
126
+ }
127
+
128
+ /** A claim's resource name for the turn to merge into `target`, on `repository` when the read named it. */
129
+ const turnResource = (target: string, repository: string | undefined) =>
130
+ `merge:${repository === undefined ? '' : `${repository}:`}${target}`
131
+ .toLowerCase()
132
+ .replace(/[^a-z0-9._:-]+/g, '-')
133
+ .slice(0, 128)
93
134
 
94
135
  const threadLine = (thread: ReviewThreads['threads'][number]) =>
95
136
  [
@@ -99,10 +140,13 @@ const threadLine = (thread: ReviewThreads['threads'][number]) =>
99
140
 
100
141
  const ReviewFix = Schema.Struct({ summary: Schema.String })
101
142
 
143
+ const findingLines = (findings: readonly MergedFinding[]) =>
144
+ findings.map(finding => `- ${finding.id} (${finding.severity}): ${finding.detail}`).join('\n')
145
+
102
146
  const reviewFixPrompt = (reviewed: string, findings: readonly MergedFinding[]) =>
103
147
  [
104
148
  `A review of ${reviewed} found these. Fix each blocker and major finding, with a test that shows it where one can. Kitman pushes what you leave.`,
105
- ...findings.map(finding => `- ${finding.id} (${finding.severity}): ${finding.detail}`)
149
+ findingLines(findings)
106
150
  ].join('\n')
107
151
 
108
152
  type CatchUp = NonNullable<Extract<BaseSync, { readonly status: 'merged' }>['catchUp']>
@@ -138,13 +182,16 @@ const threadKey = (thread: ReviewThreads['threads'][number]) => `${thread.id}:${
138
182
 
139
183
  /**
140
184
  * Takes an open ChangeRequest to merge: it waits on its Events with no model time between them, fixes a pipeline the
141
- * branch broke (after ruling out a flake and the target branch), answers each new review thread on the thread, merges
142
- * the target branch in on a conflict, and merges once approved, green and mergeable when told to or when a person
143
- * says so. It stops as needs you, with why, instead of spinning.
185
+ * branch broke (after ruling out a flake and a target branch that fails the same check, which it waits out), answers
186
+ * each new review thread on the thread, merges the target branch in when it is behind, and merges once approved, green
187
+ * and mergeable when told to or when a person says so. It merges the target in and merges only while it holds the
188
+ * target's turn, so ChangeRequests for one target land one at a time, in order. A head nobody approved gets a review
189
+ * of what changed since the last approved head. It runs one ci-fix and two head-fix rounds, then hands the
190
+ * ChangeRequest back to Build, and stops as needs you, with why, instead of spinning.
144
191
  */
145
192
  export default defineLoop({
146
193
  id: 'shepherd',
147
- version: '1.1.0',
194
+ version: '1.2.0',
148
195
  title: 'Shepherd',
149
196
  input: Input,
150
197
  output: Output,
@@ -159,9 +206,11 @@ export default defineLoop({
159
206
  'call',
160
207
  'write_back',
161
208
  'ask',
162
- 'verify'
209
+ 'verify',
210
+ 'claim'
163
211
  ],
164
212
  calls: (): readonly CalledLoop[] => [review, release],
213
+ offers: [{ id: 'build', title: 'Hand back to Build', loop: 'build', from: 'handBack' }],
165
214
  run: input => {
166
215
  const changeRequestId = input.changeRequestId
167
216
  // The ChangeRequest's own target: an offer's `branch` may be the offering Run's branch, which is this one.
@@ -173,7 +222,9 @@ export default defineLoop({
173
222
  const leftToPerson = new Set<string>()
174
223
  /** The last review of an unapproved head's open findings, for the review of the head that fixes them. */
175
224
  let headFindings: readonly MergedFinding[] = []
176
- let fixRounds = 0
225
+ const rounds: Record<RoundKind, number> = { 'ci-fix': 0, 'head-fix': 0 }
226
+ /** Rounds past the limit a person allowed. */
227
+ const allowed: Record<RoundKind, number> = { 'ci-fix': 0, 'head-fix': 0 }
177
228
  let replies = 0
178
229
  let stalledAt: string | undefined
179
230
  let stalls = 0
@@ -196,7 +247,90 @@ export default defineLoop({
196
247
  /** The head a catch-up merge pushed, until the forge shows it, and how many reads showed another. */
197
248
  let pushed: { readonly head: string; stale: number } | undefined
198
249
 
199
- const done = (status: Output['status'], reason: string): Output => ({ status, reason, fixRounds, replies })
250
+ /** The target's turn: held from the sync before the merge until the merge, so one ChangeRequest merges at a time. */
251
+ let turn: Claim | undefined
252
+ let turns = 0
253
+ let passes = 0
254
+ let repository: string | undefined
255
+
256
+ /**
257
+ * The head whose failure the target branch shares, the target's head then, and whether anything merged into the
258
+ * target since.
259
+ */
260
+ let redTarget: { readonly head: string; readonly targetHead: string | undefined; moved: boolean } | undefined
261
+
262
+ const fixRounds = () => rounds['ci-fix'] + rounds['head-fix']
263
+
264
+ const done = (status: Output['status'], reason: string): Output => ({
265
+ status,
266
+ reason,
267
+ fixRounds: fixRounds(),
268
+ replies
269
+ })
270
+
271
+ const handBack = (reason: string, open: string): Output => ({
272
+ ...done('handed_back', reason),
273
+ handBack: {
274
+ changeRequestId,
275
+ words: `Shepherd handed ChangeRequest ${changeRequestId} back: ${reason}. Fix it forward on its branch:\n${open}`,
276
+ ...(input.taskId === undefined ? undefined : { taskId: input.taskId }),
277
+ // Build's target, over the offer's default of this Run's branch, which is the ChangeRequest's own.
278
+ ...(target === 'HEAD' ? undefined : { branch: target })
279
+ }
280
+ })
281
+
282
+ /** Takes the target's turn, waiting for any Run ahead; why not, when it was left to another. */
283
+ const takeTurn = () =>
284
+ Effect.gen(function* () {
285
+ if (turn !== undefined) return undefined
286
+
287
+ return yield* claim(`turn:${++turns}`, { resource: turnResource(target, repository) }).pipe(
288
+ Effect.map(granted => {
289
+ turn = granted
290
+
291
+ return undefined
292
+ }),
293
+ Effect.catchTag('StepFailed', error => Effect.succeed(error.reason))
294
+ )
295
+ })
296
+
297
+ /** Gives the target's turn to the next Run waiting, before work that takes a while or once merged. */
298
+ const passTurn = () =>
299
+ Effect.gen(function* () {
300
+ if (turn === undefined) return
301
+ const held = turn
302
+
303
+ turn = undefined
304
+ yield* letGo(`pass-turn:${++passes}`, held)
305
+ })
306
+
307
+ /** Whether another round of `kind` may run: past its limit, only when a person says so. */
308
+ const mayFix = (kind: RoundKind, cycle: number, open: string) =>
309
+ Effect.gen(function* () {
310
+ if (rounds[kind] < roundLimits[kind] + allowed[kind]) return true
311
+
312
+ const answer = yield* ask(`rounds:${cycle}`, {
313
+ prompt: `Shepherd has run ${rounds[kind]} ${kind} rounds, its limit, and ${open} still stands. Hand the ChangeRequest back to Build?`,
314
+ options: [
315
+ {
316
+ value: handBackAnswer,
317
+ description: 'Stops here; the ChangeRequest stays open, with a Build offer that carries what is open.'
318
+ },
319
+ { value: 'One more round', description: `Runs one more ${kind} round here.` }
320
+ ],
321
+ recommended: handBackAnswer,
322
+ recommendationReason:
323
+ 'More rounds here have not settled it, and Build fixes and reviews the change as a whole.',
324
+ default: handBackAnswer,
325
+ // A full-auto Team stops the loop rather than going round again.
326
+ auto: handBackAnswer,
327
+ timeout: '1 hour'
328
+ })
329
+
330
+ if (answer !== handBackAnswer) allowed[kind]++
331
+
332
+ return answer !== handBackAnswer
333
+ })
200
334
 
201
335
  /** Runs the repository's pipeline on a Runner at `head` and reports it; the reason when it could not run. */
202
336
  const runOnRunner = (step: 'run' | 'rerun', cycle: number, head: string, checks: readonly string[]) =>
@@ -217,6 +351,131 @@ export default defineLoop({
217
351
  return failed
218
352
  })
219
353
 
354
+ /**
355
+ * How the head of the target branch does on the failing checks: the forge's own checks on it, and the rest of the
356
+ * repository's Runner checks run there on a Runner.
357
+ */
358
+ const checkTarget = (cycle: number, pipeline: PipelineStatus) =>
359
+ Effect.gen(function* () {
360
+ const failing = failingJobs(pipeline)
361
+ const onForge = (pipeline.target?.jobs ?? []).filter(job => failing.includes(job.name))
362
+ const failed = onForge.flatMap(job => (job.status === 'failed' ? [job.name] : []))
363
+ const passed = onForge.flatMap(job => (job.status === 'success' ? [job.name] : []))
364
+
365
+ const onRunner = failing.filter(
366
+ name => !failed.includes(name) && !passed.includes(name) && (pipeline.runnerChecks ?? []).includes(name)
367
+ )
368
+
369
+ if (onRunner.length === 0) return { failed, passed }
370
+
371
+ const atTarget = yield* verify(`target-check:${cycle}`, {
372
+ revision: `origin/${target}`,
373
+ checks: onRunner
374
+ }).pipe(Effect.catchTag('StepFailed', () => Effect.undefined))
375
+
376
+ const ran = atTarget?.checks.filter(check => onRunner.includes(check.name)) ?? []
377
+
378
+ return {
379
+ failed: [...failed, ...ran.flatMap(check => (check.status === 'failed' ? [check.name] : []))],
380
+ passed: [...passed, ...ran.flatMap(check => (check.status === 'passed' ? [check.name] : []))]
381
+ }
382
+ })
383
+
384
+ /** Records why it waits rather than fixing, then waits for something to merge into the target. */
385
+ const waitOutTarget = (cycle: number, pipeline: PipelineStatus, why: string) =>
386
+ Effect.gen(function* () {
387
+ yield* passTurn()
388
+ yield* note(`target-red:${cycle}`, {
389
+ text: `Shepherd is waiting for ${target} to change instead of fixing ${pipeline.head}: ${why}`
390
+ }).pipe(Effect.catchTag('StepFailed', () => Effect.void))
391
+
392
+ const woke = yield* waitFor(`target-moved:${cycle}`, {
393
+ event: 'change_request.closed',
394
+ filter: {
395
+ merged: true,
396
+ ...(target === 'HEAD' ? undefined : { targetBranch: target }),
397
+ ...(repository === undefined ? undefined : { repository })
398
+ },
399
+ or: [{ event: 'change_request.closed', filter: { changeRequestId } }],
400
+ timeout: '1 hour',
401
+ ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
402
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
403
+
404
+ if (woke?.payload.changeRequestId === changeRequestId)
405
+ return woke.payload.merged === true
406
+ ? done('merged', 'Someone else merged the ChangeRequest')
407
+ : done('needs_you', 'The ChangeRequest was closed')
408
+
409
+ redTarget = { head: pipeline.head, targetHead: pipeline.target?.head, moved: woke !== undefined }
410
+
411
+ return undefined
412
+ })
413
+
414
+ /**
415
+ * Merges the target branch in while holding its turn, and carries the approval to the head it pushes when the merge
416
+ * left the branch's own change as it was; the Output to stop with, when it cannot.
417
+ */
418
+ const catchUp = (cycle: number) =>
419
+ Effect.gen(function* () {
420
+ const refused = yield* takeTurn()
421
+
422
+ if (refused !== undefined) return done('needs_you', `The turn to merge into ${target} was refused: ${refused}`)
423
+
424
+ const synced = yield* syncBase(`sync:${cycle}`, { agent: 'implementer', target })
425
+
426
+ if (synced.status === 'conflict')
427
+ return done('needs_you', `Merging ${target} in conflicts on ${synced.files.join(', ')}: ${synced.reason}`)
428
+
429
+ if (synced.status !== 'merged') return undefined
430
+ const caught = synced.catchUp
431
+
432
+ const verdict =
433
+ caught === undefined
434
+ ? ({ kind: 'changed', why: 'its Runner did not report what it did to the branch' } as const)
435
+ : catchUpVerdict(caught)
436
+
437
+ if (verdict.kind === 'changed') {
438
+ unreviewed = undefined
439
+ notCarried = `merging ${target} in changed it: ${verdict.why}`
440
+ } else if (caught !== undefined && unreviewed !== undefined) {
441
+ const files = [...new Set([...unreviewed.files, ...(verdict.kind === 'review' ? verdict.files : [])])]
442
+
443
+ // With no fix since the files' merge, the review need not cover this merge's target commits; otherwise
444
+ // `since` keeps covering the fixes, and this merge with them.
445
+ unreviewed =
446
+ caught.from === unreviewed.synced ? { ...unreviewed, files, synced: caught.head } : { ...unreviewed, files }
447
+ } else if (caught !== undefined && verdict.kind === 'review') {
448
+ notCarried = undefined
449
+ unreviewed = { files: verdict.files, synced: caught.head, sync: `sync:${cycle}`, earlier: [] }
450
+ } else if (caught !== undefined) {
451
+ notCarried = undefined
452
+
453
+ const carried = yield* approveChangeRequest(`carry:${cycle}`, {
454
+ changeRequestId,
455
+ head: caught.head,
456
+ summary: `Merging ${target} in left the branch's own diff as it was approved.`,
457
+ carries: `sync:${cycle}`
458
+ }).pipe(
459
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
460
+ )
461
+
462
+ if (!carried.approved) notCarried = `the approval was not carried: ${carried.reason}`
463
+ }
464
+
465
+ // The forge can show the old head for a moment after the push; the next look reads it once it shows this one.
466
+ if (caught !== undefined) {
467
+ pushed = { head: caught.head, stale: 0 }
468
+
469
+ yield* waitFor(`pushed:${cycle}`, {
470
+ event: 'change_request.mergeable',
471
+ filter: { changeRequestId, head: caught.head },
472
+ timeout: '5 minutes'
473
+ }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
474
+ }
475
+
476
+ return undefined
477
+ })
478
+
220
479
  return Effect.gen(function* () {
221
480
  for (let cycle = 1; ; cycle++) {
222
481
  if (cycle > (input.maxCycles ?? 20)) {
@@ -234,6 +493,8 @@ export default defineLoop({
234
493
 
235
494
  const pipeline = yield* pipelineStatus(`pipeline:${cycle}`, { changeRequestId })
236
495
 
496
+ repository = pipeline.repository ?? repository
497
+
237
498
  // The forge can show an older head for a while after a catch-up push: nothing is gated on any head but the
238
499
  // pushed one, so look again; a person's push on top of it stops it for them.
239
500
  if (pushed !== undefined && pipeline.head !== pushed.head) {
@@ -276,26 +537,94 @@ export default defineLoop({
276
537
  }
277
538
 
278
539
  if (pipeline.status === 'failed' || pipeline.status === 'canceled') {
540
+ // The target moved since its failure was found to be the target's: merge it in, which may mend it. Its head
541
+ // says so where the forge gave it; else a merge into it does.
542
+ const targetMoved =
543
+ redTarget?.head === pipeline.head &&
544
+ (redTarget.targetHead !== undefined && pipeline.target !== undefined
545
+ ? pipeline.target.head !== redTarget.targetHead
546
+ : redTarget.moved)
547
+
548
+ if (targetMoved) {
549
+ redTarget = undefined
550
+
551
+ const stopped = yield* catchUp(cycle)
552
+
553
+ if (stopped !== undefined) return stopped
554
+
555
+ continue
556
+ }
557
+
558
+ const onTarget = yield* checkTarget(cycle, pipeline)
559
+ const failing = failingJobs(pipeline)
560
+
561
+ if (failing.length > 0 && failing.every(name => onTarget.failed.includes(name))) {
562
+ const stopped = yield* waitOutTarget(
563
+ cycle,
564
+ pipeline,
565
+ `${target} fails ${failing.join(', ')} at its own head too, so no fix here can mend it`
566
+ )
567
+
568
+ if (stopped !== undefined) return stopped
569
+
570
+ continue
571
+ }
572
+
573
+ // The target passes now what it failed, with nothing merged that this read shows: merge it in.
574
+ if (onTarget.passed.length > 0 && redTarget?.head === pipeline.head) {
575
+ redTarget = undefined
576
+
577
+ const stopped = yield* catchUp(cycle)
578
+
579
+ if (stopped !== undefined) return stopped
580
+
581
+ continue
582
+ }
583
+
584
+ // Kitman could not check the target, and a ci-fix found its failure the target's: wait on, fixing nothing.
585
+ if (redTarget?.head === pipeline.head) {
586
+ const stopped = yield* waitOutTarget(cycle, pipeline, `${target} still fails as ${pipeline.head} does`)
587
+
588
+ if (stopped !== undefined) return stopped
589
+
590
+ continue
591
+ }
592
+
279
593
  if (stalledAt === pipeline.head) stalls++
280
594
  else stalls = 0
281
595
 
282
596
  if (stalls >= 2)
283
597
  return done('needs_you', `Two fixes pushed nothing new; the pipeline at ${pipeline.head} still fails`)
284
598
 
285
- if (fixRounds >= (input.maxFixRounds ?? 3))
286
- return done('needs_you', `The pipeline still fails after ${fixRounds} fix rounds`)
287
- fixRounds++
599
+ if (!(yield* mayFix('ci-fix', cycle, `the failing pipeline at ${pipeline.head}`)))
600
+ return handBack(
601
+ `The pipeline at ${pipeline.head} still fails after ${rounds['ci-fix']} ci-fix rounds`,
602
+ failedJobs(pipeline).join('\n\n')
603
+ )
288
604
  stalledAt = pipeline.head
605
+ yield* passTurn()
289
606
 
290
607
  const fixed = yield* agentWork(`ci-fix:${cycle}`, {
291
608
  agent: 'implementer',
292
- prompt: ciFixPrompt(pipeline, target),
609
+ prompt: ciFixPrompt(pipeline, target, onTarget),
293
610
  output: CiFix,
294
611
  timeout: stepBudget
295
612
  })
296
613
 
297
- if (fixed.verdict === 'pre_existing')
298
- return done('needs_you', `The failure is pre-existing on the target branch: ${fixed.summary}`)
614
+ // Only a round that fixed something counts: one that found the target's failure or a flake changed nothing.
615
+ if (fixed.verdict === 'fixed') rounds['ci-fix']++
616
+
617
+ if (fixed.verdict === 'pre_existing') {
618
+ const stopped = yield* waitOutTarget(
619
+ cycle,
620
+ pipeline,
621
+ `the failure is pre-existing on the target branch: ${fixed.summary}`
622
+ )
623
+
624
+ if (stopped !== undefined) return stopped
625
+
626
+ continue
627
+ }
299
628
 
300
629
  if (fixed.verdict === 'flaky') {
301
630
  if (pipeline.source === 'reported') {
@@ -327,11 +656,15 @@ export default defineLoop({
327
656
  continue
328
657
  }
329
658
 
659
+ redTarget = undefined
660
+
330
661
  const threads = (yield* reviewThreads(`threads:${cycle}`, { changeRequestId })).threads.filter(
331
662
  thread => !answered.has(threadKey(thread))
332
663
  )
333
664
 
334
665
  if (threads.length > 0) {
666
+ yield* passTurn()
667
+
335
668
  const answers = yield* agentWork(`comments:${cycle}`, {
336
669
  agent: 'implementer',
337
670
  prompt: repliesPrompt(threads),
@@ -372,62 +705,9 @@ export default defineLoop({
372
705
  if (mergeable.payload.mergeable === false || behind) {
373
706
  behind = false
374
707
 
375
- const synced = yield* syncBase(`sync:${cycle}`, { agent: 'implementer', target })
376
-
377
- if (synced.status === 'conflict')
378
- return done('needs_you', `Merging ${target} in conflicts on ${synced.files.join(', ')}: ${synced.reason}`)
379
-
380
- if (synced.status === 'merged') {
381
- const caught = synced.catchUp
382
-
383
- const verdict =
384
- caught === undefined
385
- ? ({ kind: 'changed', why: 'its Runner did not report what it did to the branch' } as const)
386
- : catchUpVerdict(caught)
387
-
388
- if (verdict.kind === 'changed') {
389
- unreviewed = undefined
390
- notCarried = `merging ${target} in changed it: ${verdict.why}`
391
- } else if (caught !== undefined && unreviewed !== undefined) {
392
- const files = [...new Set([...unreviewed.files, ...(verdict.kind === 'review' ? verdict.files : [])])]
393
-
394
- // With no fix since the files' merge, the review need not cover this merge's target commits; otherwise
395
- // `since` keeps covering the fixes, and this merge with them.
396
- unreviewed =
397
- caught.from === unreviewed.synced
398
- ? { ...unreviewed, files, synced: caught.head }
399
- : { ...unreviewed, files }
400
- } else if (caught !== undefined && verdict.kind === 'review') {
401
- notCarried = undefined
402
- unreviewed = { files: verdict.files, synced: caught.head, sync: `sync:${cycle}`, earlier: [] }
403
- } else if (caught !== undefined) {
404
- notCarried = undefined
405
-
406
- const carried = yield* approveChangeRequest(`carry:${cycle}`, {
407
- changeRequestId,
408
- head: caught.head,
409
- summary: `Merging ${target} in left the branch's own diff as it was approved.`,
410
- carries: `sync:${cycle}`
411
- }).pipe(
412
- Effect.catchTag('StepFailed', error =>
413
- Effect.succeed({ approved: false as const, reason: error.reason })
414
- )
415
- )
416
-
417
- if (!carried.approved) notCarried = `the approval was not carried: ${carried.reason}`
418
- }
419
-
420
- // The forge can show the old head for a moment after the push; the next look reads it once it shows this one.
421
- if (caught !== undefined) {
422
- pushed = { head: caught.head, stale: 0 }
708
+ const stopped = yield* catchUp(cycle)
423
709
 
424
- yield* waitFor(`pushed:${cycle}`, {
425
- event: 'change_request.mergeable',
426
- filter: { changeRequestId, head: caught.head },
427
- timeout: '5 minutes'
428
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.void))
429
- }
430
- }
710
+ if (stopped !== undefined) return stopped
431
711
 
432
712
  continue
433
713
  }
@@ -438,6 +718,8 @@ export default defineLoop({
438
718
  const files = unreviewed
439
719
  const head = pipeline.head
440
720
 
721
+ yield* passTurn()
722
+
441
723
  const reviewed = yield* call(`review:${cycle}`, reviewLoop(), {
442
724
  base: `origin/${target}`,
443
725
  head,
@@ -449,12 +731,12 @@ export default defineLoop({
449
731
  if (reviewed.blocking) {
450
732
  const blocking = reviewed.findings.filter(isBlocking)
451
733
 
452
- if (fixRounds >= (input.maxFixRounds ?? 3))
453
- return done(
454
- 'needs_you',
455
- `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')} after ${fixRounds} fix rounds`
734
+ if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
735
+ return handBack(
736
+ `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
737
+ findingLines(blocking)
456
738
  )
457
- fixRounds++
739
+ rounds['head-fix']++
458
740
 
459
741
  yield* agentWork(`review-fix:${cycle}`, {
460
742
  agent: 'implementer',
@@ -530,6 +812,8 @@ export default defineLoop({
530
812
 
531
813
  if (!reviewedHere && approved === undefined) {
532
814
  const head = pipeline.head
815
+ // Only what changed since the last approved head is unreviewed; the rest was approved as it stands.
816
+ const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved
533
817
 
534
818
  const reviewIt = leftToPerson.has(head)
535
819
  ? 'Wait'
@@ -539,18 +823,22 @@ export default defineLoop({
539
823
  {
540
824
  value: 'Review',
541
825
  description:
542
- "Kitman's Review reads the whole change at this head and approves it if nothing blocks."
826
+ since === undefined
827
+ ? "Kitman's Review reads the whole change at this head and approves it if nothing blocks."
828
+ : `Kitman's Review reads what changed since ${since}, the last approved head, and approves it if nothing there blocks.`
543
829
  },
544
830
  { value: 'Wait', description: 'Waits for a person to approve this head.' }
545
831
  ],
546
832
  recommended: 'Review',
547
- recommendationReason: 'A passing Review of the whole change is what approved the head Build shipped.',
833
+ recommendationReason: 'A passing Review of the change is what approved the head Build shipped.',
548
834
  default: 'Wait',
549
835
  // A full-auto Team merges what its Review approved, including heads Shepherd pushed itself.
550
836
  auto: 'Review',
551
837
  timeout: '1 hour'
552
838
  })
553
839
 
840
+ yield* passTurn()
841
+
554
842
  if (reviewIt === 'Wait') {
555
843
  leftToPerson.add(head)
556
844
  approved = yield* waitFor(`approval:${cycle}`, { ...approval, timeout: '7 days' })
@@ -558,22 +846,26 @@ export default defineLoop({
558
846
  const reviewed = yield* call(`head-review:${cycle}`, reviewLoop(), {
559
847
  base: `origin/${target}`,
560
848
  head,
849
+ ...(since === undefined ? undefined : { approved: since }),
561
850
  ...(headFindings.length === 0 ? undefined : { earlier: headFindings })
562
851
  })
563
852
 
564
853
  if (reviewed.blocking) {
565
854
  const blocking = reviewed.findings.filter(isBlocking)
566
855
 
567
- if (fixRounds >= (input.maxFixRounds ?? 3))
568
- return done(
569
- 'needs_you',
570
- `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')} after ${fixRounds} fix rounds`
856
+ if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
857
+ return handBack(
858
+ `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
859
+ findingLines(blocking)
571
860
  )
572
- fixRounds++
861
+ rounds['head-fix']++
573
862
 
574
863
  yield* agentWork(`head-fix:${cycle}`, {
575
864
  agent: 'implementer',
576
- prompt: reviewFixPrompt(`the change at ${head}`, blocking),
865
+ prompt: reviewFixPrompt(
866
+ since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`,
867
+ blocking
868
+ ),
577
869
  output: ReviewFix,
578
870
  timeout: stepBudget
579
871
  })
@@ -585,7 +877,10 @@ export default defineLoop({
585
877
  const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
586
878
  changeRequestId,
587
879
  head,
588
- summary: `A review of the whole change at ${head} passed with nothing blocking.`,
880
+ summary:
881
+ since === undefined
882
+ ? `A review of the whole change at ${head} passed with nothing blocking.`
883
+ : `A review of what changed between ${since}, the last approved head, and ${head} passed with nothing blocking.`,
589
884
  review: `head-review:${cycle}`
590
885
  }).pipe(
591
886
  Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
@@ -622,6 +917,11 @@ export default defineLoop({
622
917
 
623
918
  if (merge === 'Wait') return done('ready', 'Approved, green and mergeable; left for a person to merge')
624
919
 
920
+ // A Run ahead of it merges first; its merge moves the target, which this merge then finds and catches up with.
921
+ const refused = yield* takeTurn()
922
+
923
+ if (refused !== undefined) return done('needs_you', `The turn to merge into ${target} was refused: ${refused}`)
924
+
625
925
  // Only the head whose pipeline passed is merged: one pushed while waiting goes round again.
626
926
  const merged = yield* mergeChangeRequest(`merge-change-request:${cycle}`, {
627
927
  changeRequestId,
@@ -632,6 +932,7 @@ export default defineLoop({
632
932
  if (merged.status === 'conflict') behind = true
633
933
 
634
934
  if (merged.status !== 'merged') continue
935
+ yield* passTurn()
635
936
  yield* writeBack('write-back', { milestone: 'merged' })
636
937
 
637
938
  const ship = yield* ask('ship', {
@@ -651,8 +952,34 @@ export default defineLoop({
651
952
 
652
953
  const released = yield* call('release', release, { revision: merged.revision })
653
954
 
955
+ // A failed gate changed nothing in production, and the next merge's Release gates this revision with its own.
956
+ const handedOn =
957
+ released.status === 'gate_failed' &&
958
+ (yield* ask('release-gate-failed', {
959
+ prompt: `Merged at ${merged.revision}, but its Release gate failed: ${released.reason}`,
960
+ options: [
961
+ {
962
+ value: 'Next Release',
963
+ description: 'Leaves the revision to the next Release, which gates it with the next merge.'
964
+ },
965
+ { value: 'Taken over', description: 'A person looks at the failing checks from here.' }
966
+ ],
967
+ recommended: 'Next Release',
968
+ recommendationReason:
969
+ 'Nothing was tagged or deployed, and the gate already ran the failure again in a fresh checkout.',
970
+ // No default: outside full auto a person decides.
971
+ default: null,
972
+ auto: 'Next Release'
973
+ })) === 'Next Release'
974
+
975
+ if (handedOn)
976
+ return {
977
+ ...done('merged', `Merged at ${merged.revision}; its Release gate failed, so the next Release ships it`),
978
+ release: { runStatus: released.status, reason: released.reason }
979
+ }
980
+
654
981
  // It merged either way; a Release that did not deploy, other than one a person rejected, needs a person.
655
- if (released.status !== 'deployed' && released.status !== 'rejected')
982
+ if (released.status !== 'deployed' && released.status !== 'rejected' && released.status !== 'gate_failed')
656
983
  yield* ask('release-failed', {
657
984
  prompt: `Merged at ${merged.revision}, but its Release ended ${released.status}: ${released.reason}`,
658
985
  options: [{ value: 'Taken over', description: 'A person looks at the release and production from here.' }],