@kitman-sh/software-engineering 0.12.0-rc.1 → 0.12.0-rc.3

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/review.ts CHANGED
@@ -25,7 +25,7 @@ import * as Schema from 'effect/Schema'
25
25
  import build, { BuildInput, BuildOutput } from './build'
26
26
  import { verifyHead } from './change-request-body'
27
27
  import { DeliveryFields, ownDeliveryTarget } from './delivery'
28
- import { FindingDetail, OneSentence } from './text-limits'
28
+ import { FindingDetail, OneSentence, ShortStatement } from './text-limits'
29
29
 
30
30
  /** Build, by its schemas: the module imports this one, so its definition is not ready when this one loads. */
31
31
  const buildLoop = () => ({ id: 'build', input: BuildInput, output: BuildOutput })
@@ -76,6 +76,11 @@ const Input = Schema.Struct({
76
76
  claims: Schema.optional(Schema.Array(Schema.String)),
77
77
  /** An earlier review's open findings: each is checked as fixed, changed or still there, keeping its id. */
78
78
  earlier: Schema.optional(Schema.Array(MergedFinding)),
79
+ /**
80
+ * The head an earlier review of this change read. With it or `earlier`, this review reviews the fix, as
81
+ * `git diff reviewed..head`, and a new finding outside the fix blocks only as a blocker.
82
+ */
83
+ reviewed: Schema.optional(Schema.String),
79
84
  /** The checks that fail on the head and pass on the base, which the implementer is already told. */
80
85
  failing: Schema.optional(Schema.Array(Schema.String)),
81
86
  /** Why each head test verify never ran is unverified; a ChangeRequest's head is verified here too. */
@@ -93,15 +98,31 @@ const SeatFinding = Schema.Struct({
93
98
  ...Finding.fields,
94
99
  detail: FindingDetail,
95
100
  /** In a review since an approved head: the problem is in code the change already had there. */
96
- approvedCode: Schema.optional(Schema.Boolean)
101
+ approvedCode: Schema.optional(Schema.Boolean),
102
+ /** The rule or check it breaks, worded alike for every finding that breaks it. */
103
+ rule: Schema.optional(OneSentence),
104
+ /** The sibling cases of that rule the seat checked and found fine. */
105
+ checked: Schema.optional(Schema.Array(ShortStatement)),
106
+ /** In a review of a fix: the problem is outside the fix and the code it touches. */
107
+ outsideFix: Schema.optional(Schema.Boolean)
108
+ })
109
+
110
+ /** A scope judgement with what an answer put out of scope, which is reported and never unmet. */
111
+ const ReviewedScope = Schema.Struct({
112
+ ...ScopeJudgement.fields,
113
+ reported: Schema.optional(Schema.Array(Schema.String))
97
114
  })
98
115
 
116
+ /** Met when nothing is unmet but what an answer put out of scope, so a waived criterion never blocks. */
117
+ const agreedScope = (scope: typeof ReviewedScope.Type): typeof ReviewedScope.Type =>
118
+ scope.unmet.length === 0 && (scope.reported ?? []).length > 0 ? { ...scope, met: true } : scope
119
+
99
120
  const SeatOutput = Schema.Struct({
100
121
  /** One sentence: can it merge, and what matters most. */
101
122
  summary: OneSentence,
102
123
  findings: Schema.Array(SeatFinding),
103
124
  verdicts: Schema.optional(Schema.Array(RebuttalVerdict)),
104
- scope: Schema.optional(ScopeJudgement),
125
+ scope: Schema.optional(ReviewedScope),
105
126
  followUps: Schema.optional(Schema.Array(FollowUp))
106
127
  })
107
128
 
@@ -117,7 +138,9 @@ const Output = Schema.Struct({
117
138
  blocking: Schema.Boolean,
118
139
  artifactId: Schema.String,
119
140
  /** The scope seat's judgement of the Task's scope; absent when there was no Task to judge against. */
120
- scope: Schema.optional(ScopeJudgement),
141
+ scope: Schema.optional(ReviewedScope),
142
+ /** The checks that fail on the head, given or verified here; the head is not ready while any does. */
143
+ failing: Schema.optional(Schema.Array(Schema.String)),
121
144
  /** Kitman's approval of the ChangeRequest's head, recorded when nothing blocks it; or why it was refused. */
122
145
  approval: Schema.optional(
123
146
  Schema.Struct({ head: Schema.String, approved: Schema.Boolean, reason: Schema.optional(Schema.String) })
@@ -211,7 +234,7 @@ const wholeChange = (input: typeof Input.Type) => input.files === undefined && i
211
234
 
212
235
  const scopePrompt = (input: typeof Input.Type) =>
213
236
  [
214
- "If your brief has a Task, judge its scope and give it as `scope`: does the change do what the Task's description and each of its Acceptance Criteria ask? Set `met` to true only if it does all of it, and list in `unmet` one line for each criterion or part of the description that is not done. If your brief has no Task, leave `scope` out.",
237
+ "If your brief has a Task, judge its scope and give it as `scope`: does the change do what the Task's description and each of its Acceptance Criteria ask? Judge it against what is still agreed: a criterion or part an answer under your brief's Answers so far put out of scope is reported, not unmet; list each in `reported`, one line each, and leave it out of `unmet`. Set `met` to true only if the change does all the rest, and list in `unmet` one line for each other criterion or part of the description that is not done. If your brief has no Task, leave `scope` out.",
215
238
  ...(input.outcome === undefined ? [] : [`The Outcome to prove is ${input.outcome}.`]),
216
239
  ...(input.claims === undefined || input.claims.length === 0
217
240
  ? []
@@ -221,15 +244,32 @@ const scopePrompt = (input: typeof Input.Type) =>
221
244
  ])
222
245
  ].join('\n\n')
223
246
 
247
+ const exhaustivePrompt = [
248
+ 'Review exhaustively, in this one pass. For each rule or check the change adds or alters, such as who may read or change what, a validation, a limit or a state transition, trace it through every caller and every input it can get before you report: each kind of actor, each visibility, Team and Project scope, and ids the caller gives.',
249
+ 'Report every finding of every severity in this one pass, grouped by the rule it breaks: do not stop at the first serious one in an area, and hold none back for a later round. Give each its `rule`, worded alike for every finding that breaks the same rule, and its `checked`: the sibling cases of that rule you checked and found fine, so the next round need not explore them again.'
250
+ ].join(' ')
251
+
224
252
  const earlierPrompt = (earlier: readonly MergedFinding[]) =>
225
253
  [
226
- 'An earlier review found these. Give each as a `followUps` entry with its id: fixed, changed (the code moved but the problem stands) or still_there. Do not report them again as findings; review only what changed since, for new problems.',
254
+ 'An earlier review found these. Give each as a `followUps` entry with its id: fixed, changed (the code moved but the problem stands) or still_there. Do not report them again as findings.',
227
255
  ...earlier.map(finding => `- ${finding.id} (${finding.severity}): ${finding.detail}`)
228
256
  ].join('\n')
229
257
 
258
+ /** A review of a fix: given an earlier review's findings, or the head an earlier review read. */
259
+ const fixRound = (input: typeof Input.Type) => (input.earlier?.length ?? 0) > 0 || input.reviewed !== undefined
260
+
261
+ const fixPrompt = (fix: string) =>
262
+ `This round reviews ${fix} and the code it touches, exhaustively as above. Raise a new problem outside the fix and the code it touches only if it is a blocker; report one that is not as a minor with \`outsideFix\` set to true, which does not block landing.`
263
+
264
+ const fixOf = (input: typeof Input.Type, head: string) =>
265
+ input.reviewed === undefined
266
+ ? 'the fix since the earlier review'
267
+ : `the fix, \`git diff ${input.reviewed}..${head}\` (the target branch merged into it is not the fix),`
268
+
230
269
  const promptFor = (
231
270
  seat: keyof typeof seats,
232
271
  target: string,
272
+ head: string,
233
273
  input: typeof Input.Type,
234
274
  failing: readonly string[],
235
275
  notRun: readonly string[]
@@ -239,9 +279,12 @@ const promptFor = (
239
279
  `Review ${target}`,
240
280
  'Give `summary`: one sentence on whether it can merge and what matters most.',
241
281
  'Report each problem as a finding: severity blocker (must not ship), major (fix before merge) or minor (optional); the file path from the repository root; the line; and the detail. When it is one instance of a class of bug, name every other instance in the diff in its detail. Report nothing you have not checked in the code.',
282
+ exhaustivePrompt,
283
+ "What an answer under your brief's Answers so far put out of scope is reported, not missing: do not report it as a finding.",
242
284
  'If the diff is too big to review in one go, review it directory by directory and say so in a finding on the first file you skipped.',
243
285
  ...(seat === scopeSeat && wholeChange(input) ? [scopePrompt(input)] : []),
244
286
  ...(input.earlier === undefined || input.earlier.length === 0 ? [] : [earlierPrompt(input.earlier)]),
287
+ ...(fixRound(input) ? [fixPrompt(fixOf(input, head))] : []),
245
288
  ...(failing.length === 0
246
289
  ? []
247
290
  : [
@@ -265,6 +308,57 @@ const promptFor = (
265
308
 
266
309
  const rank = { still_there: 0, changed: 1, fixed: 2 } as const
267
310
 
311
+ type SeatFinding = typeof SeatFinding.Type
312
+
313
+ /** A review of a fix lands past a new problem outside it unless that problem is a blocker. */
314
+ const outsideFixAsMinor = (finding: SeatFinding): SeatFinding =>
315
+ finding.outsideFix === true && finding.severity === 'major' ? { ...finding, severity: 'minor' } : finding
316
+
317
+ const detailOf = (detail: string, rule: string | undefined, checked: readonly string[]) =>
318
+ [
319
+ ...(rule === undefined ? [] : [`[${rule}]`]),
320
+ detail,
321
+ ...(checked.length === 0 ? [] : [`Checked and fine: ${checked.join('; ')}.`])
322
+ ].join(' ')
323
+
324
+ const idOf = (finding: SeatFinding) => `${finding.file}:${finding.line}`
325
+
326
+ /**
327
+ * Merges the seats' findings with the rule and the cases checked for each in its detail, those of one rule together.
328
+ * A line takes the first rule any seat gave it and every seat's checked cases, whichever seat's detail the merge keeps.
329
+ */
330
+ const groupedByRule = (bySeat: { readonly [seat: string]: readonly SeatFinding[] }) => {
331
+ const rules = new Map<string, string>()
332
+ const checked = new Map<string, Set<string>>()
333
+
334
+ for (const finding of Object.values(bySeat).flat()) {
335
+ const id = idOf(finding)
336
+
337
+ if (finding.rule !== undefined && !rules.has(id)) rules.set(id, finding.rule)
338
+ checked.set(id, new Set([...(checked.get(id) ?? []), ...(finding.checked ?? [])]))
339
+ }
340
+
341
+ const findings = mergeFindings(
342
+ Object.fromEntries(
343
+ Object.entries(bySeat).map(([seat, seatFindings]) => [
344
+ seat,
345
+ seatFindings.map(finding => ({
346
+ severity: finding.severity,
347
+ file: finding.file,
348
+ line: finding.line,
349
+ detail: detailOf(finding.detail, rules.get(idOf(finding)), [...(checked.get(idOf(finding)) ?? [])])
350
+ }))
351
+ ])
352
+ )
353
+ )
354
+
355
+ // Groups keep the order of their worst finding, as mergeFindings sorts by severity.
356
+ const groupOf = (finding: MergedFinding) => rules.get(finding.id) ?? finding.id
357
+ const order = [...new Set(findings.map(groupOf))]
358
+
359
+ return findings.toSorted((left, right) => order.indexOf(groupOf(left)) - order.indexOf(groupOf(right)))
360
+ }
361
+
268
362
  /** Each earlier finding's status: the worst any seat gave, and still there when no seat answered for it. */
269
363
  const followUpsOf = (earlier: readonly MergedFinding[], answers: readonly (typeof FollowUp.Type)[]) =>
270
364
  earlier.map(finding => {
@@ -289,10 +383,14 @@ const reviewText = (
289
383
  findings: readonly MergedFinding[],
290
384
  followUps: readonly (typeof FollowUp.Type)[],
291
385
  approvedFindings: readonly MergedFinding[],
292
- notRun: readonly string[]
386
+ notRun: readonly string[],
387
+ reported: readonly string[]
293
388
  ) =>
294
389
  [
295
390
  `**Kitman review.** ${summary}`,
391
+ ...(reported.length === 0
392
+ ? []
393
+ : [`Out of scope by an answer, so reported, not blocking:\n${reported.map(item => `- ${item}`).join('\n')}`]),
296
394
  ...(notRun.length === 0
297
395
  ? []
298
396
  : [`Verify never ran these tests, so they are unverified:\n${notRun.map(item => `- ${item}`).join('\n')}`]),
@@ -324,7 +422,7 @@ const fixBrief = (changeRequestId: string, findings: readonly MergedFinding[]) =
324
422
  */
325
423
  export default defineLoop({
326
424
  id: 'review',
327
- version: '3.8.0',
425
+ version: '3.9.0',
328
426
  title: 'Review',
329
427
  input: Input,
330
428
  output: Output,
@@ -372,7 +470,7 @@ export default defineLoop({
372
470
  seat =>
373
471
  agentWork(`review:${seat}`, {
374
472
  agent: seat,
375
- prompt: promptFor(seat, target, input, failing, notRun),
473
+ prompt: promptFor(seat, target, range.head, input, failing, notRun),
376
474
  output: SeatOutput
377
475
  }).pipe(Effect.map(output => [seat, output] as const)),
378
476
  { concurrency: 'unbounded' }
@@ -400,15 +498,17 @@ export default defineLoop({
400
498
  const sinceApproval = input.approved !== undefined && input.files === undefined
401
499
 
402
500
  const merged = (approvedCode: boolean) =>
403
- mergeFindings(
501
+ groupedByRule(
404
502
  Object.fromEntries(
405
503
  outputs.map(([seat, output]) => [
406
504
  seat,
407
- output.findings.filter(
408
- finding =>
409
- !earlierIds.has(`${finding.file}:${finding.line}`) &&
410
- (sinceApproval && finding.approvedCode === true) === approvedCode
411
- )
505
+ output.findings
506
+ .filter(
507
+ finding =>
508
+ !earlierIds.has(`${finding.file}:${finding.line}`) &&
509
+ (sinceApproval && finding.approvedCode === true) === approvedCode
510
+ )
511
+ .map(finding => (fixRound(input) ? outsideFixAsMinor(finding) : finding))
412
512
  ])
413
513
  )
414
514
  )
@@ -419,7 +519,8 @@ export default defineLoop({
419
519
  const findings = [...carried, ...fresh]
420
520
 
421
521
  const blockers = findings.filter(isBlocking)
422
- const scope = wholeChange(input) ? outputs.find(([seat]) => seat === scopeSeat)?.[1].scope : undefined
522
+ const judged = wholeChange(input) ? outputs.find(([seat]) => seat === scopeSeat)?.[1].scope : undefined
523
+ const scope = judged === undefined ? undefined : agreedScope(judged)
423
524
 
424
525
  // A seat's own summary is kept only when nothing blocks, so it cannot contradict the verdict.
425
526
  const summary =
@@ -438,7 +539,7 @@ export default defineLoop({
438
539
  : ['Can merge: nothing blocks it.', ...outputs.map(([, output]) => output.summary)].join(' ')
439
540
 
440
541
  const freshIds = new Set(fresh.map(finding => finding.id))
441
- const text = reviewText(summary, findings, followUps, approvedFindings, notRun)
542
+ const text = reviewText(summary, findings, followUps, approvedFindings, notRun, scope?.reported ?? [])
442
543
 
443
544
  const stored = yield* artifact('findings', {
444
545
  kind: 'review-findings',
@@ -456,6 +557,7 @@ export default defineLoop({
456
557
  artifactId: stored.artifactId,
457
558
  ...(approvedFindings.length === 0 ? undefined : { approvedFindings }),
458
559
  ...(scope === undefined ? undefined : { scope }),
560
+ ...(failing.length === 0 ? undefined : { failing }),
459
561
  ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo })
460
562
  }
461
563
 
@@ -521,6 +623,8 @@ export default defineLoop({
521
623
  words: fixBrief(changeRequestId, findings),
522
624
  changeRequestId,
523
625
  maxRounds: 2,
626
+ reviewed: range.head,
627
+ ...(findings.length === 0 ? undefined : { earlier: findings }),
524
628
  ...ownDeliveryTarget(input)
525
629
  })
526
630
 
@@ -1,4 +1,4 @@
1
- import { ResolvedDeliveryTarget, ResolvedReleaseTrigger } from '@kitman-sh/sdk/loop'
1
+ import { MergedFinding, ResolvedDeliveryTarget, ResolvedReleaseTrigger } from '@kitman-sh/sdk/loop'
2
2
  import * as Schema from 'effect/Schema'
3
3
 
4
4
  /** Shepherd's Output, outside shepherd.ts so Build can import it without the review → build → shepherd cycle. */
@@ -9,6 +9,8 @@ export const ShepherdOutput = Schema.Struct({
9
9
  reason: Schema.String,
10
10
  fixRounds: Schema.Int,
11
11
  replies: Schema.Int,
12
+ /** Each passed Review another Run recorded that Shepherd used for a head instead of reviewing that head again. */
13
+ reused: Schema.optional(Schema.Array(Schema.Struct({ review: Schema.String, head: Schema.String }))),
12
14
  /** What still stands when it stopped without landing (needs_you, handed_back), so the Run and a Build above it read partial. */
13
15
  unsettled: Schema.optional(Schema.Array(Schema.String)),
14
16
  /** The Release it started after merging, when it was told to release. */
@@ -28,7 +30,10 @@ export const ShepherdOutput = Schema.Struct({
28
30
  words: Schema.String,
29
31
  taskId: Schema.optional(Schema.String),
30
32
  /** The ChangeRequest's target, which Build merges into. */
31
- branch: Schema.optional(Schema.String)
33
+ branch: Schema.optional(Schema.String),
34
+ /** The head the review that handed it back read, and its findings, so Build's first review reviews the fix. */
35
+ reviewed: Schema.optional(Schema.String),
36
+ earlier: Schema.optional(Schema.Array(MergedFinding))
32
37
  })
33
38
  )
34
39
  })
package/src/shepherd.ts CHANGED
@@ -225,6 +225,9 @@ const repliesPrompt = (threads: ReviewThreads['threads']) =>
225
225
  /** A thread's key changes when someone adds to it, so a new comment on an answered thread is answered again. */
226
226
  const threadKey = (thread: ReviewThreads['threads'][number]) => `${thread.id}:${thread.comments.length}`
227
227
 
228
+ /** A passing review of a head with tests verify never ran: Shepherd's own `review` Step, or another Run's it `reuses`. */
229
+ type UnranReview = { readonly notRun: readonly string[] } & ({ readonly review: string } | { readonly reuses: string })
230
+
228
231
  /**
229
232
  * Takes an open ChangeRequest to merge: it waits on its Events with no model time between them, fixes a pipeline the
230
233
  * branch broke (after ruling out a flake and a target branch that fails the same check, which it waits out), answers
@@ -233,7 +236,8 @@ const threadKey = (thread: ReviewThreads['threads'][number]) => `${thread.id}:${
233
236
  * pipeline, merges its target in before any pipeline is run or fixed; one that is only behind catches up when its merge
234
237
  * finds it behind, on its turn. One whose merge Shepherd cannot settle goes back to Build. It merges the
235
238
  * target in and merges only while it holds the target's turn, so ChangeRequests for one target land one at a time, in
236
- * order. A head nobody approved gets a review of what changed since the last approved head, and the head a catch-up
239
+ * order. A head with a passed Review of the whole change that any Run recorded, such as the Build that shipped it, is
240
+ * 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
237
241
  * 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
238
242
  * head-fix rounds, each judged by the pipeline at the head the last fix pushed, then hands the ChangeRequest back to
239
243
  * Build, and stops as needs you, with why, instead of spinning. Left for a person to merge, it watches the target for up to
@@ -244,7 +248,7 @@ const threadKey = (thread: ReviewThreads['threads'][number]) => `${thread.id}:${
244
248
  */
245
249
  export default defineLoop({
246
250
  id: 'shepherd',
247
- version: '1.8.0',
251
+ version: '1.9.0',
248
252
  title: 'Shepherd',
249
253
  input: Input,
250
254
  output: Output,
@@ -283,8 +287,10 @@ export default defineLoop({
283
287
  const leftToPerson = new Set<string>()
284
288
  /** The last review of an unapproved head's open findings, for the review of the head that fixes them. */
285
289
  let headFindings: readonly MergedFinding[] = []
286
- /** Each head Shepherd's review passed but left unapproved, as verify never ran these of its tests. */
287
- const unranAt = new Map<string, { readonly notRun: readonly string[]; readonly review: string }>()
290
+ /** The head that review read. */
291
+ let headFindingsAt: string | undefined
292
+ /** Each head a review passed but left unapproved, as verify never ran these of its tests. */
293
+ const unranAt = new Map<string, UnranReview>()
288
294
  const rounds: Record<RoundKind, number> = { 'ci-fix': 0, 'head-fix': 0 }
289
295
  /** Rounds past the limit a person allowed. */
290
296
  const allowed: Record<RoundKind, number> = { 'ci-fix': 0, 'head-fix': 0 }
@@ -300,6 +306,8 @@ export default defineLoop({
300
306
  /** The base sync whose merged-from head's approval covers the rest of the change. */
301
307
  readonly sync: string
302
308
  readonly earlier: readonly MergedFinding[]
309
+ /** The head the review that found `earlier` read. */
310
+ readonly reviewed?: string
303
311
  }
304
312
  | undefined
305
313
 
@@ -307,8 +315,12 @@ export default defineLoop({
307
315
  let reviewOnceShown: string | undefined
308
316
  /** The head the last catch-up pushed, whose pipeline runs before Shepherd catches up again. */
309
317
  let pipelineFirst: string | undefined
310
- /** Heads Shepherd's own review passed, approved or left to a person for tests verify never ran. */
318
+ /** Heads Shepherd's own review passed, approved or left to a person for tests verify never ran, or it reused a Review of. */
311
319
  const reviewedHeads = new Set<string>()
320
+ /** Each passed Review another Run recorded that stood for a review of a head here. */
321
+ const reused: { readonly review: string; readonly head: string }[] = []
322
+ /** Heads it tried to approve with a Review another Run recorded, so a refusal is not asked again. */
323
+ const reuseTried = new Set<string>()
312
324
  /** The id of the approval Shepherd's own review recorded, by the head it approved. */
313
325
  const approvalOf = new Map<string, string>()
314
326
 
@@ -361,6 +373,7 @@ export default defineLoop({
361
373
  reason,
362
374
  fixRounds: fixRounds(),
363
375
  replies,
376
+ ...(reused.length === 0 ? undefined : { reused }),
364
377
  ...(input.releaseWhen === undefined ? undefined : { releaseWhen: input.releaseWhen }),
365
378
  ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo }),
366
379
  ...(status === 'needs_you' || status === 'handed_back' ? { unsettled: [reason] } : undefined)
@@ -407,14 +420,19 @@ export default defineLoop({
407
420
  }
408
421
  })
409
422
 
410
- const handBack = (reason: string, open: string): Output => ({
423
+ const handBack = (
424
+ reason: string,
425
+ open: string,
426
+ review?: { readonly reviewed: string; readonly earlier: readonly MergedFinding[] }
427
+ ): Output => ({
411
428
  ...done('handed_back', reason),
412
429
  handBack: {
413
430
  changeRequestId,
414
431
  words: `Shepherd handed ChangeRequest ${changeRequestId} back: ${reason}. Fix it forward on its branch:\n${open}`,
415
432
  ...(input.taskId === undefined ? undefined : { taskId: input.taskId }),
416
433
  // Build's target, over the offer's default of this Run's branch, which is the ChangeRequest's own.
417
- ...(target === 'HEAD' ? undefined : { branch: target })
434
+ ...(target === 'HEAD' ? undefined : { branch: target }),
435
+ ...review
418
436
  }
419
437
  })
420
438
 
@@ -797,7 +815,8 @@ export default defineLoop({
797
815
  head,
798
816
  files: files.files,
799
817
  ...(head === files.synced ? undefined : { since: files.synced }),
800
- ...(files.earlier.length === 0 ? undefined : { earlier: files.earlier })
818
+ ...(files.earlier.length === 0 ? undefined : { earlier: files.earlier }),
819
+ ...(files.reviewed === undefined ? undefined : { reviewed: files.reviewed })
801
820
  })
802
821
 
803
822
  if (reviewed.blocking) {
@@ -807,7 +826,8 @@ export default defineLoop({
807
826
  return stop(
808
827
  handBack(
809
828
  `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
810
- findingLines(blocking)
829
+ findingLines(blocking),
830
+ { reviewed: head, earlier: reviewed.findings }
811
831
  )
812
832
  )
813
833
  rounds['head-fix']++
@@ -819,7 +839,7 @@ export default defineLoop({
819
839
  timeout: stepBudget
820
840
  })
821
841
 
822
- unreviewed = { ...files, earlier: reviewed.findings }
842
+ unreviewed = { ...files, earlier: reviewed.findings, reviewed: head }
823
843
  fixedFrom = { head, changed: fix.changed, looks: 0 }
824
844
 
825
845
  return { kind: 'fixing' } as const
@@ -899,7 +919,8 @@ export default defineLoop({
899
919
  head,
900
920
  ...(notRun.length === 0 ? undefined : { notRun }),
901
921
  ...(since === undefined ? undefined : { approved: since }),
902
- ...(headFindings.length === 0 ? undefined : { earlier: headFindings })
922
+ ...(headFindings.length === 0 ? undefined : { earlier: headFindings }),
923
+ ...(headFindingsAt === undefined ? undefined : { reviewed: headFindingsAt })
903
924
  })
904
925
 
905
926
  if (reviewed.blocking) {
@@ -909,7 +930,8 @@ export default defineLoop({
909
930
  return stop(
910
931
  handBack(
911
932
  `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
912
- findingLines(blocking)
933
+ findingLines(blocking),
934
+ { reviewed: head, earlier: reviewed.findings }
913
935
  )
914
936
  )
915
937
  rounds['head-fix']++
@@ -925,12 +947,14 @@ export default defineLoop({
925
947
  })
926
948
 
927
949
  headFindings = reviewed.findings
950
+ headFindingsAt = head
928
951
  fixedFrom = { head, changed: fix.changed, looks: 0 }
929
952
 
930
953
  return { kind: 'fixing' } as const
931
954
  }
932
955
 
933
956
  headFindings = []
957
+ headFindingsAt = undefined
934
958
 
935
959
  if (notRun.length > 0) unranAt.set(head, { notRun, review: `head-review:${cycle}` })
936
960
  else {
@@ -957,6 +981,45 @@ export default defineLoop({
957
981
  return { kind: 'reviewed' } as const
958
982
  })
959
983
 
984
+ /**
985
+ * Approves the head of `pipeline` with the passed Review of the whole change at it that another Run recorded, such
986
+ * as the Build that shipped it, rather than reviewing it again; later heads are reviewed only since it. Like its own
987
+ * review, it leaves a head with tests verify never ran unapproved until a person chooses to merge it.
988
+ */
989
+ const reuseReview = (cycle: number, pipeline: PipelineStatus, reviewed: NonNullable<PipelineStatus['reviewed']>) =>
990
+ Effect.gen(function* () {
991
+ const { head } = pipeline
992
+
993
+ reuseTried.add(head)
994
+
995
+ const notRun = [...new Set([...(input.notRun ?? []), ...(reviewed.notRun ?? [])])]
996
+
997
+ if (notRun.length > 0) {
998
+ unranAt.set(head, { notRun, reuses: reviewed.review })
999
+ reviewedHeads.add(head)
1000
+ reused.push({ review: reviewed.review, head })
1001
+
1002
+ return true
1003
+ }
1004
+
1005
+ const recorded = yield* approveChangeRequest(`reuse:${cycle}`, {
1006
+ changeRequestId,
1007
+ head,
1008
+ summary: `Review ${reviewed.review} passed the whole change at ${head}, so Shepherd approves it without reviewing it again.`,
1009
+ reuses: reviewed.review
1010
+ }).pipe(
1011
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
1012
+ )
1013
+
1014
+ if (!recorded.approved) return false
1015
+
1016
+ approvalOf.set(head, recorded.reviewId)
1017
+ reviewedHeads.add(head)
1018
+ reused.push({ review: reviewed.review, head })
1019
+
1020
+ return true
1021
+ })
1022
+
960
1023
  /** Reviews the head the last catch-up pushed, if `pipeline` shows it and it still needs a review. */
961
1024
  const reviewCaughtUp = (cycle: number, pipeline: PipelineStatus) =>
962
1025
  Effect.gen(function* () {
@@ -1035,6 +1098,14 @@ export default defineLoop({
1035
1098
  else return found
1036
1099
  }
1037
1100
 
1101
+ const reviewedElsewhere =
1102
+ pipeline.approved === pipeline.head || reviewedHeads.has(pipeline.head) || reuseTried.has(pipeline.head)
1103
+ ? undefined
1104
+ : pipeline.reviewed
1105
+
1106
+ // Read again, so this head's approval is what the gates below see.
1107
+ if (reviewedElsewhere !== undefined && (yield* reuseReview(cycle, pipeline, reviewedElsewhere))) continue
1108
+
1038
1109
  // Behind alone waits for the merge, which catches up while holding the turn: catching up any sooner is undone
1039
1110
  // by every merge that lands before this one's turn. A failing pipeline catches up first, so a ci-fix never
1040
1111
  // chases what the target already fixed.
@@ -1432,7 +1503,7 @@ export default defineLoop({
1432
1503
  changeRequestId,
1433
1504
  head: pipeline.head,
1434
1505
  summary: `A review of ${pipeline.head} passed with nothing blocking; a person chose to merge it though verify never ran some of its tests.`,
1435
- review: unapproved.review
1506
+ ...('reuses' in unapproved ? { reuses: unapproved.reuses } : { review: unapproved.review })
1436
1507
  }).pipe(
1437
1508
  Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
1438
1509
  )