opencode-azure-devops-pr-review 0.4.5 → 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.
@@ -1,7 +1,8 @@
1
1
  // Comment planning (model pages) and deterministic, idempotent publication.
2
- import { commentFindings, adjustmentInput, publicationItems, evaluatePlanPage, planRepairPrompt, assemblePlan, parseLocation, reviewVerification } from './comments.mjs';
2
+ import { commentFindings, adjustmentInput, publicationItems, evaluatePlanPage, planRepairPrompt, evaluateGrouping, groupingRepairPrompt, assemblePlan, parseLocation, placeOf, reviewVerification } from './comments.mjs';
3
3
  import { observationIndex, anchorObservations, compactDispositions, textPages, itemPages, PAGE_CHARACTERS } from './comment-data.mjs';
4
- import { markersInThreads, markerTexts, deletedThreads } from './azure.mjs';
4
+ import { markersInThreads, markerTexts, deletedThreads, threadMarkers } from './azure.mjs';
5
+ import { listedPlaces, listablePlace } from './attribution.mjs';
5
6
  import { parseModelJSON, syntaxProblem } from './output.mjs';
6
7
 
7
8
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -19,6 +20,9 @@ const evidenceKeys = evidence => [...new Set(evidence.map(item =>
19
20
 
20
21
  const MARKER = /<!-- azpr-comment:[a-f0-9]{32} -->/g;
21
22
  const INLINE_BUDGET = 40000;
23
+ // The findings of the grouping pass are always inline. Above this size they go without the evidence, and a
24
+ // list that is still larger is not grouped: the pass never gets a reference it would have to read first.
25
+ const GROUPING_BUDGET = 60000;
22
26
  // Up to this size the changed-file list and the dispositions are inline on every
23
27
  // planning page; above it a page carries those of its findings and a reference.
24
28
  const PAGE_CONTEXT_CHARACTERS = 2000;
@@ -33,13 +37,26 @@ export function discussionDigest(threads) {
33
37
  if (!comments.length) continue;
34
38
  const context = thread.threadContext ?? {};
35
39
  const first = comments[0];
40
+ // The places a thread covers are read only from the comment that opened it, as AZPR posts its
41
+ // comments (never as a reply), and only in the runtime's own form: a reply that quotes such a
42
+ // comment, marker and all, says nothing about the thread it is in. The opener is comment 1 of
43
+ // its thread, as publication takes it (`deletedThreads`), wherever it stands among the comments;
44
+ // when it is gone, no other comment stands for it. Where the comments carry no such number, it
45
+ // is the comment without a parent.
46
+ const numbered = thread.comments.some(comment => comment?.id === 1);
47
+ const opening = comments.find(comment => numbered ? comment.id === 1 : !(comment.parentCommentId > 0));
48
+ const alsoAt = context.filePath && opening?.content.match(MARKER) ? listedPlaces(opening.content) : [];
49
+ // What a thread is about is said by the comment that opened it, also when a reply comes first in the
50
+ // response: the author, the excerpt and the listed places are that one comment's.
51
+ const lead = opening ?? first;
36
52
  live.push({
37
53
  threadId: thread.id, status: thread.status ?? null,
38
54
  ...(context.filePath ? { path: context.filePath, line: context.rightFileStart?.line ?? context.leftFileStart?.line ?? null } : {}),
39
- author: first.author?.displayName ?? first.author?.uniqueName ?? null,
55
+ author: lead.author?.displayName ?? lead.author?.uniqueName ?? null,
40
56
  comments: comments.length,
41
57
  azpr: comments.some(comment => comment.content.match(MARKER)),
42
- excerpt: first.content.replace(MARKER, '').replace(/\s+/g, ' ').trim().slice(0, 300),
58
+ excerpt: lead.content.replace(MARKER, '').replace(/\s+/g, ' ').trim().slice(0, 300),
59
+ ...(alsoAt.length ? { alsoAt } : {}),
43
60
  });
44
61
  }
45
62
  return live;
@@ -70,6 +87,73 @@ export function mergeCandidates(findings, limit = PLANNING_FINDINGS_PER_PAGE) {
70
87
  return [...groups.values()].filter(ids => ids.length > 1 && ids.length <= limit);
71
88
  }
72
89
 
90
+ /**
91
+ * The findings that may share a comment as one defect made at several places:
92
+ * high and medium ones on lines of a HEAD file that the PR changes (`files`,
93
+ * when given), whose place a list can hold as it is. A quick finding that
94
+ * already is a merge candidate (the same lines, another session) is left to
95
+ * that rule. Whether the lines exist in the file is for the caller, which
96
+ * reads it (`prepareComments`).
97
+ */
98
+ export function repeatEligible(findings, duplicates = [], files = null) {
99
+ const taken = new Set(duplicates.flat());
100
+ const changed = files && new Set(files.map(path => path.startsWith('/') ? path : '/' + path));
101
+ return findings.filter(finding => {
102
+ const at = parseLocation(finding.location);
103
+ return ['high', 'medium'].includes(finding.severity) && finding.inline !== false && at?.side === 'head' && Boolean(at.start) && at.end >= at.start &&
104
+ (!changed || changed.has(at.path)) && listablePlace(placeOf(finding)) && !taken.has(finding.id);
105
+ });
106
+ }
107
+
108
+ /** Whether some two of these findings lie at different places (another file, or lines that share none). */
109
+ function twoPlaces(findings) {
110
+ const at = findings.map(finding => parseLocation(finding.location));
111
+ return at.some((x, index) => at.slice(index + 1).some(y => x.path !== y.path || x.start > y.end || y.start > x.end));
112
+ }
113
+
114
+ /**
115
+ * The sets of eligible findings that have one severity and lie at two places
116
+ * or more: only within such a set can one comment hold a repeated defect.
117
+ * Findings that all share lines are no such set.
118
+ */
119
+ export function severitySets(eligible) {
120
+ return ['high', 'medium'].map(level => eligible.filter(finding => finding.severity === level)).filter(twoPlaces).map(set => set.map(finding => finding.id));
121
+ }
122
+
123
+ /**
124
+ * The eligible findings that fit one planning page together with another one
125
+ * of their severity at a different place. A group shares a page
126
+ * (`boundedGroups`), so a finding without such a partner can be in no group
127
+ * that is used: with several pages nothing is read or asked for it.
128
+ */
129
+ export function pairable(eligible, size = PAGE_CHARACTERS) {
130
+ const sized = eligible.map(finding => ({ finding, at: parseLocation(finding.location), length: JSON.stringify(finding).length }));
131
+ const together = (a, b) => a !== b && a.finding.severity === b.finding.severity && a.length + b.length <= size &&
132
+ (a.at.path !== b.at.path || a.at.start > b.at.end || b.at.start > a.at.end);
133
+ return sized.filter(a => sized.some(b => together(a, b))).map(({ finding }) => finding);
134
+ }
135
+
136
+ /**
137
+ * Groups that fit a planning page's text: a larger one is split into
138
+ * consecutive parts of two or more findings, each planned as a group of its
139
+ * own, so that no place is dropped; a single finding left over stays alone.
140
+ */
141
+ export function boundedGroups(groups, findings, size = PAGE_CHARACTERS) {
142
+ const length = new Map(findings.map(finding => [finding.id, JSON.stringify(finding).length]));
143
+ const bounded = [];
144
+ for (const ids of groups) {
145
+ let part = [], characters = 0;
146
+ for (const id of ids) {
147
+ const own = length.get(id) ?? 0;
148
+ // A part that the next finding would overfill ends here; one finding alone is no part and is planned by itself.
149
+ if (part.length && characters + own > size) { if (part.length > 1) bounded.push(part); part = []; characters = 0; }
150
+ part.push(id); characters += own;
151
+ }
152
+ if (part.length > 1) bounded.push(part);
153
+ }
154
+ return bounded;
155
+ }
156
+
73
157
  /**
74
158
  * Planning pages that keep each candidate group on one page. A group that does
75
159
  * not fit a page by itself is planned as separate findings, never truncated.
@@ -100,10 +184,17 @@ export function candidatePages(findings, candidates, size = PAGE_CHARACTERS, max
100
184
  return { pages, offered };
101
185
  }
102
186
 
103
- /** Numbered source lines: the whole file when small, else a window around the lines. */
104
- export function sourceWindow(text, { start = null, end = null, context = 25, wholeFileLines = 400 } = {}) {
187
+ /** The lines of a text as `sourceWindow` numbers them: a line break at the end begins no line. */
188
+ const sourceLines = text => {
105
189
  const lines = String(text).replace(/\r\n/g, '\n').split('\n');
106
190
  if (lines.at(-1) === '') lines.pop();
191
+ return lines;
192
+ };
193
+ const lineTotal = text => sourceLines(text).length;
194
+
195
+ /** Numbered source lines: the whole file when small, else a window around the lines. */
196
+ export function sourceWindow(text, { start = null, end = null, context = 25, wholeFileLines = 400 } = {}) {
197
+ const lines = sourceLines(text);
107
198
  let first = 1, last = lines.length;
108
199
  if (lines.length > wholeFileLines) {
109
200
  if (start) { first = Math.max(1, start - context); last = Math.min(lines.length, (end ?? start) + context); }
@@ -145,6 +236,7 @@ async function planningInput(review, store, findings, report, work, continuation
145
236
  reviewWarnings: await store.pack(review.final.reviewWarnings ?? []),
146
237
  ...(needsEvidence ? { evidenceIndex: await observationIndex(store, review.toolText ?? []) } : {}),
147
238
  ...(extras.mergeCandidates?.length ? { mergeCandidates: extras.mergeCandidates } : {}),
239
+ ...(extras.repeatCandidates?.length ? { repeatCandidates: extras.repeatCandidates } : {}),
148
240
  // This page's own earlier reads; pages planned at the same time keep theirs.
149
241
  ...(continuation && extras.evidence?.length ? { workEvidence: await store.put(extras.evidence.map(item => JSON.stringify(item)).join('\n') + '\n', 'jsonl') } : {}),
150
242
  continuation: continuation ? await store.pack(continuation, 3000) : undefined,
@@ -164,22 +256,99 @@ async function planningInput(review, store, findings, report, work, continuation
164
256
  * After a page fails, no page or continuation session starts; stages already
165
257
  * running finish (with their repairs and retries) before the failure of the
166
258
  * lowest failed page is thrown.
259
+ * One defect made at several places is several findings. Which findings may
260
+ * be such repeats is settled before the pages are made, so that a group is on
261
+ * one page: when every finding fits one page, that page's findings of equal
262
+ * severity; otherwise what one grouping pass over the high and medium findings
263
+ * proposes (a stage of its own, with repair turns). A grouping pass that fails
264
+ * costs only the grouping: every finding is then planned on its own. `active`
265
+ * tells whether the run still goes on; a stopped run is never continued.
266
+ * A place is listed as its finding states it, so only a finding whose lines
267
+ * the file has, as `fetchSource` reads it at HEAD, can be one of several
268
+ * places: without that text nothing is offered. `posted` are the markers the
269
+ * PR already has, each with its thread (`markersInThreads`; null when
270
+ * unknown), for the page's rule that a comment for several places does not
271
+ * stand on lines that already carry a comment of AZPR's.
167
272
  * @param {(payload: object, handler: object) => Promise<object>} invoke
168
273
  */
169
- export async function prepareComments(review, store, invoke, { progress, fetchSource, discussions = null, parallel = PLANNING_PARALLEL_PAGES } = {}) {
274
+ export async function prepareComments(review, store, invoke, { progress, fetchSource, discussions = null, posted = null, parallel = PLANNING_PARALLEL_PAGES, active = () => true } = {}) {
170
275
  // Adjusted by a person after a preview, if they did; otherwise the publishable findings unchanged.
171
276
  const all = commentFindings(review);
172
277
  const adjustments = adjustmentInput(review);
173
278
  // Only a quick review, which has no verifier, offers candidate duplicates to the planner.
174
- const { pages: groups, offered } = candidatePages(all, reviewVerification(review) === 'none' ? mergeCandidates(all) : []);
175
- const reports = textPages(review.final.report ?? '');
176
- const count = Math.max(groups.length, reports.length, 1);
279
+ const twice = reviewVerification(review) === 'none' ? mergeCandidates(all) : [];
280
+ // Pages as they are without any repeated defect; they change only when the grouping pass proposes a group.
281
+ let paged = candidatePages(all, twice);
177
282
  const sourceText = new Map();
178
283
  const source = path => {
179
284
  if (!fetchSource) return Promise.resolve(null);
180
285
  if (!sourceText.has(path)) sourceText.set(path, Promise.resolve().then(() => fetchSource(path)).then(text => typeof text === 'string' ? text : null, () => null));
181
286
  return sourceText.get(path);
182
287
  };
288
+ // Only a finding whose lines the HEAD file has is offered as one of several places: a place is
289
+ // listed as the finding states it, and a file that is deleted or shorter has no such lines. The
290
+ // files are read only when findings could share a comment at all; the pages read them anyway.
291
+ // With several pages a group must share one: a finding that fits a page with no other one is left out here,
292
+ // so that no file is read ahead for it and it takes none of the grouping pass's input.
293
+ const usable = findings => paged.pages.length <= 1 ? findings : pairable(findings);
294
+ let eligible = usable(repeatEligible(all, twice, review.snapshot.files));
295
+ if (severitySets(eligible).length) {
296
+ // As many reads at a time as pages are planned, so that one preview never puts all its files
297
+ // ahead of what other conversations ask of Azure DevOps.
298
+ const paths = [...new Set(eligible.map(finding => parseLocation(finding.location).path))];
299
+ let next = 0;
300
+ const reader = async () => { while (next < paths.length && active()) await source(paths[next++]); };
301
+ await Promise.all(Array.from({ length: Math.min(paths.length, Number.isSafeInteger(parallel) && parallel > 1 ? parallel : 1) }, reader));
302
+ // A run that was stopped meanwhile reads no further file and plans nothing.
303
+ if (!active()) throw new Error('Comment planning was stopped.');
304
+ // Lines are counted once for a file, however many findings it holds.
305
+ const lineCounts = new Map();
306
+ for (const path of paths) {
307
+ const head = await source(path);
308
+ if (head !== null) lineCounts.set(path, lineTotal(head));
309
+ }
310
+ // A place the file does not have is none, which may leave another finding without its partner.
311
+ eligible = usable(eligible.filter(finding => (at => at.end <= (lineCounts.get(at.path) ?? 0))(parseLocation(finding.location))));
312
+ }
313
+ let repeats = [];
314
+ if (severitySets(eligible).length) {
315
+ // The pass reads its findings inline and needs no tool. A long list goes without the evidence, and one
316
+ // that is still too long is not grouped: no stored reference, which the pass would have to read first.
317
+ let listed = eligible.map(({ id, severity, location, summary, evidence, suggestion }) => ({ id, severity, location, summary, evidence, suggestion }));
318
+ if (JSON.stringify(listed).length > GROUPING_BUDGET) listed = listed.map(({ evidence: _long, ...short }) => short);
319
+ if (paged.pages.length <= 1) repeats = severitySets(eligible);
320
+ else if (JSON.stringify(listed).length > GROUPING_BUDGET) {
321
+ progress?.(`Planning comments: ${eligible.length} findings are too many to look through for one defect at several places; planning goes on without grouping them.`);
322
+ } else {
323
+ progress?.(`Planning comments: looking for one defect at several places (${eligible.length} findings)`);
324
+ try {
325
+ const grouped = await invoke({ reviewId: review.id, outputLanguage: review.outputLanguage, findings: listed, commentWork: { kind: 'group' } }, {
326
+ async evaluate(answer) {
327
+ const { result, issues, corrections } = evaluateGrouping(answer, { findings: eligible });
328
+ return { result: result && { ...result, corrections }, issues, repairPrompt: issues.length ? groupingRepairPrompt(issues, { parseOnly: !result && syntaxProblem(issues) }) : undefined };
329
+ },
330
+ async finalize(answer) {
331
+ const { result, corrections } = evaluateGrouping(answer, { findings: eligible, final: true });
332
+ return { ...result, corrections };
333
+ },
334
+ });
335
+ // A stop that arrived while the pass was ending: no page is prepared.
336
+ if (!active()) throw new Error('Comment planning was stopped.');
337
+ repeats = boundedGroups(grouped.groups, all);
338
+ if (repeats.length) paged = candidatePages(all, [...twice, ...repeats]);
339
+ } catch (error) {
340
+ if (!active() || error?.failureClass === 'cancelled') throw error;
341
+ repeats = [];
342
+ progress?.(`Planning comments: the grouping failed (${String(error?.message ?? error).slice(0, 200)}); planning goes on without grouping repeated places.`);
343
+ }
344
+ }
345
+ }
346
+ const { pages: groups, offered } = paged;
347
+ // On one page the findings of equal severity are offered as they are; otherwise the groups that a page keeps whole.
348
+ const kept = list => offered.filter(ids => list.some(group => group.length === ids.length && group.every(id => ids.includes(id))));
349
+ const offeredTwice = kept(twice), offeredRepeats = groups.length <= 1 ? repeats : kept(repeats);
350
+ const reports = textPages(review.final.report ?? '');
351
+ const count = Math.max(groups.length, reports.length, 1);
183
352
  async function excerpts(findings) {
184
353
  const windows = new Map();
185
354
  for (const finding of findings) {
@@ -213,15 +382,18 @@ export async function prepareComments(review, store, invoke, { progress, fetchSo
213
382
  progress?.(`Planning comments, page ${index + 1}/${count}`);
214
383
  do {
215
384
  const assigned = pending;
216
- // Groups whose findings are all still open on this page.
217
- const candidates = offered.filter(ids => ids.every(id => assigned.some(item => item.id === id)));
385
+ // Findings reported twice: groups whose findings are all still open on this page. One defect at
386
+ // several places: what is still open of each group, while two or more of its findings are.
387
+ const open = id => assigned.some(item => item.id === id);
388
+ const candidates = offeredTwice.filter(ids => ids.every(open));
389
+ const repeatCandidates = offeredRepeats.map(ids => ids.filter(open)).filter(ids => twoPlaces(ids.map(id => assigned.find(item => item.id === id))));
218
390
  const sourceExcerpts = await excerpts(assigned);
219
391
  // Only the first page writes the summary note; a note from another page is dropped.
220
392
  const allowSummary = index === 0 && !summaryWritten;
221
393
  const payload = await planningInput(review, store, assigned, report,
222
394
  { kind: 'plan', page: index + 1, pages: count, allowSummary,
223
395
  ...(reports[index] ? { reportRange: { start: reports[index].start, end: reports[index].end } } : {}) },
224
- continuation, { sourceExcerpts, discussions, reportSegments: reports.length, mergeCandidates: candidates, evidence: evidence(), adjustments });
396
+ continuation, { sourceExcerpts, discussions, reportSegments: reports.length, mergeCandidates: candidates, repeatCandidates, evidence: evidence(), adjustments });
225
397
  // Another page failed while this input was prepared: start no model work.
226
398
  if (failure) return parts;
227
399
  const scoped = async answer => {
@@ -235,13 +407,14 @@ export async function prepareComments(review, store, invoke, { progress, fetchSo
235
407
  }
236
408
  return { ...review, toolText: [...fetched, ...await anchorObservations(store, review.toolText ?? [], comments, review.snapshot.head)] };
237
409
  };
410
+ const options = { assigned, candidates, repeats: repeatCandidates, sources: sourceExcerpts, discussions, posted, allowSummary };
238
411
  const page = await invoke(payload, {
239
412
  async evaluate(answer) {
240
- const { result, issues, corrections } = evaluatePlanPage(answer, { review: await scoped(answer), assigned, candidates, sources: sourceExcerpts, discussions, allowSummary });
413
+ const { result, issues, corrections } = evaluatePlanPage(answer, { review: await scoped(answer), ...options });
241
414
  return { result: result && { ...result, corrections }, issues, repairPrompt: issues.length ? planRepairPrompt(issues, { parseOnly: !result && syntaxProblem(issues) }) : undefined };
242
415
  },
243
416
  async finalize(answer) {
244
- const { result, corrections } = evaluatePlanPage(answer, { review: await scoped(answer), assigned, final: true, candidates, sources: sourceExcerpts, discussions, allowSummary });
417
+ const { result, corrections } = evaluatePlanPage(answer, { review: await scoped(answer), ...options, final: true });
245
418
  return { ...result, corrections };
246
419
  },
247
420
  });
@@ -413,8 +586,11 @@ export async function publishPlan({ run, review, azure, attempts, progress, pers
413
586
  const status = succeeded === items.length ? 'POSTED' : succeeded ? 'PARTIALLY_POSTED' : 'FAILED';
414
587
  const uncertain = states.filter(state => state === 'UNCERTAIN').length;
415
588
  const reason = halted || (uncertain ? `${uncertain} item(s) may still be created by an earlier attempt whose outcome is unknown; they are not posted again until their marker appears or ${Math.round(settleMs / 60000)} minutes have passed since that attempt. Run the same command again later.` : undefined);
589
+ // The other AZPR comments on the PR, counted by thread: a comment for several places has two markers and
590
+ // a reply may quote another thread's, so a thread is another comment when none of the markers it holds is
591
+ // a marker of this preview. That does not depend on the order of the threads.
416
592
  const planned = new Set(items.map(item => item.marker));
417
593
  return { status, readBack, ...(reason ? { reason } : {}), ...(current.status !== 'active' ? { prStatus: current.status } : {}),
418
594
  counts: Object.fromEntries([...new Set(states)].map(state => [state, states.filter(s => s === state).length])),
419
- ...(compare ? { otherComments: [...present.keys()].filter(marker => !planned.has(marker)).length } : {}) };
595
+ ...(compare ? { otherComments: [...threadMarkers(listed).values()].filter(markers => ![...markers].some(marker => planned.has(marker))).length } : {}) };
420
596
  }