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

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
 
@@ -55,6 +55,13 @@ export function parseLocation(location) {
55
55
  return { side: match[1] ?? 'head', path: match[2], start, end: match[4] ? Number(match[4]) : start };
56
56
  }
57
57
 
58
+ /** A finding's place as a comment lists it: "/src/a.ts:12-14". */
59
+ export function placeOf(finding) {
60
+ const at = parseLocation(finding.location);
61
+ if (!at) return String(finding.location ?? '');
62
+ return `${at.path}${at.start ? `:${at.start}${at.end !== at.start ? `-${at.end}` : ''}` : ''}`;
63
+ }
64
+
58
65
  /**
59
66
  * Why findings may not share one comment; [] when they may. Members must be
60
67
  * inline-eligible quick findings of different sessions with the same
@@ -78,6 +85,36 @@ export function combinationProblems(members) {
78
85
  return { problems, lines };
79
86
  }
80
87
 
88
+ /**
89
+ * Why findings may not share one comment as one defect made at several places;
90
+ * [] when they may. Members are high or medium findings of one severity, each
91
+ * on lines of a HEAD file (a first line and a last one not before it), and no
92
+ * two of them share a line: findings on the same lines are not another place.
93
+ * The comment lists each other place as its finding states it, so a place
94
+ * whose text a list cannot hold unchanged (`listablePlace`) shares no comment.
95
+ * Whether the lines exist in the file is checked where its text is known
96
+ * (`evaluatePlanPage`).
97
+ */
98
+ export function repeatProblems(members) {
99
+ const problems = [];
100
+ if (new Set(members.map(member => member.severity)).size !== 1) problems.push('combined findings must have the same severity');
101
+ else if (!['high', 'medium'].includes(members[0].severity)) problems.push('only high and medium findings get inline comments');
102
+ if (members.some(member => member.inline === false)) problems.push('a combined finding has no inline location');
103
+ const at = members.map(member => parseLocation(member.location));
104
+ if (at.some(location => location?.side !== 'head' || !location.start || location.end < location.start)) {
105
+ problems.push('every combined finding must be located on lines of a HEAD file');
106
+ return { problems };
107
+ }
108
+ const unlistable = members.filter(member => !listablePlace(placeOf(member)));
109
+ 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`);
110
+ for (let i = 0; i < at.length; i++) for (let j = i + 1; j < at.length; j++) {
111
+ if (at[i].path === at[j].path && at[i].start <= at[j].end && at[j].start <= at[i].end) {
112
+ problems.push(`${members[i].id} and ${members[j].id} are on the same lines, which is not another place`);
113
+ }
114
+ }
115
+ return { problems };
116
+ }
117
+
81
118
  // A finding ID as a text names it (F-1, Q-1001, V-2).
82
119
  const FINDING_ID = /(?<![A-Za-z0-9_-])[A-Za-z]+-\d+(?!\d)/g;
83
120
 
@@ -603,6 +640,52 @@ export function inlineMarker(target, comment, ordinal = 0) {
603
640
  return markerTag(hash([targetKey(target), 'inline', comment.path, normalizedAnchor(comment.anchor), ordinal]));
604
641
  }
605
642
 
643
+ /**
644
+ * The fingerprint of a comment that stands for one defect at several places:
645
+ * PR + path + normalized anchor + the other places it lists. Such a comment
646
+ * is a comment of its own: publication skips it only when this marker is on
647
+ * the PR, so the comment found there is this very comment, with every place,
648
+ * and nothing has to be read out of a posted text to know what it covers.
649
+ * The ordinal tells apart two comments with the same quoted lines and the
650
+ * same other places, which two defects at the same places would have.
651
+ */
652
+ export function sharedMarker(target, comment, ordinal = 0) {
653
+ return markerTag(hash([targetKey(target), 'shared', comment.path, normalizedAnchor(comment.anchor), comment.otherPlaces.map(other => other.place).sort(), ordinal]));
654
+ }
655
+
656
+ /**
657
+ * The second marker of a comment for several places: PR + path + normalized
658
+ * anchor, nothing else. It says that such a comment stands on these quoted
659
+ * lines, whatever it lists and whichever plan wrote it. Only planning reads
660
+ * it, to keep another comment off those lines (`occupiedLines`); publication,
661
+ * its ledger and its attempt records know a comment by its own marker alone.
662
+ */
663
+ export function linesMarker(target, comment) {
664
+ return markerTag(hash([targetKey(target), 'lines', comment.path, normalizedAnchor(comment.anchor)]));
665
+ }
666
+
667
+ /** How many comments on the same quoted lines the planning rule looks for on the PR (their markers count from 0). */
668
+ const SAME_LINES = 8;
669
+
670
+ /**
671
+ * Why a planned comment may not stand on its quoted lines, given the markers
672
+ * the PR already has (`posted`, marker to thread): a comment for several
673
+ * places and a comment for one place do not find each other by marker, so
674
+ * one of them would be posted next to the other. A comment for several
675
+ * places stays off lines that carry any comment of AZPR's, unless the PR has
676
+ * this very comment; a comment for one place (or for findings on the same
677
+ * lines) stays off lines that carry a comment for several places, unless the
678
+ * PR has a comment of its own kind there, which it then finds by marker as
679
+ * always. Nothing here depends on other comments of the plan. '' when it may.
680
+ */
681
+ function occupiedLines(target, comment, posted) {
682
+ const first = make => Array.from({ length: SAME_LINES }, (_, ordinal) => posted.get(make(ordinal))).find(thread => thread !== undefined);
683
+ const single = first(ordinal => inlineMarker(target, comment, ordinal)), several = posted.get(linesMarker(target, comment));
684
+ 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`;
685
+ if (comment.otherPlaces) return (single ?? several) !== undefined && first(ordinal => sharedMarker(target, comment, ordinal)) === undefined ? says(single ?? several) : '';
686
+ return several !== undefined && single === undefined ? says(several) : '';
687
+ }
688
+
606
689
  /** One summary per reviewed source commit and set of inline comments. */
