Swadhin Biswas feat(api): add runner, analytics, packages, and security services · 3/6/2026
28f7954
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/**
* Bidirectional Sync Library
* Sync local Git state with remote stacks and vice versa
*/
import { logger } from "@/lib/logger";
import { eq, and, desc } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { getDatabase, schema } from "@/db";
import { simpleGit, SimpleGit } from "simple-git";
import { getStack, getStackForPr, addToStack, createStack } from "./stacks";
import { generateId } from "./utils";
// Types
export interface SyncStatus {
localBranch: string;
remoteBranch: string | null;
ahead: number;
behind: number;
hasUnpushedChanges: boolean;
hasRemoteChanges: boolean;
lastSyncedAt: Date | null;
}
export interface StackSyncResult {
success: boolean;
message: string;
syncedBranches: string[];
conflicts?: string[];
ciStatuses?: Record<string, string>;
}
export interface RemoteCIStatus {
prNumber: number;
status: "pending" | "running" | "success" | "failure";
conclusion?: string;
checkRuns: Array<{
name: string;
status: string;
conclusion?: string;
}>;
}
/**
* Get sync status for a branch
*/
export async function getBranchSyncStatus(
repoPath: string,
branchName: string
): Promise<SyncStatus> {
const git: SimpleGit = simpleGit(repoPath);
try {
// Fetch latest from remote
await git.fetch();
// Get current branch info
const status = await git.status();
const currentBranch = status.current;
// Check if branch exists on remote
const remoteBranches = await git.branch(["-r"]);
const remoteBranch = remoteBranches.all.find(
b => b === `origin/${branchName}` || b.endsWith(`/${branchName}`)
);
if (!remoteBranch) {
return {
localBranch: branchName,
remoteBranch: null,
ahead: 0,
behind: 0,
hasUnpushedChanges: true,
hasRemoteChanges: false,
lastSyncedAt: null,
};
}
// Get ahead/behind counts
const log = await git.raw([
"rev-list",
"--left-right",
"--count",
`${branchName}...origin/${branchName}`,
]);
const [ahead, behind] = log.trim().split("\t").map(Number);
return {
localBranch: branchName,
remoteBranch: `origin/${branchName}`,
ahead: ahead || 0,
behind: behind || 0,
hasUnpushedChanges: (ahead || 0) > 0,
hasRemoteChanges: (behind || 0) > 0,
lastSyncedAt: new Date(),
};
} catch (error) {
logger.error("Error getting sync status:", error);
return {
localBranch: branchName,
remoteBranch: null,
ahead: 0,
behind: 0,
hasUnpushedChanges: false,
hasRemoteChanges: false,
lastSyncedAt: null,
};
}
}
/**
* Sync local stack to remote (push all branches)
*/
export async function pushStackToRemote(
repoPath: string,
stackId: string,
force: boolean = false
): Promise<StackSyncResult> {
const git: SimpleGit = simpleGit(repoPath);
const syncedBranches: string[] = [];
const conflicts: string[] = [];
try {
const stackInfo = await getStack(stackId);
if (!stackInfo) {
return { success: false, message: "Stack not found", syncedBranches };
}
// Sort entries by stack order
const entries = [...stackInfo.entries].sort((a, b) => a.entry.stackOrder - b.entry.stackOrder);
// Push each branch in order
for (const entry of entries) {
const branchName = entry.pr.headBranch;
try {
// Check current branch
const status = await git.status();
if (status.current !== branchName) {
await git.checkout(branchName);
}
// Push to remote
const pushArgs = ["-u", "origin", branchName];
if (force) {
pushArgs.unshift("--force-with-lease");
}
await git.push(pushArgs);
syncedBranches.push(branchName);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
if (errorMessage.includes("rejected") || errorMessage.includes("non-fast-forward")) {
conflicts.push(branchName);
} else {
throw error;
}
}
}
if (conflicts.length > 0) {
return {
success: false,
message: `Some branches have conflicts: ${conflicts.join(", ")}`,
syncedBranches,
conflicts,
};
}
return {
success: true,
message: `Pushed ${syncedBranches.length} branches to remote`,
syncedBranches,
};
} catch (error) {
logger.error("Error pushing stack:", error);
return {
success: false,
message: error instanceof Error ? error.message : "Unknown error",
syncedBranches,
conflicts,
};
}
}
/**
* Pull remote changes into local stack
*/
export async function pullStackFromRemote(
repoPath: string,
stackId: string,
rebase: boolean = true
): Promise<StackSyncResult> {
const git: SimpleGit = simpleGit(repoPath);
const syncedBranches: string[] = [];
const conflicts: string[] = [];
try {
// Fetch latest
await git.fetch();
const stackInfo = await getStack(stackId);
if (!stackInfo) {
return { success: false, message: "Stack not found", syncedBranches };
}
// Sort entries by stack order (base first)
const entries = [...stackInfo.entries].sort((a, b) => a.entry.stackOrder - b.entry.stackOrder);
// Pull each branch
for (const entry of entries) {
const branchName = entry.pr.headBranch;
try {
await git.checkout(branchName);
if (rebase) {
// Rebase on remote
await git.pull(["--rebase", "origin", branchName]);
} else {
// Merge remote
await git.pull(["origin", branchName]);
}
syncedBranches.push(branchName);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "";
if (errorMessage.includes("CONFLICT") || errorMessage.includes("conflict")) {
conflicts.push(branchName);
// Abort the rebase/merge
await git.raw(["rebase", "--abort"]).catch(() => { });
await git.raw(["merge", "--abort"]).catch(() => { });
} else {
throw error;
}
}
}
if (conflicts.length > 0) {
return {
success: false,
message: `Conflicts in: ${conflicts.join(", ")}`,
syncedBranches,
conflicts,
};
}
return {
success: true,
message: `Pulled ${syncedBranches.length} branches from remote`,
syncedBranches,
};
} catch (error) {
logger.error("Error pulling stack:", error);
return {
success: false,
message: error instanceof Error ? error.message : "Unknown error",
syncedBranches,
conflicts,
};
}
}
/**
* Sync CI status from remote for a PR
*/
export async function syncCIStatus(
repositoryId: string,
pullRequestId: string
): Promise<RemoteCIStatus | null> {
const db = getDatabase() as NodePgDatabase<typeof schema>;
// Get PR
const pr = await db.query.pullRequests.findFirst({
where: eq(schema.pullRequests.id, pullRequestId),
});
if (!pr) return null;
// Get check runs from database (these would be updated by webhook handlers)
const checks = await db.query.pullRequestChecks.findMany({
where: eq(schema.pullRequestChecks.pullRequestId, pullRequestId),
});
// Determine overall status
let overallStatus: "pending" | "running" | "success" | "failure" = "pending";
if (checks.length > 0) {
const hasRunning = checks.some(c => c.status === "in_progress");
const hasFailure = checks.some(c => c.conclusion === "failure" || c.conclusion === "cancelled");
const allSuccess = checks.every(c => c.conclusion === "success");
if (hasRunning) {
overallStatus = "running";
} else if (hasFailure) {
overallStatus = "failure";
} else if (allSuccess) {
overallStatus = "success";
}
}
return {
prNumber: pr.number,
status: overallStatus,
checkRuns: checks.map(c => ({
name: c.name,
status: c.status,
conclusion: c.conclusion || undefined,
})),
};
}
/**
* Sync all CI statuses for a stack
*/
export async function syncStackCIStatuses(
stackId: string
): Promise<Record<number, RemoteCIStatus>> {
const stackInfo = await getStack(stackId);
if (!stackInfo) return {};
const statuses: Record<number, RemoteCIStatus> = {};
for (const entry of stackInfo.entries) {
const status = await syncCIStatus(
stackInfo.stack.repositoryId,
entry.pr.id
);
if (status) {
statuses[entry.pr.number] = status;
}
}
return statuses;
}
/**
* Detect local branches that could form a stack
*/
export async function detectLocalStack(
repoPath: string,
baseBranch: string = "main"
): Promise<{
branches: string[];
suggestedOrder: string[];
}> {
const git: SimpleGit = simpleGit(repoPath);
try {
// Get all local branches
const branches = await git.branchLocal();
// Filter branches that branch off from base
const stackBranches: string[] = [];
for (const branchName of branches.all) {
if (branchName === baseBranch) continue;
// Check if branch is based on baseBranch
try {
const mergeBase = await git.raw(["merge-base", baseBranch, branchName]);
const baseHead = await git.revparse([baseBranch]);
// If merge-base is close to base head, it's likely a feature branch
stackBranches.push(branchName);
} catch {
// Ignore branches that can't be compared
}
}
// Sort by commit date (oldest first for stack order)
const branchDates: Array<{ branch: string; date: Date }> = [];
for (const branch of stackBranches) {
try {
const log = await git.log(["-1", branch]);
if (log.latest) {
branchDates.push({
branch,
date: new Date(log.latest.date),
});
}
} catch {
branchDates.push({ branch, date: new Date() });
}
}
branchDates.sort((a, b) => a.date.getTime() - b.date.getTime());
return {
branches: stackBranches,
suggestedOrder: branchDates.map(b => b.branch),
};
} catch (error) {
logger.error("Error detecting stack:", error);
return { branches: [], suggestedOrder: [] };
}
}
/**
* Create a stack from detected local branches
*/
export async function createStackFromBranches(
repositoryId: string,
baseBranch: string,
branchNames: string[],
createdById: string,
stackName?: string
): Promise<{ stackId: string; prIds: string[] }> {
const db = getDatabase() as NodePgDatabase<typeof schema>;
// Create the stack
const stack = await createStack({
repositoryId,
baseBranch,
name: stackName,
createdById,
});
const prIds: string[] = [];
// Find or create PRs for each branch
for (let i = 0; i < branchNames.length; i++) {
const branchName = branchNames[i];
// Check if PR already exists for this branch
let pr = await db.query.pullRequests.findFirst({
where: and(
eq(schema.pullRequests.repositoryId, repositoryId),
eq(schema.pullRequests.headBranch, branchName),
eq(schema.pullRequests.state, "open"),
),
});
if (pr) {
// Add existing PR to stack
await addToStack({
stackId: stack.id,
pullRequestId: pr.id,
parentPrId: i > 0 ? prIds[i - 1] : undefined,
});
prIds.push(pr.id);
}
// Note: If no PR exists, user needs to create one first
}
return { stackId: stack.id, prIds };
}
/**
* Get full sync status for a stack
*/
export async function getStackSyncStatus(
repoPath: string,
stackId: string
): Promise<{
stack: Awaited<ReturnType<typeof getStack>>;
branchStatuses: Record<string, SyncStatus>;
ciStatuses: Record<number, RemoteCIStatus>;
needsSync: boolean;
hasConflicts: boolean;
}> {
const stackInfo = await getStack(stackId);
if (!stackInfo) {
throw new Error("Stack not found");
}
const branchStatuses: Record<string, SyncStatus> = {};
let needsSync = false;
for (const entry of stackInfo.entries) {
const status = await getBranchSyncStatus(repoPath, entry.pr.headBranch);
branchStatuses[entry.pr.headBranch] = status;
if (status.hasUnpushedChanges || status.hasRemoteChanges) {
needsSync = true;
}
}
const ciStatuses = await syncStackCIStatuses(stackId);
const hasConflicts = Object.values(branchStatuses).some(
s => s.hasUnpushedChanges && s.hasRemoteChanges
);
return {
stack: stackInfo,
branchStatuses,
ciStatuses,
needsSync,
hasConflicts,
};
}