/ opencodehub / src / lib / suggestions.ts
swadhinbiswas feat: OpenCodeHub v1.1.0 - Enterprise Features & Storage Adapters · 2/15/2026
719a1cb
319 lines · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/**
 * Suggested Changes Library
 * Parse, render, and apply code suggestions from review comments
 */

import { getDatabase, schema } from "@/db";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { eq } from "drizzle-orm";
import { logger } from "./logger";
import { generateId } from "./utils";

/**
 * Parse suggestion from comment body
 * GitHub-style: ```suggestion ... ```
 */
export function parseSuggestion(commentBody: string): {
    hasSuggestion: boolean;
    suggestionContent: string | null;
    textBeforeSuggestion: string;
    textAfterSuggestion: string;
} {
    const suggestionRegex = /```suggestion\n([\s\S]*?)```/g;
    const match = suggestionRegex.exec(commentBody);

    if (!match) {
        return {
            hasSuggestion: false,
            suggestionContent: null,
            textBeforeSuggestion: commentBody,
            textAfterSuggestion: "",
        };
    }

    const suggestionContent = match[1];
    const textBeforeSuggestion = commentBody.slice(0, match.index).trim();
    const textAfterSuggestion = commentBody.slice(match.index + match[0].length).trim();

    return {
        hasSuggestion: true,
        suggestionContent,
        textBeforeSuggestion,
        textAfterSuggestion,
    };
}

/**
 * Create a comment with a suggestion
 */
export async function createSuggestionComment(options: {
    pullRequestId: string;
    authorId: string;
    path: string;
    line: number;
    startLine?: number;
    side?: "LEFT" | "RIGHT";
    commitSha: string;
    suggestionContent: string;
    body?: string;
    reviewId?: string;
}): Promise<string> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const id = generateId();

    // Format body with suggestion block
    const formattedBody = options.body
        ? `${options.body}\n\n\`\`\`suggestion\n${options.suggestionContent}\`\`\``
        : `\`\`\`suggestion\n${options.suggestionContent}\`\`\``;

    await db.insert(schema.pullRequestComments).values({
        id,
        pullRequestId: options.pullRequestId,
        authorId: options.authorId,
        reviewId: options.reviewId,
        path: options.path,
        line: options.line,
        startLine: options.startLine,
        side: options.side || "RIGHT",
        commitSha: options.commitSha,
        body: formattedBody,
        suggestionContent: options.suggestionContent,
        createdAt: new Date(),
        updatedAt: new Date(),
    });

    logger.info({ commentId: id, pullRequestId: options.pullRequestId }, "Created suggestion comment");
    return id;
}

/**
 * Apply a suggestion to the PR branch
 */