607
690
  export function summaryMarker(target, head, inlineMarkers) {
608
691
  return markerTag(hash([targetKey(target), 'summary', head, [...inlineMarkers].sort()]));
@@ -650,6 +733,119 @@ export function restoreAnchor(comment, review) {
650
733
  : { anchor: comment.anchor, startLine: comment.startLine, endLine: comment.endLine, found: false };
651
734
  }
652
735
 
736
+ // What decides where a block of Markdown begins and ends, as CommonMark reads lines (tabs made spaces first).
737
+ // 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).
738
+ const FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/s;
739
+ const fenceStart = line => {
740
+ const found = FENCE_LINE.exec(line);
741
+ return found && (found[1][0] === '~' || !found[2].includes('`')) ? { mark: found[1][0], length: found[1].length } : null;
742
+ };
743
+ const fenceEnd = (fence, line) => {
744
+ const found = FENCE_LINE.exec(line);
745
+ return Boolean(found) && found[1][0] === fence.mark && found[1].length >= fence.length && /^ *$/.test(found[2]);
746
+ };
747
+ const QUOTE_MARK = /^ {0,3}> ?/;
748
+ const LIST_ITEM = /^( {0,3}(?:[-*+]|(\d{1,9})[.)]))(?:( +)(.*))?$/s;
749
+ const THEMATIC_BREAK = /^ {0,3}([-*_])(?: *\1){2,} *$/;
750
+ const HEADING = /^ {0,3}#{1,6}(?: |$)/;
751
+ const UNDERLINE = /^ {0,3}(?:=+|-+) *$/;
752
+ // 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
753
+ // start of an HTML comment is escaped in a body): how a line starts it, what a line holds that ends it, its name.
754
+ const LASTING_HTML = [
755
+ [/^ {0,3}<(pre|script|style|textarea)(?=[\s>]|$)/i, /<\/(?:pre|script|style|textarea)>/i, found => `a <${found[1].toLowerCase()}> block`],
756
+ [/^ {0,3}<\?/, /\?>/, () => 'a <?…?> block'],
757
+ [/^ {0,3}<!\[CDATA\[/, /\]\]>/, () => 'a CDATA section'],
758
+ [/^ {0,3}<![a-z]/i, />/, () => 'a <!…> declaration'],
759
+ ];
760
+ // Raw HTML that ends at a blank line: a line that begins with one of these tags (HTML block 6), or one that is
761
+ // a whole tag and nothing else, which no paragraph continues into (7). The whole tag is taken as commonmark.js
762
+ // and markdown-it take it: of any name (`<pre/>` too, which starts no block of the first kind) and followed by
763
+ // any white space.
764
+ 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;
765
+ 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;
766
+
767
+ /**
768
+ * The block a body leaves open for what follows it after a blank line, named
769
+ * for a correction; '' when it leaves none. As CommonMark reads blocks, only
770
+ * two kinds go on over a blank line at the top level: a fenced code block
771
+ * without its closing fence, and raw HTML that waits for its own end
772
+ * (LASTING_HTML). Inside a quote or a list item both end with it, and
773
+ * unindented text after a blank line ends every quote and list.
774
+ *
775
+ * So the lines are read for where the top level is. A quote is known by its
776
+ * mark and a list item by its marker and the indentation of its content, the
777
+ * outermost one only: what is nested in it is read as its text. Its lines,
778
+ * and those of the top level, are read alike for code fences, raw HTML and
779
+ * paragraphs, since a line without the mark or the indentation still
780
+ * continues a paragraph, and a paragraph is interrupted by some list items
781
+ * only. This is a reading of lines, not a Markdown parser, and it decides
782
+ * only whether a body is sent back for correction.
783
+ */
784
+ function openBlock(text) {
785
+ // Lines that hold no quote or list item of their own: the top level, or the content of the one the lines
786
+ // are in. open: code or raw HTML that waits for its end. raw: raw HTML that ends at a blank line.
787
+ // paragraph: the last line was a paragraph's.
788
+ const run = () => ({ open: null, raw: false, paragraph: false });
789
+ const top = run();
790
+ let within = null;
791
+ const read = (state, line) => {
792
+ if (state.open) {
793
+ if (state.open.ends(line)) state.open = null;
794
+ return;
795
+ }
796
+ const indent = /^ */.exec(line)[0].length;
797
+ if (indent === line.length) state.raw = state.paragraph = false;
798
+ // Raw HTML takes every line up to a blank one; four spaces or more are code, or a paragraph's next line.
799
+ if (indent === line.length || state.raw || indent > 3) return;
800
+ const fence = fenceStart(line), html = fence ? undefined : LASTING_HTML.find(([start]) => start.test(line));
801
+ if (fence) state.open = { ends: next => fenceEnd(fence, next), name: 'a code fence' };
802
+ else if (html && !html[1].test(line)) state.open = { ends: next => html[1].test(next), name: html[2](html[0].exec(line)) };
803
+ else if (!html) state.raw = BLOCK_TAG.test(line) || (!state.paragraph && TAG_LINE.test(line));
804
+ // Under a paragraph, a line of = or - makes it a heading; what starts no block is a paragraph's line.
805
+ state.paragraph = !(fence || html || state.raw || THEMATIC_BREAK.test(line) || HEADING.test(line) || (state.paragraph && UNDERLINE.test(line)));
806
+ };
807
+ // 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.
808
+ const starts = line => Boolean(fenceStart(line)) || QUOTE_MARK.test(line) || Boolean(LIST_ITEM.exec(line)) || THEMATIC_BREAK.test(line) || HEADING.test(line)
809
+ || LASTING_HTML.some(([start]) => start.test(line)) || BLOCK_TAG.test(line);
810
+ for (const written of String(text).replace(/\r\n?/g, '\n').split('\n')) {
811
+ // A tab reaches the next column that is a multiple of four.
812
+ let line = '', column = 0;
813
+ for (const char of written) {
814
+ const width = char === '\t' ? 4 - column % 4 : 1;
815
+ line += char === '\t' ? ' '.repeat(width) : char;
816
+ column += width;
817
+ }
818
+ const indent = /^ */.exec(line)[0].length, blank = indent === line.length;
819
+ if (within) {
820
+ // A list item that began with nothing ends at a blank line; any other goes on over it.
821
+ const empty = within.empty;
822
+ within.empty = false;
823
+ if (within.quote ? QUOTE_MARK.test(line) : blank ? !empty : indent >= within.offset) {
824
+ read(within.content, within.quote ? line.replace(QUOTE_MARK, '') : line.slice(within.offset));
825
+ continue;
826
+ }
827
+ if (!blank && within.content.paragraph && !starts(line)) continue;
828
+ within = null;
829
+ }
830
+ if (!top.open && !top.raw && !blank && indent <= 3) {
831
+ const item = (top.paragraph && UNDERLINE.test(line)) || THEMATIC_BREAK.test(line) ? null : LIST_ITEM.exec(line), worded = /[^ ]/.test(item?.[4] ?? '');
832
+ if (line[indent] === '>') within = { quote: true, content: run() };
833
+ // A paragraph is interrupted only by an item with text, and by a numbered one only when it starts at 1.
834
+ else if (item && (!top.paragraph || (worded && (item[2] === undefined || Number(item[2]) === 1)))) {
835
+ // The content's column: after the marker and its spaces, or one space after it where code or nothing follows.
836
+ within = { offset: item[1].length + (worded && item[3].length <= 4 ? item[3].length : 1), empty: !worded, content: run() };
837
+ }
838
+ if (within) {
839
+ top.paragraph = false;
840
+ read(within.content, within.quote ? line.replace(QUOTE_MARK, '') : line.slice(within.offset));
841
+ continue;
842
+ }
843
+ }
844
+ read(top, line);
845
+ }
846
+ return top.open?.name ?? '';
847
+ }
848
+
653
849
  /** Strip any severity label the model wrote, then apply the canonical one. */
