@kitman-sh/software-engineering 0.13.16 → 0.13.17

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
@@ -15,8 +15,10 @@ import {
15
15
  Rebuttal,
16
16
  RebuttalVerdict,
17
17
  pipelineStatus,
18
+ type Severity,
18
19
  resolveRevisions,
19
20
  ResolvedDeliveryTarget,
21
+ ScopeJudgement,
20
22
  settleRound
21
23
  } from '@kitman-sh/sdk/loop'
22
24
  import * as Effect from 'effect/Effect'
@@ -24,7 +26,8 @@ import * as Schema from 'effect/Schema'
24
26
  import build, { BuildInput, BuildOutput } from './build'
25
27
  import { verifyHead } from './change-request-body'
26
28
  import { DeliveryFields, ownDeliveryTarget } from './delivery'
27
- import { ReviewedScope } from './reviewed-scope'
29
+ import { caseOf, inCase, listedCases, numberedCases, OutOfScopeFinding, outOfScopeCase } from './out-of-scope'
30
+ import { type CriterionDisposition, ReviewedScope } from './reviewed-scope'
28
31
  import { FindingDetail, OneSentence, ShortStatement } from './text-limits'
29
32
 
30
33
  /** Build, by its schemas: the module imports this one, so its definition is not ready when this one loads. */
