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/tui-setup.mjs CHANGED
@@ -19,7 +19,7 @@ const anyObject = Object.freeze({ type: 'object' });
19
19
  export const SETUP_RPC = Object.freeze({
20
20
  id: 'azpr.setup',
21
21
  methods: Object.freeze({
22
- /** What is set, as rows, and whether AZPR can run (`state`: required, ready or restart). */
22
+ /** What is set, as rows, and whether AZPR can run (`state`: required, migrate, ready or restart). */
23
23
  status: Object.freeze({ input: anyObject, output: anyObject }),
24
24
  /** Whether answers can be used, and their saved form, without saving anything. */
25
25
  validate: Object.freeze({ input: anyObject, output: anyObject }),
@@ -43,6 +43,7 @@ export const isSetupNotice = metadata => metadata !== null && typeof metadata ==
43
43
  typeof metadata.azpr === 'object' && metadata.azpr.setup === true;
44
44
 
45
45
  const NOT_SET_UP = 'AZPR is not set up yet. Type /pr-setup to set it up.';
46
+ const NOT_UPDATED = 'AZPR\'s settings are from an earlier version. Type /pr-setup to see what changes and update them.';
46
47
  const CANCELLED = 'AZPR setup: left before the end; nothing was saved.';
47
48
  const STOPPED = 'AZPR setup stopped: the OpenCode server did not answer as expected. What was saved before stays; run /pr-setup again.';
48
49
  const UNAVAILABLE = 'AZPR setup is not available: this OpenCode server did not answer for AZPR. Restart the OpenCode service and try again; /pr-setup --help shows the options.';
@@ -51,7 +52,10 @@ const rowOf = (status, id) => (Array.isArray(status?.rows) ? status.rows : []).f
51
52
  const withProblem = (problem, description) => problem ? `${problem}\n\n${description}` : description;
52
53
  // A model as settings name it: provider/model, optionally with #variant.
53
54
  const baseModel = value => text(value).split('#')[0];
54
- const variantOf = value => text(value).includes('#') ? text(value).slice(text(value).indexOf('#') + 1) : '';
55
+ // The variant a model names; "default" is the model's own default, as no variant is (the dialog's Default row).
56
+ const variantOf = value => { const variant = text(value).includes('#') ? text(value).slice(text(value).indexOf('#') + 1) : ''; return variant === 'default' ? '' : variant; };
57
+ // One model and variant however it is written: provider/model and provider/model#default are the same.
58
+ const effective = value => text(value).replace(/#default$/, '');
55
59
 
56
60
  /**
57
61
  * @param {object} host
@@ -120,26 +124,65 @@ export function createSetup(host) {
120
124
  }
121
125
 
122
126
  /** A model of the host's list, with its variant when it has some; '' when the row may be off; undefined when left. */
123
- async function askModel(row) {
127
+ async function askOneModel(row, { start = row.current, title = row.title, off = Boolean(row.optional) } = {}) {
124
128
  const list = await models();
125
129
  // A row that may be off can still be switched off when OpenCode offers no model; a row that needs one cannot be answered.
126
- if (!list.length && !row.optional) {
130
+ if (!list.length && !off) {
127
131
  await dialog.alert({ title: 'No model available', message: 'OpenCode offers no model that can call tools. Connect a model provider first (/connect), then run /pr-setup again.' });
128
132
  return undefined;
129
133
  }
130
- const current = baseModel(row.current);
134
+ const current = baseModel(start);
131
135
  // Where a row says what to look for (the deep model: a stronger one, or a higher variant), the search line says it.
132
- const picked = await dialog.select({ title: row.title, placeholder: text(row.prompt) || 'Search models', current: row.optional && !current ? '' : current || undefined,
133
- options: [...(row.optional ? [{ title: row.optional.label, value: '', description: row.optional.description, category: 'Off' }] : []),
136
+ const picked = await dialog.select({ title, placeholder: text(row.prompt) || 'Search models', current: off && !current ? '' : current || undefined,
137
+ options: [...(off ? [{ title: row.optional.label, value: '', description: row.optional.description, category: 'Off' }] : []),
134
138
  ...list.map(model => ({ title: model.name, value: model.id, description: model.id, category: model.provider }))] });
135
139
  if (picked === undefined || picked === '') return picked;
136
140
  const variants = list.find(model => model.id === picked)?.variants ?? [];
137
141
  if (!variants.length) return picked;
138
- const variant = await dialog.select({ title: `Variant of ${picked}`, ...(text(row.variantPrompt) ? { placeholder: row.variantPrompt } : {}), current: picked === current ? variantOf(row.current) : '',
142
+ const variant = await dialog.select({ title: `Variant of ${picked}`, ...(text(row.variantPrompt) ? { placeholder: row.variantPrompt } : {}), current: picked === current ? variantOf(start) : '',
139
143
  options: [{ title: 'Default', value: '', description: 'The model\'s own default' }, ...variants.map(name => ({ title: name, value: name }))] });
140
144
  return variant === undefined ? undefined : variant ? `${picked}#${variant}` : picked;
141
145
  }
142
146
 
147
+ // A list of models as the server part takes it as text: MODEL*N for passes in a row, entries separated by commas.
148
+ const passesText = passes => passes.reduce((runs, model) => { if (runs.at(-1)?.[0] === model) runs.at(-1)[1]++; else runs.push([model, 1]); return runs; }, [])
149
+ .map(([model, count]) => `${model}*${count}`).join(',');
150
+ const shortModel = model => text(model).slice(text(model).indexOf('/') + 1);
151
+
152
+ /**
153
+ * A mode's review passes: a model, then how often and with which other models it reviews. One model becomes
154
+ * the mode's usual number of passes (`row.usual`); the first row of the second dialog keeps that, and the
155
+ * others add a pass (the same model again, or another one) or take the last one away, between one pass and
156
+ * `row.most`. The answer is the list as text; '' when the row may be off; undefined when left.
157
+ */
158
+ async function askModel(row) {
159
+ const saved = Array.isArray(row.entries) ? row.entries.filter(item => typeof item === 'string' && item) : [];
160
+ const first = await askOneModel(row, { start: saved[0] ?? '' });
161
+ if (first === undefined || first === '') return first;
162
+ const usual = Number.isInteger(row.usual) && row.usual > 0 ? row.usual : 1, most = Number.isInteger(row.most) && row.most >= usual ? row.most : usual;
163
+ // The saved first model picked again: the saved passes are what the first row keeps, so that looking at a
164
+ // row and taking what it shows changes nothing. Another model starts with the mode's usual passes of it.
165
+ let passes = effective(first) === effective(saved[0]) && saved.length <= most ? [...saved] : Array(usual).fill(first);
166
+ for (;;) {
167
+ // A model keeps its provider where another pass has one of the same name from another provider.
168
+ const named = model => passes.some(other => other !== model && shortModel(other) === shortModel(model)) ? model : shortModel(model);
169
+ const shown = passes.map(named).join(', ');
170
+ const choice = await dialog.select({ title: `${row.title}: ${passes.length} pass${passes.length === 1 ? '' : 'es'}`, options: [
171
+ { title: `Use ${passes.length === 1 ? 'this pass' : `these ${passes.length} passes`}`, value: 'done', description: shown },
172
+ ...(passes.length < most ? [{ title: 'Add a pass of the same model', value: 'same', description: `${named(passes.at(-1))} once more` },
173
+ { title: 'Add a pass of another model', value: 'other', description: 'Different models find different defects' }] : []),
174
+ ...(passes.length > 1 ? [{ title: 'Take the last pass away', value: 'less', description: `Without ${named(passes.at(-1))}` }] : [])] });
175
+ if (choice === undefined) return undefined;
176
+ if (choice === 'done') return passesText(passes);
177
+ if (choice === 'same') passes = [...passes, passes.at(-1)];
178
+ else if (choice === 'less') passes = passes.slice(0, -1);
179
+ else {
180
+ const another = await askOneModel(row, { start: '', title: `Model of pass ${passes.length + 1}`, off: false });
181
+ if (another) passes = [...passes, another];
182
+ }
183
+ }
184
+ }
185
+
143
186
  /**
144
187
  * Ask for the token and have Azure DevOps check it. Returns `{ token }` (undefined: the saved one was
145
188
  * checked and stays), `{ organization: problem }` when Azure DevOps knows no such organization, or
@@ -213,12 +256,15 @@ export function createSetup(host) {
213
256
  problem = answer.organization;
214
257
  if (!(await ask('organization'))) return false;
215
258
  }
216
- const model = await askModel(rows('reviewModel'));
259
+ // One model for a start: the server part gives it the usual passes of /pr-review and of /pr-quick. Where the
260
+ // settings name review models already, the dialog starts on the first of them.
261
+ const reviewRow = rows('reviewModel');
262
+ const model = await askOneModel(reviewRow, { start: Array.isArray(reviewRow?.entries) && typeof reviewRow.entries[0] === 'string' ? reviewRow.entries[0] : '', off: false });
217
263
  if (model === undefined) return false;
218
264
  const yes = await dialog.confirm({ title: 'Save AZPR\'s settings?', label: { confirm: 'Save', cancel: 'Leave' },
219
265
  message: [`Organization: ${answers.organization}`, `Proxy: ${shown.proxy || 'none'}`, ...(answers.caFile ? [`CA certificate file: ${answers.caFile}`] : []),
220
266
  `Token: ${token === undefined ? 'the saved one' : 'the one just entered, in a file only you can read'}`,
221
- `Model: ${model} (reviewers, verifier and /pr-quick)`, '', 'Other settings keep their values (the defaults in a new file); /pr-setup changes them later.'].join('\n') });
267
+ `Model: ${model} (two passes of /pr-review, one of /pr-quick)`, '', 'Other settings keep their values (the defaults in a new file); /pr-setup changes them later.'].join('\n') });
222
268
  if (!yes) return false;
223
269
  const saved = await call('save', { changes: { organization: answers.organization, proxy: answers.proxy, ...(answers.caFile === undefined ? {} : { caFile: answers.caFile }), model },
224
270
  ...(token === undefined ? {} : { token }) });
@@ -232,6 +278,30 @@ export function createSetup(host) {
232
278
  return true;
233
279
  }
234
280
 
281
+ /**
282
+ * Settings of an earlier version: what the update changes, then a list whose first row keeps the file as it
283
+ * is. The server part writes the file only for the word that names what was shown here.
284
+ */
285
+ async function update(status) {
286
+ const lines = Array.isArray(status.migration?.lines) ? status.migration.lines.filter(line => typeof line === 'string') : [];
287
+ await dialog.alert({ title: 'AZPR\'s settings are from an earlier version', message: `${lines.map(line => `- ${line}`).join('\n')}\n\nNothing is changed until you confirm in the next step.` });
288
+ const choice = await dialog.select({ title: 'Update AZPR\'s settings file?', options: [
289
+ { title: 'Not now', value: 'keep', description: 'The file stays as it is; reviews do not run until it is updated' },
290
+ { title: 'Update the settings file', value: 'update', description: text(status.settingsFileShown) || text(status.settingsFile) }] });
291
+ if (choice !== 'update') return false;
292
+ const saved = await call('save', { migrate: text(status.migration?.word) });
293
+ if (!saved?.ok) { failed(saved); return true; }
294
+ if (saved.status?.state === 'ready') loaded();
295
+ // A file that had a fault before the update still has it: say what is missing, and where it is set.
296
+ const remaining = text(saved.remaining);
297
+ await dialog.alert({ title: 'AZPR\'s settings are updated', message: saved.status?.state === 'ready'
298
+ ? 'Reviews run again:\n\n/pr-check <PR URL>\n/pr-review <PR URL>\n\n/pr-setup shows the models of each mode and changes them.'
299
+ : remaining ? `The settings file has the layout of this version now. It still cannot be used:\n\n${remaining}\n\nSet that right with /pr-setup or in the settings file.`
300
+ : text(saved.status?.problem) ? `The settings file is updated, but AZPR could not load it: ${saved.status.problem.replace(/\.$/, '')}.\n\nSet that right, then restart the OpenCode service (opencode service restart) and run /pr-check <PR URL>.`
301
+ : 'The settings file is updated.\n\nRestart the OpenCode service (opencode service restart), then run /pr-check <PR URL>.' });
302
+ return true;
303
+ }
304
+
235
305
  /** The settings as one list; choosing a row changes it, and the list comes back with the new value. */
236
306
  async function settingsList(first) {
237
307
  let status = first, last;
@@ -317,6 +387,11 @@ export function createSetup(host) {
317
387
  let status;
318
388
  try { status = await call('status', {}); } catch { toast({ title: 'AZPR setup', message: UNAVAILABLE, variant: 'error', duration: 10000 }); return; }
319
389
  if (!status || !Array.isArray(status.rows)) { toast({ title: 'AZPR setup', message: text(status?.problem) || UNAVAILABLE, variant: 'error', duration: 10000 }); return; }
390
+ // Before anything else: settings of an earlier version are neither missing nor in need of repair.
391
+ if (status.state === 'migrate') {
392
+ if (!(await update(status))) toast({ message: 'AZPR setup: the settings file was left as it is.', variant: 'info' });
393
+ return;
394
+ }
320
395
  if (status.editable === false) {
321
396
  await dialog.alert({ title: 'AZPR\'s settings file needs repair', message: `${text(status.fileProblem) || 'The settings file cannot be changed here.'}\n\n${text(status.settingsFile)}\n\nRepair it by hand, then run /pr-setup again.` });
322
397
  return;
@@ -336,9 +411,9 @@ export function createSetup(host) {
336
411
  if (hinted || stopped) return;
337
412
  let status;
338
413
  try { status = await call('status', {}); } catch { return; }
339
- if (hinted || status?.state !== 'required') return;
414
+ if (hinted || !['required', 'migrate'].includes(status?.state)) return;
340
415
  hinted = true;
341
- toast({ message: NOT_SET_UP, variant: 'info', duration: 8000 });
416
+ toast({ message: status.state === 'migrate' ? NOT_UPDATED : NOT_SET_UP, variant: 'info', duration: 8000 });
342
417
  },
343
418
  get running() { return running; },
344
419
  /** The terminal part is being unloaded: a setup that is open ends at its next step, and none opens after it. */
@@ -1,64 +0,0 @@
1
- # Role: evidence verifier
2
-
3
- You independently verify the candidate findings in `assignment.findings` (IDs in
4
- `assignment.findingIds`). Other sessions verify the remaining findings; their
5
- IDs are in `assignment.allFindingIds`. `initialReports` holds every initial
6
- reviewer's report and coverage gaps, including unparsed answers.
7
-
8
- For each assigned finding, read the source yourself at `snapshot.head` and
9
- `snapshot.base`: establish the HEAD behavior from your own reads, check the
10
- reachable trigger, callers, safeguards and the strongest counterexample, then
11
- decide. azpr_read_diff shows what changed; decide from the source the claim
12
- depends on (the whole function, its callers, contracts and tests), read with
13
- azpr_read_file. Initial reports are claims, not proof: agreement between
14
- reviewers, detail or confidence are not evidence. Prefer a source or contract
15
- derivation over calculated examples, and keep a number only if you observed it.
16
-
17
- ## Decisions
18
-
19
- Return exactly one decision per assigned ID:
20
- - confirmed: the complete corrected finding under the same ID (summary,
21
- evidence, counterevidence, location, severity, suggestion) plus reason.
22
- Re-establish the location from source (`head:/path:line`). Candidates arrive
23
- without a severity: set it yourself from the harm and trigger you verified
24
- (see Severity). The location is where the defect stated in summary is:
25
- correct the lines freely, but keep the candidate's file unless that defect is
26
- in another file. When you move a finding to another file, add
27
- `movedFrom` with the candidate's location and explain the move in reason.
28
- - rejected: a concrete source-based refutation. Neither a possible intention nor
29
- BASE having the same code where this PR adds or moves the lines refutes a
30
- defect. When only the author's intent would settle a verified behavior,
31
- confirm it with a summary that asks whether the author meant it and a
32
- suggestion that asks them to confirm or document the intent.
33
- - needsInfo: the missing evidence and what would settle it. It is for behavior
34
- you could not establish, not for intent: when the behavior is verified and
35
- only the author, or a specification outside the repository, can say whether
36
- it is meant, confirm it and ask in summary.
37
- - merged: `mergedInto` names another original ID (any ID in allFindingIds) with
38
- the same root cause and correction. Do not merge into itself, form cycles or
39
- merge into a finding you reject: decide such a pair on its own evidence.
40
- Findings that need different corrections stay separate, each at its own
41
- location, even when they share a cause. A merged finding's own text is
42
- dropped, so merge only a finding whose defect the kept one states: when it
43
- names a defect the kept finding does not, confirm it under its own ID.
44
-
45
- A merge or a decision explained only in prose does not count; every assigned ID
46
- needs its own row. New, independently verified issues that no candidate covers
47
- go in newFindings with all finding fields, numbered from
48
- `assignment.firstNewFindingId` (V-1, V-2, ...). Use [] for empty categories.
49
-
50
- ## Report
51
-
52
- report covers what the structured fields do not: important exclusions with
53
- paired HEAD/BASE evidence, retained improvement recommendations from the initial
54
- reports or your own checks (affected code, concrete benefit, direction), open
55
- questions, and testing or scope limitations. Do not restate the snapshot, SHAs,
56
- findings or decisions; the runtime renders those.
57
-
58
- Return:
59
- ```json
60
- {"status":"COMPLETE","confirmed":[{"id":"F-1","summary":"...","evidence":"...","counterevidence":"...","location":"head:/src/example.ts:12","severity":"medium","suggestion":"...","reason":"Decisive check"}],"merged":[{"id":"R-1","mergedInto":"F-1","reason":"Same cause and correction"}],"rejected":[{"id":"F-2","reason":"Source-based refutation"}],"needsInfo":[],"newFindings":[],"report":"Exclusions, advice, open questions, limitations"}
61
- ```
62
-
63
- Use status COMPLETE when you finished verifying the assigned findings, or
64
- INCOMPLETE when your own checks remain unfinished (decide what you can anyway).
@@ -1,34 +0,0 @@
1
- # Role: functional correctness reviewer
2
-
3
- Independently review the files in `assignment.files` at `snapshot.head` against
4
- `snapshot.base`. Your focus is functional correctness: requirements, boundary
5
- inputs, state transitions, API and data compatibility, regressions, and whether
6
- tests would catch them. The focus orders your attention; it does not limit what
7
- you report. You receive no other reviewer's work.
8
-
9
- Check how the change fits the surrounding system: responsibilities, dependency
10
- direction, data ownership, public interfaces and invariants. For changed types
11
- or data models, check construction, deserialization and mutation boundaries:
12
- can invalid states enter, related fields diverge, or exposed mutable references
13
- bypass an invariant? Check affected comments and docs against signatures, return
14
- values, side effects and errors.
15
-
16
- `assignment.changes` gives each assigned path's change type. When
17
- `assignment.discoverFiles` is true, Azure listed only part of the changed files:
18
- use the PR's own data to find other changed paths you need and list them in
19
- `additionalFiles`.
20
-
21
- Number findings consecutively from `assignment.firstFindingId` (F-1, F-2, … or
22
- F-1001, F-1002, …); an empty array is valid. Use status COMPLETE when you
23
- reviewed every assigned file and filed every defect you found; otherwise
24
- PARTIAL with concrete `coverage.gaps`. COMPLETE describes coverage, not
25
- correctness.
26
-
27
- Return:
28
- ```json
29
- {"status":"COMPLETE","coverage":{"files":["/src/example.ts"],"gaps":[]},"additionalFiles":[],"findings":[{"id":"F-1","summary":"Defect summary","location":"head:/src/example.ts:12","evidence":"HEAD/BASE pair, reachable trigger and impact","counterevidence":"Safeguards checked and why they do not refute it","severity":"medium","suggestion":"Correction and a focused regression case"}],"report":"Important exclusions with evidence, improvement advice, open questions and tests not run"}
30
- ```
31
-
32
- `coverage.files` lists assigned paths you actually reviewed. Omit `location` when
33
- you cannot establish it from source and explain why; the verifier will settle it.
34
- Keep `report` for exclusions, advice, open questions and limitations.
@@ -1,36 +0,0 @@
1
- # Role: risk reviewer
2
-
3
- Independently review the files in `assignment.files` at `snapshot.head` against
4
- `snapshot.base`. Your focus is failure behavior: exceptions, timeouts,
5
- cancellation, resource release, partial success, retry scope, duplicate
6
- execution, concurrency, transaction boundaries, authorization and data
7
- consistency, and whether tests cover that behavior. The focus orders your
8
- attention; it does not limit what you report: a wrong calculation, a dropped
9
- item or a broken contract is a finding even when no failure path is involved.
10
- You receive no other reviewer's work.
11
-
12
- Follow control and data paths across trust and failure boundaries. Trace how a
13
- failure reaches its caller or user: does an exception become an apparent
14
- success, an empty result or an unjustified fallback, and can the caller tell and
15
- recover? Check documented failure guarantees against the actual cleanup and
16
- recovery paths.
17
-
18
- `assignment.changes` gives each assigned path's change type. When
19
- `assignment.discoverFiles` is true, Azure listed only part of the changed files:
20
- use the PR's own data to find other changed paths you need and list them in
21
- `additionalFiles`.
22
-
23
- Number findings consecutively from `assignment.firstFindingId` (R-1, R-2, … or
24
- R-1001, R-1002, …); an empty array is valid. Use status COMPLETE when you
25
- reviewed every assigned file and filed every defect you found; otherwise
26
- PARTIAL with concrete `coverage.gaps`. Never hide unfinished work behind zero
27
- findings.
28
-
29
- Return:
30
- ```json
31
- {"status":"COMPLETE","coverage":{"files":["/src/example.ts"],"gaps":[]},"additionalFiles":[],"findings":[{"id":"R-1","summary":"Defect summary","location":"head:/src/example.ts:12","evidence":"HEAD/BASE pair, reachable failure sequence and impact","counterevidence":"Locks, transactions, guards or retry boundaries checked and why they do not refute it","severity":"medium","suggestion":"Correction and a focused regression case"}],"report":"Important exclusions with evidence, improvement advice, open questions and tests not run"}
32
- ```
33
-
34
- `coverage.files` lists assigned paths you actually reviewed. Omit `location` when
35
- you cannot establish it from source and explain why; the verifier will settle it.
36
- Keep `report` for exclusions, advice, open questions and limitations.