@kitman-sh/software-engineering 0.10.69 → 0.10.71

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