@in-the-loop-labs/pair-review 5.3.7 → 5.4.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.
Files changed (39) hide show
  1. package/README.md +8 -0
  2. package/package.json +3 -3
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/css/pr.css +389 -13
  7. package/public/js/components/AIPanel.js +317 -99
  8. package/public/js/components/ReviewHistoryModal.js +294 -0
  9. package/public/js/components/ReviewModal.js +96 -7
  10. package/public/js/components/SplitButton.js +14 -0
  11. package/public/js/local.js +4 -8
  12. package/public/js/modules/comment-manager.js +2 -1
  13. package/public/js/modules/file-comment-manager.js +6 -2
  14. package/public/js/modules/pierre-bridge.js +35 -1
  15. package/public/js/modules/suggestion-manager.js +4 -1
  16. package/public/js/pr.js +174 -66
  17. package/public/js/utils/posted-comment.js +259 -14
  18. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  19. package/public/js/vendor/pierre-diffs.js +131 -1364
  20. package/public/pr.html +1 -0
  21. package/src/chat/api-reference.js +22 -2
  22. package/src/config.js +28 -4
  23. package/src/database.js +177 -56
  24. package/src/github/client.js +70 -15
  25. package/src/github/impl/graphql/pending-review-comments.js +50 -11
  26. package/src/github/impl/graphql/pending-review.js +8 -2
  27. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  28. package/src/github/impl/host/pending-review-comments.js +41 -10
  29. package/src/github/impl/host/review-comment-edit.js +36 -0
  30. package/src/github/impl/rest/pending-review.js +6 -2
  31. package/src/github/impl/rest/review-comment-edit.js +44 -0
  32. package/src/github/impl/review-comment-edit-utils.js +45 -0
  33. package/src/github/operations/pending-review.js +4 -3
  34. package/src/github/operations/review-comment-edit.js +35 -0
  35. package/src/github/record-submission.js +78 -0
  36. package/src/github/update-posted-comment.js +115 -0
  37. package/src/main.js +24 -44
  38. package/src/routes/mcp.js +1 -0
  39. package/src/routes/pr.js +147 -106
