opencode-azure-devops-pr-review 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,22 @@
1
1
  /**
2
- * Review orchestration: runtime-owned snapshot, sharded initial reviews,
3
- * sharded verification, a duplicate check for files whose findings different
4
- * verifiers confirmed, and a deterministic final version recheck. A quick
5
- * review has one reviewer per shard and no verification: the runtime checks
6
- * only the form and source of its findings, never whether they are right.
2
+ * Review orchestration: a runtime-owned snapshot, sharded reviewer passes, the
3
+ * runtime's own checks of each finding's form and source, a duplicate check of
4
+ * what different sessions reported in one file, a severity rating and a
5
+ * deterministic final version recheck. Every mode runs this pipeline with its
6
+ * own list of models: pass i of every shard runs with entry i. No stage
7
+ * verifies a finding: the runtime never judges whether a defect is real.
7
8
  */
8
- import { ROLES, initialRoles, roleFor, stageModel } from './config.mjs';
9
+ import { ROLES, reviewerRoles, roleFor, stageModel, raterState } from './config.mjs';
9
10
  import { searchLimitation } from './attribution.mjs';
10
- import { breakMergeCycles, settleMergeTargets, evaluateInitial, evaluateFinal, evaluateDuplicates, evaluateRatings, initialRepairPrompt, finalRepairPrompt, duplicateRepairPrompt, ratingRepairPrompt, quickRepairPrompt, quickFollowUpPrompt, syntaxProblem, locationPath, FINDING_FIELDS } from './output.mjs';
11
+ import { evaluateInitial, evaluateDuplicates, evaluateRatings, duplicateRepairPrompt, ratingRepairPrompt, reviewRepairPrompt, reviewFollowUpPrompt, syntaxProblem, locationPath, FINDING_FIELDS } from './output.mjs';
11
12
 
12
13
  export { locationPath };
13
- const ID_SPAN = 1000;
14
14
  const text = value => typeof value === 'string' && value.trim().length > 0;
15
- const shardLabel = task => task.count > 1 || task.part ? `shard ${task.index + 1}/${task.count}${task.part ?? ''}` : '';
15
+ /** How a reviewer session is named in notices, titles and receipts: its pass (when a mode has several) and its shard. */
16
+ const sessionLabel = task => [task.passes > 1 ? `pass ${task.pass + 1}/${task.passes}` : '',
17
+ task.count > 1 || task.part ? `shard ${task.index + 1}/${task.count}${task.part ?? ''}` : ''].filter(Boolean).join(' ');
18
+ /** The reviewer session a finding comes from, as the record names it: its shard and, with several passes, its pass. */
19
+ const sessionOf = task => `${task.index + 1}/${task.count}${task.part ?? ''}${task.passes > 1 ? ` pass ${task.pass + 1}` : ''}`;
16
20
 
17
21
  /** Sorted paths keep a directory's files in the same shard. */
