Open History to see the last commit
1import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";
2import type { PullRequestReviewPosition } from "@t3tools/contracts";
3import * as Schema from "effect/Schema";
4
5const ReviewCommentSelectionSchema = Schema.Struct({
6 start: Schema.Number,
7 side: Schema.Literals(["additions", "deletions"]),
8 end: Schema.Number,
9 endSide: Schema.Literals(["additions", "deletions"]),
10});
11type ReviewCommentSelection = typeof ReviewCommentSelectionSchema.Type;
12
13export const ReviewCommentContextSchema = Schema.Struct({
14 id: Schema.String,
15 sectionId: Schema.String,
16 sectionTitle: Schema.String,
17 filePath: Schema.String,
18 startIndex: Schema.Number,
19 endIndex: Schema.Number,
20 rangeLabel: Schema.String,
21 text: Schema.String,
22 diff: Schema.String,
23 fenceLanguage: Schema.optional(Schema.String),
24 selection: Schema.optional(ReviewCommentSelectionSchema),
25});
26
27export interface ReviewCommentContext {
28 readonly id: string;
29 readonly sectionId: string;
30 readonly sectionTitle: string;
31 readonly filePath: string;
32 readonly startIndex: number;
33 readonly endIndex: number;
34 readonly rangeLabel: string;
35 readonly text: string;
36 readonly diff: string;
37 readonly fenceLanguage?: string | undefined;
38 readonly selection?: ReviewCommentSelection | undefined;
39}
40
41interface DiffReviewLine {
42 readonly change: "context" | "add" | "delete";
43 readonly oldLineNumber: number | null;
44 readonly newLineNumber: number | null;
45 readonly content: string;
46}
47
48export type ReviewCommentMessageSegment =
49 | {
50 readonly kind: "text";
51 readonly id: string;
52 readonly text: string;
53 }
54 | {
55 readonly kind: "review-comment";
56 readonly comment: ReviewCommentContext;
57 };
58
59const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
60const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
61const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
62
63function escapeReviewCommentAttribute(value: string): string {
64 return value
65 .replace(/&/g, "&")
66 .replace(/"/g, """)
67 .replace(/</g, "<")
68 .replace(/>/g, ">");
69}
70
71function unescapeReviewCommentAttribute(value: string): string {
72 return value
73 .replace(/</g, "<")
74 .replace(/>/g, ">")
75 .replace(/"/g, '"')
76 .replace(/&/g, "&");
77}
78
79function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
80 const attributes: Record<string, string> = {};
81 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
82 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
83 }
84 return attributes;
85}
86
87function readNonNegativeInteger(value: string | undefined): number | null {
88 if (value === undefined || !/^\d+$/.test(value)) {
89 return null;
90 }
91 return Number(value);
92}
93
94function extractReviewCommentBody(rawBody: string): {
95 text: string;
96 language: string;
97 contents: string;
98} {
99 const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
100 const match = matches.at(-1);
101 const fenceIndex = match?.index;
102 return {
103 text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
104 language: match?.[2]?.trim() || "diff",
105 contents: match?.[3] ?? "",
106 };
107}
108
109function parseReviewCommentContext(
110 rawAttributes: string,
111 rawBody: string,
112 index: number,
113): ReviewCommentContext | null {
114 const attributes = readReviewCommentAttributes(rawAttributes);
115 const startIndex = readNonNegativeInteger(attributes.startIndex);
116 const endIndex = readNonNegativeInteger(attributes.endIndex);
117 const filePath = attributes.filePath?.trim();
118 const sectionId = attributes.sectionId?.trim();
119 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
120 return null;
121 }
122 const body = extractReviewCommentBody(rawBody);
123
124 return {
125 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
126 sectionId,
127 sectionTitle: attributes.sectionTitle?.trim() || "Review",
128 filePath,
129 startIndex: Math.min(startIndex, endIndex),
130 endIndex: Math.max(startIndex, endIndex),
131 rangeLabel: attributes.rangeLabel?.trim() || "line",
132 text: body.text,
133 diff: body.contents,
134 fenceLanguage: body.language,
135 };
136}
137
138export function parseReviewCommentMessageSegments(
139 value: string,
140): ReadonlyArray<ReviewCommentMessageSegment> {
141 const segments: ReviewCommentMessageSegment[] = [];
142 let cursor = 0;
143 let parsedCommentIndex = 0;
144
145 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
146 const matchIndex = match.index ?? 0;
147 const beforeText = value.slice(cursor, matchIndex);
148 if (beforeText.length > 0) {
149 segments.push({
150 kind: "text",
151 id: `review-comment-text:${cursor}`,
152 text: beforeText,
153 });
154 }
155
156 const comment = parseReviewCommentContext(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
157 if (comment) {
158 segments.push({ kind: "review-comment", comment });
159 parsedCommentIndex += 1;
160 } else {
161 segments.push({
162 kind: "text",
163 id: `review-comment-invalid:${matchIndex}`,
164 text: match[0],
165 });
166 }
167
168 cursor = matchIndex + match[0].length;
169 }
170
171 const rest = value.slice(cursor);
172 if (rest.length > 0) {
173 segments.push({
174 kind: "text",
175 id: `review-comment-text:${cursor}`,
176 text: rest,
177 });
178 }
179
180 return segments;
181}
182
183export function hasReviewCommentMessageSegments(value: string): boolean {
184 return parseReviewCommentMessageSegments(value).some(
185 (segment) => segment.kind === "review-comment",
186 );
187}
188
189export function formatReviewCommentFence(language: string, contents: string): string {
190 const longestBacktickRun = Math.max(
191 0,
192 ...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
193 );
194 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
195 return [`${fence}${language}`, contents.trimEnd(), fence].join("\n");
196}
197
198/**
199 * Keeps a comment's own words from closing the block they travel in. The parser ends an
200 * attachment at the first `</review_comment>`, so text carrying one would spill the rest of
201 * itself into the prompt — and could open a forged attachment naming any file it liked. Only
202 * ever the local reader's words before, but a pull request's review bodies come from whoever
203 * wrote them.
204 */
205function neutralizeReviewCommentTags(text: string): string {
206 return text.replace(/<(?=\/?review_comment\b)/giu, "<");
207}
208
209export function formatReviewCommentContext(comment: ReviewCommentContext): string {
210 return [
211 [
212 "<review_comment",
213 ` sectionId="${escapeReviewCommentAttribute(comment.sectionId)}"`,
214 ` sectionTitle="${escapeReviewCommentAttribute(comment.sectionTitle)}"`,
215 ` filePath="${escapeReviewCommentAttribute(comment.filePath)}"`,
216 ` startIndex="${comment.startIndex}"`,
217 ` endIndex="${comment.endIndex}"`,
218 ` rangeLabel="${escapeReviewCommentAttribute(comment.rangeLabel)}"`,
219 ">",
220 ].join(""),
221 neutralizeReviewCommentTags(comment.text.trim()),
222 formatReviewCommentFence(comment.fenceLanguage ?? "diff", comment.diff),
223 "</review_comment>",
224 ].join("\n");
225}
226
227export function appendReviewCommentsToPrompt(
228 prompt: string,
229 comments: ReadonlyArray<ReviewCommentContext>,
230): string {
231 const blocks = comments.map(formatReviewCommentContext);
232 if (blocks.length === 0) return prompt;
233 const trimmedPrompt = prompt.trim();
234 return trimmedPrompt.length > 0
235 ? `${trimmedPrompt}\n\n${blocks.join("\n\n")}`
236 : blocks.join("\n\n");
237}
238
239export function buildFileReviewComment(input: {
240 id: string;
241 filePath: string;
242 startLine: number;
243 endLine: number;
244 text: string;
245 contents: string;
246}): ReviewCommentContext {
247 const startLine = Math.max(1, Math.min(input.startLine, input.endLine));
248 const endLine = Math.max(startLine, Math.max(input.startLine, input.endLine));
249 const selectedLines = input.contents.split("\n").slice(startLine - 1, endLine);
250 return {
251 id: input.id,
252 sectionId: `file:${input.filePath}`,
253 sectionTitle: "File comment",
254 filePath: input.filePath,
255 startIndex: startLine - 1,
256 endIndex: endLine - 1,
257 rangeLabel: startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`,
258 text: input.text.trim(),
259 diff: selectedLines.join("\n"),
260 fenceLanguage: inferReviewCommentFenceLanguage(input.filePath),
261 };
262}
263
264export function inferReviewCommentFenceLanguage(filePath: string): string {
265 const normalizedPath = filePath.replaceAll("\\", "/");
266 const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1).toLowerCase();
267 const extensionIndex = fileName.lastIndexOf(".");
268 if (extensionIndex > 0 && extensionIndex < fileName.length - 1) {
269 return fileName.slice(extensionIndex + 1);
270 }
271 if (fileName.startsWith(".") && fileName.length > 1) {
272 return fileName.slice(1);
273 }
274 return "text";
275}
276
277function stripTrailingNewline(value: string): string {
278 return value.endsWith("\n") ? value.slice(0, -1) : value;
279}
280
281function buildDiffReviewLines(
282 fileDiff: FileDiffMetadata,
283 includeExpandedContext: boolean,
284 slice?: { readonly startIndex: number; readonly endIndex: number },
285): ReadonlyArray<DiffReviewLine> {
286 const rows: DiffReviewLine[] = [];
287 let rowIndex = 0;
288 let oldContextStart = 1;
289 let newContextStart = 1;
290 const pushRow = (row: DiffReviewLine) => {
291 if (!slice || (rowIndex >= slice.startIndex && rowIndex <= slice.endIndex)) {
292 rows.push(row);
293 }
294 rowIndex += 1;
295 };
296 const pushContextGap = (oldStart: number, newStart: number, lineCount: number) => {
297 const count = Math.max(0, lineCount);
298 const firstOffset = slice ? Math.max(0, slice.startIndex - rowIndex) : 0;
299 const lastOffset = slice ? Math.min(count - 1, slice.endIndex - rowIndex) : count - 1;
300 for (let offset = firstOffset; offset <= lastOffset; offset += 1) {
301 rows.push({
302 change: "context",
303 oldLineNumber: oldStart + offset,
304 newLineNumber: newStart + offset,
305 content: stripTrailingNewline(fileDiff.additionLines[newStart + offset - 1] ?? ""),
306 });
307 }
308 rowIndex += count;
309 };
310
311 for (const hunk of fileDiff.hunks) {
312 if (includeExpandedContext) {
313 const oldHunkStart = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);
314 const newHunkStart = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);
315 const contextLines = Math.min(oldHunkStart - oldContextStart, newHunkStart - newContextStart);
316 pushContextGap(oldContextStart, newContextStart, contextLines);
317 }
318
319 let oldLineNumber = hunk.deletionStart;
320 let newLineNumber = hunk.additionStart;
321 let deletionLineIndex = hunk.deletionLineIndex;
322 let additionLineIndex = hunk.additionLineIndex;
323
324 for (const segment of hunk.hunkContent) {
325 if (segment.type === "context") {
326 for (let index = 0; index < segment.lines; index += 1) {
327 pushRow({
328 change: "context",
329 oldLineNumber,
330 newLineNumber,
331 content: stripTrailingNewline(
332 fileDiff.additionLines[additionLineIndex] ??
333 fileDiff.deletionLines[deletionLineIndex] ??
334 "",
335 ),
336 });
337 oldLineNumber += 1;
338 newLineNumber += 1;
339 deletionLineIndex += 1;
340 additionLineIndex += 1;
341 }
342 continue;
343 }
344
345 for (let index = 0; index < segment.deletions; index += 1) {
346 pushRow({
347 change: "delete",
348 oldLineNumber,
349 newLineNumber: null,
350 content: stripTrailingNewline(fileDiff.deletionLines[deletionLineIndex] ?? ""),
351 });
352 oldLineNumber += 1;
353 deletionLineIndex += 1;
354 }
355
356 for (let index = 0; index < segment.additions; index += 1) {
357 pushRow({
358 change: "add",
359 oldLineNumber: null,
360 newLineNumber,
361 content: stripTrailingNewline(fileDiff.additionLines[additionLineIndex] ?? ""),
362 });
363 newLineNumber += 1;
364 additionLineIndex += 1;
365 }
366 }
367
368 oldContextStart = hunk.deletionStart + hunk.deletionCount;
369 newContextStart = hunk.additionStart + hunk.additionCount;
370 if (hunk.deletionCount === 0) oldContextStart += 1;
371 if (hunk.additionCount === 0) newContextStart += 1;
372 }
373
374 if (includeExpandedContext) {
375 const trailingLines = Math.min(
376 fileDiff.deletionLines.length - oldContextStart + 1,
377 fileDiff.additionLines.length - newContextStart + 1,
378 );
379 pushContextGap(oldContextStart, newContextStart, trailingLines);
380 }
381
382 return rows;
383}
384
385function getDiffReviewSelectionPoint(
386 line: DiffReviewLine,
387): { lineNumber: number; side: SelectionSide } | null {
388 if (line.change === "delete" && line.oldLineNumber !== null) {
389 return { lineNumber: line.oldLineNumber, side: "deletions" };
390 }
391 if (line.newLineNumber !== null) {
392 return { lineNumber: line.newLineNumber, side: "additions" };
393 }
394 if (line.oldLineNumber !== null) {
395 return { lineNumber: line.oldLineNumber, side: "deletions" };
396 }
397 return null;
398}
399
400export function restoreDiffReviewCommentRange(
401 fileDiff: FileDiffMetadata,
402 comment: ReviewCommentContext,
403): SelectedLineRange | null {
404 if (comment.selection) return comment.selection;
405
406 const includeExpandedContext = !fileDiff.isPartial;
407 const startLine = buildDiffReviewLines(fileDiff, includeExpandedContext, {
408 startIndex: comment.startIndex,
409 endIndex: comment.startIndex,
410 })[0];
411 const endLine =
412 comment.endIndex === comment.startIndex
413 ? startLine
414 : buildDiffReviewLines(fileDiff, includeExpandedContext, {
415 startIndex: comment.endIndex,
416 endIndex: comment.endIndex,
417 })[0];
418 if (!startLine || !endLine) return null;
419 const start = getDiffReviewSelectionPoint(startLine);
420 const end = getDiffReviewSelectionPoint(endLine);
421 if (!start || !end) return null;
422 return {
423 start: start.lineNumber,
424 side: start.side,
425 end: end.lineNumber,
426 endSide: end.side,
427 };
428}
429
430function findDiffReviewLineIndex(
431 fileDiff: FileDiffMetadata,
432 lineNumber: number,
433 side: SelectionSide | undefined,
434 includeExpandedContext = !fileDiff.isPartial,
435): number {
436 const findOnSide = (selectedSide: "left" | "right") => {
437 let rowIndex = 0;
438 let oldContextStart = 1;
439 let newContextStart = 1;
440 const findContextIndex = (oldStart: number, newStart: number, lineCount: number) => {
441 const count = Math.max(0, lineCount);
442 const selectedStart = selectedSide === "left" ? oldStart : newStart;
443 const offset = lineNumber - selectedStart;
444 return offset >= 0 && offset < count ? rowIndex + offset : -1;
445 };
446
447 for (const hunk of fileDiff.hunks) {
448 if (includeExpandedContext) {
449 const oldContextEnd = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);
450 const newContextEnd = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);
451 const contextLines = Math.min(
452 oldContextEnd - oldContextStart,
453 newContextEnd - newContextStart,
454 );
455 const contextIndex = findContextIndex(oldContextStart, newContextStart, contextLines);
456 if (contextIndex >= 0) return contextIndex;
457 rowIndex += Math.max(0, contextLines);
458 }
459
460 let oldLineNumber = hunk.deletionStart;
461 let newLineNumber = hunk.additionStart;
462 for (const segment of hunk.hunkContent) {
463 if (segment.type === "context") {
464 const contextIndex = findContextIndex(oldLineNumber, newLineNumber, segment.lines);
465 if (contextIndex >= 0) return contextIndex;
466 rowIndex += segment.lines;
467 oldLineNumber += segment.lines;
468 newLineNumber += segment.lines;
469 continue;
470 }
471
472 if (
473 selectedSide === "left" &&
474 lineNumber >= oldLineNumber &&
475 lineNumber < oldLineNumber + segment.deletions
476 ) {
477 return rowIndex + lineNumber - oldLineNumber;
478 }
479 rowIndex += segment.deletions;
480 oldLineNumber += segment.deletions;
481
482 if (
483 selectedSide === "right" &&
484 lineNumber >= newLineNumber &&
485 lineNumber < newLineNumber + segment.additions
486 ) {
487 return rowIndex + lineNumber - newLineNumber;
488 }
489 rowIndex += segment.additions;
490 newLineNumber += segment.additions;
491 }
492
493 oldContextStart = hunk.deletionStart + hunk.deletionCount;
494 newContextStart = hunk.additionStart + hunk.additionCount;
495 if (hunk.deletionCount === 0) oldContextStart += 1;
496 if (hunk.additionCount === 0) newContextStart += 1;
497 }
498
499 if (!includeExpandedContext) return -1;
500 const trailingLines = Math.min(
501 fileDiff.deletionLines.length - oldContextStart + 1,
502 fileDiff.additionLines.length - newContextStart + 1,
503 );
504 return findContextIndex(oldContextStart, newContextStart, trailingLines);
505 };
506
507 const selectedSide = side === "deletions" ? "left" : "right";
508 const preferredIndex = findOnSide(selectedSide);
509 return preferredIndex >= 0
510 ? preferredIndex
511 : findOnSide(selectedSide === "left" ? "right" : "left");
512}
513
514/** Resolve the host-facing coordinates of a line selected in the diff viewer. */
515export function resolveDiffReviewPosition(
516 fileDiff: FileDiffMetadata,
517 lineNumber: number,
518 side: SelectionSide | undefined,
519): PullRequestReviewPosition | null {
520 const lineIndex = findDiffReviewLineIndex(fileDiff, lineNumber, side);
521 if (lineIndex < 0) return null;
522 const line = buildDiffReviewLines(fileDiff, !fileDiff.isPartial, {
523 startIndex: lineIndex,
524 endIndex: lineIndex,
525 })[0];
526 if (line === undefined) return null;
527
528 switch (line.change) {
529 case "add":
530 return line.newLineNumber === null ? null : { kind: "added", newLine: line.newLineNumber };
531 case "delete":
532 return line.oldLineNumber === null ? null : { kind: "deleted", oldLine: line.oldLineNumber };
533 case "context":
534 return line.oldLineNumber === null || line.newLineNumber === null
535 ? null
536 : {
537 kind: "context",
538 oldLine: line.oldLineNumber,
539 newLine: line.newLineNumber,
540 side: side === "deletions" ? "left" : "right",
541 };
542 }
543}
544
545function getDiffRange(
546 lines: ReadonlyArray<DiffReviewLine>,
547 key: "oldLineNumber" | "newLineNumber",
548): { start: number; count: number } {
549 const numberedLines = lines.filter((line) => line[key] !== null);
550 return {
551 start: numberedLines[0]?.[key] ?? 0,
552 count: numberedLines.length,
553 };
554}
555
556function getDiffChangeMarker(change: DiffReviewLine["change"]): string {
557 if (change === "add") return "+";
558 if (change === "delete") return "-";
559 return " ";
560}
561
562function formatDiffReviewRangeLabel(lines: ReadonlyArray<DiffReviewLine>): string {
563 const firstLine = lines[0];
564 const lastLine = lines.at(-1);
565 if (!firstLine || !lastLine) return "line";
566 const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
567 const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
568 if (firstNumber === null || lastNumber === null) {
569 return lines.length === 1 ? "line" : `${lines.length} lines`;
570 }
571
572 const firstMarker = getDiffChangeMarker(firstLine.change).trim();
573 const marker =
574 firstMarker.length > 0 && lines.every((line) => line.change === firstLine.change)
575 ? firstMarker
576 : "";
577 return firstNumber === lastNumber
578 ? `${marker}${firstNumber}`
579 : `${marker}${firstNumber} to ${marker}${lastNumber}`;
580}
581
582export function buildDiffReviewComment(input: {
583 id: string;
584 sectionId: string;
585 sectionTitle: string;
586 filePath: string;
587 fileDiff: FileDiffMetadata;
588 range: SelectedLineRange;
589 text: string;
590}): ReviewCommentContext | null {
591 const includeExpandedContext = !input.fileDiff.isPartial;
592 const startIndex = findDiffReviewLineIndex(
593 input.fileDiff,
594 input.range.start,
595 input.range.side,
596 includeExpandedContext,
597 );
598 const endIndex = findDiffReviewLineIndex(
599 input.fileDiff,
600 input.range.end,
601 input.range.endSide ?? input.range.side,
602 includeExpandedContext,
603 );
604 if (startIndex < 0 || endIndex < 0) return null;
605
606 const normalizedStartIndex = Math.min(startIndex, endIndex);
607 const normalizedEndIndex = Math.max(startIndex, endIndex);
608 const selectedLines = buildDiffReviewLines(input.fileDiff, includeExpandedContext, {
609 startIndex: normalizedStartIndex,
610 endIndex: normalizedEndIndex,
611 });
612 const oldRange = getDiffRange(selectedLines, "oldLineNumber");
613 const newRange = getDiffRange(selectedLines, "newLineNumber");
614
615 return {
616 id: input.id,
617 sectionId: input.sectionId,
618 sectionTitle: input.sectionTitle,
619 filePath: input.filePath,
620 startIndex: normalizedStartIndex,
621 endIndex: normalizedEndIndex,
622 rangeLabel: formatDiffReviewRangeLabel(selectedLines),
623 text: input.text.trim(),
624 diff: [
625 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
626 ...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),
627 ].join("\n"),
628 fenceLanguage: "diff",
629 selection: {
630 start: input.range.start,
631 side: input.range.side ?? "additions",
632 end: input.range.end,
633 endSide: input.range.endSide ?? input.range.side ?? "additions",
634 },
635 };
636}
637
638export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
639 if ((comment.fenceLanguage ?? "diff") !== "diff") {
640 return "";
641 }
642 const diff = comment.diff.trim();
643 if (diff.length === 0) {
644 return "";
645 }
646 if (diff.startsWith("diff --git ")) {
647 return diff;
648 }
649
650 const normalizedPath = comment.filePath.replaceAll("\\", "/");
651 return [
652 `diff --git a/${normalizedPath} b/${normalizedPath}`,
653 `--- a/${normalizedPath}`,
654 `+++ b/${normalizedPath}`,
655 diff,
656 ].join("\n");
657}