opencode-azure-devops-pr-review 0.4.5 → 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/setup.mjs CHANGED
@@ -11,8 +11,8 @@ import { open, readFile, lstat, mkdir, link, rename, stat, unlink } from 'node:f
11
11
  import { homedir } from 'node:os';
12
12
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { createHash, randomUUID } from 'node:crypto';
15
- import { COMMANDS, MODES, REPOSITORY, SETTING_CHECKS, modelRef, modelSlots, patProblem, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
14
+ import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto';
15
+ import { COMMANDS, MODES, REPOSITORY, SETTING_CHECKS, MAX_REVIEWERS, MIGRATION_NEEDED, isModelReference, migrateSettings, modelRef, patProblem, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
16
16
  import { parseUniqueJSON } from './output.mjs';
17
17
  import { appendReport } from './session.mjs';
18
18
  import { fetchTransportSupported, listOf, recordOf, requireMethods } from './host.mjs';
@@ -30,8 +30,9 @@ const CHECK_TIMEOUT_MS = 20000;
30
30
  // How long a first setup waits for OpenCode to drop the commands that only said that AZPR is not ready.
31
31
  const RELEASE_WAIT_MS = 3000;
32
32
  // The commands of a process without usable settings: each only says that AZPR cannot run here yet. The words are
33
- // true of every reason: no settings, settings that cannot be used, and settings that were saved elsewhere since
34
- // (by a setup in another project directory, say) and wait for a restart. /pr-setup tells which it is.
33
+ // true of every reason: no settings, settings that cannot be used, settings of 0.4.x that wait for their update,
34
+ // and settings that were saved elsewhere since (by a setup in another project directory, say) and wait for a
35
+ // restart. /pr-setup tells which it is.
35
36
  const PLACEHOLDER_DESCRIPTION = 'AZPR is not ready here; run /pr-setup to see what it needs';
36
37
  // Where every setting is described: the README is long, so its section is named, and linked for a terminal that opens links.
37
38
  const SETTINGS_REFERENCE = `the README's section "All settings and defaults" (https://github.com/${REPOSITORY}#all-settings-and-defaults)`;
@@ -110,6 +111,8 @@ export function parseSetupArguments(text) {
110
111
  if (FIRST_SETUP_FLAGS.some(flag => result[flag] !== undefined) && ['--organization', '--model'].some(flag => !result[flag])) {
111
112
  throw new Error('[AZPR] Supply --organization and --model (--pat-file is optional). Use /pr-setup --help.');
112
113
  }
114
+ // The update of settings of 0.4.x is one confirmed change of the whole file: nothing else travels with it.
115
+ if (result['--migrate'] !== undefined && Object.keys(result).length > 1) throw new Error('[AZPR] --migrate stands alone: update the settings first, then change them. Use /pr-setup --help.');
113
116
  return result;
114
117
  }
115
118
 
@@ -118,9 +121,6 @@ const text = value => typeof value === 'string' ? value : '';
118
121
  const OFF_WORD = /^(?:none|off)$/i;
119
122
  const azureOf = raw => object(raw.azure) ? raw.azure : {};
120
123
  const withAzure = (raw, values) => ({ ...raw, azure: { ...azureOf(raw), ...values } });
121
- const modelsOf = (raw, mode) => modelSlots(mode).map(slot => text(raw.models?.[mode]?.[slot]));
122
- const withModels = (raw, mode, value) => ({ ...raw, models: { ...(object(raw.models) ? raw.models : {}),
123
- [mode]: { ...(object(raw.models?.[mode]) ? raw.models[mode] : {}), ...Object.fromEntries(modelSlots(mode).map(slot => [slot, value])) } } });
124
124
  /** The one value that all of them have, or null when they differ. */
125
125
  const shared = values => values.every(value => value === values[0]) ? values[0] : null;
126
126
  /**
@@ -128,6 +128,37 @@ const shared = values => values.every(value => value === values[0]) ? values[0]
128
128
  * only that they differ, since the list has room for a few words; the settings file has each of them.
129
129
  */
130
130
  const together = (values, empty, differ) => shared(values) === null ? differ : shared(values) || empty;
131
+ // How many passes one model named for a mode becomes: a person can then add entries or take them away.
132
+ const USUAL_PASSES = Object.freeze({ review: 2, deep: 2, quick: 1 });
133
+ const NOT_A_MODEL = '(not a model ID)';
134
+ /** A mode's reviewer models as the settings have them: one entry per pass. */
135
+ const reviewersOf = (raw, mode) => Array.isArray(raw.models?.[mode]?.reviewers) ? raw.models[mode].reviewers.filter(item => typeof item === 'string') : [];
136
+ /** `raw` with that list for the mode; the mode's other settings (its rater) stay. */
137
+ const withReviewers = (raw, mode, list) => ({ ...raw, models: { ...(object(raw.models) ? raw.models : {}),
138
+ [mode]: { ...(object(raw.models?.[mode]) ? raw.models[mode] : {}), reviewers: list } } });
139
+ /** A list as runs of one model: [[model, count], …]. */
140
+ const runs = list => list.reduce((all, model) => { if (all.at(-1)?.[0] === model) all.at(-1)[1]++; else all.push([model, 1]); return all; }, []);
141
+ /**
142
+ * A list as text, the form an option and a dialog give it in: entries separated by commas, a model that
143
+ * runs several passes in a row as MODEL*N. A model always carries its count here, also a single one
144
+ * (MODEL*1): a model named alone, without a count, means the mode's usual number of passes.
145
+ */
146
+ const reviewersText = list => runs(list).map(([model, count]) => `${model}*${count}`).join(',');
147
+ /** A list as a row of the settings list shows it, in a few words: each model without its provider, with its count. */
148
+ function reviewersShown(list, empty) {
149
+ if (!list.length) return empty;
150
+ const shown = list.map(model => isModelReference(model) ? model : NOT_A_MODEL);
151
+ const short = model => model === NOT_A_MODEL ? model : model.slice(model.indexOf('/') + 1);
152
+ // Passes are counted by the whole reference; a model keeps its provider where another provider has one of that name.
153
+ const providers = new Map();
154
+ for (const model of new Set(shown)) providers.set(short(model), (providers.get(short(model)) ?? 0) + 1);
155
+ return runs(shown).map(([model, count]) => `${providers.get(short(model)) > 1 ? model : short(model)}${count > 1 ? ` ×${count}` : ''}`).join(' + ');
156
+ }
157
+ /**
158
+ * The entries of a list that are model IDs. What a settings file holds in a model's place may be anything, a
159
+ * pasted token included: a row names such an entry (`NOT_A_MODEL`) and never returns it.
160
+ */
161
+ const modelsOnly = list => list.filter(isModelReference);
131
162
  /** A path as a row of the list shows it: its last two parts where it is long. The dialog of the row has all of it. */
132
163
  const shortPath = value => value.length <= 30 ? value : `…/${value.split('/').filter(Boolean).slice(-2).join('/')}`.slice(0, 34);
133
164
  /** A proxy as it may be shown: scheme, host and port, and whether it carries a user name and password. */
@@ -164,13 +195,35 @@ async function caFileOf(answer) {
164
195
  await readCaCertificates(value);
165
196
  return value;
166
197
  }
167
- async function modelOf(context, answer, optional) {
198
+ async function modelOf(context, answer) {
168
199
  const value = text(answer).trim();
169
- if (optional && (value === '' || OFF_WORD.test(value))) return '';
170
200
  valid(SETTING_CHECKS.model, value, 'The model');
171
- await checkModel(context, value);
201
+ await checkModels(context, [value]);
172
202
  return value;
173
203
  }
204
+ /**
205
+ * A mode's reviewer models from an answer: MODEL (the mode's usual number of passes of that model), or
206
+ * entries separated by commas, each MODEL or MODEL*N, in the order of the passes (at most four in all);
207
+ * `off` or `none` where the mode may be off. A model reference holds neither a comma nor a star. What is
208
+ * wrong is said by the entry's position, never by quoting it.
209
+ */
210
+ async function reviewersFrom(context, answer, row) {
211
+ const value = text(answer).trim();
212
+ if (row.optional && (value === '' || OFF_WORD.test(value))) return [];
213
+ const entries = value.split(',').map(entry => entry.trim());
214
+ const list = [];
215
+ for (const [index, entry] of entries.entries()) {
216
+ const star = entry.lastIndexOf('*'), model = star < 0 ? entry : entry.slice(0, star).trim();
217
+ const count = star < 0 ? (entries.length === 1 ? USUAL_PASSES[row.mode] : 1) : /^[1-9]\d?$/.test(entry.slice(star + 1).trim()) ? Number(entry.slice(star + 1)) : 0;
218
+ const name = entries.length === 1 ? 'The model' : `Entry ${index + 1}`;
219
+ valid(SETTING_CHECKS.model, model, name);
220
+ if (!count) throw new Error(`[AZPR] ${name}: after the star comes the number of passes, 1 to ${MAX_REVIEWERS}.`);
221
+ for (let pass = 0; pass < count; pass++) list.push(model);
222
+ }
223
+ if (list.length > MAX_REVIEWERS) throw new Error(`[AZPR] ${row.label} take at most ${MAX_REVIEWERS} passes in all.`);
224
+ await checkModels(context, list);
225
+ return list;
226
+ }
174
227
  const choiceOf = (row, answer) => {
175
228
  const value = text(answer).trim();
176
229
  if (!row.choices.some(choice => choice.value === value)) throw new Error(`[AZPR] ${row.label} must be one of: ${row.choices.map(choice => choice.value).join(', ')}.`);
@@ -208,17 +261,17 @@ const ROWS = Object.freeze([
208
261
  description: () => 'Only where a company proxy inspects HTTPS: the absolute path of its root CA certificate, a PEM file. Leave it empty and press Enter to skip.',
209
262
  get: raw => text(azureOf(raw).caFile), show: value => value ? shortPath(value) : 'none', current: value => value,
210
263
  accept: async (_context, answer) => caFileOf(answer), set: (raw, value) => withAzure(raw, { caFile: value }) },
211
- { id: 'reviewModel', flag: '--review-model', group: 'Models', label: 'Review model', kind: 'model', title: 'Model for /pr-review', hint: 'for /pr-review',
212
- get: raw => modelsOf(raw, 'review'), show: values => together(values, 'not set', 'differs by role'), current: values => shared(values) ?? '',
213
- accept: (context, answer) => modelOf(context, answer, false), set: (raw, value) => withModels(raw, 'review', value) },
214
- { id: 'quickModel', flag: '--quick-model', group: 'Models', label: 'Quick model', kind: 'model', title: 'Model for /pr-quick', hint: 'for /pr-quick', optional: { label: 'Off', description: '/pr-quick stays off' },
215
- get: raw => modelsOf(raw, 'quick'), show: values => values[0] || 'off', current: values => values[0],
216
- accept: (context, answer) => modelOf(context, answer, true), set: (raw, value) => withModels(raw, 'quick', value) },
217
- { id: 'deepModel', flag: '--deep-model', group: 'Models', label: 'Deep model', kind: 'model', title: 'Model for /pr-deep', hint: 'for /pr-deep',
218
- // /pr-deep is the same review with stronger models: another model, or the same one reasoning longer.
264
+ { id: 'reviewModel', flag: '--review-model', group: 'Models', label: 'Review models', kind: 'model', mode: 'review', title: 'Model for /pr-review', hint: 'for /pr-review',
265
+ get: raw => reviewersOf(raw, 'review'), show: list => reviewersShown(list, 'not set'), current: list => reviewersText(modelsOnly(list)),
266
+ accept: (context, answer, _raw, row) => reviewersFrom(context, answer, row), set: (raw, list) => withReviewers(raw, 'review', list) },
267
+ { id: 'quickModel', flag: '--quick-model', group: 'Models', label: 'Quick models', kind: 'model', mode: 'quick', title: 'Model for /pr-quick', hint: 'for /pr-quick', optional: { label: 'Off', description: '/pr-quick stays off' },
268
+ get: raw => reviewersOf(raw, 'quick'), show: list => reviewersShown(list, 'off'), current: list => reviewersText(modelsOnly(list)),
269
+ accept: (context, answer, _raw, row) => reviewersFrom(context, answer, row), set: (raw, list) => withReviewers(raw, 'quick', list) },
270
+ { id: 'deepModel', flag: '--deep-model', group: 'Models', label: 'Deep models', kind: 'model', mode: 'deep', title: 'Model for /pr-deep', hint: 'for /pr-deep',
271
+ // /pr-deep is the same review with stronger models: another model, the same one reasoning longer, or more passes.
219
272
  prompt: 'Stronger than the review model, or a higher variant', variantPrompt: 'A higher variant reasons longer', optional: { label: 'Off', description: '/pr-deep stays off' },
220
- get: raw => modelsOf(raw, 'deep'), show: values => together(values, 'off', 'differs by role'), current: values => shared(values) ?? '',
221
- accept: (context, answer) => modelOf(context, answer, true), set: (raw, value) => withModels(raw, 'deep', value) },
273
+ get: raw => reviewersOf(raw, 'deep'), show: list => reviewersShown(list, 'off'), current: list => reviewersText(modelsOnly(list)),
274
+ accept: (context, answer, _raw, row) => reviewersFrom(context, answer, row), set: (raw, list) => withReviewers(raw, 'deep', list) },
222
275
  { id: 'language', flag: '--language', group: 'Reviews', label: 'Output language', kind: 'choice', title: 'Language of reports and comments',
223
276
  choices: LANGUAGES.map(([value, label]) => ({ value, label, description: value })),
224
277
  other: { label: 'Another language', title: 'Language of reports and comments', description: 'A language tag such as en, zh-TW, pt-BR or it.', placeholder: 'pt-BR' },
@@ -246,18 +299,27 @@ const ROWS = Object.freeze([
246
299
  const rowOf = id => ROWS.find(row => row.id === id);
247
300
  /** --model, --pat-file and --replace belong to a first setup, as does --organization; the other options change one setting each. */
248
301
  const FIRST_SETUP_FLAGS = Object.freeze(['--organization', '--model', '--pat-file', '--replace']);
249
- const SETUP_FLAGS = Object.freeze([...new Set([...FIRST_SETUP_FLAGS, ...ROWS.flatMap(row => row.flag ? [row.flag] : [])])]);
302
+ /** --migrate WORD confirms the update of settings of 0.4.x that /pr-setup alone showed: the word names that very change. */
303
+ const SETUP_FLAGS = Object.freeze([...new Set([...FIRST_SETUP_FLAGS, '--migrate', ...ROWS.flatMap(row => row.flag ? [row.flag] : [])])]);
250
304
 
251
- async function checkModel(context, value) {
305
+ /** Whether OpenCode offers each of these models, enabled, with tools and with the variant named; one listing for all of them. */
306
+ /** Each model of a list exists in OpenCode, can call tools and has its variant. A model is named by the place of its first entry, never quoted. */
307
+ async function checkModels(context, values) {
252
308
  if (typeof context.model?.list !== 'function') throw new Error('[AZPR] The model catalog is unavailable. Connect a model provider in OpenCode, then retry setup.');
253
309
  const catalog = listOf(await context.model.list());
254
310
  if (!catalog) throw new Error('[AZPR] The model catalog is unavailable; settings were not changed.');
255
- const { providerID, id, variant } = modelRef(value);
256
- const selected = catalog.find(item => item.providerID === providerID && item.id === id);
257
- if (!selected || selected.enabled === false) throw new Error('[AZPR] The selected model is unavailable in OpenCode. Choose an enabled ID from opencode models.');
258
- if (selected.capabilities?.tools !== true) throw new Error('[AZPR] The selected model must support tools.');
259
- if (variant && variant !== 'default' && (!Array.isArray(selected.variants) || !selected.variants.some(item => item.id === variant))) {
260
- throw new Error('[AZPR] The selected model does not offer that variant.');
311
+ // A list of one model (also of several passes of it) needs no place; a list of different models names the entry.
312
+ const several = new Set(values).size > 1;
313
+ for (const [index, value] of values.entries()) {
314
+ if (values.indexOf(value) !== index) continue;
315
+ const which = several ? ` (entry ${index + 1} of the list)` : '';
316
+ const { providerID, id, variant } = modelRef(value);
317
+ const selected = catalog.find(item => item.providerID === providerID && item.id === id);
318
+ if (!selected || selected.enabled === false) throw new Error(`[AZPR] The selected model is unavailable in OpenCode${which}. Choose an enabled ID from opencode models.`);
319
+ if (selected.capabilities?.tools !== true) throw new Error(`[AZPR] The selected model must support tools${which}.`);
320
+ if (variant && variant !== 'default' && (!Array.isArray(selected.variants) || !selected.variants.some(item => item.id === variant))) {
321
+ throw new Error(`[AZPR] The selected model does not offer that variant${which}.`);
322
+ }
261
323
  }
262
324
  }
263
325
 
@@ -282,6 +344,81 @@ async function readExisting(path) {
282
344
  }
283
345
  }
284
346
 
347
+ // The word that names one update of settings of 0.4.x is a keyed digest, with a key of this process: it says
348
+ // nothing of a file that may hold a token, and a word of another process, or of before a restart, names nothing.
349
+ const MIGRATION_KEY = randomBytes(16);
350
+ const shownModel = value => isModelReference(value) ? value : NOT_A_MODEL;
351
+
352
+ /**
353
+ * What a settings text of AZPR 0.4.x becomes; null for any other text. `settings` is the complete file of
354
+ * this version (`written` its text), `problem` says why that file cannot be used yet ('' when it can: every
355
+ * settings file that 0.4.x could use gives one that this version can use), `lines` say what changes, in the
356
+ * words /pr-setup shows, and `word` names this very change: the text it replaces and the text it writes.
357
+ * Every settings text of 0.4.x is changed by this update alone, also one with a fault: a repair that rewrote
358
+ * the file in this version's layout would change its models, its rating and what automatic publication posts
359
+ * without any of it being shown.
360
+ */
361
+ function migrationOf(previous) {
362
+ let raw;
363
+ try { raw = settingsJSON(previous); } catch { return null; }
364
+ if (raw.version !== 2) return null;
365
+ let migrated, summary;
366
+ try { ({ settings: migrated, summary } = migrateSettings(raw)); } catch { return null; }
367
+ // The update repairs nothing: settings it leaves unusable are written as it leaves them, and the problem is
368
+ // named; only usable ones get what they leave out at its defaults, as the loader completes a valid file only.
369
+ let problem = '';
370
+ try { validateSettings(migrated); } catch (error) { problem = typeof error?.message === 'string' ? error.message : 'the settings could not be used.'; }
371
+ const settings = problem ? migrated : withMissingSettings(migrated).settings;
372
+ const written = settingsText(settings);
373
+ const word = createHmac('sha256', MIGRATION_KEY).update(previous).update('\0').update(written).digest('hex').slice(0, 12);
374
+ return { migrated, settings, written, problem, word, lines: migrationLines(summary, problem) };
375
+ }
376
+
377
+ /** What an update of settings of 0.4.x changes, one line per point: values that are no model IDs are named, never shown. */
378
+ function migrationLines({ modes, shardFindings, publish }, problem = '') {
379
+ const lines = ['This version reviews with a list of reviewer models per mode: each entry reviews the changed files on its own, one pass each. There is no verifier any more: the first entry also merges repeated findings and plans the comments, and a rating sets the severities.'];
380
+ // Models that are no model IDs: none chosen yet (placeholders), or values that 0.4.x could not use either,
381
+ // which the update keeps where they go now for the settings check to name.
382
+ const unchosen = list => Array.isArray(list) && list.length > 0 && list.every(item => typeof item === 'string' && /REPLACE_|YOUR_PROVIDER|YOUR_MODEL/.test(item));
383
+ const kept = mode => modes[mode].value ? `/pr-${mode}: its settings are not a group of models, so the file could not be used before either; they are kept as they are, and the settings check names them after the update.`
384
+ : modes[mode].clash ? `/pr-${mode}: its settings name reviewers, which 0.4.x did not know, so the file could not be used before either; they are kept as they are, and the settings check names them after the update.`
385
+ : unchosen(modes[mode].after.reviewers) ? `/pr-${mode}: no model was chosen yet. Choose its models with /pr-setup after the update.`
386
+ : `/pr-${mode}: its models are not all model IDs, so the file could not be used before either; they are kept as they are, and the settings check names them after the update.`;
387
+ // A group the file already wrote as this version writes one runs as it is: what it runs is named.
388
+ const current = mode => {
389
+ const { reviewers } = modes[mode].after;
390
+ return reviewers.length ? `/pr-${mode}: the file already names its reviewers as this version does, so they stay -> ${reviewers.length} pass${reviewers.length === 1 ? '' : 'es'}: ${reviewers.map(shownModel).join(', ')}.`
391
+ : `/pr-${mode}: the file already names its reviewers as this version does, none, so it stays off.`;
392
+ };
393
+ for (const mode of ['review', 'deep']) {
394
+ const { before, after, state } = modes[mode];
395
+ if (modes[mode].current) lines.push(current(mode));
396
+ else if (state === 'kept') lines.push(kept(mode));
397
+ else if (state === 'on') lines.push(`/pr-${mode}: functional ${shownModel(before.functional)}, risk ${shownModel(before.risk)}, verifier ${shownModel(before.verifier)} -> ${after.reviewers.length} passes: ${after.reviewers.map(shownModel).join(', ')}. The verifier model is no longer used.`);
398
+ else if (state === 'partial') lines.push(`/pr-${mode}: only some of its three models were set, so it was off and stays off (models.${mode}.reviewers is empty). Set it afterwards with /pr-setup.`);
399
+ else lines.push(`/pr-${mode}: off, stays off.`);
400
+ }
401
+ lines.push(modes.quick.current ? current('quick') : modes.quick.state === 'kept' ? kept('quick') : modes.quick.state !== 'on' ? '/pr-quick: off, stays off.'
402
+ : `/pr-quick: reviewer ${shownModel(modes.quick.before.reviewer)} -> 1 pass: ${shownModel(modes.quick.after.reviewers[0])}.`);
403
+ // The rating of every mode that runs, and a rater the file names wherever it is no model ID or false.
404
+ const rated = MODES.filter(mode => modes[mode].state === 'on'), raterOf = mode => modes[mode].after.rater;
405
+ const off = rated.filter(mode => raterOf(mode) === false), inherited = rated.filter(mode => raterOf(mode) === '');
406
+ if (off.length) lines.push(`Severity rating of ${off.map(mode => `/pr-${mode}`).join(', ')}: off ("rater": false), as the file says.`);
407
+ for (const mode of rated.filter(mode => isModelReference(raterOf(mode)))) {
408
+ lines.push(`Severity rating of /pr-${mode}: ${raterOf(mode)}, ${modes[mode].current ? 'as the file names it' : mode === 'quick' ? 'as the file names it (0.4.x had no rating for /pr-quick)' : 'as before'}.`);
409
+ }
410
+ for (const mode of MODES.filter(mode => modes[mode].state !== 'kept' && ![undefined, '', false].includes(raterOf(mode)) && !isModelReference(raterOf(mode)))) {
411
+ lines.push(`Severity rating of /pr-${mode}: the rater the file names is no model ID; it is kept as it is, and the settings check names it after the update.`);
412
+ }
413
+ if (inherited.length) lines.push(`Severity rating of ${inherited.map(mode => `/pr-${mode}`).join(', ')}: none ran before (no rater was set). From now on the first reviewer model rates the findings from their text alone; "rater": false in the settings file switches that off.`);
414
+ if (shardFindings !== undefined) lines.push('workflow.shardFindings is dropped: it sized the verifier\'s batches.');
415
+ if (publish.length) lines.push(`afterReview is "publish" for ${publish.map(mode => `/pr-${mode}`).join(', ')}: after the update ${publish.length > 1 ? 'these commands post' : 'this command posts'} the comments of the new reviews automatically, as the PAT owner. Reports and comments then say that findings were checked by their reviewer and that no separate verification ran. To read the comments before they are posted, set afterReview to preview for ${publish.length > 1 ? 'these modes' : 'this mode'}.`);
416
+ lines.push('Every other setting stays as it is, also one that is not a setting of this version: the settings check then names it.');
417
+ // A file that had a fault keeps it: the update changes the layout, and the repair follows it.
418
+ if (problem) lines.push(`After the update the settings still cannot be used: ${problem} Nothing runs until that is set right, with /pr-setup or in the settings file.`);
419
+ return lines;
420
+ }
421
+
285
422
  /**
286
423
  * Atomic, owner-only save; serialize setup calls and preserve unrelated values.
287
424
  * The options of a first setup (--organization, --model, --pat-file) create the file, or with --replace
@@ -295,14 +432,27 @@ async function readExisting(path) {
295
432
  export async function saveSetup(context, path, arguments_, environment = process.env) {
296
433
  const previous = await readExisting(path);
297
434
  const first = FIRST_SETUP_FLAGS.some(flag => arguments_[flag] !== undefined);
435
+ // Settings of 0.4.x take one change only: the update a person confirms with the word /pr-setup showed for
436
+ // it. No other option implies that consent, also not those of a first setup or one that repairs a fault.
437
+ const migration = previous === null ? null : migrationOf(previous);
438
+ if (migration) {
439
+ const word = arguments_['--migrate'];
440
+ if (word === undefined) throw new Error(`[AZPR] ${MIGRATION_NEEDED} Other options work after that.`);
441
+ if (word !== migration.word) throw new Error('[AZPR] That word names no update of the settings file as it is now (the file changed, or OpenCode was restarted since). Run /pr-setup alone and use the word it shows.');
442
+ const held = await settingsTextProblem(previous);
443
+ await writeSettings(path, previous, migration.settings);
444
+ return { organization: text(migration.settings.azure?.organization), patFile: text(migration.settings.azure?.patFile), changed: [], first: false, migrated: true, remaining: migration.problem,
445
+ unusable: Boolean(held.problem), before: pairWith(previous, held.digest), after: pairWith(migration.written, held.digest) };
446
+ }
447
+ if (arguments_['--migrate'] !== undefined) throw new Error('[AZPR] These settings need no update: --migrate is only for settings of AZPR 0.4.x that /pr-setup offers to update.');
298
448
  if (previous === null && !first) {
299
449
  throw new Error('[AZPR] There are no settings yet. Supply --organization and --model, or run /pr-setup alone in OpenCode\'s terminal UI. Use /pr-setup --help.');
300
450
  }
301
451
  if (previous !== null && first && !arguments_['--replace']) {
302
- throw new Error('[AZPR] Settings already exist. Add --replace to change organization, PAT file and all review/quick model slots while keeping other settings.');
452
+ throw new Error('[AZPR] Settings already exist. Add --replace to change organization, PAT file and the review and quick models while keeping other settings.');
303
453
  }
304
- const raw = previous === null ? { version: 2 } : settingsJSON(previous);
305
- if (raw.version !== 2) throw new Error('[AZPR] Setup supports only version-2 settings; existing data was preserved.');
454
+ const raw = previous === null ? { version: 3 } : settingsJSON(previous);
455
+ if (raw.version !== 3) throw new Error('[AZPR] Setup supports only version-3 settings; existing data was preserved.');
306
456
  if (raw.models !== undefined && !object(raw.models) || raw.azure !== undefined && !object(raw.azure)) {
307
457
  throw new Error('[AZPR] Repair models and azure objects in settings.json before setup; existing data was preserved.');
308
458
  }
@@ -320,10 +470,12 @@ export async function saveSetup(context, path, arguments_, environment = process
320
470
  if (typeof patFile !== 'string' || !isAbsolute(patFile) || resolve(patFile) === resolve(path)) {
321
471
  throw new Error('[AZPR] --pat-file must name an absolute path separate from settings.json.');
322
472
  }
323
- next = { ...raw, models: { ...raw.models, review: { functional: model, risk: model, verifier: model }, quick: { reviewer: model } },
473
+ // One model named for a first setup: the usual passes of /pr-review and of /pr-quick; /pr-deep stays as it is.
474
+ valid(SETTING_CHECKS.model, model, 'The model');
475
+ next = { ...withReviewers(withReviewers(raw, 'review', Array(USUAL_PASSES.review).fill(model)), 'quick', Array(USUAL_PASSES.quick).fill(model)),
324
476
  azure: { ...raw.azure, organization, pat: '', patFile } };
325
477
  validateSettings(withMissingSettings(next).settings);
326
- await checkModel(context, model);
478
+ await checkModels(context, [model]);
327
479
  // The PAT file must be usable. Its token goes with what this save leaves when the settings name the file
328
480
  // anew; for a file they named already, the token is the one of the look above, whatever is there by now.
329
481
  try {
@@ -556,22 +708,30 @@ export async function addMissingSettings(path, { waitMs = 3000, pauseMs = 100, p
556
708
  }
557
709
  }
558
710
 
559
- async function guide(context, path, problem, environment) {
711
+ /** What /pr-setup alone and --help say. For settings of 0.4.x that can be updated: what the update changes, and how to confirm it. */
712
+ async function guide(context, path, problem, environment, migration) {
713
+ if (migration) {
714
+ return `[AZPR] SETTINGS UPDATE\nSettings: ${path}\n\nThese settings are from AZPR 0.4.x. Reviews run again once the file is updated to this version; nothing is changed until you confirm.\n\n` +
715
+ `${migration.lines.map(line => `- ${line}`).join('\n')}\n\n` +
716
+ `In OpenCode's terminal UI, /pr-setup alone asks whether to update the file. In other clients, confirm with:\n\n/pr-setup --migrate ${migration.word}\n\n` +
717
+ 'The word names this very change: when the settings file changes before you confirm, /pr-setup shows the update again. No model request or Azure request is made.';
718
+ }
560
719
  let catalog = [], patFile;
561
720
  try { catalog = (listOf(await context.model.list()) ?? []).filter(item => item.enabled !== false && item.capabilities?.tools === true); } catch { /* Help remains usable before provider setup. */ }
562
721
  try { patFile = defaultPatFile(environment); } catch { patFile = '$XDG_CONFIG_HOME/azpr/pat'; }
563
722
  const models = catalog.slice(0, 12).map(item => `${item.providerID}/${item.id}`);
564
723
  const options = ROWS.filter(row => row.flag && row.flag !== '--organization').map(row => `${row.flag} ${row.other ? 'TAG' : row.kind === 'choice' ? row.choices.map(choice => choice.value).join('|')
565
- : row.kind === 'model' ? `PROVIDER/MODEL${row.optional ? '|off' : ''}` : row.id === 'proxy' ? 'URL|none' : 'PATH|none'}`);
724
+ : row.kind === 'model' ? `MODELS${row.optional ? '|off' : ''}` : row.id === 'proxy' ? 'URL|none' : 'PATH|none'}`);
566
725
  return `[AZPR] SETUP${problem ? ' REQUIRED' : ''}\nSettings: ${path}\n${problem ? `Problem when OpenCode loaded AZPR: ${problem}\n` : ''}\n` +
567
726
  'In OpenCode\'s terminal UI, /pr-setup alone asks for the organization, an optional proxy, the token and a model in dialogs, checks the token with Azure DevOps and saves it for you; afterwards it lists the settings to change. In other clients, or to script it:\n\n' +
568
727
  `1. Connect your provider in OpenCode and choose one tool-capable model ID (${models.length ? models.join(', ') : 'run opencode models'}).\n` +
569
728
  `2. Create an Azure DevOps PAT for one organization with Code (Read) and Pull Request Threads (Read & write). Keep it alone in a regular file owned by you, with mode 600 (by default ${patFile}); never paste it into this conversation.\n` +
570
729
  `3. Run ${USAGE}\n\n` +
571
730
  '--organization also takes a PR or organization URL. Without --pat-file, setup uses the default PAT file, or with --replace the PAT file already set. ' +
572
- 'The selected model fills the three review roles and the quick reviewer. Deep remains unchanged (off for a new profile). Existing settings require --replace for these three options; other settings are kept. No model request or Azure request is made.\n\n' +
731
+ 'The selected model reviews twice in /pr-review and once in /pr-quick. Deep remains unchanged (off for a new profile). Existing settings require --replace for these three options; other settings are kept. No model request or Azure request is made.\n\n' +
573
732
  `One setting of existing settings is changed without --replace: ${options.join(', ')}. A model takes a variant as PROVIDER/MODEL#VARIANT. ` +
574
- `--deep-model sets the models of /pr-deep, which runs the same review: choose a stronger model than the review model, or the same model with a higher variant. Every setting is described in ${SETTINGS_REFERENCE}.\n\n` +
733
+ `MODELS is a mode's review passes in order: PROVIDER/MODEL alone means that mode's usual number of passes of one model (review 2, deep 2, quick 1); MODEL*N sets the number (MODEL*1 is one pass), and entries separated by commas run different models, one pass each, at most ${MAX_REVIEWERS} passes in all (A,B or A*2,B). The first entry also merges repeated findings, plans the comments and rates the severities. ` +
734
+ `--deep-model sets the models of /pr-deep, which runs the same review: choose a stronger model than the review model, the same model with a higher variant, or more passes. Every setting is described in ${SETTINGS_REFERENCE}.\n\n` +
575
735
  `A first setup is loaded at once. After a later change, ${RESTART}. Then run /pr-check <PR URL>. Settings changes do not affect reviews already running.`;
576
736
  }
577
737
 
@@ -601,7 +761,9 @@ async function settingsTextProblem(text) {
601
761
  if (raw.enabled === false) return { disabled: true, problem: '', digest: await tokenDigest(text) };
602
762
  settings = validateSettings(raw);
603
763
  } catch (error) {
604
- return { problem: error instanceof Error && error.message ? error.message.replace(/^\[AZPR\] /, '') : 'the settings could not be loaded.', digest: await tokenDigest(text) };
764
+ return { problem: error instanceof Error && error.message ? error.message.replace(/^\[AZPR\] /, '') : 'the settings could not be loaded.', digest: await tokenDigest(text),
765
+ // Settings of 0.4.x: not a fault to repair, an update to confirm.
766
+ ...(error?.needsMigration ? { migration: true } : {}) };
605
767
  }
606
768
  if (!settings.azure.patFile) return { problem: '', digest: '' };
607
769
  try { return { problem: '', digest: digestOf(await readPatFile(settings.azure.patFile)) }; }
@@ -669,12 +831,19 @@ function createSetupService({ context, path, environment, options, loaded, saved
669
831
  let previous;
670
832
  try { previous = await readExisting(path); }
671
833
  catch (error) { return { previous: undefined, raw: null, fileProblem: said(error, `The settings file could not be read (${error?.code ?? 'unknown error'}).`) }; }
672
- if (previous === null) return { previous, raw: { version: 2 }, fileProblem: '' };
834
+ if (previous === null) return { previous, raw: { version: 3 }, fileProblem: '' };
673
835
  try {
836
+ // Settings of 0.4.x are changed in one way only, the update a person confirms: no row of theirs is edited,
837
+ // also not to repair a fault.
838
+ const migration = migrationOf(previous);
839
+ if (migration) return { previous, raw: null, fileProblem: MIGRATION_NEEDED, migration };
674
840
  const raw = settingsJSON(previous);
675
- if (raw.version !== 2) throw new Error('[AZPR] Setup supports only version-2 settings.');
841
+ if (raw.version !== 3) throw new Error('[AZPR] Setup supports only version-3 settings.');
676
842
  for (const name of ['models', 'azure', 'debug', 'afterReview']) if (raw[name] !== undefined && !object(raw[name])) throw new Error(`[AZPR] "${name}" in the settings file is not a JSON object.`);
677
- if (object(raw.models)) for (const mode of MODES) if (raw.models[mode] !== undefined && !object(raw.models[mode])) throw new Error(`[AZPR] "models.${mode}" in the settings file is not a JSON object.`);
843
+ if (object(raw.models)) for (const mode of MODES) {
844
+ if (raw.models[mode] !== undefined && !object(raw.models[mode])) throw new Error(`[AZPR] "models.${mode}" in the settings file is not a JSON object.`);
845
+ if (raw.models[mode]?.reviewers !== undefined && !Array.isArray(raw.models[mode].reviewers)) throw new Error(`[AZPR] "models.${mode}.reviewers" in the settings file is not a list.`);
846
+ }
678
847
  return { previous, raw, fileProblem: '' };
679
848
  } catch (error) { return { previous, raw: null, fileProblem: said(error, 'The settings file could not be read as settings.') }; }
680
849
  }
@@ -712,8 +881,8 @@ function createSetupService({ context, path, environment, options, loaded, saved
712
881
  };
713
882
 
714
883
  async function status() {
715
- const { previous, raw, fileProblem } = await current();
716
- const view = withMissingSettings(raw ?? { version: 2 }).settings;
884
+ const { previous, raw, fileProblem, migration } = await current();
885
+ const view = withMissingSettings(raw ?? migration?.settings ?? { version: 3 }).settings;
717
886
  const token = await tokenState(view);
718
887
  const use = loaded();
719
888
  // A process that found no usable settings: setup is required while there are none, and once there are some
@@ -723,10 +892,14 @@ function createSetupService({ context, path, environment, options, loaded, saved
723
892
  // For settings in use the runtime itself says whether it would refuse new runs, by the rule of its
724
893
  // preflight: any difference of the settings text but the defaults a load wrote into it, and any other
725
894
  // content of the PAT file, whoever wrote them.
726
- const state = use.blocked ? ((await settingsProblem(path)).problem ? 'required' : 'restart')
727
- : previous === null ? 'required'
728
- : (await drifted(use)) ? 'restart' : 'ready';
895
+ // Settings of 0.4.x that can be updated are neither missing nor faulty: `migrate`, with what the update
896
+ // changes and the word that confirms it. Their rows are shown as they will be and cannot be edited before.
897
+ const state = migration ? 'migrate'
898
+ : use.blocked ? ((await settingsProblem(path)).problem ? 'required' : 'restart')
899
+ : previous === null ? 'required'
900
+ : (await drifted(use)) ? 'restart' : 'ready';
729
901
  return { version: 1, state, problem: use.blocked ? use.problem : '', editable: raw !== null, fileProblem,
902
+ ...(migration ? { migration: { lines: migration.lines, word: migration.word } } : {}),
730
903
  settingsFile: path, settingsFileShown: shortPath(shownPath(path)), settingsReference: SETTINGS_REFERENCE, organization: text(azureOf(view).organization),
731
904
  rows: ROWS.map(row => row.kind === 'secret'
732
905
  ? { id: row.id, group: row.group, label: row.label, kind: row.kind, title: row.title, description: `${row.description(view, environment)}${token.note ? ` ${token.note}` : ''}`, value: token.shown, saved: token.saved,
@@ -735,7 +908,9 @@ function createSetupService({ context, path, environment, options, loaded, saved
735
908
  : { id: row.id, group: row.group, label: row.label, kind: row.kind, title: row.title, value: row.show(row.get(view)), current: row.current(row.get(view)),
736
909
  ...(row.description ? { description: row.description(view, environment) } : {}), ...(row.placeholder ? { placeholder: row.placeholder } : {}),
737
910
  ...(row.hint ? { hint: row.hint } : {}), ...(row.prompt ? { prompt: row.prompt } : {}), ...(row.variantPrompt ? { variantPrompt: row.variantPrompt } : {}),
738
- ...(row.optional ? { optional: row.optional } : {}), ...(row.choices ? { choices: row.choices } : {}), ...(row.other ? { other: row.other } : {}) }) };
911
+ ...(row.optional ? { optional: row.optional } : {}), ...(row.choices ? { choices: row.choices } : {}), ...(row.other ? { other: row.other } : {}),
912
+ // A list of models: its entries, how many passes one model named alone becomes, and how many there may be.
913
+ ...(row.mode ? { entries: modelsOnly(row.get(view)), usual: USUAL_PASSES[row.mode], most: MAX_REVIEWERS } : {}) }) };
739
914
  }
740
915
 
741
916
  /** An answer that is given is text, as a dialog gives it: anything else is no answer, not an empty one. */
@@ -743,7 +918,10 @@ function createSetupService({ context, path, environment, options, loaded, saved
743
918
  for (const name of names) if (input[name] !== undefined && typeof input[name] !== 'string') throw new Error('[AZPR] Setup takes each answer as text.');
744
919
  };
745
920
 
746
- /** The answers of `changes` in their saved form, applied to `raw`; `model` stands for the review and the quick model. */
921
+ /**
922
+ * The answers of `changes` in their saved form, applied to `raw`; `model` stands for the review and the quick
923
+ * models: one model named for a first setup, the usual number of passes of each of the two modes.
924
+ */
747
925
  async function apply(raw, changes) {
748
926
  if (!object(changes)) throw new Error('[AZPR] Setup was given no settings to change.');
749
927
  let next = raw;
@@ -761,7 +939,8 @@ function createSetupService({ context, path, environment, options, loaded, saved
761
939
  // not those of a proxy that was just typed either. For such a proxy nothing goes back, and the dialog
762
940
  // keeps what was typed.
763
941
  if (row.id === 'proxy' && value && shownProxy(value).endsWith(')')) { if (text(answer).trim() !== value) values[id] = text(answer).trim(); }
764
- else values[id] = row.kind === 'choice' && typeof value === 'boolean' ? (value ? 'on' : 'off') : value;
942
+ // A list goes back as the text an answer gives it in, so that a dialog can start from it again.
943
+ else values[id] = row.kind === 'choice' && typeof value === 'boolean' ? (value ? 'on' : 'off') : Array.isArray(value) ? row.current(value) : value;
765
944
  shown[id] = row.show(row.get(withMissingSettings(next).settings));
766
945
  }
767
946
  }
@@ -842,8 +1021,19 @@ function createSetupService({ context, path, environment, options, loaded, saved
842
1021
  if (turn.busy) return { ok: false, problem: 'Another setup is being saved.' };
843
1022
  turn.busy = true;
844
1023
  try {
845
- textual(input, ['token', 'organization']);
846
- const { previous, raw, fileProblem } = await current();
1024
+ textual(input, ['token', 'organization', 'migrate']);
1025
+ const { previous, raw, fileProblem, migration } = await current();
1026
+ if (input.migrate !== undefined) {
1027
+ // The update of settings of 0.4.x: confirmed by the word that names what was shown, and saved alone.
1028
+ if (input.changes !== undefined || input.token !== undefined || input.organization !== undefined) return { ok: false, problem: 'The update of the settings is saved by itself, before anything else is changed.' };
1029
+ if (!migration) return { ok: false, problem: 'These settings need no update.' };
1030
+ if (input.migrate !== migration.word) return { ok: false, problem: 'The settings file changed since the update was shown, or OpenCode was restarted since, so nothing was saved. Run /pr-setup again to see the update as it is now.' };
1031
+ const held = await settingsTextProblem(previous);
1032
+ await writeSettings(path, previous, migration.settings, options.settingsPrepared);
1033
+ await saved({ made: loaded().blocked && Boolean(held.problem), before: pairWith(previous, held.digest), after: pairWith(migration.written, held.digest) });
1034
+ // What the updated file still lacks, if anything: the dialogs go on to set it.
1035
+ return { ok: true, status: await status(), ...(migration.problem ? { remaining: migration.problem } : {}) };
1036
+ }
847
1037
  if (raw === null) return { ok: false, problem: fileProblem };
848
1038
  // Whether it is this save that makes the settings usable, judged on the text it replaces: only then are
849
1039
  // they this setup's to load. And the token that goes with them, from the same look, to tell later
@@ -1001,7 +1191,10 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
1001
1191
  for (const name of Object.keys(COMMANDS)) if (!taken.has(name)) editor.add({ name, description: PLACEHOLDER_DESCRIPTION, async execute(event) {
1002
1192
  const now = await settingsProblem(path);
1003
1193
  const usable = !now.problem && !now.disabled;
1004
- await appendReport(context, { sessionID: event.sessionID, text: !usable
1194
+ await appendReport(context, { sessionID: event.sessionID, text: now.migration
1195
+ // Settings of 0.4.x: nothing to repair, an update to confirm in /pr-setup, which this process then loads.
1196
+ ? `[AZPR] SETTINGS UPDATE REQUIRED\nNo review or Azure request was started. Settings: ${path}\n${now.problem}`
1197
+ : !usable
1005
1198
  ? `[AZPR] SETUP REQUIRED\nNo review or Azure request was started. Settings at ${path} could not be used when OpenCode loaded AZPR: ${now.problem || use.problem} Run /pr-setup (in the terminal UI it asks in dialogs; --help shows the options); repair an existing settings file if necessary, then ${RESTART}.`
1006
1199
  : use.loadProblem
1007
1200
  ? `[AZPR] RESTART REQUIRED\nNo review or Azure request was started. The settings at ${path} are saved, but AZPR could not load them: ${use.loadProblem} Repair that, then ${RESTART}.`
@@ -1141,7 +1334,9 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
1141
1334
  try {
1142
1335
  const arguments_ = parseSetupArguments(event.prompt.text ?? '');
1143
1336
  if (arguments_ === null) {
1144
- text = await guide(context, path, use.blocked ? use.problem : '', environment);
1337
+ // Settings of 0.4.x that can be updated: what the update changes, and the word that confirms it.
1338
+ const offered = await readExisting(path).then(previous => typeof previous === 'string' ? migrationOf(previous) : null, () => null);
1339
+ text = await guide(context, path, use.blocked ? use.problem : '', environment, offered ?? undefined);
1145
1340
  // /pr-setup alone: the terminal UI opens its dialogs when it sees this notice. --help only explains.
1146
1341
  if (!(event.prompt.text ?? '').trim()) metadata = { azpr: { setup: true } };
1147
1342
  } else {
@@ -1153,7 +1348,11 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
1153
1348
  saved = await saveSetup(context, path, arguments_, environment);
1154
1349
  if (wasBlocked) after = await afterSave({ made: saved.unusable, before: saved.before, after: saved.after });
1155
1350
  } finally { turn.busy = false; }
1156
- text = `[AZPR] SETTINGS SAVED\nSettings: ${path}\n` +
1351
+ // An updated file that had a fault before still has it: say what, and where it is set.
1352
+ text = saved.migrated && saved.remaining
1353
+ ? `[AZPR] SETTINGS UPDATED\nSettings: ${path}\nThe settings file now has the layout of this version, and still cannot be used: ${saved.remaining} Set that right with /pr-setup (in the terminal UI it asks in dialogs; --help shows the options) or in the settings file. No model or Azure request was made.`
1354
+ : `[AZPR] SETTINGS ${saved.migrated ? 'UPDATED' : 'SAVED'}\nSettings: ${path}\n` +
1355
+ (saved.migrated ? 'The settings file now has the layout of this version; /pr-setup shows and changes the models of each mode.\n' : '') +
1157
1356
  (saved.first ? `Organization: ${saved.organization}; PAT file: ${saved.patFile}\n` : '') +
1158
1357
  (saved.changed.length ? `Changed: ${saved.changed.join(', ')}\n` : '') +
1159
1358
  (after.ready ? 'AZPR has loaded them: run /pr-check <PR URL>. No model or Azure request was made.'