@@ -0,0 +1,36 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { requireFields, normalizeComment, updateResult } = require('../review-comment-edit-utils');
3
+ const { commentId, reviewId } = require('../rest/review-comment-edit');
4
+
5
+ const UPDATE_ENDPOINT = '/repos/{owner}/{repo}/pulls/comments/{comment_id}';
6
+ const LIST_ENDPOINT = '/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments';
7
+
8
+ function endpoint(template, values) {
9
+ // Defense in depth: never allow endpoint configuration to send credentials
10
+ // outside the bound host, even when constructed without config validation.
11
+ if (typeof template !== 'string' || !template.startsWith('/') || template.startsWith('//') || /[\\\r\n]/.test(template)) {
12
+ throw new Error('review_comment_edit endpoint must be a relative path');
13
+ }
14
+ return template.replace(/\{(owner|repo|pull_number|comment_id|review_id)\}/g, (_match, key) => {
15
+ requireFields(values, [key]);
16
+ return encodeURIComponent(String(values[key]));
17
+ });
18
+ }
19
+
20
+ async function updateReviewComment(octokit, features, ref, body) {
21
+ requireFields(ref, ['owner', 'repo']);
22
+ const id = await commentId(octokit, ref);
23
+ const path = endpoint(features.review_comment_edit_endpoint || UPDATE_ENDPOINT, { ...ref, comment_id: id });
24
+ const { data } = await octokit.request(`PATCH ${path}`, { body });
25
+ return updateResult(data);
26
+ }
27
+
28
+ async function listCommentsForReview(octokit, features, ref) {
29
+ requireFields(ref, ['owner', 'repo', 'pull_number']);
30
+ const id = await reviewId(octokit, ref);
31
+ const path = endpoint(features.review_comment_edit_list_endpoint || LIST_ENDPOINT, { ...ref, review_id: id });
32
+ const rows = await octokit.paginate(`GET ${path}`, { per_page: 100 });
33
+ return rows.map(normalizeComment);
34
+ }
35
+
36
+ module.exports = { updateReviewComment, listCommentsForReview };
@@ -187,9 +187,10 @@ async function getPendingReviewForUser(octokit, owner, repo, prNumber) {
187
187
  * @param {Object} octokit
188
188
  * @param {string|number} nodeId - GraphQL node id OR numeric review id
189
189
  * @param {Object} prContext - { owner, repo, prNumber, reviewId? }
190
+ * @param {Object} [options] - { strict?: boolean }, propagate non-404 failures
190
191
  * @returns {Promise<Object|null>}
191
192
  */
192
- async function getReviewById(octokit, nodeId, prContext) {
193
+ async function getReviewById(octokit, nodeId, prContext, { strict = false } = {}) {
193
194
  if (!prContext || !prContext.owner || !prContext.repo || !prContext.prNumber) {
194
195
  throw new Error(
195
196
  'REST getReviewById requires prContext={owner, repo, prNumber}. ' +
@@ -210,7 +211,9 @@ async function getReviewById(octokit, nodeId, prContext) {
210
211
  } else {
211
212
  // No usable numeric id — surface a clear error rather than calling
212
213
  // the REST API with a GraphQL node id (which would 404).
213
- logger.warn(`REST getReviewById called with non-numeric id "${nodeId}" and no prContext.reviewId`);
214
+ const message = `REST getReviewById called with non-numeric id "${nodeId}" and no prContext.reviewId`;
215
+ logger.warn(message);
216
+ if (strict) throw new Error(message);
214
217
  return null;
215
218
  }
216
219
  }
@@ -237,6 +240,7 @@ async function getReviewById(octokit, nodeId, prContext) {
237
240
  return null;
238
241
  }
239
242
  logger.warn(`Error fetching review ${reviewId} via REST: ${error.message}`);
243
+ if (strict) throw error;
240
244
  return null;
241
245
  }
242
246
  }
@@ -0,0 +1,44 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { failure, requireFields, normalizeComment, updateResult } = require('../review-comment-edit-utils');
3
+
4
+ // A node-only ref is resolved with a read, never by posting a replacement.
5
+ async function commentId(octokit, ref) {
6
+ if (ref?.github_comment_id) return String(ref.github_comment_id);
7
+ requireFields(ref, ['github_comment_node_id']);
8
+ const result = await octokit.graphql(`query($id: ID!) {
9
+ node(id: $id) { ... on PullRequestReviewComment { fullDatabaseId } }
10
+ }`, { id: ref.github_comment_node_id });
11
+ if (!result.node?.fullDatabaseId) throw failure('not_found', 'Review comment not found');
12
+ return String(result.node.fullDatabaseId);
13
+ }
14
+
15
+ async function reviewId(octokit, ref) {
16
+ if (ref?.github_review_id) return String(ref.github_review_id);
17
+ requireFields(ref, ['github_node_id']);
18
+ const result = await octokit.graphql(`query($id: ID!) {
19
+ node(id: $id) { ... on PullRequestReview { fullDatabaseId } }
20
+ }`, { id: ref.github_node_id });
21
+ if (!result.node?.fullDatabaseId) throw failure('not_found', 'Review not found');
22
+ return String(result.node.fullDatabaseId);
23
+ }
24
+
25
+ async function updateReviewComment(octokit, ref, body) {
26
+ requireFields(ref, ['owner', 'repo']);
27
+ const id = await commentId(octokit, ref);
28
+ const { data } = await octokit.rest.pulls.updateReviewComment({
29
+ owner: ref.owner, repo: ref.repo, comment_id: id, body
30
+ });
31
+ return updateResult(data);
32
+ }
33
+
34
+ async function listCommentsForReview(octokit, ref) {
35
+ requireFields(ref, ['owner', 'repo', 'pull_number']);
36
+ const id = await reviewId(octokit, ref);
37
+ const rows = await octokit.paginate(octokit.rest.pulls.listCommentsForReview, {
38
+ owner: ref.owner, repo: ref.repo, pull_number: ref.pull_number,
39
+ review_id: id, per_page: 100
40
+ });
41
+ return rows.map(normalizeComment);
42
+ }
43
+
44
+ module.exports = { updateReviewComment, listCommentsForReview, commentId, reviewId };
@@ -0,0 +1,45 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const stringId = value => value == null ? null : String(value);
3
+
4
+ function failure(code, message) {
5
+ return Object.assign(new Error(message), { code });
6
+ }
7
+
8
+ function requireFields(ref, fields) {
9
+ for (const field of fields) {
10
+ if (ref?.[field] == null || ref[field] === '') {
11
+ throw failure('invalid_ref', `Review comment reference requires ${field}`);
12
+ }
13
+ }
14
+ }
15
+
16
+ function normalizeComment(row) {
17
+ const id = stringId(row.id ?? row.github_comment_id);
18
+ const nodeId = row.node_id ?? row.github_comment_node_id ?? null;
19
+ const url = row.html_url ?? row.github_comment_url ?? null;
20
+ const login = row.user?.login ?? row.author_login ?? null;
21
+ return {
22
+ id, node_id: nodeId, html_url: url, user: { login },
23
+ github_comment_id: id, github_comment_node_id: nodeId,
24
+ github_comment_url: url, author_login: login,
25
+ in_reply_to_id: stringId(row.in_reply_to_id),
26
+ path: row.path, line: row.line ?? null, start_line: row.start_line ?? null,
27
+ side: row.side ?? null, start_side: row.start_side ?? null,
28
+ original_line: row.original_line ?? null,
29
+ original_start_line: row.original_start_line ?? null,
30
+ subject_type: row.subject_type ?? null,
31
+ body: row.body, created_at: row.created_at ?? null
32
+ };
33
+ }
34
+
35
+ function updateResult(row) {
36
+ const normalized = normalizeComment(row);
37
+ return {
38
+ github_comment_id: normalized.github_comment_id,
39
+ github_comment_node_id: normalized.github_comment_node_id,
40
+ github_comment_url: normalized.github_comment_url,
41
+ body: normalized.body
42
+ };
43
+ }
44
+
45
+ module.exports = { stringId, failure, requireFields, normalizeComment, updateResult };
@@ -65,15 +65,16 @@ async function getPendingReviewForUser(octokit, features, owner, repo, prNumber)
65
65
  * REQUIRED when `features.pending_review_check === "rest"` because the
66
66
  * REST endpoint identifies a review by (owner, repo, pull_number,
67
67
  * review_id) rather than by node id. Optional for the GraphQL path.
68
+ * @param {Object} [options] - { strict?: boolean }, propagate non-not-found failures
68
69
  * @returns {Promise<Object|null>}
69
70
  */
70
- async function getReviewById(octokit, features, nodeId, prContext) {
71
+ async function getReviewById(octokit, features, nodeId, prContext, options) {
71
72
  const mode = selectFeature(features);
72
73
  if (mode === 'graphql') {
73
- return graphqlImpl.getReviewById(octokit, nodeId);
74
+ return graphqlImpl.getReviewById(octokit, nodeId, options);
74
75
  }
75
76
  if (mode === 'rest') {
76
- return restImpl.getReviewById(octokit, nodeId, prContext);
77
+ return restImpl.getReviewById(octokit, nodeId, prContext, options);
77
78
  }
78
79
  if (mode === 'host') {
79
80
  throw new Error('Host implementation for pending_review_check not yet available (Phase 5)');
@@ -0,0 +1,35 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const graphqlImpl = require('../impl/graphql/review-comment-edit');
3
+ const restImpl = require('../impl/rest/review-comment-edit');
4
+ const hostImpl = require('../impl/host/review-comment-edit');
5
+
6
+ const AREA = 'review_comment_edit';
7
+ const IMPLEMENTED_MODES = new Set(['graphql', 'rest', 'host']);
8
+
9
+ async function dispatch(method, octokit, features, ref, body) {
10
+ const mode = features?.[AREA] || 'graphql';
11
+ try {
12
+ if (mode === 'graphql') return await graphqlImpl[method](octokit, ref, body);
13
+ if (mode === 'rest') return await restImpl[method](octokit, ref, body);
14
+ if (mode === 'host') return await hostImpl[method](octokit, features, ref, body);
15
+ throw new Error(`Unknown features.${AREA} value: "${mode}"`);
16
+ } catch (error) {
17
+ const types = (error.errors || []).map(item => item.type ?? item.extensions?.code);
18
+ const status = error.status ?? error.response?.status;
19
+ // Octokit's legacy `code` can be the numeric HTTP status; never let it
20
+ // override the stable operation codes (and avoid that deprecated getter).
21
+ const code = status === 404 || types.includes('NOT_FOUND') ? 'not_found' :
22
+ status === 403 || status === 422 || types.some(type => ['FORBIDDEN', 'UNPROCESSABLE', 'UNPROCESSABLE_ENTITY'].includes(type)) ? 'forbidden' :
23
+ status ? undefined : error.code;
24
+ const wrapped = new Error(`${method} (${mode}): ${error.message}`, { cause: error });
25
+ if (code) wrapped.code = code;
26
+ if (status) wrapped.status = status;
27
+ throw wrapped;
28
+ }
29
+ }
30
+
31
+ module.exports = {
32
+ AREA, IMPLEMENTED_MODES,
33
+ updateReviewComment: (octokit, features, ref, body) => dispatch('updateReviewComment', octokit, features, ref, body),
34
+ listCommentsForReview: (octokit, features, ref) => dispatch('listCommentsForReview', octokit, features, ref)
35
+ };
@@ -0,0 +1,78 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { GitHubReviewRepository, CommentPostingRepository, run } = require('../database');
3
+ const logger = require('../utils/logger');
4
+
5
+ /** Record the exact attached subset, inside the caller's short transaction. */
6
+ async function recordReviewSubmission(db, {
7
+ reviewId, event, body, githubReview, existingDraft = null,
8
+ sourceRows, sentComments, postedComments, postedAt = new Date().toISOString()
9
+ }) {
10
+ const review = await new GitHubReviewRepository(db).upsertForSubmission(reviewId, {
11
+ github_node_id: githubReview.id == null ? null : String(githubReview.id),
12
+ github_review_id: githubReview.databaseId == null
13
+ ? (existingDraft?.databaseId == null ? null : String(existingDraft.databaseId))
14
+ : String(githubReview.databaseId),
15
+ state: event === 'DRAFT' ? 'pending' : 'submitted',
16
+ event: event === 'DRAFT' ? null : event,
17
+ body: body || '', submitted_at: event === 'DRAFT' ? null : postedAt,
18
+ github_url: githubReview.html_url || existingDraft?.url || null
19
+ });
20
+ // A successful submission with unknown per-comment accounting keeps the
21
+ // historical all-sent contract, preventing silent reposts on the next submit.
22
+ // Failure callers only invoke this helper with an explicit known subset.
23
+ const posted = postedComments == null
24
+ ? sentComments.map((_, index) => ({ index })) : postedComments;
25
+ const postings = posted.map(p => {
26
+ const sent = sentComments[p.index];
27
+ const source = sourceRows[p.index];
28
+ if (!sent || !source) throw new Error(`Invalid posted comment index: ${p.index}`);
29
+ return {
30
+ comment_id: source.id, github_review_row_id: review.id,
31
+ comment_body: source.body, body: sent.body, file: sent.path,
32
+ line_start: sent.start_line ?? sent.line, line_end: sent.line,
33
+ side: sent.side, is_file_level: sent.isFileLevel,
34
+ github_comment_id: p.github_comment_id,
35
+ github_comment_node_id: p.github_comment_node_id,
36
+ github_comment_url: p.github_comment_url, posted_at: postedAt
37
+ };
38
+ });
39
+ await new CommentPostingRepository(db).insertMany(postings);
40
+ // Headless suggestions have a terminal disposition, not user lifecycle.
41
+ for (const p of postings) {
42
+ await run(db, "UPDATE comments SET status = 'submitted', updated_at = ? WHERE id = ? AND source = 'ai'",
43
+ [postedAt, p.comment_id]);
44
+ }
45
+ return review.id;
46
+ }
47
+
48
+ /** The API call has already failed; persist only its known, retained subset. */
49
+ async function recordRetainedSubmission(db, error, args, afterCommit = () => {}) {
50
+ if (!error.reviewRetained) return;
51
+ if (Array.isArray(error.postedComments) && error.postedComments.length) {
52
+ let began = false;
53
+ try {
54
+ await run(db, 'BEGIN TRANSACTION');
55
+ began = true;
56
+ await recordReviewSubmission(db, {
57
+ ...args, event: 'DRAFT', githubReview: error.pendingReview,
58
+ postedComments: error.postedComments
59
+ });
60
+ await run(db, 'COMMIT');
61
+ began = false;
62
+ } catch (dbError) {
63
+ if (began) {
64
+ try { await run(db, 'ROLLBACK'); }
65
+ catch (rollbackError) { logger.error('Failed to roll back retained-posting bookkeeping:', rollbackError); }
66
+ }
67
+ logger.error('Failed to record retained GitHub comment postings:', dbError);
68
+ error.message += ' Recording the retained comments locally failed; check the pending review on GitHub before resubmitting.';
69
+ throw error;
70
+ }
71
+ afterCommit();
72
+ error.message += ` ${error.postedComments.length} of ${args.sentComments.length} comments were added to your pending review on GitHub and are marked as such.`;
73
+ } else if (error.postedComments === null) {
74
+ error.message += ' The added subset is unknown; check the pending review on GitHub before resubmitting.';
75
+ }
76
+ }
77
+
78
+ module.exports = { recordReviewSubmission, recordRetainedSubmission };
@@ -0,0 +1,115 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { query, queryOne, run, withTransaction, CommentRepository, CommentPostingRepository } = require('../database');
3
+ const { buildReviewComments } = require('../utils/diff-annotator');
4
+
5
+ /** Exact wire identity, never a fuzzy body/line search. Replies cannot match roots. */
6
+ function matchesPosting(candidate, posting, login) {
7
+ if (!login || !candidate.user?.login || candidate.user.login.toLowerCase() !== login.toLowerCase() ||
8
+ candidate.in_reply_to_id != null || candidate.path !== posting.file || candidate.body !== posting.body) return false;
9
+ if (posting.is_file_level) return candidate.subject_type === 'file';
10
+ if (candidate.subject_type === 'file') return false;
11
+ // GitHub shifts current coordinates as commits land, even before a comment
12
+ // becomes outdated. Original coordinates identify the anchor we sent.
13
+ const line = candidate.original_line;
14
+ const start = candidate.original_start_line;
15
+ const expectedEnd = posting.line_end ?? posting.line_start;
16
+ if (expectedEnd == null || line == null) return false;
17
+ const expectedStart = posting.line_start === expectedEnd ? null : posting.line_start;
18
+ return line === expectedEnd && (start ?? null) === (expectedStart ?? null) &&
19
+ candidate.side === (posting.side || 'RIGHT') &&
20
+ (candidate.start_side ?? null) === (expectedStart == null ? null : (posting.side || 'RIGHT'));
21
+ }
22
+
23
+ function identityError(posting) {
24
+ return Object.assign(new Error("Couldn't find this comment on GitHub. Nothing was posted."), {
25
+ status: 409, code: 'unresolved_identity', review_url: posting.review_url
26
+ });
27
+ }
28
+
29
+ /** Network work precedes the short bookkeeping transaction; there is NO create fallback. */
30
+ async function updatePostedComment(db, { commentId, githubClient, owner, repo, pull_number }, afterCommit = () => {}) {
31
+ const comments = new CommentRepository(db);
32
+ const comment = await comments.getComment(commentId, 'user');
33
+ if (!comment?.publication) throw Object.assign(new Error('Comment has not been posted'), { status: 400 });
34
+ const posting = await queryOne(db, `SELECT p.*, gr.github_review_id, gr.github_node_id,
35
+ gr.github_url AS review_url, gr.state AS review_state FROM comment_postings p
36
+ LEFT JOIN github_reviews gr ON gr.id = p.github_review_row_id
37
+ WHERE p.comment_id = ? ORDER BY p.id DESC LIMIT 1`, [commentId]);
38
+ const ref = { owner, repo, pull_number, github_comment_id: posting.github_comment_id,
39
+ github_comment_node_id: posting.github_comment_node_id, github_review_id: posting.github_review_id,
40
+ github_node_id: posting.github_node_id };
41
+ // Each adapter can resolve the other ID form through a read-only lookup.
42
+ const hasUsableId = ref.github_comment_node_id || ref.github_comment_id;
43
+ let recovered = null;
44
+ if (!hasUsableId) {
45
+ const user = await githubClient.getAuthenticatedUser();
46
+ const trustedReview = !posting.backfilled && (ref.github_review_id || ref.github_node_id);
47
+ // PR-wide lists omit unpublished comments. Never search them for a draft.
48
+ if (!trustedReview && posting.review_state === 'pending') throw identityError(posting);
49
+ const candidates = trustedReview
50
+ ? await githubClient.listCommentsForReview(ref)
51
+ : await githubClient.listReviewComments({ owner, repo, pull_number });
52
+ const matches = [];
53
+ for (const candidate of candidates.filter(c => matchesPosting(c, posting, user.login))) {
54
+ // A legacy PR-wide search can otherwise mistake another locally known
55
+ // comment for this one when the original copy was deleted on the host.
56
+ const claimed = await queryOne(db, `SELECT 1 FROM comment_postings WHERE comment_id != ? AND
57
+ ((? IS NOT NULL AND github_comment_id = ?) OR (? IS NOT NULL AND github_comment_node_id = ?)) LIMIT 1`,
58
+ [commentId, candidate.id == null ? null : String(candidate.id), candidate.id == null ? null : String(candidate.id),
59
+ candidate.node_id ?? null, candidate.node_id ?? null]);
60
+ if (!claimed) matches.push(candidate);
61
+ }
62
+ if (matches.length !== 1) throw identityError(posting);
63
+ const match = matches[0];
64
+ recovered = { id: match.id == null ? null : String(match.id), node: match.node_id || null,
65
+ url: match.html_url || null };
66
+ ref.github_comment_id = recovered.id;
67
+ ref.github_comment_node_id = recovered.node;
68
+ if (!recovered.node && !recovered.id) throw identityError(posting);
69
+ // Repair survives even an update rejection, so the next attempt targets the same comment.
70
+ await run(db, `UPDATE comment_postings SET github_comment_id = ?, github_comment_node_id = ?,
71
+ github_comment_url = COALESCE(?, github_comment_url) WHERE comment_id = ?`,
72
+ [recovered.id, recovered.node, recovered.url, commentId]);
73
+ }
74
+ // An edit cannot move the host anchor. Preserve the posted shape rather
75
+ // than recalculating inline vs file fallback against today's diff. User
76
+ // bodies already include any configured adoption formatting.
77
+ const sent = posting.is_file_level
78
+ ? buildReviewComments([comment], '')[0] : { body: comment.body };
79
+ const result = await githubClient.updateReviewComment(ref, sent.body);
80
+ const ids = { id: result?.github_comment_id || ref.github_comment_id,
81
+ node: result?.github_comment_node_id || ref.github_comment_node_id,
82
+ url: result?.github_comment_url || recovered?.url || posting.github_comment_url };
83
+ await withTransaction(db, async () => {
84
+ await run(db, `UPDATE comment_postings SET github_comment_id = ?, github_comment_node_id = ?,
85
+ github_comment_url = COALESCE(?, github_comment_url) WHERE comment_id = ?`,
86
+ [ids.id, ids.node, ids.url, commentId]);
87
+ await new CommentPostingRepository(db).insertMany([{ ...posting, id: undefined,
88
+ github_comment_id: ids.id, github_comment_node_id: ids.node,
89
+ github_comment_url: ids.url,
90
+ comment_body: comment.body, body: sent.body, kind: 'update',
91
+ posted_at: new Date().toISOString() }]);
92
+ });
93
+ afterCommit(comment.review_id);
94
+ return comments.getComment(commentId, 'user');
95
+ }
96
+
97
+ /** Group old duplicate review identities while retaining every posting and lifecycle. */
98
+ async function listSubmissions(db, reviewId) {
99
+ const reviews = await query(db, 'SELECT * FROM github_reviews WHERE review_id = ? ORDER BY id DESC', [reviewId]);
100
+ const postings = await query(db, `SELECT p.*, c.status, c.status AS comment_status FROM comment_postings p
101
+ JOIN comments c ON c.id = p.comment_id WHERE c.review_id = ? ORDER BY p.id`, [reviewId]);
102
+ const groups = [];
103
+ for (const review of reviews) {
104
+ let group = groups.find(g => (review.github_node_id && g.github_node_id === review.github_node_id) ||
105
+ (review.github_review_id && g.github_review_id === review.github_review_id));
106
+ if (!group) { group = { ...review, postings: [] }; groups.push(group); }
107
+ group.postings.push(...postings.filter(p => p.github_review_row_id === review.id));
108
+ }
109
+ for (const group of groups) group.postings.sort((a, b) => a.id - b.id);
110
+ const unknown = postings.filter(p => p.github_review_row_id == null);
111
+ if (unknown.length) groups.push({ id: null, state: 'submitted', event: null, body: '', postings: unknown });
112
+ return groups;
113
+ }
114
+
115
+ module.exports = { matchesPosting, updatePostedComment, listSubmissions };
package/src/main.js CHANGED
@@ -8,6 +8,8 @@ const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, Work
8
8
  const { PRArgumentParser } = require('./github/parser');
9
9
  const { GitHubClient } = require('./github/client');
10
10
  const { buildSubmitPrContext } = require('./github/submit-pr-context');
11
+ const { recordReviewSubmission, recordRetainedSubmission } = require('./github/record-submission');
12
+ const { broadcastReviewEvent } = require('./events/review-events');
11
13
  const { GitWorktreeManager } = require('./git/worktree');
12
14
  const { fetchNoTags } = require('./git/fetch-helpers');
13
15
  const { cleanupOrphanedKeepFiles } = require('./git/pack-cleanup');
@@ -1374,7 +1376,7 @@ async function loadHeadlessSuggestions(db, reviewId) {
1374
1376
  type,
1375
1377
  is_file_level
1376
1378
  FROM comments
1377
- WHERE review_id = ? AND source = 'ai' AND ai_level IS NULL AND (is_raw = 0 OR is_raw IS NULL) AND status = 'active'
1379
+ WHERE review_id = ? AND source = 'ai' AND ai_level IS NULL AND (is_raw = 0 OR is_raw IS NULL) AND ${CommentRepository.pendingCommentSql('comments')}
1378
1380
  ORDER BY file, line_start
1379
1381
  `, [reviewId]);
1380
1382
 
@@ -1400,7 +1402,6 @@ async function loadHeadlessSuggestions(db, reviewId) {
1400
1402
  * @param {Object} options - Mode-specific options
1401
1403
  * @param {string} options.mode - 'draft' or 'review'
1402
1404
  * @param {string} options.reviewEvent - 'DRAFT' or 'COMMENT'
1403
- * @param {string} options.commentStatus - 'draft' or 'submitted'
1404
1405
  * @param {string} options.modeLabel - Display label for log messages (e.g., 'draft mode', 'action review mode')
1405
1406
  * @param {import('../git/worktree-pool-lifecycle').WorktreePoolLifecycle} [externalPoolLifecycle] - Shared pool lifecycle instance (avoids creating a fresh singleton)
1406
1407
  */
@@ -1783,14 +1784,22 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1783
1784
  });
1784
1785
 
1785
1786
  let githubReview;
1786
- if (options.reviewEvent === 'DRAFT') {
1787
- githubReview = await githubClient.createDraftReviewGraphQL(
1788
- prNodeId, reviewBody, githubComments, existingDraft?.id, submitPrContext
1789
- );
1790
- } else {
1791
- githubReview = await githubClient.createReviewGraphQL(
1792
- prNodeId, options.reviewEvent, reviewBody, githubComments, existingDraft?.id, submitPrContext
1793
- );
1787
+ try {
1788
+ if (options.reviewEvent === 'DRAFT') {
1789
+ githubReview = await githubClient.createDraftReviewGraphQL(
1790
+ prNodeId, reviewBody, githubComments, existingDraft?.id, submitPrContext
1791
+ );
1792
+ } else {
1793
+ githubReview = await githubClient.createReviewGraphQL(
1794
+ prNodeId, options.reviewEvent, reviewBody, githubComments, existingDraft?.id, submitPrContext
1795
+ );
1796
+ }
1797
+ } catch (error) {
1798
+ await recordRetainedSubmission(db, error, {
1799
+ reviewId: review.id, body: reviewBody, existingDraft,
1800
+ sourceRows: aiSuggestions, sentComments: githubComments
1801
+ }, () => broadcastReviewEvent(review.id, { type: 'review:comments_changed' }));
1802
+ throw error;
1794
1803
  }
1795
1804
 
1796
1805
  // When adding to an existing draft, use the existing URL and include prior comments in total count
@@ -1804,12 +1813,6 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1804
1813
  // - github_reviews.github_node_id -> GraphQL node ID (e.g., "PRR_kwDOM...")
1805
1814
  // - reviewData JSON -> uses 'github_node_id' key for the GraphQL node ID
1806
1815
  const githubNodeId = String(githubReview.id); // GraphQL methods return node IDs
1807
- const githubDatabaseId = githubReview.databaseId
1808
- ? String(githubReview.databaseId)
1809
- : existingDraft ? String(existingDraft.databaseId) : null;
1810
-
1811
- const githubReviewState = options.reviewEvent === 'DRAFT' ? 'pending' : 'submitted';
1812
-
1813
1816
  // Update database to track the review
1814
1817
  await run(db, 'BEGIN TRANSACTION');
1815
1818
 
@@ -1831,35 +1834,14 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1831
1834
  reviewData: reviewData
1832
1835
  });
1833
1836
 
1834
- // Create a github_reviews record to track this submission (matches pr.js)
1835
- const githubReviewRepo = new GitHubReviewRepository(db);
1836
- await githubReviewRepo.create(review.id, {
1837
- github_review_id: githubDatabaseId,
1838
- github_node_id: githubNodeId,
1839
- state: githubReviewState,
1840
- body: reviewBody || '',
1841
- github_url: githubReview.html_url
1837
+ await recordReviewSubmission(db, {
1838
+ reviewId: review.id, event: options.reviewEvent, body: reviewBody,
1839
+ githubReview, existingDraft, sourceRows: aiSuggestions,
1840
+ sentComments: githubComments, postedComments: githubReview.postedComments
1842
1841
  });
1843
1842
 
1844
- // Update AI suggestions to appropriate status (batch update for performance)
1845
- // Only the submitted suggestions (loadHeadlessSuggestions skipped the rest)
1846
- if (aiSuggestions.length > 0) {
1847
- const suggestionIds = aiSuggestions.map(s => s.id);
1848
- const placeholders = suggestionIds.map(() => '?').join(',');
1849
- await run(db, `
1850
- UPDATE comments
1851
- SET status = ?, updated_at = ?
1852
- WHERE id IN (${placeholders})
1853
- `, [options.commentStatus, now, ...suggestionIds]);
1854
- }
1855
-
1856
- // Submitting a pending review publishes the comments saved to it
1857
- // earlier, which are still 'draft' locally.
1858
- if (options.reviewEvent !== 'DRAFT' && existingDraft) {
1859
- await new CommentRepository(db).markDraftCommentsSubmitted(review.id, now);
1860
- }
1861
-
1862
1843
  await run(db, 'COMMIT');
1844
+ broadcastReviewEvent(review.id, { type: 'review:comments_changed' });
1863
1845
 
1864
1846
  const successLabel = options.reviewEvent === 'DRAFT' ? 'Draft review created' : 'Review submitted';
1865
1847
  console.log(`\n✅ ${successLabel} successfully!`);
@@ -2701,7 +2683,6 @@ async function handleDraftModeReview(args, config, db, flags = {}, poolLifecycle
2701
2683
  await performHeadlessReview(args, config, db, flags, {
2702
2684
  mode: 'draft',
2703
2685
  reviewEvent: 'DRAFT',
2704
- commentStatus: 'draft',
2705
2686
  modeLabel: 'draft mode'
2706
2687
  }, poolLifecycle);
2707
2688
  }
@@ -2720,7 +2701,6 @@ async function handleActionReview(args, config, db, flags = {}, poolLifecycle =
2720
2701
  await performHeadlessReview(args, config, db, flags, {
2721
2702
  mode: 'review',
2722
2703
  reviewEvent: 'COMMENT',
2723
- commentStatus: 'submitted',
2724
2704
  modeLabel: 'action review mode'
2725
2705
  }, poolLifecycle);
2726
2706
  }
package/src/routes/mcp.js CHANGED
@@ -271,6 +271,7 @@ function createMCPServer(db, options = {}) {
271
271
  type: c.type,
272
272
  title: c.title,
273
273
  status: c.status,
274
+ posted: c.publication?.state || null,
274
275
  created_at: c.created_at,
275
276
  });
276
277
  }