Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
pr-stage.ts15.1 KB · 516 lines
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
/**
 * /stage slash-command — deploys a per-PR preview environment.
 *
 * When a user comments `/stage` on any PR, this module:
 *   1. Detects the repo's framework (next.js, bun, docker, static, node)
 *   2. For static/nextjs repos: runs `bun run build` in a temporary worktree
 *   3. Falls back to a built-in static file server at GET /preview/:stageJobId/*
 *      when no cloud deploy provider is configured
 *   4. Posts a reply comment with the live URL (or an error)
 *
 * All stage jobs are held in memory with a 4-hour TTL. Static previews
 * additionally write files to ${GIT_REPOS_PATH}/.stage-previews/${id}/ and
 * are served for 48 hours via src/routes/pulls.tsx (previewRoute).
 *
 * No new npm packages — uses only Bun built-ins.
 */

import { join } from "path";
import { db } from "../db";
import { pullRequests, prComments, repositories, users } from "../db/schema";
import { eq, and } from "drizzle-orm";
import { config } from "./config";
import { getRepoPath } from "../git/repository";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface StageJob {
  id: string;
  prId: string;
  repoId: string;
  status: "queued" | "detecting" | "deploying" | "live" | "failed";
  framework?: "nextjs" | "node" | "bun" | "static" | "docker";
  previewUrl?: string;
  error?: string;
  startedAt: string;
  liveAt?: string;
}

// ---------------------------------------------------------------------------
// In-memory store (4 h TTL)
// ---------------------------------------------------------------------------

const STAGE_TTL_MS = 4 * 60 * 60 * 1000; // 4 hours

const stageJobs = new Map<
  string,
  { job: StageJob; expiresAt: number }
>();

// Key: prId → jobId (so we can detect existing active jobs per PR)
const prToJobId = new Map<string, string>();

function getJob(id: string): StageJob | null {
  const entry = stageJobs.get(id);
  if (!entry) return null;
  if (Date.now() > entry.expiresAt) {
    stageJobs.delete(id);
    return null;
  }
  return entry.job;
}

function setJob(job: StageJob): void {
  stageJobs.set(job.id, {
    job,
    expiresAt: Date.now() + STAGE_TTL_MS,
  });
}

// ---------------------------------------------------------------------------
// Git helper
// ---------------------------------------------------------------------------

async function git(
  args: string[],
  cwd: string
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  const proc = Bun.spawn(["git", ...args], {
    cwd,
    stdout: "pipe",
    stderr: "pipe",
  });
  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 };
}

// ---------------------------------------------------------------------------
// Framework detection
// ---------------------------------------------------------------------------

async function detectFramework(
  ownerName: string,
  repoName: string
): Promise<StageJob["framework"]> {
  const repoDir = getRepoPath(ownerName, repoName);
  // List all files (HEAD) — bare repo so we use ls-tree
  const { stdout } = await git(
    ["ls-tree", "-r", "--name-only", "HEAD"],
    repoDir
  );
  const files = stdout.trim().split("\n").filter(Boolean);

  const hasFile = (name: string) =>
    files.some((f) => f === name || f.endsWith(`/${name}`));
  const hasPattern = (re: RegExp) => files.some((f) => re.test(f));

  if (hasPattern(/^next\.config\.(js|ts|mjs|cjs)$/)) return "nextjs";

  // Check package.json for bun engine
  if (hasFile("package.json")) {
    try {
      const { stdout: blob } = await git(
        ["show", `HEAD:package.json`],
        repoDir
      );
      const pkg = JSON.parse(blob) as Record<string, unknown>;
      const engines = pkg.engines as Record<string, string> | undefined;
      if (engines && typeof engines.bun === "string") return "bun";
    } catch {
      /* ignore parse errors */
    }
  }

  if (hasFile("Dockerfile")) return "docker";
  if (hasFile("index.html")) return "static";

  return "node";
}

// ---------------------------------------------------------------------------
// Static file serving helpers
// ---------------------------------------------------------------------------

const PREVIEW_SERVE_DIR_TTL_MS = 48 * 60 * 60 * 1000; // 48 hours
const previewExpiry = new Map<string, number>(); // jobId → expiresAt

export function getPreviewDir(jobId: string): string {
  return join(config.gitReposPath, ".stage-previews", jobId);
}

export function markPreviewExpiry(jobId: string): void {
  previewExpiry.set(jobId, Date.now() + PREVIEW_SERVE_DIR_TTL_MS);
}

export function isPreviewExpired(jobId: string): boolean {
  const exp = previewExpiry.get(jobId);
  if (exp === undefined) return true;
  return Date.now() > exp;
}

// ---------------------------------------------------------------------------
// Post a PR comment as the system (bot) user — inserts directly into DB
// ---------------------------------------------------------------------------

