Swadhin Biswas Feature/ai code reviewer (#73) · 8/2/2026
105a287
240 lines · 7.5 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
/**
 * Stacks API
 * Create and manage stacked PRs
 */

import type { APIRoute } from "astro";
import { eq, and, desc } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { getDatabase, schema } from "@/db";
import { getUserFromRequest } from "@/lib/auth";
import { canWriteRepo } from "@/lib/permissions";
import { compareBranches, getCommit } from "@/lib/git";
import { resolveRepoPath } from "@/lib/git-storage";
import { parseBody, success } from "@/lib/api";
import { withErrorHandler, Errors } from "@/lib/errors";
import { logger } from "@/lib/logger";
import { z } from "zod";
import crypto from "crypto";

const createStackSchema = z.object({
    repositoryId: z.string().optional(),
    owner: z.string().optional(),
    repo: z.string().optional(),
    baseBranch: z.string().default("main"),
    name: z.string().optional(),
    branches: z.array(z.object({
        name: z.string(),
        title: z.string(),
        description: z.string().optional(),
        parentBranch: z.string().optional(),
    })),
}).refine(data => data.repositoryId || (data.owner && data.repo), {
    message: "Either repositoryId or owner and repo must be provided",
});


// GET /api/stacks - List user's stacks
export const GET: APIRoute = withErrorHandler(async ({ request }) => {
    const tokenPayload = await getUserFromRequest(request);
    if (!tokenPayload) {
        throw Errors.unauthorized();
    }

    const url = new URL(request.url);
    const repoId = url.searchParams.get("repositoryId");

    const db = getDatabase() as NodePgDatabase<typeof schema>;

    let stacks;
    if (repoId) {
        stacks = await db.query.prStacks.findMany({
            where: and(
                eq(schema.prStacks.repositoryId, repoId),
                eq(schema.prStacks.createdById, tokenPayload.userId)
            ),
            with: {
                entries: {
                    with: {
                        pullRequest: true,
                    },
                    orderBy: (e, { asc }) => [asc(e.stackOrder)],
                },
            },
            orderBy: [desc(schema.prStacks.updatedAt)],
        });
    } else {
        stacks = await db.query.prStacks.findMany({
            where: eq(schema.prStacks.createdById, tokenPayload.userId),
            with: {
                repository: true,
                entries: {
                    with: {
                        pullRequest: true,
                    },
                    orderBy: (e, { asc }) => [asc(e.stackOrder)],
                },
            },
            orderBy: [desc(schema.prStacks.updatedAt)],
        });
    }

    return success({ stacks });
});

// POST /api/stacks - Create a new stack with PRs
export const POST: APIRoute = withErrorHandler(async ({ request }) => {
    const tokenPayload = await getUserFromRequest(request);
    if (!tokenPayload) {
        throw Errors.unauthorized();
    }

    const parsed = await parseBody(request, createStackSchema);
    if ("error" in parsed) return parsed.error;

    const { name, branches } = parsed.data;
    const baseBranch = parsed.data.baseBranch || "main";
    let repositoryId = parsed.data.repositoryId;

    const db = getDatabase() as NodePgDatabase<typeof schema>;

    // Find repo by owner/name if only provided
    if (!repositoryId && parsed.data.owner && parsed.data.repo) {
        const ownerUser = await db.query.users.findFirst({
            where: eq(schema.users.username, parsed.data.owner),
        });

        if (ownerUser) {
            const repo = await db.query.repositories.findFirst({
                where: and(
                    eq(schema.repositories.ownerId, ownerUser.id),
                    eq(schema.repositories.name, parsed.data.repo)
                ),
            });
            if (repo) {
                repositoryId = repo.id;
            }
        }
    }

    if (!repositoryId) {
        throw Errors.notFound("Repository not found");
    }

    // Verify repository exists and user has access
    const repo = await db.query.repositories.findFirst({
        where: eq(schema.repositories.id, repositoryId),
    });

    if (!repo) {
        throw Errors.notFound("Repository not found");
    }

    if (!(await canWriteRepo(tokenPayload.userId, repo, { isAdmin: tokenPayload.isAdmin }))) {
        throw Errors.forbidden();
    }

    const repoPath = await resolveRepoPath(repo.diskPath);
    const lastPr = await db.query.pullRequests.findFirst({
        where: eq(schema.pullRequests.repositoryId, repositoryId),
        orderBy: [desc(schema.pullRequests.number)],
    });
    let nextPrNumber = (lastPr?.number || 0) + 1;

    const now = new Date();
    const stackId = `stack_${crypto.randomBytes(8).toString("hex")}`;

    // Create the stack
    await db.insert(schema.prStacks).values({
        id: stackId,
        repositoryId,
        baseBranch,
        name: name || `Stack ${stackId.slice(-6)}`,
        status: "active",
        createdById: tokenPayload.userId,
        createdAt: now,
        updatedAt: now,
    });

    // Create PRs for each branch
    const createdPRs: any[] = [];
    let parentPrId: string | null = null;
    let stackOrder = 1;

    for (const branch of branches) {
        const prId = `pr_${crypto.randomBytes(8).toString("hex")}`;
        const prNumber = nextPrNumber++;
        const prBaseBranch = branch.parentBranch || baseBranch;

        const headCommit = await getCommit(repoPath, branch.name);
        if (!headCommit) {
            throw Errors.badRequest(`Head branch ${branch.name} not found`);
        }

        const baseCommit = await getCommit(repoPath, prBaseBranch);
        if (!baseCommit) {
            throw Errors.badRequest(`Base branch ${prBaseBranch} not found`);
        }

        const { diffs } = await compareBranches(repoPath, prBaseBranch, branch.name);
        const additions = diffs.reduce((sum, diff) => sum + diff.additions, 0);
        const deletions = diffs.reduce((sum, diff) => sum + diff.deletions, 0);
        const changedFiles = diffs.length;

        // Create the PR with required schema fields
        await db.insert(schema.pullRequests).values({
            id: prId,
            repositoryId,
            number: prNumber,
            title: branch.title,
            body: branch.description || "",
            state: "open",
            authorId: tokenPayload.userId,
            headBranch: branch.name,
            headSha: headCommit.sha,
            baseBranch: prBaseBranch,
            baseSha: baseCommit.sha,
            additions,
            deletions,
            changedFiles,
            isDraft: false,
            createdAt: now,
            updatedAt: now,
        });

        // Add to stack
        await db.insert(schema.prStackEntries).values({
            id: `se_${crypto.randomBytes(8).toString("hex")}`,
            stackId,
            pullRequestId: prId,
            stackOrder,
            parentPrId,
            createdAt: now,
        });

        createdPRs.push({
            id: prId,
            number: prNumber,
            title: branch.title,
            branch: branch.name,
            baseBranch: prBaseBranch,
            stackOrder,
        });

        parentPrId = prId;
        stackOrder++;
    }

    logger.info({ stackId, userId: tokenPayload.userId }, "Stacked PR created");

    return success({
        stack: {
            id: stackId,
            name: name || `Stack ${stackId.slice(-6)}`,
            baseBranch,
            pullRequests: createdPRs,
        },
        message: `Created stack with ${createdPRs.length} PRs`,
    });
});