opencode-azure-devops-pr-review 0.4.5 → 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.
package/src/comments.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // Comment plans: per-item validation, stable markers and saved publication text.
2
2
  import { createHash } from 'node:crypto';
3
- import { renderReviewSummary, describeReview } from './attribution.mjs';
3
+ import { renderReviewSummary, renderOtherPlaces, listablePlace, OTHER_PLACES_HEADINGS, describeReview } from './attribution.mjs';
4
4
  import { targetKey } from './azure.mjs';
5
5
  import { parseModelJSON, canonicalKey, parseRepairPrompt } from './output.mjs';
6
6
 
@@ -15,6 +15,7 @@ const hash = value => createHash('sha256').update(JSON.stringify(value)).digest(
15
15
  const markerTag = fingerprint => `<!-- azpr-comment:${fingerprint} -->`;
16
16
  const escapeComments = value => value.replaceAll('<!--', '&lt;!--').replaceAll('-->', '--&gt;');
17
17
 
18
+ /** The findings of a verified review saved by 0.4.x: what its verifier confirmed, and what it added. */
18
19
  export function confirmedFindings(review) {
19
20
  // Initial candidates remain audit data. Only verifier-corrected claims count;
20
21
  // a moved finding's initial location stays in the report, not in the claim.
@@ -24,35 +25,95 @@ export function confirmedFindings(review) {
24
25
  }
25
26
 
26
27
  /**
27
- * Whether a saved review's findings were independently verified: "none" for a
28
- * quick review, "independent" for review and deep. Reviews saved before this
29
- * field existed are known only by their profile; anything else is null and is
30
- * never commented on.
28
+ * How a saved review's findings were produced, which decides what of it may
29
+ * become comments and what its comments say about it:
30
+ * - 'reviewers': this pipeline (reviewer passes, a duplicate check, a rating; no
31
+ * verification). The record says so itself, with `method` and
32
+ * `verification: 'none'`, and both must be there.
33
+ * - 'verified': a /pr-review or /pr-deep saved by 0.4.x, whose findings a
34
+ * verifier confirmed: `verification: 'independent'`, or no such field at all
35
+ * in records older than it.
36
+ * - 'quick': a /pr-quick saved by 0.4.x (`verification: 'none'`, no method).
37
+ * - null: anything else: a method this version does not know, or fields that
38
+ * contradict each other. Such a review can be listed and shown; it is never
39
+ * planned, adjusted or published.
31
40
  */
32
- export function reviewVerification(review) {
33
- if (review?.verification === 'none' || review?.verification === 'independent') return review.verification;
34
- if (review?.verification === undefined && ['review', 'deep'].includes(review?.profile)) return 'independent';
41
+ export function reviewMethod(review) {
42
+ const profile = review?.profile;
43
+ if (review?.method !== undefined) {
44
+ return isObject(review.method) && review.method.kind === 'reviewers' && review.method.version === 1 && review.verification === 'none'
45
+ && ['review', 'deep', 'quick'].includes(profile) ? 'reviewers' : null;
46
+ }
47
+ if (review?.verification === 'none') return profile === 'quick' ? 'quick' : null;
48
+ if (review?.verification === 'independent' || review?.verification === undefined) return ['review', 'deep'].includes(profile) ? 'verified' : null;
35
49
  return null;
36
50
  }
37
51
 
38
52
  /**
39
- * The findings comment planning may use: verified ones (CONFIRMED and verifier
40
- * additions) for review and deep; for a quick review the REPORTED ones, which
41
- * passed the runtime's checks but were not independently verified. A quick
42
- * finding whose location cannot carry an inline comment says `inline: false`.
53
+ * Whether a saved review's findings were independently verified, as its
54
+ * comments disclose it: "independent" for a verified review of 0.4.x, "none"
55
+ * for every other review whose method is known, null where it is not.
56
+ */
57
+ export function reviewVerification(review) {
58
+ const method = reviewMethod(review);
59
+ return method === 'verified' ? 'independent' : method ? 'none' : null;
60
+ }
61
+
62
+ /**
63
+ * The findings comment planning may use. A review of this pipeline, and a
64
+ * quick review of 0.4.x: the REPORTED ones that were not merged, which passed
65
+ * the runtime's checks and were not independently verified; one whose location
66
+ * cannot carry an inline comment says `inline: false`. A verified review of
67
+ * 0.4.x: the verifier's CONFIRMED findings and its additions. A review whose
68
+ * method is unknown has none.
43
69
  */
44
70
  export function publishableFindings(review) {
45
- if (reviewVerification(review) !== 'none') return confirmedFindings(review);
71
+ const method = reviewMethod(review);
72
+ if (method === 'verified') return confirmedFindings(review);
73
+ if (!method) return [];
46
74
  return review.final.dispositions.filter(d => d.status === 'REPORTED' && isObject(d.finding))
47
75
  .map(({ id, finding, inline, shard }) => ({ ...finding, id, ...(inline === false ? { inline: false } : {}), ...(shard ? { shard } : {}) }));
48
76
  }
49
77
 
50
- /** "head:/src/a.ts:12-14" -> { side, path, start, end }; null when no path. A location without a side is HEAD. */
78
+ /**
79
+ * Where a finding's location points, in every form a review of this version or of 0.4.x saved it:
80
+ * "head:/src/a.ts:12-14" -> { side, path, start, end }, also a structured location (JSON, or an object, with
81
+ * side, path, lineStart and lineEnd) and a path without its leading slash or with "./". A location without a side
82
+ * is HEAD, and a side is one only with its colon, so that "base/a.ts" is a path. null where it names no file.
83
+ * Every reading of a location goes through here: excerpts, skips, placement and the other places alike.
84
+ */
51
85
  export function parseLocation(location) {
52
- const match = /^(?:(head|base):?)?:?(\/[^:]+?)(?::(\d+)(?:-(\d+))?)?\s*$/.exec(String(location ?? '').trim());
53
- if (!match) return null;
54
- const start = match[3] ? Number(match[3]) : null;
55
- return { side: match[1] ?? 'head', path: match[2], start, end: match[4] ? Number(match[4]) : start };
86
+ let value = location;
87
+ if (typeof value === 'string' && value.trim().startsWith('{')) { try { value = JSON.parse(value); } catch { /* A string location. */ } }
88
+ if (value && typeof value === 'object') {
89
+ // Its path is a field of its own, so a colon in it is part of the name; its range is kept as written (a
90
+ // reversed one as the text form "3-2" is), and an end it leaves out is its start.
91
+ const side = value.side ?? 'head';
92
+ if (!['head', 'base'].includes(side) || typeof value.path !== 'string' || !value.path.startsWith('/') || /[\0\r\n]/.test(value.path)) return null;
93
+ // An end it leaves out is its start; an end it gives that is no line number leaves the range unknown, as a
94
+ // start that is none does: the file still takes a comment for one finding, and the place no other.
95
+ const start = Number.isSafeInteger(value.lineStart) && value.lineStart > 0 ? value.lineStart : null;
96
+ const end = value.lineEnd === undefined || value.lineEnd === null ? start : Number.isSafeInteger(value.lineEnd) && value.lineEnd > 0 ? value.lineEnd : null;
97
+ return { side, path: value.path, start: start && end ? start : null, end: start && end ? end : null };
98
+ }
99
+ const text = String(value ?? '').trim();
100
+ const side = /^(head|base):/.exec(text)?.[1], rest = side ? text.slice(side.length + 1) : text;
101
+ const match = /^([^:]+?)(?::(\d+)(?:-(\d+))?)?\s*$/.exec(rest.replace(/^(?:\.\/)+/, '').replace(/^\/+/, ''));
102
+ if (!match || /[\0\r\n]/.test(match[1])) return null;
103
+ // A bare word with neither a side, a leading slash or "./", a slash inside nor a line is no location.
104
+ if (!side && !/^(?:\.\/|\/)/.test(rest) && !match[2] && !match[1].includes('/')) return null;
105
+ const start = match[2] ? Number(match[2]) : null;
106
+ return { side: side ?? 'head', path: `/${match[1]}`, start, end: match[3] ? Number(match[3]) : start };
107
+ }
108
+
109
+ /** The file a finding's location names (`parseLocation`); null where it names none. */
110
+ export const ownFile = location => parseLocation(location)?.path ?? null;
111
+
112
+ /** A finding's place as a comment lists it: "/src/a.ts:12-14". */
113
+ export function placeOf(finding) {
114
+ const at = parseLocation(finding.location);
115
+ if (!at) return String(finding.location ?? '');
116
+ return `${at.path}${at.start ? `:${at.start}${at.end !== at.start ? `-${at.end}` : ''}` : ''}`;
56
117
  }
57
118
 
58
119
  /**
@@ -78,12 +139,43 @@ export function combinationProblems(members) {
78
139
  return { problems, lines };
79
140
  }
80
141
 
81
- // A finding ID as a text names it (F-1, Q-1001, V-2).
82
- const FINDING_ID = /(?<![A-Za-z0-9_-])[A-Za-z]+-\d+(?!\d)/g;
142
+ /**
143
+ * Why findings may not share one comment as one defect made at several places;
144
+ * [] when they may. Members are high or medium findings of one severity, each
145
+ * on lines of a HEAD file (a first line and a last one not before it), and no
146
+ * two of them share a line: findings on the same lines are not another place.
147
+ * The comment lists each other place as its finding states it, so a place
148
+ * whose text a list cannot hold unchanged (`listablePlace`) shares no comment.
149
+ * Whether the lines exist in the file is checked where its text is known
150
+ * (`evaluatePlanPage`).
151
+ */
152
+ export function repeatProblems(members) {
153
+ const problems = [];
154
+ if (new Set(members.map(member => member.severity)).size !== 1) problems.push('combined findings must have the same severity');
155
+ else if (!['high', 'medium'].includes(members[0].severity)) problems.push('only high and medium findings get inline comments');
156
+ if (members.some(member => member.inline === false)) problems.push('a combined finding has no inline location');
157
+ const at = members.map(member => parseLocation(member.location));
158
+ if (at.some(location => location?.side !== 'head' || !location.start || location.end < location.start)) {
159
+ problems.push('every combined finding must be located on lines of a HEAD file');
160
+ return { problems };
161
+ }
162
+ const unlistable = members.filter(member => !listablePlace(placeOf(member)));
163
+ if (unlistable.length) problems.push(`the file name of ${unlistable.map(member => member.id).join(', ')} cannot be written into a list of places as it is`);
164
+ for (let i = 0; i < at.length; i++) for (let j = i + 1; j < at.length; j++) {
165
+ if (at[i].path === at[j].path && at[i].start <= at[j].end && at[j].start <= at[i].end) {
166
+ problems.push(`${members[i].id} and ${members[j].id} are on the same lines, which is not another place`);
167
+ }
168
+ }
169
+ return { problems };
170
+ }
171
+
172
+ // A finding ID as a text names it (F-1, and in reviews of 0.4.x also R-2, Q-1001, V-2): not inside a name, but
173
+ // also where Markdown emphasis wraps it in underscores (_F-1_).
174
+ const FINDING_ID = /(?<![A-Za-z0-9-])(?<![A-Za-z0-9-]_+)[A-Za-z]+-\d+(?!\d)/g;
83
175
 
84
176
  /**
85
- * Other findings of this review that a skip reason names. The verifier already
86
- * merged duplicates, so another finding's comment never covers a finding.
177
+ * Other findings of this review that a skip reason names. Duplicates were
178
+ * merged before planning, so another finding's comment never covers a finding.
87
179
  */
88
180
  function citedFindings(reason, own, findingIds) {
89
181
  const named = String(reason).match(FINDING_ID) ?? [];
@@ -209,7 +301,7 @@ export function commentToken(review) {
209
301
  * they are now (`commentToken`), which a command picked from this offer hands back. Undefined for a review
210
302
  * with more findings than the panel lists: half a list would let a person replace adjustments they cannot see.
211
303
  */
212
- export function previewActions(review, { held = false } = {}) {
304
+ export function previewActions(review, { held = false, plannable = true } = {}) {
213
305
  const findings = publishableFindings(review);
214
306
  if (findings.length > ACTION_FINDINGS) return undefined;
215
307
  const { excluded, severity } = adjustmentsOf(review);
@@ -218,10 +310,11 @@ export function previewActions(review, { held = false } = {}) {
218
310
  review: review.id,
219
311
  state: commentToken(review),
220
312
  target: describeReview(review),
221
- plan: !review.plan,
313
+ // Planning and adjusting need a model of the review's mode (`plannable`); posting a saved preview needs none.
314
+ plan: !review.plan && plannable,
222
315
  publish: Boolean(review.plan) && !held && !everyFindingExcluded(review),
223
316
  posts: publicationItems(review.plan).length,
224
- adjust: !publicationStarted(review),
317
+ adjust: !publicationStarted(review) && plannable,
225
318
  findings: findings.map(finding => ({
226
319
  id: finding.id,
227
320
  severity: Object.hasOwn(severity, finding.id) ? severity[finding.id] : finding.severity,
@@ -247,10 +340,14 @@ export function resolveAdjustments(review, { exclude, severity, reset = false })
247
340
  const findings = publishableFindings(review);
248
341
  const byId = new Map(findings.map(finding => [finding.id, finding]));
249
342
  const problems = [];
343
+ const rows = review.final?.dispositions ?? [];
250
344
  const check = id => {
251
345
  if (byId.has(id)) return;
252
- const row = (review.final?.dispositions ?? []).find(item => item.id === id);
253
- problems.push(row?.status === 'MERGED' && row.mergedInto ? `${id} was merged into ${row.mergedInto}; adjust ${row.mergedInto} instead`
346
+ const row = rows.find(item => item.id === id);
347
+ // A merged finding names the finding that stands for it, through every link of a chain (0.4.x saved some).
348
+ let target = row?.status === 'MERGED' ? row.mergedInto : undefined;
349
+ for (const seen = new Set([id]); target && !byId.has(target) && !seen.has(target);) { seen.add(target); target = rows.find(item => item.id === target)?.mergedInto; }
350
+ problems.push(row?.status === 'MERGED' && byId.has(target) ? `${id} was merged into ${target}; adjust ${target} instead`
254
351
  : row ? `${id} is ${row.status}, not a finding this review can publish` : `${id} is not a finding of review ${review.id}`);
255
352
  };
256
353
  for (const id of [...(exclude ?? []), ...Object.keys(severity ?? {})]) check(id);
@@ -344,8 +441,23 @@ export function describeEarlierText(review, otherComments = 0) {
344
441
  * change. Only IDs written as the runtime writes them are found. Returns
345
442
  * readable rows; [] when nothing names an excluded finding.
346
443
  */
347
- export function excludedReferences(review) {
444
+ /**
445
+ * The findings a person excluded, and those merged into one of them: a text that names a merged finding names
446
+ * the finding that stands for it.
447
+ */
448
+ function excludedIds(review) {
348
449
  const excluded = new Set(adjustmentsOf(review).excluded);
450
+ // Through every link of a chain (a review of 0.4.x may hold F-1 -> F-2 -> R-1), in whatever order the rows are.
451
+ const merged = (review?.final?.dispositions ?? []).filter(row => row?.status === 'MERGED');
452
+ for (let grown = true; grown;) {
453
+ grown = false;
454
+ for (const row of merged) if (excluded.has(row.mergedInto) && !excluded.has(row.id)) { excluded.add(row.id); grown = true; }
455
+ }
456
+ return excluded;
457
+ }
458
+
459
+ export function excludedReferences(review) {
460
+ const excluded = excludedIds(review);
349
461
  if (!excluded.size || !review?.plan) return [];
350
462
  const rows = [];
351
463
  for (const item of publicationItems(review.plan)) {
@@ -603,6 +715,52 @@ export function inlineMarker(target, comment, ordinal = 0) {
603
715
  return markerTag(hash([targetKey(target), 'inline', comment.path, normalizedAnchor(comment.anchor), ordinal]));
604
716
  }
605
717
 
718
+ /**
719
+ * The fingerprint of a comment that stands for one defect at several places:
720
+ * PR + path + normalized anchor + the other places it lists. Such a comment
721
+ * is a comment of its own: publication skips it only when this marker is on
722
+ * the PR, so the comment found there is this very comment, with every place,
723
+ * and nothing has to be read out of a posted text to know what it covers.
724
+ * The ordinal tells apart two comments with the same quoted lines and the
725
+ * same other places, which two defects at the same places would have.
726
+ */
727
+ export function sharedMarker(target, comment, ordinal = 0) {
728
+ return markerTag(hash([targetKey(target), 'shared', comment.path, normalizedAnchor(comment.anchor), comment.otherPlaces.map(other => other.place).sort(), ordinal]));
729
+ }
730
+
731
+ /**
732
+ * The second marker of a comment for several places: PR + path + normalized
733
+ * anchor, nothing else. It says that such a comment stands on these quoted
734
+ * lines, whatever it lists and whichever plan wrote it. Only planning reads
735
+ * it, to keep another comment off those lines (`occupiedLines`); publication,
736
+ * its ledger and its attempt records know a comment by its own marker alone.
737
+ */
738
+ export function linesMarker(target, comment) {
739
+ return markerTag(hash([targetKey(target), 'lines', comment.path, normalizedAnchor(comment.anchor)]));
740
+ }
741
+
742
+ /** How many comments on the same quoted lines the planning rule looks for on the PR (their markers count from 0). */
743
+ const SAME_LINES = 8;
744
+
745
+ /**
746
+ * Why a planned comment may not stand on its quoted lines, given the markers
747
+ * the PR already has (`posted`, marker to thread): a comment for several
748
+ * places and a comment for one place do not find each other by marker, so
749
+ * one of them would be posted next to the other. A comment for several
750
+ * places stays off lines that carry any comment of AZPR's, unless the PR has
751
+ * this very comment; a comment for one place (or for findings on the same
752
+ * lines) stays off lines that carry a comment for several places, unless the
753
+ * PR has a comment of its own kind there, which it then finds by marker as
754
+ * always. Nothing here depends on other comments of the plan. '' when it may.
755
+ */
756
+ function occupiedLines(target, comment, posted) {
757
+ const first = make => Array.from({ length: SAME_LINES }, (_, ordinal) => posted.get(make(ordinal))).find(thread => thread !== undefined);
758
+ const single = first(ordinal => inlineMarker(target, comment, ordinal)), several = posted.get(linesMarker(target, comment));
759
+ const says = thread => `the PR already has a comment of AZPR's on these quoted lines${thread ? ` (thread ${thread})` : ''}, and a second one is not put on them`;
760
+ if (comment.otherPlaces) return (single ?? several) !== undefined && first(ordinal => sharedMarker(target, comment, ordinal)) === undefined ? says(single ?? several) : '';
761
+ return several !== undefined && single === undefined ? says(several) : '';
762
+ }
763
+
606
764
  /** One summary per reviewed source commit and set of inline comments. */
607
765
  export function summaryMarker(target, head, inlineMarkers) {
608
766
  return markerTag(hash([targetKey(target), 'summary', head, [...inlineMarkers].sort()]));
@@ -629,7 +787,10 @@ export function restoreAnchor(comment, review) {
629
787
  });
630
788
  const declared = new Map();
631
789
  for (const observation of observations) {
790
+ // Split only as far as the range needs; the empty element after a final line break is no line of the file,
791
+ // as in the search below.
632
792
  const lines = observation.output.split(/\r?\n/, comment.endLine + 1);
793
+ if (lines.at(-1) === '' && lines.length <= comment.endLine) lines.pop();
633
794
  const selected = lines.slice(comment.startLine - 1, comment.endLine), anchor = selected.join('\n');
634
795
  if (selected.length === count && forms.has(trim(anchor))) declared.set(JSON.stringify([anchor]), { anchor, startLine: comment.startLine, endLine: comment.endLine });
635
796
  }
@@ -650,6 +811,119 @@ export function restoreAnchor(comment, review) {
650
811
  : { anchor: comment.anchor, startLine: comment.startLine, endLine: comment.endLine, found: false };
651
812
  }
652
813
 
814
+ // What decides where a block of Markdown begins and ends, as CommonMark reads lines (tabs made spaces first).
815
+ // A line ends at a line feed or a carriage return only, so the rest of one may hold any other character (the s flag).
816
+ const FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/s;
817
+ const fenceStart = line => {
818
+ const found = FENCE_LINE.exec(line);
819
+ return found && (found[1][0] === '~' || !found[2].includes('`')) ? { mark: found[1][0], length: found[1].length } : null;
820
+ };
821
+ const fenceEnd = (fence, line) => {
822
+ const found = FENCE_LINE.exec(line);
823
+ return Boolean(found) && found[1][0] === fence.mark && found[1].length >= fence.length && /^ *$/.test(found[2]);
824
+ };
825
+ const QUOTE_MARK = /^ {0,3}> ?/;
826
+ const LIST_ITEM = /^( {0,3}(?:[-*+]|(\d{1,9})[.)]))(?:( +)(.*))?$/s;
827
+ const THEMATIC_BREAK = /^ {0,3}([-*_])(?: *\1){2,} *$/;
828
+ const HEADING = /^ {0,3}#{1,6}(?: |$)/;
829
+ const UNDERLINE = /^ {0,3}(?:=+|-+) *$/;
830
+ // Raw HTML that ends only where a line says so, not at a blank line (CommonMark's HTML blocks 1 and 3 to 5; the
831
+ // start of an HTML comment is escaped in a body): how a line starts it, what a line holds that ends it, its name.
832
+ const LASTING_HTML = [
833
+ [/^ {0,3}<(pre|script|style|textarea)(?=[\s>]|$)/i, /<\/(?:pre|script|style|textarea)>/i, found => `a <${found[1].toLowerCase()}> block`],
834
+ [/^ {0,3}<\?/, /\?>/, () => 'a <?…?> block'],
835
+ [/^ {0,3}<!\[CDATA\[/, /\]\]>/, () => 'a CDATA section'],
836
+ [/^ {0,3}<![a-z]/i, />/, () => 'a <!…> declaration'],
837
+ ];
838
+ // Raw HTML that ends at a blank line: a line that begins with one of these tags (HTML block 6), or one that is
839
+ // a whole tag and nothing else, which no paragraph continues into (7). The whole tag is taken as commonmark.js
840
+ // and markdown-it take it: of any name (`<pre/>` too, which starts no block of the first kind) and followed by
841
+ // any white space.
842
+ const BLOCK_TAG = /^ {0,3}<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i;
843
+ const TAG_LINE = /^ {0,3}(?:<[a-z][a-z0-9-]*(?:\s+[a-z_:][a-z0-9:._-]*(?:\s*=\s*(?:[^"'=<>`\x00-\x20]+|'[^']*'|"[^"]*"))?)*\s*\/?>|<\/[a-z][a-z0-9-]*\s*>)\s*$/i;
844
+
845
+ /**
846
+ * The block a body leaves open for what follows it after a blank line, named
847
+ * for a correction; '' when it leaves none. As CommonMark reads blocks, only
848
+ * two kinds go on over a blank line at the top level: a fenced code block
849
+ * without its closing fence, and raw HTML that waits for its own end
850
+ * (LASTING_HTML). Inside a quote or a list item both end with it, and
851
+ * unindented text after a blank line ends every quote and list.
852
+ *
853
+ * So the lines are read for where the top level is. A quote is known by its
854
+ * mark and a list item by its marker and the indentation of its content, the
855
+ * outermost one only: what is nested in it is read as its text. Its lines,
856
+ * and those of the top level, are read alike for code fences, raw HTML and
857
+ * paragraphs, since a line without the mark or the indentation still
858
+ * continues a paragraph, and a paragraph is interrupted by some list items
859
+ * only. This is a reading of lines, not a Markdown parser, and it decides
860
+ * only whether a body is sent back for correction.
861
+ */
862
+ function openBlock(text) {
863
+ // Lines that hold no quote or list item of their own: the top level, or the content of the one the lines
864
+ // are in. open: code or raw HTML that waits for its end. raw: raw HTML that ends at a blank line.
865
+ // paragraph: the last line was a paragraph's.
866
+ const run = () => ({ open: null, raw: false, paragraph: false });
867
+ const top = run();
868
+ let within = null;
869
+ const read = (state, line) => {
870
+ if (state.open) {
871
+ if (state.open.ends(line)) state.open = null;
872
+ return;
873
+ }
874
+ const indent = /^ */.exec(line)[0].length;
875
+ if (indent === line.length) state.raw = state.paragraph = false;
876
+ // Raw HTML takes every line up to a blank one; four spaces or more are code, or a paragraph's next line.
877
+ if (indent === line.length || state.raw || indent > 3) return;
878
+ const fence = fenceStart(line), html = fence ? undefined : LASTING_HTML.find(([start]) => start.test(line));
879
+ if (fence) state.open = { ends: next => fenceEnd(fence, next), name: 'a code fence' };
880
+ else if (html && !html[1].test(line)) state.open = { ends: next => html[1].test(next), name: html[2](html[0].exec(line)) };
881
+ else if (!html) state.raw = BLOCK_TAG.test(line) || (!state.paragraph && TAG_LINE.test(line));
882
+ // Under a paragraph, a line of = or - makes it a heading; what starts no block is a paragraph's line.
883
+ state.paragraph = !(fence || html || state.raw || THEMATIC_BREAK.test(line) || HEADING.test(line) || (state.paragraph && UNDERLINE.test(line)));
884
+ };
885
+ // Whether a line starts a block wherever it stands, so that it never continues the paragraph of a quote or a list item above it.
886
+ const starts = line => Boolean(fenceStart(line)) || QUOTE_MARK.test(line) || Boolean(LIST_ITEM.exec(line)) || THEMATIC_BREAK.test(line) || HEADING.test(line)
887
+ || LASTING_HTML.some(([start]) => start.test(line)) || BLOCK_TAG.test(line);
888
+ for (const written of String(text).replace(/\r\n?/g, '\n').split('\n')) {
889
+ // A tab reaches the next column that is a multiple of four.
890
+ let line = '', column = 0;
891
+ for (const char of written) {
892
+ const width = char === '\t' ? 4 - column % 4 : 1;
893
+ line += char === '\t' ? ' '.repeat(width) : char;
894
+ column += width;
895
+ }
896
+ const indent = /^ */.exec(line)[0].length, blank = indent === line.length;
897
+ if (within) {
898
+ // A list item that began with nothing ends at a blank line; any other goes on over it.
899
+ const empty = within.empty;
900
+ within.empty = false;
901
+ if (within.quote ? QUOTE_MARK.test(line) : blank ? !empty : indent >= within.offset) {
902
+ read(within.content, within.quote ? line.replace(QUOTE_MARK, '') : line.slice(within.offset));
903
+ continue;
904
+ }
905
+ if (!blank && within.content.paragraph && !starts(line)) continue;
906
+ within = null;
907
+ }
908
+ if (!top.open && !top.raw && !blank && indent <= 3) {
909
+ const item = (top.paragraph && UNDERLINE.test(line)) || THEMATIC_BREAK.test(line) ? null : LIST_ITEM.exec(line), worded = /[^ ]/.test(item?.[4] ?? '');
910
+ if (line[indent] === '>') within = { quote: true, content: run() };
911
+ // A paragraph is interrupted only by an item with text, and by a numbered one only when it starts at 1.
912
+ else if (item && (!top.paragraph || (worded && (item[2] === undefined || Number(item[2]) === 1)))) {
913
+ // The content's column: after the marker and its spaces, or one space after it where code or nothing follows.
914
+ within = { offset: item[1].length + (worded && item[3].length <= 4 ? item[3].length : 1), empty: !worded, content: run() };
915
+ }
916
+ if (within) {
917
+ top.paragraph = false;
918
+ read(within.content, within.quote ? line.replace(QUOTE_MARK, '') : line.slice(within.offset));
919
+ continue;
920
+ }
921
+ }
922
+ read(top, line);
923
+ }
924
+ return top.open?.name ?? '';
925
+ }
926
+
653
927
  /** Strip any severity label the model wrote, then apply the canonical one. */
654
928
  export function normalizeTitle(body, severity) {
655
929
  const trimmed = body.trim();
@@ -671,13 +945,21 @@ const aliases = (value, names) => {
671
945
  * @returns {{result: object, issues: string[], corrections: object[]}}
672
946
  * With `final`, every remaining problem becomes a local skip instead of an issue.
673
947
  * `candidates` lists the groups of a quick review whose findings one comment
674
- * may combine (`findingIds`); the runtime never combines findings itself.
948
+ * may combine (`findingIds`): one defect reported twice on the same lines.
949
+ * `repeats` lists the groups, of any review, whose findings may be one defect
950
+ * made at several places; a comment that combines some of them stands at one
951
+ * place and carries the others as `otherPlaces`, which the runtime renders.
952
+ * The runtime never combines findings itself.
675
953
  * `sources` are the page's source excerpts and `discussions` the live threads
676
954
  * the runtime read (null when it could not): skip causes are checked against them.
955
+ * `posted` maps the markers the PR already has to their threads
956
+ * (`markersInThreads`; null when the threads could not be read): a comment
957
+ * for several places and a comment for one place are not put on the same
958
+ * quoted lines (`occupiedLines`).
677
959
  * With `allowSummary: false` a summary note is dropped, never repaired: only
678
960
  * the page the runtime chose writes it.
679
961
  */
680
- export function evaluatePlanPage(answerText, { review, assigned, final = false, candidates = [], sources = [], discussions = null, allowSummary = true }) {
962
+ export function evaluatePlanPage(answerText, { review, assigned, final = false, candidates = [], repeats = [], sources = [], discussions = null, posted = null, allowSummary = true }) {
681
963
  const corrections = [], issues = [];
682
964
  const parsed = parseModelJSON(answerText, { keys: ['status', 'comments', 'skipped'] });
683
965
  if (!parsed.value) {
@@ -703,12 +985,12 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
703
985
  status = 'READY';
704
986
  }
705
987
  const eligible = new Map(assigned.map(finding => [finding.id, finding]));
706
- // Findings a person excluded after a preview: no published text may name them.
707
- const excluded = new Set(adjustmentsOf(review).excluded);
988
+ // Findings a person excluded after a preview, and those merged into them: no published text may name them.
989
+ const excluded = excludedIds(review);
708
990
  const changed = new Set(review.snapshot.files.map(path => path.startsWith('/') ? path : '/' + path));
709
- // Quick findings were not independently verified: an inline comment needs a
710
- // checked location and an anchor found in source text the runtime read.
711
- const quick = reviewVerification(review) === 'none';
991
+ // Findings that nothing verified after their reviewer (every review of this pipeline, and a quick review of
992
+ // 0.4.x): an inline comment needs a checked location and an anchor found in source text the runtime read.
993
+ const unverified = reviewVerification(review) === 'none';
712
994
  const comments = [], skipped = [], handled = new Set(), reported = new Set(), refusedCombinations = [];
713
995
  const skip = (findingId, reason, extra = {}) => { if (!handled.has(findingId)) { handled.add(findingId); skipped.push({ findingId, reason, ...extra }); } };
714
996
  // A location that can carry an inline comment: on a changed HEAD file whose text the page shows.
@@ -720,13 +1002,16 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
720
1002
  // Body, path and anchor of one inline comment; `lines` bounds the anchor of a combined comment.
721
1003
  function draft(c, label, severity, lines) {
722
1004
  const problems = [];
723
- if (String(c.severity ?? '').toLowerCase() !== severity) corrections.push({ action: 'use-verified-severity', findingId: label });
1005
+ if (String(c.severity ?? '').toLowerCase() !== severity) corrections.push({ action: 'use-review-severity', findingId: label });
724
1006
  const body = nonempty(c.body) ? escapeComments(normalizeTitle(c.body, severity)) : '';
725
1007
  if (!body) problems.push('body is empty');
726
1008
  else if (body.length > INLINE_SOFT_LIMIT && !final) problems.push(`body is ${body.length} characters; keep it within ${INLINE_SOFT_LIMIT}`);
727
1009
  else if (body.length > INLINE_HARD_LIMIT) problems.push(`body exceeds ${INLINE_HARD_LIMIT} characters`);
728
1010
  const named = namedExcluded(body, excluded);
729
1011
  if (named.length) problems.push(`body names ${named.join(', ')}, which a person excluded from publication; leave ${named.length === 1 ? 'it' : 'them'} out`);
1012
+ // The list of other places is the runtime's: its heading appears nowhere in a body, however it is
1013
+ // indented, quoted or continued, so that no text a planner wrote reads like the runtime's list.
1014
+ if (OTHER_PLACES_HEADINGS.some(heading => body.includes(heading))) problems.push('body holds the heading of the list of other places, which only the runtime writes; leave that list out');
730
1015
  const path = nonempty(c.path) ? (c.path.startsWith('/') ? c.path : '/' + c.path) : '';
731
1016
  if (!changed.has(path) || /[\r\n\0]/.test(path)) problems.push(`path ${JSON.stringify(c.path ?? '')} is not a changed file of this PR`);
732
1017
  else if (lines && path !== lines.path) problems.push(`path must be ${lines.path}, where the combined findings are`);
@@ -746,34 +1031,78 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
746
1031
  restored = restoreAnchor({ path, startLine, endLine, anchor }, review);
747
1032
  if (restored.startLine !== startLine) corrections.push({ action: 'restore-anchor-location', findingId: label, from: startLine, to: restored.startLine });
748
1033
  if (restored.ambiguous && !final) problems.push('the anchor text appears several times in the observed source; quote more lines to make it unique');
749
- else if (quick && !restored.found) problems.push('the anchor text was not found in the HEAD source; quote the exact lines from sourceExcerpts');
1034
+ else if (unverified && !restored.found) problems.push('the anchor text was not found in the HEAD source; quote the exact lines from sourceExcerpts');
750
1035
  else if (lines && (restored.startLine < lines.start || restored.endLine > lines.end)) problems.push(`the anchor must lie within lines ${lines.start}-${lines.end}, which every combined finding covers`);
751
1036
  }
752
1037
  if (problems.length) return { problems };
753
1038
  if (body.length > INLINE_SOFT_LIMIT) corrections.push({ action: 'accept-long-body', findingId: label, characters: body.length });
754
- return { problems, comment: { severity, path, startLine: restored.startLine, endLine: restored.endLine, anchor: restored.anchor, body } };
1039
+ return { problems, found: restored.found, comment: { severity, path, startLine: restored.startLine, endLine: restored.endLine, anchor: restored.anchor, body } };
755
1040
  }
756
- // One comment for findings of a listed candidate group. The planner decides
757
- // whether they state one defect; the runtime checks only the group rules.
1041
+ // One comment for findings of a listed group: one defect reported twice on
1042
+ // the same lines (`candidates`, quick reviews) or made at several places
1043
+ // (`repeats`). The planner decides whether they state one defect; the runtime
1044
+ // checks only the group rules.
758
1045
  function combine(c, ids) {
759
1046
  const label = ids.join('+');
760
1047
  const members = ids.map(id => eligible.get(id));
761
1048
  const problems = [];
1049
+ const listed = group => ids.every(id => group.includes(id));
1050
+ const twice = unverified && candidates.some(listed), repeated = !twice && repeats.some(listed);
762
1051
  let lines;
763
- if (!quick || !candidates.length) problems.push('findingIds may combine only the findings of a listed mergeCandidates group');
1052
+ if (!(unverified && candidates.length) && !repeats.length) problems.push('findingIds may combine only the findings of one listed group (mergeCandidates or repeatCandidates)');
764
1053
  else if (members.some(member => !member)) problems.push(`${ids.filter(id => !eligible.has(id)).join(', ')} not assigned to this page`);
765
- else if (!candidates.some(group => ids.every(id => group.includes(id)))) problems.push('the findings are not all in one mergeCandidates group');
1054
+ else if (!twice && !repeated) problems.push('the findings are not all in one listed group (mergeCandidates or repeatCandidates)');
766
1055
  else if (members.some(member => handled.has(member.id))) problems.push('a combined finding already has a comment or skip');
767
1056
  else {
768
- const checked = combinationProblems(members);
1057
+ const checked = twice ? combinationProblems(members) : repeatProblems(members);
769
1058
  problems.push(...checked.problems);
770
1059
  lines = checked.lines;
1060
+ // Every place a comment lists is a place of this PR's changes as it is at HEAD: a changed
1061
+ // file whose text the runtime read for this page, and lines that file has.
1062
+ const absent = twice ? [] : members.filter(member => {
1063
+ const at = parseLocation(member.location);
1064
+ const read = sources.find(item => item.path === at?.path);
1065
+ return !at || !changed.has(at.path) || !read || !(at.end <= (read.totalLines ?? read.lastLine));
1066
+ });
1067
+ if (absent.length) problems.push(`${absent.map(member => `${member.id} (${placeOf(member)})`).join(', ')} ${absent.length === 1 ? 'is' : 'are'} not on lines of a changed file as the runtime read it at HEAD`);
771
1068
  if (!nonempty(c.mergeReason)) problems.push('a combined comment needs a mergeReason');
772
1069
  }
773
- let drafted;
1070
+ let drafted, first;
774
1071
  if (!problems.length) {
775
1072
  drafted = draft(c, label, members[0].severity, lines);
776
1073
  problems.push(...drafted.problems);
1074
+ // Where the comment stands follows from the lines it quotes, so they must be lines the file has:
1075
+ // the quote is found in the HEAD text, also for a review whose single comments need not be, and
1076
+ // ends within the file (where the file's line count is known, it is checked below as well).
1077
+ if (!problems.length && repeated && !drafted.found) problems.push('the anchor text was not found in the HEAD source; quote the exact lines from sourceExcerpts');
1078
+ // (An anchor in a file that holds none of the findings is refused below, where the place is looked for.)
1079
+ // The list follows the body: a block the body leaves open would take it in.
1080
+ const left = !problems.length && repeated ? openBlock(drafted.comment.body) : '';
1081
+ if (left) problems.push(`body leaves ${left} open, which would take the list of other places into it; close it`);
1082
+ const lineCount = (read => read && (read.totalLines ?? read.lastLine))(repeated && drafted.comment && sources.find(item => item.path === drafted.comment.path));
1083
+ if (!problems.length && lineCount && drafted.comment.endLine > lineCount) {
1084
+ problems.push(`the anchor (lines ${drafted.comment.startLine}-${drafted.comment.endLine}) reaches past the end of ${drafted.comment.path}, which has ${lineCount} line(s); quote lines the file has`);
1085
+ }
1086
+ }
1087
+ if (!problems.length && repeated) {
1088
+ // The comment stands at one of the places: the one finding whose lines its anchor touches.
1089
+ // Members never share a line, but quoted lines can reach from one into the next: such an
1090
+ // anchor names no place, and the runtime does not choose one.
1091
+ const { path, startLine, endLine } = drafted.comment;
1092
+ const touched = members.filter(member => (at => at.path === path && startLine <= at.end && endLine >= at.start)(parseLocation(member.location)));
1093
+ if (touched.length === 1) [first] = touched;
1094
+ else if (!touched.length) problems.push(`the anchor must lie on the lines of one of the combined findings (${members.map(member => `${member.id} at ${placeOf(member)}`).join(', ')})`);
1095
+ else problems.push(`the anchor (lines ${startLine}-${endLine}) touches the lines of ${touched.map(member => `${member.id} at ${placeOf(member)}`).join(' and ')}; quote lines of one of them only`);
1096
+ }
1097
+ if (!problems.length && posted) {
1098
+ // Comments for one place and comments for several do not find each other by marker: neither is put
1099
+ // on quoted lines that carry the other kind (`occupiedLines`).
1100
+ const others = repeated ? members.filter(member => member !== first).map(member => ({ place: placeOf(member) })) : undefined;
1101
+ const taken = occupiedLines(review.target, { ...drafted.comment, ...(others ? { otherPlaces: others } : {}) }, posted);
1102
+ if (taken) {
1103
+ problems.push(repeated ? `${taken}. Anchor this comment on the lines of another of its findings, or leave ${first.id} out of it; a finding that an existing thread covers is skipped with cause existing-thread`
1104
+ : `${taken}. Skip these findings with cause existing-thread when that thread covers them, or quote other lines`);
1105
+ }
777
1106
  }
778
1107
  if (problems.length) {
779
1108
  if (!final) {
@@ -788,7 +1117,13 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
788
1117
  return;
789
1118
  }
790
1119
  for (const id of ids) handled.add(id);
791
- comments.push({ findingId: ids[0], findingIds: ids, ...drafted.comment, mergeReason: c.mergeReason.trim() });
1120
+ if (!repeated) { comments.push({ findingId: ids[0], findingIds: ids, ...drafted.comment, mergeReason: c.mergeReason.trim() }); return; }
1121
+ // The place of the comment first, the others in the order of the page; their
1122
+ // locations are the findings' own, never text the planner wrote.
1123
+ const position = new Map(assigned.map((finding, index) => [finding.id, index]));
1124
+ const others = members.filter(member => member !== first).sort((a, b) => position.get(a.id) - position.get(b.id));
1125
+ comments.push({ findingId: first.id, findingIds: [first.id, ...others.map(member => member.id)], ...drafted.comment, mergeReason: c.mergeReason.trim(),
1126
+ otherPlaces: others.map(member => ({ findingId: member.id, place: placeOf(member) })) });
792
1127
  }
793
1128
  for (const [index, raw] of (Array.isArray(value.comments) ? value.comments : []).entries()) {
794
1129
  if (!isObject(raw)) { corrections.push({ action: 'drop-non-object-comment', index }); continue; }
@@ -806,6 +1141,14 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
806
1141
  continue;
807
1142
  }
808
1143
  const { problems, comment } = draft(c, finding.id, finding.severity);
1144
+ // A comment for one finding stands in that finding's own file (`ownFile`): an excerpt of another file is
1145
+ // another place. A location that names no file keeps the finding in the summary index.
1146
+ const own = ownFile(finding.location);
1147
+ if (!own) problems.push(`${finding.id}'s location names no file of its own to comment on`);
1148
+ else if (comment?.path && comment.path !== own) problems.push(`path ${comment.path} is not ${finding.id}'s own file ${own}; quote lines of that file`);
1149
+ // A comment for one place is not put on quoted lines that carry a comment for several places.
1150
+ const taken = !problems.length && posted ? occupiedLines(review.target, comment, posted) : '';
1151
+ if (taken) problems.push(`${taken}. Skip ${finding.id} with cause existing-thread when that thread covers it, or quote other lines`);
809
1152
  if (problems.length) {
810
1153
  if (!final) { issues.push(`comment for ${finding.id}: ${problems.join('; ')}.`); reported.add(finding.id); continue; }
811
1154
  skip(finding.id, `No inline comment: ${problems.join('; ')}. The finding remains in the summary index.`);
@@ -822,9 +1165,11 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
822
1165
  const reason = nonempty(s.reason) ? s.reason.trim() : 'Skipped by the comment planner without a stated reason.';
823
1166
  const cited = citedFindings(reason, s.findingId, findingIds);
824
1167
  if (cited.length && !final) {
825
- issues.push(quick
826
- ? `skip for ${s.findingId} relies on ${cited.join(', ')}: another finding's comment does not cover it. Comment on ${s.findingId} at the lines of its own claim, combine it with findingIds only when a listed mergeCandidates group holds both and they state one defect, or skip it only when it cannot be anchored, cannot be stated faithfully within the limit, or an existing PR thread already covers it (name the thread, not a finding).`
827
- : `skip for ${s.findingId} relies on ${cited.join(', ')}: findings of this review are separate issues (the verifier already merged duplicates), so another finding's comment does not cover it. Comment on ${s.findingId} at the lines of its own claim, or skip it only when it cannot be anchored, cannot be stated faithfully within the limit, or an existing PR thread already covers it (name the thread, not a finding).`);
1168
+ // Only a quick review of 0.4.x reaches planning with repeated reports unmerged; every other review had its
1169
+ // duplicates merged first, by the duplicate check or by its verifier.
1170
+ issues.push(reviewMethod(review) === 'quick'
1171
+ ? `skip for ${s.findingId} relies on ${cited.join(', ')}: another finding's comment does not cover it. Comment on ${s.findingId} at the lines of its own claim, combine it with findingIds only when a listed mergeCandidates or repeatCandidates group holds both and they state one defect, or skip it only when it cannot be anchored, cannot be stated faithfully within the limit, or an existing PR thread already covers it (name the thread, not a finding).`
1172
+ : `skip for ${s.findingId} relies on ${cited.join(', ')}: findings of this review are separate issues (duplicates were merged before planning), so another finding's comment does not cover it. Comment on ${s.findingId} at the lines of its own claim, give one comment findingIds with both only when a listed repeatCandidates group holds them and they are one defect made at several places, or skip it only when it cannot be anchored, cannot be stated faithfully within the limit, or an existing PR thread already covers it (name the thread, not a finding).`);
828
1173
  reported.add(s.findingId);
829
1174
  continue;
830
1175
  }
@@ -875,6 +1220,74 @@ export function planRepairPrompt(issues, { parseOnly = false } = {}) {
875
1220
  return `AZPR runtime: this comment plan page needs correction before it can be saved.\n${listed}\n\nReturn the complete corrected JSON object for this page (status, comments, skipped, optional summary and summaryDetails). Keep valid comments unchanged.`;
876
1221
  }
877
1222
 
1223
+ /**
1224
+ * Validate the grouping pass: which findings may be one defect made at several
1225
+ * places. Only a proposal: each planning page still decides whether a group
1226
+ * gets one comment, and the runtime checks that comment's rules. A group holds
1227
+ * two or more of `findings` (the high and medium ones on lines of a HEAD file)
1228
+ * under `repeatProblems`, and a finding belongs to at most one group. With
1229
+ * `final`, a group that breaks a rule is dropped instead of reported.
1230
+ * @returns {{result: {status: string, groups: string[][]}|null, issues: string[], corrections: object[]}}
1231
+ */
1232
+ export function evaluateGrouping(answerText, { findings, final = false }) {
1233
+ const corrections = [], issues = [];
1234
+ const parsed = parseModelJSON(answerText, { keys: ['status', 'groups'] });
1235
+ if (!parsed.value) {
1236
+ if (!final) return { result: null, issues: [`Your answer could not be used: ${parsed.problem}.`], corrections };
1237
+ return { result: { status: 'READY', groups: [] }, issues: [], corrections: [{ action: 'no-usable-grouping' }] };
1238
+ }
1239
+ if (parsed.corrections) corrections.push(...parsed.corrections);
1240
+ const value = aliases(parsed.value, ['status', 'groups']);
1241
+ // The pass has one answer and no continuation: any other status is an answer that stopped early,
1242
+ // which a correction turn may finish. After the repairs the groups it did name are kept, since each
1243
+ // is only a proposal that meets the rules.
1244
+ // A missing status is no READY either: an answer may name unfinished work without one.
1245
+ const status = String(value.status ?? '').trim().toUpperCase();
1246
+ if (status !== 'READY') {
1247
+ if (final) corrections.push({ action: 'accept-grouping-without-ready', status: status.slice(0, 40) });
1248
+ else issues.push('status must be READY: this pass has no continuation. Name the groups you are sure of and return READY; use [] when nothing repeats.');
1249
+ }
1250
+ const order = new Map(findings.map((finding, index) => [finding.id, index]));
1251
+ const byId = new Map(findings.map(finding => [finding.id, finding]));
1252
+ const taken = new Set(), groups = [];
1253
+ const refuse = (ids, problem) => {
1254
+ if (final) corrections.push({ action: 'drop-invalid-group', findingIds: ids, problem });
1255
+ else issues.push(`group ${ids.join(', ')}: ${problem}. Correct it or leave it out.`);
1256
+ };
1257
+ // An answer without `groups` (a page's answer, say) is no grouping: it gets its correction turn like any other.
1258
+ if (!Array.isArray(value.groups) && !final) issues.push(value.groups === undefined ? 'groups is missing: answer with {"status": "READY", "groups": [...]}, and "groups": [] when nothing repeats.'
1259
+ : 'groups must be an array of {"findingIds": [...], "reason": "..."}; use [] when nothing repeats.');
1260
+ for (const [index, raw] of (Array.isArray(value.groups) ? value.groups : []).entries()) {
1261
+ const group = Array.isArray(raw) ? { findingIds: raw } : isObject(raw) ? aliases(raw, ['findingIds', 'reason']) : {};
1262
+ // An entry that is no group at all (its findings are not a list) is a mistake to correct; a list of fewer
1263
+ // than two findings is a group of nothing, and nothing to correct.
1264
+ if (!Array.isArray(group.findingIds)) {
1265
+ if (final) corrections.push({ action: 'drop-malformed-group', index });
1266
+ else issues.push(`group ${index + 1}: findingIds must be an array of finding IDs, as in {"findingIds": ["F-2", "F-5"], "reason": "..."}.`);
1267
+ continue;
1268
+ }
1269
+ const ids = [...new Set(group.findingIds.map(id => String(id)))];
1270
+ if (ids.length < 2) { corrections.push({ action: 'drop-group-without-two-findings', index }); continue; }
1271
+ const unknown = ids.filter(id => !byId.has(id));
1272
+ if (unknown.length) { refuse(ids, `${unknown.join(', ')} ${unknown.length === 1 ? 'is' : 'are'} not in findings`); continue; }
1273
+ const again = ids.filter(id => taken.has(id));
1274
+ if (again.length) { refuse(ids, `${again.join(', ')} already ${again.length === 1 ? 'belongs' : 'belong'} to another group`); continue; }
1275
+ const { problems } = repeatProblems(ids.map(id => byId.get(id)));
1276
+ if (problems.length) { refuse(ids, problems.join('; ')); continue; }
1277
+ for (const id of ids) taken.add(id);
1278
+ // In the order of the findings, so that pages and their comments do not depend on how the answer listed them.
1279
+ groups.push(ids.sort((a, b) => order.get(a) - order.get(b)));
1280
+ }
1281
+ groups.sort((a, b) => order.get(a[0]) - order.get(b[0]));
1282
+ return { result: { status: 'READY', groups }, issues, corrections };
1283
+ }
1284
+
1285
+ export function groupingRepairPrompt(issues, { parseOnly = false } = {}) {
1286
+ if (parseOnly) return parseRepairPrompt(issues);
1287
+ const listed = issues.slice(0, 25).map(issue => `- ${issue}`).join('\n');
1288
+ return `AZPR runtime: this grouping needs correction before it can be used.\n${listed}\n\nReturn the complete corrected JSON object (status, groups). When unsure whether findings are one defect, leave them out of every group.`;
1289
+ }
1290
+
878
1291
  function summaryComment(review, note, details, inlineMarkers, groups = []) {
879
1292
  const chinese = /^zh(?:-|$)/i.test(review.outputLanguage ?? '');
880
1293
  const traditional = chinese && new Intl.Locale(review.outputLanguage).maximize().script === 'Hant';
@@ -892,19 +1305,35 @@ function summaryComment(review, note, details, inlineMarkers, groups = []) {
892
1305
  /** Assemble validated pages into one saved plan with markers and exact content. */
893
1306
  export function assemblePlan(review, pages) {
894
1307
  const ordinals = new Map();
1308
+ // Comments that are alike in what their marker is made of are told apart by their order in the plan.
1309
+ const ordinalOf = (...key) => {
1310
+ const name = JSON.stringify(key), ordinal = ordinals.get(name) ?? 0;
1311
+ ordinals.set(name, ordinal + 1);
1312
+ return ordinal;
1313
+ };
895
1314
  const comments = pages.flatMap(page => page.comments).map(c => {
896
- const key = `${c.path}\n${normalizedAnchor(c.anchor)}`;
897
- const ordinal = ordinals.get(key) ?? 0;
898
- ordinals.set(key, ordinal + 1);
899
- const marker = inlineMarker(review.target, c, ordinal);
900
1315
  // Azure positions are one-based UTF-16 offsets within their lines.
901
1316
  const endOffset = Math.max(1, c.anchor.split('\n').at(-1).length);
902
- return { ...c, kind: 'inline', startOffset: 1, endOffset, marker,
903
- content: `${c.body}${review.attribution ? `\n\n---\n${review.attribution}` : ''}\n\n${marker}` };
1317
+ const anchor = normalizedAnchor(c.anchor);
1318
+ if (!c.otherPlaces?.length) {
1319
+ const marker = inlineMarker(review.target, c, ordinalOf('inline', c.path, anchor));
1320
+ return { ...c, kind: 'inline', startOffset: 1, endOffset, marker,
1321
+ content: `${c.body}${review.attribution ? `\n\n---\n${review.attribution}` : ''}\n\n${marker}` };
1322
+ }
1323
+ // One defect made at several places: the runtime lists the other places under the comment's own text.
1324
+ // The comment is known by a marker of its own (`sharedMarker`); before it stands the marker that says a
1325
+ // comment for several places is on these quoted lines (`linesMarker`), which planning reads.
1326
+ const places = c.otherPlaces.map(other => other.place).sort();
1327
+ const marker = sharedMarker(review.target, c, ordinalOf('shared', c.path, anchor, places)), lines = linesMarker(review.target, c);
1328
+ const list = escapeComments(renderOtherPlaces(c.otherPlaces, review.outputLanguage ?? 'en'));
1329
+ return { ...c, kind: 'inline', startOffset: 1, endOffset, marker, linesMarker: lines,
1330
+ content: `${c.body}\n\n${list}${review.attribution ? `\n\n---\n${review.attribution}` : ''}\n\n${lines}\n\n${marker}` };
904
1331
  });
905
1332
  const skipped = pages.flatMap(page => page.skipped);
906
1333
  const intro = pages.map(page => page.summary).find(Boolean);
907
1334
  const details = [...new Set(pages.map(page => page.summaryDetails).filter(nonempty))].join('\n\n');
908
- const groups = comments.filter(c => c.findingIds?.length > 1).map(c => c.findingIds);
1335
+ // Findings reported twice on the same lines share an index row; the places of
1336
+ // one repeated defect are findings of their own and keep their rows.
1337
+ const groups = comments.filter(c => c.findingIds?.length > 1 && !c.otherPlaces).map(c => c.findingIds);
909
1338
  return { summary: summaryComment(review, intro, details, comments.map(c => c.marker), groups), comments, skipped };
910
1339
  }