Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

reviewCommentContext.ts

470 lines14.8 KB

1import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";
2import * as Schema from "effect/Schema";
3​
4export const ReviewCommentContextSchema = Schema.Struct({
5 id: Schema.String,
6 sectionId: Schema.String,
7 sectionTitle: Schema.String,
8 filePath: Schema.String,
9 startIndex: Schema.Number,
10 endIndex: Schema.Number,
11 rangeLabel: Schema.String,
12 text: Schema.String,
13 diff: Schema.String,
14 fenceLanguage: Schema.optional(Schema.String),
15});
16​
17export interface ReviewCommentContext {
18 readonly id: string;
19 readonly sectionId: string;
20 readonly sectionTitle: string;
21 readonly filePath: string;
22 readonly startIndex: number;
23 readonly endIndex: number;
24 readonly rangeLabel: string;
25 readonly text: string;
26 readonly diff: string;
27 readonly fenceLanguage?: string | undefined;
29​
30interface DiffReviewLine {
31 readonly change: "context" | "add" | "delete";
32 readonly oldLineNumber: number | null;
33 readonly newLineNumber: number | null;
34 readonly content: string;
36​
37export type ReviewCommentMessageSegment =
38 | {
39 readonly kind: "text";
40 readonly id: string;
41 readonly text: string;
42 }
43 | {
44 readonly kind: "review-comment";
45 readonly comment: ReviewCommentContext;
46 };
47​
48const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
49const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
50const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
51​
52function escapeReviewCommentAttribute(value: string): string {
53 return value
54 .replace(/&/g, "&amp;")
55 .replace(/"/g, "&quot;")
56 .replace(/</g, "&lt;")
57 .replace(/>/g, "&gt;");
59​
60function unescapeReviewCommentAttribute(value: string): string {
61 return value
62 .replace(/&lt;/g, "<")
63 .replace(/&gt;/g, ">")
64 .replace(/&quot;/g, '"')
65 .replace(/&amp;/g, "&");
67​
68function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
69 const attributes: Record<string, string> = {};
70 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
71 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
72 }
73 return attributes;
75​
76function readNonNegativeInteger(value: string | undefined): number | null {
77 if (value === undefined || !/^\d+$/.test(value)) {
78 return null;
79 }
80 return Number(value);
82​
83function extractReviewCommentBody(rawBody: string): {
84 text: string;
85 language: string;
86 contents: string;
87} {
88 const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
89 const match = matches.at(-1);
90 const fenceIndex = match?.index;
91 return {
92 text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
93 language: match?.[2]?.trim() || "diff",
94 contents: match?.[3] ?? "",
95 };
97​
98function parseReviewCommentContext(
99 rawAttributes: string,
100 rawBody: string,
101 index: number,
102): ReviewCommentContext | null {
103 const attributes = readReviewCommentAttributes(rawAttributes);
104 const startIndex = readNonNegativeInteger(attributes.startIndex);
105 const endIndex = readNonNegativeInteger(attributes.endIndex);
106 const filePath = attributes.filePath?.trim();
107 const sectionId = attributes.sectionId?.trim();
108 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
109 return null;
110 }
111 const body = extractReviewCommentBody(rawBody);
112​
113 return {
114 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
115 sectionId,
116 sectionTitle: attributes.sectionTitle?.trim() || "Review",
117 filePath,
118 startIndex: Math.min(startIndex, endIndex),
119 endIndex: Math.max(startIndex, endIndex),
120 rangeLabel: attributes.rangeLabel?.trim() || "line",
121 text: body.text,
122 diff: body.contents,
123 fenceLanguage: body.language,
124 };
126​
127export function parseReviewCommentMessageSegments(
128 value: string,
129): ReadonlyArray<ReviewCommentMessageSegment> {
130 const segments: ReviewCommentMessageSegment[] = [];
131 let cursor = 0;
132 let parsedCommentIndex = 0;
133​
134 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
135 const matchIndex = match.index ?? 0;
136 const beforeText = value.slice(cursor, matchIndex);
137 if (beforeText.length > 0) {
138 segments.push({
139 kind: "text",
140 id: `review-comment-text:${cursor}`,
141 text: beforeText,
142 });
143 }
144​
145 const comment = parseReviewCommentContext(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
146 if (comment) {
147 segments.push({ kind: "review-comment", comment });
148 parsedCommentIndex += 1;
149 } else {
150 segments.push({
151 kind: "text",
152 id: `review-comment-invalid:${matchIndex}`,
153 text: match[0],
154 });
155 }
156​
157 cursor = matchIndex + match[0].length;
158 }
159​
160 const rest = value.slice(cursor);
161 if (rest.length > 0) {
162 segments.push({
163 kind: "text",
164 id: `review-comment-text:${cursor}`,
165 text: rest,
166 });
167 }
168​
169 return segments;
171​
172export function hasReviewCommentMessageSegments(value: string): boolean {
173 return parseReviewCommentMessageSegments(value).some(
174 (segment) => segment.kind === "review-comment",
175 );
177​
178export function formatReviewCommentFence(language: string, contents: string): string {
179 const longestBacktickRun = Math.max(
180 0,
181 ...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
182 );
183 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
184 return [`${fence}${language}`, contents.trimEnd(), fence].join("\n");
186​
187/**
188 * Keeps a comment's own words from closing the block they travel in. The parser ends an
189 * attachment at the first `</review_comment>`, so text carrying one would spill the rest of
190 * itself into the prompt — and could open a forged attachment naming any file it liked. Only
191 * ever the local reader's words before, but a pull request's review bodies come from whoever
192 * wrote them.
193 */
194function neutralizeReviewCommentTags(text: string): string {
195 return text.replace(/<(?=\/?review_comment\b)/giu, "&lt;");
197​
198export function formatReviewCommentContext(comment: ReviewCommentContext): string {
199 return [
200 [
201 "<review_comment",
202 ` sectionId="${escapeReviewCommentAttribute(comment.sectionId)}"`,
203 ` sectionTitle="${escapeReviewCommentAttribute(comment.sectionTitle)}"`,
204 ` filePath="${escapeReviewCommentAttribute(comment.filePath)}"`,
205 ` startIndex="${comment.startIndex}"`,
206 ` endIndex="${comment.endIndex}"`,
207 ` rangeLabel="${escapeReviewCommentAttribute(comment.rangeLabel)}"`,
208 ">",
209 ].join(""),
210 neutralizeReviewCommentTags(comment.text.trim()),
211 formatReviewCommentFence(comment.fenceLanguage ?? "diff", comment.diff),
212 "</review_comment>",
213 ].join("\n");
215​
216export function appendReviewCommentsToPrompt(
217 prompt: string,
218 comments: ReadonlyArray<ReviewCommentContext>,
219): string {
220 const blocks = comments.map(formatReviewCommentContext);
221 if (blocks.length === 0) return prompt;
222 const trimmedPrompt = prompt.trim();
223 return trimmedPrompt.length > 0
224 ? `${trimmedPrompt}\n\n${blocks.join("\n\n")}`
225 : blocks.join("\n\n");
227​
228export function buildFileReviewComment(input: {
229 id: string;
230 filePath: string;
231 startLine: number;
232 endLine: number;
233 text: string;
234 contents: string;
235}): ReviewCommentContext {
236 const startLine = Math.max(1, Math.min(input.startLine, input.endLine));
237 const endLine = Math.max(startLine, Math.max(input.startLine, input.endLine));
238 const selectedLines = input.contents.split("\n").slice(startLine - 1, endLine);
239 return {
240 id: input.id,
241 sectionId: `file:${input.filePath}`,
242 sectionTitle: "File comment",
243 filePath: input.filePath,
244 startIndex: startLine - 1,
245 endIndex: endLine - 1,
246 rangeLabel: startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`,
247 text: input.text.trim(),
248 diff: selectedLines.join("\n"),
249 fenceLanguage: inferReviewCommentFenceLanguage(input.filePath),
250 };
252​
253export function inferReviewCommentFenceLanguage(filePath: string): string {
254 const normalizedPath = filePath.replaceAll("\\", "/");
255 const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1).toLowerCase();
256 const extensionIndex = fileName.lastIndexOf(".");
257 if (extensionIndex > 0 && extensionIndex < fileName.length - 1) {
258 return fileName.slice(extensionIndex + 1);
259 }
260 if (fileName.startsWith(".") && fileName.length > 1) {
261 return fileName.slice(1);
262 }
263 return "text";
265​
266function stripTrailingNewline(value: string): string {
267 return value.endsWith("\n") ? value.slice(0, -1) : value;
269​
270function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffReviewLine> {
271 const rows: DiffReviewLine[] = [];
272​
273 for (const hunk of fileDiff.hunks) {
274 let oldLineNumber = hunk.deletionStart;
275 let newLineNumber = hunk.additionStart;
276 let deletionLineIndex = hunk.deletionLineIndex;
277 let additionLineIndex = hunk.additionLineIndex;
278​
279 for (const segment of hunk.hunkContent) {
280 if (segment.type === "context") {
281 for (let index = 0; index < segment.lines; index += 1) {
282 rows.push({
283 change: "context",
284 oldLineNumber,
285 newLineNumber,
286 content: stripTrailingNewline(
287 fileDiff.additionLines[additionLineIndex] ??
288 fileDiff.deletionLines[deletionLineIndex] ??
289 "",
290 ),
291 });
292 oldLineNumber += 1;
293 newLineNumber += 1;
294 deletionLineIndex += 1;
295 additionLineIndex += 1;
296 }
297 continue;
298 }
299​
300 for (let index = 0; index < segment.deletions; index += 1) {
301 rows.push({
302 change: "delete",
303 oldLineNumber,
304 newLineNumber: null,
305 content: stripTrailingNewline(fileDiff.deletionLines[deletionLineIndex] ?? ""),
306 });
307 oldLineNumber += 1;
308 deletionLineIndex += 1;
309 }
310​
311 for (let index = 0; index < segment.additions; index += 1) {
312 rows.push({
313 change: "add",
314 oldLineNumber: null,
315 newLineNumber,
316 content: stripTrailingNewline(fileDiff.additionLines[additionLineIndex] ?? ""),
317 });
318 newLineNumber += 1;
319 additionLineIndex += 1;
320 }
321 }
322 }
323​
324 return rows;
326​
327function getDiffReviewSelectionPoint(
328 line: DiffReviewLine,
329): { lineNumber: number; side: SelectionSide } | null {
330 if (line.change === "delete" && line.oldLineNumber !== null) {
331 return { lineNumber: line.oldLineNumber, side: "deletions" };
332 }
333 if (line.newLineNumber !== null) {
334 return { lineNumber: line.newLineNumber, side: "additions" };
335 }
336 if (line.oldLineNumber !== null) {
337 return { lineNumber: line.oldLineNumber, side: "deletions" };
338 }
339 return null;
341​
342export function restoreDiffReviewCommentRange(
343 fileDiff: FileDiffMetadata,
344 comment: ReviewCommentContext,
345): SelectedLineRange | null {
346 const lines = buildDiffReviewLines(fileDiff);
347 const startLine = lines[comment.startIndex];
348 const endLine = lines[comment.endIndex];
349 if (!startLine || !endLine) return null;
350 const start = getDiffReviewSelectionPoint(startLine);
351 const end = getDiffReviewSelectionPoint(endLine);
352 if (!start || !end) return null;
353 return {
354 start: start.lineNumber,
355 side: start.side,
356 end: end.lineNumber,
357 endSide: end.side,
358 };
360​
361function findDiffReviewLineIndex(
362 lines: ReadonlyArray<DiffReviewLine>,
363 lineNumber: number,
364 side: SelectionSide | undefined,
365): number {
366 const preferredKey = side === "deletions" ? "oldLineNumber" : "newLineNumber";
367 const preferredIndex = lines.findIndex((line) => line[preferredKey] === lineNumber);
368 if (preferredIndex >= 0) return preferredIndex;
369 const fallbackKey = preferredKey === "oldLineNumber" ? "newLineNumber" : "oldLineNumber";
370 return lines.findIndex((line) => line[fallbackKey] === lineNumber);
372​
373function getDiffRange(
374 lines: ReadonlyArray<DiffReviewLine>,
375 key: "oldLineNumber" | "newLineNumber",
376): { start: number; count: number } {
377 const numberedLines = lines.filter((line) => line[key] !== null);
378 return {
379 start: numberedLines[0]?.[key] ?? 0,
380 count: numberedLines.length,
381 };
383​
384function getDiffChangeMarker(change: DiffReviewLine["change"]): string {
385 if (change === "add") return "+";
386 if (change === "delete") return "-";
387 return " ";
389​
390function formatDiffReviewRangeLabel(lines: ReadonlyArray<DiffReviewLine>): string {
391 const firstLine = lines[0];
392 const lastLine = lines.at(-1);
393 if (!firstLine || !lastLine) return "line";
394 const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
395 const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
396 if (firstNumber === null || lastNumber === null) {
397 return lines.length === 1 ? "line" : `${lines.length} lines`;
398 }
399​
400 const firstMarker = getDiffChangeMarker(firstLine.change).trim();
401 const marker =
402 firstMarker.length > 0 && lines.every((line) => line.change === firstLine.change)
403 ? firstMarker
404 : "";
405 return firstNumber === lastNumber
406 ? `${marker}${firstNumber}`
407 : `${marker}${firstNumber} to ${marker}${lastNumber}`;
409​
410export function buildDiffReviewComment(input: {
411 id: string;
412 sectionId: string;
413 sectionTitle: string;
414 filePath: string;
415 fileDiff: FileDiffMetadata;
416 range: SelectedLineRange;
417 text: string;
418}): ReviewCommentContext | null {
419 const lines = buildDiffReviewLines(input.fileDiff);
420 const startIndex = findDiffReviewLineIndex(lines, input.range.start, input.range.side);
421 const endIndex = findDiffReviewLineIndex(
422 lines,
423 input.range.end,
424 input.range.endSide ?? input.range.side,
425 );
426 if (startIndex < 0 || endIndex < 0) return null;
427​
428 const normalizedStartIndex = Math.min(startIndex, endIndex);
429 const normalizedEndIndex = Math.max(startIndex, endIndex);
430 const selectedLines = lines.slice(normalizedStartIndex, normalizedEndIndex + 1);
431 const oldRange = getDiffRange(selectedLines, "oldLineNumber");
432 const newRange = getDiffRange(selectedLines, "newLineNumber");
433​
434 return {
435 id: input.id,
436 sectionId: input.sectionId,
437 sectionTitle: input.sectionTitle,
438 filePath: input.filePath,
439 startIndex: normalizedStartIndex,
440 endIndex: normalizedEndIndex,
441 rangeLabel: formatDiffReviewRangeLabel(selectedLines),
442 text: input.text.trim(),
443 diff: [
444 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
445 ...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),
446 ].join("\n"),
447 fenceLanguage: "diff",
448 };
450​
451export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
452 if ((comment.fenceLanguage ?? "diff") !== "diff") {
453 return "";
454 }
455 const diff = comment.diff.trim();
456 if (diff.length === 0) {
457 return "";
458 }
459 if (diff.startsWith("diff --git ")) {
460 return diff;
461 }
462​
463 const normalizedPath = comment.filePath.replaceAll("\\", "/");
464 return [
465 `diff --git a/${normalizedPath} b/${normalizedPath}`,
466 `--- a/${normalizedPath}`,
467 `+++ b/${normalizedPath}`,
468 diff,
469 ].join("\n");