654
850
  export function normalizeTitle(body, severity) {
655
851
  const trimmed = body.trim();
@@ -671,13 +867,21 @@ const aliases = (value, names) => {
671
867
  * @returns {{result: object, issues: string[], corrections: object[]}}
672
868
  * With `final`, every remaining problem becomes a local skip instead of an issue.
673
869
  * `candidates` lists the groups of a quick review whose findings one comment
674
- * may combine (`findingIds`); the runtime never combines findings itself.
870
+ * may combine (`findingIds`): one defect reported twice on the same lines.
871
+ * `repeats` lists the groups, of any review, whose findings may be one defect
872
+ * made at several places; a comment that combines some of them stands at one
873
+ * place and carries the others as `otherPlaces`, which the runtime renders.
874
+ * The runtime never combines findings itself.
675
875
  * `sources` are the page's source excerpts and `discussions` the live threads
676
876
  * the runtime read (null when it could not): skip causes are checked against them.
877
+ * `posted` maps the markers the PR already has to their threads
878
+ * (`markersInThreads`; null when the threads could not be read): a comment
879
+ * for several places and a comment for one place are not put on the same
880
+ * quoted lines (`occupiedLines`).
677
881
  * With `allowSummary: false` a summary note is dropped, never repaired: only
678
882
  * the page the runtime chose writes it.
679
883
  */
680
- export function evaluatePlanPage(answerText, { review, assigned, final = false, candidates = [], sources = [], discussions = null, allowSummary = true }) {
884
+ export function evaluatePlanPage(answerText, { review, assigned, final = false, candidates = [], repeats = [], sources = [], discussions = null, posted = null, allowSummary = true }) {
681
885
  const corrections = [], issues = [];
682
886
  const parsed = parseModelJSON(answerText, { keys: ['status', 'comments', 'skipped'] });
683
887
  if (!parsed.value) {
@@ -727,6 +931,9 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
727
931
  else if (body.length > INLINE_HARD_LIMIT) problems.push(`body exceeds ${INLINE_HARD_LIMIT} characters`);
728
932
  const named = namedExcluded(body, excluded);
729
933
  if (named.length) problems.push(`body names ${named.join(', ')}, which a person excluded from publication; leave ${named.length === 1 ? 'it' : 'them'} out`);
934
+ // The list of other places is the runtime's: its heading appears nowhere in a body, however it is
935
+ // indented, quoted or continued, so that no text a planner wrote reads like the runtime's list.
936
+ 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
937
  const path = nonempty(c.path) ? (c.path.startsWith('/') ? c.path : '/' + c.path) : '';
731
938
  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
939
  else if (lines && path !== lines.path) problems.push(`path must be ${lines.path}, where the combined findings are`);
@@ -751,29 +958,73 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
751
958
  }
752
959
  if (problems.length) return { problems };
753
960
  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 } };
961
+ return { problems, found: restored.found, comment: { severity, path, startLine: restored.startLine, endLine: restored.endLine, anchor: restored.anchor, body } };
755
962
  }
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.
963
+ // One comment for findings of a listed group: one defect reported twice on
964
+ // the same lines (`candidates`, quick reviews) or made at several places
965
+ // (`repeats`). The planner decides whether they state one defect; the runtime
966
+ // checks only the group rules.
758
967
  function combine(c, ids) {
759
968
  const label = ids.join('+');
760
969
  const members = ids.map(id => eligible.get(id));
761
970
  const problems = [];
971
+ const listed = group => ids.every(id => group.includes(id));
972
+ const twice = quick && candidates.some(listed), repeated = !twice && repeats.some(listed);
762
973
  let lines;
763
- if (!quick || !candidates.length) problems.push('findingIds may combine only the findings of a listed mergeCandidates group');
974
+ if (!(quick && candidates.length) && !repeats.length) problems.push('findingIds may combine only the findings of one listed group (mergeCandidates or repeatCandidates)');
764
975
  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');
976
+ else if (!twice && !repeated) problems.push('the findings are not all in one listed group (mergeCandidates or repeatCandidates)');
766
977
  else if (members.some(member => handled.has(member.id))) problems.push('a combined finding already has a comment or skip');
767
978
  else {
768
- const checked = combinationProblems(members);
979
+ const checked = twice ? combinationProblems(members) : repeatProblems(members);
769
980
  problems.push(...checked.problems);
770
981
  lines = checked.lines;
982
+ // Every place a comment lists is a place of this PR's changes as it is at HEAD: a changed
983
+ // file whose text the runtime read for this page, and lines that file has.
984
+ const absent = twice ? [] : members.filter(member => {
985
+ const at = parseLocation(member.location);
986
+ const read = sources.find(item => item.path === at?.path);
987
+ return !at || !changed.has(at.path) || !read || !(at.end <= (read.totalLines ?? read.lastLine));
988
+ });
989
+ 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
990
  if (!nonempty(c.mergeReason)) problems.push('a combined comment needs a mergeReason');
772
991
  }
773
- let drafted;
992
+ let drafted, first;
774
993
  if (!problems.length) {
775
994
  drafted = draft(c, label, members[0].severity, lines);
776
995
  problems.push(...drafted.problems);
996
+ // Where the comment stands follows from the lines it quotes, so they must be lines the file has:
997
+ // the quote is found in the HEAD text, also for a review whose single comments need not be, and
998
+ // ends within the file (a quote that adds an empty line after the last one is found, but is no line).
999
+ if (!problems.length && repeated && !drafted.found) problems.push('the anchor text was not found in the HEAD source; quote the exact lines from sourceExcerpts');
1000
+ // (An anchor in a file that holds none of the findings is refused below, where the place is looked for.)
1001
+ // The list follows the body: a block the body leaves open would take it in.
1002
+ const left = !problems.length && repeated ? openBlock(drafted.comment.body) : '';
1003
+ if (left) problems.push(`body leaves ${left} open, which would take the list of other places into it; close it`);
1004
+ const lineCount = (read => read && (read.totalLines ?? read.lastLine))(repeated && drafted.comment && sources.find(item => item.path === drafted.comment.path));
1005
+ if (!problems.length && lineCount && drafted.comment.endLine > lineCount) {
1006
+ 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`);
1007
+ }
1008
+ }
1009
+ if (!problems.length && repeated) {
1010
+ // The comment stands at one of the places: the one finding whose lines its anchor touches.
1011
+ // Members never share a line, but quoted lines can reach from one into the next: such an
1012
+ // anchor names no place, and the runtime does not choose one.
1013
+ const { path, startLine, endLine } = drafted.comment;
1014
+ const touched = members.filter(member => (at => at.path === path && startLine <= at.end && endLine >= at.start)(parseLocation(member.location)));
1015
+ if (touched.length === 1) [first] = touched;
1016
+ 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(', ')})`);
1017
+ 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`);
1018
+ }
1019
+ if (!problems.length && posted) {
1020
+ // Comments for one place and comments for several do not find each other by marker: neither is put
1021
+ // on quoted lines that carry the other kind (`occupiedLines`).
1022
+ const others = repeated ? members.filter(member => member !== first).map(member => ({ place: placeOf(member) })) : undefined;
1023
+ const taken = occupiedLines(review.target, { ...drafted.comment, ...(others ? { otherPlaces: others } : {}) }, posted);
1024
+ if (taken) {
1025
+ 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`
1026
+ : `${taken}. Skip these findings with cause existing-thread when that thread covers them, or quote other lines`);
1027
+ }
777
1028
  }
