opencode-azure-devops-pr-review 0.2.3 → 0.3.1

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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "opencode-azure-devops-pr-review",
3
- "version": "0.2.3",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
- "description": "Azure DevOps PR reviews from a URL in OpenCode, with no checkout, configurable models, separate verification, and comment previews",
5
+ "description": "Azure DevOps PR reviews from a URL in OpenCode, with no checkout, configurable models, separate verification, and comment previews you can adjust before posting",
6
6
  "scripts": {
7
7
  "test": "node --test tests/*.test.mjs",
8
8
  "check": "node --check src/session.mjs && node --check src/runtime.mjs && node --check src/comment-data.mjs && node --check src/comment-work.mjs && node --check src/comments.mjs && node --check src/config.mjs && node --check src/output.mjs && node --check src/diagnostics.mjs && node --check src/attribution.mjs && node --check src/host.mjs && node --check src/tool-queue.mjs && node --check src/azure.mjs && node --check src/diff.mjs && node --check src/search.mjs && node --check src/review-tools.mjs && node --check src/review-work.mjs && node --check src/store.mjs && node --check src/plugin.js && node --check src/setup.mjs && node --check server.js && sh -n install.sh && sh -n uninstall.sh"
@@ -44,6 +44,7 @@
44
44
  "docs/",
45
45
  "AGENTS.md",
46
46
  "CONTRIBUTING.md",
47
+ "CODE_OF_CONDUCT.md",
47
48
  "SECURITY.md"
48
49
  ],
