opencode-azure-devops-pr-review 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/comments.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // Comment plans: per-item validation, stable markers and saved publication text.
2
2
  import { createHash } from 'node:crypto';
3
- import { renderReviewSummary } from './attribution.mjs';
3
+ import { renderReviewSummary, describeReview } from './attribution.mjs';
4
4
  import { targetKey } from './azure.mjs';
5
5
  import { parseModelJSON, canonicalKey, parseRepairPrompt } from './output.mjs';
6
6
 
@@ -177,6 +177,61 @@ export function previewNextSteps(review, { held = false } = {}) {
177
177
  `Each --exclude or --severity list replaces the saved one. For another review add its ID; /pr-comment --list shows them.`;
178
178
  }
179
179
 
180
+ // What the terminal panel can list of one review; a review with more findings is adjusted with typed commands.
181
+ const ACTION_FINDINGS = 200;
182
+
183
+ /**
184
+ * What a review's comments are at this moment, as one short word: its saved preview (by the moment it was
185
+ * planned; none while there is no preview) and a person's adjustments. A step that the terminal panel offers
186
+ * carries the word of that moment, and so does the command the panel sends for it (`--seen`): the runtime
187
+ * refuses the command when the word is another one by then. A notice shows what its own conversation was told,
188
+ * and a command typed in another session of the review, or in another client, changes the review without
189
+ * telling it: what is acted on must still be what was on screen. The word survives a restart, since the
190
+ * review's record holds what it is made of.
191
+ */
192
+ export function commentToken(review) {
193
+ const { excluded, severity } = adjustmentsOf(review);
194
+ const levels = Object.keys(severity).sort().map(id => [id, severity[id]]);
195
+ return createHash('sha256').update(JSON.stringify([review.id, review.plan ? String(review.planCreatedAt ?? '') : null, [...excluded].sort(), levels])).digest('hex').slice(0, 12);
196
+ }
197
+
198
+ /**
199
+ * After a preview, or after a review that no preview follows by itself: the next steps as data, for the
200
+ * terminal panel, which offers them as rows a person picks instead of typing. It travels in the metadata of
201
+ * that notice, which no model reads.
202
+ * `plan` says that the review has no preview yet: planning one comes first, so nothing can be posted.
203
+ * `publish` says whether the preview can be posted as it is (`held` leaves that out, as the text does),
204
+ * `posts` how many comment items it holds, `target` which review and PR it is, in the runtime's words, and
205
+ * `adjust` whether its findings can still be adjusted (not once its publication has started).
206
+ * `findings` are the findings this review can publish: each with the level it is published at, the level the
207
+ * review gave it where a person changed that (`original`), whether a person left it out (`excluded`), and its
208
+ * summary, which is the review's text and is only ever shown. `state` is the word for the review's comments as
209
+ * they are now (`commentToken`), which a command picked from this offer hands back. Undefined for a review
210
+ * with more findings than the panel lists: half a list would let a person replace adjustments they cannot see.
211
+ */
212
+ export function previewActions(review, { held = false } = {}) {
213
+ const findings = publishableFindings(review);
214
+ if (findings.length > ACTION_FINDINGS) return undefined;
215
+ const { excluded, severity } = adjustmentsOf(review);
216
+ const left = new Set(excluded);
217
+ return {
218
+ review: review.id,
219
+ state: commentToken(review),
220
+ target: describeReview(review),
221
+ plan: !review.plan,
222
+ publish: Boolean(review.plan) && !held && !everyFindingExcluded(review),
223
+ posts: publicationItems(review.plan).length,
224
+ adjust: !publicationStarted(review),
225
+ findings: findings.map(finding => ({
226
+ id: finding.id,
227
+ severity: Object.hasOwn(severity, finding.id) ? severity[finding.id] : finding.severity,
228
+ ...(Object.hasOwn(severity, finding.id) ? { original: finding.severity } : {}),
229
+ ...(left.has(finding.id) ? { excluded: true } : {}),
230
+ summary: String(finding.summary ?? '').replace(/\s+/g, ' ').trim().slice(0, 160),
231
+ })),
232
+ };
233
+ }
234
+
180
235
  /**
181
236
  * Apply a /pr-comment adjustment request to a review. `exclude` and `severity`
182
237
  * each replace their whole list when given (empty: none); `reset` clears both.
package/src/host.mjs CHANGED
@@ -44,6 +44,7 @@ export function hostCapabilities(context) {
44
44
  permissionHook: fn('permission.hook'),
45
45
  toolTransform: fn('tool.transform'),
46
46
  sessionRemove: fn('session.remove'),
47
+ sessionUpdate: fn('session.update'),
47
48
  eventSubscribe: fn('event.subscribe'),
48
49
  pluginList: fn('plugin.list'),
49
50
  };
@@ -175,6 +176,17 @@ export const USED_UP_LIMITS = Object.freeze({
175
176
  */
176
177
  export const isSessionNotFound = error => (error?._tag ?? error?.name) === 'Session.NotFoundError';
177
178
 
179
+ /**
180
+ * Whether a session still has the name OpenCode shows for one that nobody named. OpenCode 2.3.0 creates a
181
+ * conversation without a title and lists it as "New session"; earlier releases stored the same words with the
182
+ * time it was created. OpenCode's own model names such a conversation when it first runs there.
183
+ */
184
+ export function isUntitledSession(session) {
185
+ const title = session?.title;
186
+ return title === undefined || title === null || title === '' ||
187
+ (typeof title === 'string' && /^New session - \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(title));
188
+ }
189
+
178
190
  /** Throw one readable error naming every missing host method. */
