@in-the-loop-labs/pair-review 5.3.6 → 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.
- package/README.md +8 -0
- package/package.json +3 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/public/css/pr.css +407 -13
- package/public/js/components/AIPanel.js +323 -104
- package/public/js/components/ReviewHistoryModal.js +294 -0
- package/public/js/components/ReviewModal.js +131 -14
- package/public/js/components/SplitButton.js +14 -0
- package/public/js/local.js +4 -8
- package/public/js/modules/comment-manager.js +6 -12
- package/public/js/modules/comment-minimizer.js +4 -1
- package/public/js/modules/file-comment-manager.js +38 -74
- package/public/js/modules/pierre-bridge.js +36 -0
- package/public/js/modules/suggestion-manager.js +4 -1
- package/public/js/pr.js +337 -191
- package/public/js/utils/posted-comment.js +326 -0
- package/public/js/vendor/pierre-diffs-worker.js +41 -13485
- package/public/js/vendor/pierre-diffs.js +131 -1364
- package/public/local.html +1 -0
- package/public/pr.html +2 -0
- package/src/chat/api-reference.js +22 -2
- package/src/config.js +28 -4
- package/src/database.js +177 -35
- package/src/github/client.js +95 -16
- package/src/github/impl/graphql/pending-review-comments.js +118 -14
- package/src/github/impl/graphql/pending-review.js +8 -2
- package/src/github/impl/graphql/review-comment-edit.js +89 -0
- package/src/github/impl/host/pending-review-comments.js +41 -10
- package/src/github/impl/host/review-comment-edit.js +36 -0
- package/src/github/impl/rest/pending-review.js +6 -2
- package/src/github/impl/rest/review-comment-edit.js +44 -0
- package/src/github/impl/review-comment-edit-utils.js +45 -0
- package/src/github/operations/pending-review.js +4 -3
- package/src/github/operations/review-comment-edit.js +35 -0
- package/src/github/record-submission.js +78 -0
- package/src/github/update-posted-comment.js +115 -0
- package/src/main.js +24 -38
- package/src/routes/mcp.js +1 -0
- package/src/routes/pr.js +152 -100
package/src/github/client.js
CHANGED
|
@@ -6,6 +6,7 @@ const { GitHubApiError, isComplexityError } = require('./errors');
|
|
|
6
6
|
const pendingReviewOps = require('./operations/pending-review');
|
|
7
7
|
const reviewLifecycleOps = require('./operations/review-lifecycle');
|
|
8
8
|
const pendingReviewCommentsOps = require('./operations/pending-review-comments');
|
|
9
|
+
const reviewCommentEditOps = require('./operations/review-comment-edit');
|
|
9
10
|
|
|
10
11
|
// Defaults used when `GitHubClient` is constructed from a bare token
|
|
11
12
|
// string (i.e. without a resolved binding). These mirror the
|
|
@@ -17,9 +18,33 @@ const DEFAULT_FEATURES = Object.freeze({
|
|
|
17
18
|
pending_review_check: 'graphql',
|
|
18
19
|
stack_walker: 'graphql',
|
|
19
20
|
review_lifecycle: 'graphql',
|
|
20
|
-
pending_review_comments: 'graphql'
|
|
21
|
+
pending_review_comments: 'graphql',
|
|
22
|
+
review_comment_edit: 'graphql'
|
|
21
23
|
});
|
|
22
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Fetch for Octokit that keeps a network failure's error code. Native fetch
|
|
27
|
+
* rejects with `TypeError('fetch failed')` and the code (ECONNREFUSED,
|
|
28
|
+
* ENOTFOUND, ...) on `cause`; @octokit/request then rewraps it keeping only
|
|
29
|
+
* the message. Appending the code to the message lets callers tell a
|
|
30
|
+
* connection that was never made (safe to retry a mutation) from one lost
|
|
31
|
+
* mid-request. Looks up `globalThis.fetch` per call so test stubs apply.
|
|
32
|
+
*
|
|
33
|
+
* @param {...any} args - Arguments for fetch
|
|
34
|
+
* @returns {Promise<Response>}
|
|
35
|
+
*/
|
|
36
|
+
async function fetchKeepingErrorCode(...args) {
|
|
37
|
+
try {
|
|
38
|
+
return await globalThis.fetch(...args);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
const code = error && error.cause && error.cause.code;
|
|
41
|
+
if (typeof code === 'string' && error.message && !error.message.includes(code)) {
|
|
42
|
+
error.message = `${error.message} (${code})`;
|
|
43
|
+
}
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
23
48
|
/**
|
|
24
49
|
* Build the `Authorization` header value for a token, mirroring
|
|
25
50
|
* `@octokit/auth-token`'s scheme selection: JWTs (three dot-delimited
|
|
@@ -155,7 +180,8 @@ class GitHubClient {
|
|
|
155
180
|
_buildOctokit() {
|
|
156
181
|
const octokit = new Octokit({
|
|
157
182
|
baseUrl: this.apiHost || undefined,
|
|
158
|
-
userAgent: 'pair-review v1.0.0'
|
|
183
|
+
userAgent: 'pair-review v1.0.0',
|
|
184
|
+
request: { fetch: fetchKeepingErrorCode }
|
|
159
185
|
});
|
|
160
186
|
|
|
161
187
|
// (1) Stamp the live token onto every request. Reads `this.token` at
|
|
@@ -366,6 +392,37 @@ class GitHubClient {
|
|
|
366
392
|
}
|
|
367
393
|
}
|
|
368
394
|
|
|
395
|
+
/**
|
|
396
|
+
* Update an existing review comment in place, including a pending draft.
|
|
397
|
+
* Never creates a comment or retries an update as a create operation.
|
|
398
|
+
* @param {Object} ref - {owner, repo, pull_number, github_comment_id,
|
|
399
|
+
* github_comment_node_id, github_review_id, github_node_id}. The last
|
|
400
|
+
* node id identifies the review, not the comment. Only needed fields
|
|
401
|
+
* for the chosen transport must be supplied; missing IDs use safe reads.
|
|
402
|
+
* @param {string} body - Already-formatted wire body; sent unchanged.
|
|
403
|
+
* @returns {Promise<{github_comment_id: string|null,
|
|
404
|
+
* github_comment_node_id: string|null, github_comment_url: string|null, body: string}>}
|
|
405
|
+
* @throws {Error} code: not_found, forbidden, invalid_ref; other errors
|
|
406
|
+
* retain their cause and include operation/transport context.
|
|
407
|
+
*/
|
|
408
|
+
async updateReviewComment(ref, body) {
|
|
409
|
+
return reviewCommentEditOps.updateReviewComment(this.octokit, this.features, ref, body);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Paginate one review's comments, including the author's pending draft.
|
|
414
|
+
* @param {Object} ref - Same shape as updateReviewComment; provide a
|
|
415
|
+
* github_review_id and/or github_node_id (review node ID).
|
|
416
|
+
* @returns {Promise<Array<Object>>} REST-shaped candidates (string id,
|
|
417
|
+
* node_id, html_url, user.login, in_reply_to_id, path, line, start_line,
|
|
418
|
+
* side, start_side, original_line, original_start_line, subject_type,
|
|
419
|
+
* body, created_at), plus github_comment_id/github_comment_node_id/
|
|
420
|
+
* github_comment_url/author_login aliases. Bodies are never normalized.
|
|
421
|
+
*/
|
|
422
|
+
async listCommentsForReview(ref) {
|
|
423
|
+
return reviewCommentEditOps.listCommentsForReview(this.octokit, this.features, ref);
|
|
424
|
+
}
|
|
425
|
+
|
|
369
426
|
/**
|
|
370
427
|
* Validate GitHub token by making a test API call
|
|
371
428
|
* @returns {Promise<boolean>} Whether the token is valid
|
|
@@ -662,9 +719,11 @@ class GitHubClient {
|
|
|
662
719
|
*
|
|
663
720
|
* @param {string} nodeId - GraphQL node id
|
|
664
721
|
* @param {Object} [prContext] - `{ owner, repo, prNumber, reviewId? }`
|
|
722
|
+
* @param {Object} [options]
|
|
723
|
+
* @param {boolean} [options.strict=false] - Throw lookup failures other than not found
|
|
665
724
|
*/
|
|
666
|
-
async getReviewById(nodeId, prContext) {
|
|
667
|
-
return pendingReviewOps.getReviewById(this.octokit, this.features, nodeId, prContext);
|
|
725
|
+
async getReviewById(nodeId, prContext, options) {
|
|
726
|
+
return pendingReviewOps.getReviewById(this.octokit, this.features, nodeId, prContext, options);
|
|
668
727
|
}
|
|
669
728
|
|
|
670
729
|
/**
|
|
@@ -710,6 +769,7 @@ class GitHubClient {
|
|
|
710
769
|
// the alt-host REST/extension path rather than GraphQL. Keep the
|
|
711
770
|
// messages accurate to what really ran.
|
|
712
771
|
const transport = this.apiHost ? 'alt-host' : 'GraphQL';
|
|
772
|
+
const submission = { postedComments: [], reviewRetained: false, pendingReview: null };
|
|
713
773
|
try {
|
|
714
774
|
console.log(`Creating review (${transport}) for PR ${prNodeId} with ${comments.length} comments`);
|
|
715
775
|
|
|
@@ -759,10 +819,13 @@ class GitHubClient {
|
|
|
759
819
|
? { ...prContext, reviewId: reviewDatabaseId !== null ? reviewDatabaseId : prContext.reviewId }
|
|
760
820
|
: (reviewDatabaseId !== null ? { reviewId: reviewDatabaseId } : null);
|
|
761
821
|
|
|
822
|
+
submission.pendingReview = { id: reviewId, databaseId: reviewDatabaseId };
|
|
823
|
+
submission.reviewRetained = true;
|
|
762
824
|
let successfulComments = 0;
|
|
763
825
|
if (comments.length > 0) {
|
|
764
826
|
console.log(`Step 2: Adding ${comments.length} comments in batches...`);
|
|
765
827
|
let batchResult;
|
|
828
|
+
submission.postedComments = null; // Unknown until the transport reports a subset.
|
|
766
829
|
try {
|
|
767
830
|
batchResult = await this.addCommentsInBatches(prNodeId, reviewId, comments, 10, downstreamPrContext);
|
|
768
831
|
} catch (commentError) {
|
|
@@ -773,8 +836,10 @@ class GitHubClient {
|
|
|
773
836
|
// `batchResult.failed` was returned, leaving a pending review
|
|
774
837
|
// behind on these throws when we created it ourselves.
|
|
775
838
|
console.error(`CRITICAL: comment batch threw before completion: ${commentError.message}`);
|
|
839
|
+
submission.postedComments = commentError.postedComments ?? null;
|
|
776
840
|
if (!usedExistingReview) {
|
|
777
841
|
const cleaned = await this.deletePendingReview(reviewId, downstreamPrContext);
|
|
842
|
+
submission.reviewRetained = !cleaned;
|
|
778
843
|
if (!cleaned) {
|
|
779
844
|
console.warn('Warning: Failed to clean up pending review - manual cleanup may be required');
|
|
780
845
|
}
|
|
@@ -789,6 +854,7 @@ class GitHubClient {
|
|
|
789
854
|
throw wrapped;
|
|
790
855
|
}
|
|
791
856
|
successfulComments = batchResult.successCount;
|
|
857
|
+
submission.postedComments = batchResult.posted ?? null;
|
|
792
858
|
|
|
793
859
|
if (batchResult.failed) {
|
|
794
860
|
const failedCount = comments.length - successfulComments;
|
|
@@ -796,6 +862,7 @@ class GitHubClient {
|
|
|
796
862
|
console.error(`CRITICAL: ${failedCount} of ${comments.length} comments failed to add to GitHub`);
|
|
797
863
|
if (!usedExistingReview) {
|
|
798
864
|
const cleaned = await this.deletePendingReview(reviewId, downstreamPrContext);
|
|
865
|
+
submission.reviewRetained = !cleaned;
|
|
799
866
|
if (!cleaned) {
|
|
800
867
|
console.warn('Warning: Failed to clean up pending review - manual cleanup may be required');
|
|
801
868
|
}
|
|
@@ -824,7 +891,8 @@ class GitHubClient {
|
|
|
824
891
|
databaseId: result.databaseId,
|
|
825
892
|
html_url: result.url,
|
|
826
893
|
state: result.state,
|
|
827
|
-
comments_count: successfulComments
|
|
894
|
+
comments_count: successfulComments,
|
|
895
|
+
postedComments: submission.postedComments
|
|
828
896
|
};
|
|
829
897
|
|
|
830
898
|
} catch (error) {
|
|
@@ -835,10 +903,10 @@ class GitHubClient {
|
|
|
835
903
|
// label the message with the actual transport for accuracy.
|
|
836
904
|
if (error.errors) {
|
|
837
905
|
const messages = error.errors.map(e => e.message).join(', ');
|
|
838
|
-
throw new Error(`GitHub ${transport} error: ${messages}`);
|
|
906
|
+
throw Object.assign(new Error(`GitHub ${transport} error: ${messages}`), submission);
|
|
839
907
|
}
|
|
840
908
|
|
|
841
|
-
throw new Error(`Failed to submit review (${transport}): ${error.message}`);
|
|
909
|
+
throw Object.assign(new Error(`Failed to submit review (${transport}): ${error.message}`), submission);
|
|
842
910
|
}
|
|
843
911
|
}
|
|
844
912
|
|
|
@@ -860,6 +928,7 @@ class GitHubClient {
|
|
|
860
928
|
// historical; the real transport may be the alt-host REST/extension
|
|
861
929
|
// path rather than GraphQL. See createReviewGraphQL for the rationale.
|
|
862
930
|
const transport = this.apiHost ? 'alt-host' : 'GraphQL';
|
|
931
|
+
const submission = { postedComments: [], reviewRetained: false, pendingReview: null };
|
|
863
932
|
try {
|
|
864
933
|
console.log(`Creating draft review (${transport}) for PR ${prNodeId} with ${comments.length} comments`);
|
|
865
934
|
|
|
@@ -909,10 +978,13 @@ class GitHubClient {
|
|
|
909
978
|
? { ...prContext, reviewId: reviewDatabaseId !== null ? reviewDatabaseId : prContext.reviewId }
|
|
910
979
|
: (reviewDatabaseId !== null ? { reviewId: reviewDatabaseId } : null);
|
|
911
980
|
|
|
981
|
+
submission.pendingReview = { id: reviewId, databaseId: reviewDatabaseId };
|
|
982
|
+
submission.reviewRetained = true;
|
|
912
983
|
let successfulComments = 0;
|
|
913
984
|
if (comments.length > 0) {
|
|
914
985
|
console.log(`Step 2: Adding ${comments.length} comments in batches...`);
|
|
915
986
|
let batchResult;
|
|
987
|
+
submission.postedComments = null; // Unknown until the transport reports a subset.
|
|
916
988
|
try {
|
|
917
989
|
batchResult = await this.addCommentsInBatches(prNodeId, reviewId, comments, 10, downstreamPrContext);
|
|
918
990
|
} catch (commentError) {
|
|
@@ -923,8 +995,10 @@ class GitHubClient {
|
|
|
923
995
|
// `batchResult.failed` was returned, leaving a pending review
|
|
924
996
|
// behind on these throws when we created it ourselves.
|
|
925
997
|
console.error(`CRITICAL: comment batch threw before completion: ${commentError.message}`);
|
|
998
|
+
submission.postedComments = commentError.postedComments ?? null;
|
|
926
999
|
if (!usedExistingReview) {
|
|
927
1000
|
const cleaned = await this.deletePendingReview(reviewId, downstreamPrContext);
|
|
1001
|
+
submission.reviewRetained = !cleaned;
|
|
928
1002
|
if (!cleaned) {
|
|
929
1003
|
console.warn('Warning: Failed to clean up pending review - manual cleanup may be required');
|
|
930
1004
|
}
|
|
@@ -939,6 +1013,7 @@ class GitHubClient {
|
|
|
939
1013
|
throw wrapped;
|
|
940
1014
|
}
|
|
941
1015
|
successfulComments = batchResult.successCount;
|
|
1016
|
+
submission.postedComments = batchResult.posted ?? null;
|
|
942
1017
|
|
|
943
1018
|
if (batchResult.failed) {
|
|
944
1019
|
const failedCount = comments.length - successfulComments;
|
|
@@ -947,6 +1022,7 @@ class GitHubClient {
|
|
|
947
1022
|
console.error(`CRITICAL: ${failedCount} of ${comments.length} comments failed to add to draft review`);
|
|
948
1023
|
if (!usedExistingReview) {
|
|
949
1024
|
const cleaned = await this.deletePendingReview(reviewId, downstreamPrContext);
|
|
1025
|
+
submission.reviewRetained = !cleaned;
|
|
950
1026
|
if (!cleaned) {
|
|
951
1027
|
console.warn('Warning: Failed to clean up pending review - manual cleanup may be required');
|
|
952
1028
|
}
|
|
@@ -969,7 +1045,8 @@ class GitHubClient {
|
|
|
969
1045
|
databaseId: reviewDatabaseId,
|
|
970
1046
|
html_url: reviewUrl,
|
|
971
1047
|
state: 'PENDING',
|
|
972
|
-
comments_count: successfulComments
|
|
1048
|
+
comments_count: successfulComments,
|
|
1049
|
+
postedComments: submission.postedComments
|
|
973
1050
|
};
|
|
974
1051
|
|
|
975
1052
|
} catch (error) {
|
|
@@ -979,10 +1056,10 @@ class GitHubClient {
|
|
|
979
1056
|
// harmless on the REST/host path. Label with the actual transport.
|
|
980
1057
|
if (error.errors) {
|
|
981
1058
|
const messages = error.errors.map(e => e.message).join(', ');
|
|
982
|
-
throw new Error(`GitHub ${transport} error: ${messages}`);
|
|
1059
|
+
throw Object.assign(new Error(`GitHub ${transport} error: ${messages}`), submission);
|
|
983
1060
|
}
|
|
984
1061
|
|
|
985
|
-
throw new Error(`Failed to create draft review (${transport}): ${error.message}`);
|
|
1062
|
+
throw Object.assign(new Error(`Failed to create draft review (${transport}): ${error.message}`), submission);
|
|
986
1063
|
}
|
|
987
1064
|
}
|
|
988
1065
|
|
|
@@ -1111,12 +1188,14 @@ class GitHubClient {
|
|
|
1111
1188
|
* @returns {Promise<{login: string, name: string, avatar_url: string}>}
|
|
1112
1189
|
*/
|
|
1113
1190
|
async getAuthenticatedUser() {
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1191
|
+
// Share in-flight requests as well as successful reads. A failed lookup
|
|
1192
|
+
// must not poison the cache for a later recovery attempt.
|
|
1193
|
+
if (!this._authenticatedUser) {
|
|
1194
|
+
this._authenticatedUser = this.octokit.rest.users.getAuthenticated()
|
|
1195
|
+
.then(({ data }) => ({ login: data.login, name: data.name, avatar_url: data.avatar_url }))
|
|
1196
|
+
.catch(error => { this._authenticatedUser = null; throw error; });
|
|
1197
|
+
}
|
|
1198
|
+
return this._authenticatedUser;
|
|
1120
1199
|
}
|
|
1121
1200
|
|
|
1122
1201
|
/**
|
|
@@ -12,12 +12,66 @@ const { isComplexityError } = require('../../errors');
|
|
|
12
12
|
*
|
|
13
13
|
* The return shape (success count, failed flag, failedDetails) is the
|
|
14
14
|
* same shape `GitHubClient.addCommentsInBatches` historically returned;
|
|
15
|
-
* callers depend on
|
|
15
|
+
* callers depend on those fields for cleanup and error reporting. The
|
|
16
|
+
* additive `posted` array maps successful aliases back to input indexes;
|
|
17
|
+
* null means a transport failure left the subset unknown.
|
|
16
18
|
*/
|
|
17
19
|
|
|
18
20
|
const MIN_BATCH_SIZE = 1;
|
|
19
21
|
const DEFAULT_BATCH_SIZE = 10;
|
|
20
22
|
|
|
23
|
+
// Connection failures that happen before any request bytes reach GitHub.
|
|
24
|
+
// Octokit wraps fetch failures in a status-500 RequestError carrying only
|
|
25
|
+
// the original message, so match the code in the message as well.
|
|
26
|
+
const PRE_SEND_NETWORK_CODES = /\b(ECONNREFUSED|ENOTFOUND|EAI_AGAIN)\b/;
|
|
27
|
+
// GraphQL error messages that mean execution may have started.
|
|
28
|
+
const AMBIGUOUS_GRAPHQL_MESSAGE = /timeout|timed out|something went wrong/i;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether a failed batch mutation can be re-sent without risk of adding
|
|
32
|
+
* the same comments twice. Mutations are not idempotent: if GitHub ran
|
|
33
|
+
* the first request and only the response was lost (timeout, reset, 5xx),
|
|
34
|
+
* a retry duplicates every comment in the batch. So retry only failures
|
|
35
|
+
* that show GitHub did not run the mutation:
|
|
36
|
+
* - the connection was never made (refused, DNS failure);
|
|
37
|
+
* - GitHub refused the request with a 4xx response;
|
|
38
|
+
* - a GraphQL error response with no `data` at all (errors raised before
|
|
39
|
+
* execution, per the GraphQL spec), unless it reports a timeout;
|
|
40
|
+
* - a complexity/size rejection (never one carried by a 5xx response or a
|
|
41
|
+
* failed fetch: those are judged by status and connection alone).
|
|
42
|
+
* Anything carrying `data` (even null) ran at least partly and is never
|
|
43
|
+
* re-sent; everything else is ambiguous and fails the batch.
|
|
44
|
+
*
|
|
45
|
+
* @param {Error} error - The error thrown by octokit.graphql
|
|
46
|
+
* @returns {boolean} True if the batch can safely be sent again
|
|
47
|
+
*/
|
|
48
|
+
function isSafeToRetry(error) {
|
|
49
|
+
if (!error) return false;
|
|
50
|
+
if (error.data !== undefined) return false;
|
|
51
|
+
|
|
52
|
+
const status = typeof error.status === 'number' ? error.status : null;
|
|
53
|
+
const neverConnected = () => PRE_SEND_NETWORK_CODES.test(
|
|
54
|
+
[error.code, error.cause && error.cause.code, error.message].filter(Boolean).join(' ')
|
|
55
|
+
);
|
|
56
|
+
// A real 5xx response: GitHub may have run the mutation, whatever the
|
|
57
|
+
// message says (even one that looks like a complexity limit).
|
|
58
|
+
if (error.response && status !== null && status >= 500) return false;
|
|
59
|
+
// A status with no response is octokit's wrapper for a fetch failure;
|
|
60
|
+
// only a connection that was never made is safe.
|
|
61
|
+
if (!error.response && status !== null) return neverConnected();
|
|
62
|
+
|
|
63
|
+
if (isComplexityError(error)) return true;
|
|
64
|
+
|
|
65
|
+
if (Array.isArray(error.errors) && error.errors.length > 0) {
|
|
66
|
+
return !error.errors.some(e => AMBIGUOUS_GRAPHQL_MESSAGE.test((e && e.message) || ''));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// A real HTTP response means the request reached GitHub: only a 4xx
|
|
70
|
+
// rejection is safe, whatever the message says.
|
|
71
|
+
if (error.response) return status !== null && status >= 400 && status < 500;
|
|
72
|
+
return neverConnected();
|
|
73
|
+
}
|
|
74
|
+
|
|
21
75
|
/**
|
|
22
76
|
* Build the GraphQL mutation text for a batch of comments. Aliases each
|
|
23
77
|
* inner mutation as `comment0`, `comment1`, ... so partial-failure paths
|
|
@@ -26,7 +80,10 @@ const DEFAULT_BATCH_SIZE = 10;
|
|
|
26
80
|
* @param {Array} batch - Slice of comments to include in this mutation
|
|
27
81
|
* @returns {string} The full mutation text
|
|
28
82
|
*/
|
|
29
|
-
function buildBatchMutation(batch) {
|
|
83
|
+
function buildBatchMutation(batch, { includeCommentMetadata = true } = {}) {
|
|
84
|
+
const threadSelection = includeCommentMetadata
|
|
85
|
+
? 'thread { id comments(first: 1) { nodes { id fullDatabaseId url } } }'
|
|
86
|
+
: 'thread { id }';
|
|
30
87
|
const commentMutations = batch.map((comment, index) => {
|
|
31
88
|
const isFileLevel = comment.isFileLevel || !comment.line;
|
|
32
89
|
|
|
@@ -39,7 +96,7 @@ function buildBatchMutation(batch) {
|
|
|
39
96
|
subjectType: FILE
|
|
40
97
|
body: ${JSON.stringify(comment.body)}
|
|
41
98
|
}) {
|
|
42
|
-
|
|
99
|
+
${threadSelection}
|
|
43
100
|
}
|
|
44
101
|
`;
|
|
45
102
|
}
|
|
@@ -59,7 +116,7 @@ function buildBatchMutation(batch) {
|
|
|
59
116
|
side: ${side}
|
|
60
117
|
body: ${JSON.stringify(comment.body)}
|
|
61
118
|
}) {
|
|
62
|
-
|
|
119
|
+
${threadSelection}
|
|
63
120
|
}
|
|
64
121
|
`;
|
|
65
122
|
}).join('\n');
|
|
@@ -73,25 +130,38 @@ function buildBatchMutation(batch) {
|
|
|
73
130
|
|
|
74
131
|
/**
|
|
75
132
|
* Add comments to a pending review in batches, with adaptive batch sizing
|
|
76
|
-
* on GitHub complexity errors. Sequential, with one retry per
|
|
133
|
+
* on GitHub complexity errors. Sequential, with at most one retry per
|
|
134
|
+
* batch, and only when the failure shows GitHub did not run the mutation
|
|
135
|
+
* (see isSafeToRetry).
|
|
77
136
|
*
|
|
78
137
|
* @param {Object} octokit - Octokit instance (must expose .graphql)
|
|
79
138
|
* @param {string} prNodeId - GraphQL node ID for the PR
|
|
80
139
|
* @param {string} reviewId - GraphQL node ID for the pending review
|
|
81
140
|
* @param {Array} comments - Array of comments with path, line (optional), side, body, isFileLevel
|
|
82
141
|
* @param {number} [batchSize=10] - Initial batch size
|
|
83
|
-
* @returns {Promise<{successCount: number, failed: boolean, failedDetails: string[]}>}
|
|
142
|
+
* @returns {Promise<{successCount: number, failed: boolean, failedDetails: string[], posted: Array|null}>}
|
|
84
143
|
*/
|
|
85
144
|
async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batchSize = DEFAULT_BATCH_SIZE) {
|
|
86
145
|
if (comments.length === 0) {
|
|
87
|
-
return { successCount: 0, failed: false, failedDetails: [] };
|
|
146
|
+
return { successCount: 0, failed: false, failedDetails: [], posted: [] };
|
|
88
147
|
}
|
|
89
148
|
|
|
90
149
|
let currentBatchSize = batchSize;
|
|
91
150
|
let remaining = comments.slice();
|
|
92
151
|
let totalSuccessful = 0;
|
|
93
152
|
const failedDetails = [];
|
|
153
|
+
const posted = [];
|
|
154
|
+
const recordPosted = (result, index) => {
|
|
155
|
+
const comment = result.thread.comments?.nodes?.[0];
|
|
156
|
+
posted.push({
|
|
157
|
+
index,
|
|
158
|
+
github_comment_id: comment?.fullDatabaseId != null ? String(comment.fullDatabaseId) : null,
|
|
159
|
+
github_comment_node_id: comment?.id ?? null,
|
|
160
|
+
github_comment_url: comment?.url ?? null
|
|
161
|
+
});
|
|
162
|
+
};
|
|
94
163
|
let batchNumber = 0;
|
|
164
|
+
let includeCommentMetadata = true;
|
|
95
165
|
|
|
96
166
|
logger.info(`Adding ${comments.length} comments in batches of up to ${currentBatchSize}`);
|
|
97
167
|
|
|
@@ -100,7 +170,7 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
100
170
|
const batch = remaining.slice(0, currentBatchSize);
|
|
101
171
|
logger.info(`Adding comments batch ${batchNumber} (${batch.length} comments, ${remaining.length} remaining)...`);
|
|
102
172
|
|
|
103
|
-
|
|
173
|
+
let batchMutation = buildBatchMutation(batch, { includeCommentMetadata });
|
|
104
174
|
|
|
105
175
|
// Try the batch, with one retry on failure
|
|
106
176
|
let batchResult = null;
|
|
@@ -120,8 +190,28 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
120
190
|
} catch (error) {
|
|
121
191
|
batchError = error;
|
|
122
192
|
|
|
123
|
-
//
|
|
124
|
-
|
|
193
|
+
// Inspect partial results before any retry, including complexity
|
|
194
|
+
// retries. Replaying this mutation would duplicate successful aliases.
|
|
195
|
+
// Stop this batch and report its exact subset to the orchestrator.
|
|
196
|
+
if (error.data) break;
|
|
197
|
+
|
|
198
|
+
// Older GraphQL hosts may not expose fullDatabaseId. Only a pure
|
|
199
|
+
// field-validation rejection is safe to retry: validation precedes
|
|
200
|
+
// all mutation execution. Never replay partial or transport failures.
|
|
201
|
+
const metadataValidationError = error.errors?.length && error.errors.every(e =>
|
|
202
|
+
(e.extensions?.code === 'undefinedField' && e.extensions?.fieldName === 'fullDatabaseId') ||
|
|
203
|
+
/(?:Cannot query field ["']fullDatabaseId["']|Field ["']fullDatabaseId["'] doesn.t exist)/i.test(e.message || ''));
|
|
204
|
+
if (includeCommentMetadata && metadataValidationError && isSafeToRetry(error)) {
|
|
205
|
+
includeCommentMetadata = false;
|
|
206
|
+
batchMutation = buildBatchMutation(batch, { includeCommentMetadata });
|
|
207
|
+
logger.warn('GraphQL host lacks fullDatabaseId; posting without optional comment metadata');
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Complexity/cost limit: halve batch size and re-attempt. Only when
|
|
212
|
+
// re-sending is safe: never after data (some comments may have
|
|
213
|
+
// landed) or a 5xx response (the batch may have run).
|
|
214
|
+
if (isComplexityError(error) && isSafeToRetry(error)) {
|
|
125
215
|
const newSize = Math.max(MIN_BATCH_SIZE, Math.floor(currentBatchSize / 2));
|
|
126
216
|
if (newSize < currentBatchSize) {
|
|
127
217
|
logger.warn(
|
|
@@ -135,6 +225,14 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
135
225
|
// Already at the minimum - fall through to normal retry logic
|
|
136
226
|
}
|
|
137
227
|
|
|
228
|
+
if (!isSafeToRetry(error)) {
|
|
229
|
+
logger.error(
|
|
230
|
+
`Batch ${batchNumber} failed after GitHub may have applied it; not retrying ` +
|
|
231
|
+
`so comments are not added twice: ${error.message}`
|
|
232
|
+
);
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
|
|
138
236
|
if (retryAttempt < maxRetries) {
|
|
139
237
|
logger.warn(`Batch ${batchNumber} failed, retrying... (${error.message})`);
|
|
140
238
|
retryAttempt++;
|
|
@@ -174,6 +272,7 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
174
272
|
const commentResult = batchError.data[`comment${i}`];
|
|
175
273
|
if (commentResult && commentResult.thread && commentResult.thread.id) {
|
|
176
274
|
batchSuccessful++;
|
|
275
|
+
recordPosted(commentResult, comments.length - remaining.length + i);
|
|
177
276
|
} else {
|
|
178
277
|
const ghError = perCommentErrors[`comment${i}`] || 'No error details available';
|
|
179
278
|
const location = `${batch[i].path}:${batch[i].line || 'file-level'}`;
|
|
@@ -183,7 +282,7 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
183
282
|
}
|
|
184
283
|
if (batchSuccessful < batch.length) {
|
|
185
284
|
logger.error(`CRITICAL: Batch ${batchNumber} had ${batch.length - batchSuccessful} failures`);
|
|
186
|
-
return { successCount: totalSuccessful + batchSuccessful, failed: true, failedDetails };
|
|
285
|
+
return { successCount: totalSuccessful + batchSuccessful, failed: true, failedDetails, posted };
|
|
187
286
|
}
|
|
188
287
|
logger.info(`Batch ${batchNumber} complete (recovered from partial error): ${batchSuccessful} comments added`);
|
|
189
288
|
totalSuccessful += batchSuccessful;
|
|
@@ -195,7 +294,10 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
195
294
|
const location = `${batch[i].path}:${batch[i].line || 'file-level'}`;
|
|
196
295
|
failedDetails.push(`${location} - ${ghError}`);
|
|
197
296
|
}
|
|
198
|
-
|
|
297
|
+
// The earlier batches are known only if GitHub did not run this one;
|
|
298
|
+
// a failure it may have applied leaves the subset unknown.
|
|
299
|
+
return { successCount: totalSuccessful, failed: true, failedDetails,
|
|
300
|
+
posted: isSafeToRetry(batchError) ? posted : null };
|
|
199
301
|
}
|
|
200
302
|
} else if (batchResult) {
|
|
201
303
|
let batchSuccessful = 0;
|
|
@@ -203,6 +305,7 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
203
305
|
const commentResult = batchResult[`comment${i}`];
|
|
204
306
|
if (commentResult && commentResult.thread && commentResult.thread.id) {
|
|
205
307
|
batchSuccessful++;
|
|
308
|
+
recordPosted(commentResult, comments.length - remaining.length + i);
|
|
206
309
|
} else {
|
|
207
310
|
const location = `${batch[i].path}:${batch[i].line || 'file-level'}`;
|
|
208
311
|
logger.warn(`Comment ${i} in batch ${batchNumber} failed to add: ${location} - No error details available`);
|
|
@@ -212,7 +315,7 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
212
315
|
|
|
213
316
|
if (batchSuccessful < batch.length) {
|
|
214
317
|
logger.error(`CRITICAL: Batch ${batchNumber} had ${batch.length - batchSuccessful} failures`);
|
|
215
|
-
return { successCount: totalSuccessful + batchSuccessful, failed: true, failedDetails };
|
|
318
|
+
return { successCount: totalSuccessful + batchSuccessful, failed: true, failedDetails, posted };
|
|
216
319
|
}
|
|
217
320
|
|
|
218
321
|
totalSuccessful += batchSuccessful;
|
|
@@ -223,12 +326,13 @@ async function addCommentsInBatches(octokit, prNodeId, reviewId, comments, batch
|
|
|
223
326
|
}
|
|
224
327
|
|
|
225
328
|
logger.info(`All batches complete: ${totalSuccessful} total comments added`);
|
|
226
|
-
return { successCount: totalSuccessful, failed: false, failedDetails };
|
|
329
|
+
return { successCount: totalSuccessful, failed: false, failedDetails, posted };
|
|
227
330
|
}
|
|
228
331
|
|
|
229
332
|
module.exports = {
|
|
230
333
|
addCommentsInBatches,
|
|
231
334
|
buildBatchMutation,
|
|
335
|
+
isSafeToRetry,
|
|
232
336
|
MIN_BATCH_SIZE,
|
|
233
337
|
DEFAULT_BATCH_SIZE
|
|
234
338
|
};
|
|
@@ -114,9 +114,11 @@ async function getPendingReviewForUser(octokit, owner, repo, prNumber) {
|
|
|
114
114
|
*
|
|
115
115
|
* @param {Object} octokit - Octokit instance (must expose .graphql)
|
|
116
116
|
* @param {string} nodeId - GraphQL node ID for the review
|
|
117
|
+
* @param {Object} [options]
|
|
118
|
+
* @param {boolean} [options.strict=false] - Throw errors other than confirmed absence
|
|
117
119
|
* @returns {Promise<Object|null>} Review data or null if not found
|
|
118
120
|
*/
|
|
119
|
-
async function getReviewById(octokit, nodeId) {
|
|
121
|
+
async function getReviewById(octokit, nodeId, { strict = false } = {}) {
|
|
120
122
|
try {
|
|
121
123
|
logger.debug(`Fetching review by node ID: ${nodeId}`);
|
|
122
124
|
|
|
@@ -137,12 +139,16 @@ async function getReviewById(octokit, nodeId) {
|
|
|
137
139
|
url: review.url
|
|
138
140
|
};
|
|
139
141
|
} catch (error) {
|
|
140
|
-
|
|
142
|
+
const isNotFound = e => e.type === 'NOT_FOUND' || e.message?.includes('not found');
|
|
143
|
+
// Mixed GraphQL errors are not evidence that the review was deleted.
|
|
144
|
+
if (error.status === 404 || (error.errors?.length &&
|
|
145
|
+
(strict ? error.errors.every(e => e.type === 'NOT_FOUND') : error.errors.some(isNotFound)))) {
|
|
141
146
|
logger.debug(`Review not found for node ID: ${nodeId}`);
|
|
142
147
|
return null;
|
|
143
148
|
}
|
|
144
149
|
|
|
145
150
|
logger.warn(`Error fetching review by node ID ${nodeId}: ${error.message}`);
|
|
151
|
+
if (strict) throw error;
|
|
146
152
|
return null;
|
|
147
153
|
}
|
|
148
154
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
const { failure, requireFields, normalizeComment, updateResult } = require('../review-comment-edit-utils');
|
|
3
|
+
const restImpl = require('../rest/review-comment-edit');
|
|
4
|
+
|
|
5
|
+
async function commentNodeId(octokit, ref) {
|
|
6
|
+
if (ref?.github_comment_node_id) return ref.github_comment_node_id;
|
|
7
|
+
requireFields(ref, ['owner', 'repo', 'github_comment_id']);
|
|
8
|
+
const { data } = await octokit.rest.pulls.getReviewComment({
|
|
9
|
+
owner: ref.owner, repo: ref.repo, comment_id: ref.github_comment_id
|
|
10
|
+
});
|
|
11
|
+
if (!data.node_id) throw failure('invalid_ref', 'Comment read did not return a node id');
|
|
12
|
+
return data.node_id;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function reviewNodeId(octokit, ref) {
|
|
16
|
+
if (ref?.github_node_id) return ref.github_node_id;
|
|
17
|
+
requireFields(ref, ['owner', 'repo', 'pull_number', 'github_review_id']);
|
|
18
|
+
const { data } = await octokit.rest.pulls.getReview({
|
|
19
|
+
owner: ref.owner, repo: ref.repo, pull_number: ref.pull_number,
|
|
20
|
+
review_id: ref.github_review_id
|
|
21
|
+
});
|
|
22
|
+
if (!data.node_id) throw failure('invalid_ref', 'Review read did not return a node id');
|
|
23
|
+
return data.node_id;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function updateReviewComment(octokit, ref, body) {
|
|
27
|
+
const id = await commentNodeId(octokit, ref);
|
|
28
|
+
const result = await octokit.graphql(`mutation($id: ID!, $body: String!) {
|
|
29
|
+
updatePullRequestReviewComment(input: {pullRequestReviewCommentId: $id, body: $body}) {
|
|
30
|
+
pullRequestReviewComment { id fullDatabaseId url body }
|
|
31
|
+
}
|
|
32
|
+
}`, { id, body });
|
|
33
|
+
const row = result.updatePullRequestReviewComment?.pullRequestReviewComment;
|
|
34
|
+
if (!row) throw failure('not_found', 'Updated review comment was not returned');
|
|
35
|
+
return updateResult({ id: row.fullDatabaseId, node_id: row.id, html_url: row.url, body: row.body });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function listCommentsForReview(octokit, ref) {
|
|
39
|
+
const id = await reviewNodeId(octokit, ref);
|
|
40
|
+
const rows = [];
|
|
41
|
+
let cursor = null;
|
|
42
|
+
let reviewId = ref.github_review_id;
|
|
43
|
+
do {
|
|
44
|
+
const result = await octokit.graphql(`query($id: ID!, $cursor: String) {
|
|
45
|
+
node(id: $id) { ... on PullRequestReview {
|
|
46
|
+
fullDatabaseId
|
|
47
|
+
comments(first: 100, after: $cursor) {
|
|
48
|
+
nodes {
|
|
49
|
+
id fullDatabaseId url body path line startLine originalLine originalStartLine
|
|
50
|
+
subjectType createdAt author { login } replyTo { id fullDatabaseId }
|
|
51
|
+
}
|
|
52
|
+
pageInfo { hasNextPage endCursor }
|
|
53
|
+
}
|
|
54
|
+
} }
|
|
55
|
+
}`, { id, cursor });
|
|
56
|
+
if (!result.node?.comments) throw failure('not_found', 'Review not found');
|
|
57
|
+
reviewId = reviewId ?? result.node.fullDatabaseId;
|
|
58
|
+
for (const row of result.node.comments.nodes) {
|
|
59
|
+
rows.push(normalizeComment({
|
|
60
|
+
id: row.fullDatabaseId, node_id: row.id, html_url: row.url,
|
|
61
|
+
body: row.body, path: row.path, line: row.line, start_line: row.startLine,
|
|
62
|
+
original_line: row.originalLine, original_start_line: row.originalStartLine,
|
|
63
|
+
subject_type: row.subjectType?.toLowerCase(), created_at: row.createdAt,
|
|
64
|
+
user: row.author, in_reply_to_id: row.replyTo ? (row.replyTo.fullDatabaseId ?? row.replyTo.id ?? 'unknown-reply') : null
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
const info = result.node.comments.pageInfo;
|
|
68
|
+
if (!info.hasNextPage) break;
|
|
69
|
+
if (!info.endCursor || info.endCursor === cursor) throw new Error('Review comment pagination did not advance');
|
|
70
|
+
cursor = info.endCursor;
|
|
71
|
+
} while (true);
|
|
72
|
+
|
|
73
|
+
// GitHub's GraphQL comment type exposes no diff side fields. Enrich from
|
|
74
|
+
// the same review's REST list (also includes the author's pending comments),
|
|
75
|
+
// never infer RIGHT or mistake an outdated comment for a file comment.
|
|
76
|
+
if (rows.some(row => row.subject_type !== 'file')) {
|
|
77
|
+
requireFields(ref, ['owner', 'repo', 'pull_number']);
|
|
78
|
+
if (!reviewId) throw failure('invalid_ref', 'Review has no REST id for diff-side lookup');
|
|
79
|
+
const geometry = await restImpl.listCommentsForReview(octokit, { ...ref, github_review_id: reviewId });
|
|
80
|
+
const byId = new Map(geometry.map(row => [row.id, row]));
|
|
81
|
+
for (const row of rows) {
|
|
82
|
+
const match = row.id == null ? null : byId.get(row.id);
|
|
83
|
+
if (match) { row.side = match.side; row.start_side = match.start_side; }
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return rows;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
module.exports = { updateReviewComment, listCommentsForReview };
|