18
22
  export function shardFiles(files, size) {
@@ -23,52 +27,6 @@ export function shardFiles(files, size) {
23
27
  return shards;
24
28
  }
25
29
 
26
- /**
27
- * Group findings for verification by file so related claims share a session:
28
- * shards end only between files. One file's findings are split only when that
29
- * file alone has more findings than a shard holds.
30
- */
31
- export function shardFindings(findings, size) {
32
- if (!findings.length) return [[]];
33
- const sorted = [...findings].sort((a, b) => locationPath(a.location).localeCompare(locationPath(b.location)) || a.id.localeCompare(b.id, undefined, { numeric: true }));
34
- const files = [];
35
- for (const finding of sorted) {
36
- const path = locationPath(finding.location);
37
- if (files.at(-1)?.path === path) files.at(-1).findings.push(finding);
38
- else files.push({ path, findings: [finding] });
39
- }
40
- const shards = [];
41
- let current = [];
42
- for (const { findings: group } of files) {
43
- if (current.length && current.length + group.length > size) { shards.push(current); current = []; }
44
- if (group.length > size) {
45
- for (let index = 0; index < group.length; index += size) shards.push(group.slice(index, index + size));
46
- continue;
47
- }
48
- current.push(...group);
49
- }
50
- if (current.length) shards.push(current);
51
- return shards;
52
- }
53
-
54
- /**
55
- * Confirmed claims that ended in one file although different verification
56
- * shards decided them: a verifier moved a finding into another shard's file, or
57
- * a file had more findings than one shard holds. Only these files lost the
58
- * "one verifier per file" guarantee, so only they get a duplicate check.
59
- * @param {{id: string, shard: object, finding: object}[]} claims
60
- */
61
- export function sameFileGroups(claims) {
62
- const byFile = new Map();
63
- for (const claim of claims) {
64
- const path = locationPath(claim.finding.location);
65
- if (!path) continue;
66
- if (!byFile.has(path)) byFile.set(path, []);
67
- byFile.get(path).push(claim);
68
- }
69
- return [...byFile].filter(([, items]) => new Set(items.map(item => item.shard)).size > 1).map(([path, items]) => ({ path, items }));
70
- }
71
-
72
30
  /** Run tasks with bounded parallelism; results keep the task order. */
73
31
  export async function runPool(tasks, limit, worker) {
74
32
  const results = new Array(tasks.length);
@@ -90,18 +48,6 @@ export async function snapshotForModel(snapshot, store) {
90
48
  commits: await store.pack(commits ?? [], 8000) };
91
49
  }
92
50
 
93
- /** Make finding IDs unique across shards; keep the model's ID when it is free. */
94
- function uniqueIds(findings, prefix, used, valid = () => true) {
95
- let next = 1;
96
- for (const finding of findings) {
97
- if (valid(finding.id) && !used.has(finding.id)) { used.add(finding.id); continue; }
98
- while (used.has(`${prefix}-${next}`)) next++;
99
- finding.shardId = finding.id;
100
- finding.id = `${prefix}-${next}`;
101
- used.add(finding.id);
102
- }
103
- }
104
-
105
51
  /** The PR snapshot every review starts from, with its warnings. */
106
52
  async function prepareSnapshot(ctx, run, request) {
107
53
  const { azure, progress } = ctx;
@@ -118,35 +64,36 @@ async function prepareSnapshot(ctx, run, request) {
118
64
  }
119
65
 
120
66
  /**
121
- * One initial session per task; a task that fills its model context is split
122
- * in half and both halves run (`counter.next` hands out their ID ranges).
123
- * `handlerFor(task, prefix)` returns the stage handler that accepts answers.
67
+ * One reviewer session per task (a pass of a shard); a task that fills its
68
+ * model context is split in half and both halves run, as parts of the same
69
+ * pass. `handlerFor(task)` returns the stage handler that accepts answers.
70
+ * Findings are numbered by each answer on its own (F-1, F-2, …): the runtime
71
+ * gives the review's IDs once every pass has answered.
124
72
  */
125
- function initialRunner(ctx, run, request, { snapshot, modelSnapshot, counter, handlerFor }) {
73
+ function reviewRunner(ctx, run, request, { snapshot, modelSnapshot, handlerFor }) {
126
74
  const { runStage, progress, settings } = ctx;
127
75
  const changes = new Map(snapshot.changes.map(change => [change.path, change]));
128
- async function initialTask(task) {
129
- const prefix = ROLES[task.role].prefix;
76
+ async function reviewTask(task) {
130
77
  const payload = {
131
78
  prUrl: request.prUrl, userContext: request.userContext, outputLanguage: settings.outputLanguage, snapshot: modelSnapshot,
132
79
  assignment: { shard: `${task.index + 1}/${task.count}${task.part ?? ''}`, files: task.files, changes: task.files.map(path => changes.get(path)).filter(Boolean),
133
- firstFindingId: `${prefix}-${task.idBase + 1}`, discoverFiles: !snapshot.filesComplete },
80
+ firstFindingId: `${LOCAL_PREFIX}-${task.base ?? 1}`, discoverFiles: !snapshot.filesComplete },
134
81
  };
135
82
  try {
136
- const result = await runStage(run, task.role, payload, handlerFor(task, prefix), { label: shardLabel(task) });
83
+ const result = await runStage(run, task.role, payload, handlerFor(task), { label: sessionLabel(task) });
137
84
  return [{ task, result }];
138
85
  } catch (error) {
139
86
  if (!run.active) throw error;
140
87
  if (error?.failureClass === 'overflow' && task.files.length > 1) {
141
88
  const middle = Math.ceil(task.files.length / 2);
142
- progress(run, `${task.role} reached its context limit on ${task.files.length} files; splitting the shard in two.`);
143
- const halves = [task.files.slice(0, middle), task.files.slice(middle)].map((files, half) => ({ ...task, files, idBase: (counter.next += ID_SPAN), part: `${task.part ?? ''}${half ? 'b' : 'a'}` }));
144
- return [...await initialTask(halves[0]), ...await initialTask(halves[1])];
89
+ progress(run, `${ROLES[task.role].label}${sessionLabel(task) ? ` ${sessionLabel(task)}` : ''} reached its context limit on ${task.files.length} files; splitting the shard in two.`);
90
+ const halves = [task.files.slice(0, middle), task.files.slice(middle)].map((files, half) => ({ ...task, files, part: `${task.part ?? ''}${half ? 'b' : 'a'}` }));
91
+ return [...await reviewTask(halves[0]), ...await reviewTask(halves[1])];
145
92
  }
146
93
  return [{ task, error }];
147
94
  }
148
95
  }
149
- return initialTask;
96
+ return reviewTask;
150
97
  }
151
98
 
152
99
  /** Deterministic final version recheck. Only a changed source commit is stale. */
@@ -167,279 +114,20 @@ async function finalRecheck(ctx, run, snapshot, warnings) {
167
114
  return { freshness, stale };
168
115
  }
169
116
 
170
- /** Findings one severity-rating session receives. */
171
- const RATING_BATCH = 25;
172
- const RATING_DESCRIPTION_CHARACTERS = 4000;
173
-
174
- /**
175
- * Severity rating, only where models.<mode>.rater names a model; without one
176
- * the verifier's severity is final. After verification and merging, a session
177
- * without tools rates the surviving findings from their text alone, without
178
- * the level the verifier gave them. It is meant for a model stronger than the
179
- * reviewers': measured runs showed a gain there and none when a model rated
180
- * its own review. A finding the rating does not cover, and every finding of a
181
- * failed batch, keeps the verifier's severity. Returns the number of sessions.
182
- */
183
- async function rateSeverities(ctx, run, { snapshot, dispositions, newFindings, warnings }) {
184
- const { runStage, progress, settings } = ctx;
185
- const rater = roleFor(run.profile, 'rating');
186
- if (!stageModel(settings, rater)) return 0;
187
- const rated = [
188
- ...dispositions.filter(d => d.status === 'CONFIRMED' && d.verifiedFinding).map(d => ({ id: d.id, get: () => d.verifiedFinding, set: value => { d.verifiedFinding = value; } })),
189
- ...newFindings.map((finding, index) => ({ id: finding.id, get: () => newFindings[index], set: value => { newFindings[index] = value; } })),
190
- ];
191
- if (!rated.length) return 0;
192
- const batches = [];
193
- for (let at = 0; at < rated.length; at += RATING_BATCH) batches.push(rated.slice(at, at + RATING_BATCH));
194
- progress(run, `Severity rating: ${rated.length} finding(s) in ${batches.length} session(s).`);
195
- const description = text(snapshot.description) ? snapshot.description : '';
196
- const change = { title: snapshot.title ?? '', description: description.length > RATING_DESCRIPTION_CHARACTERS
197
- ? `${description.slice(0, RATING_DESCRIPTION_CHARACTERS)} […]` : description };
198
- const outcomes = await runPool(batches.map((items, index) => ({ items, index, count: batches.length })), settings.workflow.parallelSessions, async task => {
199
- const ids = task.items.map(item => item.id);
200
- const payload = {
201
- outputLanguage: settings.outputLanguage, change,
202
- assignment: { kind: 'rating', findingIds: ids,
203
- findings: task.items.map(item => { const { severity: _verified, ...finding } = item.get(); return { ...finding, id: item.id }; }) },
204
- };
205
- try {
206
- const result = await runStage(run, rater, payload, {
207
- evaluate(answer) {
208
- const { result, issues } = evaluateRatings(answer, { ids });
209
- return { result, issues, repairPrompt: issues.length ? ratingRepairPrompt(issues, { parseOnly: !result.structured && syntaxProblem(issues) }) : undefined };
210
- },
211
- }, { label: task.count > 1 ? `${task.index + 1}/${task.count}` : '' });
212
- return { ...task, result };
213
- } catch (error) {
214
- if (!run.active) throw error;
215
- return { ...task, error };
216
- }
217
- });
218
- if (!run.active) throw new Error(run.reason || 'Review stopped.');
219
- for (const { items, result, error } of outcomes) {
220
- if (!result) {
221
- warnings.push(`The severity rating failed (${error?.message ?? 'unknown error'}); its ${items.length} finding(s) keep the verifier's severity.`);
222
- continue;
223
- }
224
- const byId = new Map(result.ratings.map(row => [row.id, row]));
225
- for (const item of items) {
226
- const row = byId.get(item.id);
227
- if (row) item.set({ ...item.get(), severity: row.severity });
228
- }
229
- warnings.push(...result.warnings.map(message => `Severity rating: ${message}`));
230
- }
231
- return batches.length;
232
- }
233
-
234
- /**
235
- * @param {object} ctx { azure, runStage, progress, settings, dataFor }
236
- * @param {object} run
237
- * @param {object} request parsed /pr-review arguments
238
- */
239
- export async function runReview(ctx, run, request) {
240
- if (run.profile === 'quick') return runQuickReview(ctx, run, request);
241
- const { runStage, progress, settings } = ctx;
242
- const { store, snapshot, warnings, modelSnapshot } = await prepareSnapshot(ctx, run, request);
243
- const shards = shardFiles(snapshot.files, settings.workflow.shardFiles);
244
- const roles = initialRoles(run.profile);
245
- const counter = { next: shards.length * ID_SPAN };
246
- const tasks = roles.flatMap(role => shards.map((files, index) => ({ role, files, index, count: shards.length, idBase: index * ID_SPAN })));
247
- progress(run, `Initial review: ${tasks.length} session(s) for ${roles.length} roles and ${shards.length} shard(s).`);
248
- const initialTask = initialRunner(ctx, run, request, { snapshot, modelSnapshot, counter, handlerFor: (task, prefix) => ({
249
- evaluate(answer) {
250
- const { result, issues } = evaluateInitial(answer, { prefix, assigned: task.files, inventory: snapshot.files, filesComplete: snapshot.filesComplete });
251
- return { result, issues, repairPrompt: issues.length ? initialRepairPrompt(issues, { parseOnly: !result.structured && syntaxProblem(issues) }) : undefined };
252
- },
253
- }) });
254
-
255
- const outcomes = (await runPool(tasks, settings.workflow.parallelSessions, initialTask)).flat();
256
- if (!run.active) throw new Error(run.reason || 'Review stopped.');
257
- const succeeded = outcomes.filter(outcome => outcome.result);
258
- if (!succeeded.length) throw new Error(`Every initial review session failed: ${[...new Set(outcomes.map(outcome => outcome.error?.message).filter(Boolean))].slice(0, 3).join(' | ')}`);
259
-
260
- // Merge initial work per role.
261
- const findings = [], initialReports = [], coverage = {}, discovered = new Set();
262
- for (const role of roles) {
263
- const prefix = ROLES[role].prefix, used = new Set();
264
- const roleOutcomes = outcomes.filter(outcome => outcome.task.role === role);
265
- coverage[role] = { assigned: 0, covered: 0, failedFiles: [], gaps: [] };
266
- for (const { task, result, error } of roleOutcomes) {
267
- coverage[role].assigned += task.files.length;
268
- if (!result) {
269
- coverage[role].failedFiles.push(...task.files);
270
- warnings.push(`${role} shard ${task.index + 1}/${task.count}${task.part ?? ''} failed (${error?.message ?? 'unknown error'}); its ${task.files.length || 'unknown'} file(s) lack this role's review.`);
271
- continue;
272
- }
273
- uniqueIds(result.findings, prefix, used);
274
- for (const finding of result.findings) findings.push({ ...finding, origin: role });
275
- coverage[role].covered += result.coverage.files.filter(path => task.files.includes(path)).length;
276
- coverage[role].gaps.push(...result.coverage.gaps);
277
- for (const path of result.additionalFiles) discovered.add(path);
278
- initialReports.push({ role, shard: `${task.index + 1}/${task.count}${task.part ?? ''}`, files: task.files.length, status: result.status,
279
- structured: result.structured, report: result.report, gaps: result.coverage.gaps, warnings: result.warnings });
280
- }
281
- }
282
- if (discovered.size) warnings.push(`Reviewers reported ${discovered.size} changed path(s) missing from Azure's list: ${[...discovered].slice(0, 20).join(', ')}${discovered.size > 20 ? ', ...' : ''}`);
283
- progress(run, `Initial review finished: ${findings.length} candidate finding(s). Verifying.`);
284
-
285
- // Verification, sharded by finding. Without candidates one verifier still
286
- // runs: it checks the initial reports and writes the checks and limitations.
287
- const verifier = roleFor(run.profile, 'verifier');
288
- const groups = shardFindings(findings, settings.workflow.shardFindings);
289
- const allIds = findings.map(finding => finding.id);
290
- const packedReports = await store.pack(initialReports);
291
- let nextNewBase = groups.length * ID_SPAN;
292
- // Like initial shards, a verifier assignment that overflows the context is
293
- // split (between files where possible) and only an indivisible one fails.
294
- // Candidates go to the verifier without the reviewer's severity, so it sets
295
- // the level from what it verified instead of keeping a label.
296
- async function verifyTask(task) {
297
- const payload = {
298
- prUrl: request.prUrl, userContext: request.userContext, outputLanguage: settings.outputLanguage, snapshot: modelSnapshot,
299
- assignment: { shard: `${task.index + 1}/${task.count}${task.part ?? ''}`, findingIds: task.assigned.map(f => f.id), findings: task.assigned.map(({ severity: _claimed, ...candidate }) => candidate),
300
- allFindingIds: await store.pack(allIds, 4000), firstNewFindingId: `V-${task.idBase + 1}` },
301
- initialReports: packedReports, discoveredFiles: [...discovered],
302
- };
303
- try {
304
- const result = await runStage(run, verifier, payload, {
305
- evaluate(answer, previous) {
306
- const { result, issues, repairIds } = evaluateFinal(answer, { originals: task.assigned, allIds, previous, supplement: Boolean(previous?.structured) });
307
- if (!issues.length) return { result, issues };
308
- return { result, issues, repairPrompt: finalRepairPrompt(issues, repairIds, { parseOnly: !result.structured && syntaxProblem(issues), full: !result.structured, includeNewFindings: issues.some(issue => issue.startsWith('newFindings')) }) };
309
- },
310
- }, { label: task.count > 1 || task.part ? `shard ${task.index + 1}/${task.count}${task.part ?? ''}` : '' });
311
- return [{ task, result }];
312
- } catch (error) {
313
- if (!run.active) throw error;
314
- if (error?.failureClass === 'overflow' && task.assigned.length > 1) {
315
- progress(run, `The verifier reached its context limit on ${task.assigned.length} findings; splitting the shard.`);
316
- const parts = shardFindings(task.assigned, Math.ceil(task.assigned.length / 2));
317
- const smaller = parts.map((assigned, index) => ({ ...task, assigned, idBase: (nextNewBase += ID_SPAN), part: `${task.part ?? ''}${String.fromCharCode(97 + index)}` }));
318
- const outcomes = [];
319
- for (const part of smaller) outcomes.push(...await verifyTask(part));
320
- return outcomes;
321
- }
322
- return [{ task, error }];
323
- }
324
- }
325
- const verifications = (await runPool(groups.map((assigned, index) => ({ assigned, index, count: groups.length, idBase: index * ID_SPAN })),
326
- settings.workflow.parallelSessions, verifyTask)).flat();
327
- if (!run.active) throw new Error(run.reason || 'Review stopped.');
328
-
329
- const dispositions = [], newFindings = [], reports = [], usedNew = new Set(allIds), decidedIn = new Map();
330
- let verified = 0;
331
- for (const { task, result, error } of verifications) {
332
- const label = task.count > 1 || task.part ? `Verification shard ${task.index + 1}/${task.count}${task.part ?? ''}` : '';
333
- if (!result) {
334
- warnings.push(`${label || 'Verification'} failed (${error?.message ?? 'unknown error'}); its findings are UNREVIEWED.`);
335
- for (const finding of task.assigned) dispositions.push({ id: finding.id, status: 'UNREVIEWED', reason: 'The verification session failed; this finding is not confirmed.' });
336
- continue;
337
- }
338
- if (result.structured) verified++;
339
- dispositions.push(...result.dispositions);
340
- // New findings need IDs unique across the review: never a missing ID or one of an original finding.
341
- uniqueIds(result.newFindings, 'V', usedNew, id => typeof id === 'string' && /^V-\d+$/.test(id));
342
- for (const decided of [...result.dispositions, ...result.newFindings]) decidedIn.set(decided.id, task);
343
- newFindings.push(...result.newFindings);
344
- for (const row of result.incompleteNewFindings ?? []) reports.push(`Incomplete new finding (not eligible for comments): ${row.summary || row.id || 'unnamed'}`);
345
- if (text(result.report)) reports.push(label ? `### ${label}\n\n${result.report}` : result.report);
346
- if (result.modelStatus === 'INCOMPLETE') warnings.push(`${label || 'The verifier'} reported unfinished checks; see its report.`);
347
- warnings.push(...result.warnings.map(message => label ? `${label}: ${message}` : message));
348
- }
349
-
350
- // Same-file duplicate check. Shards keep a file's findings together, but a
351
- // moved finding or a split crowded file can bring findings that different
352
- // verifiers confirmed into one file; a model compares only those, and a
353
- // failed check keeps every finding.
354
- const claims = [
355
- ...dispositions.filter(d => d.status === 'CONFIRMED' && d.verifiedFinding).map(d => ({ id: d.id, shard: decidedIn.get(d.id), finding: d.verifiedFinding, reason: d.reason })),
356
- ...newFindings.map(finding => ({ id: finding.id, shard: decidedIn.get(finding.id), finding })),
357
- ];
358
- const sameFile = sameFileGroups(claims);
359
- if (sameFile.length) {
360
- progress(run, `Duplicate check: ${sameFile.length} file(s) hold findings that different verification shards confirmed.`);
361
- const checker = roleFor(run.profile, 'dedupe');
362
- const checks = await runPool(sameFile.map((group, index) => ({ group, index, count: sameFile.length })), settings.workflow.parallelSessions, async task => {
363
- const ids = task.group.items.map(item => item.id);
364
- const findings = task.group.items.map(({ id, shard, finding, reason }) => ({ ...finding, id,
365
- verificationShard: `${shard.index + 1}/${shard.count}`, ...(text(reason) ? { verifierReason: reason } : {}) }));
366
- const payload = {
367
- prUrl: request.prUrl, userContext: request.userContext, outputLanguage: settings.outputLanguage, snapshot: modelSnapshot,
368
- assignment: { kind: 'duplicates', file: task.group.path, findingIds: ids, findings: await store.pack(findings, 40000) },
369
- };
370
- try {
371
- const result = await runStage(run, checker, payload, {
372
- evaluate(answer) {
373
- const { result, issues } = evaluateDuplicates(answer, { ids });
374
- return { result, issues, repairPrompt: issues.length ? duplicateRepairPrompt(issues, { parseOnly: !result.structured && syntaxProblem(issues) }) : undefined };
375
- },
376
- }, { label: task.count > 1 ? `${task.index + 1}/${task.count}` : '' });
377
- return { ...task, result };
378
- } catch (error) {
379
- if (!run.active) throw error;
380
- return { ...task, error };
381
- }
382
- });
383
- if (!run.active) throw new Error(run.reason || 'Review stopped.');
384
- for (const { group, result, error } of checks) {
385
- if (!result) {
386
- warnings.push(`The duplicate check of ${group.path} failed (${error?.message ?? 'unknown error'}); its ${group.items.length} findings stay confirmed and may include duplicates.`);
387
- continue;
388
- }
389
- for (const merge of result.merges) {
390
- const reason = `${merge.reason} [Runtime: merged by the same-file duplicate check after verification had confirmed it.]`;
391
- const entry = dispositions.find(d => d.id === merge.id && d.status === 'CONFIRMED');
392
- if (entry) Object.assign(entry, { status: 'MERGED', mergedInto: merge.mergedInto, reason });
393
- else {
394
- const index = newFindings.findIndex(finding => finding.id === merge.id);
395
- if (index >= 0) dispositions.push({ id: merge.id, status: 'MERGED', mergedInto: merge.mergedInto, reason, verifiedFinding: newFindings.splice(index, 1)[0] });
396
- }
397
- }
398
- if (text(result.report)) reports.push(`### Duplicate check: ${group.path}\n\n${result.report}`);
399
- warnings.push(...result.warnings.map(message => `Duplicate check of ${group.path}: ${message}`));
400
- }
401
- }
402
-
403
- // A merge may name a finding another shard decided; a cycle across shards
404
- // would otherwise hide every finding in it without a warning.
405
- const cyclic = breakMergeCycles(dispositions);
406
- if (cyclic.length) warnings.push(`Merges across verification shards formed a cycle; ${cyclic.join(', ')} ${cyclic.length === 1 ? 'is' : 'are'} shown as UNREVIEWED.`);
407
- // A verifier may merge into a finding that another shard rejected or left
408
- // undecided; only the combined decisions can tell, and such a merged finding
409
- // must not vanish behind the rejection. Surviving verifier-added findings are
410
- // confirmed targets (the duplicate check may merge into them).
411
- const dangling = settleMergeTargets(dispositions, { unknownIsDangling: true, confirmedIds: new Set(newFindings.map(finding => finding.id)) });
412
- if (dangling.length) warnings.push(`Merged into findings that were not confirmed and shown as UNREVIEWED: ${dangling.map(row => `${row.id} → ${row.target} (${row.status})`).join(', ')}.`);
413
-
414
- const ratings = await rateSeverities(ctx, run, { snapshot, dispositions, newFindings, warnings });
415
-
416
- const search = searchLimitation(run, settings);
417
- if (search) warnings.push(search);
418
- const { freshness, stale } = await finalRecheck(ctx, run, snapshot, warnings);
419
- const status = stale ? 'STALE' : verified ? 'COMPLETE' : 'PARTIAL';
420
- return {
421
- status, snapshot, freshness, dispositions, newFindings, findings,
422
- report: reports.join('\n\n'),
423
- reviewWarnings: [...new Set(warnings)],
424
- coverage, discoveredFiles: [...discovered], initialReports,
425
- initialObservations: status === 'COMPLETE' ? [] : findings,
426
- unstructuredInitials: status === 'COMPLETE' ? [] : initialReports.filter(item => !item.structured).map(item => item.report),
427
- shards: { initial: shards.length, verification: groups.length, duplicateChecks: sameFile.length, ratings },
428
- };
429
- }
430
-
431
- // ------------------------------------------------------------------ quick review
117
+ // ------------------------------------------------------------------ findings and their checks
432
118
 
433
- const QUICK_LOCATION = /^(?:(head|base):)?(\/[^:\n]+?)(?::(\d+)(?:-(\d+))?)?\s*$/;
119
+ // The prefix of finding IDs: an answer numbers its own findings F-1, F-2, …, and the review's IDs use it too.
120
+ const LOCAL_PREFIX = 'F';
121
+ const LOCATION = /^(?:(head|base):)?(\/[^:\n]+?)(?::(\d+)(?:-(\d+))?)?\s*$/;
434
122
  const lineCount = source => {
435
123
  const lines = source.replace(/\r\n/g, '\n').split('\n');
436
124
  if (lines.at(-1) === '') lines.pop();
437
125
  return lines.length;
438
126
  };
439
- export const QUICK_REPORTED_REASON = 'Reported by the quick reviewer; it passed the runtime\'s format and source checks and was not independently verified.';
127
+ export const REPORTED_REASON = 'Reported by its reviewer, which checked it against the source it read; it passed the runtime\'s format and source checks. No separate verification ran.';
440
128
 
441
129
  /**
442
- * Check a quick finding's location against the reviewed commits: the file
130
+ * Check a finding's location against the reviewed commits: the file
443
131
  * exists at that version, the lines are in range and this session's own tools
444
132
  * showed that file's content. Only form and source are checked, never whether
445
133
  * the defect is real. `repairable` problems go back to the reviewer; `inline`
@@ -447,8 +135,8 @@ export const QUICK_REPORTED_REASON = 'Reported by the quick reviewer; it passed
447
135
  * @param {object} finding
448
136
  * @param {{snapshot: object, azure: object, run: object, reads?: Set<string>}} context
449
137
  */
450
- export async function checkQuickLocation(finding, { snapshot, azure, run, reads }) {
451
- const match = QUICK_LOCATION.exec(String(finding.location ?? '').trim());
138
+ export async function checkLocation(finding, { snapshot, azure, run, reads }) {
139
+ const match = LOCATION.exec(String(finding.location ?? '').trim());
452
140
  if (!match) return { problem: `location ${JSON.stringify(finding.location ?? '')} must be head:/path:line or head:/path:start-end (base: only for content that exists only in BASE).`, repairable: true };
453
141
  const side = match[1] ?? 'head', path = match[2], start = match[3] ? Number(match[3]) : null, end = match[4] ? Number(match[4]) : start;
454
142
  const version = side === 'base' ? snapshot.base : snapshot.head, label = side.toUpperCase();
@@ -477,17 +165,13 @@ export async function checkQuickLocation(finding, { snapshot, azure, run, reads
477
165
  return { ok: true, inline: side === 'head' && Boolean(change) && !change.changeType?.includes('delete') };
478
166
  }
479
167
 
168
+
480
169
  /**
481
- * Accept one quick-review answer: the initial-review contract with a required
482
- * location, plus the runtime's location and source checks. Field and location
483
- * problems get correction turns; what is still wrong afterwards is NEEDS_INFO.
484
- */
485
- /**
486
- * A parsed quick answer is usable only with a findings array and at least one
487
- * reviewed file or accepted finding. Uses the answer's own IDs (before they are
488
- * made unique), which key `invalid` and `checks`.
170
+ * A parsed reviewer answer is usable only with a findings array and at least
171
+ * one reviewed file or accepted finding. Uses the answer's own IDs, which key
172
+ * `invalid` and `checks`.
489
173
  */
490
- export function quickUsable(result, files) {
174
+ export function usableAnswer(result, files) {
491
175
  if (!result?.structured || result.envelope?.findings !== true) return false;
492
176
  const reviewed = result.envelope?.coverage ? result.coverage.files.filter(path => files.includes(path)) : [];
493
177
  const accepted = result.findings.filter(finding => !result.invalid?.[finding.id]?.length && result.checks?.[finding.id]?.ok).length;
@@ -495,119 +179,440 @@ export function quickUsable(result, files) {
495
179
  }
496
180
 
497
181
  /**
498
- * `usable` follows quickUsable. A usable PARTIAL answer with nothing to repair
182
+ * Accept one reviewer answer: the review contract with a required location,
183
+ * plus the runtime's location and source checks. Field and location problems
184
+ * get correction turns; what is still wrong afterwards is NEEDS_INFO.
185
+ * `usable` follows usableAnswer. A usable PARTIAL answer with nothing to repair
499
186
  * that names unfinished work (gaps or assigned files not reviewed) also gets a
500
187
  * `followUp`: the runtime may ask the same session once to continue.
501
188
  */
502
- export async function evaluateQuick(answer, { task, snapshot, azure, run, reads }) {
503
- const { result, issues } = evaluateInitial(answer, { prefix: 'Q', assigned: task.files, inventory: snapshot.files, filesComplete: snapshot.filesComplete, requireLocation: true });
189
+ export async function evaluateReview(answer, { task, snapshot, azure, run, reads }) {
190
+ const { result, issues } = evaluateInitial(answer, { prefix: LOCAL_PREFIX, assigned: task.files, inventory: snapshot.files, filesComplete: snapshot.filesComplete });
504
191
  // A plain object, so the stage record shows each finding's check.
505
192
  const checks = {};
506
193
  for (const finding of result.findings) {
507
- if (!Object.hasOwn(result.invalid, finding.id)) checks[finding.id] = await checkQuickLocation(finding, { snapshot, azure, run, reads });
194
+ if (!Object.hasOwn(result.invalid, finding.id)) checks[finding.id] = await checkLocation(finding, { snapshot, azure, run, reads });
508
195
  }
509
196
  const all = [...issues, ...Object.entries(checks).filter(([, check]) => check.repairable).map(([id, check]) => `${id}: ${check.problem}`)];
510
197
  const checked = { ...result, checks };
511
- const usable = quickUsable(checked, task.files);
198
+ const usable = usableAnswer(checked, task.files);
512
199
  const uncovered = task.files.filter(path => !result.coverage.files.includes(path));
513
200
  const unfinished = result.status === 'PARTIAL' && (result.coverage.gaps.length > 0 || uncovered.length > 0);
514
201
  return { result: checked, issues: all, usable,
515
- repairPrompt: all.length ? quickRepairPrompt(all, { parseOnly: !result.structured && syntaxProblem(all) }) : undefined,
516
- ...(usable && !all.length && unfinished ? { followUp: { prompt: quickFollowUpPrompt({ gaps: result.coverage.gaps, uncovered }), gaps: result.coverage.gaps, uncovered } } : {}) };
202
+ repairPrompt: all.length ? reviewRepairPrompt(all, { parseOnly: !result.structured && syntaxProblem(all) }) : undefined,
203
+ ...(usable && !all.length && unfinished ? { followUp: { prompt: reviewFollowUpPrompt({ gaps: result.coverage.gaps, uncovered }), gaps: result.coverage.gaps, uncovered } } : {}) };
517
204
  }
518
205
 
519
- const findingKey = finding => JSON.stringify(FINDING_FIELDS.filter(key => key !== 'id').map(key => String(finding?.[key] ?? '').replace(/\s+/g, ' ').trim()));
206
+ // Records identical in every field, character for character (their fields are trimmed when an answer is read):
207
+ // whitespace inside quoted code can tell two places apart, so it is not normalized.
208
+ const findingKey = finding => JSON.stringify(FINDING_FIELDS.filter(key => key !== 'id').map(key => String(finding?.[key] ?? '')));
520
209
  const findingOnly = finding => Object.fromEntries(FINDING_FIELDS.filter(key => key !== 'id' && Object.hasOwn(finding, key)).map(key => [key, finding[key]]));
521
210
 
211
+ /** The fields of a finding whose text may name another finding of its answer. */
212
+ const PROSE_FIELDS = ['summary', 'evidence', 'counterevidence', 'suggestion'];
213
+ // An ID as a text names it: not inside a name (a letter, digit or hyphen before or after it, also across a run of
214
+ // underscores), but where Markdown emphasis wraps it in underscores (_F-1_).
215
+ const ID_TOKEN = new RegExp(`(?<![A-Za-z0-9-])(?<![A-Za-z0-9-]_+)${LOCAL_PREFIX}-[1-9]\\d*(?![A-Za-z0-9-])(?!_+[A-Za-z0-9-])`, 'g');
216
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
217
+
218
+ /**
219
+ * What an answer's text says of its own findings, by the IDs the answer gave them, with the review's IDs of those
220
+ * findings (`ids`: the answer's ID -> the review's). Code stays as written: a fenced block (from a line that opens
221
+ * with three or more backticks or tildes to a line of at least as many of the same and nothing else, or to the
222
+ * end of the text), an inline code span (from a run of backticks to the next run of the same length; without
223
+ * one, to the end of its paragraph), and an ID written directly between quotes, which is a literal and no
224
+ * reference. Other IDs, and text without IDs of the answer, are left as they are.
225
+ */
226
+ export function renameReferences(text, ids) {
227
+ if (typeof text !== 'string' || !ids?.size) return text;
228
+ const prose = part => part.replace(ID_TOKEN, (token, offset, whole) => {
229
+ const before = whole[offset - 1], after = whole[offset + token.length];
230
+ return !ids.has(token) || ((before === '"' || before === "'") && after === before) ? token : ids.get(token);
231
+ });
232
+ const spans = part => {
233
+ let out = '', at = 0;
234
+ // A backtick a backslash escapes opens no span.
235
+ const opener = /(?<!\\)`+/g;
236
+ for (let match; (match = opener.exec(part));) {
237
+ const closer = new RegExp('(?<!`)' + match[0] + '(?!`)', 'g');
238
+ closer.lastIndex = match.index + match[0].length;
239
+ const end = closer.exec(part), stop = end ? end.index + end[0].length : part.length;
240
+ out += prose(part.slice(at, match.index)) + part.slice(match.index, stop);
241
+ at = opener.lastIndex = stop;
242
+ }
243
+ return out + prose(part.slice(at));
244
+ };
245
+ const out = [];
246
+ let paragraph = [], fence = null;
247
+ const flush = () => { if (paragraph.length) out.push(spans(paragraph.join('\n'))); paragraph = []; };
248
+ for (const line of text.split('\n')) {
249
+ if (fence) {
250
+ out.push(line);
251
+ if (fence.test(line)) fence = null;
252
+ continue;
253
+ }
254
+ // A fence line is read without its carriage return (CRLF text); the line itself stays as it is.
255
+ const open = FENCE.exec(line.replace(/\r$/, ''));
256
+ // A fence of backticks has no backtick in its info string; one that does is inline code.
257
+ if (open && !(open[1][0] === '`' && open[2].includes('`'))) {
258
+ flush();
259
+ out.push(line);
260
+ fence = new RegExp(`^ {0,3}${open[1][0]}{${open[1].length},}[ \\t]*\\r?$`);
261
+ continue;
262
+ }
263
+ if (!line.trim()) { flush(); out.push(line); continue; }
264
+ paragraph.push(line);
265
+ }
266
+ flush();
267
+ return out.join('\n');
268
+ }
269
+
522
270
  /**
523
- * Quick review: one reviewer per shard covers functional and risk focus and
524
- * checks its own findings against the source; no verifier, duplicate check or
525
- * summary session runs. Findings that pass the runtime's checks are REPORTED
526
- * (not independently verified); the rest are NEEDS_INFO. Status, coverage and
527
- * verification are reported separately: a parsed answer without a usable
528
- * review never makes a commentable COMPLETE, and zero findings never hide
529
- * files that were not reviewed.
271
+ * The order in which a review numbers its findings: by side (HEAD first), path
272
+ * and lines, then by where each was reported (pass, shard, part of a split
273
+ * shard, place in its answer). Nothing here depends on which session finished
274
+ * first or on the IDs a model wrote. A finding without a usable location comes
275
+ * after those with one.
530
276
  */
531
- export async function runQuickReview(ctx, run, request) {
532
- const { azure, progress, settings } = ctx;
533
- const { snapshot, warnings, modelSnapshot } = await prepareSnapshot(ctx, run, request);
277
+ function placeKey(entry) {
278
+ const match = LOCATION.exec(String(entry.finding.location ?? '').trim());
279
+ const start = match?.[3] ? Number(match[3]) : 0;
280
+ return { located: match ? 0 : 1, side: match?.[1] === 'base' ? 1 : 0, path: match?.[2] ?? '', start, end: match?.[4] ? Number(match[4]) : start };
281
+ }
282
+ function byPlaceAndSource(a, b) {
283
+ const x = placeKey(a), y = placeKey(b);
284
+ return x.located - y.located || x.side - y.side || (x.path < y.path ? -1 : x.path > y.path ? 1 : 0) || x.start - y.start || x.end - y.end ||
285
+ a.task.pass - b.task.pass || a.task.index - b.task.index || ((a.task.part ?? '') < (b.task.part ?? '') ? -1 : (a.task.part ?? '') > (b.task.part ?? '') ? 1 : 0) || a.position - b.position;
286
+ }
287
+
288
+ /**
289
+ * The findings a duplicate check compares: those still reported on one side of
290
+ * one file, where two of them come from different reviewer sessions (a finding
291
+ * that stands for identical records of several sessions shares each of them). Groups
292
+ * are sorted by side and path and keep the findings in the review's order, so a
293
+ * check's input is the same whatever order the sessions finished in.
294
+ * @param {{id: string, status: string, finding?: object, sessions: string[]}[]} dispositions
295
+ */
296
+ export function duplicateGroups(dispositions) {
297
+ const groups = new Map();
298
+ for (const entry of dispositions) {
299
+ if (entry.status !== 'REPORTED') continue;
300
+ const match = LOCATION.exec(String(entry.finding.location ?? '').trim());
301
+ if (!match) continue;
302
+ const side = match[1] ?? 'head', key = `${side}\n${match[2]}`;
303
+ if (!groups.has(key)) groups.set(key, { side, path: match[2], items: [] });
304
+ groups.get(key).items.push(entry);
305
+ }
306
+ // Worth a check only where two findings could be merged at all: two that share no session.
307
+ const comparable = items => items.some((a, index) => items.slice(index + 1).some(b => !a.sessions.some(session => b.sessions.includes(session))));
308
+ return [...groups.entries()].filter(([, group]) => comparable(group.items))
309
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, group]) => group);
310
+ }
311
+
312
+ /** Findings one severity-rating session receives. */
313
+ const RATING_BATCH = 25;
314
+ const RATING_DESCRIPTION_CHARACTERS = 4000;
315
+ // What a rating session sees of a finding: its text and its place, never a level, a count or where it came from.
316
+ const RATED_FIELDS = Object.freeze(['summary', 'location', 'evidence', 'counterevidence', 'suggestion']);
317
+
318
+ /**
319
+ * Severity rating: sessions without tools rate the findings that are still
320
+ * reported from their text alone, without the level their reviewer gave them,
321
+ * so that the findings of different reviewers are levelled on one scale. It
322
+ * runs with models.<mode>.rater, or with the first reviewer model where that is
323
+ * empty; rater: false switches it off. A finding the rating does not cover, and
324
+ * every finding of a failed batch, keeps its reviewer's severity, which the
325
+ * record keeps in any case (`reviewerSeverity`). Returns what the method
326
+ * description says of the rating.
327
+ */
328
+ async function rateSeverities(ctx, run, { snapshot, dispositions, warnings }) {
329
+ const { runStage, progress, settings } = ctx;
330
+ const rater = roleFor(run.profile, 'rating');
331
+ const state = raterState(settings, run.profile);
332
+ if (state === 'off' || !stageModel(settings, rater)) return { state: 'off', sessions: 0, failed: 0, rated: 0, kept: 0 };
333
+ const rated = dispositions.filter(row => row.status === 'REPORTED');
334
+ const outcome = { state, model: stageModel(settings, rater), sessions: 0, failed: 0, rated: 0, kept: 0 };
335
+ if (!rated.length) return outcome;
336
+ const batches = [];
337
+ for (let at = 0; at < rated.length; at += RATING_BATCH) batches.push(rated.slice(at, at + RATING_BATCH));
338
+ outcome.sessions = batches.length;
339
+ progress(run, `Severity rating: ${rated.length} finding(s) in ${batches.length} session(s).`);
340
+ const description = text(snapshot.description) ? snapshot.description : '';
341
+ const change = { title: snapshot.title ?? '', description: description.length > RATING_DESCRIPTION_CHARACTERS
342
+ ? `${description.slice(0, RATING_DESCRIPTION_CHARACTERS)} […]` : description };
343
+ const outcomes = await runPool(batches.map((items, index) => ({ items, index, count: batches.length })), settings.workflow.parallelSessions, async task => {
344
+ const ids = task.items.map(item => item.id);
345
+ const payload = {
346
+ outputLanguage: settings.outputLanguage, change,
347
+ assignment: { kind: 'rating', findingIds: ids,
348
+ findings: task.items.map(item => ({ id: item.id, ...Object.fromEntries(RATED_FIELDS.filter(key => Object.hasOwn(item.finding, key)).map(key => [key, item.finding[key]])) })) },
349
+ };
350
+ try {
351
+ const result = await runStage(run, rater, payload, {
352
+ evaluate(answer) {
353
+ const { result, issues } = evaluateRatings(answer, { ids });
354
+ // Usable where it rated something: its valid ratings stand if a correction turn fails.
355
+ return { result, issues, usable: result.structured && result.ratings.length > 0,
356
+ repairPrompt: issues.length ? ratingRepairPrompt(issues, { parseOnly: !result.structured && syntaxProblem(issues) }) : undefined };
357
+ },
358
+ }, { label: task.count > 1 ? `${task.index + 1}/${task.count}` : '' });
359
+ return { ...task, result };
360
+ } catch (error) {
361
+ if (!run.active) throw error;
362
+ return { ...task, error };
363
+ }
364
+ });
365
+ if (!run.active) throw new Error(run.reason || 'Review stopped.');
366
+ for (const { items, result, error } of outcomes) {
367
+ if (!result) {
368
+ outcome.failed++;
369
+ outcome.kept += items.length;
370
+ warnings.push(`The severity rating failed (${error?.message ?? 'unknown error'}); its ${items.length} finding(s) keep their reviewer's severity.`);
371
+ continue;
372
+ }
373
+ const byId = new Map(result.ratings.map(row => [row.id, row]));
374
+ for (const item of items) {
375
+ const row = byId.get(item.id);
376
+ if (!row) { outcome.kept++; continue; }
377
+ outcome.rated++;
378
+ item.finding = { ...item.finding, severity: row.severity };
379
+ item.ratedSeverity = row.severity;
380
+ }
381
+ warnings.push(...result.warnings.map(message => `Severity rating: ${message}`));
382
+ }
383
+ return outcome;
384
+ }
385
+
386
+ /**
387
+ * One review. Each entry of the mode's model list is a pass: an independent
388
+ * reviewer session per shard that covers functional and failure focus and
389
+ * checks its own findings against the source. The runtime then checks each
390
+ * finding's form and source (REPORTED, or NEEDS_INFO), numbers the findings in
391
+ * a fixed order, removes records identical in every field, has a duplicate
392
+ * check merge repeated reports of one defect, and has the findings rated.
393
+ * Status, coverage and method are reported separately: a parsed answer without
394
+ * a usable review never makes a commentable COMPLETE, zero findings never hide
395
+ * files that were not reviewed, and a pass that fails leaves the others' work.
396
+ * @param {object} ctx { azure, runStage, progress, settings, dataFor }
397
+ * @param {object} run
398
+ * @param {object} request parsed /pr-review arguments
399
+ */
400
+ export async function runReview(ctx, run, request) {
401
+ const { azure, runStage, progress, settings } = ctx;
402
+ const { store, snapshot, warnings, modelSnapshot } = await prepareSnapshot(ctx, run, request);
534
403
  const shards = shardFiles(snapshot.files, settings.workflow.shardFiles);
535
- const [role] = initialRoles('quick');
536
- const counter = { next: shards.length * ID_SPAN };
537
- const tasks = shards.map((files, index) => ({ role, files, index, count: shards.length, idBase: index * ID_SPAN }));
538
- progress(run, `Quick review: ${tasks.length} session(s) for ${shards.length} shard(s); no independent verification follows.`);
539
- const initialTask = initialRunner(ctx, run, request, { snapshot, modelSnapshot, counter, handlerFor: task => ({
540
- evaluate: (answer, _previous, session) => evaluateQuick(answer, { task, snapshot, azure, run, reads: session?.reads }),
404
+ const roles = reviewerRoles(settings, run.profile), passes = roles.length;
405
+ // One pool for every pass of every shard: the session limit holds for the review, not per pass.
406
+ // A shard's sessions number their findings in a range of the shard's own (F-1001, F-2001, …), apart from the
407
+ // review's IDs, which the runtime gives once every pass has answered and then puts where an answer's text names
408
+ // one of its own findings. Every pass of a shard gets the same range, so that no pass's input differs from
409
+ // another's.
410
+ const tasks = roles.flatMap((role, pass) => shards.map((files, index) => ({ role, pass, passes, files, index, count: shards.length, base: (index + 1) * 1000 + 1 })));
411
+ progress(run, `Review: ${tasks.length} session(s) for ${shards.length} shard(s)${passes > 1 ? ` in ${passes} independent passes` : ''}; no separate verification follows.`);
412
+ const reviewTask = reviewRunner(ctx, run, request, { snapshot, modelSnapshot, handlerFor: task => ({
413
+ evaluate: (answer, _previous, session) => evaluateReview(answer, { task, snapshot, azure, run, reads: session?.reads }),
414
+ // Only a shard of several files can be split: one of one file keeps an answer it gave before its context overflowed.
415
+ splittable: task.files.length > 1,
541
416
  }) });
542
- const outcomes = (await runPool(tasks, settings.workflow.parallelSessions, initialTask)).flat();
417
+ const outcomes = (await runPool(tasks, settings.workflow.parallelSessions, reviewTask)).flat();
543
418
  if (!run.active) throw new Error(run.reason || 'Review stopped.');
544
- if (!outcomes.some(outcome => outcome.result)) throw new Error(`Every quick review session failed: ${[...new Set(outcomes.map(outcome => outcome.error?.message).filter(Boolean))].slice(0, 3).join(' | ')}`);
419
+ if (!outcomes.some(outcome => outcome.result)) throw new Error(`Every review session failed: ${[...new Set(outcomes.map(outcome => outcome.error?.message).filter(Boolean))].slice(0, 3).join(' | ')}`);
545
420
 
546
- const findings = [], dispositions = [], reports = [], initialReports = [], unusableTexts = [], discovered = new Set(), covered = new Set(), used = new Set();
547
- const coverage = { [role]: { assigned: 0, covered: 0, failedFiles: [], gaps: [] } };
548
- let usable = 0, failedShards = 0, reviewerGaps = false;
421
+ const collected = [], reports = [], answerReports = [], answerGaps = [], initialReports = [], unusableTexts = [], discovered = new Set();
422
+ // Per pass: the assigned paths a usable answer reported as reviewed. Retries, follow-ups and the parts of a
423
+ // split shard belong to their pass; a path counts once per pass however often it is named.
424
+ const reviewedBy = roles.map(() => new Set());
425
+ const coverage = Object.fromEntries(roles.map(role => [role, { assigned: 0, covered: 0, failedFiles: [], gaps: [] }]));
426
+ // Per pass, the shard sessions whose outcome its coverage rests on: a split shard counts its two halves, not the
427
+ // session that overflowed, and a session retried after a transient failure counts once. The stage records and the
428
+ // receipt list every session that ran.
429
+ const passRecords = roles.map((role, pass) => ({ pass: pass + 1, model: stageModel(settings, role), sessions: 0, failed: 0 }));
430
+ let usable = 0, failedSessions = 0, reviewerGaps = false;
549
431
  for (const { task, result, error } of outcomes) {
550
- const label = shardLabel(task);
551
- coverage[role].assigned += task.files.length;
432
+ const label = sessionLabel(task), named = `The review ${label || 'session'}`, entry = coverage[task.role], record = passRecords[task.pass];
433
+ entry.assigned += task.files.length;
434
+ record.sessions++;
552
435
  if (!result) {
553
- failedShards++;
554
- coverage[role].failedFiles.push(...task.files);
555
- warnings.push(`The quick review ${label || 'session'} failed (${error?.message ?? 'unknown error'}); its ${task.files.length || 'unknown'} file(s) were not reviewed.`);
436
+ failedSessions++; record.failed++;
437
+ entry.failedFiles.push(...task.files);
438
+ warnings.push(`${named} failed (${error?.message ?? 'unknown error'}); its ${task.files.length || 'unknown'} file(s) were not reviewed${passes > 1 ? ' in this pass' : ''}.`);
556
439
  continue;
557
440
  }
558
- // Classify before IDs are made unique: the checks are keyed by the answer's IDs.
559
- const entries = result.findings.map(finding => ({ finding, problems: result.invalid?.[finding.id] ?? [], check: result.checks?.[finding.id] }));
560
- const isUsable = quickUsable(result, task.files);
561
- uniqueIds(result.findings, 'Q', used);
562
- const reviewed = result.envelope?.coverage ? result.coverage.files.filter(path => task.files.includes(path)) : [];
441
+ const isUsable = usableAnswer(result, task.files);
442
+ const reviewed = result.envelope?.coverage ? [...new Set(result.coverage.files.filter(path => task.files.includes(path)))] : [];
563
443
  if (!isUsable) {
564
- failedShards++;
565
- coverage[role].failedFiles.push(...task.files);
566
- warnings.push(`The quick review ${label || 'session'} returned no usable review (${result.structured ? 'no reviewed file or usable finding' : 'no structured answer'}); its ${task.files.length} file(s) count as not reviewed.`);
567
- if (text(result.report)) unusableTexts.push(label ? `### ${label}\n\n${result.report}` : result.report);
444
+ failedSessions++; record.failed++;
445
+ entry.failedFiles.push(...task.files);
446
+ warnings.push(`${named} returned no usable review (${result.structured ? 'no reviewed file or usable finding' : 'no structured answer'}); its ${task.files.length} file(s) count as not reviewed${passes > 1 ? ' in this pass' : ''}.`);
447
+ if (text(result.report)) unusableTexts.push({ session: sessionOf(task), label, text: result.report });
568
448
  } else {
569
449
  usable++;
570
- for (const path of reviewed) covered.add(path);
571
- coverage[role].covered += reviewed.length;
572
- coverage[role].gaps.push(...result.coverage.gaps);
450
+ for (const path of reviewed) reviewedBy[task.pass].add(path);
451
+ entry.covered += reviewed.length;
452
+ answerGaps.push({ role: task.role, session: sessionOf(task), gaps: result.coverage.gaps });
573
453
  if (result.coverage.gaps.length) reviewerGaps = true;
574
454
  for (const path of result.additionalFiles) discovered.add(path);
575
- if (text(result.report)) reports.push(label ? `### ${label}\n\n${result.report}` : result.report);
576
- }
577
- // The session that reported a finding, recorded by the runtime (never derived from IDs):
578
- // comment planning may combine findings of different sessions that repeat one defect.
579
- const shard = `${task.index + 1}/${task.count}${task.part ?? ''}`;
580
- for (const { finding, problems, check } of entries) {
581
- findings.push({ ...finding, origin: role });
582
- const partial = findingOnly(finding);
583
- if (!isUsable) dispositions.push({ id: finding.id, status: 'NEEDS_INFO', reason: 'The finding comes from a quick review answer that was not usable. [Runtime: not eligible for comments.]', partialFinding: partial, shard });
584
- else if (problems.length) dispositions.push({ id: finding.id, status: 'NEEDS_INFO', reason: `The finding is ${problems.join('; ')} after the correction turns. [Runtime: not eligible for comments.]`, partialFinding: partial, shard });
585
- else if (!check?.ok) dispositions.push({ id: finding.id, status: 'NEEDS_INFO', reason: `The location check failed: ${check?.problem ?? 'it was not checked.'} [Runtime: not eligible for comments.]`, partialFinding: partial, shard });
586
- else dispositions.push({ id: finding.id, status: 'REPORTED', reason: QUICK_REPORTED_REASON, finding: partial, inline: check.inline, shard });
455
+ if (text(result.report)) answerReports.push({ session: sessionOf(task), label, text: result.report });
587
456
  }
588
- initialReports.push({ role, shard: `${task.index + 1}/${task.count}${task.part ?? ''}`, files: task.files.length, status: result.status,
457
+ // The session that reported a finding is recorded by the runtime, never derived from IDs. The checks are
458
+ // keyed by the answer's own IDs, which stay with the finding (`localId`).
459
+ const session = sessionOf(task);
460
+ result.findings.forEach((finding, position) => {
461
+ const problems = result.invalid?.[finding.id] ?? [], check = result.checks?.[finding.id];
462
+ const verdict = !isUsable ? { status: 'NEEDS_INFO', reason: 'The finding comes from a reviewer answer that was not usable. [Runtime: not eligible for comments.]' }
463
+ : problems.length ? { status: 'NEEDS_INFO', reason: `The finding is ${problems.join('; ')} after the correction turns. [Runtime: not eligible for comments.]` }
464
+ : !check?.ok ? { status: 'NEEDS_INFO', reason: `The location check failed: ${check?.problem ?? 'it was not checked.'} [Runtime: not eligible for comments.]` }
465
+ : { status: 'REPORTED', reason: REPORTED_REASON, inline: check.inline };
466
+ // An ID the parser had to give a finding (none, a malformed or a repeated one) is no ID the answer's text uses.
467
+ collected.push({ ...verdict, finding: findingOnly(finding), localId: finding.id, suppliedId: finding.generatedId ? undefined : finding.id, task, session, position });
468
+ });
469
+ initialReports.push({ role: task.role, shard: `${task.index + 1}/${task.count}${task.part ?? ''}`, ...(passes > 1 ? { pass: task.pass + 1 } : {}), files: task.files.length, status: result.status,
589
470
  structured: result.structured, usable: isUsable, report: result.report, gaps: result.coverage.gaps, warnings: result.warnings });
590
- warnings.push(...result.warnings.map(message => label ? `Quick review ${label}: ${message}` : `Quick review: ${message}`));
471
+ warnings.push(...result.warnings.map(message => `Review${label ? ` ${label}` : ''}: ${message}`));
591
472
  }
592
- // Only records identical in every field are duplicates; findings on the same lines stay separate.
473
+
474
+ // The review's IDs, in a fixed order, before anything is merged.
475
+ collected.sort(byPlaceAndSource);
476
+ const findings = [], dispositions = [];
477
+ // Where an answer's text names one of its own findings by an ID the answer gave it, the review names that
478
+ // finding by its review ID: in the finding fields, the notes and the gaps. Code stays as written
479
+ // (`renameReferences`), and the answer's own ID stays on record (`localId`). Until the merges are settled a text
480
+ // names the ID its finding was given; once they are, it names the finding that stays, which is what the rating,
481
+ // the comments and every reader see.
482
+ const ownIds = new Map();
483
+ collected.forEach((entry, index) => {
484
+ if (!ownIds.has(entry.session)) ownIds.set(entry.session, new Map());
485
+ const ids = ownIds.get(entry.session);
486
+ if (entry.suppliedId && !ids.has(entry.suppliedId)) ids.set(entry.suppliedId, `${LOCAL_PREFIX}-${index + 1}`);
487
+ });
488
+ const named = (session, survivorOf = id => id) => new Map([...(ownIds.get(session) ?? [])].map(([own, id]) => [own, survivorOf(id)]));
489
+ const proseOf = (finding, ids) => Object.fromEntries(Object.entries(finding).map(([key, value]) => [key, PROSE_FIELDS.includes(key) ? renameReferences(value, ids) : value]));
490
+ // Records identical in every field are duplicates, where what their texts name is the same: a finding that
491
+ // names itself names itself in each copy, and texts that name different other findings differ, for the
492
+ // duplicate check to decide about.
493
+ const keys = new Map();
494
+ collected.forEach((entry, index) => {
495
+ const id = `${LOCAL_PREFIX}-${index + 1}`, finding = proseOf(entry.finding, named(entry.session));
496
+ // In the key, a reference reads as what it names, apart from any text that only looks like an ID.
497
+ const self = new Map([...named(entry.session)].map(([own, review]) => [own, review === id ? '\u0000itself' : `\u0000${review}`]));
498
+ keys.set(id, findingKey(proseOf(entry.finding, self)));
499
+ dispositions.push({ id, status: entry.status, reason: entry.reason,
500
+ ...(entry.status === 'REPORTED' ? { finding, inline: entry.inline, reviewerSeverity: finding.severity } : { partialFinding: finding }),
501
+ shard: entry.session, pass: entry.task.pass + 1, localId: entry.localId, sessions: [entry.session] });
502
+ });
503
+ // Only records identical in every field are duplicates; findings on the same lines stay separate. The first in
504
+ // the review's order stays, and it stands for the sessions that reported the same record as a usable finding.
593
505
  const kept = new Map();
594
506
  let duplicates = 0;
595
507
  for (const status of ['REPORTED', 'NEEDS_INFO']) for (const entry of dispositions.filter(row => row.status === status)) {
596
- const key = findingKey(entry.finding ?? entry.partialFinding);
597
- if (!kept.has(key)) { kept.set(key, entry.id); continue; }
598
- Object.assign(entry, { status: 'MERGED', mergedInto: kept.get(key), reason: `Identical in every field to ${kept.get(key)}. [Runtime: exact duplicate.]` });
508
+ const key = keys.get(entry.id);
509
+ if (!kept.has(key)) { kept.set(key, entry); continue; }
510
+ const first = kept.get(key);
511
+ if (status === 'REPORTED' && first.status === 'REPORTED') first.sessions = [...new Set([...first.sessions, ...entry.sessions])];
512
+ Object.assign(entry, { status: 'MERGED', mergedInto: first.id, reason: `Identical in every field to ${first.id}. [Runtime: exact duplicate.]`, mergedFinding: entry.finding ?? entry.partialFinding });
599
513
  delete entry.finding; delete entry.inline; delete entry.partialFinding;
600
514
  duplicates++;
601
515
  }
602
516
  if (duplicates) warnings.push(`Removed ${duplicates} exact duplicate finding(s); findings that differ in any field are kept.`);
517
+
518
+ // The duplicate check: what different sessions reported on one side of one file is compared by the first
519
+ // reviewer model. It only merges, and never two findings of one session; a failed check keeps every finding.
520
+ const groups = duplicateGroups(dispositions);
521
+ const duplicateCheck = { groups: groups.length, failed: 0, merged: 0, refused: 0 };
522
+ if (groups.length) {
523
+ progress(run, `Duplicate check: ${groups.length} file(s) hold findings from more than one reviewer session.`);
524
+ const checker = roleFor(run.profile, 'dedupe');
525
+ const checks = await runPool(groups.map((group, index) => ({ group, index, count: groups.length })), settings.workflow.parallelSessions, async task => {
526
+ const ids = task.group.items.map(item => item.id);
527
+ const sessions = Object.fromEntries(task.group.items.map(item => [item.id, item.sessions]));
528
+ const candidates = task.group.items.map(({ id, sessions: reportedBy, finding }) => ({ ...finding, id, session: reportedBy.join(' + ') }));
529
+ try {
530
+ // Preparing the input is part of the check: a write that fails costs this file's check, not the review.
531
+ const payload = {
532
+ prUrl: request.prUrl, userContext: request.userContext, outputLanguage: settings.outputLanguage, snapshot: modelSnapshot,
533
+ assignment: { kind: 'duplicates', file: task.group.path, side: task.group.side, findingIds: ids, findings: await store.pack(candidates, 40000) },
534
+ };
535
+ const result = await runStage(run, checker, payload, {
536
+ evaluate(answer) {
537
+ const { result, issues } = evaluateDuplicates(answer, { ids, sessions });
538
+ // Usable where it decided something: its valid merges stand if a correction turn fails.
539
+ return { result, issues, usable: result.structured && result.decided === true,
540
+ repairPrompt: issues.length ? duplicateRepairPrompt(issues, { parseOnly: !result.structured && syntaxProblem(issues) }) : undefined };
541
+ },
542
+ }, { label: task.count > 1 ? `${task.index + 1}/${task.count}` : '' });
543
+ return { ...task, result };
544
+ } catch (error) {
545
+ if (!run.active) throw error;
546
+ return { ...task, error };
547
+ }
548
+ });
549
+ if (!run.active) throw new Error(run.reason || 'Review stopped.');
550
+ const byId = new Map(dispositions.map(row => [row.id, row]));
551
+ for (const { group, result, error } of checks) {
552
+ if (!result) {
553
+ duplicateCheck.failed++;
554
+ warnings.push(`The duplicate check of ${group.path} failed (${error?.message ?? 'unknown error'}); its ${group.items.length} findings stay reported and may include duplicates.`);
555
+ continue;
556
+ }
557
+ // An answer without usable JSON, or without a list of merges, also after the correction turns, decided
558
+ // nothing: a failed check, whose findings all stay as they are.
559
+ const decided = result.structured !== false && result.decided === true;
560
+ if (!decided) duplicateCheck.failed++;
561
+ duplicateCheck.refused += result.refused ?? 0;
562
+ for (const merge of decided ? result.merges : []) {
563
+ const entry = byId.get(merge.id), target = byId.get(merge.mergedInto);
564
+ if (entry?.status !== 'REPORTED' || target?.status !== 'REPORTED') continue;
565
+ target.sessions = [...new Set([...target.sessions, ...entry.sessions])];
566
+ // What the kept finding stands for: each merged report with its session and the level its reviewer gave it.
567
+ target.alsoReported = [...(target.alsoReported ?? []), { id: entry.id, sessions: entry.sessions, severity: entry.reviewerSeverity }, ...(entry.alsoReported ?? [])];
568
+ Object.assign(entry, { status: 'MERGED', mergedInto: target.id, reason: `${merge.reason} [Runtime: merged by the duplicate check of independent reviewer sessions.]`, mergedFinding: entry.finding });
569
+ delete entry.finding; delete entry.inline; delete entry.alsoReported;
570
+ duplicateCheck.merged++;
571
+ }
572
+ if (text(result.report)) reports.push(`### Duplicate check: ${group.path}\n\n${result.report}`);
573
+ warnings.push(...result.warnings.map(message => `Duplicate check of ${group.path}: ${message}`));
574
+ }
575
+ progress(run, `Duplicate check finished: ${duplicateCheck.merged} finding(s) merged into another session's finding.`);
576
+ }
577
+ // A record merged as an exact duplicate into a finding the duplicate check merged in turn names the finding that
578
+ // stays, so that every merged ID leads to one that a person can see, adjust and comment on.
579
+ const byIdAll = new Map(dispositions.map(row => [row.id, row]));
580
+ for (const row of dispositions) {
581
+ if (row.status !== 'MERGED') continue;
582
+ const seen = new Set([row.id]);
583
+ let target = byIdAll.get(row.mergedInto);
584
+ while (target?.status === 'MERGED' && !seen.has(target.id)) { seen.add(target.id); target = byIdAll.get(target.mergedInto); }
585
+ if (target && target.id !== row.mergedInto) row.mergedInto = target.id;
586
+ }
587
+ // The merges are settled: a text that names a finding that was merged names the finding that stays, the one a
588
+ // person can see, adjust and exclude.
589
+ const survivorOf = id => byIdAll.get(id)?.status === 'MERGED' ? byIdAll.get(id).mergedInto : id;
590
+ collected.forEach((entry, index) => {
591
+ const id = `${LOCAL_PREFIX}-${index + 1}`, row = byIdAll.get(id), finding = proseOf(entry.finding, named(entry.session, survivorOf));
592
+ for (const key of ['finding', 'partialFinding', 'mergedFinding']) if (row[key]) row[key] = finding;
593
+ findings.push({ ...finding, id, origin: entry.task.role });
594
+ });
595
+ const reportOf = ({ session, label, text: body }) => {
596
+ const value = renameReferences(body, named(session, survivorOf));
597
+ return label ? `### ${label}\n\n${value}` : value;
598
+ };
599
+ reports.unshift(...answerReports.map(reportOf));
600
+ for (const { role, session, gaps } of answerGaps) coverage[role].gaps.push(...gaps.map(gap => renameReferences(gap, named(session, survivorOf))));
601
+
602
+ const rating = await rateSeverities(ctx, run, { snapshot, dispositions, warnings });
603
+
603
604
  const search = searchLimitation(run, settings);
604
605
  if (search) warnings.push(search);
605
- if (discovered.size) warnings.push(`The quick reviewer reported ${discovered.size} changed path(s) missing from Azure's list: ${[...discovered].slice(0, 20).join(', ')}${discovered.size > 20 ? ', ...' : ''}`);
606
- const unreviewedFiles = snapshot.files.filter(path => !covered.has(path)).length;
607
- const reasons = [...(failedShards ? ['shard-failed'] : []), ...(snapshot.filesComplete ? [] : ['partial-file-list']), ...(reviewerGaps ? ['reviewer-gaps'] : [])];
608
- const coverageSummary = { complete: !unreviewedFiles && !reasons.length, unreviewedFiles, filesComplete: snapshot.filesComplete, reasons };
606
+ if (discovered.size) warnings.push(`Reviewers reported ${discovered.size} changed path(s) missing from Azure's list: ${[...discovered].slice(0, 20).join(', ')}${discovered.size > 20 ? ', ...' : ''}`);
607
+ // Two numbers, of the changed files Azure listed: reviewed in at least one pass, and reviewed in every pass.
608
+ const reviewedOnce = snapshot.files.filter(path => reviewedBy.some(set => set.has(path))).length;
609
+ const reviewedByAll = snapshot.files.filter(path => reviewedBy.every(set => set.has(path))).length;
610
+ const unreviewedFiles = snapshot.files.length - reviewedOnce;
611
+ const reasons = [...(failedSessions && unreviewedFiles ? ['shard-failed'] : []), ...(snapshot.filesComplete ? [] : ['partial-file-list']), ...(reviewerGaps ? ['reviewer-gaps'] : [])];
612
+ const coverageSummary = { complete: !unreviewedFiles && !reasons.length, unreviewedFiles, filesComplete: snapshot.filesComplete, reasons,
613
+ files: snapshot.files.length, passes, reviewedOnce, reviewedByAll, failedSessions };
609
614
  const reported = dispositions.filter(row => row.status === 'REPORTED').length;
610
- progress(run, `Quick review finished: ${reported} reported finding(s), ${dispositions.filter(row => row.status === 'NEEDS_INFO').length} need more information; coverage ${coverageSummary.complete ? 'complete' : 'incomplete'}.`);
615
+ progress(run, `Review finished: ${reported} reported finding(s), ${dispositions.filter(row => row.status === 'NEEDS_INFO').length} need more information; ${reviewedOnce}/${snapshot.files.length} file(s) reviewed${passes > 1 ? `, ${reviewedByAll}/${snapshot.files.length} in every pass` : ''}.`);
611
616
 
612
617
  const { freshness, stale } = await finalRecheck(ctx, run, snapshot, warnings);
613
618
  const status = stale ? 'STALE' : usable ? 'COMPLETE' : 'PARTIAL';
@@ -616,8 +621,11 @@ export async function runQuickReview(ctx, run, request) {
616
621
  report: reports.join('\n\n'),
617
622
  reviewWarnings: [...new Set(warnings)],
618
623
  coverage, coverageSummary, discoveredFiles: [...discovered], initialReports, verification: 'none',
624
+ // How the findings were produced, for every later reader of the record: which models were asked for, what each
625
+ // pass did, and whether the duplicate check and the rating ran.
626
+ method: { kind: 'reviewers', version: 1, requested: [...settings.models[run.profile].reviewers], passes: passRecords, duplicateCheck, rating },
619
627
  initialObservations: status === 'COMPLETE' ? [] : findings,
620
- unstructuredInitials: unusableTexts,
621
- shards: { initial: shards.length, verification: 0, duplicateChecks: 0 },
628
+ unstructuredInitials: unusableTexts.map(reportOf),
629
+ shards: { initial: shards.length, passes, duplicateChecks: groups.length, ratings: rating.sessions },
622
630
  };
623
631
  }