@in-the-loop-labs/pair-review 5.0.2 → 5.0.3

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/README.md CHANGED
@@ -373,6 +373,7 @@ consolidated suggestion layer the app shows by default):
373
373
  {
374
374
  "ok": true, // false on failure (see below)
375
375
  "mode": "local", // "pr" or "local"
376
+ "consolidation": "success", // "success", "failed", "skipped", or null (see below)
376
377
  "run": {
377
378
  "id": "…", // analysis run id
378
379
  "review_id": 1,
@@ -418,6 +419,25 @@ consolidated suggestion layer the app shows by default):
418
419
  }
419
420
  ```
420
421
 
422
+ **`consolidation`** reports the outcome of the final cross-level (and, for a
423
+ council, cross-voice) consolidation step:
424
+
425
+ | Value | Meaning |
426
+ | --- | --- |
427
+ | `"success"` | Consolidation ran and merged the inputs. |
428
+ | `"failed"` | It threw. The run still completes and `ok` stays `true`, but `suggestions` is the raw union of every analysis level and every council voice rather than a merged review — expect duplicates and a much larger `count`. |
429
+ | `"skipped"` | There was nothing to merge — a council that resolved to a single voice or a single level, or an executable provider that returns its own final set. The suggestion set is the intended one; this is a healthy outcome, not a degraded one. |
430
+ | `null` | The run recorded no consolidation stage. |
431
+
432
+ Only `"failed"` indicates degraded output, so branch on that value rather than on
433
+ `!= "success"` — a single-voice council legitimately reports `"skipped"`. The
434
+ human-readable (non-`--json`) output prints a warning for `"failed"` only.
435
+
436
+ ```bash
437
+ # Treat a degraded run as a failure
438
+ [ "$(echo "$result" | jq -r '.consolidation')" = "failed" ] && echo "unconsolidated!" >&2
439
+ ```
440
+
421
441
  **On failure** (invalid flags, an unreadable `--instructions-file`, or an
422
442
  analysis error raised while running the headless flow) `--json` emits a JSON
423
443
  document on stdout — a compact failure envelope — and the exit code is non-zero,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@in-the-loop-labs/pair-review",
3
- "version": "5.0.2",
3
+ "version": "5.0.3",
4
4
  "description": "Your AI-powered code review partner - Close the feedback loop with AI coding agents",
5
5
  "main": "src/server.js",
6
6
  "bin": {
@@ -84,6 +84,7 @@
84
84
  "@changesets/cli": "^2.29.8",
85
85
  "@playwright/test": "^1.57.0",
86
86
  "@vitest/coverage-v8": "^4.0.16",
87
+ "dompurify": "^3.2.6",
87
88
  "esbuild": "^0.27.4",
88
89
  "highlight.js": "^11.11.1",
89
90
  "jsdom": "^29.0.1",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pair-review",
3
- "version": "5.0.2",
3
+ "version": "5.0.3",
4
4
  "description": "pair-review app integration — Open PRs and local changes in the pair-review web UI, run server-side AI analysis, and address review feedback. Requires the pair-review MCP server.",
5
5
  "author": {
6
6
  "name": "in-the-loop-labs",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code-critic",
3
- "version": "5.0.2",
3
+ "version": "5.0.3",
4
4
  "description": "AI-powered code review analysis — Run three-level AI analysis directly in your coding agent. Works standalone, no server required.",
5
5
  "author": {
6
6
  "name": "in-the-loop-labs",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pair-loop",
3
- "version": "5.0.2",
3
+ "version": "5.0.3",
4
4
  "description": "Agent-orchestrated review loop — implement, review with pair-review multi-model councils via the headless CLI, triage, fix, and repeat until a final review returns no blockers. MCP-independent.",
5
5
  "author": {
6
6
  "name": "in-the-loop-labs",
@@ -1,7 +1,12 @@
1
1
  // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
2
  /**
3
- * Safe markdown renderer for comments
4
- * Uses markdown-it with security settings to prevent XSS
3
+ * Safe markdown renderer for comments.
4
+ *
5
+ * Uses markdown-it to render markdown and DOMPurify to sanitize the result.
6
+ * Enabling raw HTML (`html: true`) lets us render the GitHub-supported inline
7
+ * HTML subset (e.g. <sub>, <sup>, <kbd>) and lets DOMPurify strip HTML comments
8
+ * (e.g. tracking markers) from the rendered view. DOMPurify is what keeps this
9
+ * safe from XSS — it must be present before we enable raw HTML.
5
10
  */
6
11
 
7
12
  /**
@@ -21,82 +26,214 @@ function escapeHtmlAttribute(text) {
21
26
  .replace(/'/g, '&#39;');
22
27
  }
23
28
 
24
- // Browser-only code: markdown rendering requires markdown-it library
25
- if (typeof window !== 'undefined' && window.markdownit) {
26
- (function() {
27
- // Initialize markdown-it with safe defaults
28
- const md = window.markdownit({
29
- html: false, // Disable HTML tags to prevent XSS
30
- xhtmlOut: false, // Don't use self-closing tags
31
- breaks: true, // Convert \n to <br>
32
- langPrefix: 'language-', // CSS class prefix for code blocks
33
- linkify: true, // Auto-convert URLs to links
34
- typographer: true // Enable smartquotes and other typographic replacements
35
- });
36
-
37
- // Enable emoji shortcode support (e.g., :smile: -> 😄)
38
- if (window.markdownitEmoji) {
39
- md.use(window.markdownitEmoji);
40
- }
29
+ /**
30
+ * GitHub-like allowlist for inline HTML permitted in comment bodies.
31
+ * Standard markdown output tags plus the safe inline subset GitHub renders.
32
+ */
33
+ const ALLOWED_TAGS = [
34
+ // Standard markdown output
35
+ 'p', 'a', 'code', 'pre', 'blockquote',
36
+ 'ul', 'ol', 'li',
37
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
38
+ 'em', 'strong', 's', 'hr', 'br', 'span',
39
+ 'table', 'thead', 'tbody', 'tr', 'th', 'td',
40
+ 'img',
41
+ // GitHub-supported inline HTML subset
42
+ 'sub', 'sup', 'kbd', 'ins', 'del', 'mark',
43
+ 'details', 'summary', 'abbr'
44
+ ];
45
+
46
+ const ALLOWED_ATTR = [
47
+ 'href', 'title', 'target', 'rel',
48
+ 'src', 'alt', 'align', 'class',
49
+ 'start', 'colspan', 'rowspan'
50
+ ];
51
+
52
+ /**
53
+ * Configure a markdown-it instance with the project's rendering options.
54
+ * Raw HTML is enabled here; sanitization happens separately via DOMPurify.
55
+ * @param {function} markdownit - the markdown-it factory (window.markdownit)
56
+ * @param {object} [opts]
57
+ * @param {boolean} [opts.html=true] - allow raw HTML tokens
58
+ * @param {object} [opts.emoji] - markdown-it-emoji plugin (optional)
59
+ * @returns {object} configured markdown-it instance
60
+ */
61
+ function configureMarkdownIt(markdownit, opts = {}) {
62
+ const html = opts.html !== undefined ? opts.html : true;
63
+
64
+ const md = markdownit({
65
+ html, // Allow raw HTML; DOMPurify sanitizes the output
66
+ xhtmlOut: false, // Don't use self-closing tags
67
+ breaks: true, // Convert \n to <br>
68
+ langPrefix: 'language-', // CSS class prefix for code blocks
69
+ linkify: true, // Auto-convert URLs to links
70
+ typographer: true // Enable smartquotes and other typographic replacements
71
+ });
72
+
73
+ // Enable emoji shortcode support (e.g., :smile: -> 😄)
74
+ if (opts.emoji) {
75
+ md.use(opts.emoji);
76
+ }
77
+
78
+ // Configure link rendering to open in new tab and add security.
79
+ // (DOMPurify's afterSanitizeAttributes hook re-applies these as a backstop.)
80
+ const defaultLinkRender = md.renderer.rules.link_open || function(tokens, idx, options, env, self) {
81
+ return self.renderToken(tokens, idx, options);
82
+ };
83
+
84
+ md.renderer.rules.link_open = function(tokens, idx, options, env, self) {
85
+ const token = tokens[idx];
86
+ token.attrPush(['target', '_blank']);
87
+ token.attrPush(['rel', 'noopener noreferrer']);
88
+ return defaultLinkRender(tokens, idx, options, env, self);
89
+ };
90
+
91
+ return md;
92
+ }
93
+
94
+ /**
95
+ * Sanitize rendered HTML with DOMPurify using the project allowlist.
96
+ * Removes HTML comments (default) and dangerous tags/attributes, converts
97
+ * markdown-it's table-alignment inline style into the allowlisted `align`
98
+ * attribute (so arbitrary inline styles never need to be permitted), forces
99
+ * safe link attributes on anchors, and scopes `class` to markdown code
100
+ * language hints only.
101
+ * @param {object} purify - a configured DOMPurify instance
102
+ * @param {string} html - HTML to sanitize
103
+ * @returns {string} sanitized HTML
104
+ */
105
+ function sanitizeHtml(purify, html) {
106
+ // Hooks are registered idempotently (removed then re-added) so repeated
107
+ // sanitize() calls on the same instance don't stack duplicates.
41
108
 
42
- // Configure link rendering to open in new tab and add security
43
- const defaultLinkRender = md.renderer.rules.link_open || function(tokens, idx, options, env, self) {
44
- return self.renderToken(tokens, idx, options);
45
- };
46
-
47
- md.renderer.rules.link_open = function(tokens, idx, options, env, self) {
48
- const token = tokens[idx];
49
- token.attrPush(['target', '_blank']);
50
- token.attrPush(['rel', 'noopener noreferrer']);
51
- return defaultLinkRender(tokens, idx, options, env, self);
52
- };
53
-
54
- /**
55
- * Escape HTML characters (fallback for when markdown rendering fails)
56
- * NOTE: This only escapes <, >, and &. It does NOT escape quotes.
57
- * Use escapeHtmlAttribute() when placing content in HTML attributes.
58
- * @param {string} text - Text to escape
59
- * @returns {string} Escaped text
60
- */
61
- function escapeHtml(text) {
62
- if (!text) return '';
63
- const div = document.createElement('div');
64
- div.textContent = text;
65
- return div.innerHTML;
109
+ // markdown-it encodes table column alignment as an inline `text-align` style.
110
+ // Convert it to the allowlisted `align` attribute BEFORE sanitization so we
111
+ // never have to permit arbitrary inline styles (which could hide or cover
112
+ // review UI via position/z-index/display). The `style` attribute itself is
113
+ // then dropped by the allowlist.
114
+ purify.removeHook('beforeSanitizeAttributes');
115
+ purify.addHook('beforeSanitizeAttributes', function (node) {
116
+ const tag = node.tagName;
117
+ if (tag === 'TH' || tag === 'TD') {
118
+ const align = node.style && node.style.textAlign;
119
+ if (align === 'left' || align === 'center' || align === 'right') {
120
+ node.setAttribute('align', align);
121
+ }
66
122
  }
123
+ });
67
124
 
68
- /**
69
- * Render markdown to safe HTML
70
- * @param {string} text - Markdown text to render
71
- * @returns {string} Safe HTML output
72
- */
73
- function renderMarkdown(text) {
74
- if (!text) return '';
75
-
76
- try {
77
- // Render markdown to HTML
78
- return md.render(text);
79
- } catch (error) {
80
- console.error('Markdown rendering error:', error);
81
- // Fall back to escaped text if rendering fails
82
- return escapeHtml(text);
125
+ purify.removeHook('afterSanitizeAttributes');
126
+ purify.addHook('afterSanitizeAttributes', function (node) {
127
+ const tag = node.tagName;
128
+ // Force safe rel/target on links regardless of DOMPurify version defaults.
129
+ if (tag === 'A' && node.getAttribute('href')) {
130
+ node.setAttribute('target', '_blank');
131
+ node.setAttribute('rel', 'noopener noreferrer');
132
+ }
133
+ // Scope `class` to expected markdown output: only `language-*` on code/pre.
134
+ // Stops rendered repo content from reusing layout-sensitive app classes.
135
+ if (node.hasAttribute('class')) {
136
+ const kept =
137
+ tag === 'CODE' || tag === 'PRE'
138
+ ? node.getAttribute('class').split(/\s+/).filter((c) => /^language-[\w-]+$/.test(c))
139
+ : [];
140
+ if (kept.length) {
141
+ node.setAttribute('class', kept.join(' '));
142
+ } else {
143
+ node.removeAttribute('class');
83
144
  }
84
145
  }
146
+ });
147
+
148
+ return purify.sanitize(html, {
149
+ ALLOWED_TAGS,
150
+ ALLOWED_ATTR,
151
+ ALLOW_DATA_ATTR: false,
152
+ });
153
+ }
154
+
155
+ /**
156
+ * Create the renderMarkdown function.
157
+ * When a DOMPurify instance is provided, the markdown-it output is sanitized
158
+ * (safe to enable raw HTML). Without it, callers should pass an md configured
159
+ * with `html: false` so no unsanitized HTML is ever emitted.
160
+ * @param {object} config
161
+ * @param {object} config.md - configured markdown-it instance
162
+ * @param {object} [config.purify] - DOMPurify instance (optional)
163
+ * @param {function} [config.escape] - fallback escaper for render errors
164
+ * @returns {function(string): string} renderMarkdown
165
+ */
166
+ function createRenderMarkdown(config) {
167
+ const { md, purify, escape } = config;
168
+ const fallbackEscape = escape || ((text) => escapeHtmlAttribute(text));
169
+
170
+ return function renderMarkdown(text) {
171
+ if (!text) return '';
172
+
173
+ try {
174
+ const rendered = md.render(text);
175
+ return purify ? sanitizeHtml(purify, rendered) : rendered;
176
+ } catch (error) {
177
+ // eslint-disable-next-line no-console
178
+ console.error('Markdown rendering error:', error);
179
+ // Fall back to escaped text if rendering fails
180
+ return fallbackEscape(text);
181
+ }
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Wire the markdown renderer onto a window/global object.
187
+ * Raw HTML is only enabled when a DOMPurify instance is present to sanitize it;
188
+ * otherwise we fall back to html:false so unsanitized HTML is never emitted.
189
+ * Defines `win.renderMarkdown` and `win.markdownRenderer`. No-op without
190
+ * `win.markdownit`.
191
+ * @param {object} win - a window-like object (expects markdownit, optionally
192
+ * DOMPurify, markdownitEmoji, and document)
193
+ */
194
+ function initMarkdownGlobals(win) {
195
+ if (!win || !win.markdownit) return;
196
+
197
+ /**
198
+ * Escape HTML characters (fallback for when markdown rendering fails).
199
+ * NOTE: This only escapes <, >, and &. It does NOT escape quotes.
200
+ * Use escapeHtmlAttribute() when placing content in HTML attributes.
201
+ */
202
+ function escapeHtml(text) {
203
+ if (!text) return '';
204
+ const div = win.document.createElement('div');
205
+ div.textContent = text;
206
+ return div.innerHTML;
207
+ }
85
208
 
86
- // Export functions to global scope
87
- window.renderMarkdown = renderMarkdown;
209
+ // Only enable raw HTML when DOMPurify is available to sanitize it.
210
+ const purify = win.DOMPurify || null;
211
+ const md = configureMarkdownIt(win.markdownit, {
212
+ html: !!purify,
213
+ emoji: win.markdownitEmoji || undefined
214
+ });
88
215
 
89
- // Also export markdown instance for advanced usage if needed
90
- window.markdownRenderer = md;
91
- })();
216
+ win.renderMarkdown = createRenderMarkdown({ md, purify, escape: escapeHtml });
217
+ // Also expose the markdown instance for advanced usage if needed.
218
+ win.markdownRenderer = md;
92
219
  }
93
220
 
94
- // Export escapeHtmlAttribute to window (browser) regardless of markdown-it availability
221
+ // Browser-only code: markdown rendering requires the markdown-it library.
95
222
  if (typeof window !== 'undefined') {
223
+ initMarkdownGlobals(window);
224
+ // Export escapeHtmlAttribute regardless of markdown-it availability.
96
225
  window.escapeHtmlAttribute = escapeHtmlAttribute;
97
226
  }
98
227
 
99
228
  // Export for Node.js testing
100
229
  if (typeof module !== 'undefined' && module.exports) {
101
- module.exports = { escapeHtmlAttribute };
230
+ module.exports = {
231
+ escapeHtmlAttribute,
232
+ configureMarkdownIt,
233
+ sanitizeHtml,
234
+ createRenderMarkdown,
235
+ initMarkdownGlobals,
236
+ ALLOWED_TAGS,
237
+ ALLOWED_ATTR
238
+ };
102
239
  }
package/public/local.html CHANGED
@@ -566,6 +566,8 @@
566
566
  <!-- Markdown-it Library for rendering markdown in comments -->
567
567
  <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.2/dist/markdown-it.min.js"></script>
568
568
  <script src="https://cdn.jsdelivr.net/npm/markdown-it-emoji@2.0.2/dist/markdown-it-emoji.min.js"></script>
569
+ <!-- DOMPurify sanitizes rendered markdown HTML (must load before markdown.js) -->
570
+ <script src="https://cdn.jsdelivr.net/npm/dompurify@3.2.6/dist/purify.min.js"></script>
569
571
 
570
572
  <!-- Markdown renderer utility -->
571
573
  <script src="/js/utils/markdown.js"></script>
package/public/pr.html CHANGED
@@ -371,6 +371,8 @@
371
371
  <!-- Markdown-it Library for rendering markdown in comments -->
372
372
  <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.2/dist/markdown-it.min.js"></script>
373
373
  <script src="https://cdn.jsdelivr.net/npm/markdown-it-emoji@2.0.2/dist/markdown-it-emoji.min.js"></script>
374
+ <!-- DOMPurify sanitizes rendered markdown HTML (must load before markdown.js) -->
375
+ <script src="https://cdn.jsdelivr.net/npm/dompurify@3.2.6/dist/purify.min.js"></script>
374
376
 
375
377
  <!-- Markdown renderer utility -->
376
378
  <script src="/js/utils/markdown.js"></script>
@@ -131,7 +131,7 @@ async function runExecutableVoice(voiceProvider, reviewId, worktreePath, prMetad
131
131
  try {
132
132
  const executableContext = {
133
133
  title: prMetadata.title || null,
134
- description: prMetadata.description || null,
134
+ description: resolveReviewDescription(prMetadata) || null,
135
135
  cwd: worktreePath,
136
136
  outputDir: tmpDir,
137
137
  model: voiceProvider.resolvedModel !== undefined ? voiceProvider.resolvedModel : (voiceProvider.model || null),
@@ -201,18 +201,64 @@ async function runExecutableVoice(voiceProvider, reviewId, worktreePath, prMetad
201
201
  }
202
202
  }
203
203
 
204
+ /**
205
+ * Resolve the `owner/repo` identifier from review metadata.
206
+ *
207
+ * Review metadata reaches the analyzer in more than one shape:
208
+ * - the normalized `pr_metadata` row (server routes, headless PR path), where
209
+ * `repository` is the `"owner/repo"` string;
210
+ * - the raw stored `pr_data` blob, where `repository` is the GitHub API object
211
+ * `{ full_name, clone_url, ssh_url, default_branch }`;
212
+ * - local reviews, where `repository` is a bare directory name (no slash).
213
+ *
214
+ * Accept all three instead of assuming a string. Callers used to do
215
+ * `prMetadata.repository?.split('/')`, which threw `TypeError` on the object
216
+ * shape — and because every consolidation stage builds its dedup context first,
217
+ * that single throw silently disabled consolidation for the whole run (#557).
218
+ *
219
+ * @param {Object} prMetadata - PR/review metadata
220
+ * @returns {string|null} The repository identifier, or null when unavailable
221
+ */
222
+ function resolveRepositorySlug(prMetadata) {
223
+ const repository = prMetadata?.repository;
224
+ if (typeof repository === 'string') return repository || null;
225
+ if (repository && typeof repository.full_name === 'string') return repository.full_name || null;
226
+ return null;
227
+ }
228
+
229
+ /**
230
+ * Resolve the review description from review metadata.
231
+ *
232
+ * The normalized `pr_metadata` row and local metadata both use `description`;
233
+ * the raw `pr_data` blob carries the same text under the GitHub API's `body`.
234
+ * Accepting both keeps the PR description in the prompt regardless of which
235
+ * shape a caller passes — the same shape divergence behind #557.
236
+ *
237
+ * @param {Object} prMetadata - PR/review metadata
238
+ * @returns {string|null|undefined} The description, or null/undefined when unset
239
+ */
240
+ function resolveReviewDescription(prMetadata) {
241
+ return prMetadata?.description ?? prMetadata?.body;
242
+ }
243
+
204
244
  /**
205
245
  * Build the dedup context object from PR metadata and run identifiers.
206
246
  *
207
- * @param {Object} prMetadata - PR metadata with repository and pr_number
247
+ * Tolerates both metadata shapes described on {@link resolveRepositorySlug}: the
248
+ * pull request number is read from `pr_number` (normalized row) and falls back
249
+ * to `number` (raw `pr_data` blob). Local reviews carry neither and yield
250
+ * `undefined`, which the dedup consumers already treat as "not a PR".
251
+ *
252
+ * @param {Object} prMetadata - PR metadata with repository and pr_number/number
208
253
  * @param {Object} ids - { reviewId, serverPort, runId, excludeRunIds }
209
254
  * @param {string} [ids.runId] - Single run ID to exclude (backward compat)
210
255
  * @param {string[]} [ids.excludeRunIds] - Array of run IDs to exclude (takes precedence over runId)
211
256
  * @returns {Object} { owner, repo, pullNumber, reviewId, serverPort, runId, excludeRunIds }
212
257
  */
213
258
  function buildDedupContext(prMetadata, { reviewId, serverPort, runId, excludeRunIds }) {
214
- const [owner, repo] = prMetadata.repository?.split('/') || [];
215
- return { owner, repo, pullNumber: prMetadata.pr_number, reviewId, serverPort, runId, excludeRunIds };
259
+ const [owner, repo] = resolveRepositorySlug(prMetadata)?.split('/') || [];
260
+ const pullNumber = prMetadata?.pr_number ?? prMetadata?.number;
261
+ return { owner, repo, pullNumber, reviewId, serverPort, runId, excludeRunIds };
216
262
  }
217
263
 
218
264
  /**
@@ -1219,20 +1265,25 @@ Or simply ignore any changes to files matching these patterns in your analysis.
1219
1265
  * @returns {string} Context section or empty string
1220
1266
  */
1221
1267
  buildPRContextSection(prMetadata, criticalNote) {
1268
+ const description = resolveReviewDescription(prMetadata);
1222
1269
  // Check for null/undefined explicitly to include section even if fields are empty strings
1223
- if (prMetadata.title != null || prMetadata.description != null) {
1270
+ if (prMetadata.title != null || description != null) {
1224
1271
  const isLocal = prMetadata.reviewType === 'local';
1225
1272
  const sectionTitle = isLocal ? 'Review Context' : 'Pull Request Context';
1226
1273
  const descriptionLabel = isLocal ? 'Description:' : "Author's Description:";
1227
1274
 
1228
- // Build metadata lines (repository for both modes, PR-specific fields only for PR mode)
1275
+ // Build metadata lines (repository for both modes, PR-specific fields only for PR mode).
1276
+ // Both fields go through the shape-tolerant resolvers so a raw `pr_data`
1277
+ // blob renders "owner/repo" rather than "[object Object]" (#557).
1229
1278
  const lines = [];
1230
- if (prMetadata.repository) {
1231
- lines.push(`**Repository:** ${prMetadata.repository}`);
1279
+ const repositorySlug = resolveRepositorySlug(prMetadata);
1280
+ if (repositorySlug) {
1281
+ lines.push(`**Repository:** ${repositorySlug}`);
1232
1282
  }
1233
1283
  if (!isLocal) {
1234
- if (prMetadata.pr_number) {
1235
- lines.push(`**PR #:** ${prMetadata.pr_number}`);
1284
+ const pullNumber = prMetadata.pr_number ?? prMetadata.number;
1285
+ if (pullNumber) {
1286
+ lines.push(`**PR #:** ${pullNumber}`);
1236
1287
  }