179
191
  export function requireMethods(context, paths, purpose) {
180
192
  const missing = paths.filter(path => typeof path.split('.').reduce((value, key) => value?.[key], context) !== 'function');
package/src/output.mjs CHANGED
@@ -730,7 +730,9 @@ export function normalizeFindingId(value) {
730
730
  }
731
731
 
732
732
  const COMMENT_USAGE = '[AZPR] Usage: /pr-comment [review-id] [--publish | --show], or with --exclude <IDs|none> and/or --severity <ID=high|medium|low,…|none>, or --reset; /pr-comment --list shows the saved reviews. Without an ID the command acts on this conversation\'s current review. /pr-comment --help has examples.';
733
- const COMMENT_OPTIONS = ['publish', 'show', 'list', 'exclude', 'severity', 'reset'];
733
+ const COMMENT_OPTIONS = ['publish', 'show', 'list', 'exclude', 'severity', 'reset', 'seen'];
734
+ // The word for what a review's comments were when a step was offered (`commentToken` in comments.mjs).
735
+ const SEEN = /^[a-f0-9]{12}$/;
734
736
 
735
737
  /**
736
738
  * /pr-comment's arguments: an optional review ID, then at most one of
@@ -739,6 +741,10 @@ const COMMENT_OPTIONS = ['publish', 'show', 'list', 'exclude', 'severity', 'rese
739
741
  * for an empty one) or --reset alone. List items are separated by commas or
740
742
  * spaces. --list stands alone and names no review. Anything else is refused.
741
743
  * Without an ID the runtime picks the conversation's current review.
744
+ * --seen <word> goes with any of them but --show and --list: it names what the
745
+ * review's preview and adjustments were when the step was offered, and the
746
+ * runtime refuses the command when they are something else by now. The
747
+ * terminal panel adds it to the commands it sends; a typed command needs none.
742
748
  */
743
749
  export function parseCommentRequest(raw) {
744
750
  const args = String(raw ?? '').trim().split(/\s+/).filter(Boolean);
@@ -749,7 +755,7 @@ export function parseCommentRequest(raw) {
749
755
  const option = /^--([a-z]+)(?:=([\s\S]*))?$/.exec(token);
750
756
  if (option) {
751
757
  if (!COMMENT_OPTIONS.includes(option[1]) || values.has(option[1])) throw new Error(COMMENT_USAGE);
752
- open = ['exclude', 'severity'].includes(option[1]) ? option[1] : null;
758
+ open = ['exclude', 'severity', 'seen'].includes(option[1]) ? option[1] : null;
753
759
  if (option[2] !== undefined && !open) throw new Error(COMMENT_USAGE);
754
760
  values.set(option[1], option[2] === undefined ? [] : [option[2]]);
755
761
  continue;
@@ -757,8 +763,13 @@ export function parseCommentRequest(raw) {
757
763
  if (!open) throw new Error(COMMENT_USAGE);
758
764
  values.get(open).push(token);
759
765
  }
766
+ const seen = values.get('seen');
767
+ if (seen && (seen.length !== 1 || !SEEN.test(seen[0]) || values.has('show') || values.has('list'))) {
768
+ throw new Error('[AZPR] --seen takes the one word the terminal panel adds to its commands, and goes with neither --show nor --list; a typed command needs none.');
769
+ }
770
+ values.delete('seen');
760
771
  const named = [...values.keys()];
761
- const request = { ...(reviewId ? { reviewId } : {}), publish: values.has('publish'), show: values.has('show') };
772
+ const request = { ...(reviewId ? { reviewId } : {}), publish: values.has('publish'), show: values.has('show'), ...(seen ? { seen: seen[0] } : {}) };
762
773
  if (values.has('list')) {
763
774
  if (named.length > 1 || reviewId) throw new Error(COMMENT_USAGE);
764
775
  return { list: true };
package/src/runtime.mjs CHANGED
@@ -21,14 +21,14 @@ import { createDiagnostics, diagnosticResponse, diagnosticToolError, createStage
21
21
  import { createCommentData, captureObservation, PAGE_CHARACTERS, COMMENT_TURN_CHARACTERS } from './comment-data.mjs';
22
22
  import { prepareComments, publishPlan, discussionDigest, PLANNING_PARALLEL_PAGES } from './comment-work.mjs';
23
23
  import { automaticPublicationProblems, automaticPublicationRepeats, publicationItems, publishableFindings, reviewVerification,
24
- everAdjusted, hasAdjustments, resolveAdjustments, everyFindingExcluded, publicationStarted, describeAdjustments, describeEarlierText, excludedReferences, previewNextSteps } from './comments.mjs';
24
+ everAdjusted, hasAdjustments, resolveAdjustments, everyFindingExcluded, publicationStarted, describeAdjustments, describeEarlierText, excludedReferences, previewNextSteps, previewActions, commentToken } from './comments.mjs';
25
25
  import { createToolQueue } from './tool-queue.mjs';
26
26
  import { API_VERSION, createAzureClient, fetchTransport, pemCertificates, proxyLabel, restBaseUrl, targetKey } from './azure.mjs';
27
27
  import { REVIEW_TOOL_NAMES, reviewToolDefinitions, runReviewTool } from './review-tools.mjs';
28
28
  import { runReview } from './review-work.mjs';
29
29
  import { createReviewStore, createReviewWrites, stateRoot, REVIEW_LIMIT } from './store.mjs';
30
- import { PROGRESS_EVENT_TYPES, TESTED_HOST_VERSION, USED_UP_LIMITS, fetchTransportSupported, hostCapabilities, isSessionNotFound, listOf, packageNamed, pluginEntries, pluginSourceLabel, recordOf, requireMethods, sessionProgress, tokenUsage, usageTotals, withoutCredentials } from './host.mjs';
31
- import { reviewProvenance, provenanceReport, commentAttribution, renderFinalReport, renderCommentActions, renderIncompleteDraft, renderReceipt, renderDiagnosticNotices, renderCheckReport, renderPublication, describeReview, enclose } from './attribution.mjs';
30
+ import { PROGRESS_EVENT_TYPES, TESTED_HOST_VERSION, USED_UP_LIMITS, fetchTransportSupported, hostCapabilities, isSessionNotFound, isUntitledSession, listOf, packageNamed, pluginEntries, pluginSourceLabel, recordOf, requireMethods, sessionProgress, tokenUsage, usageTotals, withoutCredentials } from './host.mjs';
31
+ import { reviewProvenance, provenanceReport, commentAttribution, renderFinalReport, renderCommentActions, renderIncompleteDraft, renderReceipt, renderDiagnosticNotices, renderCheckReport, renderPublication, describeReview, conversationTitle, enclose } from './attribution.mjs';
32
32
 
33
33
  const DEFAULT_DIR = dirname(fileURLToPath(import.meta.url));
34
34
  const ownRole = name => typeof name === 'string' && Object.hasOwn(ROLES, name);
@@ -100,6 +100,13 @@ async function bounded(operation, signal) {
100
100
  try { return await Promise.race([operation(), stopped]); } finally { signal.removeEventListener('abort', onAbort); }
101
101
  }
102
102
  const scoped = (operation, signal) => signal ? bounded(operation, signal) : operation();
103
+ // Naming a conversation (`nameConversation`): how long its watch of the host's renames stays open after the host
104
+ // answered its last write, how many names it writes at most (its own, and names it writes back), how long it
105
+ // still watches once the plugin is being unloaded, and how long the unloading waits for all of that.
106
+ const NAMING_MS = 3000, NAMING_WRITES = 4, NAMING_FINISH_MS = 250, NAMING_UNLOAD_MS = 5000;
107
+ // Before a name is written back, how long the host must have reported no name of that conversation: the name
108
+ // written is the last one.
109
+ const NAMING_SETTLE_MS = 50;
103
110
  async function deadline(operation, milliseconds) {
104
111
  const controller = new AbortController();
105
112
  const timer = setTimeout(() => controller.abort(new Error('Timed out.')), milliseconds);
@@ -119,7 +126,7 @@ function completedText(text) {
119
126
  /**
120
127
  * Session/command-scoped integration.
121
128
  * `options` (offline tests only): stateDirectory, azureTimeoutMs, retryDelayMs,
122
- * removeTimeoutMs, stageIdleMs, azureBaseUrl and fetch. A base URL override (also
129
+ * removeTimeoutMs, stageIdleMs, namingMs, namingUnloadMs, azureBaseUrl and fetch. A base URL override (also
123
130
  * AZPR_TEST_AZURE_BASE_URL for exact-host fixtures) must be a loopback test server.
124
131
  * setup.mjs passes settingsPath and settingsCompletion (what it added to the
125
132
  * settings file before this read, for /pr-check).
@@ -269,7 +276,8 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
269
276
  ' /pr-comment --publish post the saved preview as the PAT owner; safe to repeat\n' +
270
277
  ' /pr-comment --list the reviews saved for this conversation, with their IDs (no model)\n' +
271
278
  ' /pr-comment 1a2b3c4d --publish a review ID first acts on that review\n\n' +
272
- 'Finding IDs are those of the report and the preview (f1 reads as F-1). Each --exclude or --severity list replaces the saved one, so name every finding you want in it.',
279
+ 'Finding IDs are those of the report and the preview (f1 reads as F-1). Each --exclude or --severity list replaces the saved one, so name every finding you want in it.\n\n' +
280
+ 'The terminal panel adds --seen WORD to the commands it sends: the word names the preview and the adjustments its step was offered for, and the command is refused when they have changed since. A typed command needs none.',
273
281
  };
274
282
  const HELP_ARGUMENT = /^(?:--help|-h)$/;
275
283
  const commandDescription = name => COMMAND_DESCRIPTIONS[name];
@@ -675,12 +683,15 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
675
683
  // The terminal panel reads no settings file: what it needs of the settings travels with the notices. Only
676
684
  // terminalPanel: manual is marked, so the default sends every notice exactly as before.
677
685
  const noticeMetadata = settings.terminalPanel === 'manual' ? { azpr: { panel: 'manual' } } : undefined;
678
- const notice = input => appendReport(context, { ...input, metadata: noticeMetadata });
679
- async function deliver(sessionID, body, runId) {
686
+ // `extra` is what one notice carries besides, under the same key: what it offers as a next step, as data for the
687
+ // steps at the panel's foot (stopping the run a STARTED notice announces; the next steps of a review or a
688
+ // preview). No model reads a notice's metadata, and every other notice is sent exactly as before.
689
+ const notice = ({ extra, ...input }) => appendReport(context, { ...input, metadata: extra ? { azpr: { ...noticeMetadata?.azpr, ...extra } } : noticeMetadata });
690
+ async function deliver(sessionID, body, runId, extra) {
680
691
  let failure;
681
692
  for (let attempt = 1; attempt <= 3; attempt++) {
682
693
  try {
683
- await deadline(signal => notice({ sessionID, text: body, signal }), 10000);
694
+ await deadline(signal => notice({ sessionID, text: body, signal, ...(extra ? { extra } : {}) }), 10000);
684
695
  return { queued: true, attempts: attempt };
685
696
  } catch (error) {
686
697
  failure = error;
@@ -1069,9 +1080,9 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1069
1080
  checks.push({ name: 'Deep model', ok: true, warning: true, detail: `${problem} /pr-deep is unavailable until it is fixed; other commands are not affected.` });
1070
1081
  }
1071
1082
  if (settings.deepPartial) checks.push({ name: 'Deep models', ok: true, warning: true, detail: 'Only some models.deep roles are set; /pr-deep needs all three.' });
1072
- else if (!settings.deepReady) checks.push({ name: 'Deep models', ok: true, detail: 'Not set: /pr-deep stays off until all three models.deep roles name models stronger than models.review.' });
1083
+ else if (!settings.deepReady) checks.push({ name: 'Deep models', ok: true, detail: 'Not set: /pr-deep stays off until all three models.deep roles name models stronger than models.review: another model, or the same one with a higher variant.' });
1073
1084
  else if (modelSlots('deep').every(slot => settings.models.deep[slot] === settings.models.review[slot])) {
1074
- checks.push({ name: 'Deep models', ok: true, warning: true, detail: 'models.deep repeats models.review, so /pr-deep would only repeat /pr-review; set stronger models there for the PRs that need them.' });
1085
+ checks.push({ name: 'Deep models', ok: true, warning: true, detail: 'models.deep repeats models.review, so /pr-deep would only repeat /pr-review; set stronger models there (another model, or a higher variant) for the PRs that need them.' });
1075
1086
  }
1076
1087
  // One OpenCode release is validated; on others, reviews still run and what AZPR needs is detected at runtime.
1077
1088
  const host = capabilities.version === 'unknown' ? 'OpenCode did not report its version' : `OpenCode ${capabilities.version}`;
@@ -1141,6 +1152,175 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1141
1152
  return { status: checks.every(check => check.ok) ? 'READY' : 'NOT_READY', report: renderCheckReport(snapshot, checks, run.readiness) };
1142
1153
  }
1143
1154
 
1155
+ /**
1156
+ * A conversation nobody named yet gets a name that says which PR its command is about. OpenCode names a
1157
+ * conversation when its own model first runs there, which an AZPR command never makes it do: the session
1158
+ * list would go on calling it "New session", as if it were unused.
1159
+ *
1160
+ * OpenCode has no rename that applies only to a conversation without a name, and nothing ties a rename it
1161
+ * reports to the call that made it. A read followed by a write can therefore replace a name that was given
1162
+ * in between, and no plugin can rule that out. What AZPR does instead: it names a conversation only where
1163
+ * the host reports renames (`session.renamed`), follows them from before its read, and lets a name that
1164
+ * anyone else gave stand wherever it can tell, and also where it cannot:
1165
+ * - A rename reported while the conversation is read stops the naming: everything the feed holds by then
1166
+ * is looked at.
1167
+ * - A report with other words than AZPR wrote is someone else's name. A report with AZPR's words is AZPR's
1168
+ * write or someone's choice of the same words; the two cannot be told apart. Where it follows someone
1169
+ * else's name, that name may have been replaced by AZPR's write, so it is written back: in doubt the name
1170
+ * that is not AZPR's stays. (The one case this decides wrongly: a person who gives a name and then exactly
1171
+ * the words AZPR wrote last, both in that moment, keeps the name given first.)
1172
+ * - What is written back is the last name reported, once the host has reported no name of this conversation
1173
+ * for NAMING_SETTLE_MS, and never AZPR's own first words (`take`).
1174
+ * - The watch stays open for NAMING_MS after the host answered AZPR's last write, however promptly a report
1175
+ * came, since an earlier name can be reported after it; and it is never closed while a write is under way,
1176
+ * which could still replace a name. It writes NAMING_WRITES times at most.
1177
+ * - One conversation is named by one watch at a time: a second one would take the first one's write for
1178
+ * someone's choice. When the plugin is unloaded, a watch first ends what it is doing (`finish`).
1179
+ * Nothing waits for it and a failure changes nothing: a feed that fails has ended. With debug records on,
1180
+ * the run's record says how it ended (`conversation-name.json`), never with a name that is not AZPR's own.
1181
+ */
1182
+ const namings = new Map(); // conversation → the watch that is naming it: { end(), finish() }
1183
+ function nameConversation(run, target) {
1184
+ if (disposed || !capabilities.sessionUpdate || !capabilities.eventSubscribe) return;
1185
+ const sessionID = run.origin, own = conversationTitle(target);
1186
+ if (namings.has(sessionID)) return;
1187
+ const ENDED = Object.freeze({ done: true });
1188
+ let feed, timer, stop, outcome = 'kept', busy = false, finishing = false;
1189
+ const stopped = new Promise(resolve => { stop = resolve; });
1190
+ const watch = {};
1191
+ const close = () => {
1192
+ clearTimeout(timer);
1193
+ if (namings.get(sessionID) === watch) namings.delete(sessionID);
1194
+ stop(ENDED);
1195
+ const ended = feed;
1196
+ feed = undefined;
1197
+ if (ended) void Promise.resolve().then(() => ended.return?.()).catch(() => {});
1198
+ };
1199
+ // The watch closes this long after now, unless it gets busy before that: with a write, or with the moment
1200
+ // it waits before one.
1201
+ const arm = () => {
1202
+ clearTimeout(timer);
1203
+ if (!feed || busy) return;
1204
+ timer = setTimeout(close, finishing ? NAMING_FINISH_MS : options.namingMs ?? NAMING_MS);
1205
+ timer.unref?.();
1206
+ };
1207
+ // One read of the feed. It never rejects, also while nobody awaits it yet: a feed that fails has ended.
1208
+ const read = () => {
1209
+ try { return Promise.resolve(feed.next()).then(result => result ?? ENDED, () => ENDED); } catch { return Promise.resolve(ENDED); }
1210
+ };
1211
+ // A name for this conversation that the feed reports, or undefined for any other event.
1212
+ const renamed = event => event?.type === 'session.renamed' && event.data?.sessionID === sessionID && typeof event.data.title === 'string' ? event.data.title : undefined;
1213
+ // One write of a name; whether the host took it. The watch is not closed while it is under way.
1214
+ const write = async title => {
1215
+ clearTimeout(timer);
1216
+ busy = true;
1217
+ try { await context.session.update({ sessionID, title }); return true; } catch { return false; } finally { busy = false; arm(); }
1218
+ };
1219
+ // On record before anything can end it, so that a watch that ends at once leaves none behind.
1220
+ namings.set(sessionID, watch);
1221
+ watch.end = close;
1222
+ // The plugin is being unloaded: what is under way is ended first. A write is waited for, and what the feed
1223
+ // has reported by a moment after it is still acted on, so that a name it replaced is written back.
1224
+ watch.finish = () => {
1225
+ finishing = true;
1226
+ arm();
1227
+ return watch.done;
1228
+ };
1229
+ watch.done = (async () => {
1230
+ try {
1231
+ feed = context.event.subscribe({ types: ['session.renamed'] })[Symbol.asyncIterator]();
1232
+ arm();
1233
+ // Listening begins with the first read of the feed, before the conversation is read.
1234
+ let pending = read();
1235
+ const conversation = recordOf(await Promise.race([context.session.get({ sessionID }), stopped.then(() => undefined)]));
1236
+ if (!feed || !conversation || conversation.parentID || !isUntitledSession(conversation)) return;
1237
+ // What the feed reported while the conversation was read: it was named meanwhile. Everything the feed
1238
+ // holds by now is looked at, also behind another conversation's event: a read of the feed takes some
1239
+ // turns of its own, so each one is given until the event loop comes round, not just until this turn ends.
1240
+ const NOTHING = Symbol('nothing has arrived');
1241
+ for (;;) {
1242
+ let round;
1243
+ const arrived = await Promise.race([pending, stopped, new Promise(resolve => { round = setImmediate(resolve, NOTHING); })]);
1244
+ clearImmediate(round);
1245
+ if (arrived === NOTHING) break;
1246
+ if (arrived.done || !feed) return;
1247
+ pending = read();
1248
+ if (renamed(arrived.value) !== undefined) return;
1249
+ }
1250
+ if (disposed) return;
1251
+ // `mine` is what AZPR wrote last, and `awaited` whether the report of that write may still be to come.
1252
+ // `theirs` is the last name with words of someone's own that the feed reported since, and `due` whether
1253
+ // AZPR's words were reported after it, so that it may have been replaced.
1254
+ let mine = own, awaited = true, theirs, due = false, writes = 1, named = false, back = false;
1255
+ const take = title => {
1256
+ if (title === mine) {
1257
+ // AZPR's last write, or someone's choice of the same words.
1258
+ awaited = false;
1259
+ if (mine === own) named = true;
1260
+ due = theirs !== undefined;
1261
+ } else if (title === own) {
1262
+ // AZPR's first words, reported after AZPR wrote a name back. While that write's report is still to
1263
+ // come, this may be AZPR's first write, reported late: the name written back lands after it either
1264
+ // way. Afterwards it can only be someone's choice of these words, which stands.
1265
+ if (!awaited) { theirs = undefined; due = false; }
1266
+ } else {
1267
+ // Someone else's name: it is in place unless AZPR's words are reported after it.
1268
+ theirs = title;
1269
+ due = false;
1270
+ }
1271
+ };
1272
+ outcome = await write(mine) ? 'unconfirmed' : 'failed';
1273
+ const QUIET = Symbol('the host reported nothing more');
1274
+ for (;;) {
1275
+ const next = await Promise.race([pending, stopped]);
1276
+ if (next.done || !feed) return;
1277
+ pending = read();
1278
+ const title = renamed(next.value);
1279
+ if (title !== undefined) take(title);
1280
+ if (named && !back) outcome = 'named';
1281
+ if (back && !awaited) outcome = 'restored';
1282
+ if (!due) continue;
1283
+ // A name is to be written back. What the host reports of this conversation within a moment is taken
1284
+ // first, so that the name written is the last one reported; the moment begins again with each such
1285
+ // report, and with nothing else (another conversation's renames do not put the write off). The watch
1286
+ // is not closed meanwhile.
1287
+ clearTimeout(timer);
1288
+ busy = true;
1289
+ let quiet;
1290
+ const silence = () => new Promise(resolve => { quiet = setTimeout(resolve, NAMING_SETTLE_MS, QUIET); });
1291
+ try {
1292
+ let hush = silence();
1293
+ for (;;) {
1294
+ const more = await Promise.race([pending, stopped, hush]);
1295
+ if (more === QUIET) break;
1296
+ if (more.done || !feed) return;
1297
+ pending = read();
1298
+ const other = renamed(more.value);
1299
+ if (other === undefined) continue;
1300
+ take(other);
1301
+ clearTimeout(quiet);
1302
+ hush = silence();
1303
+ }
1304
+ } finally { clearTimeout(quiet); busy = false; }
1305
+ // A name reported after AZPR's words is in place by itself.
1306
+ if (!due) { arm(); continue; }
1307
+ if (writes >= NAMING_WRITES) return;
1308
+ mine = theirs;
1309
+ theirs = undefined;
1310
+ due = false;
1311
+ awaited = true;
1312
+ back = true;
1313
+ writes++;
1314
+ outcome = await write(mine) ? 'unconfirmed' : 'failed';
1315
+ }
1316
+ } catch { /* Naming is a convenience: the command goes on, and the conversation keeps the name it has. */ }
1317
+ finally {
1318
+ close();
1319
+ void run.debug?.write?.('conversation-name.json', { outcome, ...(outcome === 'named' ? { title: own } : {}) });
1320
+ }
1321
+ })();
1322
+ }
1323
+
1144
1324
  async function executeReview(mode, input, output, dispatch) {
1145
1325
  // Also after a restart, when this process no longer knows the sessions it created: the saved reviews and the
1146
1326
  // records of unfinished runs name them.
@@ -1166,6 +1346,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1166
1346
  : after?.mode === 'publish' ? ` After a COMPLETE review it plans the comments and posts them automatically as the PAT owner (${after.source}); a comment that a safeguard holds back waits for a person.` : '';
1167
1347
  const { run, status, report, failure, review, stopped } = await workflow({ origin: input.sessionID, notifySession: input.sessionID, mode, profile,
1168
1348
  userContext: request.userContext, prUrl: request.prUrl, ...(shown ? { afterReview: shown } : {}), ...(startNote ? { startNote } : {}) }, async run => {
1349
+ nameConversation(run, request.target);
1169
1350
  if (mode === 'check') { run.phase = 'source check'; return runCheck(run, request); }
1170
1351
  run.phase = 'review';
1171
1352
  const final = await runReview({ azure, runStage, progress, settings, dataFor }, run, request);
@@ -1216,9 +1397,32 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1216
1397
  }
1217
1398
  output.text = renderReceipt(run, enclosed, status, failure, settings);
1218
1399
  // Only a COMPLETE review that nothing stopped hands on to the comment step, after its receipt.
1219
- if (status === 'COMPLETE' && review && after.mode !== 'none' && !stopped) output.next = { review, after };
1400
+ const handsOn = status === 'COMPLETE' && review && after.mode !== 'none' && !stopped;
1401
+ if (handsOn) output.next = { review, after };
1402
+ // Where no preview follows by itself (afterReview: none, a review that was stopped, or one without findings to
1403
+ // comment on, which the step skips), the panel offers what the receipt names: a preview, and the findings to
1404
+ // adjust before it. Where one follows, its own notices are what the panel shows next.
1405
+ // The receipt encloses the report, not a preview: it offers planning one, never posting. A command that
1406
+ // acted on this review while its sessions were cleaned up (the review can be named from its STARTED notice)
1407
+ // has a receipt of its own, which says what is next.
1408
+ if (status === 'COMPLETE' && review && (!handsOn || !publishableFindings(review).length) && !review.plan && !everAdjusted(review)) {
1409
+ const offered = previewActions(review);
1410
+ if (offered) output.extra = { next: offered };
1411
+ }
1220
1412
  }
1221
1413
 
1414
+ /**
1415
+ * What a preview's receipt depends on: the plan, a person's adjustments and what publication has recorded.
1416
+ * A command that plans or adjusts puts another object in the place of the plan or of the adjustments, and a
1417
+ * publication records every item it handles anew, with the moment (also one that finds everything on the PR
1418
+ * already, and one that follows an earlier publication). So the same objects and the same record mean the
1419
+ * same preview, of which nothing was posted since.
1420
+ */
1421
+ const publicationRecord = review => review.publication instanceof Map ? [...review.publication.values()].map(entry => `${entry?.state}@${entry?.at}`).join(' ') : '';
1422
+ const previewState = review => ({ plan: review.plan, adjustments: review.adjustments, posting: publicationRecord(review) });
1423
+ /** Said to a command that was picked for comments the review no longer has (`--seen`, `commentToken`). */
1424
+ const changedSince = review => `[AZPR] Review ${review.id} is no longer as it was shown: its preview was planned again or its findings were adjusted since, in another session or by another command. Nothing was done. /pr-comment ${review.id} --show shows the saved preview.`;
1425
+
1222
1426
  function renderPlan(review) {
1223
1427
  const plan = review.plan;
1224
1428
  // A combined comment lists every finding it covers and why (preview only; Azure DevOps gets the content).
@@ -1311,10 +1515,25 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1311
1515
  if (request.list) { output.text = renderReviewList(input.sessionID, owner); return; }
1312
1516
  const review = request.reviewId ? completed.get(request.reviewId) : currentReview(input.sessionID, owner);
1313
1517
  if (!review || !belongs(review)) throw new Error(`[AZPR] No completed review is available for this conversation. The latest ${REVIEW_LIMIT} completed reviews are kept privately across restarts; run /pr-review, /pr-quick or /pr-deep again if it has expired.`);
1518
+ // A step picked in the terminal panel says what the review's comments were when it was offered. A command
1519
+ // typed in another session of the review, or another client, may have planned or adjusted since, which
1520
+ // that panel was not told: what is acted on is what was on screen, or nothing. Checked here to answer at
1521
+ // once, before the review becomes the current one (a step that is refused changes nothing, also not which
1522
+ // review the next command without an ID acts on), and again under the comment lock before anything is
1523
+ // planned, saved or posted.
1524
+ if (request.seen && request.seen !== commentToken(review)) throw new Error(changedSince(review));
1314
1525
  // The review a person just used stays the current one for the next command without an ID, also
1315
1526
  // for a command that answers at once (--show, unchanged adjustments) or is refused below.
1316
1527
  const kept = markUsed(review);
1317
- if (request.show) { output.text = `${renderSavedPreview(review)}${await kept ? '' : UNSAVED_CHOICE}`; return; }
1528
+ if (request.show) {
1529
+ // The preview shown again offers what its own receipt offered, as the review is now: both are read here,
1530
+ // before anything is awaited, so that what is offered is what the text shows.
1531
+ const saved = renderSavedPreview(review);
1532
+ const next = review.plan && previewActions(review, { held: Boolean(holdNote(review)) });
1533
+ output.text = `${saved}${await kept ? '' : UNSAVED_CHOICE}`;
1534
+ if (next) output.extra = { next };
1535
+ return;
1536
+ }
1318
1537
  if (request.adjust) {
1319
1538
  // Checked here to answer at once, and again under the comment lock before anything is saved.
1320
1539
  if (publicationStarted(review)) throw new Error(adjustmentsClosed(review));
@@ -1322,7 +1541,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1322
1541
  output.text = `[AZPR] Review ${review.id} already has these adjustments; nothing was planned. /pr-comment ${review.id} --show shows the saved preview, and /pr-comment ${review.id} plans it again.${await kept ? '' : UNSAVED_CHOICE}`;
1323
1542
  return;
1324
1543
  }
1325
- return commentOn(review, { publish: false, notifySession: input.sessionID, adjust: request.adjust }, output, dispatch);
1544
+ return commentOn(review, { publish: false, notifySession: input.sessionID, adjust: request.adjust, seen: request.seen }, output, dispatch);
1326
1545
  }
1327
1546
  // A review a person adjusted (also one reset since) is posted only from a preview planned after
1328
1547
  // its latest adjustment, as the person read it: never planned and posted in one step, and once
@@ -1335,7 +1554,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1335
1554
  throw new Error(`[AZPR] Publication of review ${review.id}'s adjusted preview has started, so it is not planned again. /pr-comment ${review.id} --publish retries the saved preview and /pr-comment ${review.id} --show shows it; run a new review to change what is posted.`);
1336
1555
  }
1337
1556
  }
1338
- return commentOn(review, { publish: request.publish, notifySession: input.sessionID }, output, dispatch);
1557
+ return commentOn(review, { publish: request.publish, notifySession: input.sessionID, seen: request.seen }, output, dispatch);
1339
1558
  }
1340
1559
 
1341
1560
  /**
@@ -1356,17 +1575,20 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1356
1575
  if (!others) await saveSelection(review);
1357
1576
  }
1358
1577
  }
1359
- async function commentRun(review, { publish, notifySession, auto, adjust }, output, dispatch) {
1578
+ async function commentRun(review, { publish, notifySession, auto, adjust, seen }, output, dispatch) {
1360
1579
  // A saved review whose verification cannot be established is never commented on.
1361
1580
  const verification = reviewVerification(review);
1362
1581
  if (!verification) throw new Error(`[AZPR] Review ${review.id} does not say whether its findings were verified; run a new review before commenting.`);
1363
1582
  if (review.profile === 'quick' && !settings.quickReady) throw new Error(`[AZPR] Review ${review.id} is a quick review; set models.quick.reviewer, which plans its comments, before /pr-comment.`);
1364
- let planning = false, held = [], nothingNew = '', discussions = null, changed = [], earlier = '', hold = '';
1583
+ let planning = false, held = [], nothingNew = '', discussions = null, changed = [], earlier = '', hold = '', shown;
1365
1584
  const step = auto && `(automatic ${auto.mode === 'publish' ? 'publication' : 'preview'} after review ${review.id} completed; ${auto.source})`;
1366
1585
  const { run, status, report, failure } = await workflow({ origin: review.origin, notifySession, mode: 'comment',
1367
1586
  profile: review.profile, review, lockKey: targetKey(review.target), startNote: ` It acts on ${describeReview(review)}.`,
1368
1587
  ...(auto ? { auto, startLabel: step } : adjust ? { startLabel: `(adjusting the findings of review ${review.id})` } : {}) }, async run => {
1369
1588
  run.snapshot = review.snapshot;
1589
+ // Under the comment lock, where no other comment command of this PR runs: the review's comments are still
1590
+ // the ones this command was picked for.
1591
+ if (seen && seen !== commentToken(review)) throw new Error(changedSince(review));
1370
1592
  if (adjust) {
1371
1593
  // Under the comment lock: a publication that began since the request closes the adjustments.
1372
1594
  if (publicationStarted(review)) throw new Error(adjustmentsClosed(review));
@@ -1415,6 +1637,8 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1415
1637
  await run.debug.write('comment-plan.json', { sourceReview: review.id, snapshot: review.snapshot, parallelPages, ...review.plan });
1416
1638
  }
1417
1639
  const preview = renderPlan(review);
1640
+ // What the receipt says and offers is true of the review as it is here, under the command's lock.
1641
+ shown = previewState(review);
1418
1642
  if (everyFindingExcluded(review)) {
1419
1643
  return { status: 'NOTHING_TO_POST', report: `${preview}\n\nA person excluded every finding of review ${review.id}, so nothing will be posted. /pr-comment ${review.id} --exclude none restores them.` };
1420
1644
  }
@@ -1454,13 +1678,28 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1454
1678
  const obsolete = scheduleCleanup(run, review);
1455
1679
  await persistReview(review);
1456
1680
  await finishCleanup(run, review, obsolete);
1681
+ // What an earlier cleanup could not delete is tried again.
1682
+ void releaseExpired();
1683
+ // The command locks were released before the cleanup, so another command may have adjusted this review,
1684
+ // planned its preview again or posted it since. What this run planned is then not what a person would post
1685
+ // or adjust now: it is neither enclosed nor offered, and the run ends with a receipt of a status of its own,
1686
+ // REPLACED, which the terminal panel takes for the end of this run but not for what happened last. The
1687
+ // other command's receipt says what is next; it may have gone to another session of the review.
1688
+ // From this look at the review to the receipt's text and offer nothing is awaited: the document, the offer
1689
+ // and the word it carries are of one moment. The record is saved after that. What a command changes from
1690
+ // then on meets that word: a step picked under this receipt is refused (`--seen`).
1691
+ const now = previewState(review);
1692
+ const replaced = status === 'PREVIEW' && shown && (now.plan !== shown.plan || now.adjustments !== shown.adjustments || now.posting !== shown.posting);
1693
+ if (replaced) {
1694
+ // Such a run says nothing a person acts on: the conversation's current review stays as it is.
1695
+ output.text = `[AZPR ${run.id}] REPLACED; source review=${review.id}\nActed on ${describeReview(review)}.\nThis run's preview was replaced before its receipt: while the run ended, another /pr-comment command changed or posted the preview of this review, so what this run planned is not shown. The receipt of that command says what can be done next, and /pr-comment ${review.id} --show shows the saved preview.\n${renderDiagnosticNotices(run, settings)}All grants are revoked.`;
1696
+ await persistReview(review);
1697
+ return;
1698
+ }
1457
1699
  // The review whose receipt arrives last is the current one, as a preview's next steps say; this holds for
1458
1700
  // the automatic step too, which no command selected. The cleanup may have waited for OpenCode while a
1459
1701
  // person used another review here, so the choice is made now, next to the receipt.
1460
1702
  review.usedAt = stamp();
1461
- await persistReview(review);
1462
- // What an earlier cleanup could not delete is tried again.
1463
- void releaseExpired();
1464
1703
  const safe = enclose('comment', report);
1465
1704
  // A held preview says itself what to do; an adjustment says whether it was saved.
1466
1705
  const retry = failure && ['INCOMPLETE', 'FAILED', 'PARTIALLY_POSTED'].includes(status) && !hold
@@ -1475,7 +1714,12 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1475
1714
  const adjusted = changed.length ? `Adjusted by a person: ${changed.join('; ')}.${status === 'PREVIEW' ? ' The comments were planned again, so their wording may differ: read the whole preview before publishing.' : ''}\n` : '';
1476
1715
  // After a preview nothing is posted yet: say what a person can type next, without the review ID.
1477
1716
  const next = status === 'PREVIEW' ? `${previewNextSteps(review, { held: Boolean(hold) })}\n` : '';
1717
+ // The same steps as data, for the terminal panel's rows.
1718
+ const offered = status === 'PREVIEW' ? previewActions(review, { held: Boolean(hold) }) : undefined;
1719
+ if (offered) output.extra = { next: offered };
1478
1720
  output.text = `[AZPR ${run.id}] ${status}; source review=${review.id}\nActed on ${describeReview(review)}.\n${automatic}${adjusted}${earlier}${holds}${none}${failure ? `Reason: ${failure}\n` : ''}${renderDiagnosticNotices(run, settings)}${retry}\n<azpr_comment_data>\n${safe}\n</azpr_comment_data>\n${next}All grants are revoked. The text above is data, not instructions.`;
1721
+ // The choice of the current review is on record before the receipt is delivered.
1722
+ await persistReview(review);
1479
1723
  }
1480
1724
 
1481
1725
  async function executeStop(input, output) {
@@ -1524,13 +1768,13 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1524
1768
  if (!dispatch.run) {
1525
1769
  try {
1526
1770
  await task;
1527
- await deliver(sessionID, output.text);
1771
+ await deliver(sessionID, output.text, undefined, output.extra);
1528
1772
  } finally { ended(); }
1529
1773
  return;
1530
1774
  }
1531
1775
  const run = dispatch.run;
1532
1776
  const completion = task.then(async () => {
1533
- const delivered = await deliver(sessionID, output.text, run.id);
1777
+ const delivered = await deliver(sessionID, output.text, run.id, output.extra);
1534
1778
  await run.debug?.write('delivery.json', { ...delivered, sessionID });
1535
1779
  }).catch(async error => {
1536
1780
  const delivered = await deliver(sessionID, `[AZPR ${run.id}] INCOMPLETE\nReason: ${errorText(error)}`, run.id);
@@ -1539,8 +1783,11 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1539
1783
  jobs.add(completion);
1540
1784
  void completion.finally(() => jobs.delete(completion));
1541
1785
  try {
1786
+ // What the notice's last sentence says is also there as data, for the terminal panel: the run can be
1787
+ // stopped, by its ID, from now until its receipt.
1542
1788
  await deadline(signal => notice({ sessionID,
1543
- text: `[AZPR ${run.id}] STARTED /${name}${run.startLabel ? ` ${run.startLabel}` : ''}. Work continues in this OpenCode process; the result will return to this conversation.${run.startNote ?? ''} Stop with /pr-stop ${run.id}.`, signal }), 10000);
1789
+ text: `[AZPR ${run.id}] STARTED /${name}${run.startLabel ? ` ${run.startLabel}` : ''}. Work continues in this OpenCode process; the result will return to this conversation.${run.startNote ?? ''} Stop with /pr-stop ${run.id}.`, signal,
1790
+ extra: { next: { stop: run.id } } }), 10000);
1544
1791
  } catch (error) {
1545
1792
  await abortRun(run, 'The command start notice could not be queued. No review was started.', 'INCOMPLETE');
1546
1793
  throw error;
@@ -1818,6 +2065,14 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
1818
2065
  await Promise.allSettled([...runs.values()].map(run => abortRun(run, 'OpenCode V2 plugin unloaded.')));
1819
2066
  await Promise.allSettled([...jobs]);
1820
2067
  closeEvents();
2068
+ // A naming that is under way ends what it is doing: its write is waited for, and a name that the write
2069
+ // replaced is still written back. A host that does not answer is not waited for without end.
2070
+ if (namings.size) {
2071
+ const waited = new AbortController();
2072
+ await Promise.race([Promise.allSettled([...namings.values()].map(watch => watch.finish())), sleep(options.namingUnloadMs ?? NAMING_UNLOAD_MS, waited.signal).catch(() => {})]);
2073
+ waited.abort();
2074
+ for (const watch of [...namings.values()]) watch.end();
2075
+ }
1821
2076
  completed.clear();
1822
2077
  openStores.clear();
1823
2078
  await Promise.allSettled(registrations.reverse().map(r => r.dispose()));