778
1029
  if (problems.length) {
779
1030
  if (!final) {
@@ -788,7 +1039,13 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
788
1039
  return;
789
1040
  }
790
1041
  for (const id of ids) handled.add(id);
791
- comments.push({ findingId: ids[0], findingIds: ids, ...drafted.comment, mergeReason: c.mergeReason.trim() });
1042
+ if (!repeated) { comments.push({ findingId: ids[0], findingIds: ids, ...drafted.comment, mergeReason: c.mergeReason.trim() }); return; }
1043
+ // The place of the comment first, the others in the order of the page; their
1044
+ // locations are the findings' own, never text the planner wrote.
1045
+ const position = new Map(assigned.map((finding, index) => [finding.id, index]));
1046
+ const others = members.filter(member => member !== first).sort((a, b) => position.get(a.id) - position.get(b.id));
1047
+ comments.push({ findingId: first.id, findingIds: [first.id, ...others.map(member => member.id)], ...drafted.comment, mergeReason: c.mergeReason.trim(),
1048
+ otherPlaces: others.map(member => ({ findingId: member.id, place: placeOf(member) })) });
792
1049
  }
793
1050
  for (const [index, raw] of (Array.isArray(value.comments) ? value.comments : []).entries()) {
794
1051
  if (!isObject(raw)) { corrections.push({ action: 'drop-non-object-comment', index }); continue; }
@@ -806,6 +1063,9 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
806
1063
  continue;
807
1064
  }