1237
1288
  if (prMetadata.author) {
1238
1289
  lines.push(`**Author:** @${prMetadata.author}`);
@@ -1245,7 +1296,7 @@ Or simply ignore any changes to files matching these patterns in your analysis.
1245
1296
  ${metadataLines}**Title:** ${prMetadata.title || '(No title provided)'}
1246
1297
 
1247
1298
  **${descriptionLabel}**
1248
- ${prMetadata.description || '(No description provided)'}
1299
+ ${description || '(No description provided)'}
1249
1300
 
1250
1301
  ⚠️ **Critical Note:** ${criticalNote}
1251
1302
 
@@ -4158,5 +4209,7 @@ File-level suggestions should NOT have a line number. They apply to the entire f
4158
4209
 
4159
4210
  module.exports = Analyzer;
4160
4211
  module.exports.buildDedupContext = buildDedupContext;
4212
+ module.exports.resolveRepositorySlug = resolveRepositorySlug;
4213
+ module.exports.resolveReviewDescription = resolveReviewDescription;
4161
4214
  module.exports.buildDedupInstructions = buildDedupInstructions;
4162
4215
  module.exports.fetchExistingReviewComments = fetchExistingReviewComments;
package/src/main.js CHANGED
@@ -2,7 +2,7 @@
2
2
  const fs = require('fs');
3
3
  const { v4: uuidv4 } = require('uuid');
4
4
  const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, resolveLoadSkills, buildCouncilProviderOverrides } = require('./config');