async function postPrComment(prId: string, body: string): Promise<void> {
  // Find the repo owner to use as the author (best-effort)
  const [pr] = await db
    .select({ authorId: pullRequests.authorId })
    .from(pullRequests)
    .where(eq(pullRequests.id, prId))
    .limit(1);
  if (!pr) return;

  await db.insert(prComments).values({
    pullRequestId: prId,
    authorId: pr.authorId,
    body,
    moderationStatus: "approved",
  });
}

// ---------------------------------------------------------------------------
// Build a static preview — checkout HEAD into a worktree, optionally build
// ---------------------------------------------------------------------------

async function buildStaticPreview(
  ownerName: string,
  repoName: string,
  framework: StageJob["framework"],
  jobId: string
): Promise<{ ok: boolean; error?: string }> {
  const repoDir = getRepoPath(ownerName, repoName);
  const outputDir = getPreviewDir(jobId);

  // Create a temporary worktree
  const worktreeDir = join(
    config.gitReposPath,
    ".stage-worktrees",
    `${jobId}_${Date.now()}`
  );

  try {
    // Create worktree (detached HEAD at HEAD commit)
    const wt = await git(
      ["worktree", "add", "--detach", worktreeDir, "HEAD"],
      repoDir
    );
    if (wt.exitCode !== 0) {
      return { ok: false, error: wt.stderr.trim() || "Failed to create worktree" };
    }

    // For nextjs/node/bun — try to build
    if (framework === "nextjs" || framework === "bun" || framework === "node") {
      // Check if package.json exists before attempting build
      const hasPackageJson = await Bun.file(
        join(worktreeDir, "package.json")
      ).exists();
      if (hasPackageJson) {
        const install = Bun.spawn(["bun", "install", "--frozen-lockfile"], {
          cwd: worktreeDir,
          stdout: "pipe",
          stderr: "pipe",
        });
        await install.exited; // best-effort

        const build = Bun.spawn(["bun", "run", "build"], {
          cwd: worktreeDir,
          stdout: "pipe",
          stderr: "pipe",
        });
        const buildExit = await build.exited;
        if (buildExit !== 0) {
          // Build failed — try to serve static files from the worktree as-is
          // (some projects don't have a build step)
        }
      }
    }

    // Determine what to copy into outputDir
    // nextjs: .next/static or out/ or build/
    // others: dist/ or public/ or . (whole worktree)
    const candidateDirs: string[] = [];
    if (framework === "nextjs") {
      candidateDirs.push(
        join(worktreeDir, "out"),
        join(worktreeDir, ".next", "static"),
        join(worktreeDir, "build")
      );
    }
    candidateDirs.push(
      join(worktreeDir, "dist"),
      join(worktreeDir, "public"),
      join(worktreeDir, "_site"),
      worktreeDir
    );

    // Find first candidate that has an index.html
    let sourceDir: string | null = null;
    for (const candidate of candidateDirs) {
      try {
        const indexExists = await Bun.file(
          join(candidate, "index.html")
        ).exists();
        if (indexExists) {
          sourceDir = candidate;
          break;
        }
      } catch {
        /* skip */
      }
    }

    if (!sourceDir) {
      // Copy the entire worktree
      sourceDir = worktreeDir;
    }

    // Recursively copy sourceDir → outputDir
    const copyResult = await copyDir(sourceDir, outputDir);
    if (!copyResult.ok) {
      return { ok: false, error: copyResult.error };
    }

    markPreviewExpiry(jobId);
    return { ok: true };
  } finally {
    // Clean up worktree
    await git(["worktree", "remove", "--force", worktreeDir], repoDir).catch(
      () => {}
    );
  }
}

// ---------------------------------------------------------------------------
// Simple recursive directory copy using Bun
// ---------------------------------------------------------------------------

async function copyDir(
  src: string,
  dst: string
): Promise<{ ok: boolean; error?: string }> {
  try {
    // Ensure destination directory exists first
    const mkdir = Bun.spawn(["mkdir", "-p", dst], {
      stdout: "pipe",
      stderr: "pipe",
    });
    await mkdir.exited;

    const proc = Bun.spawn(["cp", "-r", src + "/.", dst], {
      stdout: "pipe",
      stderr: "pipe",
    });
    // Drain stdout to prevent deadlock
    const [, stderr, exitCode] = await Promise.all([
      new Response(proc.stdout).text(),
      new Response(proc.stderr).text(),
      proc.exited,
    ]);
    if (exitCode !== 0) {
      return {
        ok: false,
        error: stderr.trim() || `cp exited ${exitCode}`,
      };
    }
    return { ok: true };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : String(err),
    };
  }
}

// ---------------------------------------------------------------------------
// Main trigger function
// ---------------------------------------------------------------------------