808
1065
  const { problems, comment } = draft(c, finding.id, finding.severity);
1066
+ // A comment for one place is not put on quoted lines that carry a comment for several places.
1067
+ const taken = !problems.length && posted ? occupiedLines(review.target, comment, posted) : '';
1068
+ if (taken) problems.push(`${taken}. Skip ${finding.id} with cause existing-thread when that thread covers it, or quote other lines`);
809
1069
  if (problems.length) {
810
1070
  if (!final) { issues.push(`comment for ${finding.id}: ${problems.join('; ')}.`); reported.add(finding.id); continue; }
811
1071
  skip(finding.id, `No inline comment: ${problems.join('; ')}. The finding remains in the summary index.`);
@@ -823,8 +1083,8 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
823
1083
  const cited = citedFindings(reason, s.findingId, findingIds);
824
1084
  if (cited.length && !final) {
825
1085
  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).`);
1086
+ ? `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).`
1087
+ : `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, 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
1088
  reported.add(s.findingId);
829
1089
  continue;
830
1090
  }
@@ -875,6 +1135,74 @@ export function planRepairPrompt(issues, { parseOnly = false } = {}) {
875
1135
  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
1136
  }
877
1137
 
1138
+ /**
1139
+ * Validate the grouping pass: which findings may be one defect made at several
1140
+ * places. Only a proposal: each planning page still decides whether a group
1141
+ * gets one comment, and the runtime checks that comment's rules. A group holds
1142
+ * two or more of `findings` (the high and medium ones on lines of a HEAD file)
1143
+ * under `repeatProblems`, and a finding belongs to at most one group. With
1144
+ * `final`, a group that breaks a rule is dropped instead of reported.
1145
+ * @returns {{result: {status: string, groups: string[][]}|null, issues: string[], corrections: object[]}}
1146
+ */
1147
+ export function evaluateGrouping(answerText, { findings, final = false }) {
1148
+ const corrections = [], issues = [];
1149
+ const parsed = parseModelJSON(answerText, { keys: ['status', 'groups'] });
1150
+ if (!parsed.value) {
1151
+ if (!final) return { result: null, issues: [`Your answer could not be used: ${parsed.problem}.`], corrections };
1152
+ return { result: { status: 'READY', groups: [] }, issues: [], corrections: [{ action: 'no-usable-grouping' }] };
1153
+ }
1154
+ if (parsed.corrections) corrections.push(...parsed.corrections);
1155
+ const value = aliases(parsed.value, ['status', 'groups']);
1156
+ // The pass has one answer and no continuation: any other status is an answer that stopped early,
1157
+ // which a correction turn may finish. After the repairs the groups it did name are kept, since each
1158
+ // is only a proposal that meets the rules.
1159
+ // A missing status is no READY either: an answer may name unfinished work without one.
1160
+ const status = String(value.status ?? '').trim().toUpperCase();
1161
+ if (status !== 'READY') {
1162
+ if (final) corrections.push({ action: 'accept-grouping-without-ready', status: status.slice(0, 40) });
1163
+ 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.');
1164
+ }
1165
+ const order = new Map(findings.map((finding, index) => [finding.id, index]));
1166
+ const byId = new Map(findings.map(finding => [finding.id, finding]));
1167
+ const taken = new Set(), groups = [];
1168
+ const refuse = (ids, problem) => {
1169
+ if (final) corrections.push({ action: 'drop-invalid-group', findingIds: ids, problem });
1170
+ else issues.push(`group ${ids.join(', ')}: ${problem}. Correct it or leave it out.`);
1171
+ };
1172
+ // An answer without `groups` (a page's answer, say) is no grouping: it gets its correction turn like any other.
1173
+ if (!Array.isArray(value.groups) && !final) issues.push(value.groups === undefined ? 'groups is missing: answer with {"status": "READY", "groups": [...]}, and "groups": [] when nothing repeats.'
1174
+ : 'groups must be an array of {"findingIds": [...], "reason": "..."}; use [] when nothing repeats.');
1175
+ for (const [index, raw] of (Array.isArray(value.groups) ? value.groups : []).entries()) {
1176
+ const group = Array.isArray(raw) ? { findingIds: raw } : isObject(raw) ? aliases(raw, ['findingIds', 'reason']) : {};
1177
+ // An entry that is no group at all (its findings are not a list) is a mistake to correct; a list of fewer
1178
+ // than two findings is a group of nothing, and nothing to correct.
1179
+ if (!Array.isArray(group.findingIds)) {
1180
+ if (final) corrections.push({ action: 'drop-malformed-group', index });
1181
+ else issues.push(`group ${index + 1}: findingIds must be an array of finding IDs, as in {"findingIds": ["F-2", "F-5"], "reason": "..."}.`);
1182
+ continue;
1183
+ }
1184
+ const ids = [...new Set(group.findingIds.map(id => String(id)))];
1185
+ if (ids.length < 2) { corrections.push({ action: 'drop-group-without-two-findings', index }); continue; }
1186
+ const unknown = ids.filter(id => !byId.has(id));
1187
+ if (unknown.length) { refuse(ids, `${unknown.join(', ')} ${unknown.length === 1 ? 'is' : 'are'} not in findings`); continue; }
1188
+ const again = ids.filter(id => taken.has(id));
1189
+ if (again.length) { refuse(ids, `${again.join(', ')} already ${again.length === 1 ? 'belongs' : 'belong'} to another group`); continue; }
1190
+ const { problems } = repeatProblems(ids.map(id => byId.get(id)));
1191
+ if (problems.length) { refuse(ids, problems.join('; ')); continue; }
1192
+ for (const id of ids) taken.add(id);
1193
+ // In the order of the findings, so that pages and their comments do not depend on how the answer listed them.
1194
+ groups.push(ids.sort((a, b) => order.get(a) - order.get(b)));
1195
+ }
1196
+ groups.sort((a, b) => order.get(a[0]) - order.get(b[0]));
1197
+ return { result: { status: 'READY', groups }, issues, corrections };
1198
+ }
1199
+
1200
+ export function groupingRepairPrompt(issues, { parseOnly = false } = {}) {
1201
+ if (parseOnly) return parseRepairPrompt(issues);
1202
+ const listed = issues.slice(0, 25).map(issue => `- ${issue}`).join('\n');
1203
+ 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.`;
1204
+ }
1205
+
878
1206
  function summaryComment(review, note, details, inlineMarkers, groups = []) {
879
1207
  const chinese = /^zh(?:-|$)/i.test(review.outputLanguage ?? '');
880
1208
  const traditional = chinese && new Intl.Locale(review.outputLanguage).maximize().script === 'Hant';
@@ -892,19 +1220,35 @@ function summaryComment(review, note, details, inlineMarkers, groups = []) {
892
1220
  /** Assemble validated pages into one saved plan with markers and exact content. */
893
1221
  export function assemblePlan(review, pages) {
894
1222
  const ordinals = new Map();
1223
+ // Comments that are alike in what their marker is made of are told apart by their order in the plan.
1224
+ const ordinalOf = (...key) => {
1225
+ const name = JSON.stringify(key), ordinal = ordinals.get(name) ?? 0;
1226
+ ordinals.set(name, ordinal + 1);
1227
+ return ordinal;
1228
+ };
895
1229
  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
1230
  // Azure positions are one-based UTF-16 offsets within their lines.
901
1231
  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}` };