5
- const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, WorktreeRepository, ReviewRepository, RepoSettingsRepository, GitHubReviewRepository, WorktreePoolRepository, CouncilRepository, CommentRepository, AnalysisRunRepository } = require('./database');
5
+ const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, WorktreeRepository, ReviewRepository, RepoSettingsRepository, GitHubReviewRepository, WorktreePoolRepository, CouncilRepository, CommentRepository, AnalysisRunRepository, PRMetadataRepository } = require('./database');
6
6
  const { PRArgumentParser } = require('./github/parser');
7
7
  const { GitHubClient } = require('./github/client');
8
8
  const { GitWorktreeManager } = require('./git/worktree');
@@ -1541,17 +1541,25 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1541
1541
  }).catch(err => { logger.warn(`Review hook failed: ${err.message}`); });
1542
1542
  }
1543
1543
 
1544
- // Get PR metadata ID for AI analysis
1545
- const prMetadata = await queryOne(db, `
1546
- SELECT id, pr_data FROM pr_metadata
1547
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1548
- `, [prInfo.number, repository]);
1544
+ // Get PR metadata for AI analysis.
1545
+ //
1546
+ // Read it through PRMetadataRepository.getByPR — the SAME accessor the web
1547
+ // routes use (src/routes/pr.js) — so the analyzer receives the normalized
1548
+ // row shape it expects: `repository` as the "owner/repo" string, `pr_number`
1549
+ // as the number, plus `description`/`author` from their columns. Passing the
1550
+ // raw `pr_data` blob here (the previous behavior) handed the analyzer the
1551
+ // GitHub API shape, where `repository` is an object and the number lives
1552
+ // under `number`, which made buildDedupContext throw and silently drop every
1553
+ // consolidation stage into its store-everything fallback (#557).
1554
+ const prMetadataRepo = new PRMetadataRepository(db);
1555
+ const prMetadata = await prMetadataRepo.getByPR(prInfo.number, repository);
1549
1556
 