export async function triggerStage(
  prId: string,
  _triggeredByUserId: string
): Promise<StageJob> {
  // Return existing active job if one exists for this PR
  const existingJobId = prToJobId.get(prId);
  if (existingJobId) {
    const existing = getJob(existingJobId);
    if (
      existing &&
      (existing.status === "live" || existing.status === "deploying" || existing.status === "detecting")
    ) {
      return existing;
    }
  }

  // Create new job
  const jobId = crypto.randomUUID();
  const now = new Date().toISOString();

  const job: StageJob = {
    id: jobId,
    prId,
    repoId: "",
    status: "queued",
    startedAt: now,
  };

  setJob(job);
  prToJobId.set(prId, jobId);

  // Run the pipeline asynchronously (fire-and-forget from caller's perspective)
  runStagePipeline(job).catch((err) => {
    job.status = "failed";
    job.error = err instanceof Error ? err.message : String(err);
    setJob(job);
  });

  return job;
}

async function runStagePipeline(job: StageJob): Promise<void> {
  const startMs = Date.now();

  // ── 1. Load PR + repo info ──────────────────────────────────────────────
  const [pr] = await db
    .select({
      id: pullRequests.id,
      repositoryId: pullRequests.repositoryId,
    })
    .from(pullRequests)
    .where(eq(pullRequests.id, job.prId))
    .limit(1);

  if (!pr) {
    job.status = "failed";
    job.error = "PR not found";
    setJob(job);
    return;
  }

  job.repoId = pr.repositoryId;

  const [repoRow] = await db
    .select({
      name: repositories.name,
      ownerId: repositories.ownerId,
    })
    .from(repositories)
    .where(eq(repositories.id, pr.repositoryId))
    .limit(1);

  if (!repoRow) {
    job.status = "failed";
    job.error = "Repository not found";
    setJob(job);
    return;
  }

  const [ownerRow] = await db
    .select({ username: users.username })
    .from(users)
    .where(eq(users.id, repoRow.ownerId))
    .limit(1);

  if (!ownerRow) {
    job.status = "failed";
    job.error = "Repository owner not found";
    setJob(job);
    return;
  }

  const ownerName = ownerRow.username;
  const repoName = repoRow.name;

  // ── 2. Detect framework ─────────────────────────────────────────────────
  job.status = "detecting";
  setJob(job);

  let framework: StageJob["framework"];
  try {
    framework = await detectFramework(ownerName, repoName);
  } catch (err) {
    framework = "node";
  }
  job.framework = framework;

  // ── 3. Deploy ───────────────────────────────────────────────────────────
  job.status = "deploying";
  setJob(job);

  // If it's docker, we can't easily build/run it locally — tell the user
  if (framework === "docker") {
    await postPrComment(
      job.prId,
      "<!-- cmd:stage -->\n\n**Preview not available** — Docker-based projects require a configured deployment provider. " +
        "Set `VAPRON_DEPLOY_URL` in repo settings to enable staging."
    );
    job.status = "failed";
    job.error = "Docker projects require an external deploy provider";
    setJob(job);
    return;
  }

  // Use built-in static file server (fallback)
  const previewBaseUrl = config.previewDomain || config.appBaseUrl;
  const previewUrl = `${previewBaseUrl}/preview/${job.id}/index.html`;

  const buildResult = await buildStaticPreview(
    ownerName,
    repoName,
    framework,
    job.id
  );

  if (!buildResult.ok) {
    // Post "preview not available" comment
    await postPrComment(
      job.prId,
      `<!-- cmd:stage -->\n\n**Preview not available** — could not build the project: ${buildResult.error}\n\n` +
        `Configure a deployment provider in repo settings, or add an \`index.html\` for static hosting.`
    );
    job.status = "failed";
    job.error = buildResult.error;
    setJob(job);
    return;
  }

  // ── 4. Reply ─────────────────────────────────────────────────────────────
  job.status = "live";
  job.previewUrl = previewUrl;
  job.liveAt = new Date().toISOString();
  setJob(job);

  const elapsedSec = Math.round((Date.now() - startMs) / 1000);
  const frameworkLabel =
    framework === "nextjs"
      ? "Next.js"
      : framework === "bun"
        ? "Bun"
        : framework === "static"
          ? "Static"
          : framework === "node"
            ? "Node.js"
            : framework ?? "Unknown";

  await postPrComment(
    job.prId,
    `<!-- cmd:stage -->\n\n` +
      `**Preview deployed!**\n\n` +
      `[View preview →](${previewUrl})\n\n` +
      `Framework detected: **${frameworkLabel}** · Deployed in **${elapsedSec}s**`
  );
}

// ---------------------------------------------------------------------------
// Look up a job by ID (used by the preview route)
// ---------------------------------------------------------------------------

export function getStageJob(jobId: string): StageJob | null {
  return getJob(jobId);
}