49
50
  "publishConfig": {
@@ -236,7 +236,7 @@ export function renderCheckReport(snapshot, checks, readiness) {
236
236
  /** Publication ledger rows for receipts. */
237
237
  export function renderPublication(review, result) {
238
238
  const rows = [...(review.publication ?? new Map()).values()].map(entry =>
239
- `- ${entry.kind === 'summary' ? 'PR summary' : `${(entry.findingIds ?? [entry.findingId]).join(', ')} (${entry.path}:${entry.startLine})`}: ${entry.state}${entry.threadId ? `; thread=${entry.threadId}` : ''}${entry.error ? `; error=${entry.error}` : ''}${entry.contentMismatch ? '; returned text differs' : ''}`).join('\n');
239
+ `- ${entry.kind === 'summary' ? 'PR summary' : `${(entry.findingIds ?? [entry.findingId]).join(', ')} (${entry.path}:${entry.startLine})`}: ${entry.state}${entry.threadId ? `; thread=${entry.threadId}` : ''}${entry.error ? `; error=${entry.error}` : ''}${entry.contentMismatch ? '; returned text differs' : ''}${entry.earlierText ? '; the PR keeps its earlier text' : ''}`).join('\n');
240
240
  const counts = result?.counts ? Object.entries(result.counts).map(([state, count]) => `${state}=${count}`).join(', ') : '';
241
241
  return `Publication${counts ? ` (${counts})` : ''}${result?.readBack && result.readBack !== 'complete' ? `; read-back ${result.readBack}` : ''}:\n${rows || '- Nothing recorded.'}\n\nPOSTED/VERIFIED entries were created by AZPR and VERIFIED ones were read back from Azure DevOps. ALREADY_PRESENT entries existed before this run. DELETED entries were created by AZPR and later deleted on the PR; AZPR does not post them again. FAILED entries are safe to retry with /pr-comment ${review.id} --publish; existing comments are skipped by their markers. UNVERIFIED entries were created but not found when read back; a re-run checks them again and never posts them twice. UNCERTAIN entries may still appear from an earlier attempt and are retried only after their marker check settles.`;
242
242
  }
package/src/azure.mjs CHANGED
@@ -52,6 +52,21 @@ const clean = value => String(value ?? '').replace(/[\x00-\x1f\x7f]+/g, ' ').rep
52
52
  export const normalizePath = path => (path.startsWith('/') ? path : '/' + path);
53
53
  export const isCommitSha = sha;
54
54
 
55
+ /** An organization name as given, or the organization of an HTTPS dev.azure.com/<org>/… or <org>.visualstudio.com URL. */
56
+ export function organizationName(raw) {
57
+ if (typeof raw !== 'string' || !/^https?:\/\//i.test(raw.trim())) return raw;
58
+ let url;
59
+ try { url = new URL(raw.trim()); } catch { url = null; }
60
+ if (!url || url.protocol !== 'https:' || url.username || url.password || url.port) {
61
+ throw new Error('[AZPR] Use an organization name, or an HTTPS Azure DevOps URL without credentials or a custom port.');
62
+ }
63
+ if (url.hostname.toLowerCase() === 'dev.azure.com') {
64
+ try { return decodeURIComponent(url.pathname.split('/').filter(Boolean)[0] ?? ''); } catch { return ''; }
65
+ }
66
+ if (/^[a-z0-9-]+\.visualstudio\.com$/i.test(url.hostname)) return url.hostname.split('.')[0];
67
+ throw new Error('[AZPR] Only dev.azure.com and <organization>.visualstudio.com URLs name an organization.');
68
+ }
69
+
55
70
  /**
56
71
  * Parse an Azure DevOps Services PR URL. Only cloud URLs are supported; the
57
72
  * REST client always talks to dev.azure.com/<organization>.
@@ -220,6 +235,21 @@ export function markersInThreads(threads) {
220
235
  return found;
221
236
  }
222
237
 
238
+ /** The text of the live comment that carries each marker, found as markersInThreads finds its thread. */
239
+ export function markerTexts(threads) {
240
+ const found = new Map();
241
+ for (const thread of threads) {
242
+ if (thread?.isDeleted === true) continue;
243
+ for (const comment of Array.isArray(thread?.comments) ? thread.comments : []) {
244
+ if (comment?.isDeleted === true || typeof comment?.content !== 'string') continue;
245
+ for (const match of comment.content.matchAll(MARKER_PATTERN)) {
246
+ if (!found.has(match[0])) found.set(match[0], comment.content);
247
+ }
248
+ }
249
+ }
250
+ return found;
251
+ }
252
+
223
253
  /**
224
254
  * IDs of threads whose first comment, the one AZPR posts when it creates a
225
255
  * thread, was deleted on the PR. Azure DevOps keeps listing such a thread
@@ -302,7 +332,7 @@ export function createAzureClient({ organization, pat, baseUrl = DEFAULT_BASE_UR
302
332
  function intermediaryFailure(status, label, method, forwarded = true) {
303
333
  if (status === 407) {
304
334
  return new AzureError(`A proxy refused ${label}: it requires authentication (HTTP 407).`, { kind: 'proxy', status,
305
- hint: 'Put the proxy user name and password in azure.proxy (http://user:password@host:port, percent-encoded) and restart OpenCode.' });
335
+ hint: 'Put the proxy user name and password in azure.proxy (http://user:password@host:port, percent-encoded) and restart the OpenCode service (opencode service restart).' });
306
336
  }
307
337
  // A gateway that already forwarded a write may have delivered it.
308
338
  return new AzureError(`A proxy or gateway answered ${label} with HTTP ${status} instead of Azure DevOps (no Azure DevOps response headers).`, {
@@ -317,7 +347,7 @@ export function createAzureClient({ organization, pat, baseUrl = DEFAULT_BASE_UR
317
347
  const detail = clean(body?.message);
318
348
  const suffix = `${code ? ` ${code}` : ''}${detail ? `: ${detail}` : ''}`;
319
349
  if (status === 203 || status === 401 || (status >= 300 && status < 400)) {
320
- return new AzureError(`Azure DevOps rejected the PAT for organization "${organization}" (HTTP ${status}). Check that the PAT (azure.pat, or the file named by azure.patFile) is valid, not expired and created for this organization, then restart OpenCode.`, { kind: 'auth', status });
350
+ return new AzureError(`Azure DevOps rejected the PAT for organization "${organization}" (HTTP ${status}). Check that the PAT (azure.pat, or the file named by azure.patFile) is valid, not expired and created for this organization, then restart the OpenCode service (opencode service restart).`, { kind: 'auth', status });
321
351
  }
322
352
  if (status === 403) return new AzureError(`Azure DevOps refused ${label} (HTTP 403${suffix}). The PAT needs Code (Read) and Pull Request Threads (Read & write) for this organization.`, { kind: 'permission', status, code });
323
353
  if (status === 404) return new AzureError(`Azure DevOps could not find ${label} (HTTP 404${suffix}).`, { kind: 'not-found', status, code });
@@ -352,7 +382,7 @@ export function createAzureClient({ organization, pat, baseUrl = DEFAULT_BASE_UR
352
382
  // A rejected certificate fails the handshake before anything is sent; retrying cannot help.
353
383
  if (CERTIFICATE_CODES.test(known)) {
354
384
  throw new AzureError(`Azure DevOps ${label} failed: the server's TLS certificate was not accepted (${clean(known)}).`, { kind: 'tls', code: known, cause: error,
355
- hint: 'If a proxy inspects HTTPS, set azure.caFile to its root CA certificate (PEM) and restart OpenCode.' });
385
+ hint: 'If a proxy inspects HTTPS, set azure.caFile to its root CA certificate (PEM) and restart the OpenCode service (opencode service restart).' });
356
386
  }
357
387
  throw new AzureError(`Azure DevOps ${label} failed: network error${code ? ` (${clean(code)})` : ''}.`, { kind: 'network', transient: true, cause: error,
358
388
  uncertain: method !== 'GET' && !NOT_SENT_CODES.test(known),
@@ -1,7 +1,7 @@
1
1
  // Comment planning (model pages) and deterministic, idempotent publication.
2
- import { publishableFindings, publicationItems, evaluatePlanPage, planRepairPrompt, assemblePlan, parseLocation, reviewVerification } from './comments.mjs';
2
+ import { commentFindings, adjustmentInput, publicationItems, evaluatePlanPage, planRepairPrompt, assemblePlan, parseLocation, reviewVerification } from './comments.mjs';
3
3
  import { observationIndex, anchorObservations, compactDispositions, textPages, itemPages, PAGE_CHARACTERS } from './comment-data.mjs';
4
- import { markersInThreads, deletedThreads } from './azure.mjs';
4
+ import { markersInThreads, markerTexts, deletedThreads } from './azure.mjs';
5
5
  import { parseModelJSON, syntaxProblem } from './output.mjs';
6
6
 
7
7
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -131,6 +131,8 @@ async function planningInput(review, store, findings, report, work, continuation
131
131
  description: await store.pack(description ?? '', 3000) },
132
132
  outputLanguage: review.outputLanguage,
133
133
  findings,
134
+ // Only when a person adjusted the findings after a preview; the input is otherwise unchanged.
135
+ ...(extras.adjustments ? { adjustments: extras.adjustments } : {}),
134
136
  // Runtime-read HEAD source around each finding; anchors can come straight from here.
135
137
  sourceExcerpts: await store.pack(sources, INLINE_BUDGET),
136
138
  // Every live thread on the PR, read by the runtime when planning started.
@@ -165,7 +167,9 @@ async function planningInput(review, store, findings, report, work, continuation
165
167
  * @param {(payload: object, handler: object) => Promise<object>} invoke
166
168
  */
167
169
  export async function prepareComments(review, store, invoke, { progress, fetchSource, discussions = null, parallel = PLANNING_PARALLEL_PAGES } = {}) {
168
- const all = publishableFindings(review);
170
+ // Adjusted by a person after a preview, if they did; otherwise the publishable findings unchanged.
171
+ const all = commentFindings(review);
172
+ const adjustments = adjustmentInput(review);
169
173
  // Only a quick review, which has no verifier, offers candidate duplicates to the planner.
170
174
  const { pages: groups, offered } = candidatePages(all, reviewVerification(review) === 'none' ? mergeCandidates(all) : []);
171
175
  const reports = textPages(review.final.report ?? '');
@@ -217,7 +221,7 @@ export async function prepareComments(review, store, invoke, { progress, fetchSo
217
221
  const payload = await planningInput(review, store, assigned, report,
218
222
  { kind: 'plan', page: index + 1, pages: count, allowSummary,
219
223
  ...(reports[index] ? { reportRange: { start: reports[index].start, end: reports[index].end } } : {}) },
220
- continuation, { sourceExcerpts, discussions, reportSegments: reports.length, mergeCandidates: candidates, evidence: evidence() });
224
+ continuation, { sourceExcerpts, discussions, reportSegments: reports.length, mergeCandidates: candidates, evidence: evidence(), adjustments });
221
225
  // Another page failed while this input was prepared: start no model work.
222
226
  if (failure) return parts;
223
227
  const scoped = async answer => {
@@ -310,8 +314,12 @@ export const UNCERTAIN_SETTLE_MS = 15 * 60 * 1000;
310
314
  * comment was deleted on the PR is DELETED: settled, and never sent again.
311
315
  * - With `only` (a set of markers), handles just those items; the others stay
312
316
  * in the saved plan for a later publication.
317
+ * - With `compare` (a review a person adjusted), an item already on the PR
318
+ * with other text is still skipped, marked `earlierText`: the PR keeps that
319
+ * earlier version, since nothing posted is ever changed. The result then
320
+ * counts the other AZPR comments on the PR (`otherComments`).
313
321
  */
314
- export async function publishPlan({ run, review, azure, attempts, progress, persist, now = () => Date.now(), settleMs = UNCERTAIN_SETTLE_MS, only }) {
322
+ export async function publishPlan({ run, review, azure, attempts, progress, persist, now = () => Date.now(), settleMs = UNCERTAIN_SETTLE_MS, only, compare = false }) {
315
323
  const items = publicationItems(review.plan).filter(item => !only || only.has(item.marker));
316
324
  const ledger = review.publication ??= new Map();
317
325
  const current = await azure.versions(run, review.snapshot);
@@ -319,7 +327,9 @@ export async function publishPlan({ run, review, azure, attempts, progress, pers
319
327
  if (current.head !== review.snapshot.head) {
320
328
  return { status: 'STALE', reason: `The PR source commit changed after the review (reviewed ${review.snapshot.head.slice(0, 12)}, current ${current.head.slice(0, 12)}). Run a new review before commenting.` };
321
329
  }
322
- const present = markersInThreads(await azure.threads(run, review.snapshot));
330
+ const listed = await azure.threads(run, review.snapshot);
331
+ const present = markersInThreads(listed);
332
+ const texts = compare ? markerTexts(listed) : null;
323
333
  const at = () => new Date(now()).toISOString();
324
334
  const record = (item, entry) => ledger.set(item.marker, {
325
335
  ...(item.kind === 'summary' ? { kind: 'summary' } : { kind: 'inline', findingId: item.findingId, ...(item.findingIds ? { findingIds: item.findingIds } : {}), path: item.path, startLine: item.startLine }),
@@ -334,7 +344,10 @@ export async function publishPlan({ run, review, azure, attempts, progress, pers
334
344
  let written = 0, halted = '';
335
345
  for (const [index, item] of items.entries()) {
336
346
  if (!run.active) throw new Error(run.reason || 'Publication stopped.');
337
- if (present.has(item.marker)) { record(item, { state: 'ALREADY_PRESENT', threadId: present.get(item.marker) }); continue; }
347
+ if (present.has(item.marker)) {
348
+ record(item, { state: 'ALREADY_PRESENT', threadId: present.get(item.marker), ...(texts && texts.get(item.marker) !== item.content ? { earlierText: true } : {}) });
349
+ continue;
350
+ }
338
351
  if (halted) { record(item, { state: 'FAILED', error: halted }); continue; }
339
352
  const earlier = attempts.get(item.marker);
340
353
  if (earlier?.state === 'CREATED') {
@@ -377,10 +390,16 @@ export async function publishPlan({ run, review, azure, attempts, progress, pers
377
390
  try {
378
391
  const listedAfter = await azure.threads(run, review.snapshot);
379
392
  const after = markersInThreads(listedAfter), removedAfter = deletedThreads(listedAfter);
393
+ const textsAfter = compare ? markerTexts(listedAfter) : null;
380
394
  for (const item of items) {
381
395
  const entry = ledger.get(item.marker);
382
396
  if (!['POSTED', 'UNCERTAIN', 'FAILED'].includes(entry.state)) continue;
383
- if (after.has(item.marker)) Object.assign(entry, { state: 'VERIFIED', threadId: after.get(item.marker) });
397
+ if (after.has(item.marker)) {
398
+ // A comment this run did not create (an earlier attempt's, or one the first list did not show yet,
399
+ // also after a refused write) keeps its own text.
400
+ const earlierText = textsAfter && (entry.state !== 'POSTED' || entry.earlierAttempt) && textsAfter.get(item.marker) !== item.content;
401
+ Object.assign(entry, { state: 'VERIFIED', threadId: after.get(item.marker), ...(earlierText ? { earlierText: true } : {}) });
402
+ }
384
403
  else if (entry.state === 'POSTED') entry.state = removedAfter.has(entry.threadId) ? 'DELETED' : 'UNVERIFIED';
385
404
  }
386
405
  } catch (error) {
@@ -393,5 +412,7 @@ export async function publishPlan({ run, review, azure, attempts, progress, pers
393
412
  const status = succeeded === items.length ? 'POSTED' : succeeded ? 'PARTIALLY_POSTED' : 'FAILED';
394
413
  const uncertain = states.filter(state => state === 'UNCERTAIN').length;
395
414
  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);
396
- return { status, readBack, ...(reason ? { reason } : {}), counts: Object.fromEntries([...new Set(states)].map(state => [state, states.filter(s => s === state).length])) };
415
+ const planned = new Set(items.map(item => item.marker));
416
+ return { status, readBack, ...(reason ? { reason } : {}), counts: Object.fromEntries([...new Set(states)].map(state => [state, states.filter(s => s === state).length])),
417
+ ...(compare ? { otherComments: [...present.keys()].filter(marker => !planned.has(marker)).length } : {}) };
397
418
  }
package/src/comments.mjs CHANGED
@@ -78,15 +78,123 @@ export function combinationProblems(members) {
78
78
  return { problems, lines };
79
79
  }
80
80
 
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;
83
+
81
84
  /**
82
85
  * Other findings of this review that a skip reason names. The verifier already
83
86
  * merged duplicates, so another finding's comment never covers a finding.
84
87
  */
85
88
  function citedFindings(reason, own, findingIds) {
86
- const named = String(reason).match(/(?<![A-Za-z0-9_-])[A-Za-z]+-\d+(?!\d)/g) ?? [];
89
+ const named = String(reason).match(FINDING_ID) ?? [];
87
90
  return [...new Set(named)].filter(id => id !== own && findingIds.has(id));
88
91
  }
89
92
 
93
+ /**
94
+ * A person's adjustments of a review's findings after a preview, as saved in
95
+ * `review.adjustments`: findings `excluded` from publication and a changed
96
+ * `severity` per finding ID. A review saved without them has none.
97
+ */
98
+ function adjustmentsOf(review) {
99
+ const saved = review?.adjustments;
100
+ const excluded = Array.isArray(saved?.excluded) ? saved.excluded : [];
101
+ const severity = isObject(saved?.severity) ? saved.severity : {};
102
+ return { excluded, severity, active: excluded.length > 0 || Object.keys(severity).length > 0 };
103
+ }
104
+
105
+ export const hasAdjustments = review => adjustmentsOf(review).active;
106
+
107
+ /**
108
+ * Whether a person ever adjusted the review's findings, also when --reset
109
+ * cleared them since: such a review is posted only from a preview planned
110
+ * after its latest adjustment, exactly as that preview reads.
111
+ */
112
+ export const everAdjusted = review => isObject(review?.adjustments);
113
+
114
+ /**
115
+ * The findings comments are planned for: publishableFindings as a person
116
+ * adjusted them after a preview, without the excluded ones and with the
117
+ * changed severities. Without adjustments, exactly publishableFindings(review).
118
+ */
119
+ export function commentFindings(review) {
120
+ const findings = publishableFindings(review);
121
+ const { excluded, severity, active } = adjustmentsOf(review);
122
+ if (!active) return findings;
123
+ const left = new Set(excluded);
124
+ return findings.filter(finding => !left.has(finding.id))
125
+ .map(finding => Object.hasOwn(severity, finding.id) ? { ...finding, severity: severity[finding.id] } : finding);
126
+ }
127
+
128
+ /** Whether a person excluded every finding the review could publish, so there is nothing to post. */
129
+ export function everyFindingExcluded(review) {
130
+ return adjustmentsOf(review).excluded.length > 0 && publishableFindings(review).length > 0 && commentFindings(review).length === 0;
131
+ }
132
+
133
+ const ADJUSTMENT_RULE = 'A person read the comment preview and adjusted these findings. An excluded finding is not published: never name, describe or allude to it in a comment, the summary note or summaryDetails, also where the report or dispositions discuss it. A changed severity is final and `findings` already carries it: write and title each comment for that severity.';
134
+
135
+ /** What the comment planner is told about a person's adjustments; undefined without them, so its input stays unchanged. */
136
+ export function adjustmentInput(review) {
137
+ const { excluded, severity, active } = adjustmentsOf(review);
138
+ if (!active) return undefined;
139
+ const original = new Map(publishableFindings(review).map(finding => [finding.id, finding.severity]));
140
+ const changes = Object.entries(severity).map(([id, to]) => ({ id, from: original.get(id), to }));
141
+ return { ...(excluded.length ? { excludedFindings: excluded } : {}), ...(changes.length ? { severityChanges: changes } : {}), rule: ADJUSTMENT_RULE };
142
+ }
143
+
144
+ /** How a preview states a person's adjustments; '' without them. Nothing of this reaches the PR. */
145
+ export function describeAdjustments(review) {
146
+ const { excluded, severity, active } = adjustmentsOf(review);
147
+ if (!active) return '';
148
+ const original = new Map(publishableFindings(review).map(finding => [finding.id, finding.severity]));
149
+ const rows = [...(excluded.length ? [`- Excluded from publication: ${excluded.join(', ')}`] : []),
150
+ ...Object.entries(severity).map(([id, to]) => `- ${id}: severity ${original.get(id)} → ${to}`)];
151
+ return `Adjusted by a person after the preview (not stated on the PR):\n${rows.join('\n')}`;
152
+ }
153
+
154
+ /**
155
+ * Apply a /pr-comment adjustment request to a review. `exclude` and `severity`
156
+ * each replace their whole list when given (empty: none); `reset` clears both.
157
+ * Every ID must name a finding this review can publish (a merged duplicate
158
+ * points to the finding it was merged into). The list a request names wins
159
+ * over the kept other one: excluding a finding drops its severity change, and
160
+ * a severity for an excluded finding restores it; naming one finding in both
161
+ * lists is refused. A severity equal to the review's is no change. Throws,
162
+ * changing nothing, on any problem. Returns the adjustments to save
163
+ * (`next`), what changes (`changes`, readable rows) and `unchanged`.
164
+ */
165
+ export function resolveAdjustments(review, { exclude, severity, reset = false }) {
166
+ const findings = publishableFindings(review);
167
+ const byId = new Map(findings.map(finding => [finding.id, finding]));
168
+ const problems = [];
169
+ const check = id => {
170
+ if (byId.has(id)) return;
171
+ const row = (review.final?.dispositions ?? []).find(item => item.id === id);
172
+ problems.push(row?.status === 'MERGED' && row.mergedInto ? `${id} was merged into ${row.mergedInto}; adjust ${row.mergedInto} instead`
173
+ : row ? `${id} is ${row.status}, not a finding this review can publish` : `${id} is not a finding of review ${review.id}`);
174
+ };
175
+ for (const id of [...(exclude ?? []), ...Object.keys(severity ?? {})]) check(id);
176
+ for (const id of exclude ?? []) if (severity && Object.hasOwn(severity, id)) problems.push(`${id} cannot be excluded and given a severity at once`);
177
+ if (problems.length) throw new Error(`[AZPR] Nothing was changed: ${[...new Set(problems)].join('; ')}. Findings of review ${review.id} you can adjust: ${[...byId.keys()].join(', ') || 'none'}.`);
178
+ const current = adjustmentsOf(review);
179
+ let excluded = reset ? [] : exclude ?? current.excluded;
180
+ const changed = reset ? {} : { ...(severity ?? current.severity) };
181
+ if (exclude && !severity) for (const id of exclude) delete changed[id];
182
+ if (severity && !exclude) excluded = excluded.filter(id => !Object.hasOwn(severity, id));
183
+ for (const [id, level] of Object.entries(changed)) if (byId.get(id)?.severity === level) delete changed[id];
184
+ const order = id => findings.findIndex(finding => finding.id === id);
185
+ const next = { excluded: [...new Set(excluded)].sort((a, b) => order(a) - order(b)),
186
+ severity: Object.fromEntries(Object.entries(changed).sort(([a], [b]) => order(a) - order(b))) };
187
+ const before = new Set(current.excluded), after = new Set(next.excluded);
188
+ const level = (adjustments, id) => adjustments.severity[id] ?? byId.get(id)?.severity;
189
+ const changes = [
190
+ ...next.excluded.filter(id => !before.has(id)).map(id => `excluded ${id}`),
191
+ ...current.excluded.filter(id => !after.has(id)).map(id => `restored ${id}`),
192
+ ...[...new Set([...Object.keys(current.severity), ...Object.keys(next.severity)])].sort((a, b) => order(a) - order(b))
193
+ .filter(id => !after.has(id) && level(current, id) !== level(next, id)).map(id => `${id} severity ${level(current, id)} → ${level(next, id)}`),
194
+ ];
195
+ return { next, changes, unchanged: changes.length === 0 };
196
+ }
197
+
90
198
  /** Why a planner may skip a finding: the policy's grounds, one cause each. */
91
199
  export const SKIP_CAUSES = Object.freeze(['low-severity', 'no-inline-location', 'existing-thread', 'cannot-anchor', 'too-long']);
92
200
 
@@ -116,6 +224,66 @@ export function publicationItems(plan) {
116
224
  return [...(plan?.summary ? [plan.summary] : []), ...(plan?.comments ?? [])];
117
225
  }
118
226
 
227
+ /**
228
+ * Whether publication of the review's saved plan began: an item was sent, may
229
+ * have landed or was found on the PR. Items that only failed with a definite
230
+ * error, so that nothing was created, leave the plan open to adjustments.
231
+ */
232
+ export function publicationStarted(review) {
233
+ const ledger = review?.publication instanceof Map ? [...review.publication.values()] : [];
234
+ return ledger.some(entry => entry?.state !== 'FAILED');
235
+ }
236
+
237
+ /**
238
+ * For a review a person adjusted: what the PR keeps from earlier publications
239
+ * after this one, since AZPR never changes a posted comment. Names the items
240
+ * of the preview the PR already had with other text (`earlierText` in the
241
+ * ledger), marks those the adjustments concern, and counts the other AZPR
242
+ * comments on the PR where an excluded finding may still show. '' when none.
243
+ */
244
+ export function describeEarlierText(review, otherComments = 0) {
245
+ const { excluded, severity, active } = adjustmentsOf(review);
246
+ const kept = review?.publication instanceof Map ? [...review.publication.values()].filter(entry => entry?.earlierText) : [];
247
+ const rows = kept.map(entry => {
248
+ if (entry.kind === 'summary') return `the PR summary${active ? ' (it may still list findings you excluded or show earlier severities)' : ''}`;
249
+ const ids = entry.findingIds ?? [entry.findingId];
250
+ return `${ids.join(', ')} at ${entry.path}:${entry.startLine}${ids.some(id => Object.hasOwn(severity, id)) ? ' (you changed its severity)' : ''}`;
251
+ });
252
+ const lines = [];
253
+ if (rows.length) lines.push(`Already on the PR with earlier text, which AZPR does not change, so this preview is not what the PR shows there: ${rows.join('; ')}. Edit them on the PR if they should change.`);
254
+ if (excluded.length && otherComments > 0) lines.push(`The PR has ${otherComments} other AZPR comment(s) from earlier publications that are not part of this preview; AZPR does not change them, so a finding you excluded may still be visible there.`);
255
+ return lines.map(line => `${line}\n`).join('');
256
+ }
257
+
258
+ /**
259
+ * Where the text a saved preview would post still names a finding a person
260
+ * excluded. The planner's own text is checked page by page; this checks the
261
+ * items as they would be posted, including the summary rows the runtime
262
+ * renders from the review's own finding summaries, which no planner turn can
263
+ * change. Only IDs written as the runtime writes them are found. Returns
264
+ * readable rows; [] when nothing names an excluded finding.
265
+ */
266
+ export function excludedReferences(review) {
267
+ const excluded = new Set(adjustmentsOf(review).excluded);
268
+ if (!excluded.size || !review?.plan) return [];
269
+ const rows = [];
270
+ for (const item of publicationItems(review.plan)) {
271
+ const names = namedExcluded(item.content, excluded);
272
+ if (!names.length) continue;
273
+ if (item.kind === 'summary') {
274
+ const sources = commentFindings(review).filter(finding => namedExcluded(finding.summary, excluded).length).map(finding => finding.id);
275
+ rows.push(`the PR summary names ${names.join(', ')}${sources.length ? ` (in the summary row of ${sources.join(', ')})` : ''}`);
276
+ } else rows.push(`the comment of ${(item.findingIds ?? [item.findingId]).join(', ')} at ${item.path}:${item.startLine} names ${names.join(', ')}`);
277
+ }
278
+ return rows;
279
+ }
280
+
281
+ /** Findings a person excluded that a text names, read as `citedFindings` reads IDs. */
282
+ function namedExcluded(text, excluded) {
283
+ if (!excluded.size || !text) return [];
284
+ return [...new Set(String(text).match(FINDING_ID) ?? [])].filter(id => excluded.has(id));
285
+ }
286
+
119
287
  /**
120
288
  * Why automatic publication has nothing new to post: the plan has no inline
121
289
  * comment, and the planner skipped every finding because a live thread of the
@@ -454,6 +622,8 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
454
622
  status = 'READY';
455
623
  }
456
624
  const eligible = new Map(assigned.map(finding => [finding.id, finding]));
625
+ // Findings a person excluded after a preview: no published text may name them.
626
+ const excluded = new Set(adjustmentsOf(review).excluded);
457
627
  const changed = new Set(review.snapshot.files.map(path => path.startsWith('/') ? path : '/' + path));
458
628
  // Quick findings were not independently verified: an inline comment needs a
459
629
  // checked location and an anchor found in source text the runtime read.
@@ -474,6 +644,8 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
474
644
  if (!body) problems.push('body is empty');
475
645
  else if (body.length > INLINE_SOFT_LIMIT && !final) problems.push(`body is ${body.length} characters; keep it within ${INLINE_SOFT_LIMIT}`);
476
646
  else if (body.length > INLINE_HARD_LIMIT) problems.push(`body exceeds ${INLINE_HARD_LIMIT} characters`);
647
+ const named = namedExcluded(body, excluded);
648
+ if (named.length) problems.push(`body names ${named.join(', ')}, which a person excluded from publication; leave ${named.length === 1 ? 'it' : 'them'} out`);
477
649
  const path = nonempty(c.path) ? (c.path.startsWith('/') ? c.path : '/' + c.path) : '';
478
650
  if (!changed.has(path) || /[\r\n\0]/.test(path)) problems.push(`path ${JSON.stringify(c.path ?? '')} is not a changed file of this PR`);
479
651
  else if (lines && path !== lines.path) problems.push(`path must be ${lines.path}, where the combined findings are`);
@@ -601,10 +773,18 @@ export function evaluatePlanPage(answerText, { review, assigned, final = false,
601
773
  }
602
774
  if (status === 'INCOMPLETE') { corrections.push({ action: 'accept-incomplete-plan-page', reason: nonempty(value.reason) ? value.reason.trim() : '' }); status = 'READY'; }
603
775
  const note = nonempty(value.summary) ? value.summary : '';
604
- const summary = note && allowSummary && note.length <= SUMMARY_NOTE_LIMIT && !/<!--|-->/.test(note) ? note.trim() : undefined;
776
+ let summary = note && allowSummary && note.length <= SUMMARY_NOTE_LIMIT && !/<!--|-->/.test(note) ? note.trim() : undefined;
605
777
  if (note && !allowSummary) corrections.push({ action: 'drop-unallowed-summary' });
606
778
  else if (note && !summary) corrections.push({ action: 'drop-invalid-summary-note' });
607
- const summaryDetails = nonempty(value.summaryDetails) ? escapeComments(value.summaryDetails.trim()) : '';
779
+ let summaryDetails = nonempty(value.summaryDetails) ? escapeComments(value.summaryDetails.trim()) : '';
780
+ // A finding a person excluded appears nowhere in the summary either; after repairs the text that names it is dropped.
781
+ for (const [field, text] of [['summary', summary], ['summaryDetails', summaryDetails]]) {
782
+ const named = namedExcluded(text, excluded);
783
+ if (!named.length) continue;
784
+ if (!final) issues.push(`${field} names ${named.join(', ')}, which a person excluded from publication; leave ${named.length === 1 ? 'it' : 'them'} out.`);
785
+ else if (field === 'summary') { summary = undefined; corrections.push({ action: 'drop-summary-note-naming-excluded', findingIds: named }); }
786
+ else { summaryDetails = ''; corrections.push({ action: 'drop-summary-details-naming-excluded', findingIds: named }); }
787
+ }
608
788
  return { result: { status, comments, skipped, summary, summaryDetails, ...(continuation ? { continuation } : {}) }, issues, corrections };
609
789
  }
610
790
 
@@ -620,7 +800,7 @@ function summaryComment(review, note, details, inlineMarkers, groups = []) {
620
800
  const heading = chinese ? traditional ? '審查說明' : '审查说明' : 'Review notes';
621
801
  const notes = nonempty(note) ? `**${heading}**\n\n${note.trim()}` : '';
622
802
  // Only combinations the plan accepted share an index row.
623
- const index = renderReviewSummary(publishableFindings(review), review.outputLanguage ?? 'en', notes, { verification: reviewVerification(review), groups });
803
+ const index = renderReviewSummary(commentFindings(review), review.outputLanguage ?? 'en', notes, { verification: reviewVerification(review), groups });
624
804
  // The summary's disclosure may add incomplete coverage of a quick review.
625
805
  const attribution = review.summaryAttribution ?? review.attribution;
626
806
  const disclosure = attribution ? `🤖 ${attribution}\n\n` : '';
package/src/config.mjs CHANGED
@@ -5,6 +5,11 @@ import { REVIEW_TOOL_NAMES } from './review-tools.mjs';
5
5
  export const MODES = Object.freeze(['review', 'deep', 'quick']);
6
6
  export const COMMANDS = Object.freeze({ 'pr-check': 'check', 'pr-review': 'review', 'pr-deep': 'deep', 'pr-quick': 'quick', 'pr-stop': 'stop', 'pr-comment': 'comment' });
7
7
 
8
+ // How the host identifies this plugin and its published packages in its plugin list.
9
+ export const PLUGIN_ID = 'azpr';
10
+ export const PACKAGE_NAME = 'opencode-azure-devops-pr-review';
11
+ export const REPOSITORY = 'WTLAIB/opencode-azure-devops-pr-review-v2';
12
+
8
13
  // Native tools no private role may use. Shell is governed by the `shell` setting.
9
14
  export const NATIVE_TOOL_PERMISSIONS = Object.freeze({
10
15
  execute: 'deny', edit: 'deny', write: 'deny', patch: 'deny', skill: 'deny', subagent: 'deny',
package/src/host.mjs CHANGED
@@ -44,9 +44,53 @@ export function hostCapabilities(context) {
44
44
  toolTransform: fn('tool.transform'),
45
45
  sessionRemove: fn('session.remove'),
46
46
  eventSubscribe: fn('event.subscribe'),
47
+ pluginList: fn('plugin.list'),
47
48
  };
48
49
  }
49
50
 
51
+ /** Whether a package specification names the npm package, or the Git repository (github:, git URLs, owner/repo). */
52
+ export function packageNamed(target, name, repository) {
53
+ const spec = typeof target === 'string' ? target.trim() : '';
54
+ if (spec === name || spec.startsWith(`${name}@`)) return true;
55
+ const repo = repository.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
+ return new RegExp(`(?:^|[:/])${repo}(?:\\.git)?(?:[?#]|$)`).test(spec.toLowerCase());
57
+ }
58
+
59
+ /**
60
+ * This plugin's entries in the host's plugin list. OpenCode 2.1.4 lists
61
+ * { id?, source: { type: package|local|builtin|sdk, target?, version? },
62
+ * state: { status: active|failed, error? } } and keeps only the first entry
63
+ * of a plugin ID: a second one is listed as failed with "Duplicate plugin ID".
64
+ * `running` is the active entry with the plugin's ID; `others` are the other
65
+ * entries with that ID or naming one of its packages. null without a list.
66
+ */
67
+ export function pluginEntries(value, { id, ownPackage }) {
68
+ const entries = listOf(value);
69
+ if (!entries) return null;
70
+ const ours = entries.filter(entry => isRecord(entry) && (entry.id === id || (entry.source?.type === 'package' && ownPackage(entry.source.target))));
71
+ const running = ours.find(entry => entry.id === id && entry.state?.status === 'active') ?? null;
72
+ return { running, others: ours.filter(entry => entry !== running) };
73
+ }
74
+
75
+ /**
76
+ * Text with each URL's user name, password and query string masked: a Git or
77
+ * tarball package specification, and host messages that quote one, can carry
78
+ * a token there.
79
+ */
80
+ export function withoutCredentials(text) {
81
+ return String(text ?? '').replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/?#]*@)?([^\s?#]*)(\?[^\s#]*)?/gi,
82
+ (match, scheme, userinfo, rest, query) => `${scheme}${userinfo ? '***@' : ''}${rest}${query ? '?***' : ''}`);
83
+ }
84
+
85
+ /** A path- and credential-free label for a plugin list entry's source: its package specification and installed version or commit. */
86
+ export function pluginSourceLabel(source) {
87
+ if (source?.type === 'local') return 'a local source installation';
88
+ if (source?.type !== 'package' || typeof source.target !== 'string') return 'an entry of unknown origin';
89
+ const version = typeof source.version === 'string' && source.version && !source.target.endsWith(`@${source.version}`) && !source.target.endsWith(`#${source.version}`)
90
+ ? /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i.test(source.version) ? `commit ${source.version.slice(0, 7)}` : `version ${source.version}` : '';
91
+ return `${withoutCredentials(source.target)}${version ? ` (${version})` : ''}`;
92
+ }
93
+
50
94
  /**
51
95
  * Session events that show a turn progressing while no hook runs. OpenCode
52
96
  * 2.1.2 and 2.1.4 emit one delta event per streamed chunk of answer text,
package/src/output.mjs CHANGED
@@ -667,3 +667,74 @@ export function parseReviewRequest(raw, { flags = true } = {}) {
667
667
  if (option && OPTION.test(userContext)) throw new Error(`[AZPR] Use at most one of ${FLAG_NAMES}, right after the PR URL, and start your context with a word.`);
668
668
  return { request: raw, prUrl: match[1], userContext, target, ...(option ? { flag: option[1], afterReview: REVIEW_FLAGS[option[1]] } : {}) };
669
669
  }
670
+
671
+ /** A finding ID as the runtime writes it (F-1, Q-1001, V-2); f1 and F1 read as F-1. null otherwise. */
672
+ export function normalizeFindingId(value) {
673
+ const match = /^([A-Za-z]+)-?(\d+)$/.exec(String(value ?? '').trim());
674
+ return match ? `${match[1].toUpperCase()}-${match[2]}` : null;
675
+ }
676
+
677
+ const COMMENT_USAGE = '[AZPR] Usage: /pr-comment [review-id] [--publish | --show], or /pr-comment <review-id> with --exclude <IDs|none> and/or --severity <ID=high|medium|low,…|none>, or --reset. Omit the ID for this conversation\'s latest completed review.';
678
+ const COMMENT_OPTIONS = ['publish', 'show', 'exclude', 'severity', 'reset'];
679
+
680
+ /**
681
+ * /pr-comment's arguments: an optional review ID, then at most one of
682
+ * --publish and --show, or adjustments of a named review's findings:
683
+ * --exclude and --severity (each at most once, each a complete list; `none`
684
+ * for an empty one) or --reset alone. List items are separated by commas or
685
+ * spaces. Anything else is refused.
686
+ */
687
+ export function parseCommentRequest(raw) {
688
+ const args = String(raw ?? '').trim().split(/\s+/).filter(Boolean);
689
+ const reviewId = /^[a-f0-9]{8}$/.test(args[0] ?? '') ? args.shift() : undefined;
690
+ const values = new Map();
691
+ let open = null;
692
+ for (const token of args) {
693
+ const option = /^--([a-z]+)(?:=([\s\S]*))?$/.exec(token);
694
+ if (option) {
695
+ if (!COMMENT_OPTIONS.includes(option[1]) || values.has(option[1])) throw new Error(COMMENT_USAGE);
696
+ open = ['exclude', 'severity'].includes(option[1]) ? option[1] : null;
697
+ if (option[2] !== undefined && !open) throw new Error(COMMENT_USAGE);
698
+ values.set(option[1], option[2] === undefined ? [] : [option[2]]);
699
+ continue;
700
+ }
701
+ if (!open) throw new Error(COMMENT_USAGE);
702
+ values.get(open).push(token);
703
+ }
704
+ const named = [...values.keys()];
705
+ const request = { ...(reviewId ? { reviewId } : {}), publish: values.has('publish'), show: values.has('show') };
706
+ if (!named.some(name => ['exclude', 'severity', 'reset'].includes(name))) {
707
+ if (named.length > 1) throw new Error(COMMENT_USAGE);
708
+ return request;
709
+ }
710
+ if (named.some(name => ['publish', 'show'].includes(name)) || (values.has('reset') && named.length > 1)) throw new Error(COMMENT_USAGE);
711
+ if (!reviewId) throw new Error('[AZPR] Name the review whose findings you adjust: /pr-comment <review-id> --exclude … (the ID is in its receipt).');
712
+ const items = name => values.get(name).join(' ').split(/[\s,]+/).filter(Boolean);
713
+ const adjust = values.has('reset') ? { reset: true } : {};
714
+ if (values.has('exclude')) {
715
+ const listed = items('exclude');
716
+ if (!listed.length) throw new Error('[AZPR] --exclude needs the finding IDs to exclude, or none.');
717
+ if (listed.length === 1 && listed[0].toLowerCase() === 'none') adjust.exclude = [];
718
+ else {
719
+ const ids = listed.map(normalizeFindingId);
720
+ const bad = listed.filter((_, index) => !ids[index]);
721
+ if (bad.length) throw new Error(`[AZPR] Not a finding ID: ${bad.join(', ')}. Use the IDs of the review report, such as F-1 or R-2, or none.`);
722
+ adjust.exclude = [...new Set(ids)];
723
+ }
724
+ }
725
+ if (values.has('severity')) {
726
+ const listed = items('severity');
727
+ if (!listed.length) throw new Error('[AZPR] --severity needs ID=high, ID=medium or ID=low entries, or none.');
728
+ if (listed.length === 1 && listed[0].toLowerCase() === 'none') adjust.severity = {};
729
+ else {
730
+ adjust.severity = {};
731
+ for (const entry of listed) {
732
+ const match = /^([^=]+)=(high|medium|low)$/i.exec(entry), id = match && normalizeFindingId(match[1]);
733
+ if (!id) throw new Error(`[AZPR] Not a severity change: ${entry}. Write ID=high, ID=medium or ID=low, such as F-2=low.`);
734
+ if (Object.hasOwn(adjust.severity, id)) throw new Error(`[AZPR] --severity names ${id} twice.`);
735
+ adjust.severity[id] = match[2].toLowerCase();
736
+ }
737
+ }
738
+ }
739
+ return { ...request, adjust };
740
+ }
package/src/plugin.js CHANGED
@@ -1,7 +1,8 @@
1
+ import { PLUGIN_ID } from './config.mjs';
1
2
  import { setupPlugin } from './setup.mjs';
2
3
 
3
4
  // Pure OpenCode V2 definition; the host supplies its domain APIs.
4
5
  export default {
5
- id: 'azpr',
6
+ id: PLUGIN_ID,
6
7
  setup: setupPlugin,
7
8
  };