1232
+ const anchor = normalizedAnchor(c.anchor);
1233
+ if (!c.otherPlaces?.length) {
1234
+ const marker = inlineMarker(review.target, c, ordinalOf('inline', c.path, anchor));
1235
+ return { ...c, kind: 'inline', startOffset: 1, endOffset, marker,
1236
+ content: `${c.body}${review.attribution ? `\n\n---\n${review.attribution}` : ''}\n\n${marker}` };
1237
+ }
1238
+ // One defect made at several places: the runtime lists the other places under the comment's own text.
1239
+ // The comment is known by a marker of its own (`sharedMarker`); before it stands the marker that says a
1240
+ // comment for several places is on these quoted lines (`linesMarker`), which planning reads.
1241
+ const places = c.otherPlaces.map(other => other.place).sort();
1242
+ const marker = sharedMarker(review.target, c, ordinalOf('shared', c.path, anchor, places)), lines = linesMarker(review.target, c);
1243
+ const list = escapeComments(renderOtherPlaces(c.otherPlaces, review.outputLanguage ?? 'en'));
1244
+ return { ...c, kind: 'inline', startOffset: 1, endOffset, marker, linesMarker: lines,
1245
+ content: `${c.body}\n\n${list}${review.attribution ? `\n\n---\n${review.attribution}` : ''}\n\n${lines}\n\n${marker}` };
904
1246
  });