1550
1557
  if (!prMetadata) {
1551
1558
  throw new Error('Failed to retrieve stored PR metadata');
1552
1559
  }
1553
1560
 
1554
- const storedPRData = JSON.parse(prMetadata.pr_data);
1561
+ // The raw blob is still needed for fields that live only in pr_data (node_id).
1562
+ const storedPRData = prMetadata.pr_data_parsed;
1555
1563
 
1556
1564
  // Get or create a review record for this PR
1557
1565
  // The review.id is passed to the analyzer so comments use review.id, not prMetadata.id
@@ -1600,7 +1608,7 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1600
1608
  const { result: analysisResult } = await runHeadlessAnalysis(db, config, {
1601
1609
  reviewId: review.id,
1602
1610
  worktreePath,
1603
- prMetadata: storedPRData,
1611
+ prMetadata,
1604
1612
  changedFiles: null,
1605
1613
  repository,
1606
1614
  repoSettings,
@@ -1868,7 +1876,11 @@ Found ${validSuggestions.length} suggestion${validSuggestions.length === 1 ? ''
1868
1876
  * @param {Object} params
1869
1877
  * @param {number} params.reviewId - Review id comments are stored under
1870
1878
  * @param {string} params.worktreePath - Checked-out worktree / local repo path
1871
- * @param {Object} params.prMetadata - PR/local metadata (head_sha, base_sha, etc.)
1879
+ * @param {Object} params.prMetadata - PR/local metadata (head_sha, base_sha, etc.).
1880
+ * PR mode MUST pass the normalized `pr_metadata` row (`repository` as the
1881
+ * "owner/repo" string, `pr_number` as the number) — the raw `pr_data` blob has
1882
+ * `repository` as an object and the number under `number`, which breaks dedup
1883
+ * context construction and, with it, consolidation (#557).
1872
1884
  * @param {Array|null} params.changedFiles - Changed-file list (local mode) or null (PR mode computes it)
1873
1885
  * @param {string} params.repository - owner/repo
1874
1886
  * @param {Object|null} params.repoSettings - Repo settings row
@@ -1953,9 +1965,11 @@ async function runHeadlessAnalysis(db, config, {
1953
1965
  * convention) so the in-memory usage tracker populated by
1954
1966
  * `resetAndRehydrate()` is the one acquisitions go through. Falls back to a
1955
1967
  * fresh instance only when not supplied.
1956
- * @returns {Promise<Object>} { githubClient, worktreePath, storedPRData, review,
1968
+ * @returns {Promise<Object>} { githubClient, worktreePath, prMetadata, review,
1957
1969
  * repository, repoSettings, poolWorktreeId, poolLifecycle, reviewConfig,
1958
- * providerOverrides }
1970
+ * providerOverrides }. `prMetadata` is the normalized `pr_metadata` row from
1971
+ * `PRMetadataRepository.getByPR` — the shape the analyzer expects — NOT the
1972
+ * raw `pr_data` blob (#557).
1959
1973
  */
1960
1974
  async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycle = null) {
1961
1975
  const parser = new PRArgumentParser(config);
@@ -2160,17 +2174,16 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2160
2174
  }).catch(err => { logger.warn(`Review hook failed: ${err.message}`); });
2161
2175
  }
2162
2176
 
2163
- const prMetadata = await queryOne(db, `
2164
- SELECT id, pr_data FROM pr_metadata
2165
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
2166
- `, [prInfo.number, repository]);
2177
+ // Read through PRMetadataRepository.getByPR so the analyzer gets the same
2178
+ // normalized row the web routes pass (see the matching comment in
2179
+ // performHeadlessReview and issue #557).
2180
+ const prMetadataRepo = new PRMetadataRepository(db);
2181
+ const prMetadata = await prMetadataRepo.getByPR(prInfo.number, repository);
2167
2182
 
2168
2183
  if (!prMetadata) {
2169
2184
  throw new Error('Failed to retrieve stored PR metadata');
2170
2185
  }
2171
2186
 
2172
- const storedPRData = JSON.parse(prMetadata.pr_data);
2173
-
2174
2187
  const reviewRepo = new ReviewRepository(db);
2175
2188
  const { review } = await reviewRepo.getOrCreate({ prNumber: prInfo.number, repository });
2176
2189
 
@@ -2199,7 +2212,7 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2199
2212
  return {
2200
2213
  githubClient,
2201
2214
  worktreePath,
2202
- storedPRData,
2215
+ prMetadata,
2203
2216
  review,
2204
2217
  repository,
2205
2218
  repoSettings,
@@ -2467,7 +2480,7 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2467
2480
  ({ runId } = await runHeadlessAnalysis(db, config, {
2468
2481
  reviewId: prep.review.id,
2469
2482
  worktreePath: prep.worktreePath,
2470
- prMetadata: prep.storedPRData,
2483
+ prMetadata: prep.prMetadata,
2471
2484
  changedFiles: null,
2472
2485
  repository: prep.repository,
2473
2486
  repoSettings: prep.repoSettings,
@@ -2503,7 +2516,9 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2503
2516
  * @param {Object} db - Database instance
2504
2517
  * @param {string} runId - Analysis run id
2505
2518
  * @param {'pr'|'local'} mode - Review mode (passthrough)
2506
- * @returns {Promise<Object>} { ok, mode, run, suggestions, count }
2519
+ * @returns {Promise<Object>} { ok, mode, consolidation, run, suggestions, count }
2520
+ * where `consolidation` is 'success' | 'failed' | 'skipped' | null — see the
2521
+ * inline comment on the field for what each value means for `suggestions`.
2507
2522
  */
2508
2523
  async function buildHeadlessJson(db, runId, mode) {
2509
2524
  const run = await new AnalysisRunRepository(db).getById(runId, { includeDiff: false });
@@ -2523,6 +2538,26 @@ async function buildHeadlessJson(db, runId, mode) {
2523
2538
  // see buildHeadlessErrorJson for the failure shape.
2524
2539
  ok: true,
2525
2540
  mode,
2541
+ // Hoisted out of `run.level_outcomes` because it materially changes what
2542
+ // `suggestions` contains. When consolidation throws, every analyzer path
2543
+ // falls back to storing the raw union of all levels (and, for a council, all
2544
+ // voices) and STILL records status 'completed' — so a consumer branching only
2545
+ // on `ok`/`status` cannot tell a consolidated review from a duplicate-laden
2546
+ // concatenation.
2547
+ //
2548
+ // A straight passthrough of whatever the analyzer recorded, so the domain is
2549
+ // the analyzer's, not ours:
2550
+ // 'success' — consolidation ran and merged the inputs.
2551
+ // 'failed' — it threw; `suggestions` is the unmerged union. DEGRADED.
2552
+ // 'skipped' — nothing to merge (single voice / single level / an executable
2553
+ // tool that returns its own final set). HEALTHY: the suggestion
2554
+ // set is already the intended one, which is why
2555
+ // emitHeadlessResult warns on 'failed' only.
2556
+ // null — the run recorded no consolidation stage at all.
2557
+ // Deliberately NOT collapsed to a boolean or folded into null: the web UI
2558
+ // renders the same tri-state (public/js/modules/analysis-history.js), and
2559
+ // 'skipped' carries information null does not.
2560
+ consolidation: run?.level_outcomes?.consolidation ?? null,
2526
2561
  run,
2527
2562
  suggestions,
2528
2563
  count: suggestions.length
@@ -2560,6 +2595,11 @@ function buildHeadlessErrorJson({ mode, error }) {
2560
2595
  * Otherwise prints a human-readable summary to stdout. A successful run with zero
2561
2596
  * suggestions is still success — operational errors propagate to main()'s catch.
2562
2597
  *
2598
+ * Both output modes flag a failed consolidation, which completes the run but
2599
+ * replaces the consolidated review with the raw union of every level/voice.
2600
+ *
2601
+ * Exported for unit testing.
2602
+ *
2563
2603
  * @param {Object} db - Database instance
2564
2604
  * @param {Object} params
2565
2605
  * @param {string} params.runId - Analysis run id
@@ -2588,6 +2628,13 @@ async function emitHeadlessResult(db, { runId, mode, flags }) {
2588
2628
  }
2589
2629
  lines.push(` Config type: ${run.config_type || 'standard'}`);
2590
2630
  lines.push(` Status: ${run.status || '(unknown)'}`);
2631
+ // A failed consolidation still completes the run, so the status line alone
2632
+ // understates it — call out that the listing below is unconsolidated.
2633
+ if (doc.consolidation === 'failed') {
2634
+ lines.push('');
2635
+ lines.push(' WARNING: consolidation failed. The suggestions below are the raw union of');
2636
+ lines.push(' every analysis level (and every council voice) — expect duplicates.');
2637
+ }
2591
2638
  if (run.summary) {
2592
2639
  lines.push('');
2593
2640
  lines.push('Summary:');
@@ -2789,4 +2836,4 @@ if (require.main === module) {
2789
2836
  main();
2790
2837
  }
2791
2838
 
2792
- module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, resolveCliInstructions };
2839
+ module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, resolveCliInstructions };