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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
|
import { join } from "path";
import { mkdir, rm, writeFile, readFile } from "fs/promises";
import { existsSync } from "fs";
import { config } from "./config";
import { getAnthropic, MODEL_SONNET, extractText, parseJsonResponse } from "./ai-client";
import { db } from "../db";
import { users, repositories, pullRequests } from "../db/schema";
import { eq, and } from "drizzle-orm";
export type MigrationTarget =
| { type: "language"; from: string; to: string }
| { type: "framework"; from: string; to: string }
| { type: "custom"; description: string };
export interface MigrationJob {
id: string;
repoId: string;
owner: string;
repo: string;
userId: string;
target: MigrationTarget;
status:
| "queued"
| "analyzing"
| "translating"
| "committing"
| "opening-pr"
| "done"
| "failed";
progress: number;
currentFile?: string;
branchName: string;
prNumber?: number;
error?: string;
filesTotal: number;
filesTranslated: number;
startedAt: string;
completedAt?: string;
}
interface MigrationPlan {
filesToTranslate: Array<{ from: string; to: string; notes: string }>;
filesToSkip: string[];
newFiles: Array<{ path: string; content: string }>;
}
interface ResolvedRepo {
ownerId: string;
repoId: string;
defaultBranch: string;
diskPath: string;
}
const migrationJobs = new Map<string, MigrationJob>();
setInterval(() => {
const cutoff = Date.now() - 4 * 60 * 60 * 1000;
for (const [id, job] of migrationJobs) {
if (
(job.status === "done" || job.status === "failed") &&
job.completedAt &&
new Date(job.completedAt).getTime() < cutoff
) {
migrationJobs.delete(id);
}
}
}, 5 * 60 * 1000);
const activeByRepo = new Map<string, string>();
const dailyCounts = new Map<string, number[]>();
function recordDailyUse(userId: string): boolean {
const now = Date.now();
const dayMs = 24 * 60 * 60 * 1000;
const existing = (dailyCounts.get(userId) ?? []).filter(
(ts) => now - ts < dayMs
);
if (existing.length >= 3) return false;
existing.push(now);
dailyCounts.set(userId, existing);
return true;
}
export function isRepoMigrating(repoId: string): boolean {
const jobId = activeByRepo.get(repoId);
if (!jobId) return false;
const job = migrationJobs.get(jobId);
if (!job) {
activeByRepo.delete(repoId);
return false;
}
if (job.status === "done" || job.status === "failed") {
activeByRepo.delete(repoId);
return false;
}
return true;
}
export function getJob(jobId: string): MigrationJob | undefined {
return migrationJobs.get(jobId);
}
async function git(
args: string[],
opts?: { cwd?: string }
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const proc = Bun.spawn(["git", ...args], {
cwd: opts?.cwd,
stdout: "pipe",
stderr: "pipe",
env: {
...process.env,
GIT_AUTHOR_NAME: "Gluecron Migration Bot",
GIT_AUTHOR_EMAIL: "migration-bot@gluecron.com",
GIT_COMMITTER_NAME: "Gluecron Migration Bot",
GIT_COMMITTER_EMAIL: "migration-bot@gluecron.com",
},
});
const [stdout, stderr] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
const exitCode = await proc.exited;
return { stdout, stderr, exitCode };
}
function isBinaryContent(content: string): boolean {
const sample = content.slice(0, 512);
return sample.includes("\0");
}
function shouldSkipPath(path: string): boolean {
const lower = path.toLowerCase();
const skip = [
"node_modules/",
"dist/",
".git/",
".next/",
"build/",
"target/",
"__pycache__/",
".venv/",
"vendor/",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb",
"poetry.lock",
"cargo.lock",
"go.sum",
"composer.lock",
"gemfile.lock",
];
return skip.some((s) => lower.includes(s));
}
function targetLabel(target: MigrationTarget): string {
if (target.type === "language") return `${target.from} → ${target.to}`;
if (target.type === "framework") return `${target.from} → ${target.to}`;
return target.description;
}
async function planMigration(
fileList: string[],
target: MigrationTarget
): Promise<MigrationPlan | null> {
const anthropic = getAnthropic();
let goalDescription: string;
if (target.type === "language") {
goalDescription = `Convert all source code from ${target.from} to ${target.to}`;
} else if (target.type === "framework") {
goalDescription = `Migrate the codebase from ${target.from} framework to ${target.to} framework`;
} else {
goalDescription = target.description;
}
const fileListStr = fileList.slice(0, 500).join("\n");
const prompt = `You are a migration expert. Given this repository's file list, create a migration plan.
Goal: ${goalDescription}
Files in repository:
${fileListStr}
Return a JSON object (no markdown, no code fences, raw JSON only) with this exact shape:
{
"filesToTranslate": [
{ "from": "src/index.ts", "to": "src/index.py", "notes": "convert Express handlers to Flask routes" }
],
"filesToSkip": ["package-lock.json", "node_modules/..."],
"newFiles": [
{ "path": "requirements.txt", "content": "flask==3.0.0\n..." }
]
}
Rules:
- filesToTranslate: only source code files (no binaries, no lock files, no minified JS in dist/)
- Cap filesToTranslate at 40 entries maximum
- filesToSkip: lock files, binary assets, generated files that don't need translation
- newFiles: new config/manifest files needed for the target (e.g. requirements.txt for Python, go.mod for Go)
- Keep new file content concise and correct for the target stack
- The "to" field should use the correct extension for the target language`;
try {
const msg = await anthropic.messages.create({
model: MODEL_SONNET,
max_tokens: 4096,
messages: [{ role: "user", content: prompt }],
});
const text = extractText(msg);
const plan = parseJsonResponse<MigrationPlan>(text);
if (!plan) return null;
if (plan.filesToTranslate && plan.filesToTranslate.length > 40) {
plan.filesToTranslate = plan.filesToTranslate.slice(0, 40);
}
return plan;
} catch {
return null;
}
}
async function translateFile(
content: string,
fromPath: string,
target: MigrationTarget,
notes: string
): Promise<string | null> {
const anthropic = getAnthropic();
let instruction: string;
if (target.type === "language") {
instruction = `Translate this ${target.from} file to ${target.to}.${notes ? ` Notes: ${notes}` : ""}`;
} else if (target.type === "framework") {
instruction = `Migrate this file from ${target.from} to ${target.to}.${notes ? ` Notes: ${notes}` : ""}`;
} else {
instruction = `Apply this transformation: ${target.description}${notes ? `. Notes: ${notes}` : ""}`;
}
const prompt = `${instruction}
Return ONLY the translated file content, no explanation, no code fences, no markdown. Start the output with the actual file content.
Original file (${fromPath}):
${content}`;
try {
const msg = await anthropic.messages.create({
model: MODEL_SONNET,
max_tokens: 8192,
messages: [{ role: "user", content: prompt }],
});
return extractText(msg);
} catch {
return null;
}
}
async function resolveRepo(
ownerName: string,
repoName: string
): Promise<ResolvedRepo | null> {
try {
const [ownerRow] = await db
.select()
.from(users)
.where(eq(users.username, ownerName))
.limit(1);
if (!ownerRow) return null;
const [repoRow] = await db
.select()
.from(repositories)
.where(
and(
eq(repositories.ownerId, ownerRow.id),
eq(repositories.name, repoName)
)
)
.limit(1);
if (!repoRow) return null;
return {
ownerId: ownerRow.id,
repoId: repoRow.id,
defaultBranch: repoRow.defaultBranch || "main",
diskPath: repoRow.diskPath,
};
} catch {
return null;
}
}
async function insertPullRequest(params: {
repositoryId: string;
authorId: string;
title: string;
body: string;
baseBranch: string;
headBranch: string;
}): Promise<number> {
const [row] = await db
.insert(pullRequests)
.values({
repositoryId: params.repositoryId,
authorId: params.authorId,
title: params.title,
body: params.body,
state: "open",
baseBranch: params.baseBranch,
headBranch: params.headBranch,
isDraft: true,
})
.returning({ number: pullRequests.number });
return row.number;
}
async function runMigration(job: MigrationJob): Promise<void> {
const worktreeBase = join(config.gitReposPath, ".migration-worktrees");
const worktreePath = join(worktreeBase, job.id);
try {
job.status = "analyzing";
job.progress = 5;
const resolved = await resolveRepo(job.owner, job.repo);
if (!resolved) throw new Error("Repository not found");
const bareRepoPath = resolved.diskPath;
const lsResult = await git(["ls-tree", "-r", "--name-only", "HEAD"], {
cwd: bareRepoPath,
});
if (lsResult.exitCode !== 0) {
throw new Error("Repository has no commits yet — nothing to migrate");
}
const allFiles = lsResult.stdout
.split("\n")
.map((f) => f.trim())
.filter(Boolean)
.filter((f) => !shouldSkipPath(f));
if (allFiles.length === 0) {
throw new Error("No translatable files found in the repository");
}
job.progress = 10;
const plan = await planMigration(allFiles, job.target);
if (!plan) throw new Error("Failed to generate migration plan from Claude");
job.filesTotal = plan.filesToTranslate.length + plan.newFiles.length;
job.progress = 20;
await mkdir(worktreeBase, { recursive: true });
const wtResult = await git(
["worktree", "add", "--no-checkout", worktreePath, "HEAD"],
{ cwd: bareRepoPath }
);
if (wtResult.exitCode !== 0) {
throw new Error(`Failed to create worktree: ${wtResult.stderr}`);
}
const checkoutResult = await git(["checkout", "-f", "HEAD", "--", "."], {
cwd: worktreePath,
});
const branchResult = await git(
["checkout", "-b", job.branchName],
{ cwd: worktreePath }
);
if (branchResult.exitCode !== 0) {
throw new Error(`Failed to create branch: ${branchResult.stderr}`);
}
job.status = "translating";
job.progress = 25;
const progressPerFile = plan.filesToTranslate.length > 0
? 50 / plan.filesToTranslate.length
: 50;
for (let i = 0; i < plan.filesToTranslate.length; i++) {
const entry = plan.filesToTranslate[i];
job.currentFile = entry.from;
job.filesTranslated = i;
let originalContent: string;
try {
const showResult = await git(
["show", `HEAD:${entry.from}`],
{ cwd: bareRepoPath }
);
if (showResult.exitCode !== 0) {
job.progress = Math.round(25 + (i + 1) * progressPerFile);
continue;
}
originalContent = showResult.stdout;
} catch {
job.progress = Math.round(25 + (i + 1) * progressPerFile);
continue;
}
if (isBinaryContent(originalContent)) {
job.progress = Math.round(25 + (i + 1) * progressPerFile);
continue;
}
if (originalContent.length > 50 * 1024) {
job.progress = Math.round(25 + (i + 1) * progressPerFile);
continue;
}
const translated = await translateFile(
originalContent,
entry.from,
job.target,
entry.notes || ""
);
if (!translated) {
job.progress = Math.round(25 + (i + 1) * progressPerFile);
continue;
}
const destPath = join(worktreePath, entry.to);
const destDir = destPath.substring(0, destPath.lastIndexOf("/"));
if (destDir && destDir !== worktreePath) {
await mkdir(destDir, { recursive: true });
}
await writeFile(destPath, translated, "utf-8");
if (entry.from !== entry.to) {
const srcPath = join(worktreePath, entry.from);
if (existsSync(srcPath)) {
try {
await rm(srcPath);
} catch {
}
}
}
job.filesTranslated = i + 1;
job.progress = Math.round(25 + (i + 1) * progressPerFile);
}
for (const newFile of plan.newFiles) {
const destPath = join(worktreePath, newFile.path);
const destDir = destPath.substring(0, destPath.lastIndexOf("/"));
if (destDir && destDir !== worktreePath) {
await mkdir(destDir, { recursive: true });
}
await writeFile(destPath, newFile.content, "utf-8");
job.filesTranslated = Math.min(
job.filesTranslated + 1,
job.filesTotal
);
}
job.currentFile = undefined;
job.progress = 75;
job.status = "committing";
const label = targetLabel(job.target);
const addResult = await git(["add", "-A"], { cwd: worktreePath });
if (addResult.exitCode !== 0) {
throw new Error(`git add failed: ${addResult.stderr}`);
}
const statusResult = await git(
["status", "--porcelain"],
{ cwd: worktreePath }
);
if (!statusResult.stdout.trim()) {
throw new Error("No changes were produced by the migration — all files may have been skipped");
}
const commitMsg = `migrate: AI translation — ${label}\n\nAutomatically generated by Gluecron AI Codebase Migrator.\nFiles translated: ${job.filesTranslated}/${job.filesTotal}`;
const commitResult = await git(
["commit", "-m", commitMsg],
{ cwd: worktreePath }
);
if (commitResult.exitCode !== 0) {
throw new Error(`git commit failed: ${commitResult.stderr}`);
}
job.progress = 85;
const pushResult = await git(
["push", bareRepoPath, `HEAD:refs/heads/${job.branchName}`],
{ cwd: worktreePath }
);
if (pushResult.exitCode !== 0) {
throw new Error(`git push failed: ${pushResult.stderr}`);
}
job.progress = 92;
job.status = "opening-pr";
const prBody = [
`## AI Codebase Migration — ${label}`,
"",
"This pull request was **automatically generated** by the Gluecron AI Codebase Migrator.",
"",
`**Migration type:** ${job.target.type}`,
`**Target:** ${label}`,
`**Files translated:** ${job.filesTranslated}`,
`**Total files processed:** ${job.filesTotal}`,
"",
"> **Review carefully before merging.** AI translation is thorough but not perfect.",
"> Test the migrated code in a staging environment before landing to main.",
].join("\n");
const prTitle = `migrate: AI codebase migration — ${label}`;
const prNumber = await insertPullRequest({
repositoryId: resolved.repoId,
authorId: job.userId,
title: prTitle,
body: prBody,
baseBranch: resolved.defaultBranch,
headBranch: job.branchName,
});
job.prNumber = prNumber;
job.progress = 100;
job.status = "done";
job.completedAt = new Date().toISOString();
} catch (err) {
job.status = "failed";
job.error = err instanceof Error ? err.message : "Unknown error";
job.completedAt = new Date().toISOString();
} finally {
try {
if (existsSync(worktreePath)) {
const resolved2 = await resolveRepo(job.owner, job.repo);
if (resolved2) {
await git(["worktree", "prune"], { cwd: resolved2.diskPath });
}
await rm(worktreePath, { recursive: true, force: true });
}
} catch {
}
activeByRepo.delete(job.repoId);
}
}
export interface StartMigrationParams {
owner: string;
repo: string;
repoId: string;
userId: string;
target: MigrationTarget;
}
export async function startMigration(
params: StartMigrationParams
): Promise<{ ok: true; job: MigrationJob } | { ok: false; error: string }> {
if (isRepoMigrating(params.repoId)) {
return {
ok: false,
error: "A migration is already in progress for this repository. Wait for it to finish.",
};
}
if (!recordDailyUse(params.userId)) {
return {
ok: false,
error: "You have reached the daily limit of 3 migrations. Try again tomorrow.",
};
}
const jobId = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
const timestamp = Math.floor(Date.now() / 1000);
let branchSuffix: string;
if (params.target.type === "language") {
branchSuffix = `${params.target.from.toLowerCase()}-to-${params.target.to.toLowerCase()}`;
} else if (params.target.type === "framework") {
branchSuffix = `${params.target.from.toLowerCase()}-to-${params.target.to.toLowerCase()}`;
} else {
branchSuffix = "custom";
}
branchSuffix = branchSuffix.replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").slice(0, 40);
const branchName = `migrate/${branchSuffix}-${timestamp}`;
const job: MigrationJob = {
id: jobId,
repoId: params.repoId,
owner: params.owner,
repo: params.repo,
userId: params.userId,
target: params.target,
status: "queued",
progress: 0,
branchName,
filesTotal: 0,
filesTranslated: 0,
startedAt: new Date().toISOString(),
};
migrationJobs.set(jobId, job);
activeByRepo.set(params.repoId, jobId);
void runMigration(job);
return { ok: true, job };
}
|