@@ -53,6 +56,8 @@ const choices = ['Post to the ChangeRequest', 'Fix here', 'Build from it', 'Done
53
56
  const Input = Schema.Struct({
54
57
  /** Reviews this ChangeRequest, then asks what next: posting, fixing and building are each the user's call. */
55
58
  changeRequestId: Schema.optional(Schema.String),
59
+ /** With `base` and `head`, the ChangeRequest the change delivers: Kitman gives its Task's Out of scope list only if that ChangeRequest delivers the Task. */
60
+ deliveredBy: Schema.optional(Schema.String),
56
61
  /** Or reviews `git diff base...head`, and only returns the findings. */
57
62
  base: Schema.optional(Schema.String),
58
63
  head: Schema.optional(Schema.String),
@@ -92,6 +97,16 @@ const Input = Schema.Struct({
92
97
  failing: Schema.optional(Schema.Array(Schema.String)),
93
98
  /** Why each head test verify never ran is unverified; a ChangeRequest's head is verified here too. */
94
99
  notRun: Schema.optional(Schema.Array(Schema.String)),
100
+ /** Earlier reviews' findings kept apart as out of scope; one whose case the Task no longer lists is open again. */
101
+ outOfScopeFindings: Schema.optional(Schema.Array(OutOfScopeFinding)),
102
+ /** The acceptance criteria the implementer answered not met, in its words, for the scope seat to judge. */
103
+ unmetCriteria: Schema.optional(Schema.Array(Schema.String)),
104
+ /** The other acceptance criteria, in the implementer's words, numbered after those so the scope seat can name one it finds not done. */
105
+ metCriteria: Schema.optional(Schema.Array(Schema.String)),
106
+ /** The criteria the implementer answered can only be seen once merged, in its words, numbered after the met ones. */
107
+ afterMergeCriteria: Schema.optional(Schema.Array(Schema.String)),
108
+ /** The Task's Out of scope list, the only cases a finding or unmet part may be waived for; Kitman sets it when the Run starts. */
109
+ taskOutOfScope: Schema.optional(Schema.Array(Schema.String)),
95
110
  /** What to do after a ChangeRequest's review without asking; Done when nobody answers. */
96
111
  next: Schema.optional(Schema.Literals(choices)),
97
112
  ...DeliveryFields
@@ -101,6 +116,13 @@ const FollowUpStatus = Schema.Literals(['fixed', 'changed', 'still_there'])
101
116
 
102
117
  const FollowUp = Schema.Struct({ id: Schema.String, status: FollowUpStatus })
103
118
 
119
+ const SeatFollowUp = Schema.Struct({
120
+ ...FollowUp.fields,
121
+ /** The problem's severity now, when it is not fixed and the fix changed it. */
122
+ severity: Schema.optional(Finding.fields.severity),
123
+ ...outOfScopeCase
124
+ })
125
+
104
126
  const SeatFinding = Schema.Struct({
105
127
  ...Finding.fields,
106
128
  detail: FindingDetail,
@@ -111,27 +133,200 @@ const SeatFinding = Schema.Struct({
111
133
  /** The sibling cases of that rule the seat checked and found fine. */
112
134
  checked: Schema.optional(Schema.Array(ShortStatement)),
113
135
  /** In a review of a fix: the problem is outside the fix and the code it touches. */
114
- outsideFix: Schema.optional(Schema.Boolean)
136
+ outsideFix: Schema.optional(Schema.Boolean),
137
+ ...outOfScopeCase
115
138
  })
116
139
 
117
- /** Met when nothing is unmet but what an answer put out of scope, so a waived criterion never blocks. */
118
- const agreedScope = (scope: typeof ReviewedScope.Type): typeof ReviewedScope.Type =>
119
- scope.unmet.length === 0 && (scope.reported ?? []).length > 0 ? { ...scope, met: true } : scope
140
+ const isText = Schema.is(Schema.String)
141
+
142
+ const SeatUnmet = Schema.Union([
143
+ Schema.String,
144
+ Schema.Struct({
145
+ part: Schema.String,
146
+ /** The numbered criterion it is, which its number's judgement in `criteria` settles. */
147
+ criterion: Schema.optional(Schema.Int),
148
+ ...outOfScopeCase
149
+ })
150
+ ])
151
+
152
+ const SeatScope = Schema.Struct({
153
+ ...ScopeJudgement.fields,
154
+ unmet: Schema.Array(SeatUnmet),
155
+ reported: Schema.optional(Schema.Array(Schema.String)),
156
+ /** Each of the implementer's unmet criteria, by number: met now, or why not. */
157
+ criteria: Schema.optional(
158
+ Schema.Array(
159
+ Schema.Struct({
160
+ criterion: Schema.Int,
161
+ met: Schema.optional(Schema.Boolean),
162
+ /** An answer under Answers so far put it out of scope. */
163
+ reported: Schema.optional(Schema.Boolean),
164
+ ...outOfScopeCase
165
+ })
166
+ )
167
+ )
168
+ })
169
+
170
+ type OutOfScopeParts = NonNullable<ReviewedScope['outOfScope']>
171
+
172
+ /** Each numbered criterion in its exact words, so Build knows which answer it settles; one judged two ways is open. */
173
+ const dispositionsOf = (
174
+ judged: NonNullable<(typeof SeatScope.Type)['criteria']>,
175
+ cases: readonly string[],
176
+ unmetCriteria: readonly string[],
177
+ reportedByAnswer: readonly string[]
178
+ ): readonly CriterionDisposition[] => {
179
+ const byCriterion = new Map<string, CriterionDisposition>()
180
+
181
+ for (const entry of judged) {
182
+ const criterion = unmetCriteria[entry.criterion - 1]
183
+
184
+ if (criterion === undefined) continue
185
+ const item = caseOf(cases, entry)
186
+
187
+ const disposition: CriterionDisposition =
188
+ entry.met === true
189
+ ? { criterion, status: 'met' }
190
+ : entry.reported === true || (item === undefined && reportedByAnswer.includes(criterion))
191
+ ? { criterion, status: 'reported' }
192
+ : item === undefined
193
+ ? { criterion, status: 'open' }
194
+ : { criterion, status: 'out_of_scope', item }
195
+
196
+ const known = byCriterion.get(criterion)
197
+
198
+ byCriterion.set(
199
+ criterion,
200
+ known === undefined || JSON.stringify(known) === JSON.stringify(disposition)
201
+ ? disposition
202
+ : { criterion, status: 'open' }
203
+ )
204
+ }
205
+
206
+ return [...byCriterion.values()]
207
+ }
208
+
209
+ /** Met when nothing is unmet but what this review found out of scope, so a waived criterion or case never blocks. */
210
+ const agreedScope = (
211
+ { unmet, criteria = [], reported: seatReported = [], ...scope }: typeof SeatScope.Type,
212
+ cases: readonly string[],
213
+ numberedCriteria: readonly string[],
214
+ earlier: OutOfScopeParts
215
+ ): ReviewedScope => {
216
+ const given = unmet.map(entry =>
217
+ isText(entry)
218
+ ? { part: entry, item: undefined }
219
+ : {
220
+ part: (entry.criterion === undefined ? undefined : numberedCriteria[entry.criterion - 1]) ?? entry.part,
221
+ item: caseOf(cases, entry)
222
+ }
223
+ )
224
+
225
+ const numbered = new Set(numberedCriteria)
226
+ const parts = given.filter(({ part }) => !numbered.has(part))
227
+ const judgedByNumber = dispositionsOf(criteria, cases, numberedCriteria, seatReported)
228
+ const named = given.filter(({ part }) => numbered.has(part))
229
+
230
+ // A numbered criterion's number wins over a line in `unmet` naming it, unless the two disagree on whether it is done.
231
+ const dispositions = [
232
+ ...judgedByNumber.map(entry =>
233
+ entry.status === 'met' && named.some(({ part }) => part === entry.criterion)
234
+ ? { criterion: entry.criterion, status: 'open' as const }
235
+ : entry
236
+ ),
237
+ ...named.flatMap(({ part, item }, index): readonly CriterionDisposition[] =>
238
+ judgedByNumber.some(entry => entry.criterion === part) || named.findIndex(other => other.part === part) !== index
239
+ ? []
240
+ : named.filter(other => other.part === part).every(other => other.item === item) && item !== undefined
241
+ ? [{ criterion: part, status: 'out_of_scope', item }]
242
+ : [{ criterion: part, status: 'open' }]
243
+ )
244
+ ]
245
+
246
+ const criteriaApart = dispositions.flatMap(({ criterion, item }) =>
247
+ item === undefined ? [] : [{ part: criterion, item }]
248
+ )
249
+
250
+ const marked = [...parts.flatMap(({ part, item }) => (item === undefined ? [] : [{ part, item }])), ...criteriaApart]
251
+ const waivedParts = new Set(marked.map(entry => entry.part))
252
+
253
+ const left = [
254
+ ...new Set([
255
+ ...parts.flatMap(({ part }) => (waivedParts.has(part) ? [] : [part])),
256
+ ...dispositions.flatMap(entry => (entry.status === 'open' ? [entry.criterion] : []))
257
+ ])
258
+ ]
259
+
260
+ const judgedAgain = new Set([...waivedParts, ...left, ...dispositions.map(entry => entry.criterion)])
261
+ const kept = earlier.filter(({ part }) => !judgedAgain.has(part))
262
+ const outOfScope = [...kept, ...marked]
263
+ const byAnswer = dispositions.flatMap(entry => (entry.status === 'reported' ? [entry.criterion] : []))
264
+ const judgedOtherwise = new Set(dispositions.flatMap(entry => (entry.status === 'reported' ? [] : [entry.criterion])))
265
+
266
+ // A report of a criterion this review judged by its number another way justifies nothing.
267
+ const reported = [...new Set([...seatReported, ...byAnswer])].filter(
268
+ part => !left.includes(part) && !judgedOtherwise.has(part)
269
+ )
270
+
271
+ const waived = reported.length + marked.length
272
+ // Without a list, a seat that names an unmet part but calls the scope met is taken at its word, as before.
273
+ const strict = cases.length > 0 || unmet.some(entry => !isText(entry))
274
+
275
+ return {
276
+ ...scope,
277
+ ...(reported.length === 0 ? undefined : { reported }),
278
+ unmet: left,
279
+ met: left.length === 0 ? scope.met || waived > 0 : scope.met && !strict,
280
+ ...(outOfScope.length === 0 ? undefined : { outOfScope }),
281
+ ...(dispositions.length === 0 ? undefined : { criteria: dispositions })
282
+ }
283
+ }
284
+
285
+ /** A numbered criterion this review neither judged nor kept reported or apart is unmet, so no review passes without judging it. */
286
+ const withUnjudged = (
287
+ scope: ReviewedScope | undefined,
288
+ unmetCriteria: readonly string[]
289
+ ): ReviewedScope | undefined => {
290
+ const settled = new Set([
291
+ ...(scope?.criteria ?? []).map(entry => entry.criterion),
292
+ ...(scope?.outOfScope ?? []).map(entry => entry.part),
293
+ ...(scope?.reported ?? []),
294
+ ...(scope?.unmet ?? [])
295
+ ])
296
+
297
+ const unjudged = unmetCriteria.filter(criterion => !settled.has(criterion))
298
+
299
+ return unjudged.length === 0 ? scope : { ...scope, met: false, unmet: [...(scope?.unmet ?? []), ...unjudged] }
300
+ }
120
301
 
121
- /** This review's judgement, or the earlier one when it gave none. What was reported stays so unless it is unmet now. */
302
+ /** This review's judgement, or the earlier one when it gave none. What was reported or out of scope stays so unless it is unmet now. */
122
303
  const carriedScope = (
123
- judged: typeof ReviewedScope.Type | undefined,
124
- earlier: typeof ReviewedScope.Type | undefined
125
- ): typeof ReviewedScope.Type | undefined => {
126
- if (judged === undefined) return earlier
304
+ judged: typeof SeatScope.Type | undefined,
305
+ earlier: ReviewedScope | undefined,
306
+ cases: readonly string[],
307
+ numberedCriteria: readonly string[]
308
+ ): ReviewedScope | undefined => {
309
+ if (judged === undefined) {
310
+ if (earlier === undefined) return undefined
311
+ const { criteria: _, ...carried } = earlier
312
+
313
+ return carried
314
+ }
315
+
316
+ const scope = agreedScope(judged, cases, numberedCriteria, earlier?.outOfScope ?? [])
127
317
 
128
- const scope = agreedScope(judged)
318
+ const judgedOtherwise = new Set(
319
+ (scope.criteria ?? []).flatMap(entry => (entry.status === 'reported' ? [] : [entry.criterion]))
320
+ )
129
321
 
130
322
  const reported = [...new Set([...(earlier?.reported ?? []), ...(scope.reported ?? [])])].filter(
131
- item => !scope.unmet.includes(item)
323
+ item => !scope.unmet.includes(item) && !judgedOtherwise.has(item)
132
324
  )
133
325
 
134
- return earlier === undefined || reported.length === 0 ? scope : { ...scope, reported }
326
+ if (earlier === undefined) return scope
327
+ const { reported: _, ...rest } = scope
328
+
329
+ return reported.length === 0 ? rest : { ...rest, reported }
135
330
  }
136
331
 
137
332
  const SeatOutput = Schema.Struct({
@@ -139,16 +334,29 @@ const SeatOutput = Schema.Struct({
139
334
  summary: OneSentence,
140
335
  findings: Schema.Array(SeatFinding),
141
336
  verdicts: Schema.optional(Schema.Array(RebuttalVerdict)),
142
- scope: Schema.optional(ReviewedScope),
143
- followUps: Schema.optional(Schema.Array(FollowUp))
337
+ scope: Schema.optional(SeatScope),
338
+ followUps: Schema.optional(Schema.Array(SeatFollowUp))
339
+ })
340
+
341
+ const ApprovedFinding = Schema.Struct({
342
+ ...MergedFinding.fields,
343
+ item: Schema.optionalKey(Schema.String),
344
+ problem: OutOfScopeFinding.fields.problem
144
345
  })
145
346
 
347
+ type ApprovedFinding = typeof ApprovedFinding.Type
348
+
146
349
  const Output = Schema.Struct({
147
350
  /** What the review leads with: each reviewer's one sentence. */
148
351
  summary: Schema.String,
149
352
  findings: Schema.Array(MergedFinding),
150
- /** In a review since an approved head, the findings about code that head already had; they never block. */
151
- approvedFindings: Schema.optional(Schema.Array(MergedFinding)),
353
+ /**
354
+ * In a review since an approved head, the findings about code that head already had; they never block. One in a case
355
+ * the Task lists as Out of scope keeps its case as `item`, at its own severity.
356
+ */
357
+ approvedFindings: Schema.optional(Schema.Array(ApprovedFinding)),
358
+ /** The majors and minors in cases the Task lists as Out of scope, earlier reviews' among them; they never block. */
359
+ outOfScopeFindings: Schema.optional(Schema.Array(OutOfScopeFinding)),
152
360
  /** Each earlier finding, as fixed, changed but not fixed, or still there. */
153
361
  followUps: Schema.Array(FollowUp),
154
362
  verdicts: Schema.Array(RebuttalVerdict),
@@ -209,7 +417,7 @@ const targetOf = (input: typeof Input.Type, { base, head, branches, epic }: Rang
209
417
  if (input.files === undefined && input.approved !== undefined)
210
418
  return [
211
419
  `only what the change gained or lost since it was approved at ${input.approved}: compare \`git diff ${base}...${input.approved}\`, the change as approved, with \`git diff ${base}...${head}\`, the change now, in your checkout. The rest was reviewed and approved before.`,
212
- 'Report a problem in code the change already had at the approved head only if it matters, with `approvedCode` set to true: such findings are kept apart and do not block.'
420
+ "Report a problem in code the change already had at the approved head only if it matters, with `approvedCode` set to true: such findings are kept apart and do not block, unless one is a blocker in one of the Task's numbered out-of-scope cases."
213
421
  ].join('\n\n')
214
422
 
215
423
  return input.files === undefined
@@ -265,35 +473,146 @@ const pinnedRange = (input: typeof Input.Type) =>
265
473
  /** A review of the whole change judges its scope; one of some files or of a change since an approval does not. */
266
474
  const wholeChange = (input: typeof Input.Type) => input.files === undefined && input.approved === undefined
267
475
 
268
- const wholeScopePrompt =
269
- "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."
476
+ const casesOf = (input: typeof Input.Type) => listedCases(input.taskOutOfScope)
477
+
478
+ const unmetCriteriaOf = (input: typeof Input.Type) => (casesOf(input).length === 0 ? [] : (input.unmetCriteria ?? []))
270
479
 
271
- const rejudgedScopePrompt = (unmet: readonly string[]) =>
480
+ const afterMergeCriteriaOf = (input: typeof Input.Type) =>
481
+ casesOf(input).length === 0 ? [] : (input.afterMergeCriteria ?? [])
482
+
483
+ /** The criteria the scope seat judges by number: the unmet ones first. */
484
+ const criteriaOf = (input: typeof Input.Type) =>
485
+ casesOf(input).length === 0
486
+ ? []
487
+ : [...new Set([...unmetCriteriaOf(input), ...(input.metCriteria ?? []), ...afterMergeCriteriaOf(input)])]
488
+
489
+ const outOfScopePrompt = (cases: readonly string[]) =>
272
490
  [
491
+ "The Task's Out of scope list is these numbered cases, and no other list in your brief is. The change need not handle them, so a case it does not handle is not missing scope:",
492
+ ...numberedCases(cases),
493
+ "Report a problem in one of them at its real severity, with `outOfScope` set to the case's number: a major or minor is kept apart and does not block. A blocker there, such as a security hole or lost data, still blocks."
494
+ ].join('\n')
495
+
496
+ const wholeScopePrompt =
497
+ "If your brief has a Task, judge its scope and give it as `scope`: does the change make the Task's Promise true, if it has one, and 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, unless it is a numbered criterion your brief asks you to judge in `criteria`, 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 the Promise and each other criterion or part of the description that is not done, except a numbered criterion, which you judge in `criteria` alone. If your brief has no Task, leave `scope` out."
498
+
499
+ const rejudgedScopePrompt = ({ unmet, outOfScope = [] }: ReviewedScope, numbered: readonly string[]) => {
500
+ const shown = unmet.filter(item => !numbered.includes(item))
501
+
502
+ return [
273
503
  [
274
- "If your brief has a Task, judge its scope again and give it as `scope`. An earlier round judged what the Task's description and Acceptance Criteria ask, and that stands, so do not judge all of it again.",
504
+ "If your brief has a Task, judge its scope again and give it as `scope`. An earlier round judged what the Task's Promise, if it has one, its description and Acceptance Criteria ask, and that stands, so do not judge all of it again.",
275
505
  ...(unmet.length === 0
276
506
  ? ['It found nothing unmet.']
277
- : [
278
- 'It found these unmet. Judge each of these again, against the code at the head, and list each that is still not done in `unmet`, in the same words:',
279
- ...unmet.map(item => `- ${item}`)
280
- ])
507
+ : shown.length === 0
508
+ ? ['What it found unmet is among the numbered criteria below, which you judge by number.']
509
+ : [
510
+ `It found these unmet. Judge each of these again, against the code at the head, and list each that is still not done in \`unmet\`, in the same words${numbered.length === 0 ? '' : ', unless it is one of the numbered criteria below: judge that one by its number alone, which wins over any line naming it'}:`,
511
+ ...shown.map(item => `- ${item}`)
512
+ ])
281
513
  ].join('\n'),
282
- "Also list in `unmet`, one line each, any criterion or part the fix undoes. What an answer under your brief's Answers so far put out of scope is reported, not unmet: list each of these in `reported` instead. Set `met` to true only if `unmet` is empty. If your brief has no Task, leave `scope` out."
514
+ ...(outOfScope.length === 0
515
+ ? []
516
+ : [
517
+ [
518
+ "It found these not done only because of one of the Task's numbered out-of-scope cases. They stay reported apart, so leave them out of `unmet`:",
519
+ ...outOfScope.map(({ part, item }) => `- ${inCase(part, item)}`)
520
+ ].join('\n')
521
+ ]),
522
+ "Also list in `unmet`, one line each, the Promise and any criterion or part the fix undoes, except a numbered criterion, which you judge in `criteria` alone. What an answer under your brief's Answers so far put out of scope is reported, not unmet: list each of these in `reported` instead, unless it is a numbered criterion. Set `met` to true only if `unmet` is empty. If your brief has no Task, leave `scope` out."
283
523
  ].join('\n\n')
524
+ }
284
525
 
285
526
  /** A review of a fix: given an earlier review's findings, or the head an earlier review read. */
286
527
  const fixRound = (input: typeof Input.Type) => (input.earlier?.length ?? 0) > 0 || input.reviewed !== undefined
287
528
 
529
+ /** In a review of a fix, the earlier judgement; a part put in a case the Task no longer lists is unmet again. */
530
+ const earlierScope = (input: typeof Input.Type): ReviewedScope | undefined => {
531
+ if (!fixRound(input) || input.scope === undefined) return undefined
532
+
533
+ const { outOfScope = [], ...scope } = input.scope
534
+ const listed = outOfScope.filter(({ item }) => casesOf(input).includes(item))
535
+ const unlisted = outOfScope.flatMap(entry => (listed.includes(entry) ? [] : [entry.part]))
536
+
537
+ return {
538
+ ...scope,
539
+ ...(unlisted.length === 0 ? undefined : { met: false, unmet: [...new Set([...scope.unmet, ...unlisted])] }),
540
+ ...(listed.length === 0 ? undefined : { outOfScope: listed })
541
+ }
542
+ }
543
+
288
544
  /** The earlier judgement a review of a fix starts from; undefined when it is unmet but names nothing. */
289
- const scopeToRejudge = (input: typeof Input.Type) =>
290
- fixRound(input) && (input.scope?.met === true || (input.scope?.unmet.length ?? 0) > 0) ? input.scope : undefined
545
+ const scopeToRejudge = (input: typeof Input.Type) => {
546
+ const scope = earlierScope(input)
547
+
548
+ return scope?.met === true || (scope?.unmet.length ?? 0) > 0 ? scope : undefined
549
+ }
550
+
551
+ /** The numbered criteria an earlier round of this review found not done, which a review of the fix must judge again. */
552
+ const earlierOpenCriteriaOf = (input: typeof Input.Type) => {
553
+ const scope = earlierScope(input)
554
+
555
+ const open = new Set([
556
+ ...(scope?.unmet ?? []),
557
+ ...(scope?.criteria ?? []).flatMap(entry => (entry.status === 'open' ? [entry.criterion] : []))
558
+ ])
559
+
560
+ return criteriaOf(input).filter(criterion => open.has(criterion))
561
+ }
562
+
563
+ /** The numbered criteria the scope seat must judge in every review: those answered not met, and those found not done. */
564
+ const requiredCriteriaOf = (input: typeof Input.Type) => [
565
+ ...new Set([...unmetCriteriaOf(input), ...earlierOpenCriteriaOf(input)])
566
+ ]
567
+
568
+ const numbersOf = (input: typeof Input.Type, criteria: readonly string[]) =>
569
+ criteriaOf(input).flatMap((criterion, index) => (criteria.includes(criterion) ? [index + 1] : []))
570
+
571
+ const answeredPrompt = (input: typeof Input.Type) => {
572
+ const notMet = numbersOf(input, unmetCriteriaOf(input))
573
+ const afterMerge = numbersOf(input, afterMergeCriteriaOf(input))
574
+ const reopened = numbersOf(input, earlierOpenCriteriaOf(input)).filter(number => !notMet.includes(number))
575
+ const required = [...notMet, ...reopened].toSorted((left, right) => left - right)
576
+
577
+ return [
578
+ notMet.length === 0 && afterMerge.length === 0
579
+ ? 'The implementer answered each of them met.'
580
+ : `The implementer answered ${[
581
+ ...(notMet.length === 0 ? [] : [`${notMet.join(', ')} not met`]),
582
+ ...(afterMerge.length === 0
583
+ ? []
584
+ : [
585
+ `${afterMerge.join(', ')} after merge, as their result shows only once the change is merged; judge those by the code, never as not done only because that result cannot be seen yet`
586
+ ])
587
+ ].join(', and ')}, and the rest met.`,
588
+ ...(reopened.length === 0 ? [] : [`An earlier round found ${reopened.join(', ')} not done.`]),
589
+ required.length === 0
590
+ ? 'Give one only if the change does not do it.'
591
+ : `Judge ${required.join(', ')} every time, and any other only if the change does not do it.`
592
+ ].join(' ')
593
+ }
291
594
 
292
595
  const scopePrompt = (input: typeof Input.Type) => {
293
596
  const earlier = scopeToRejudge(input)
294
597
 
295
598
  return [
296
- earlier === undefined ? wholeScopePrompt : rejudgedScopePrompt(earlier.unmet),
599
+ earlier === undefined ? wholeScopePrompt : rejudgedScopePrompt(earlier, criteriaOf(input)),
600
+ ...(casesOf(input).length === 0
601
+ ? []
602
+ : [
603
+ `A part that is not done only because it falls in one of the Task's numbered out-of-scope cases is never unmet, even where the Promise, the description or a criterion covers it. Give it in \`unmet\` as \`{ part, outOfScope }\`, with the case's number; Kitman reports it apart. Give each part once${criteriaOf(input).length === 0 ? '' : ', and a numbered criterion only by its number'}.`
604
+ ]),
605
+ ...(criteriaOf(input).length === 0
606
+ ? []
607
+ : [
608
+ [
609
+ [
610
+ "The Task's acceptance criteria are numbered below, in the implementer's words. Judge a numbered criterion in `criteria` alone, by its number, as `{ criterion, met }`: `met` true only if the change does it. For one not done only because of a numbered out-of-scope case, also set `outOfScope` to the case's number; for one an answer under your brief's Answers so far put out of scope, set `reported` to true instead. Leave them out of `unmet` and `reported`, even one an answer put out of scope or one you would word as the Task does: Kitman lists them there itself, and a criterion's number wins over any line there that names it. If you still give a line in `unmet` about one, give it as `{ part, criterion }` with the criterion's number.",
611
+ answeredPrompt(input)
612
+ ].join(' '),
613
+ ...numberedCases(criteriaOf(input))
614
+ ].join('\n')
615
+ ]),
297
616
  ...(input.outcome === undefined ? [] : [`The Outcome to prove is ${input.outcome}.`]),
298
617
  ...(input.claims === undefined || input.claims.length === 0
299
618
  ? []
@@ -312,14 +631,30 @@ const exhaustivePrompt = (subject: string) =>
312
631
  '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.'
313
632
  ].join(' ')
314
633
 
315
- const earlierPrompt = (earlier: readonly MergedFinding[]) =>
634
+ const earlierPrompt = (earlier: readonly MergedFinding[], cases: readonly string[]) =>
316
635
  [
317
- 'Earlier rounds, by both reviewers, left these findings open. 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.',
636
+ [
637
+ 'Earlier rounds, by both reviewers, left these findings open. 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.',
638
+ ...(cases.length === 0
639
+ ? []
640
+ : [
641
+ "If one that is not fixed is in one of the Task's numbered out-of-scope cases, set `outOfScope` on its entry to the case's number.",
642
+ 'If one that is not fixed now has another severity, worse or less bad, set `severity` on its entry to its severity now: a blocker always blocks.',
643
+ 'Report a different problem on the same line as a finding.'
644
+ ])
645
+ ].join(' '),
318
646
  ...earlier.map(finding => `- ${finding.id} (${finding.severity}): ${finding.detail}`)
319
647
  ].join('\n')
320
648
 
321
- const outsideFixPrompt =
322
- '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.'
649
+ const outsideFixPrompt = (cases: readonly string[]) =>
650
+ [
651
+ '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.',
652
+ ...(cases.length === 0
653
+ ? []
654
+ : [
655
+ "A problem in one of the Task's numbered out-of-scope cases is the exception: report it at its real severity, with `outOfScope` set."
656
+ ])
657
+ ].join(' ')
323
658
 
324
659
  /** The fix a review of one reads, in place of the change `targetOf` names. */
325
660
  const fixTargetOf = (input: typeof Input.Type, { head, branches, epic }: Range) => {
@@ -337,7 +672,7 @@ const fixTargetOf = (input: typeof Input.Type, { head, branches, epic }: Range)
337
672
  ? input.approved === undefined
338
673
  ? []
339
674
  : [
340
- `The change was approved at ${input.approved}. Report a problem in code it already had there only if it matters, with \`approvedCode\` set to true: such findings are kept apart and do not block.`
675
+ `The change was approved at ${input.approved}. Report a problem in code it already had there only if it matters, with \`approvedCode\` set to true: such findings are kept apart and do not block, unless one is a blocker in one of the Task's numbered out-of-scope cases.`
341
676
  ]
342
677
  : [
343
678
  [
@@ -357,6 +692,7 @@ const promptFor = (
357
692
  seat: keyof typeof seats,
358
693
  target: string,
359
694
  input: typeof Input.Type,
695
+ earlier: readonly MergedFinding[],
360
696
  failing: readonly string[],
361
697
  notRun: readonly string[]
362
698
  ) =>
@@ -367,10 +703,11 @@ const promptFor = (
367
703
  '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.',
368
704
  exhaustivePrompt(fixRound(input) ? 'the fix' : 'the change'),
369
705
  "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.",
706
+ ...(casesOf(input).length === 0 ? [] : [outOfScopePrompt(casesOf(input))]),
370
707
  '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.',
371
708
  ...(seat === scopeSeat && wholeChange(input) ? [scopePrompt(input)] : []),
372
- ...(input.earlier === undefined || input.earlier.length === 0 ? [] : [earlierPrompt(input.earlier)]),
373
- ...(fixRound(input) ? [outsideFixPrompt] : []),
709
+ ...(earlier.length === 0 ? [] : [earlierPrompt(earlier, casesOf(input))]),
710
+ ...(fixRound(input) ? [outsideFixPrompt(casesOf(input))] : []),
374
711
  ...(failing.length === 0
375
712
  ? []
376
713
  : [
@@ -400,6 +737,30 @@ type SeatFinding = typeof SeatFinding.Type
400
737
  const outsideFixAsMinor = (finding: SeatFinding): SeatFinding =>
401
738
  finding.outsideFix === true && finding.severity === 'major' ? { ...finding, severity: 'minor' } : finding
402
739
 
740
+ /**
741
+ * The findings to follow up: the open ones, and those kept apart in a case the Task no longer lists. One of those on an
742
+ * open finding's line keeps an id of its own, so a rebuttal of the open one does not settle it.
743
+ */
744
+ const earlierOf = (input: typeof Input.Type): readonly MergedFinding[] => {
745
+ const followed = new Map((input.earlier ?? []).map(finding => [finding.id, finding]))
746
+
747
+ for (const { item, problem: _, ...finding } of input.outOfScopeFindings ?? []) {
748
+ if (casesOf(input).includes(item)) continue
749
+ const taken = new Set(followed.keys())
750
+ const id = taken.has(finding.id) ? ownId(inCase(finding.id, item), taken) : finding.id
751
+
752
+ followed.set(id, { ...finding, id })
753
+ }
754
+
755
+ return [...followed.values()]
756
+ }
757
+
758
+ const keptApart = (
759
+ finding: MergedFinding & { readonly problem?: string },
760
+ item: string
761
+ ): readonly OutOfScopeFinding[] =>
762
+ finding.severity === 'blocker' ? [] : [{ ...finding, severity: finding.severity, item }]
763
+
403
764
  const detailOf = (detail: string, rule: string | undefined, checked: readonly string[]) =>
404
765
  [
405
766
  ...(rule === undefined ? [] : [`[${rule}]`]),
@@ -409,9 +770,58 @@ const detailOf = (detail: string, rule: string | undefined, checked: readonly st
409
770
 
410
771
  const severityRank = { blocker: 0, major: 1, minor: 2 } as const
411
772
 
773
+ const ownId = (id: string, taken: ReadonlySet<string>) => {
774
+ if (!taken.has(id)) return id
775
+ let number = 2
776
+
777
+ while (taken.has(`${id} (${number})`)) number++
778
+
779
+ return `${id} (${number})`
780
+ }
781
+
782
+ const wordingsOf = ({ detail, problem }: OutOfScopeFinding) => (problem === undefined ? [detail] : [detail, problem])
783
+
784
+ /** Each problem once, at the worst severity given it, under an id of its own so each is followed up alone. */
785
+ const distinctApart = (
786
+ findings: readonly OutOfScopeFinding[],
787
+ taken: ReadonlySet<string> = new Set()
788
+ ): readonly OutOfScopeFinding[] => {
789
+ const kept: OutOfScopeFinding[] = []
790
+
791
+ for (const finding of findings) {
792
+ const index = kept.findIndex(
793
+ known =>
794
+ known.file === finding.file &&
795
+ known.line === finding.line &&
796
+ known.item === finding.item &&
797
+ wordingsOf(known).some(wording => wordingsOf(finding).includes(wording))
798
+ )
799
+
800
+ const same = kept[index]
801
+
802
+ if (same === undefined) {
803
+ kept.push({ ...finding, id: ownId(finding.id, new Set([...taken, ...kept.map(known => known.id)])) })
804
+ continue
805
+ }
806
+
807
+ kept[index] = {
808
+ ...same,
809
+ ...(same.problem !== undefined || finding.problem === undefined ? undefined : { problem: finding.problem }),
810
+ severity: severityRank[finding.severity] < severityRank[same.severity] ? finding.severity : same.severity,
811
+ seats: [...new Set([...same.seats, ...finding.seats])]
812
+ }
813
+ }
814
+
815
+ return kept
816
+ }
817
+
412
818
  const blockingSeatsOf = (finding: MergedFinding) =>
413
819
  isBlocking(finding) ? (finding.blockingSeats ?? finding.seats) : []
414
820
 
821
+ const stillOpen = ' Still open on this line: '
822
+
823
+ const problemsOf = (detail: string) => detail.split(stillOpen).map(problem => problem.trim())
824
+
415
825
  /** A worse problem on an open finding's line, with that finding's own. */
416
826
  const withEarlier = (worse: MergedFinding, earlier: MergedFinding): MergedFinding => {
417
827
  const { blockingSeats: _, ...finding } = worse
@@ -420,7 +830,7 @@ const withEarlier = (worse: MergedFinding, earlier: MergedFinding): MergedFindin
420
830
 
421
831
  return {
422
832
  ...finding,
423
- detail: `${finding.detail} Still open on this line: ${earlier.detail}`,
833
+ detail: `${finding.detail}${stillOpen}${earlier.detail}`,
424
834
  seats,
425
835
  ...(blockingSeats.length === seats.length ? undefined : { blockingSeats })
426
836
  }
@@ -432,7 +842,11 @@ const idOf = (finding: SeatFinding) => `${finding.file}:${finding.line}`
432
842
  * Merges the seats' findings with the rule and the cases checked for each in its detail, those of one rule together.
433
843
  * A line takes the first rule any seat gave it and every seat's checked cases, whichever seat's detail the merge keeps.
434
844
  */
435
- const groupedByRule = (bySeat: { readonly [seat: string]: readonly SeatFinding[] }) => {
845
+ const groupedByRule = (
846
+ bySeat: { readonly [seat: string]: readonly SeatFinding[] },
847
+ cases: readonly string[],
848
+ taken: Set<string>
849
+ ) => {
436
850
  const rules = new Map<string, string>()
437
851
  const checked = new Map<string, Set<string>>()
438
852
 
@@ -443,25 +857,91 @@ const groupedByRule = (bySeat: { readonly [seat: string]: readonly SeatFinding[]
443
857
  checked.set(id, new Set([...(checked.get(id) ?? []), ...(finding.checked ?? [])]))
444
858
  }
445
859
 
860
+ const detailed = (finding: SeatFinding) =>
861
+ detailOf(finding.detail, rules.get(idOf(finding)), [...(checked.get(idOf(finding)) ?? [])])
862
+
863
+ // Across seats a blocker merges by line unless marked with a case the line's first blocker lacks.
864
+ const distinct: (MergedFinding & { readonly problem: string })[] = []
865
+
866
+ const blockers = Object.entries(bySeat).flatMap(([seat, seatFindings]) =>
867
+ seatFindings.flatMap(finding => (finding.severity === 'blocker' ? [{ seat, finding }] : []))
868
+ )
869
+
870
+ const firstOn = new Map<string, SeatFinding>()
871
+
872
+ for (const { finding } of blockers) if (!firstOn.has(idOf(finding))) firstOn.set(idOf(finding), finding)
873
+
874
+ const merges = new Set(
875
+ Object.keys(bySeat).flatMap(seat =>
876
+ [...firstOn].flatMap(([id, first]) => {
877
+ const own = blockers
878
+ .filter(entry => entry.seat === seat && idOf(entry.finding) === id)
879
+ .map(entry => entry.finding)
880
+
881
+ return own.find(finding => finding.detail === first.detail) ?? own[0] ?? []
882
+ })
883
+ )
884
+ )
885
+
886
+ const merging = Object.entries(bySeat).map(
887
+ ([seat, seatFindings]) =>
888
+ [
889
+ seat,
890
+ seatFindings.flatMap(finding => {
891
+ const id = idOf(finding)
892
+ const first = firstOn.get(id)
893
+ const marked = caseOf(cases, finding)
894
+
895
+ const another =
896
+ finding.severity === 'blocker' &&
897
+ cases.length > 0 &&
898
+ finding.detail !== first?.detail &&
899
+ (!merges.has(finding) || (marked !== undefined && marked !== (first && caseOf(cases, first))))
900
+
901
+ if (!another) return [finding]
902
+
903
+ const index = distinct.findIndex(known => known.id === id && known.problem === finding.detail)
904
+ const known = distinct[index]
905
+
906
+ if (known === undefined)
907
+ distinct.push({ ...finding, id, detail: detailed(finding), seats: [seat], problem: finding.detail })
908
+ else distinct[index] = { ...known, seats: [...new Set([...known.seats, seat])] }
909
+
910
+ return []
911
+ })
912
+ ] as const
913
+ )
914
+
446
915
  const findings = mergeFindings(
447
916
  Object.fromEntries(
448
- Object.entries(bySeat).map(([seat, seatFindings]) => [
917
+ merging.map(([seat, seatFindings]) => [
449
918
  seat,
450
919
  seatFindings.map(finding => ({
451
920
  severity: finding.severity,
452
921
  file: finding.file,
453
922
  line: finding.line,
454
- detail: detailOf(finding.detail, rules.get(idOf(finding)), [...(checked.get(idOf(finding)) ?? [])])
923
+ detail: detailed(finding)
455
924
  }))
456
925
  ])
457
926
  )
458
927
  )
459
928
 
929
+ for (const finding of findings) taken.add(finding.id)
930
+
931
+ const apart = distinct.map(({ file, line, severity, detail, seats, id }) => {
932
+ const own = ownId(id, taken)
933
+
934
+ taken.add(own)
935
+
936
+ return { id: own, severity, file, line, detail, seats }
937
+ })
938
+
460
939
  // Groups keep the order of their worst finding, as mergeFindings sorts by severity.
461
- const groupOf = (finding: MergedFinding) => rules.get(finding.id) ?? finding.id
462
- const order = [...new Set(findings.map(groupOf))]
940
+ const groupOf = (finding: MergedFinding) => rules.get(`${finding.file}:${finding.line}`) ?? finding.id
941
+ const all = [...findings, ...apart]
942
+ const order = [...new Set(all.map(groupOf))]
463
943
 
464
- return findings.toSorted((left, right) => order.indexOf(groupOf(left)) - order.indexOf(groupOf(right)))
944
+ return all.toSorted((left, right) => order.indexOf(groupOf(left)) - order.indexOf(groupOf(right)))
465
945
  }
466
946
 
467
947
  /** Each earlier finding's status: the worst any seat gave, and still there when no seat answered for it. */
@@ -478,6 +958,52 @@ const followUpsOf = (earlier: readonly MergedFinding[], answers: readonly (typeo
478
958
  }
479
959
  })
480
960
 
961
+ type SeatedFollowUp = typeof SeatFollowUp.Type & { readonly seat: string }
962
+
963
+ /**
964
+ * An earlier finding at the worst severity the seats that find it not fixed say it has now, which may be less than
965
+ * before, with the seats that judged it blocking.
966
+ */
967
+ const currentOf = (finding: MergedFinding, answers: readonly SeatedFollowUp[]): MergedFinding => {
968
+ const judging = answers.flatMap(({ id, status, severity, seat }) =>
969
+ id === finding.id && status !== 'fixed' && severity !== undefined ? [{ seat, severity }] : []
970
+ )
971
+
972
+ const now = judging.reduce<Severity | undefined>(
973
+ (worst, { severity }) => (worst === undefined || severityRank[severity] < severityRank[worst] ? severity : worst),
974
+ undefined
975
+ )
976
+
977
+ if (now === undefined || now === finding.severity) return finding
978
+ const { blockingSeats: _, ...current } = finding
979
+ const seats = [...new Set([...finding.seats, ...judging.map(({ seat }) => seat)])]
980
+
981
+ const blockingSeats = isBlocking({ severity: now })
982
+ ? [
983
+ ...new Set([
984
+ ...blockingSeatsOf(finding),
985
+ ...judging.flatMap(({ seat, severity }) => (isBlocking({ severity }) ? [seat] : []))
986
+ ])
987
+ ]
988
+ : []
989
+
990
+ return {
991
+ ...current,
992
+ severity: now,
993
+ seats,
994
+ ...(blockingSeats.length === 0 || blockingSeats.length === seats.length ? undefined : { blockingSeats })
995
+ }
996
+ }
997
+
998
+ /** The out-of-scope case an earlier major or minor falls in, when every seat that finds it not fixed says it is in one. */
999
+ const earlierCaseOf = (finding: MergedFinding, answers: readonly SeatedFollowUp[], cases: readonly string[]) => {
1000
+ const items = answers.flatMap(answer =>
1001
+ answer.id === finding.id && answer.status !== 'fixed' ? [caseOf(cases, answer)] : []
1002
+ )
1003
+
1004
+ return finding.severity === 'blocker' || items.includes(undefined) ? undefined : items[0]
1005
+ }
1006
+
481
1007
  const findingLines = (findings: readonly MergedFinding[]) =>
482
1008
  findings
483
1009
  .map(finding => `- **${finding.severity}** \`${finding.id}\` ${finding.detail} _(${finding.seats.join(', ')})_`)
@@ -487,11 +1013,15 @@ const reviewText = (
487
1013
  summary: string,
488
1014
  findings: readonly MergedFinding[],
489
1015
  followUps: readonly (typeof FollowUp.Type)[],
490
- approvedFindings: readonly MergedFinding[],
1016
+ approvedFindings: readonly ApprovedFinding[],
1017
+ outOfScopeFindings: readonly MergedFinding[],
491
1018
  notRun: readonly string[],
492
- reported: readonly string[]
493
- ) =>
494
- [
1019
+ scope: ReviewedScope | undefined
1020
+ ) => {
1021
+ const reported = scope?.reported ?? []
1022
+ const outOfScope = scope?.outOfScope ?? []
1023
+
1024
+ return [
495
1025
  `**Kitman review.** ${summary}`,
496
1026
  ...(reported.length === 0
497
1027
  ? []
@@ -502,13 +1032,29 @@ const reviewText = (
502
1032
  ...(findings.length === 0 ? [] : [findingLines(findings)]),
503
1033
  ...(approvedFindings.length === 0
504
1034
  ? []
505
- : [`In code approved before, not blocking:\n${findingLines(approvedFindings)}`]),
1035
+ : [
1036
+ `In code approved before, not blocking:\n${findingLines(
1037
+ approvedFindings.map(({ item, ...finding }) =>
1038
+ item === undefined ? finding : { ...finding, detail: inCase(finding.detail, item) }
1039
+ )
1040
+ )}`
1041
+ ]),
1042
+ ...(outOfScope.length + outOfScopeFindings.length === 0
1043
+ ? []
1044
+ : [
1045
+ [
1046
+ 'In a case the Task lists as Out of scope, so reported, not blocking:',
1047
+ ...outOfScope.map(({ part, item }) => `- ${inCase(part, item)}`),
1048
+ ...(outOfScopeFindings.length === 0 ? [] : [findingLines(outOfScopeFindings)])
1049
+ ].join('\n')
1050
+ ]),
506
1051
  ...(followUps.length === 0
507
1052
  ? []
508
1053
  : [
509
1054
  `Earlier findings:\n${followUps.map(entry => `- \`${entry.id}\` ${entry.status.replace('_', ' ')}`).join('\n')}`
510
1055
  ])
511
1056
  ].join('\n\n')
1057
+ }
512
1058
 
513
1059
  const fixBrief = (changeRequestId: string, findings: readonly MergedFinding[], unmet: readonly string[]) =>
514
1060
  [
@@ -528,7 +1074,7 @@ const fixBrief = (changeRequestId: string, findings: readonly MergedFinding[], u
528
1074
  */
529
1075
  export default defineLoop({
530
1076
  id: 'review',
531
- version: '3.10.0',
1077
+ version: '3.11.0',
532
1078
  title: 'Review',
533
1079
  input: Input,
534
1080
  output: Output,
@@ -571,24 +1117,24 @@ export default defineLoop({
571
1117
  const failing = [...new Set([...(input.failing ?? []), ...verified.failing])]
572
1118
  const notRun = [...new Set([...(input.notRun ?? []), ...verified.notRun])]
573
1119
 
1120
+ const earlier = earlierOf(input)
1121
+
574
1122
  const outputs = yield* Effect.forEach(
575
1123
  fixRound(input) ? ([scopeSeat] as const) : seatNames,
576
1124
  seat =>
577
1125
  agentWork(`review:${seat}`, {
578
1126
  agent: seat,
579
- prompt: promptFor(seat, target, input, failing, notRun),
1127
+ prompt: promptFor(seat, target, input, earlier, failing, notRun),
580
1128
  output: SeatOutput
581
1129
  }).pipe(Effect.map(output => [seat, output] as const)),
582
1130
  { concurrency: 'unbounded' }
583
1131
  )
584
1132
 
585
- const earlier = input.earlier ?? []
1133
+ const cases = casesOf(input)
586
1134
  const earlierById = new Map(earlier.map(finding => [finding.id, finding]))
587
1135
 
588
- const answered = followUpsOf(
589
- earlier,
590
- outputs.flatMap(([, output]) => output.followUps ?? [])
591
- )
1136
+ const answers = outputs.flatMap(([seat, output]) => (output.followUps ?? []).map(answer => ({ ...answer, seat })))
1137
+ const answered = followUpsOf(earlier, answers)
592
1138
 
593
1139
  const standing = new Set(answered.flatMap(entry => (entry.status === 'fixed' ? [] : [entry.id])))
594
1140
 
@@ -598,43 +1144,154 @@ export default defineLoop({
598
1144
 
599
1145
  const withdrawn = new Set(settled.withdrawn.map(entry => entry.finding.id))
600
1146
 
601
- const open = new Map([...earlierById].filter(([id]) => standing.has(id) && !withdrawn.has(id)))
1147
+ const open = new Map(
1148
+ [...earlierById].flatMap(([id, finding]) =>
1149
+ standing.has(id) && !withdrawn.has(id) ? [[id, currentOf(finding, answers)] as const] : []
1150
+ )
1151
+ )
1152
+
1153
+ const movedApart = new Map<string, OutOfScopeFinding>()
1154
+
1155
+ for (const [id, finding] of open) {
1156
+ const item = earlierCaseOf(finding, answers, cases)
1157
+
1158
+ if (item === undefined) continue
1159
+ open.delete(id)
1160
+
1161
+ for (const apart of keptApart(finding, item)) movedApart.set(id, apart)
1162
+ }
602
1163
 
603
1164
  const followUps = answered.filter(entry => !withdrawn.has(entry.id))
604
1165
 
605
1166
  const sinceApproval = input.approved !== undefined && input.files === undefined
606
1167
 
607
- /** A problem on an earlier finding's line is new when it is worse, or when that finding is fixed. */
608
- const isNew = (finding: SeatFinding) => {
1168
+ const groupOf = (finding: SeatFinding) => {
1169
+ const approved = sinceApproval && finding.approvedCode === true
1170
+
1171
+ if (caseOf(cases, finding) !== undefined)
1172
+ return finding.severity === 'blocker'
1173
+ ? ('fresh' as const)
1174
+ : approved
1175
+ ? ('approvedApart' as const)
1176
+ : ('outOfScope' as const)
1177
+
1178
+ return approved ? ('approvedCode' as const) : ('fresh' as const)
1179
+ }
1180
+
1181
+ const keepsSeverity = (finding: SeatFinding) => {
1182
+ const group = groupOf(finding)
1183
+
1184
+ return group === 'outOfScope' || group === 'approvedApart'
1185
+ }
1186
+
1187
+ const listedApart = [
1188
+ ...(input.outOfScopeFindings ?? []).filter(finding => cases.includes(finding.item)),
1189
+ ...movedApart.values()
1190
+ ]
1191
+
1192
+ const unfixedOn = (finding: SeatFinding) => {
609
1193
  const before = earlierById.get(idOf(finding))
610
1194
 
1195
+ return before !== undefined && (standing.has(before.id) || withdrawn.has(before.id)) ? before : undefined
1196
+ }
1197
+
1198
+ const saysAgain = (before: MergedFinding, finding: SeatFinding) =>
1199
+ [finding.detail, detailOf(finding.detail, finding.rule, finding.checked ?? [])].some(text =>
1200
+ problemsOf(before.detail).includes(text.trim())
1201
+ )
1202
+
1203
+ const isNew = (finding: SeatFinding) => {
1204
+ const before = unfixedOn(finding)
1205
+
1206
+ return (
1207
+ before === undefined ||
1208
+ movedApart.has(before.id) ||
1209
+ severityRank[finding.severity] < severityRank[before.severity] ||
1210
+ (finding.severity === 'blocker' &&
1211
+ (withdrawn.has(before.id) || caseOf(cases, finding) !== undefined) &&
1212
+ !saysAgain(before, finding))
1213
+ )
1214
+ }
1215
+
1216
+ // Nothing out of scope blocks, so only an unfixed finding's own words, said no worse, are left out.
1217
+ const isNewApart = (finding: SeatFinding) => {
1218
+ const before = unfixedOn(finding)
1219
+
611
1220
  return (
612
1221
  before === undefined ||
1222
+ movedApart.has(before.id) ||
613
1223
  severityRank[finding.severity] < severityRank[before.severity] ||
614
- (!standing.has(before.id) && !withdrawn.has(before.id))
1224
+ !saysAgain(before, finding)
615
1225
  )
616
1226
  }
617
1227
 
618
- const merged = (approvedCode: boolean) =>
1228
+ const seatFindings = (holds: (finding: SeatFinding) => boolean) =>
1229
+ Object.fromEntries(
1230
+ outputs.map(([seat, output]) => [
1231
+ seat,
1232
+ output.findings
1233
+ .map(finding => (fixRound(input) && !keepsSeverity(finding) ? outsideFixAsMinor(finding) : finding))
1234
+ .filter(holds)
1235
+ ])
1236
+ )
1237
+
1238
+ const takenIds = new Set(earlierById.keys())
1239
+
1240
+ const merged = (holds: (finding: SeatFinding) => boolean) =>
619
1241
  groupedByRule(
620
- Object.fromEntries(
621
- outputs.map(([seat, output]) => [
622
- seat,
623
- output.findings
624
- .map(finding => (fixRound(input) ? outsideFixAsMinor(finding) : finding))
625
- .filter(finding => isNew(finding) && (sinceApproval && finding.approvedCode === true) === approvedCode)
626
- ])
627
- )
1242
+ seatFindings(finding => isNew(finding) && holds(finding)),
1243
+ cases,
1244
+ takenIds
628
1245
  )
629
1246
 
630
- const fresh = merged(false).map(finding => {
1247
+ const ownFinding = (finding: MergedFinding) => {
1248
+ const id = ownId(finding.id, takenIds)
1249
+
1250
+ takenIds.add(id)
1251
+
1252
+ return { ...finding, id }
1253
+ }
1254
+
1255
+ // A different blocker, no worse, on an earlier finding's line is its own finding, which that one's fix or rebuttal does not settle.
1256
+ const fresh = merged(finding => groupOf(finding) === 'fresh').map(finding => {
631
1257
  const before = open.get(finding.id)
1258
+ const rebutted = earlierById.get(finding.id)
1259
+ const worse = (than: MergedFinding) => severityRank[finding.severity] < severityRank[than.severity]
1260
+
1261
+ if (before !== undefined) return worse(before) ? withEarlier(finding, before) : ownFinding(finding)
632
1262
 
633
- return before === undefined ? finding : withEarlier(finding, before)
1263
+ return rebutted !== undefined && withdrawn.has(rebutted.id) && !worse(rebutted) ? ownFinding(finding) : finding
634
1264
  })
635
1265
 
636
1266
  const freshIds = new Set(fresh.map(finding => finding.id))
637
- const approvedFindings = sinceApproval ? merged(true) : []
1267
+
1268
+ const apartOf = (group: 'outOfScope' | 'approvedApart') =>
1269
+ Object.entries(seatFindings(finding => groupOf(finding) === group && isNewApart(finding))).flatMap(
1270
+ ([seat, found]) =>
1271
+ found.flatMap(finding =>
1272
+ keptApart(
1273
+ {
1274
+ id: idOf(finding),
1275
+ severity: finding.severity,
1276
+ file: finding.file,
1277
+ line: finding.line,
1278
+ detail: detailOf(finding.detail, finding.rule, finding.checked ?? []),
1279
+ seats: [seat],
1280
+ problem: finding.detail
1281
+ },
1282
+ caseOf(cases, finding) ?? ''
1283
+ )
1284
+ )
1285
+ )
1286
+
1287
+ const approvedInScope = merged(finding => groupOf(finding) === 'approvedCode')
1288
+
1289
+ const approvedFindings: readonly ApprovedFinding[] = [
1290
+ ...approvedInScope,
1291
+ ...distinctApart(apartOf('approvedApart'), new Set(approvedInScope.map(finding => finding.id)))
1292
+ ]
1293
+
1294
+ const outOfScopeFindings = distinctApart([...listedApart, ...apartOf('outOfScope')])
638
1295
 
639
1296
  const findings = [...[...open.values()].filter(finding => !freshIds.has(finding.id)), ...fresh]
640
1297
 
@@ -645,7 +1302,10 @@ export default defineLoop({
645
1302
 
646
1303
  const blockers = findings.filter(isBlocking)
647
1304
  const judged = outputs.find(([seat]) => seat === scopeSeat)?.[1].scope
648
- const scope = wholeChange(input) ? carriedScope(judged, fixRound(input) ? input.scope : undefined) : undefined
1305
+
1306
+ const scope = wholeChange(input)
1307
+ ? withUnjudged(carriedScope(judged, earlierScope(input), cases, criteriaOf(input)), requiredCriteriaOf(input))
1308
+ : undefined
649
1309
 
650
1310
  // A seat's own summary is kept only when nothing blocks, so it cannot contradict the verdict.
651
1311
  const summary =
@@ -660,16 +1320,33 @@ export default defineLoop({
660
1320
  : findings.length === 0
661
1321
  ? sinceApproval
662
1322
  ? `No findings in what changed since ${input.approved}: nothing stands in the way of merging.`
663
- : 'No findings: nothing stands in the way of merging.'
1323
+ : outOfScopeFindings.length > 0
1324
+ ? 'No findings in scope: nothing stands in the way of merging.'
1325
+ : 'No findings: nothing stands in the way of merging.'
664
1326
  : ['Can merge: nothing blocks it.', ...outputs.map(([, output]) => output.summary)].join(' ')
665
1327
 
666
- const text = reviewText(summary, findings, followUps, approvedFindings, notRun, scope?.reported ?? [])
1328
+ const shownOutOfScope = outOfScopeFindings.map(finding => ({
1329
+ ...finding,
1330
+ detail: inCase(finding.detail, finding.item)
1331
+ }))
1332
+
1333
+ const text = reviewText(summary, findings, followUps, approvedFindings, shownOutOfScope, notRun, scope)
1334
+
1335
+ const apart = {
1336
+ ...(approvedFindings.length === 0 ? undefined : { approvedFindings }),
1337
+ ...(outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings })
1338
+ }
667
1339
 
668
1340
  const stored = yield* artifact('findings', {
669
1341
  kind: 'review-findings',
670
1342
  title: 'Review findings',
671
1343
  text,
672
- data: { findings, followUps, ...(approvedFindings.length === 0 ? undefined : { approvedFindings }) }
1344
+ data: {
1345
+ findings,
1346
+ followUps,
1347
+ ...apart,
1348
+ ...(scope === undefined ? undefined : { scope: { outOfScope: scope.outOfScope ?? [] } })
1349
+ }
673
1350
  })
674
1351
 
675
1352
  const reviewed = {
@@ -679,7 +1356,7 @@ export default defineLoop({
679
1356
  verdicts,
680
1357
  blocking: findings.some(isBlocking),
681
1358
  artifactId: stored.artifactId,
682
- ...(approvedFindings.length === 0 ? undefined : { approvedFindings }),
1359
+ ...apart,
683
1360
  ...(scope === undefined ? undefined : { scope }),
684
1361
  ...(failing.length === 0 ? undefined : { failing }),
685
1362
  ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo })
@@ -749,6 +1426,7 @@ export default defineLoop({
749
1426
  maxRounds: 2,
750
1427
  reviewed: range.head,
751
1428
  ...(findings.length === 0 ? undefined : { earlier: findings }),
1429
+ ...(outOfScopeFindings.length === 0 ? undefined : { outOfScopeFindings }),
752
1430
  ...(scope === undefined ? undefined : { scope }),
753
1431
  ...ownDeliveryTarget(input)
754
1432
  })