905
1247
  const skipped = pages.flatMap(page => page.skipped);
906
1248
  const intro = pages.map(page => page.summary).find(Boolean);
907
1249
  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);
1250
+ // Findings reported twice on the same lines share an index row; the places of
1251
+ // one repeated defect are findings of their own and keep their rows.
1252
+ const groups = comments.filter(c => c.findingIds?.length > 1 && !c.otherPlaces).map(c => c.findingIds);
909
1253
  return { summary: summaryComment(review, intro, details, comments.map(c => c.marker), groups), comments, skipped };
910
1254
  }
package/src/config.mjs CHANGED
@@ -175,11 +175,12 @@ function integer(value, at, min, max) {
175
175
  if (!Number.isInteger(value) || value < min || value > max) throw new Error(`${at} must be an integer from ${min} to ${max}.`);
176
176
  return value;
177
177
  }
178
+ /** Whether a value is a model reference as settings take one: provider/model, optionally #variant; no placeholder. */
179
+ export const isModelReference = value => typeof value === 'string' && value.length <= 512 &&
180
+ /^[A-Za-z0-9][A-Za-z0-9._:-]*\/[A-Za-z0-9][A-Za-z0-9._:@/+=-]*(?:#[A-Za-z0-9][A-Za-z0-9._-]*)?$/.test(value) && !/REPLACE_|YOUR_PROVIDER|YOUR_MODEL/.test(value);
178
181
  function model(value, at, optional = false) {
179
182
  if (optional && value === '') return '';
180
- if (typeof value !== 'string' || value.length > 512 ||
181
- !/^[A-Za-z0-9][A-Za-z0-9._:-]*\/[A-Za-z0-9][A-Za-z0-9._:@/+=-]*(?:#[A-Za-z0-9][A-Za-z0-9._-]*)?$/.test(value) ||
182
- /REPLACE_|YOUR_PROVIDER|YOUR_MODEL/.test(value)) throw new Error(`${at}: select an actual provider/model ID from opencode models, optionally with a variant as provider/model#variant; do not use a display name or placeholder.`);
183
+ if (!isModelReference(value)) throw new Error(`${at}: select an actual provider/model ID from opencode models, optionally with a variant as provider/model#variant; do not use a display name or placeholder.`);
183
184
  return value;
184
185
  }
185
186
  /** A forward proxy for Azure DevOps calls. Never echo it: it may carry credentials. */
@@ -1,8 +1,8 @@
1
1
  # Role: comment planner
2
2
 
3
3
  `commentWork` identifies this work page. Account for every finding in `findings`
4
- (at most four per page): each one appears exactly once, either in `comments` or
5
- in `skipped` with a reason. Other pages handle other findings.
4
+ (usually at most four per page): each one appears exactly once, either in
5
+ `comments` or in `skipped` with a reason. Other pages handle other findings.
6
6
  <!-- azpr:verified -->
7
7
  The verifier already merged duplicate findings: each finding is a separate
8
8
  issue, so never skip one because another finding of this review has or will get
@@ -22,6 +22,27 @@ when unsure, comment on each finding separately; never combine findings
22
22
  outside a listed group.
23
23
  <!-- azpr:end -->
24
24
 
25
+ One mistake is sometimes made at several places (the same wrong call in each
26
+ handler, the same stale text in each copy), and each place is a finding of its
27
+ own. `repeatCandidates`, when present, lists groups of this page's findings
28
+ that may be such repeats: findings of one severity at different places. Give
29
+ findings of one group a single comment only when they are the same mistake and
30
+ one instruction corrects every place: anchor it at the place that shows the
31
+ mistake most clearly, quoting lines of that one finding only, give it
32
+ `findingIds` with every finding it covers and a `mergeReason`, and word the
33
+ body so that it holds for each of them. Do not list the other places: the
34
+ runtime adds each other finding's file and lines under your text. A thread of
35
+ AZPR's in `existingDiscussions` (`azpr: true`) that already covers findings,
36
+ at its own place or in its `alsoAt`, settles them: skip them with cause
37
+ `existing-thread`, and do not write the comment again at another place. The
38
+ runtime puts no second comment on lines that carry a different comment of
39
+ AZPR's: when the place you would choose has such a thread, anchor the comment
40
+ at another of its places, or leave that finding out of it. Findings that only
41
+ resemble each other, that follow from one another, or whose places need
42
+ different corrections keep their own comments; when unsure, comment on each
43
+ finding separately. A combined comment accounts for every finding it names;
44
+ never combine findings outside a listed group.
45
+
25
46
  The runtime already read what this page normally needs, so most pages need no
26
47
  tool call at all:
27
48
 
@@ -33,7 +54,9 @@ tool call at all:
33
54
  and `allDispositions` holding the complete lists.
34
55
  - `existingDiscussions` (when `discussionsRead` is true): every live thread on
35
56
  the PR with its path, line, author and the start of its first comment.
36
- Deleted threads are already excluded.
57
+ Deleted threads are already excluded. A thread whose comment lists further
58
+ places of the same defect names them in `alsoAt`: those places are discussed
59
+ there too.
37
60
 
38
61
  Read more only when these do not answer a question: azpr_read_file at version
39
62
  "head" for lines outside an excerpt, azpr_pr_threads when you need a full
@@ -98,6 +121,26 @@ Every `skipped` entry names its `cause`, one of:
98
121
  severity, the location, the thread, the lines in `sourceExcerpts`) and asks you
99
122
  to correct a skip whose cause does not hold.
100
123
 
124
+ ## Grouping pass
125
+
126
+ When `commentWork.kind` is `"group"`, the work is not a page: write no comments
127
+ and no skips. `findings` then holds the review's high and medium findings (ID,
128
+ severity, location, summary, suggestion, and the evidence unless the list is
129
+ long). Say which of them are one mistake made at several places, as described
130
+ above: the same defect, and one instruction corrects every place. A group has
131
+ two or more findings of one severity at different places; a finding belongs to
132
+ one group at most, and most findings belong to none. No tool call is needed,
133
+ and the pass has one answer, without a continuation. Return only:
134
+
135
+ ```json
136
+ {"status": "READY", "groups": [{"findingIds": ["F-2", "F-5"], "reason": "The shared mistake and the one correction, in a sentence."}]}
137
+ ```
138
+
139
+ Use `"groups": []` when nothing repeats. The pages decide afterwards whether a
140
+ group gets one comment.
141
+
142
+ ## Longer pages
143
+
101
144
  When this page needs more reading than fits, return `"status": "CONTINUE"` with
102
145
  the comments and skips you finished plus `"continuation"`: exact data
103
146
  references, the checks already done and what remains. A fresh session continues
@@ -26,6 +26,8 @@ One general PR summary plus inline comments for high and medium findings:
26
26
  <!-- azpr:end -->
27
27
  - Each inline comment discusses one root cause on a changed HEAD file, with the
28
28
  smallest useful RIGHT-side line range.
29
+ - One mistake made at several places gets one comment at one of them; the
30
+ runtime lists the other places under it.
29
31
  - Low-severity findings are not inline; they appear in the summary index.
30
32
  - Skip a finding (with a local reason) when it cannot be anchored reliably, its
31
33
  claim cannot be stated faithfully within the length limit, or an existing