export async function applySuggestion(
    commentId: string,
    appliedById: string
): Promise<{ success: boolean; commitSha?: string; error?: string }> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    // Get comment with suggestion
    const comment = await db.query.pullRequestComments.findFirst({
        where: eq(schema.pullRequestComments.id, commentId),
        with: {
            pullRequest: {
                with: {
                    repository: true,
                },
            },
        },
    });

    if (!comment) {
        return { success: false, error: "Comment not found" };
    }

    if (!comment.suggestionContent) {
        return { success: false, error: "Comment has no suggestion" };
    }

    if (comment.suggestionApplied) {
        return { success: false, error: "Suggestion already applied" };
    }

    if (!comment.path || !comment.line) {
        return { success: false, error: "Comment missing file path or line number" };
    }

    const pr = comment.pullRequest;
    if (!pr || !pr.repository) {
        return { success: false, error: "Pull request or repository not found" };
    }

    try {
        // Import git functions dynamically
        const { resolveRepoPath } = await import("./git-storage");
        const { getFileContent, getGit } = await import("./git");

        const repoPath = await resolveRepoPath(pr.repository.diskPath);

        // Get current file content
        const fileResult = await getFileContent(repoPath, comment.path, pr.headBranch);
        if (!fileResult) {
            return { success: false, error: "File not found" };
        }

        const lines = fileResult.content.split("\n");
        const startLine = comment.startLine || comment.line;
        const endLine = comment.line;

        // Validate line numbers
        if (startLine < 1 || endLine > lines.length) {
            return { success: false, error: "Invalid line numbers" };
        }

        // Apply the suggestion
        const newLines = [
            ...lines.slice(0, startLine - 1),
            ...comment.suggestionContent.split("\n"),
            ...lines.slice(endLine),
        ];

        const newContent = newLines.join("\n");

        // Create a working copy and apply changes
        const git = getGit(repoPath);
        const tempPath = `${repoPath}.worktree`;

        // Use git worktree for applying changes
        const fs = await import("fs/promises");
        const path = await import("path");

        // Clone to temp for modification
        await fs.mkdir(tempPath, { recursive: true });
        const workGit = (await import("simple-git")).simpleGit(tempPath);
        await workGit.clone(repoPath, tempPath, ["--branch", pr.headBranch]);

        // Write the modified file
        const filePath = path.join(tempPath, comment.path);
        await fs.mkdir(path.dirname(filePath), { recursive: true });
        await fs.writeFile(filePath, newContent);

        // Get user info for commit
        const user = await db.query.users.findFirst({
            where: eq(schema.users.id, appliedById),
        });

        // Commit the change
        await workGit.addConfig("user.name", user?.displayName || "OpenCodeHub");
        await workGit.addConfig("user.email", user?.email || "[email protected]");
        await workGit.add(comment.path);

        // Get PR author for co-author attribution
        const prAuthor = await db.query.users.findFirst({
            where: eq(schema.users.id, pr.authorId),
        });

        const commitMessage = `Apply suggestion from code review\n\nCo-authored-by: ${prAuthor?.username || "reviewer"} <[email protected]>`;
        await workGit.commit(commitMessage);

        // Push to the branch
        await workGit.push("origin", pr.headBranch);

        // Get new commit SHA
        const log = await workGit.log({ n: 1 });
        const newCommitSha = log.latest?.hash || "";

        // Update comment as applied
        await db
            .update(schema.pullRequestComments)
            .set({
                suggestionApplied: true,
                suggestionAppliedById: appliedById,
                suggestionAppliedAt: new Date(),
                suggestionCommitSha: newCommitSha,
                updatedAt: new Date(),
            })
            .where(eq(schema.pullRequestComments.id, commentId));

        // Update PR head SHA
        await db
            .update(schema.pullRequests)
            .set({
                headSha: newCommitSha,
                updatedAt: new Date(),
            })
            .where(eq(schema.pullRequests.id, pr.id));

        // Cleanup temp directory
        await fs.rm(tempPath, { recursive: true, force: true });

        logger.info({ commentId, commitSha: newCommitSha }, "Suggestion applied");
        return { success: true, commitSha: newCommitSha };

    } catch (error) {
        logger.error({ error, commentId }, "Failed to apply suggestion");
        return {
            success: false,
            error: error instanceof Error ? error.message : "Failed to apply suggestion"
        };
    }
}

/**
 * Batch apply multiple suggestions
 */
export async function batchApplySuggestions(
    commentIds: string[],
    appliedById: string
): Promise<{
    success: boolean;
    applied: string[];
    failed: { id: string; error: string }[];
    commitSha?: string;
}> {
    const applied: string[] = [];
    const failed: { id: string; error: string }[] = [];

    // Apply suggestions one by one
    // Note: In a production system, you'd want to batch these into a single commit
    for (const commentId of commentIds) {
        const result = await applySuggestion(commentId, appliedById);
        if (result.success) {
            applied.push(commentId);
        } else {
            failed.push({ id: commentId, error: result.error || "Unknown error" });
        }
    }

    return {
        success: failed.length === 0,
        applied,
        failed,
    };
}

/**
 * Check if user can apply suggestions to a PR
 */
export async function canApplySuggestions(
    userId: string,
    pullRequestId: string
): Promise<boolean> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const pr = await db.query.pullRequests.findFirst({
        where: eq(schema.pullRequests.id, pullRequestId),
        with: {
            repository: true,
        },
    });

    if (!pr) return false;

    // PR author can apply suggestions
    if (pr.authorId === userId) return true;

    // Repository owner can apply
    if (pr.repository?.ownerId === userId) return true;

    // Check if user has write access
    const { canWriteRepo } = await import("./permissions");
    return canWriteRepo(userId, pr.repository!);
}

/**
 * Get pending suggestions for a PR
 */
export async function getPendingSuggestions(pullRequestId: string) {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const comments = await db.query.pullRequestComments.findMany({
        where: eq(schema.pullRequestComments.pullRequestId, pullRequestId),
        with: {
            author: true,
        },
    });

    return comments.filter(c => c.suggestionContent && !c.suggestionApplied);
}