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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "opencode-azure-devops-pr-review",
3
- "version": "0.4.5",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
- "description": "Azure DevOps PR reviews from a URL in OpenCode, with no checkout, configurable models, separate verification, and comment previews you can adjust before posting",
5
+ "description": "Azure DevOps PR reviews from a URL in OpenCode, with no checkout, review passes on the models you choose, and comment previews you can adjust before posting",
6
6
  "scripts": {
7
7
  "test": "node --test tests/*.test.mjs",
8
8
  "check": "node --check src/session.mjs && node --check src/runtime.mjs && node --check src/comment-data.mjs && node --check src/comment-work.mjs && node --check src/comments.mjs && node --check src/config.mjs && node --check src/output.mjs && node --check src/diagnostics.mjs && node --check src/attribution.mjs && node --check src/host.mjs && node --check src/tool-queue.mjs && node --check src/azure.mjs && node --check src/diff.mjs && node --check src/search.mjs && node --check src/review-tools.mjs && node --check src/review-work.mjs && node --check src/store.mjs && node --check src/plugin.js && node --check src/setup.mjs && node --check src/tui-model.mjs && node --check src/tui-setup.mjs && node --check src/tui-actions.mjs && node --check src/tui.js && node --check server.js && node --check scripts/build-tui.mjs && node scripts/build-tui.mjs --check && sh -n install.sh && sh -n uninstall.sh",
@@ -1,15 +1,54 @@
1
- import { ROLES, MAX_ARCHIVE_MEGABYTES } from './config.mjs';
1
+ import { ROLES, MAX_ARCHIVE_MEGABYTES, isModelReference } from './config.mjs';
2
2
  // Deterministic attribution from invoked reviewer stages, not model-authored claims.
3
+ // `comment` is the disclosure line of comments on a verified review saved by 0.4.x and `quick` the method named
4
+ // for a quick review of 0.4.x: posted comments carry them, so they stay as they were. `reviewers` names the
5
+ // method of every review of this pipeline.
3
6
  const vocabulary = {
4
- en: { title: 'AI review provenance', disclaimer: 'AI-generated review, not human approval. Posting through a user account does not imply that person verified these conclusions.', method: 'Independent initial reviews, followed by source-based verification, duplicate merging, and rejection of unsupported findings; not majority voting.', roles: ['Source check', 'Functional review', 'Risk review', 'Verification', 'Duplicate check', 'Quick review', 'Severity rating'], stage: 'Stage', model: 'Selected provider/model ID', sessions: 'Sessions', count: 'Initial findings', dispositions: 'Finding dispositions', finding: 'Finding', result: 'Result', merged: 'Merged into', extra: 'New verifier findings', note: 'IDs identify the models selected in OpenCode, not independently verified provider backend identities. Host auxiliary models and the original chat model are not part of this ledger.', comment: 'AI-generated review; not human review or approval. Models:',
5
- quickMethod: 'Quick review: one reviewer per shard covered functional and risk focus and checked its own findings against the source it read; no independent verification or duplicate merging. The runtime checked only the form and source of the findings.',
6
- lead: 'AI-generated review; not human review or approval. ', quick: 'Review method: quick review, not independently verified', coverage: 'coverage incomplete', models: 'Models:', separator: '; ', end: '. ' },
7
- tw: { title: 'AI 審查來源', disclaimer: '本報告由 AI 產生,不代表人工核准。使用個人帳號發佈,不表示該使用者已驗證這些結論。', method: '各模型獨立初審,再由驗證模型回查原始碼、交叉驗證、合併重複問題並排除缺乏證據的結論;不是多數決。', roles: ['來源檢查', '功能初審', '風險初審', '驗證', '重複檢查', '快速審查', '嚴重度評定'], stage: '階段', model: '實際選用的 provider/model ID', sessions: '工作階段數', count: '初審問題數', dispositions: '問題處置', finding: '問題', result: '結果', merged: '合併至', extra: '驗證新增問題', note: '此處記錄 OpenCode 實際選用的模型 ID,不是對供應商後端模型身分的獨立驗證;不包含主對話及宿主的輔助模型。', comment: 'AI 審查,非人工審查或核准。模型:',
8
- quickMethod: '快速審查:每個分片由一位審查者同時檢查功能與風險,並依自己讀到的原始碼回查發現;沒有獨立驗證,也沒有合併重複問題。runtime 只檢查發現的形式與來源。',
9
- lead: 'AI 審查,非人工審查或核准。', quick: '審查方式:快速審查,未經獨立驗證', coverage: '覆蓋不完整', models: '模型:', separator: ';', end: '。' },
10
- cn: { title: 'AI 审查来源', disclaimer: '本报告由 AI 产生,不代表人工批准。使用个人账号发布,不表示该用户已验证这些结论。', method: '各模型独立初审,再由验证模型回查源码、交叉验证、合并重复问题并排除缺乏证据的结论;不是多数决。', roles: ['来源检查', '功能初审', '风险初审', '验证', '重复检查', '快速审查', '严重度评定'], stage: '阶段', model: '实际选用的 provider/model ID', sessions: '会话数', count: '初审问题数', dispositions: '问题处置', finding: '问题', result: '结果', merged: '合并至', extra: '验证新增问题', note: '此处记录 OpenCode 实际选用的模型 ID,不是对供应商后端模型身份的独立验证;不包含主对话及宿主的辅助模型。', comment: 'AI 审查,非人工审查或批准。模型:',
11
- quickMethod: '快速审查:每个分片由一位审查者同时检查功能与风险,并依自己读到的源码回查发现;没有独立验证,也没有合并重复问题。runtime 只检查发现的形式与来源。',
12
- lead: 'AI 审查,非人工审查或批准。', quick: '审查方式:快速审查,未经独立验证', coverage: '覆盖不完整', models: '模型:', separator: ';', end: '。' },
7
+ en: { title: 'AI review provenance', disclaimer: 'AI-generated review, not human approval. Posting through a user account does not imply that person verified these conclusions.',
8
+ roles: { review: 'Review', dedupe: 'Duplicate check', rating: 'Severity rating' }, pass: n => ` (pass ${n})`, stage: 'Stage', model: 'Selected provider/model ID', sessions: 'Sessions', count: 'Findings reported', dispositions: 'Finding dispositions', finding: 'Finding', result: 'Result', merged: 'Merged into',
9
+ note: 'IDs identify the models selected in OpenCode, not independently verified provider backend identities. Host auxiliary models and the original chat model are not part of this ledger.', comment: 'AI-generated review; not human review or approval. Models:',
10
+ method: { one: 'One reviewer session per shard reviewed the changed files.', several: n => `${n} independent reviewer passes reviewed the changed files, each shard in a session of its own.`,
11
+ oneAsked: 'One reviewer session per shard was asked to review the changed files.', severalAsked: n => `${n} independent reviewer passes were asked to review the changed files, each shard in a session of its own.`,
12
+ failed: (count, of) => `${count} of the ${of} reviewer sessions failed or gave no usable review; the coverage says what that left unreviewed.`,
13
+ checks: 'Each reviewer checked its own findings against the source it read, and the runtime checked the form and source of every reported finding.',
14
+ unchecked: 'No reviewer session gave a usable review, so the findings on record are observations that nothing checked.',
15
+ checksSome: 'Each reviewer session that gave a usable review checked its own findings against the source it read, and the runtime checked the form and source of every reported finding.',
16
+ dedupe: 'A duplicate check merged repeated reports of one defect.', dedupeNone: 'A duplicate check compared what different sessions reported in one file and merged nothing.',
17
+ dedupeFailed: count => `The duplicate check of ${count} file(s) failed, so their findings may repeat each other.`,
18
+ rated: 'A rating session without tools set the severities from the finding texts alone.', kept: count => `${count} finding(s) got no usable rating and keep their reviewer's level.`, unrated: 'The severities are the reviewers\' own.',
19
+ end: 'No separate verification ran, and nothing was decided by voting.' },
20
+ lead: 'AI-generated review; not human review or approval. ', quick: 'Review method: quick review, not independently verified', reviewers: 'Review method: findings checked by their reviewer against the source, no separate verification',
21
+ coverage: 'coverage incomplete', models: 'Models:', separator: '; ', end: '. ' },
22
+ tw: { title: 'AI 審查來源', disclaimer: '本報告由 AI 產生,不代表人工核准。使用個人帳號發佈,不表示該使用者已驗證這些結論。',
23
+ roles: { review: '審查', dedupe: '重複檢查', rating: '嚴重度評定' }, pass: n => `(第 ${n} 次)`, stage: '階段', model: '實際選用的 provider/model ID', sessions: '工作階段數', count: '回報問題數', dispositions: '問題處置', finding: '問題', result: '結果', merged: '合併至',
24
+ note: '此處記錄 OpenCode 實際選用的模型 ID,不是對供應商後端模型身分的獨立驗證;不包含主對話及宿主的輔助模型。', comment: 'AI 審查,非人工審查或核准。模型:',
25
+ method: { one: '每個分片的變更檔由一個審查工作階段審查。', several: n => `變更檔由 ${n} 次獨立的審查各審一遍,每個分片各用一個工作階段。`,
26
+ oneAsked: '每個分片的變更檔交給一個審查工作階段審查。', severalAsked: n => `變更檔安排了 ${n} 次獨立的審查,每個分片各用一個工作階段。`,
27
+ failed: (count, of) => `${of} 個審查工作階段中有 ${count} 個失敗或沒有可用的審查結果;因此沒審到的部分見覆蓋範圍。`,
28
+ checks: '審查者依自己讀到的原始碼查證自己的發現,runtime 檢查每則回報的發現的形式與來源。',
29
+ unchecked: '沒有任何審查工作階段給出可用的審查,紀錄中的發現只是未經查證的觀察。',
30
+ checksSome: '給出可用審查的工作階段依自己讀到的原始碼查證自己的發現,runtime 檢查每則回報的發現的形式與來源。',
31
+ dedupe: '重複檢查合併了同一個缺陷的重複回報。', dedupeNone: '重複檢查比對了不同工作階段在同一個檔案回報的發現,沒有合併任何一則。',
32
+ dedupeFailed: count => `${count} 個檔案的重複檢查失敗,這些檔案的發現可能彼此重複。`,
33
+ rated: '嚴重度由一個沒有工具的評定工作階段只依發現的文字評定。', kept: count => `${count} 則發現沒有可用的評定,沿用審查者給的等級。`, unrated: '嚴重度是審查者自己給的。',
34
+ end: '沒有另外的驗證,也不是多數決。' },
35
+ lead: 'AI 審查,非人工審查或核准。', quick: '審查方式:快速審查,未經獨立驗證', reviewers: '審查方式:發現由審查者依原始碼自行查證,沒有另外的驗證',
36
+ coverage: '覆蓋不完整', models: '模型:', separator: ';', end: '。' },
37
+ cn: { title: 'AI 审查来源', disclaimer: '本报告由 AI 产生,不代表人工批准。使用个人账号发布,不表示该用户已验证这些结论。',
38
+ roles: { review: '审查', dedupe: '重复检查', rating: '严重度评定' }, pass: n => `(第 ${n} 次)`, stage: '阶段', model: '实际选用的 provider/model ID', sessions: '会话数', count: '报告问题数', dispositions: '问题处置', finding: '问题', result: '结果', merged: '合并至',
39
+ note: '此处记录 OpenCode 实际选用的模型 ID,不是对供应商后端模型身份的独立验证;不包含主对话及宿主的辅助模型。', comment: 'AI 审查,非人工审查或批准。模型:',
40
+ method: { one: '每个分片的变更文件由一个审查会话审查。', several: n => `变更文件由 ${n} 次独立的审查各审一遍,每个分片各用一个会话。`,
41
+ oneAsked: '每个分片的变更文件交给一个审查会话审查。', severalAsked: n => `变更文件安排了 ${n} 次独立的审查,每个分片各用一个会话。`,
42
+ failed: (count, of) => `${of} 个审查会话中有 ${count} 个失败或没有可用的审查结果;因此没审到的部分见覆盖范围。`,
43
+ checks: '审查者依自己读到的源码查证自己的发现,runtime 检查每则报告的发现的形式与来源。',
44
+ unchecked: '没有任何审查会话给出可用的审查,记录中的发现只是未经查证的观察。',
45
+ checksSome: '给出可用审查的会话依自己读到的源码查证自己的发现,runtime 检查每则报告的发现的形式与来源。',
46
+ dedupe: '重复检查合并了同一个缺陷的重复报告。', dedupeNone: '重复检查比对了不同会话在同一个文件报告的发现,没有合并任何一则。',
47
+ dedupeFailed: count => `${count} 个文件的重复检查失败,这些文件的发现可能彼此重复。`,
48
+ rated: '严重度由一个没有工具的评定会话只依发现的文字评定。', kept: count => `${count} 则发现没有可用的评定,沿用审查者给的等级。`, unrated: '严重度是审查者自己给的。',
49
+ end: '没有另外的验证,也不是多数决。' },
50
+ lead: 'AI 审查,非人工审查或批准。', quick: '审查方式:快速审查,未经独立验证', reviewers: '审查方式:发现由审查者依源码自行查证,没有另外的验证',
51
+ coverage: '覆盖不完整', models: '模型:', separator: ';', end: '。' },
13
52
  };
14
53
  // Fixed coverage reasons for the summary disclosure; reviewer text never goes there.
15
54
  const coverageWords = {
@@ -51,7 +90,7 @@ export function renderCommentActions(id, language, after) {
51
90
  ['PR 留言', '预览留言(会用到模型,不会发布)', '排除发现或改严重度(用报告里的 ID),再看新的预览', '以 PAT 拥有者的身份发布已保存的预览',
52
91
  `这些命令不需要 review ID:会作用在这个对话当前的 review,也就是这一份,直到这里有另一份 review 完成或被使用。之后要指定这一份时加上 ID,例如 \`/pr-comment ${id} --publish\`;\`/pr-comment --list\` 列出保存的 review,\`/pr-comment --help\` 列出所有选项。`,
53
92
  'Review 与预览私下保存(最近 20 份),重启 OpenCode 后仍可使用。发布时会跳过 PR 上已存在的留言,可以安全地重跑。']);
54
- return `## ${heading}\n\n${automatic ? `${automatic}\n\n` : ''}- ${preview}: \`/pr-comment\`\n- ${adjust}: \`/pr-comment --exclude F-1,R-2\`, \`/pr-comment --severity F-3=low\`\n- ${publish}: \`/pr-comment --publish\`\n\n${current}\n\n${retention}`;
93
+ return `## ${heading}\n\n${automatic ? `${automatic}\n\n` : ''}- ${preview}: \`/pr-comment\`\n- ${adjust}: \`/pr-comment --exclude F-1,F-2\`, \`/pr-comment --severity F-3=low\`\n- ${publish}: \`/pr-comment --publish\`\n\n${current}\n\n${retention}`;
55
94
  }
56
95
 
57
96
  /**
@@ -74,7 +113,7 @@ export function conversationTitle(target) {
74
113
  return `AZPR: PR #${target.pullRequestId} (${String(target.repository).slice(0, 60)})`;
75
114
  }
76
115
 
77
- /** Models per role, aggregated over shards and retries. */
116
+ /** Models per role, aggregated over shards and retries: the passes in their order, then the duplicate check and the rating. */
78
117
  export function reviewProvenance(run) {
79
118
  const rows = new Map();
80
119
  for (const stage of run.stages) {
@@ -86,15 +125,39 @@ export function reviewProvenance(run) {
86
125
  row.findings += stage.result?.findings?.length ?? 0;
87
126
  rows.set(key, row);
88
127
  }
89
- return { mode: run.profile, stages: [...rows.values()].sort((a, b) => ROLES[a.role].order - ROLES[b.role].order) };
128
+ const position = role => (typeof ROLES[role].slot === 'number' ? ROLES[role].slot : 0);
129
+ return { mode: run.profile, stages: [...rows.values()].sort((a, b) => ROLES[a.role].order - ROLES[b.role].order || position(a.role) - position(b.role)) };
130
+ }
131
+
132
+ /**
133
+ * How a review of this pipeline produced its findings, in fixed sentences, from the method its record states:
134
+ * what ran, and what of it failed. A sentence says only what the record holds: sessions that failed, a
135
+ * duplicate check that merged, merged nothing or failed, a rating that set every level, some or none.
136
+ */
137
+ /** Whether a review of this version had a session that gave a usable review; a record without passes is taken as it was. */
138
+ export const answered = final => !Array.isArray(final?.method?.passes) || final.method.passes.some(pass => (pass.sessions ?? 0) > (pass.failed ?? 0));
139
+
140
+ export function methodText(method, language) {
141
+ const m = words(language).method, passes = method?.passes ?? [], check = method?.duplicateCheck ?? {}, rating = method?.rating ?? {};
142
+ const sessions = passes.reduce((sum, pass) => sum + (pass.sessions ?? 0), 0), failed = passes.reduce((sum, pass) => sum + (pass.failed ?? 0), 0);
143
+ const checked = (check.groups ?? 0) - (check.failed ?? 0);
144
+ const rated = rating.state && rating.state !== 'off' && rating.rated > 0;
145
+ // The passes reviewed the files where every session gave a usable review; otherwise they were asked to, and
146
+ // only the sessions that gave one checked their findings (none, where no session did).
147
+ const ok = answered({ method }), all = ok && !failed;
148
+ return [passes.length > 1 ? (all ? m.several : m.severalAsked)(passes.length) : all ? m.one : m.oneAsked, ...(failed ? [m.failed(failed, sessions)] : []), !ok ? m.unchecked : all ? m.checks : m.checksSome,
149
+ ...(check.merged ? [m.dedupe] : checked > 0 ? [m.dedupeNone] : []), ...(check.failed ? [m.dedupeFailed(check.failed)] : []),
150
+ rated ? m.rated : m.unrated, ...(rated && rating.kept ? [m.kept(rating.kept)] : []), m.end].join(pick(language, ' ', '', ''));
90
151
  }
91
152
 
92
153
  export function provenanceReport(provenance, final, language) {
93
154
  const w = words(language);
94
- const quick = provenance.mode === 'quick';
95
- const rows = provenance.stages.map(s => `| ${w.roles[ROLES[s.role]?.order]} | \`${s.model}\` | ${s.sessions} | ${ROLES[s.role]?.format === 'initial' ? s.findings : '—'} |`).join('\n');
155
+ // A pass is named by its number wherever the review had several, also when only one of them left a row.
156
+ const several = (final.method?.passes?.length ?? 0) > 1 || provenance.stages.filter(s => ROLES[s.role]?.kind === 'review').length > 1;
157
+ const name = role => `${w.roles[ROLES[role]?.kind] ?? role}${several && ROLES[role]?.kind === 'review' ? w.pass(ROLES[role].slot + 1) : ''}`;
158
+ const rows = provenance.stages.map(s => `| ${name(s.role)} | \`${s.model}\` | ${s.sessions} | ${ROLES[s.role]?.format === 'initial' ? s.findings : '—'} |`).join('\n');
96
159
  const dispositions = final.dispositions.map(d => `| ${d.id} | ${d.status} | ${d.mergedInto ?? '—'} |`).join('\n');
97
- return `## ${w.title} (${provenance.mode})\n\n${w.disclaimer}\n\n${quick ? w.quickMethod : w.method}\n\n| ${w.stage} | ${w.model} | ${w.sessions} | ${w.count} |\n| --- | --- | --- | --- |\n${rows}\n\n${w.note}\n\n### ${w.dispositions}\n\n| ${w.finding} | ${w.result} | ${w.merged} |\n| --- | --- | --- |\n${dispositions || '| — | — | — |'}${quick ? '' : `\n\n${w.extra}: ${(final.newFindings ?? []).map(f => f.id).join(', ') || '0'}`}`;
160
+ return `## ${w.title} (${provenance.mode})\n\n${w.disclaimer}\n\n${methodText(final.method, language)}\n\n| ${w.stage} | ${w.model} | ${w.sessions} | ${w.count} |\n| --- | --- | --- | --- |\n${rows}\n\n${w.note}\n\n### ${w.dispositions}\n\n| ${w.finding} | ${w.result} | ${w.merged} |\n| --- | --- | --- |\n${dispositions || '| — | — | — |'}`;
98
161
  }
99
162
 
100
163
  /** Fixed-phrase description of incomplete coverage; '' when coverage is complete or unknown. */
@@ -109,37 +172,150 @@ export function coverageNote(coverage, language) {
109
172
  }
110
173
 
111
174
  /**
112
- * The disclosure line of AZPR's comments. Verified reviews keep the original
113
- * line; a quick review names its method and, for the summary, incomplete
114
- * coverage. The models are those of the review stages and comment planning.
175
+ * The disclosure line of AZPR's comments, by the method of their review
176
+ * (`reviewMethod` in comments.mjs). A review of this pipeline names its method
177
+ * and, for the summary, incomplete coverage; so does a quick review saved by
178
+ * 0.4.x, in its own words; a verified review saved by 0.4.x keeps the line it
179
+ * always had. The models are those of the review stages and comment planning.
115
180
  */
116
- export function commentAttribution(provenance, language, commentModel, { verification = 'independent', coverage } = {}) {
181
+ export function commentAttribution(provenance, language, commentModel, { method = 'reviewers', coverage } = {}) {
117
182
  if (!provenance) return '';
118
183
  const w = words(language);
119
184
  const models = [...new Set([...provenance.stages.map(s => s.model), commentModel])].map(model => `\`${model}\``).join(', ');
120
- if (verification !== 'none') return `${w.comment} ${models}`;
185
+ if (method === 'verified') return `${w.comment} ${models}`;
121
186
  const gap = coverageNote(coverage, language);
122
187
  const brackets = pick(language, ['(', ')'], ['(', ')'], ['(', ')']);
123
- return `${w.lead}${w.quick}${gap ? `${w.separator}${w.coverage}${pick(language, ' ', '', '')}${brackets[0]}${gap}${brackets[1]}` : ''}${w.end}${w.models} ${models}`;
188
+ return `${w.lead}${method === 'quick' ? w.quick : w.reviewers}${gap ? `${w.separator}${w.coverage}${pick(language, ' ', '', '')}${brackets[0]}${gap}${brackets[1]}` : ''}${w.end}${w.models} ${models}`;
124
189
  }
125
190
 
126
191
  // Presentation uses validated fields; it neither translates nor invents claims.
127
192
  const reportVocabulary = {
128
- en: { scope: 'Scope and versions', overview: 'Checks and limitations', findings: 'Confirmed findings', decisions: 'Finding decisions', evidence: 'Evidence and impact', counter: 'Counterevidence', suggestion: 'Correction and verification', location: 'Location', moved: 'initial location', none: 'None reported.', draft: 'Incomplete review draft', warning: 'AI-generated, unconfirmed initial observations. Verification did not complete. This is not an approved review or input for PR comments.', failure: 'Failure', candidates: 'Unconfirmed initial observations', gaps: 'Coverage gaps', coverage: 'Coverage', partial: 'Verification did not produce a structured result. These claims are provisional and cannot be used for PR comments.', stale: 'The PR source changed during the review. Run a new review before commenting.' },
129
- tw: { scope: '範圍與版本', overview: '查證與限制', findings: '已確認問題', decisions: '問題裁決理由', evidence: '證據與影響', counter: '反證檢查', suggestion: '修正與驗證建議', location: '位置', moved: '初審位置', none: '未列出。', draft: '未完成審查草稿', warning: 'AI 產生的初審觀察,尚未完成驗證,不能視為已確認結論或用於 PR 留言。', failure: '失敗原因', candidates: '尚未確認的初審觀察', gaps: '覆蓋缺口', coverage: '覆蓋範圍', partial: '驗證沒有產生結構化結果,下列結論僅供檢視,不能用於 PR 留言。', stale: 'PR 原始碼在審查期間已變更,請重新審查後再留言。' },
130
- cn: { scope: '范围与版本', overview: '查证与限制', findings: '已确认问题', decisions: '问题裁决理由', evidence: '证据与影响', counter: '反证检查', suggestion: '修正与验证建议', location: '位置', moved: '初审位置', none: '未列出。', draft: '未完成审查草稿', warning: 'AI 产生的初审观察,尚未完成验证,不能视为已确认结论或用于 PR 留言。', failure: '失败原因', candidates: '尚未确认的初审观察', gaps: '覆盖缺口', coverage: '覆盖范围', partial: '验证没有产生结构化结果,下列结论仅供查看,不能用于 PR 留言。', stale: 'PR 源码在审查期间已变更,请重新审查后再留言。' },
193
+ en: { scope: 'Scope and versions', overview: 'Checks and limitations', decisions: 'Finding decisions', evidence: 'Evidence and impact', counter: 'Counterevidence', suggestion: 'Correction and verification', location: 'Location', none: 'None reported.', draft: 'Incomplete review draft',
194
+ warning: 'AI-generated, unconfirmed review observations. The review did not complete. This is not an approved review or input for PR comments.', failure: 'Failure', candidates: 'Unconfirmed review observations', gaps: 'Coverage gaps', coverage: 'Coverage', stale: 'The PR source changed during the review. Run a new review before commenting.',
195
+ banner: 'Reported findings were checked by their reviewer against the source; no separate verification ran.', complete: 'complete', incomplete: 'incomplete',
196
+ once: (x, y) => `${x}/${y} changed file(s) reviewed`, every: (z, y, n) => `${z}/${y} in all ${n} passes`, findings: 'Reported findings',
197
+ partial: 'No review session produced a usable result. These claims are provisional and cannot be used for PR comments.',
198
+ reported: 'passed the runtime\'s format and source checks; no separate verification ran.', needsInfo: 'Findings that need more information (not eligible for comments)', reviewer: 'reviewer' },
199
+ tw: { scope: '範圍與版本', overview: '查證與限制', decisions: '問題裁決理由', evidence: '證據與影響', counter: '反證檢查', suggestion: '修正與驗證建議', location: '位置', none: '未列出。', draft: '未完成審查草稿',
200
+ warning: 'AI 產生的審查觀察,審查沒有完成,不能視為已確認結論或用於 PR 留言。', failure: '失敗原因', candidates: '尚未確認的審查觀察', gaps: '覆蓋缺口', coverage: '覆蓋範圍', stale: 'PR 原始碼在審查期間已變更,請重新審查後再留言。',
201
+ banner: '回報的發現由審查者依原始碼自行查證;沒有另外的驗證。', complete: '完整', incomplete: '不完整',
202
+ once: (x, y) => `已審查 ${x}/${y} 個變更檔`, every: (z, y, n) => `${z}/${y} 個在全部 ${n} 次審查都審過`, findings: '回報的問題',
203
+ partial: '沒有任何審查工作階段產生可用結果,下列結論僅供檢視,不能用於 PR 留言。',
204
+ reported: '通過 runtime 的形式與來源檢查;沒有另外的驗證。', needsInfo: '需要更多資訊的發現(不能用於留言)', reviewer: '審查者' },
205
+ cn: { scope: '范围与版本', overview: '查证与限制', decisions: '问题裁决理由', evidence: '证据与影响', counter: '反证检查', suggestion: '修正与验证建议', location: '位置', none: '未列出。', draft: '未完成审查草稿',
206
+ warning: 'AI 产生的审查观察,审查没有完成,不能视为已确认结论或用于 PR 留言。', failure: '失败原因', candidates: '尚未确认的审查观察', gaps: '覆盖缺口', coverage: '覆盖范围', stale: 'PR 源码在审查期间已变更,请重新审查后再留言。',
207
+ banner: '报告的发现由审查者依源码自行查证;没有另外的验证。', complete: '完整', incomplete: '不完整',
208
+ once: (x, y) => `已审查 ${x}/${y} 个变更文件`, every: (z, y, n) => `${z}/${y} 个在全部 ${n} 次审查都审过`, findings: '报告的问题',
209
+ partial: '没有任何审查会话产生可用结果,下列结论仅供查看,不能用于 PR 留言。',
210
+ reported: '通过 runtime 的形式与来源检查;没有另外的验证。', needsInfo: '需要更多信息的发现(不能用于留言)', reviewer: '审查者' },
131
211
  };
132
212
  const reportWords = language => reportVocabulary[pick(language, 'en', 'tw', 'cn')];
133
213
 
134
214
  function displayLocation(value) {
135
- try {
136
- const p = JSON.parse(value);
137
- if (p && ['head', 'base'].includes(p.side) && typeof p.path === 'string' && p.path.startsWith('/') &&
138
- Number.isSafeInteger(p.lineStart) && p.lineStart > 0 && Number.isSafeInteger(p.lineEnd) && p.lineEnd >= p.lineStart) {
139
- return `${p.side}:${p.path}:${p.lineStart}${p.lineEnd === p.lineStart ? '' : '-' + p.lineEnd}`;
140
- }
141
- } catch { /* Ordinary string locations stay literal. */ }
142
- return value;
215
+ // A structured location (a JSON string or an object, as 0.4.x saved some) reads as the text form; an end it leaves
216
+ // out is its start. Anything else that is no text is shown as JSON, never as "[object Object]".
217
+ let p = value;
218
+ if (typeof p === 'string' && p.trim().startsWith('{')) { try { p = JSON.parse(p); } catch { return value; } }
219
+ if (!p || typeof p !== 'object') return value;
220
+ const side = p.side ?? 'head', end = p.lineEnd === undefined || p.lineEnd === null ? p.lineStart : p.lineEnd;
221
+ if (['head', 'base'].includes(side) && typeof p.path === 'string' && p.path.startsWith('/') && Number.isSafeInteger(p.lineStart) && p.lineStart > 0 && Number.isSafeInteger(end) && end >= p.lineStart) {
222
+ return `${side}:${p.path}:${p.lineStart}${end === p.lineStart ? '' : '-' + end}`;
223
+ }
224
+ return typeof value === 'string' ? value : JSON.stringify(value);
225
+ }
226
+
227
+ /** The heading of the list of other places in each language it is written in; what reads the list back knows it by these lines. */
228
+ export const OTHER_PLACES_HEADINGS = Object.freeze(['**📍 Also at** (the same defect; fix these places with it):', '**📍 其他位置**(同一個問題,請一併修正):', '**📍 其他位置**(同一个问题,请一并修正):']);
229
+
230
+ /**
231
+ * The other places of one defect that a comment covers, as the runtime adds
232
+ * them under the comment's own text: one row per finding with its file and
233
+ * lines, from the findings' own locations, never from text a model wrote.
234
+ * A plain list: nothing here is collapsed or linked.
235
+ * @param {{findingId: string, place: string}[]} places
236
+ */
237
+ export function renderOtherPlaces(places, language) {
238
+ const [english, traditional, simplified] = OTHER_PLACES_HEADINGS;
239
+ const heading = pick(language, english, traditional, simplified);
240
+ return `${heading}\n${places.map(({ findingId, place }) => placeRow(place, findingId, pick(language, ROW_BRACKETS[0], ROW_BRACKETS[1], ROW_BRACKETS[1]))).join('\n')}`;
241
+ }
242
+
243
+ // How a row puts its finding ID in brackets: in English, and in Chinese.
244
+ const ROW_BRACKETS = [[' (', ')'], ['(', ')']];
245
+
246
+ /** One row of that list: the place in a code span that holds any text (longer than the longest run of backticks inside it), then the finding ID. */
247
+ function placeRow(place, findingId, [open, close]) {
248
+ const text = String(place).replace(/[\r\n\t]+/g, ' ');
249
+ const run = Math.max(0, ...(text.match(/`+/g) ?? []).map(match => match.length));
250
+ const fence = '`'.repeat(run + 1);
251
+ return `- ${run ? `${fence} ${text} ${fence}` : `\`${text}\``}${open}${String(findingId).replace(/[^A-Za-z0-9_-]/g, '')}${close}`;
252
+ }
253
+
254
+ /**
255
+ * Whether a place can be written into that list and read back as it is: its
256
+ * text holds no control character, no line separator and neither end of an
257
+ * HTML comment, which the posted text would have to change, and its path no
258
+ * colon (a structured location of 0.4.x may name one), since the reader takes
259
+ * the first colon for the start of the lines.
260
+ */
261
+ export const listablePlace = place => typeof place === 'string' && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]|<!--|-->/.test(place) &&
262
+ (place.match(/:/g) ?? []).length <= 1;
263
+
264
+ /**
265
+ * The places a posted comment of AZPR's lists, read back from its text for a
266
+ * later plan (`alsoAt` in the digest of a thread): the rows under the heading
267
+ * `renderOtherPlaces` writes, where they end the comment's own text as
268
+ * `assemblePlan` writes it. A row counts only when writing its place and its
269
+ * finding ID again gives the very line (so a row is one a finding's place
270
+ * could have produced: a path, its lines in order, an ID). After the rows
271
+ * comes a blank line, then the attribution if there is one (a rule, the line
272
+ * `commentAttribution` writes for a comment, and a blank line), then the two
273
+ * markers of such a comment (`linesMarker`, then its own) with a blank line
274
+ * between them.
275
+ * [] for any other text: one that merely holds such a heading or such rows,
276
+ * one whose row has another form, one that was continued after the list.
277
+ * What is read here tells a planner what a thread says it covers, as the
278
+ * start of the thread's text does; nothing is posted or skipped because of it.
279
+ */
280
+ export function listedPlaces(content) {
281
+ // Line by line as written: only the line ends a service may return differ from what the runtime wrote.
282
+ const lines = String(content ?? '').split(/\r?\n/);
283
+ while (lines.length && lines.at(-1) === '') lines.pop();
284
+ const heading = lines.findLastIndex(line => OTHER_PLACES_HEADINGS.includes(line));
285
+ if (heading < 0) return [];
286
+ // The rows are written in the heading's language: English brackets under the English heading, Chinese ones otherwise.
287
+ const brackets = ROW_BRACKETS[OTHER_PLACES_HEADINGS.indexOf(lines[heading]) ? 1 : 0];
288
+ const places = [];
289
+ let next = heading + 1;
290
+ for (; next < lines.length && lines[next].startsWith('- `'); next++) {
291
+ // The row's parts, each read once: the opening code-span delimiter, the finding ID at the end, the place
292
+ // between them. Writing the row again must give the very line, so nothing else passes.
293
+ const line = lines[next], fence = /^`+/.exec(line.slice(2))[0], id = /[((]([A-Za-z]+-\d+)[))]$/.exec(line);
294
+ const inner = id && line.slice(2 + fence.length, id.index).trimEnd();
295
+ const place = inner && inner.endsWith(fence) ? inner.slice(0, -fence.length).trim() : '';
296
+ const at = /^\/[^:]+:([1-9]\d*)(?:-([1-9]\d*))?$/.exec(place);
297
+ // A place as a finding's is written (lines in order), in the row the runtime writes for it under this heading.
298
+ if (!at || Number(at[2] ?? at[1]) < Number(at[1]) || !listablePlace(place) || placeRow(place, id[1], brackets) !== line) return [];
299
+ places.push(place);
300
+ }
301
+ const rest = lines.slice(next);
302
+ const marker = /^<!-- azpr-comment:[a-f0-9]{32} -->$/;
303
+ // The end of a comment for several places: the marker of its lines, a blank line, its own marker.
304
+ if (!places.length || rest.shift() !== '' || !marker.test(rest.pop() ?? '') || rest.pop() !== '' || !marker.test(rest.pop() ?? '')) return [];
305
+ if (!rest.length) return places;
306
+ // The attribution: a rule, the line the runtime writes for a comment, and a blank line.
307
+ return rest.length === 3 && rest[0] === '---' && commentAttributionLine(rest[1]) && rest[2] === '' ? places : [];
308
+ }
309
+
310
+ /**
311
+ * Whether a line is the attribution `commentAttribution` writes for an inline
312
+ * comment, in any language: its fixed wording for a review of this pipeline,
313
+ * or for a verified or a quick review of 0.4.x, then the models (references as settings take them), each in a code
314
+ * span, and nothing else.
315
+ */
316
+ function commentAttributionLine(line) {
317
+ return Object.values(vocabulary).flatMap(words => [`${words.comment} `, ...[words.quick, words.reviewers].map(method => `${words.lead}${method}${words.end}${words.models} `)])
318
+ .some(wording => line.startsWith(wording) && line.slice(wording.length).split(', ').every(span => /^`[^`]+`$/.test(span) && isModelReference(span.slice(1, -1))));
143
319
  }
144
320
 
145
321
  /** A compact index of existing claims, not another model-authored assessment. */
@@ -158,7 +334,7 @@ export function renderReviewSummary(findings, language, introduction = '', { ver
158
334
  }
159
335
  findings = entries;
160
336
  const counts = ['high', 'medium', 'low'].map(level => `${level}: ${findings.filter(f => f.severity === level).length}`).join(' · ');
161
- // A quick review confirms nothing, so it does not speak of confirmed defects.
337
+ // Only a verified review of 0.4.x speaks of confirmed defects: nothing else confirms anything.
162
338
  const empty = verification === 'none'
163
339
  ? pick(language, 'No defects reported; this does not establish that the code is bug-free.', '未回報缺陷;這不保證程式沒有問題。', '未报告缺陷;这不保证程序没有问题。')
164
340
  : pick(language, 'No confirmed defects found; this does not establish that the code is bug-free.', '未發現可確認缺陷;這不保證程式沒有問題。', '未发现可确认缺陷;这不保证程序没有问题。');
@@ -166,7 +342,7 @@ export function renderReviewSummary(findings, language, introduction = '', { ver
166
342
  return `## PR Review Summary\n\n${introduction ? `${introduction}\n\n` : ''}${counts}\n\n${rows ? `| Severity | Summary | ${w.location} |\n| --- | --- | --- |\n${rows}` : empty}`;
167
343
  }
168
344
 
169
- const findingFields = ['id', 'summary', 'severity', 'location', 'movedFrom', 'evidence', 'counterevidence', 'suggestion', 'origin', 'shardId', 'originalId'];
345
+ const findingFields = ['id', 'summary', 'severity', 'reviewerSeverity', 'location', 'evidence', 'counterevidence', 'suggestion', 'origin', 'shardId', 'originalId', 'generatedId'];
170
346
  function extraOutput(value, known) {
171
347
  const entries = Object.entries(value ?? {}).filter(([key, content]) => !known.includes(key) && content !== '' && content !== null && content !== undefined);
172
348
  if (!entries.length) return '';
@@ -178,7 +354,9 @@ function extraOutput(value, known) {
178
354
  }
179
355
  function renderFinding(finding = {}, w) {
180
356
  finding ??= {};
181
- return `### ${finding.id || '—'} — ${finding.summary || w.none} (${finding.severity || '—'})\n\n**${w.location}:** ${displayLocation(finding.location) || '—'}${finding.movedFrom ? ` (${w.moved}: ${displayLocation(finding.movedFrom)})` : ''}\n\n**${w.evidence}**\n\n${finding.evidence || w.none}\n\n**${w.counter}**\n\n${finding.counterevidence || w.none}\n\n**${w.suggestion}**\n\n${finding.suggestion || w.none}${extraOutput(finding, findingFields)}`;
357
+ // A level the rating changed shows the one its reviewer gave next to it.
358
+ const level = `${finding.severity || '—'}${finding.reviewerSeverity && finding.reviewerSeverity !== finding.severity ? `; ${w.reviewer}: ${finding.reviewerSeverity}` : ''}`;
359
+ return `### ${finding.id || '—'} — ${finding.summary || w.none} (${level})\n\n**${w.location}:** ${displayLocation(finding.location) || '—'}\n\n**${w.evidence}**\n\n${finding.evidence || w.none}\n\n**${w.counter}**\n\n${finding.counterevidence || w.none}\n\n**${w.suggestion}**\n\n${finding.suggestion || w.none}${extraOutput(finding, findingFields)}`;
182
360
  }
183
361
 
184
362
  function renderSnapshot(final) {
@@ -200,54 +378,37 @@ function renderCoverage(final, w) {
200
378
  return `\n\n**${w.coverage}**\n\n${rows}`;
201
379
  }
202
380
 
203
- const quickReportVocabulary = {
204
- en: { banner: 'Quick review: one reviewer per shard; the findings are not independently verified.', coverage: 'Coverage', complete: 'complete', incomplete: 'incomplete',
205
- findings: 'Reported findings (quick review, not independently verified)', partial: 'No quick review session produced a usable result. These claims are provisional and cannot be used for PR comments.',
206
- reported: 'passed the runtime\'s format and source checks; not independently verified.', needsInfo: 'Findings that need more information (not eligible for comments)' },
207
- tw: { banner: '快速審查:每個分片由一位審查者審查,發現未經獨立驗證。', coverage: '覆蓋', complete: '完整', incomplete: '不完整',
208
- findings: '回報的問題(快速審查,未經獨立驗證)', partial: '沒有任何快速審查工作階段產生可用結果,下列結論僅供檢視,不能用於 PR 留言。',
209
- reported: '通過 runtime 的形式與來源檢查,未經獨立驗證。', needsInfo: '需要更多資訊的發現(不能用於留言)' },
210
- cn: { banner: '快速审查:每个分片由一位审查者审查,发现未经独立验证。', coverage: '覆盖', complete: '完整', incomplete: '不完整',
211
- findings: '报告的问题(快速审查,未经独立验证)', partial: '没有任何快速审查会话产生可用结果,下列结论仅供查看,不能用于 PR 留言。',
212
- reported: '通过 runtime 的形式与来源检查,未经独立验证。', needsInfo: '需要更多信息的发现(不能用于留言)' },
213
- };
214
-
215
- /** Status, coverage and verification of a quick review, stated separately at the top. */
216
- function renderQuickReport(final, language) {
217
- const w = reportWords(language), q = quickReportVocabulary[pick(language, 'en', 'tw', 'cn')];
218
- const reported = final.dispositions.filter(d => d.status === 'REPORTED').map(d => ({ ...d.finding, id: d.id }));
381
+ /**
382
+ * The report of a review: status, coverage and method stated separately at the
383
+ * top, then the findings that are still reported, with the level in effect
384
+ * (and the reviewer's own where the rating changed it).
385
+ */
386
+ export function renderFinalReport(final, language) {
387
+ const w = reportWords(language);
388
+ const reported = final.dispositions.filter(d => d.status === 'REPORTED').map(d => ({ ...d.finding, id: d.id, reviewerSeverity: d.reviewerSeverity }));
219
389
  const pendingInfo = final.dispositions.filter(d => d.status === 'NEEDS_INFO' && d.partialFinding).map(d => ({ ...d.partialFinding, id: d.id }));
220
- const gap = coverageNote(final.coverageSummary, language);
221
- const coverageLine = `**${q.coverage}:** ${final.coverageSummary?.complete ? q.complete : `${q.incomplete}${gap ? ` (${gap})` : ''}`}`;
222
- const banner = `${final.status === 'STALE' ? `**STALE: ${w.stale}**\n\n` : final.status !== 'COMPLETE' ? `**${final.status}: ${q.partial}**\n\n` : ''}**${q.banner}**\n\n${coverageLine}\n\n`;
390
+ const c = final.coverageSummary, gap = coverageNote(c, language);
391
+ // Two numbers of the changed files Azure listed: reviewed at least once, and reviewed in every pass.
392
+ const counts = c && Number.isInteger(c.files) ? ` — ${w.once(c.reviewedOnce, c.files)}${c.passes > 1 ? `, ${w.every(c.reviewedByAll, c.files, c.passes)}` : ''}` : '';
393
+ const coverageLine = `**${w.coverage}:** ${c?.complete ? w.complete : `${w.incomplete}${gap ? ` (${gap})` : ''}`}${counts}`;
394
+ // A review without a usable answer has no checked findings to speak of: it says only that, and its coverage. A
395
+ // STALE review says that its source changed, and whether a session gave a usable review.
396
+ const usable = final.status === 'COMPLETE' || (final.status === 'STALE' && answered(final));
397
+ const banner = `${final.status === 'STALE' ? `**STALE: ${w.stale}**\n\n` : ''}${usable ? `**${w.banner}**` : `**${final.status}: ${w.partial}**`}\n\n${coverageLine}\n\n`;
223
398
  const limitations = (final.reviewWarnings ?? []).map(message => `- ${message}`).join('\n');
224
399
  const reportedIds = reported.map(f => f.id);
225
- const decisions = [...(reportedIds.length ? [`- **${reportedIds.join(', ')} — REPORTED:** ${q.reported}`] : []),
400
+ const decisions = [...(reportedIds.length ? [`- **${reportedIds.join(', ')} — REPORTED:** ${w.reported}`] : []),
226
401
  ...final.dispositions.filter(d => d.status !== 'REPORTED').map(d => `- **${d.id || '—'} — ${d.status}${d.mergedInto ? ' → ' + d.mergedInto : ''}:** ${d.reason || w.none}`)].join('\n');
227
402
  const reference = [...(final.initialObservations ?? []).map(f => renderFinding(f, w)), ...(final.unstructuredInitials ?? [])].join('\n\n');
228
- const referenceTitle = pick(language, 'Initial observations (reference only, not final conclusions)', '初審觀察(參考資料,非最終結論)', '初审观察(参考资料,非最终结论)');
229
- return `${banner}${final.status === 'COMPLETE' ? renderReviewSummary(reported, language, '', { verification: 'none' }) + '\n\n' : ''}## ${w.overview}\n\n${final.report || w.none}${limitations ? '\n\n' + limitations : ''}${renderCoverage(final, w)}\n\n## ${q.findings}\n\n${reported.map(f => renderFinding(f, w)).join('\n\n') || w.none}${pendingInfo.length && final.status === 'COMPLETE' ? `\n\n## ${q.needsInfo}\n\n${pendingInfo.map(f => renderFinding(f, w)).join('\n\n')}` : ''}\n\n## ${w.scope}\n\n${renderSnapshot(final)}\n\n## ${w.decisions}\n\n${decisions || w.none}${reference ? '\n\n## ' + referenceTitle + '\n\n' + reference : ''}`;
230
- }
231
-
232
- export function renderFinalReport(final, language) {
233
- if (final.verification === 'none') return renderQuickReport(final, language);
234
- const w = reportWords(language);
235
- const findingTitle = final.status === 'COMPLETE' ? w.findings : pick(language, 'Model-reported findings (verification limited)', '模型提出的問題(驗證有限)', '模型提出的问题(验证有限)');
236
- const findings = [...final.dispositions.filter(d => d.status === 'CONFIRMED').map(d => d.verifiedFinding), ...(final.newFindings ?? [])];
237
- const decisions = final.dispositions.map(d => `- **${d.id || '—'} — ${d.status}${d.mergedInto ? ' → ' + d.mergedInto : ''}:** ${d.reason || w.none}`).join('\n');
238
- const limitations = (final.reviewWarnings ?? []).map(message => `- ${message}`).join('\n');
239
- const unreviewedIds = new Set(final.dispositions.filter(d => d.status === 'UNREVIEWED').map(d => d.id));
240
- const pending = [...(final.initialObservations?.length ? final.initialObservations : (final.findings ?? []).filter(f => unreviewedIds.has(f.id))).map(f => renderFinding(f, w)), ...(final.unstructuredInitials ?? [])].join('\n\n');
241
- const referenceTitle = pick(language, 'Initial observations (reference only, not final conclusions)', '初審觀察(參考資料,非最終結論)', '初审观察(参考资料,非最终结论)');
242
- const banner = final.status === 'STALE' ? `**STALE: ${w.stale}**\n\n` : final.status !== 'COMPLETE' ? `**${final.status}: ${w.partial}**\n\n` : '';
243
- return `${banner}${final.status === 'COMPLETE' ? renderReviewSummary(findings, language) + '\n\n' : ''}## ${w.overview}\n\n${final.report || w.none}${limitations ? '\n\n' + limitations : ''}${renderCoverage(final, w)}\n\n## ${findingTitle}\n\n${findings.map(f => renderFinding(f, w)).join('\n\n') || w.none}\n\n## ${w.scope}\n\n${renderSnapshot(final)}\n\n## ${w.decisions}\n\n${decisions || w.none}${pending ? '\n\n## ' + referenceTitle + '\n\n' + pending : ''}`;
403
+ const referenceTitle = pick(language, 'Review observations (reference only, not final conclusions)', '審查觀察(參考資料,非最終結論)', '审查观察(参考资料,非最终结论)');
404
+ return `${banner}${final.status === 'COMPLETE' ? renderReviewSummary(reported, language, '', { verification: 'none' }) + '\n\n' : ''}## ${w.overview}\n\n${final.report || w.none}${limitations ? '\n\n' + limitations : ''}${renderCoverage(final, w)}\n\n## ${w.findings}\n\n${reported.map(f => renderFinding(f, w)).join('\n\n') || w.none}${pendingInfo.length && final.status === 'COMPLETE' ? `\n\n## ${w.needsInfo}\n\n${pendingInfo.map(f => renderFinding(f, w)).join('\n\n')}` : ''}\n\n## ${w.scope}\n\n${renderSnapshot(final)}\n\n## ${w.decisions}\n\n${decisions || w.none}${reference ? '\n\n## ' + referenceTitle + '\n\n' + reference : ''}`;
244
405
  }
245
406
 
246
- /** Completed initial responses are retained when verification never finished. */
247
- export function renderIncompleteDraft(stages, failure, language, { quick = false } = {}) {
407
+ /** What the reviewers that answered wrote is kept when the review did not complete. */
408
+ export function renderIncompleteDraft(stages, failure, language) {
248
409
  const initials = stages.filter(s => ROLES[s.role]?.format === 'initial' && s.result);
249
410
  if (!initials.length) return '';
250
- const w = quick ? { ...reportWords(language), warning: pick(language, 'AI-generated, unconfirmed quick review observations. The quick review did not complete. This is not an approved review or input for PR comments.', 'AI 產生的快速審查觀察,審查沒有完成,不能視為已確認結論或用於 PR 留言。', 'AI 产生的快速审查观察,审查没有完成,不能视为已确认结论或用于 PR 留言。') } : reportWords(language);
411
+ const w = reportWords(language);
251
412
  const ledger = stages.map(s => `- ${s.role}${s.label ? ` (${s.label})` : ''}: ${s.status}; session=${s.sessionID}; model=${s.model}`).join('\n');
252
413
  const observations = initials.map(s => `### ${s.role}${s.label ? ` — ${s.label}` : ''}\n\n${s.result.report || w.none}\n\n**${w.gaps}:** ${s.result.coverage?.gaps?.join('; ') || w.none}\n\n${s.result.findings.map(f => renderFinding(f, w)).join('\n\n') || w.none}`).join('\n\n');
253
414
  return `## ${w.draft}\n\n**${w.warning}**\n\n**${w.failure}:** ${failure}\n\n${ledger}\n\n## ${w.candidates}\n\n${observations}`;
@@ -298,6 +459,8 @@ function renderStageReceipt(stage) {
298
459
  ];
299
460
  for (const [label, count] of counters) if (count) fields.push(`${label}=${count}`);
300
461
  if (stage.followUp) fields.push(`follow-up=${stage.followUp.outcome}${stage.followUp.failureClass ? `:${stage.followUp.failureClass}` : ''}`);
462
+ // A correction turn that failed: the answer before it stands, with the items it would have repaired degraded.
463
+ if (stage.repairFailure) fields.push(`repair=failed:${stage.repairFailure.failureClass}`);
301
464
  if (stage.failureClass) fields.push(`failure=${stage.failureClass}`);
302
465
  if (stage.error) fields.push(`error=${stage.error}`);
303
466
  return '- ' + fields.join('; ');
@@ -305,31 +468,26 @@ function renderStageReceipt(stage) {
305
468
 
306
469
  export function renderReceipt(run, report, status, error, settings) {
307
470
  const rows = run.stages.map(renderStageReceipt).join('\n');
308
- // A quick review states coverage and verification next to its status.
309
- const quick = run.mode === 'quick' ? `${run.quickSummary ? `; coverage ${run.quickSummary.coverage?.complete ? 'complete' : 'incomplete'}` : ''}; verification none (quick review)` : '';
310
- let body = `[AZPR ${run.id}] ${status}${quick}\n${error ? `Reason (${run.phase ?? 'workflow'}): ${error}\n` : ''}${rows}${rows ? '\n' : ''}`;
311
- if (run.stages.some(s => s.repairs?.length)) body += '\nRepair notice: some answers did not meet the output contract and the same session was asked to correct them. Remaining problems were downgraded per item (UNREVIEWED, NEEDS_INFO or skipped comments) instead of discarding the review.\n';
471
+ // A review states coverage and verification next to its status: whether every changed file was reviewed,
472
+ // with several passes how many files every pass reviewed, and that nothing verified the findings separately.
473
+ const reviewing = ['review', 'deep', 'quick'].includes(run.mode), summary = run.reviewSummary?.coverage;
474
+ // Of the changed files: how many were reviewed at all, where that is not every one, and with several passes how many every pass reviewed.
475
+ const counted = Number.isInteger(summary?.files);
476
+ const once = counted && summary.reviewedOnce < summary.files ? `, ${summary.reviewedOnce}/${summary.files} file(s) reviewed` : '';
477
+ const every = counted && summary.passes > 1 ? `, ${summary.reviewedByAll}/${summary.files}${once ? '' : ' file(s)'} in every pass` : '';
478
+ const method = reviewing ? `${summary ? `; coverage ${summary.complete ? 'complete' : 'incomplete'}${once}${every}` : ''}; verification none` : '';
479
+ let body = `[AZPR ${run.id}] ${status}${method}\n${error ? `Reason (${run.phase ?? 'workflow'}): ${error}\n` : ''}${rows}${rows ? '\n' : ''}`;
480
+ if (run.stages.some(s => s.repairs?.length)) body += '\nRepair notice: some answers did not meet the output contract and the same session was asked to correct them. Remaining problems were downgraded per item (NEEDS_INFO, a merge or rating left out, or skipped comments) instead of discarding the review.\n';
312
481
  if (run.stages.some(s => s.attempt > 1)) body += '\nRetry notice: a stage failed for a transient reason and ran again in a new session.\n';
313
482
  if (run.stages.some(s => s.followUp)) body += '\nFollow-up notice: a session answered PARTIAL and named unfinished work, so the same session was asked once to continue (follow-up=completed, still-partial, unusable or failed). A follow-up that failed or gave no usable answer kept the answer it followed.\n';
314
- if (run.draft) body += run.mode === 'quick'
315
- ? '\nIncomplete draft notice: the quick review did not complete; its observations are unconfirmed and not input for PR comments.\n'
316
- : '\nIncomplete draft notice: initial observations are unconfirmed because verification did not complete; they are not input for PR comments.\n';
483
+ if (run.draft) body += '\nIncomplete draft notice: the review did not complete; its observations are unconfirmed and not input for PR comments.\n';
317
484
  if (run.sessionsRemoved) body += `\nSession notice: ${run.sessionsRemoved} reviewer session(s) of this run were deleted when it ended; only a session that holds the report or draft is kept (deletePrivateSessions). debug.enabled keeps them all.\n`;
318
485
  body += renderDiagnosticNotices(run, settings);
319
486
  body += run.mode === 'check'
320
487
  ? '\nStatus: READY means AZPR can read the PR through the Azure DevOps REST API; it does not review or approve the PR.\n'
321
488
  : run.mode === 'comment'
322
489
  ? ''
323
- : run.mode === 'quick'
324
- ? '\nStatus: COMPLETE means at least one quick review session produced a usable result and no source-commit change was detected. Quick findings are not independently verified: the runtime checked only their form and source, and findings that failed those checks are NEEDS_INFO. Coverage says whether every changed file was reviewed. STALE means the PR source commit changed during the review. PARTIAL means no session produced a usable result. None of these approves the PR.\n'
325
- : '\nStatus: COMPLETE means verification produced structured decisions and no source-commit change was detected; findings without a usable decision are listed as UNREVIEWED. STALE means the PR source commit changed during the review. PARTIAL keeps unverified results. None of these approves the PR.\n';
326
- if (run.mode === 'quick' && status === 'COMPLETE' && run.quickSummary && (run.quickSummary.high > 0 || !run.quickSummary.coverage?.complete)) {
327
- const hint = [run.quickSummary.high > 0 ? `${run.quickSummary.high} high-severity finding(s)` : '', !run.quickSummary.coverage?.complete ? 'incomplete coverage' : ''].filter(Boolean).join(' and ');
328
- // Automatic publication follows the user's explicit choice; the hint stays advisory.
329
- body += run.afterReview?.mode === 'publish'
330
- ? `\nVerification hint: ${hint}. These findings are not independently verified; the automatic publication posts them with that disclosure (and the summary with the coverage). For an independent check first, set afterReview.quick to preview or use /pr-review.\n`
331
- : `\nVerification hint: ${hint}. Before publishing, consider /pr-review for an independently verified review.\n`;
332
- }
490
+ : '\nStatus: COMPLETE means at least one review session produced a usable result and no source-commit change was detected. A REPORTED finding was checked by its reviewer against the source and by the runtime for form and source only; nothing verified it separately. A finding that failed the runtime\'s checks, or that comes from an answer that was not usable, is NEEDS_INFO. Coverage says whether every changed file was reviewed, and with several passes how many files every pass reviewed. STALE means the PR source commit changed during the review. PARTIAL means no session produced a usable result. None of these approves the PR.\n';
333
491
  if (run.userContext) body += '\nSupplementary context applies to this command only.\n';
334
492
  if (report) {
335
493
  const last = run.reportStage;
@@ -357,7 +515,8 @@ export function searchLimitation(run, settings) {
357
515
  const setting = ![...refused.values()].some(Boolean) || !megabytes ? ''
358
516
  : megabytes < MAX_ARCHIVE_MEGABYTES ? ` azure.archiveMegabytes is ${megabytes}; it accepts up to ${MAX_ARCHIVE_MEGABYTES}.`
359
517
  : ` azure.archiveMegabytes is at its maximum of ${MAX_ARCHIVE_MEGABYTES}.`;
360
- return `Content search (azpr_search_code) was unavailable: ${[...refused.keys()].join('; ')}. Sessions could find and read files but not search file contents, so callers and other uses of the changed code may not have been checked.${setting}`;
518
+ // In a fixed order: which read was refused first must not change the text the planner is given.
519
+ return `Content search (azpr_search_code) was unavailable: ${[...refused.keys()].sort().join('; ')}. Sessions could find and read files but not search file contents, so callers and other uses of the changed code may not have been checked.${setting}`;
361
520
  }
362
521
 
363
522
  export function renderDiagnosticNotices(run, settings) {
package/src/azure.mjs CHANGED
@@ -238,6 +238,18 @@ export function markersInThreads(threads) {
238
238
  return found;
239
239
  }
240
240
 
241
+ /** The AZPR markers each live thread holds in its live comments, by thread: AZPR's comments on the PR, thread by thread. */
242
+ export function threadMarkers(threads) {
243
+ const found = new Map();
244
+ for (const thread of threads) {
245
+ if (thread?.isDeleted === true) continue;
246
+ const markers = (Array.isArray(thread?.comments) ? thread.comments : []).filter(comment => comment?.isDeleted !== true && typeof comment?.content === 'string')
247
+ .flatMap(comment => [...comment.content.matchAll(MARKER_PATTERN)].map(match => match[0]));
248
+ if (markers.length) found.set(thread.id, new Set(markers));
249
+ }
250
+ return found;
251
+ }
252
+
241
253
  /** The text of the live comment that carries each marker, found as markersInThreads finds its thread. */
242
254
  export function markerTexts(threads) {
243
255
  const found = new Map();