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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/comments.mjs CHANGED
@@ -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,37 +25,90 @@ 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 };
56
107
  }
57
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
+
58
112
  /** A finding's place as a comment lists it: "/src/a.ts:12-14". */
59
113
  export function placeOf(finding) {
60
114
  const at = parseLocation(finding.location);
@@ -115,12 +169,13 @@ export function repeatProblems(members) {
115
169
  return { problems };
116
170
  }
117
171
 
118
- // A finding ID as a text names it (F-1, Q-1001, V-2).
119
- const FINDING_ID = /(?<![A-Za-z0-9_-])[A-Za-z]+-\d+(?!\d)/g;
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;
120
175
 
121
176
  /**
122
- * Other findings of this review that a skip reason names. The verifier already
123
- * 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.
124
179
  */
125
180
  function citedFindings(reason, own, findingIds) {
126
181
  const named = String(reason).match(FINDING_ID) ?? [];
@@ -246,7 +301,7 @@ export function commentToken(review) {
246
301
  * they are now (`commentToken`), which a command picked from this offer hands back. Undefined for a review
247
302
  * with more findings than the panel lists: half a list would let a person replace adjustments they cannot see.
248
303
  */
249
- export function previewActions(review, { held = false } = {}) {
304
+ export function previewActions(review, { held = false, plannable = true } = {}) {
250
305
  const findings = publishableFindings(review);
251
306
  if (findings.length > ACTION_FINDINGS) return undefined;
252
307
  const { excluded, severity } = adjustmentsOf(review);
@@ -255,10 +310,11 @@ export function previewActions(review, { held = false } = {}) {
255
310
  review: review.id,
256
311
  state: commentToken(review),
257
312
  target: describeReview(review),
258
- 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,
259
315
  publish: Boolean(review.plan) && !held && !everyFindingExcluded(review),
260
316
  posts: publicationItems(review.plan).length,
261
- adjust: !publicationStarted(review),
317
+ adjust: !publicationStarted(review) && plannable,
262
318
  findings: findings.map(finding => ({
263
319
  id: finding.id,
264
320
  severity: Object.hasOwn(severity, finding.id) ? severity[finding.id] : finding.severity,
@@ -284,10 +340,14 @@ export function resolveAdjustments(review, { exclude, severity, reset = false })
284
340
  const findings = publishableFindings(review);
285
341
  const byId = new Map(findings.map(finding => [finding.id, finding]));
286
342
  const problems = [];
343
+ const rows = review.final?.dispositions ?? [];
287
344
  const check = id => {
288
345
  if (byId.has(id)) return;
289
- const row = (review.final?.dispositions ?? []).find(item => item.id === id);
290
- 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`
291
351
  : row ? `${id} is ${row.status}, not a finding this review can publish` : `${id} is not a finding of review ${review.id}`);
292
352
  };
293
353
  for (const id of [...(exclude ?? []), ...Object.keys(severity ?? {})]) check(id);
@@ -381,8 +441,23 @@ export function describeEarlierText(review, otherComments = 0) {
381
441
  * change. Only IDs written as the runtime writes them are found. Returns
382
442
  * readable rows; [] when nothing names an excluded finding.
383
443
  */
384
- 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) {
385
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);
386
461
  if (!excluded.size || !review?.plan) return [];
387
462
  const rows = [];
388
463
  for (const item of publicationItems(review.plan)) {
@@ -712,7 +787,10 @@ export function restoreAnchor(comment, review) {
712
787
  });
713
788
  const declared = new Map();
714
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.
715
792
  const lines = observation.output.split(/\r?\n/, comment.endLine + 1);
793
+ if (lines.at(-1) === '' && lines.length <= comment.endLine) lines.pop();
716
794
  const selected = lines.slice(comment.startLine - 1, comment.endLine), anchor = selected.join('\n');
717
795
  if (selected.length === count && forms.has(trim(anchor))) declared.set(JSON.stringify([anchor]), { anchor, startLine: comment.startLine, endLine: comment.endLine });
718
796
  }
@@ -907,12 +985,12 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
907
985
  status = 'READY';
908
986
  }
909
987
  const eligible = new Map(assigned.map(finding => [finding.id, finding]));
910
- // Findings a person excluded after a preview: no published text may name them.
911
- 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);
912
990
  const changed = new Set(review.snapshot.files.map(path => path.startsWith('/') ? path : '/' + path));
913
- // Quick findings were not independently verified: an inline comment needs a
914
- // checked location and an anchor found in source text the runtime read.
915
- 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';
916
994
  const comments = [], skipped = [], handled = new Set(), reported = new Set(), refusedCombinations = [];
917
995
  const skip = (findingId, reason, extra = {}) => { if (!handled.has(findingId)) { handled.add(findingId); skipped.push({ findingId, reason, ...extra }); } };
918
996
  // A location that can carry an inline comment: on a changed HEAD file whose text the page shows.
@@ -924,7 +1002,7 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
924
1002
  // Body, path and anchor of one inline comment; `lines` bounds the anchor of a combined comment.
925
1003
  function draft(c, label, severity, lines) {
926
1004
  const problems = [];
927
- 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 });
928
1006
  const body = nonempty(c.body) ? escapeComments(normalizeTitle(c.body, severity)) : '';
929
1007
  if (!body) problems.push('body is empty');
930
1008
  else if (body.length > INLINE_SOFT_LIMIT && !final) problems.push(`body is ${body.length} characters; keep it within ${INLINE_SOFT_LIMIT}`);
@@ -953,7 +1031,7 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
953
1031
  restored = restoreAnchor({ path, startLine, endLine, anchor }, review);
954
1032
  if (restored.startLine !== startLine) corrections.push({ action: 'restore-anchor-location', findingId: label, from: startLine, to: restored.startLine });
955
1033
  if (restored.ambiguous && !final) problems.push('the anchor text appears several times in the observed source; quote more lines to make it unique');
956
- 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');
957
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`);
958
1036
  }
959
1037
  if (problems.length) return { problems };
@@ -969,9 +1047,9 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
969
1047
  const members = ids.map(id => eligible.get(id));
970
1048
  const problems = [];
971
1049
  const listed = group => ids.every(id => group.includes(id));
972
- const twice = quick && candidates.some(listed), repeated = !twice && repeats.some(listed);
1050
+ const twice = unverified && candidates.some(listed), repeated = !twice && repeats.some(listed);
973
1051
  let lines;
974
- if (!(quick && candidates.length) && !repeats.length) problems.push('findingIds may combine only the findings of one listed group (mergeCandidates or repeatCandidates)');
1052
+ if (!(unverified && candidates.length) && !repeats.length) problems.push('findingIds may combine only the findings of one listed group (mergeCandidates or repeatCandidates)');
975
1053
  else if (members.some(member => !member)) problems.push(`${ids.filter(id => !eligible.has(id)).join(', ')} not assigned to this page`);
976
1054
  else if (!twice && !repeated) problems.push('the findings are not all in one listed group (mergeCandidates or repeatCandidates)');
977
1055
  else if (members.some(member => handled.has(member.id))) problems.push('a combined finding already has a comment or skip');
@@ -995,7 +1073,7 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
995
1073
  problems.push(...drafted.problems);
996
1074
  // Where the comment stands follows from the lines it quotes, so they must be lines the file has:
997
1075
  // 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).
1076
+ // ends within the file (where the file's line count is known, it is checked below as well).
999
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');
1000
1078
  // (An anchor in a file that holds none of the findings is refused below, where the place is looked for.)
1001
1079
  // The list follows the body: a block the body leaves open would take it in.
@@ -1063,6 +1141,11 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
1063
1141
  continue;
1064
1142
  }
1065
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`);
1066
1149
  // A comment for one place is not put on quoted lines that carry a comment for several places.
1067
1150
  const taken = !problems.length && posted ? occupiedLines(review.target, comment, posted) : '';
1068
1151
  if (taken) problems.push(`${taken}. Skip ${finding.id} with cause existing-thread when that thread covers it, or quote other lines`);
@@ -1082,9 +1165,11 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
1082
1165
  const reason = nonempty(s.reason) ? s.reason.trim() : 'Skipped by the comment planner without a stated reason.';
1083
1166
  const cited = citedFindings(reason, s.findingId, findingIds);
1084
1167
  if (cited.length && !final) {
1085
- issues.push(quick
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'
1086
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).`
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).`);
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).`);
1088
1173
  reported.add(s.findingId);
1089
1174
  continue;
1090
1175
  }